Debian Codegraph @

DisplayCAL/wx_display_adjustment_frame.py

raw
1 """Interactive display calibration UI."""
2
3 import os
4 import platform
5 import re
6 import sys
7
8 from DisplayCAL import audio, config
9 from DisplayCAL import localization as lang
10 from DisplayCAL.config import (
11 get_bitmap,
12 get_data_path,
13 get_default_dpi,
14 get_icon,
15 get_icon_bundle,
16 getcfg,
17 setcfg,
18 )
19 from DisplayCAL.lib.agw import labelbook
20 from DisplayCAL.lib.agw.fmresources import (
21 IMG_NONE,
22 IMG_OVER_EW_BORDER,
23 IMG_OVER_IMG,
24 IMG_OVER_PIN,
25 INB_BORDER,
26 INB_BOTTOM,
27 INB_FIT_BUTTON,
28 INB_FIT_LABELTEXT,
29 INB_LEFT,
30 INB_RIGHT,
31 INB_SHOW_ONLY_IMAGES,
32 INB_SHOW_ONLY_TEXT,
33 INB_TOP,
34 INB_USE_PIN_BUTTON,
35 INB_WEB_HILITE,
36 )
37 from DisplayCAL.lib.agw.pygauge import PyGauge
38 from DisplayCAL.log import get_file_logger
39 from DisplayCAL.meta import NAME as APPNAME
40 from DisplayCAL.options import DEBUG
41 from DisplayCAL.util_list import intlist
42 from DisplayCAL.util_str import wrap
43 from DisplayCAL.wx_addons import wx
44 from DisplayCAL.wx_windows import (
45 NAV_KEYCODES,
46 NUMPAD_KEYCODES,
47 PROCESSING_KEYCODES,
48 BaseFrame,
49 FlatShadedButton,
50 wx_Panel,
51 )
52
53 BGCOLOUR = wx.Colour(0x33, 0x33, 0x33)
54 BORDERCOLOUR = wx.Colour(0x22, 0x22, 0x22)
55 FGCOLOUR = wx.Colour(0x99, 0x99, 0x99)
56
57 CRT = True
58
59
60 def get_panel(parent, size=wx.DefaultSize):
61 """Get a panel with the specified size."""
62 scale = max(getcfg("app.dpi") / get_default_dpi(), 1.0)
63 size = tuple(round(v * scale) for v in size)
64 panel = wx_Panel(parent, wx.ID_ANY, size=size)
65 if DEBUG:
66 from random import randint
67
68 panel.SetBackgroundColour(
69 wx.Colour(randint(0, 255), randint(0, 255), randint(0, 255)) # noqa: S311
70 )
71 get_panel.i += 1
72 wx.StaticText(panel, wx.ID_ANY, str(get_panel.i) + " " + str(size))
73 else:
74 panel.SetBackgroundColour(BGCOLOUR)
75 return panel
76
77
78 get_panel.i = 0
79
80
81 def get_xy_vt_dE(groups):
82 """Get x, y, vt, and dE from a regex match."""
83 x = float(groups[0])
84 y = float(groups[1])
85 vt = ""
86 dE = 0
87 if len(groups) > 2:
88 vt = groups[2] or ""
89 if groups[3]:
90 dE = float(groups[3])
91 return x, y, vt, dE
92
93
94 def set_label_and_size(txtctrl, label):
95 """Set the label and size of a text control."""
96 txtctrl.SetMinSize((txtctrl.GetSize()[0], -1))
97 txtctrl.SetLabel(label)
98 txtctrl.SetMinSize(txtctrl.GetSize())
99
100
101 class DisplayAdjustmentImageContainer(labelbook.ImageContainer):
102 """Overridden agw.ImageContainer.
103
104 Override default agw ImageContainer to use BackgroundColour and
105 ForegroundColour with no borders/labeltext and hilite image instead of
106 hilite shading.
107 """
108
109 def __init__(
110 self,
111 parent,
112 id=wx.ID_ANY, # noqa: A002
113 pos=wx.DefaultPosition,
114 size=wx.DefaultSize,
115 style=0,
116 agw_style=0,
117 name="ImageContainer",
118 ):
119 labelbook.ImageContainer.__init__(
120 self, parent, id, pos, size, style, agw_style, name
121 )
122 imagelist = None
123 for img in ("tab_hilite", "tab_selected"):
124 bmp = get_bitmap(f"theme/{img}")
125 if not imagelist:
126 img_w, img_h = bmp.Size
127 imagelist = wx.ImageList(img_w, img_h)
128 imagelist.Add(bmp)
129 self.stateimgs = imagelist
130
131 def HitTest(self, pt):
132 """Return the index of the tab at the specified position or ``wx.NOT_FOUND``.
133
134 Return the index of the tab at the specified position or ``wx.NOT_FOUND``
135 if ``None``, plus the flag style of L{HitTest}.
136
137 Args:
138 pt (wx.Point): an instance of `wx.Point`, to test for hits.
139
140 Returns:
141 tupe(int, int): The index of the tab at the specified position plus
142 the hit test flag, which can be one of the following bits:
143
144 ====================== ======= ================================
145 HitTest Flags Value Description
146 ====================== ======= ================================
147 ``IMG_OVER_IMG`` 0 The mouse is over the tab icon
148 ``IMG_OVER_PIN`` 1 The mouse is over the pin button
149 ``IMG_OVER_EW_BORDER`` 2 The mouse is over the east-west
150 book border
151 ``IMG_NONE`` 3 Nowhere
152 ====================== ======= ================================
153 """
154 if self.GetParent().GetParent().is_busy:
155 return -1, IMG_NONE
156
157 style = self.GetParent().GetAGWWindowStyleFlag()
158
159 if style & INB_USE_PIN_BUTTON and self._pinBtnRect.Contains(pt):
160 return -1, IMG_OVER_PIN
161
162 for i in range(len(self._pagesInfoVec)):
163 if self._pagesInfoVec[i].GetPosition() == wx.Point(-1, -1):
164 break
165 if i in self.GetParent().disabled_pages:
166 continue
167
168 # For Web Hover style, we test the TextRect
169 if not self.HasAGWFlag(INB_WEB_HILITE):
170 buttonRect = wx.RectPS(
171 (
172 self._pagesInfoVec[i].GetPosition()[0],
173 self._pagesInfoVec[i].GetPosition()[1] + i * 8,
174 ),
175 self._pagesInfoVec[i].GetSize(),
176 )
177 else:
178 buttonRect = self._pagesInfoVec[i].GetTextRect()
179
180 if buttonRect.Contains(pt):
181 return i, IMG_OVER_IMG
182
183 if self.PointOnSash(pt):
184 return -1, IMG_OVER_EW_BORDER
185 return -1, IMG_NONE
186
187 def OnPaint(self, event):
188 """Handle the ``wx.EVT_PAINT`` event for L{ImageContainer}.
189
190 Args:
191 event (wx.PaintEvent): a `wx.PaintEvent` event to be processed.
192 """
193 dc = wx.BufferedPaintDC(self)
194 style = self.GetParent().GetAGWWindowStyleFlag()
195
196 backBrush = wx.Brush(self.GetBackgroundColour())
197 if style & INB_BORDER:
198 borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DSHADOW))
199 else:
200 borderPen = wx.TRANSPARENT_PEN
201
202 size = self.GetSize()
203
204 # Background
205 dc.SetBrush(backBrush)
206
207 borderPen.SetWidth(1)
208 dc.SetPen(borderPen)
209 dc.DrawRectangle(0, 0, size.x, size.y)
210 bUsePin = ((style & INB_USE_PIN_BUTTON and [True]) or [False])[0]
211
212 if bUsePin:
213 # Draw the pin button
214 clientRect = self.GetClientRect()
215 pinRect = wx.Rect(clientRect.GetX() + clientRect.GetWidth() - 20, 2, 20, 20)
216 self.DrawPin(dc, pinRect, not self._bCollapsed)
217
218 if self._bCollapsed:
219 return
220
221 clientSize = 0
222 bUseYcoord = style & INB_RIGHT or style & INB_LEFT
223 clientSize = size.GetHeight() if bUseYcoord else size.GetWidth()
224
225 # We reserver 20 pixels for the 'pin' button
226
227 # The drawing of the images start position. This is
228 # depenedent of the style, especially when Pin button
229 # style is requested
230
231 if bUsePin:
232 if style & INB_TOP or style & INB_BOTTOM:
233 pos = ((style & INB_BORDER and [0]) or [1])[0]
234 else:
235 pos = ((style & INB_BORDER and [20]) or [21])[0]
236 else:
237 pos = ((style & INB_BORDER and [0]) or [1])[0]
238
239 nPadding = 4 # Pad text with 2 pixels on the left and right
240 nTextPaddingLeft = 2
241
242 count = 0
243
244 for i in range(len(self._pagesInfoVec)):
245 if (
246 self.GetParent().GetParent().is_busy
247 and i != self.GetParent().GetSelection()
248 ):
249 continue
250 if i in self.GetParent().disabled_pages:
251 continue
252
253 count = count + 1
254
255 # incase the 'fit button' style is applied,
256 # we set the rectangle width to the
257 # text width plus padding
258 # Incase the style IS applied,
259 # but the style is either LEFT or RIGHT
260 # we ignore it
261 normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
262 dc.SetFont(normalFont)
263
264 textWidth, textHeight = dc.GetTextExtent(self._pagesInfoVec[i].GetCaption())
265
266 # Restore font to be normal
267 normalFont.SetWeight(wx.FONTWEIGHT_NORMAL)
268 dc.SetFont(normalFont)
269
270 # Default values for the surronounding rectangle
271 # around a button
272 rectWidth = self._nImgSize # To avoid the recangle to 'touch' the borders
273 rectHeight = self._nImgSize
274
275 # Incase the style requires non-fixed button (fit to text)
276 # recalc the rectangle width
277 if (
278 style & INB_FIT_BUTTON
279 and not ((style & INB_LEFT) or (style & INB_RIGHT))
280 and self._pagesInfoVec[i].GetCaption() != ""
281 and not (style & INB_SHOW_ONLY_IMAGES)
282 ):
283 rectWidth = (
284 (
285 (textWidth + nPadding * 2) > rectWidth
286 and [nPadding * 2 + textWidth]
287 )
288 or [rectWidth]
289 )[0]
290
291 # Make the width an even number
292 if rectWidth % 2 != 0:
293 rectWidth += 1
294
295 # Check that we have enough space to draw the button
296 # If Pin button is used, consider its space as well (applicable
297 # for top/botton style) since in the left/right, its size is already
298 # considered in 'pos'
299 pinBtnSize = ((bUsePin and [20]) or [0])[0]
300
301 if pos + rectWidth + pinBtnSize > clientSize:
302 break
303
304 # Calculate the button rectangle
305 modRectWidth = (
306 ((style & INB_LEFT or style & INB_RIGHT) and [rectWidth - 2])
307 or [rectWidth]
308 )[0]
309 modRectHeight = (
310 ((style & INB_LEFT or style & INB_RIGHT) and [rectHeight])
311 or [rectHeight - 2]
312 )[0]
313
314 if bUseYcoord:
315 buttonRect = wx.Rect(1, pos, modRectWidth, modRectHeight)
316 else:
317 buttonRect = wx.Rect(pos, 1, modRectWidth, modRectHeight)
318
319 # if bUseYcoord:
320 # rect = wx.Rect(0, pos, rectWidth, rectWidth)
321 # else:
322 # rect = wx.Rect(pos, 0, rectWidth, rectWidth)
323
324 # Incase user set both flags:
325 # INB_SHOW_ONLY_TEXT and INB_SHOW_ONLY_IMAGES
326 # We override them to display both
327
328 if style & INB_SHOW_ONLY_TEXT and style & INB_SHOW_ONLY_IMAGES:
329 style ^= INB_SHOW_ONLY_TEXT
330 style ^= INB_SHOW_ONLY_IMAGES
331 self.GetParent().SetAGWWindowStyleFlag(style)
332
333 # Draw the caption and text
334 imgTopPadding = 0
335 if (
336 not style & INB_SHOW_ONLY_TEXT
337 and self._pagesInfoVec[i].GetImageIndex() != -1
338 ):
339 if bUseYcoord:
340 imgXcoord = 0
341 imgYcoord = (
342 (style & INB_SHOW_ONLY_IMAGES and [pos])
343 or [pos + imgTopPadding]
344 )[0] + (8 * (count - 1))
345
346 else:
347 imgXcoord = pos + (rectWidth / 2) - (self._nImgSize / 2)
348 imgYcoord = (
349 (style & INB_SHOW_ONLY_IMAGES and [self._nImgSize / 2])
350 or [imgTopPadding]
351 )[0]
352
353 if self._nHoveredImgIdx == i:
354 self.stateimgs.Draw(
355 0, dc, 0, imgYcoord, wx.IMAGELIST_DRAW_TRANSPARENT, True
356 )
357
358 if self._nIndex == i:
359 self.stateimgs.Draw(
360 1, dc, 0, imgYcoord, wx.IMAGELIST_DRAW_TRANSPARENT, True
361 )
362
363 self._ImageList.Draw(
364 self._pagesInfoVec[i].GetImageIndex(),
365 dc,
366 imgXcoord,
367 imgYcoord,
368 wx.IMAGELIST_DRAW_TRANSPARENT,
369 True,
370 )
371
372 # Draw the text
373 if (
374 not style & INB_SHOW_ONLY_IMAGES
375 and self._pagesInfoVec[i].GetCaption() != ""
376 ):
377 dc.SetFont(normalFont)
378
379 # Check if the text can fit the size of the rectangle,
380 # if not truncate it
381 fixedText = self._pagesInfoVec[i].GetCaption()
382 if not style & INB_FIT_BUTTON or (
383 style & INB_LEFT or (style & INB_RIGHT)
384 ):
385 fixedText = self.FixTextSize(
386 dc, self._pagesInfoVec[i].GetCaption(), self._nImgSize * 2 - 4
387 )
388
389 # Update the length of the text
390 textWidth, textHeight = dc.GetTextExtent(fixedText)
391
392 if bUseYcoord:
393 textOffsetX = (rectWidth - textWidth) / 2
394 textOffsetY = (
395 (
396 not style & INB_SHOW_ONLY_TEXT
397 and [pos + self._nImgSize + imgTopPadding + 3]
398 )
399 or [pos + ((self._nImgSize * 2 - textHeight) / 2)]
400 )[0]
401
402 else:
403 textOffsetX = (rectWidth - textWidth) / 2 + pos + nTextPaddingLeft
404 textOffsetY = (
405 (
406 not style & INB_SHOW_ONLY_TEXT
407 and [self._nImgSize + imgTopPadding + 3]
408 )
409 or [((self._nImgSize * 2 - textHeight) / 2)]
410 )[0]
411
412 dc.SetTextForeground(self.GetForegroundColour())
413 dc.DrawText(fixedText, textOffsetX, textOffsetY)
414
415 # Update the page info
416 self._pagesInfoVec[i].SetPosition(buttonRect.GetPosition())
417 self._pagesInfoVec[i].SetSize(buttonRect.GetSize())
418
419 pos += rectWidth
420
421 # Update all buttons that can not fit into the screen as non-visible
422 # for ii in range(count, len(self._pagesInfoVec)):
423 # self._pagesInfoVec[ii].SetPosition(wx.Point(-1, -1))
424
425 # Draw the pin button
426 if bUsePin:
427 clientRect = self.GetClientRect()
428 pinRect = wx.Rect(clientRect.GetX() + clientRect.GetWidth() - 20, 2, 20, 20)
429 self.DrawPin(dc, pinRect, not self._bCollapsed)
430
431
432 class DisplayAdjustmentFlatImageBook(labelbook.FlatImageBook):
433 """Overridden agw.ImageContainer.
434
435 This is a subclass of L{FlatImageBook} that allows you to use
436 BackgroundColour and ForegroundColour with no borders/labeltext and hilite
437 image instead of hilite shading.
438
439 Args:
440 parent (wx.Window): The parent window.
441 id (int): The identifier for the FlatImageBook.
442 pos (wx.Point): The position of the FlatImageBook.
443 size (wx.Size): The size of the FlatImageBook.
444 style (int): The style of the FlatImageBook.
445 agw_style (int): The advanced GUI window style flags.
446 name (str): The name of the FlatImageBook.
447 """
448
449 def __init__(
450 self,
451 parent,
452 id=wx.ID_ANY, # noqa: A002
453 pos=wx.DefaultPosition,
454 size=wx.DefaultSize,
455 style=0,
456 agw_style=0,
457 name="FlatImageBook",
458 ):
459 labelbook.FlatImageBook.__init__(
460 self, parent, id, pos, size, style, agw_style, name
461 )
462
463 def CreateImageContainer(self):
464 """Create the image container for the FlatImageBook.
465
466 Returns:
467 DisplayAdjustmentImageContainer: An instance of the custom image.
468 """
469 return DisplayAdjustmentImageContainer(
470 self, wx.ID_ANY, agw_style=self.GetAGWWindowStyleFlag()
471 )
472
473 def SetAGWWindowStyleFlag(self, agw_style):
474 """Set the window style.
475
476 Args:
477 agw_style: Can be a combination of the following bits.
478
479 =========================== =========== ==================================================
480 Window Styles Hex Value Description
481 =========================== =========== ==================================================
482 ``INB_BOTTOM`` 0x1 Place labels below the page area. Available only for L{FlatImageBook}.
483 ``INB_LEFT`` 0x2 Place labels on the left side. Available only for L{FlatImageBook}.
484 ``INB_RIGHT`` 0x4 Place labels on the right side.
485 ``INB_TOP`` 0x8 Place labels above the page area.
486 ``INB_BORDER`` 0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.
487 ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no images. Available only for L{LabelBook}.
488 ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.
489 ``INB_FIT_BUTTON`` 0x80 Displays a pin button to show/hide the book control.
490 ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.
491 ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to show/hide the book control.
492 ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.
493 ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
494 ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab area.
495 ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
496 =========================== =========== ==================================================
497 """ # noqa: E501
498 self._agw_style = agw_style
499
500 # Check that we are not in initialization process
501 if self._bInitializing:
502 return
503
504 if not self._pages:
505 return
506
507 # Detach the windows attached to the sizer
508 if self.GetSelection() >= 0:
509 self._mainSizer.Detach(self._windows[self.GetSelection()])
510
511 self._mainSizer.Detach(self._pages)
512
513 # Create new sizer with the requested orientaion
514 className = self.GetName()
515
516 if className == "LabelBook" or agw_style & INB_LEFT or agw_style & INB_RIGHT:
517 self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)
518 else:
519 self._mainSizer = wx.BoxSizer(wx.VERTICAL)
520
521 self.SetSizer(self._mainSizer)
522
523 # Add the tab container and the separator
524 self._mainSizer.Add(self._pages, 0, wx.EXPAND)
525
526 if className == "FlatImageBook":
527 scale = getcfg("app.dpi") / get_default_dpi()
528 scale = max(scale, 1)
529 if agw_style & INB_LEFT or agw_style & INB_RIGHT:
530 border = round(24 * scale)
531 self._pages.SetSizeHints(self._pages._nImgSize + border, -1)
532 else:
533 self._pages.SetSizeHints(-1, self._pages._nImgSize)
534
535 # Attach the windows back to the sizer to the sizer
536 if self.GetSelection() >= 0:
537 self.DoSetSelection(self._windows[self.GetSelection()])
538
539 if agw_style & INB_FIT_LABELTEXT:
540 self.ResizeTabArea()
541
542 self._mainSizer.Layout()
543 dummy = wx.SizeEvent(wx.DefaultSize)
544 wx.PostEvent(self, dummy)
545 self._pages.Refresh()
546
547
548 class DisplayAdjustmentPanel(wx_Panel):
549 """Panel for interactive display adjustment.
550
551 Args:
552 parent (None | wx.Window): The parent window.
553 id (int): The identifier for the panel.
554 title (str): The title of the panel.
555 ctrltype (str): The type of control to display, e.g., "luminance",
556 "black_level", "white_point", "black_point", or "rgb_offset".
557 """
558
559 def __init__(self, parent=None, id=wx.ID_ANY, title="", ctrltype="luminance"): # noqa: A002
560 # wx_Panel.__init__(self, parent, id)
561 super().__init__(parent, id)
562 self.ctrltype = ctrltype
563 self.SetBackgroundColour(BGCOLOUR)
564 self.SetForegroundColour(FGCOLOUR)
565 self.SetSizer(wx.BoxSizer(wx.VERTICAL))
566 self.title_txt = wx.StaticText(self, wx.ID_ANY, title)
567 font = self.title_txt.GetFont()
568 font.SetPointSize(font.PointSize + 1)
569 font.SetWeight(wx.FONTWEIGHT_BOLD)
570 self.title_txt.SetFont(font)
571 self.title_txt.SetForegroundColour(FGCOLOUR)
572 self.GetSizer().Add(self.title_txt)
573 self.sizer = wx.FlexGridSizer(0, 2, 0, 0)
574 self.GetSizer().Add(self.sizer, flag=wx.TOP, border=8)
575 self.gauges = {}
576 self.txt = {}
577 if ctrltype == "check_all":
578 txt = wx.StaticText(
579 self,
580 wx.ID_ANY,
581 lang.getstr("calibration.interactive_display_adjustment.check_all"),
582 )
583 txt.SetForegroundColour(FGCOLOUR)
584 txt.SetMaxFontSize(10)
585 txt.Wrap(250)
586 self.desc = txt
587 self.GetSizer().Insert(1, txt, flag=wx.TOP, border=8)
588 for name, lstr in (
589 ("luminance", "calibration.luminance"),
590 ("black_level", "calibration.black_luminance"),
591 ("white_point", "whitepoint"),
592 ("black_point", "black_point"),
593 ):
594 bitmap = wx.StaticBitmap(
595 self, wx.ID_ANY, get_bitmap(f"theme/icons/16x16/{name}")
596 )
597 bitmap.SetToolTipString(lang.getstr(lstr))
598 self.add_txt(name, bitmap, 4)
599 return
600 if ctrltype.startswith("rgb"):
601 if ctrltype == "rgb_offset":
602 # CRT
603 lstr = "calibration.interactive_display_adjustment.black_point.crt"
604 else:
605 lstr = "calibration.interactive_display_adjustment.white_point"
606 txt = wx.StaticText(
607 self,
608 wx.ID_ANY,
609 lang.getstr(lstr)
610 + " "
611 + lang.getstr(
612 "calibration.interactive_display_adjustment.generic_hint.plural"
613 ),
614 )
615 txt.SetForegroundColour(FGCOLOUR)
616 txt.SetMaxFontSize(10)
617 txt.Wrap(250)
618 self.desc = txt
619 self.GetSizer().Insert(1, txt, flag=wx.TOP, border=8)
620 self.sizer.Add((1, 4))
621 self.sizer.Add((1, 4))
622 self.add_marker()
623 self.add_gauge("R", f"{ctrltype}_red", "R")
624 self.sizer.Add((1, 4))
625 self.sizer.Add((1, 4))
626 self.add_gauge("G", f"{ctrltype}_green", "G")
627 self.sizer.Add((1, 4))
628 self.sizer.Add((1, 4))
629 self.add_gauge("B", f"{ctrltype}_blue", "B")
630 self.add_marker("btm")
631 self.add_txt("rgb")
632 else:
633 txt = wx.StaticText(self, wx.ID_ANY, " ")
634 txt.SetForegroundColour(FGCOLOUR)
635 txt.SetMaxFontSize(10)
636 txt.Wrap(250)
637 self.desc = txt
638 self.GetSizer().Insert(1, txt, flag=wx.TOP, border=8)
639 self.sizer.Add((1, 4))
640 self.sizer.Add((1, 4))
641 self.add_marker()
642 bitmapnames = {"rgb_offset": "black_level", "rgb_gain": "luminance"}
643 lstrs = {
644 "black_level": "calibration.black_luminance",
645 "rgb_offset": "calibration.black_luminance",
646 "rgb_gain": "calibration.luminance",
647 "luminance": "calibration.luminance",
648 }
649 self.add_gauge(
650 "L",
651 bitmapnames.get(ctrltype, ctrltype),
652 lang.getstr(lstrs.get(ctrltype, ctrltype)),
653 )
654 self.add_marker("btm")
655 self.add_txt("luminance")
656
657 def add_gauge(self, name="R", bitmap_name=None, tooltip=None):
658 """Add a gauge to the panel.
659
660 Args:
661 name (str): The name of the gauge, e.g., "R", "G", "B", or "L".
662 bitmap_name (None | str): The name of the bitmap to use for the
663 gauge label.
664 tooltip (None | str): An optional tooltip for the gauge label.
665 """
666 if bitmap_name == "black_level" or bitmap_name.startswith("rgb_offset"):
667 gaugecolors = {
668 "R": (wx.Colour(102, 0, 0), wx.Colour(204, 0, 0)),
669 "G": (wx.Colour(0, 102, 0), wx.Colour(0, 204, 0)),
670 "B": (wx.Colour(0, 0, 102), wx.Colour(0, 0, 204)),
671 "L": (wx.Colour(102, 102, 102), wx.Colour(204, 204, 204)),
672 }
673 else:
674 gaugecolors = {
675 "R": (wx.Colour(153, 0, 0), wx.Colour(255, 0, 0)),
676 "G": (wx.Colour(0, 153, 0), wx.Colour(0, 255, 0)),
677 "B": (wx.Colour(0, 0, 153), wx.Colour(0, 0, 255)),
678 "L": (wx.Colour(153, 153, 153), wx.Colour(255, 255, 255)),
679 }
680 scale = max(getcfg("app.dpi") / get_default_dpi(), 1.0)
681 self.gauges[name] = PyGauge(self, size=(round(200 * scale), round(8 * scale)))
682 self.gauges[name].SetBackgroundColour(BORDERCOLOUR)
683 self.gauges[name].SetBarGradient(gaugecolors[name])
684 self.gauges[name].SetBorderColour(BORDERCOLOUR)
685 self.gauges[name].SetValue(0)
686 if bitmap_name:
687 self.gauges[name].label = wx.StaticBitmap(
688 self, wx.ID_ANY, get_bitmap(f"theme/icons/16x16/{bitmap_name}")
689 )
690 if tooltip:
691 self.gauges[name].label.SetToolTipString(tooltip)
692 else:
693 self.gauges[name].label = wx.StaticText(self, wx.ID_ANY, name)
694 self.gauges[name].label.SetForegroundColour(FGCOLOUR)
695 self.sizer.Add(
696 self.gauges[name].label, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=8
697 )
698 self.sizer.Add(self.gauges[name], flag=wx.ALIGN_CENTER_VERTICAL)
699
700 def add_marker(self, direction="top"):
701 """Add a marker line to the panel.
702
703 Args:
704 direction (str): The direction of the marker, either "top" or "btm".
705 """
706 self.sizer.Add((1, 1))
707 scale = max(getcfg("app.dpi") / get_default_dpi(), 1.0)
708 self.sizer.Add(
709 wx.StaticBitmap(
710 self,
711 -1,
712 get_bitmap(f"theme/marker_{direction}"),
713 size=(round(200 * scale), round(10 * scale)),
714 )
715 )
716
717 def add_txt(self, name, spacer=None, border=8):
718 """Add a text label with a checkmark icon.
719
720 Args:
721 name (str): The name of the text control.
722 spacer (None | wx.Window): An optional spacer window to add before
723 the checkmark.
724 border (int): The border size around the text control.
725 """
726 checkmark = wx.StaticBitmap(
727 self, wx.ID_ANY, get_bitmap("theme/icons/16x16/checkmark")
728 )
729 txtsizer = wx.BoxSizer(wx.HORIZONTAL)
730 if spacer:
731 self.sizer.Add(spacer, flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=8)
732 txtsizer.Add(checkmark, flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=8)
733 else:
734 self.sizer.Add(
735 checkmark,
736 flag=wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL,
737 border=8,
738 )
739 initial = lang.getstr("initial")
740 current = lang.getstr("current")
741 target = lang.getstr("target")
742 strings = {len(initial): initial, len(current): current, len(target): target}
743 longest = strings[max(strings.keys())]
744 label = longest + " x 0.0000 y 0.0000 VDT 0000K 0.0 \u0394E*00\nX"
745 checkmark.GetContainingSizer().Hide(checkmark)
746 self.sizer.Add(
747 txtsizer,
748 flag=wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
749 border=border,
750 )
751 self.txt[name] = wx.StaticText(
752 self, wx.ID_ANY, label, style=wx.ST_NO_AUTORESIZE
753 )
754 self.txt[name].SetForegroundColour(BGCOLOUR)
755 self.txt[name].SetMaxFontSize(10)
756 self.txt[name].checkmark = checkmark
757 self.txt[name].spacer = spacer
758 txtsizer.Add(self.txt[name], 1)
759 self.txt[name].Fit()
760 self.txt[name].SetMinSize(
761 (self.txt[name].GetSize()[0], self.txt[name].GetSize()[1])
762 )
763
764 def update_desc(self):
765 """Update the description label based on the control type."""
766 if self.ctrltype not in ("luminance", "black_level"):
767 return
768 if self.ctrltype == "black_level":
769 lstr = "calibration.interactive_display_adjustment.black_level.crt"
770 elif getcfg("measurement_mode") == "c":
771 # CRT
772 lstr = "calibration.interactive_display_adjustment.white_level.crt"
773 else:
774 lstr = "calibration.interactive_display_adjustment.white_level.lcd"
775 self.desc.SetLabel(
776 lang.getstr(lstr)
777 + " "
778 + lang.getstr(
779 "calibration.interactive_display_adjustment.generic_hint.singular"
780 )
781 )
782 self.desc.Wrap(250)
783
784
785 NEVER = False
786 if os.getenv("XDG_SESSION_TYPE") == "wayland" and NEVER:
787 windowcls = wx.Dialog
788 else:
789 windowcls = BaseFrame
790
791
792 class DisplayAdjustmentFrame(windowcls):
793 """Main window for interactive display adjustment.
794
795 Args:
796 parent (None | wx.Window): The parent window.
797 handler (None | callable): A handler function to call when an event
798 occurs.
799 keyhandler (None | callable): A key handler function to call when a key
800 event occurs.
801 start_timer (bool): Whether to start a timer for periodic updates.
802 """
803
804 def __init__(self, parent=None, handler=None, keyhandler=None, start_timer=True):
805 # windowcls.__init__(self, parent, wx.ID_ANY,
806 # lang.getstr("calibration.interactive_display_adjustment"),
807 # style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL,
808 # name="displayadjustmentframe")
809 super().__init__(
810 parent,
811 wx.ID_ANY,
812 lang.getstr("calibration.interactive_display_adjustment"),
813 style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL,
814 name="displayadjustmentframe",
815 )
816 self.SetIcons(get_icon_bundle([256, 48, 32, 16], APPNAME))
817 self.SetBackgroundColour(BGCOLOUR)
818 self.sizer = wx.FlexGridSizer(0, 3, 0, 0)
819 self.sizer.AddGrowableCol(1)
820 self.sizer.AddGrowableRow(2)
821 self.SetSizer(self.sizer)
822
823 # FlatImageNotebook
824 self.lb = DisplayAdjustmentFlatImageBook(
825 self, agw_style=INB_LEFT | INB_SHOW_ONLY_IMAGES
826 )
827 self.lb.SetBackgroundColour(BGCOLOUR)
828 self.add_panel((12, 12), flag=wx.EXPAND)
829 self.add_panel((12, 12), flag=wx.EXPAND)
830 self.add_panel((12, 12), flag=wx.EXPAND)
831 self.add_panel((12, 12), flag=wx.EXPAND)
832 self.sizer.Add(self.lb, 1, flag=wx.EXPAND)
833 self.add_panel((12, 12), flag=wx.EXPAND)
834
835 self.pagenum_2_argyll_key_num = {}
836
837 # Page - black luminance
838 self.page_black_luminance = DisplayAdjustmentPanel(
839 self, wx.ID_ANY, lang.getstr("calibration.black_luminance"), "black_level"
840 )
841 self.lb.AddPage(
842 self.page_black_luminance,
843 lang.getstr("calibration.black_luminance"),
844 True,
845 0,
846 )
847 self.pagenum_2_argyll_key_num[len(self.pagenum_2_argyll_key_num)] = "1"
848
849 # Page - white point
850 self.page_white_point = DisplayAdjustmentPanel(
851 self,
852 wx.ID_ANY,
853 lang.getstr("whitepoint") + " / " + lang.getstr("calibration.luminance"),
854 "rgb_gain",
855 )
856 self.lb.AddPage(self.page_white_point, lang.getstr("whitepoint"), True, 1)
857 self.pagenum_2_argyll_key_num[len(self.pagenum_2_argyll_key_num)] = "2"
858
859 # Page - luminance
860 self.page_luminance = DisplayAdjustmentPanel(
861 self, wx.ID_ANY, lang.getstr("calibration.luminance")
862 )
863 self.lb.AddPage(
864 self.page_luminance, lang.getstr("calibration.luminance"), True, 2
865 )
866 self.pagenum_2_argyll_key_num[len(self.pagenum_2_argyll_key_num)] = "3"
867
868 # Page - black point
869 self.page_black_point = DisplayAdjustmentPanel(
870 self,
871 wx.ID_ANY,
872 lang.getstr("black_point")
873 + " / "
874 + lang.getstr("calibration.black_luminance"),
875 "rgb_offset",
876 )
877 self.lb.AddPage(self.page_black_point, lang.getstr("black_point"), True, 3)
878 self.pagenum_2_argyll_key_num[len(self.pagenum_2_argyll_key_num)] = "4"
879
880 # Page - check all
881 self.page_check_all = DisplayAdjustmentPanel(
882 self, wx.ID_ANY, lang.getstr("calibration.check_all"), "check_all"
883 )
884 self.lb.AddPage(
885 self.page_check_all, lang.getstr("calibration.check_all"), True, 4
886 )
887 self.pagenum_2_argyll_key_num[len(self.pagenum_2_argyll_key_num)] = "5"
888
889 # Set colours on tab list
890 self.lb.Children[0].SetBackgroundColour(BGCOLOUR)
891 self.lb.Children[0].SetForegroundColour(FGCOLOUR)
892 # Sound when measuring
893 # Needs to be stereo!
894 self.measurement_sound = audio.Sound(get_data_path("beep.wav"))
895
896 # Add buttons
897 self.btnsizer = wx.BoxSizer(wx.HORIZONTAL)
898 self.add_panel((12, 12), flag=wx.EXPAND)
899 self.add_panel((12, 12), flag=wx.EXPAND)
900 self.add_panel((12, 12), flag=wx.EXPAND)
901 self.add_panel((12, 12), flag=wx.EXPAND)
902 self.sizer.Add(self.btnsizer, flag=wx.ALIGN_RIGHT | wx.EXPAND)
903 self.btnsizer.Add(get_panel(self, (2, 12)), 1, flag=wx.EXPAND)
904 self.indicator_panel = get_panel(self, (22, 12))
905 self.indicator_panel.SetSizer(wx.BoxSizer(wx.HORIZONTAL))
906 self.indicator_panel.SetForegroundColour(FGCOLOUR)
907 self.btnsizer.Add(self.indicator_panel, flag=wx.EXPAND)
908 scale = max(getcfg("app.dpi") / get_default_dpi(), 1.0)
909 self.indicator_ctrl = wx.StaticBitmap(
910 self.indicator_panel,
911 wx.ID_ANY,
912 get_icon(10, "empty", use_mask=True),
913 size=(round(10 * scale), round(10 * scale)),
914 )
915 self.indicator_ctrl.SetForegroundColour(FGCOLOUR)
916 self.indicator_panel.GetSizer().Add(
917 self.indicator_ctrl, flag=wx.ALIGN_CENTER_VERTICAL
918 )
919 self.indicator_panel.GetSizer().Add(
920 get_panel(self.indicator_panel, (10, 12)), flag=wx.EXPAND
921 )
922 self.create_start_interactive_adjustment_button()
923 self.adjustment_btn.SetDefault()
924 self.btnsizer.Add(get_panel(self, (6, 12)), flag=wx.EXPAND)
925 bitmap = self.get_sound_on_off_btn_bitmap()
926 self.sound_on_off_btn = self.create_gradient_button(
927 bitmap, "", name="sound_on_off_btn"
928 )
929 self.sound_on_off_btn.SetToolTipString(lang.getstr("measurement.play_sound"))
930 self.sound_on_off_btn.Bind(wx.EVT_BUTTON, self.measurement_play_sound_handler)
931 self.btnsizer.Add(get_panel(self, (12, 12)), flag=wx.EXPAND)
932 self.calibration_btn = self.create_gradient_button(
933 get_bitmap("theme/icons/10x10/skip"), "", name="calibration_btn"
934 )
935 self.calibration_btn.Bind(wx.EVT_BUTTON, self.continue_to_calibration)
936 self.calibration_btn.Disable()
937 self.add_panel((12, 12), flag=wx.EXPAND)
938 self.add_panel((12, 12), flag=wx.EXPAND)
939 self.add_panel((12, 12), flag=wx.EXPAND)
940 self.add_panel((12, 12), flag=wx.EXPAND)
941
942 self.keyhandler = keyhandler
943 self.id_to_keycode = {}
944 if sys.platform == "darwin":
945 # Use an accelerator table for tab, space, 0-9, A-Z, numpad,
946 # navigation keys and processing keys
947 keycodes = [wx.WXK_TAB, wx.WXK_SPACE]
948 keycodes.extend(list(range(ord("0"), ord("9"))))
949 keycodes.extend(list(range(ord("A"), ord("Z"))))
950 keycodes.extend(NUMPAD_KEYCODES)
951 keycodes.extend(NAV_KEYCODES)
952 keycodes.extend(PROCESSING_KEYCODES)
953 for keycode in keycodes:
954 self.id_to_keycode[wx.Window.NewControlId()] = keycode
955 accels = []
956 for id_ in self.id_to_keycode:
957 keycode = self.id_to_keycode[id_]
958 self.Bind(wx.EVT_MENU, self.key_handler, id=id_)
959 accels.append((wx.ACCEL_NORMAL, keycode, id_))
960 if keycode == wx.WXK_TAB:
961 accels.append((wx.ACCEL_SHIFT, keycode, id_))
962 self.SetAcceleratorTable(wx.AcceleratorTable(accels))
963 else:
964 self.Bind(wx.EVT_CHAR_HOOK, self.key_handler)
965
966 # Event handlers
967 self.Bind(wx.EVT_CLOSE, self.OnClose, self)
968 self.Bind(wx.EVT_MOVE, self.OnMove, self)
969 self.timer = wx.Timer(self)
970 if handler:
971 self.Bind(wx.EVT_TIMER, handler, self.timer)
972 self.Bind(labelbook.EVT_IMAGENOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
973 self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)
974
975 if "gtk3" in wx.PlatformInfo:
976 # Fix background color not working for panels under GTK3
977 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
978
979 # Final initialization steps
980 self.logger = get_file_logger("adjust")
981 self._setup(True)
982
983 self.Show()
984
985 if start_timer:
986 self.start_timer()
987
988 if "gtk3" in wx.PlatformInfo:
989 OnEraseBackground = wx_Panel.__dict__["OnEraseBackground"]
990
991 def EndModal(self, returncode=wx.ID_OK):
992 """End the modal state of the display adjustment frame.
993
994 Args:
995 returncode (int): The return code to indicate the result of the
996 modal operation. Defaults to wx.ID_OK.
997
998 Returns:
999 int: The return code indicating the result of the modal operation.
1000 """
1001 return returncode
1002
1003 def MakeModal(self, modal=False):
1004 """Make the display adjustment frame modal or not.
1005
1006 Args:
1007 modal (bool): If True, make the frame modal; otherwise, make it
1008 non-modal.
1009 """
1010
1011 def OnClose(self, event):
1012 """Handle the close event of the display adjustment frame.
1013
1014 Args:
1015 event (wx.CloseEvent): The event object containing information
1016 about the window being closed.
1017 """
1018 # if getattr(self, "measurement_play_sound_ctrl", None):
1019 # setcfg("measurement.play_sound",
1020 # int(self.measurement_play_sound_ctrl.GetValue()))
1021 config.writecfg()
1022 if not self.timer.IsRunning():
1023 self.Destroy()
1024 else:
1025 self.keepGoing = False
1026
1027 def OnDestroy(self, event):
1028 """Handle the destruction of the display adjustment frame.
1029
1030 Args:
1031 event (wx.WindowDestroyEvent): The event object containing information
1032 about the window being destroyed.
1033
1034 Returns:
1035 int: Returns 0 if the control IDs were successfully unreserved.
1036 """
1037 self.stop_timer()
1038 del self.timer
1039 if not hasattr(wx.Window, "UnreserveControlId"):
1040 return 0
1041
1042 for id_ in self.id_to_keycode:
1043 if id_ >= 0:
1044 continue
1045 try:
1046 wx.Window.UnreserveControlId(id_)
1047 except wx.wxAssertionError as exception:
1048 print(exception)
1049
1050 return 0
1051
1052 def OnMove(self, event):
1053 """Handle window move event.
1054
1055 Args:
1056 event (wx.MoveEvent): The event object containing information about
1057 """
1058 if (
1059 self.IsShownOnScreen()
1060 and not self.IsIconized()
1061 and (not self.GetParent() or not self.GetParent().IsShownOnScreen())
1062 ):
1063 prev_x = getcfg("position.progress.x")
1064 prev_y = getcfg("position.progress.y")
1065 x, y = self.GetScreenPosition()
1066 if x != prev_x or y != prev_y:
1067 setcfg("position.progress.x", x)
1068 setcfg("position.progress.y", y)
1069
1070 def OnPageChanging(self, event):
1071 """Handle page changing event.
1072
1073 Args:
1074 event (wx.CommandEvent): The event object containing information
1075 """
1076 _oldsel = event.GetOldSelection()
1077 _newsel = event.GetSelection()
1078 self.abort()
1079 event.Skip()
1080
1081 def Pulse(self, msg=""):
1082 """Pulse the display adjustment with a message.
1083
1084 Args:
1085 msg (str): The message to display. If empty, it will just return
1086 the current state.
1087
1088 Returns:
1089 tuple: A tuple containing the current state (keepGoing) and a
1090 boolean indicating if the message was processed.
1091 """
1092 if not msg:
1093 return self.keepGoing, False
1094 msg = str(msg)
1095 if (
1096 msg
1097 in (
1098 lang.getstr("instrument.initializing"),
1099 lang.getstr("instrument.calibrating"),
1100 lang.getstr("please_wait"),
1101 lang.getstr("aborting"),
1102 )
1103 or msg == " " * 4
1104 or ": error -" in msg.lower()
1105 or "failed" in msg.lower()
1106 or msg.startswith(
1107 (lang.getstr("webserver.waiting"), lang.getstr("connection.waiting"))
1108 )
1109 ) and msg != self.lastmsg:
1110 self.lastmsg = msg
1111 self.Freeze()
1112 for txt in self.lb.GetCurrentPage().txt.values():
1113 txt.checkmark.GetContainingSizer().Hide(txt.checkmark)
1114 txt.SetLabel(" ")
1115 txt = next(iter(self.lb.GetCurrentPage().txt.values())) # first value
1116 if txt.GetLabel() != wrap(msg, 46):
1117 txt.SetLabel(wrap(msg, 46))
1118 txt.SetForegroundColour(FGCOLOUR)
1119 self.Thaw()
1120 return self.keepGoing, False
1121
1122 def Resume(self):
1123 """Resume the interactive display adjustment."""
1124 self.keepGoing = True
1125 self.set_sound_on_off_btn_bitmap()
1126
1127 def UpdateProgress(self, value, msg=""):
1128 """Update the progress with a value and a message.
1129
1130 Args:
1131 value (int): The value to set the progress to.
1132 msg (str): The message to display. If empty, it will just return
1133 the current state.
1134
1135 Returns:
1136 tuple: A tuple containing the current state (keepGoing) and a
1137 boolean indicating if the message was processed.
1138 """
1139 return self.Pulse(msg)
1140
1141 def UpdatePulse(self, msg=""):
1142 """Update the pulse with a message.
1143
1144 Args:
1145 msg (str): The message to display. If empty, it will just return
1146 the current state.
1147
1148 Returns:
1149 tuple: A tuple containing the current state (keepGoing) and a
1150 boolean indicating if the message was processed.
1151 """
1152 return self.Pulse(msg)
1153
1154 def _assign_image_list(self):
1155 """Assign an image list to the labelbook."""
1156 imagelist = None
1157 modes = {CRT: {"black_luminance": "luminance", "luminance": "contrast"}}
1158 for img in (
1159 "black_luminance",
1160 "white_point",
1161 "luminance",
1162 "black_point",
1163 "check_all",
1164 ):
1165 img = modes.get(getcfg("measurement_mode") == "c", {}).get(img, img)
1166 bmp = get_bitmap(f"theme/icons/72x72/{img}")
1167 if not imagelist:
1168 img_w, img_h = bmp.Size
1169 imagelist = wx.ImageList(img_w, img_h)
1170 imagelist.Add(bmp)
1171 self.lb.AssignImageList(imagelist)
1172
1173 def _setup(self, init=False):
1174 """Setup the display adjustment frame.
1175
1176 Args:
1177 init (bool): If True, perform initial setup.
1178 """
1179 self.logger.info("-" * 80)
1180 self.cold_run = True
1181 self.is_busy = None
1182 self.is_measuring = None
1183 self.keepGoing = True
1184 self.lastmsg = ""
1185 self.target_br = None
1186 self._assign_image_list()
1187 if getcfg("measurement_mode") == "c":
1188 self.lb.disabled_pages = []
1189 if getcfg("calibration.black_luminance", False):
1190 self.lb.SetSelection(0)
1191 else:
1192 self.lb.disabled_pages.append(0)
1193 self.lb.SetSelection(1)
1194 else:
1195 self.lb.disabled_pages = [0, 3]
1196 self.lb.SetSelection(1)
1197 if getcfg("trc"):
1198 self.calibration_btn.SetLabel(lang.getstr("calibration.start"))
1199 elif getcfg("calibration.continue_next"):
1200 self.calibration_btn.SetLabel(lang.getstr("calibration.skip"))
1201 else:
1202 self.calibration_btn.SetLabel(lang.getstr("finish"))
1203 self.calibration_btn.GetContainingSizer().Layout()
1204 # Update black luminance page description
1205 self.lb.GetPage(0).update_desc()
1206 # Update white luminance page description
1207 self.lb.GetPage(2).update_desc()
1208
1209 # Set size
1210 scale = getcfg("app.dpi") / get_default_dpi()
1211 scale = max(scale, 1)
1212 img_w, img_h = list(map(int, list(map(round, (84 * scale, 72 * scale)))))
1213 min_h = (
1214 (img_h + 8) * (self.lb.GetPageCount() - len(self.lb.disabled_pages)) + 2 - 8
1215 )
1216 if init:
1217 self.lb.SetMinSize((418, min_h))
1218 self.lb.SetMinSize(
1219 (self.lb.GetMinSize()[0], max(self.lb.GetMinSize()[1], min_h))
1220 )
1221 self.lb.GetCurrentPage().Fit()
1222 self.lb.GetCurrentPage().Layout()
1223 self.lb.Fit()
1224 self.lb.Layout()
1225 self.SetMinSize((0, 0))
1226 self.Fit()
1227 self.Layout()
1228 # The button sizer will be as wide as the labelbook or wider,
1229 # so use it as reference
1230 w = self.btnsizer.CalcMin()[0] - img_w - 12
1231 for pagenum in range(self.lb.GetPageCount()):
1232 page = self.lb.GetPage(pagenum)
1233 page.SetSize((w, -1))
1234 page.desc.SetLabel(page.desc.GetLabel().replace("\n", " "))
1235 if sys.platform == "darwin" and intlist(
1236 platform.mac_ver()[0].split(".")
1237 ) >= [
1238 10,
1239 10,
1240 ]:
1241 margin = 24
1242 else:
1243 margin = 12
1244 page.desc.Wrap(w - margin)
1245 bitmaps = {
1246 "black_level": {CRT: "luminance", not CRT: "black_level"},
1247 "luminance": {CRT: "contrast", not CRT: "luminance"},
1248 }
1249 if page.ctrltype == "check_all":
1250 for name in bitmaps:
1251 bitmap = bitmaps.get(name).get(getcfg("measurement_mode") == "c")
1252 page.txt[name].spacer.SetBitmap(
1253 get_bitmap(f"theme/icons/16x16/{bitmap}")
1254 )
1255 else:
1256 ctrltype = {"rgb_offset": "black_level", "rgb_gain": "luminance"}.get(
1257 page.ctrltype, page.ctrltype
1258 )
1259 bitmap = bitmaps.get(ctrltype).get(getcfg("measurement_mode") == "c")
1260 page.gauges["L"].label.SetBitmap(
1261 get_bitmap(f"theme/icons/16x16/{bitmap}")
1262 )
1263 page.Fit()
1264 page.Layout()
1265 for txt in page.txt.values():
1266 txt.SetLabel(" ")
1267 self.lb.SetMinSize(
1268 (self.lb.GetMinSize()[0], max(self.lb.GetCurrentPage().GetSize()[1], min_h))
1269 )
1270 self.Fit()
1271 self.Sizer.SetSizeHints(self)
1272 self.Sizer.Layout()
1273
1274 # Set position
1275 x = getcfg("position.progress.x")
1276 y = getcfg("position.progress.y")
1277 self.SetSaneGeometry(x, y)
1278
1279 def abort(self):
1280 """Abort the current operation."""
1281 if self.has_worker_subprocess() and self.is_measuring:
1282 self.worker.safe_send(" ")
1283
1284 def abort_and_send(self, key):
1285 """Abort the current operation and send a key to the worker subprocess.
1286
1287 Args:
1288 key (str): The key to send to the worker subprocess.
1289 """
1290 self.abort()
1291 if self.has_worker_subprocess() and self.worker.safe_send(key):
1292 self.is_busy = True
1293 self.adjustment_btn.Disable()
1294 self.calibration_btn.Disable()
1295
1296 def add_panel(self, size=wx.DefaultSize, flag=0):
1297 """Add a panel to the sizer with the specified size and flags.
1298
1299 Args:
1300 size (tuple): The size of the panel to add.
1301 flag (int): The flags to apply to the panel.
1302
1303 Returns:
1304 wx.Panel: The created panel instance.
1305 """
1306 panel = get_panel(self, size)
1307 self.sizer.Add(panel, flag=flag)
1308 return panel
1309
1310 def continue_to_calibration(self, event=None):
1311 """Continue to the calibration step after interactive adjustment.
1312
1313 Args:
1314 event (wx.Event, optional): The event that triggered this method.
1315 """
1316 if getcfg("trc"):
1317 self.abort_and_send("7")
1318 else:
1319 self.abort_and_send("8")
1320
1321 def create_start_interactive_adjustment_button(
1322 self, icon="play", enable=False, startstop="start"
1323 ):
1324 """Create or update the interactive adjustment button.
1325
1326 Args:
1327 icon (str): The icon to use for the button.
1328 enable (bool): Whether the button should be enabled.
1329 startstop (str): The action to display on the button, either
1330 "start" or "stop".
1331 """
1332 if getattr(self, "adjustment_btn", None):
1333 self.adjustment_btn._bitmap = get_bitmap(f"theme/icons/10x10/{icon}")
1334 self.adjustment_btn.SetLabel(
1335 lang.getstr(f"calibration.interactive_display_adjustment.{startstop}")
1336 )
1337 self.adjustment_btn.Enable(enable)
1338 return
1339 self.adjustment_btn = self.create_gradient_button(
1340 get_bitmap(f"theme/icons/10x10/{icon}"),
1341 lang.getstr(f"calibration.interactive_display_adjustment.{startstop}"),
1342 name="adjustment_btn",
1343 )
1344 self.adjustment_btn.Bind(wx.EVT_BUTTON, self.start_interactive_adjustment)
1345 self.adjustment_btn.Enable(enable)
1346
1347 def create_gradient_button(self, bitmap, label, name):
1348 """Create a gradient button with the specified bitmap and label.
1349
1350 Args:
1351 bitmap (wx.Bitmap): The bitmap to display on the button.
1352 label (str): The label for the button.
1353 name (str): The name of the button.
1354
1355 Returns:
1356 FlatShadedButton: The created button instance.
1357 """
1358 btn = FlatShadedButton(
1359 self, bitmap=bitmap, label=label, name=name, fgcolour=FGCOLOUR
1360 )
1361 self.btnsizer.Add(btn)
1362 self.btnsizer.Layout()
1363 return btn
1364
1365 def flush(self):
1366 """Flush the output buffer of the worker subprocess if available."""
1367
1368 def has_worker_subprocess(self):
1369 """Check if the worker subprocess is available.
1370
1371 Returns:
1372 bool: True if the worker subprocess is available, False otherwise.
1373 """
1374 return bool(
1375 getattr(self, "worker", None) and getattr(self.worker, "subprocess", None)
1376 )
1377
1378 def isatty(self):
1379 """Check if the interactive display adjustment is in a terminal.
1380
1381 Returns:
1382 bool: Always returns True, as this is a GUI application.
1383 """
1384 return True
1385
1386 def key_handler(self, event):
1387 """Handle key events for interactive display adjustment.
1388
1389 Args:
1390 event (wx.Event): The key event triggered by the user.
1391 """
1392 # print {wx.EVT_CHAR.typeId: 'EVT_CHAR',
1393 # wx.EVT_CHAR_HOOK.typeId: 'EVT_CHAR_HOOK',
1394 # wx.EVT_KEY_DOWN.typeId: 'EVT_KEY_DOWN',
1395 # wx.EVT_MENU.typeId: 'EVT_MENU'}.get(event.GetEventType(),
1396 # event.GetEventType())
1397 keycode = None
1398 if event.GetEventType() in (
1399 wx.EVT_CHAR.typeId,
1400 wx.EVT_CHAR_HOOK.typeId,
1401 wx.EVT_KEY_DOWN.typeId,
1402 ):
1403 keycode = event.GetKeyCode()
1404 elif event.GetEventType() == wx.EVT_MENU.typeId:
1405 keycode = self.id_to_keycode.get(event.GetId())
1406 if keycode == wx.WXK_TAB:
1407 self.global_navigate() or event.Skip()
1408 elif keycode >= 0:
1409 if keycode == ord(" "):
1410 if (
1411 not isinstance(self.FindFocus(), FlatShadedButton)
1412 or self.FindFocus() is self.adjustment_btn
1413 ):
1414 if self.is_measuring:
1415 self.abort()
1416 else:
1417 self.start_interactive_adjustment()
1418 else:
1419 event.Skip()
1420 elif keycode in [ord(str(c)) for c in range(1, 6)]:
1421 key_num = chr(keycode)
1422 pagenum = dict(
1423 list(
1424 zip(
1425 list(self.pagenum_2_argyll_key_num.values()),
1426 list(self.pagenum_2_argyll_key_num.keys()),
1427 )
1428 )
1429 ).get(key_num)
1430 if pagenum not in self.lb.disabled_pages and not self.is_measuring:
1431 self.lb.SetSelection(pagenum)
1432 self.start_interactive_adjustment()
1433 elif keycode in (ord("\x1b"), ord("7"), ord("8"), ord("Q"), ord("q")):
1434 if not getcfg("trc") and keycode == ord("7"):
1435 # Ignore
1436 pass
1437 elif self.keyhandler:
1438 self.keyhandler(event)
1439 elif self.has_worker_subprocess():
1440 self.worker.safe_send(chr(keycode))
1441 else:
1442 event.Skip()
1443 else:
1444 event.Skip()
1445 else:
1446 event.Skip()
1447
1448 def measurement_play_sound_handler(self, event):
1449 """Toggle the sound on/off setting and update the button bitmap.
1450
1451 Args:
1452 event (wx.Event): The event triggered by the button click.
1453 """
1454 # self.measurement_play_sound_ctrl.SetValue(
1455 # not self.measurement_play_sound_ctrl.GetValue()
1456 # )
1457 setcfg(
1458 "measurement.play_sound", int(not (bool(getcfg("measurement.play_sound"))))
1459 )
1460 self.set_sound_on_off_btn_bitmap()
1461
1462 def get_sound_on_off_btn_bitmap(self):
1463 """Get the bitmap for the sound on/off button based on the current setting."""
1464 if getcfg("measurement.play_sound"):
1465 bitmap = get_icon(16, "sound_volume_full")
1466 else:
1467 bitmap = get_icon(16, "sound_off")
1468 return bitmap
1469
1470 def set_sound_on_off_btn_bitmap(self):
1471 """Set the bitmap for the sound on/off button based on the current setting."""
1472 bitmap = self.get_sound_on_off_btn_bitmap()
1473 self.sound_on_off_btn._bitmap = bitmap
1474
1475 def parse_txt(self, txt):
1476 """Parse the text output from the instrument and update the UI.
1477
1478 Args:
1479 txt (str): The text output from the instrument.
1480 """
1481 colors = {True: wx.Colour(0x33, 0xCC, 0x0), False: FGCOLOUR}
1482 if not txt:
1483 return
1484 self.logger.info(f"{txt!r}")
1485 self.Pulse(txt)
1486
1487 if "/ Current" in txt:
1488 indicator = get_bitmap("theme/icons/10x10/record")
1489 else:
1490 indicator = get_bitmap("theme/icons/10x10/record_outline")
1491
1492 target_br = re.search(
1493 r"Target white brightness = (\d+(?:\.\d+)?)".replace(" ", r"\s+"), txt, re.I
1494 )
1495 if getcfg("measurement_mode") == "c":
1496 target_bl = re.search(
1497 (
1498 r"Target Near Black = (\d+(?:\.\d+)?), Current = (\d+(?:\.\d+)?)"
1499 ).replace(" ", r"\s+"),
1500 txt,
1501 re.I,
1502 )
1503 if target_bl:
1504 self.lb.GetCurrentPage().target_bl = [
1505 "Target",
1506 float(target_bl.groups()[0]),
1507 ]
1508 initial_br = re.search(
1509 (
1510 r"(Initial|Target)(?: Br)? (\d+(?:\.\d+)?)\s*(?:, "
1511 r"x (\d+(?:\.\d+)?)\s*, y (\d+(?:\.\d+)?)(?:\s*, "
1512 r"(?:(V[CD]T \d+K?) )?DE(?: 2K)? (\d+(?:\.\d+)?))?|$)"
1513 ).replace(" ", r"\s+"),
1514 txt,
1515 re.I,
1516 )
1517 current_br = None
1518 current_bl = None
1519 if target_br and not getattr(self, "target_br", None):
1520 self.target_br = ["Target", float(target_br.groups()[0])]
1521 if initial_br:
1522 self.lb.GetCurrentPage().initial_br = [
1523 initial_br.groups()[0],
1524 float(initial_br.groups()[1]),
1525 *list(initial_br.groups()[2:]),
1526 ]
1527 if self.lb.GetCurrentPage().ctrltype != "check_all":
1528 current_br = re.search(
1529 r"Current(?: Br)? (\d+(?:\.\d+)?)".replace(" ", r"\s+"), txt, re.I
1530 )
1531 else:
1532 current_br = re.search(
1533 (
1534 r"Target Brightness = (?:\d+(?:\.\d+)?), Current = (\d+(?:\.\d+)?)"
1535 ).replace(" ", r"\s+"),
1536 txt,
1537 re.I,
1538 )
1539 if not current_br:
1540 current_br = re.search(
1541 r"Current Brightness = (\d+(?:\.\d+)?)".replace(" ", r"\s+"),
1542 txt,
1543 re.I,
1544 )
1545 if getcfg("measurement_mode") == "c":
1546 if target_bl:
1547 current_bl = float(target_bl.groups()[1])
1548 else:
1549 current_bl = re.search(
1550 (
1551 r"Black = XYZ (?:\d+(?:\.\d+)?) (\d+(?:\.\d+)?) "
1552 r"(?:\d+(?:\.\d+)?)"
1553 ).replace(" ", r"\s+"),
1554 txt,
1555 re.I,
1556 )
1557 if current_bl:
1558 current_bl = float(current_bl.groups()[0])
1559 xy_dE_rgb = re.search(
1560 (
1561 r"x (\d+(?:\.\d+)?)[=+-]*, y (\d+(?:\.\d+)?)[=+-]*,? "
1562 r"(?:(V[CD]T \d+K?) )?DE(?: 2K)? (\d+(?:\.\d+)?) "
1563 r"R([=+-]+) G([=+-]+) B([=+-]+)"
1564 ).replace(" ", r"\s+"),
1565 txt,
1566 re.I,
1567 )
1568 white_xy_dE_re = (
1569 r"(?:Target white = x (?:\d+(?:\.\d+)?), y (?:\d+(?:\.\d+)?), "
1570 r"Current|Current white) = x (\d+(?:\.\d+)?), y (\d+(?:\.\d+)?), "
1571 r"(?:(?:(V[CD]T \d+K?) )?DE(?: 2K)?|error =) (\d+(?:\.\d+)?)"
1572 ).replace(" ", r"\s+")
1573 white_xy_dE = re.search(white_xy_dE_re, txt, re.I)
1574 black_xy_dE = re.search(white_xy_dE_re.replace(r"white", "black"), txt, re.I)
1575 white_xy_target = re.search(
1576 r"Target white = x (\d+(?:\.\d+)?), y (\d+(?:\.\d+)?)".replace(" ", r"\s+"),
1577 txt,
1578 re.I,
1579 )
1580 black_xy_target = re.search(
1581 r"Target black = x (\d+(?:\.\d+)?), y (\d+(?:\.\d+)?)".replace(" ", r"\s+"),
1582 txt,
1583 re.I,
1584 )
1585 if current_br or current_bl or xy_dE_rgb or white_xy_dE or black_xy_dE:
1586 self.Freeze()
1587 if current_br:
1588 initial_br = getattr(self.lb.GetCurrentPage(), "initial_br", None)
1589 if self.lb.GetCurrentPage().ctrltype in (
1590 "rgb_gain",
1591 "luminance",
1592 "check_all",
1593 ):
1594 target_br = getattr(self, "target_br", None)
1595 else:
1596 target_br = None
1597 if self.lb.GetCurrentPage().ctrltype == "rgb_gain" and initial_br:
1598 initial_br = ["Initial"] + initial_br[1:]
1599 compare_br = (
1600 target_br or initial_br or ("Initial", float(current_br.groups()[0]))
1601 )
1602 lstr = (compare_br[0]).lower()
1603 percent = 100.0 / compare_br[1] if compare_br[1] else 100.0
1604 l_diff = float(current_br.groups()[0]) - compare_br[1]
1605 l = round(50 + l_diff * percent)
1606 if self.lb.GetCurrentPage().gauges.get("L"):
1607 self.lb.GetCurrentPage().gauges["L"].SetValue(min(max(l, 1), 100))
1608 self.lb.GetCurrentPage().gauges["L"].Refresh()
1609 if self.lb.GetCurrentPage().txt.get("luminance"):
1610 if initial_br or target_br: # and round(l_diff, 2):
1611 if round(l_diff, 2) > 0:
1612 sign = "+"
1613 elif round(l_diff, 2) < 0:
1614 sign = "-"
1615 else:
1616 sign = "\u00b1" # plusminus
1617 label = (
1618 f"{lang.getstr(lstr)} {compare_br[1]:.2f} "
1619 f"cd/m\u00b2\n{lang.getstr('current')} "
1620 f"{float(current_br.groups()[0]):.2f} cd/m\u00b2 "
1621 f"({sign}{abs(l_diff) * percent:.2f}%)"
1622 )
1623 else:
1624 label = (
1625 f"{lang.getstr('current')} "
1626 f"{float(current_br.groups()[0]):.2f} cd/m\u00b2"
1627 )
1628 self.lb.GetCurrentPage().txt[
1629 "luminance"
1630 ].checkmark.GetContainingSizer().Show(
1631 self.lb.GetCurrentPage().txt["luminance"].checkmark,
1632 lstr == "target" and abs(l_diff) * percent <= 1,
1633 )
1634 self.lb.GetCurrentPage().txt["luminance"].SetForegroundColour(
1635 colors[lstr == "target" and abs(l_diff) * percent <= 1]
1636 )
1637 set_label_and_size(self.lb.GetCurrentPage().txt["luminance"], label)
1638 if current_bl and self.lb.GetCurrentPage().txt.get("black_level"):
1639 target_bl = getattr(self.lb.GetCurrentPage(), "target_bl", None) or getattr(
1640 self.lb.GetCurrentPage(), "initial_br", None
1641 )
1642 if target_bl:
1643 percent = 100.0 / target_bl[1]
1644 if target_bl: # and round(target_bl[1], 2) != round(current_bl, 2):
1645 l_diff = current_bl - target_bl[1]
1646 if round(l_diff, 2) > 0:
1647 sign = "+"
1648 elif round(l_diff, 2) < 0:
1649 sign = "-"
1650 else:
1651 sign = "\u00b1" # plusminus
1652 label = "{} {:.2f} cd/m\u00b2\n{} {:.2f} cd/m\u00b2 ({}{:.2f}%)".format(
1653 lang.getstr("target"),
1654 target_bl[1],
1655 lang.getstr("current"),
1656 current_bl,
1657 sign,
1658 abs(l_diff) * percent,
1659 )
1660 else:
1661 l_diff = 0 if target_bl else None
1662 label = f"{lang.getstr('current')} {current_bl:.2f} cd/m\u00b2"
1663 self.lb.GetCurrentPage().txt[
1664 "black_level"
1665 ].checkmark.GetContainingSizer().Show(
1666 self.lb.GetCurrentPage().txt["black_level"].checkmark,
1667 l_diff is not None and abs(l_diff) * percent <= 1,
1668 )
1669 self.lb.GetCurrentPage().txt["black_level"].SetForegroundColour(
1670 colors[l_diff is not None and abs(l_diff) * percent <= 1]
1671 )
1672 set_label_and_size(self.lb.GetCurrentPage().txt["black_level"], label)
1673 # groups()[0] = x
1674 # groups()[1] = y
1675 # groups()[2] = VDT/VCT (optional)
1676 # groups()[3] = dE
1677 # groups()[4] = R +-
1678 # groups()[5] = G +-
1679 # groups()[6] = B +-
1680 if xy_dE_rgb:
1681 x, y, vdt, dE = get_xy_vt_dE(xy_dE_rgb.groups())
1682 r = round(
1683 50
1684 - (xy_dE_rgb.groups()[4].count("+") - xy_dE_rgb.groups()[4].count("-"))
1685 * dE
1686 )
1687 g = round(
1688 50
1689 - (xy_dE_rgb.groups()[5].count("+") - xy_dE_rgb.groups()[5].count("-"))
1690 * dE
1691 )
1692 b = round(
1693 50
1694 - (xy_dE_rgb.groups()[6].count("+") - xy_dE_rgb.groups()[6].count("-"))
1695 * dE
1696 )
1697 if self.lb.GetCurrentPage().gauges.get("R"):
1698 self.lb.GetCurrentPage().gauges["R"].SetValue(min(max(r, 1), 100))
1699 self.lb.GetCurrentPage().gauges["R"].Refresh()
1700 if self.lb.GetCurrentPage().gauges.get("G"):
1701 self.lb.GetCurrentPage().gauges["G"].SetValue(min(max(g, 1), 100))
1702 self.lb.GetCurrentPage().gauges["G"].Refresh()
1703 if self.lb.GetCurrentPage().gauges.get("B"):
1704 self.lb.GetCurrentPage().gauges["B"].SetValue(min(max(b, 1), 100))
1705 self.lb.GetCurrentPage().gauges["B"].Refresh()
1706 if self.lb.GetCurrentPage().txt.get("rgb"):
1707 self.lb.GetCurrentPage().txt["rgb"].checkmark.GetContainingSizer().Show(
1708 self.lb.GetCurrentPage().txt["rgb"].checkmark, abs(dE) <= 1
1709 )
1710 self.lb.GetCurrentPage().txt["rgb"].SetForegroundColour(
1711 colors[abs(dE) <= 1]
1712 )
1713 label = (
1714 f"{lang.getstr('current')} "
1715 f"x {x:.4f} y {y:.4f} {vdt} {dE:.1f} \u0394E*00"
1716 ).replace(" ", " ")
1717 initial_br = getattr(self.lb.GetCurrentPage(), "initial_br", None)
1718 if initial_br and len(initial_br) > 3:
1719 x, y, vdt, dE = get_xy_vt_dE(initial_br[2:])
1720 label = (
1721 f"{lang.getstr(initial_br[0].lower())} "
1722 f"x {x:.4f} y {y:.4f} {vdt} {dE:.1f} \u0394E*00\n"
1723 ).replace(" ", " ") + label
1724 set_label_and_size(self.lb.GetCurrentPage().txt["rgb"], label)
1725 if white_xy_dE:
1726 x, y, vdt, dE = get_xy_vt_dE(white_xy_dE.groups())
1727 if self.lb.GetCurrentPage().txt.get("white_point"):
1728 self.lb.GetCurrentPage().txt[
1729 "white_point"
1730 ].checkmark.GetContainingSizer().Show(
1731 self.lb.GetCurrentPage().txt["white_point"].checkmark, abs(dE) <= 1
1732 )
1733 self.lb.GetCurrentPage().txt["white_point"].SetForegroundColour(
1734 colors[abs(dE) <= 1]
1735 )
1736 label = (
1737 f"{lang.getstr('current')} "
1738 f"x {x:.4f} y {y:.4f} {vdt} {dE:.1f} \u0394E*00"
1739 ).replace(" ", " ")
1740 if white_xy_target:
1741 x, y, vdt, dE = get_xy_vt_dE(white_xy_target.groups())
1742 label = (f"{lang.getstr('target')} x {x:.4f} y {y:.4f}\n").replace(
1743 " ", " "
1744 ) + label
1745 set_label_and_size(self.lb.GetCurrentPage().txt["white_point"], label)
1746 if black_xy_dE:
1747 x, y, vdt, dE = get_xy_vt_dE(black_xy_dE.groups())
1748 if self.lb.GetCurrentPage().txt.get("white_point"):
1749 self.lb.GetCurrentPage().txt[
1750 "black_point"
1751 ].checkmark.GetContainingSizer().Show(
1752 self.lb.GetCurrentPage().txt["black_point"].checkmark, abs(dE) <= 1
1753 )
1754 self.lb.GetCurrentPage().txt["black_point"].SetForegroundColour(
1755 colors[abs(dE) <= 1]
1756 )
1757 label = (
1758 f"{lang.getstr('current')} x {x:.4f} y {y:.4f} {vdt} {dE:.1f} "
1759 "\u0394E*00"
1760 ).replace(" ", " ")
1761 if black_xy_target:
1762 x, y, vdt, dE = get_xy_vt_dE(black_xy_target.groups())
1763 label = (f"{lang.getstr('target')} x {x:.4f} y {y:.4f}\n").replace(
1764 " ", " "
1765 ) + label
1766 set_label_and_size(self.lb.GetCurrentPage().txt["black_point"], label)
1767 if (
1768 current_br or current_bl or xy_dE_rgb
1769 ) and self.lb.GetCurrentPage().ctrltype != "check_all":
1770 if getcfg("measurement.play_sound"):
1771 self.measurement_sound.safe_play()
1772 self.indicator_ctrl.SetBitmap(indicator)
1773 self.btnsizer.Layout()
1774 if current_br or current_bl or xy_dE_rgb or white_xy_dE or black_xy_dE:
1775 self.lb.GetCurrentPage().Layout()
1776 self.Thaw()
1777 if "Press 1 .. 7" in txt or "8) Exit" in txt:
1778 if self.cold_run:
1779 self.cold_run = False
1780 self.Pulse(" " * 4)
1781 if self.is_measuring is not False:
1782 self.lb.Children[0].Refresh()
1783 if self.is_measuring is True:
1784 self.create_start_interactive_adjustment_button(enable=True)
1785 else:
1786 self.adjustment_btn.Enable()
1787 self.is_busy = False
1788 self.is_measuring = False
1789 self.indicator_ctrl.SetBitmap(get_icon(10, "empty", use_mask=True))
1790 self.calibration_btn.Enable()
1791 # Ensure frame is visible in case it was hidden (e.g. by
1792 # swap_progress_wnds during a measurement sub-step), and try to
1793 # bring it to the front so the user can interact with it.
1794 if not self.IsShownOnScreen():
1795 self.Show()
1796 self.Raise()
1797 self.lb.SetFocus() # Make frame receive EVT_CHAR_HOOK events under Linux
1798 elif "initial measurements" in txt or "check measurements" in txt:
1799 self.is_busy = True
1800 self.lb.Children[0].Refresh()
1801 self.Pulse(lang.getstr("please_wait"))
1802 if not self.is_measuring:
1803 self.create_start_interactive_adjustment_button("pause", True, "stop")
1804 self.is_measuring = True
1805 self.lb.SetFocus() # Make frame receive EVT_CHAR_HOOK events under Linux
1806
1807 # self.SetTitle("is_measuring %s timer.IsRunning %s keepGoing %s" %
1808 # (str(self.is_measuring), self.timer.IsRunning(), self.keepGoing))
1809
1810 def reset(self):
1811 """Reset the display adjustment frame to its initial state."""
1812 self.Freeze()
1813 self._setup()
1814 # Reset controls
1815 for pagenum in range(self.lb.GetPageCount()):
1816 page = self.lb.GetPage(pagenum)
1817 page.initial_br = None
1818 page.target_bl = None
1819 for name in ("R", "G", "B", "L"):
1820 if page.gauges.get(name):
1821 page.gauges[name].SetValue(0)
1822 page.gauges[name].Refresh()
1823 for txt in page.txt.values():
1824 txt.checkmark.GetContainingSizer().Hide(txt.checkmark)
1825 txt.SetForegroundColour(FGCOLOUR)
1826 self.create_start_interactive_adjustment_button()
1827 self.calibration_btn.Disable()
1828 self.Thaw()
1829
1830 def start_interactive_adjustment(self, event=None):
1831 """Start the interactive display adjustment process.
1832
1833 Args:
1834 event (wx.Event, optional): The event that triggered this method.
1835 """
1836 if self.is_measuring:
1837 self.abort()
1838 else:
1839 self.abort_and_send(self.pagenum_2_argyll_key_num[self.lb.GetSelection()])
1840
1841 def start_timer(self, ms=50):
1842 """Start the timer with a specified interval.
1843
1844 Args:
1845 ms (int): The interval in milliseconds to trigger the timer.
1846 """
1847 self.timer.Start(ms)
1848
1849 def stop_timer(self):
1850 """Stop the timer."""
1851 self.timer.Stop()
1852
1853 def write(self, txt):
1854 """Write text to the display adjustment frame.
1855
1856 Args:
1857 txt (str): The text to write.
1858 """
1859 wx.CallAfter(self.parse_txt, txt)