Debian Codegraph @

DisplayCAL/wx_display_uniformity_frame.py

raw
1 """Interactive display calibration UI."""
2
3 import os
4 import re
5 import sys
6 from time import strftime
7
8 from DisplayCAL import localization as lang
9 from DisplayCAL import report
10 from DisplayCAL.config import (
11 get_bitmap,
12 get_display_number,
13 get_display_rects,
14 get_icon_bundle,
15 get_verified_path,
16 getcfg,
17 setcfg,
18 )
19 from DisplayCAL.debughelpers import Error
20 from DisplayCAL.log import get_file_logger
21 from DisplayCAL.meta import NAME as APPNAME
22 from DisplayCAL.meta import VERSION_STRING as APPVERSION
23 from DisplayCAL.util_os import launch_file, waccess
24 from DisplayCAL.wx_addons import CustomEvent, wx
25 from DisplayCAL.wx_measure_frame import MeasureFrame
26 from DisplayCAL.wx_windows import (
27 NAV_KEYCODES,
28 NUMPAD_KEYCODES,
29 PROCESSING_KEYCODES,
30 BaseFrame,
31 FlatShadedButton,
32 wx_Panel,
33 )
34
35 BGCOLOUR = wx.Colour(0x33, 0x33, 0x33)
36
37
38 class FlatShadedNumberedButton(FlatShadedButton):
39 """Flat shaded button with a number.
40
41 Args:
42 parent (wx.Window): The parent window for this button.
43 id (int, optional): The identifier for the button. Defaults to
44 wx.ID_ANY.
45 bitmap (wx.Bitmap, optional): The bitmap to display on the button.
46 Defaults to None.
47 label (str, optional): The label for the button. Defaults to an empty
48 string.
49 pos (wx.Point, optional): The position of the button. Defaults to
50 wx.DefaultPosition.
51 size (wx.Size, optional): The size of the button. Defaults to
52 wx.DefaultSize.
53 style (int, optional): The style of the button. Defaults to
54 wx.NO_BORDER.
55 validator (wx.Validator, optional): The validator for the button.
56 Defaults to wx.DefaultValidator.
57 name (str, optional): The name of the button. Defaults to
58 "gradientbutton".
59 bgcolour (wx.Colour, optional): The background colour of the button.
60 Defaults to None.
61 fgcolour (wx.Colour, optional): The foreground colour of the button.
62 Defaults to None.
63 index (int, optional): The index of the button in the grid. Defaults to
64 0.
65 """
66
67 def __init__(
68 self,
69 parent,
70 id=wx.ID_ANY, # noqa: A002
71 bitmap=None,
72 label="",
73 pos=wx.DefaultPosition,
74 size=wx.DefaultSize,
75 style=wx.NO_BORDER,
76 validator=wx.DefaultValidator,
77 name="gradientbutton",
78 bgcolour=None,
79 fgcolour=None,
80 index=0,
81 ):
82 FlatShadedButton.__init__(
83 self,
84 parent,
85 id,
86 bitmap,
87 label,
88 pos,
89 size,
90 style,
91 validator,
92 name,
93 bgcolour,
94 fgcolour,
95 )
96 self.index = index
97
98 def OnGainFocus(self, event):
99 """Handle the focus gain event for the button.
100
101 Args:
102 event (wx.Event): The focus gain event triggered when the button
103 gains focus.
104 """
105 self.TopLevelParent.index = self.index
106 FlatShadedButton.OnGainFocus(self, event)
107
108
109 class DisplayUniformityFrame(BaseFrame):
110 """Display uniformity measurement frame.
111
112 Args:
113 parent (wx.Window): The parent window for this frame.
114 handler (callable, optional): A function to handle timer events.
115 Defaults to None.
116 keyhandler (callable, optional): A function to handle key events.
117 Defaults to None.
118 start_timer (bool, optional): Whether to start the timer on
119 initialization. Defaults to True.
120 rows (int, optional): Number of rows in the grid. Defaults to config
121 value.
122 cols (int, optional): Number of columns in the grid. Defaults to config
123 value.
124 """
125
126 def __init__(
127 self,
128 parent=None,
129 handler=None,
130 keyhandler=None,
131 start_timer=True,
132 rows=None,
133 cols=None,
134 ):
135 if not rows:
136 rows = getcfg("uniformity.rows")
137 if not cols:
138 cols = getcfg("uniformity.cols")
139 BaseFrame.__init__(
140 self,
141 parent,
142 wx.ID_ANY,
143 lang.getstr("report.uniformity"),
144 style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL,
145 name="displayuniformityframe",
146 )
147 self.SetIcons(get_icon_bundle([256, 48, 32, 16], APPNAME))
148 self.SetBackgroundColour(BGCOLOUR)
149 self.sizer = wx.GridSizer(rows, cols, 0, 0)
150 self.SetSizer(self.sizer)
151
152 self.rows = rows
153 self.cols = cols
154 self.colors = (
155 wx.WHITE,
156 wx.Colour(192, 192, 192),
157 wx.Colour(128, 128, 128),
158 wx.Colour(64, 64, 64),
159 )
160 self.labels = {}
161 self.panels = []
162 self.buttons = []
163 for index in range(rows * cols):
164 panel = wx_Panel(self, style=wx.BORDER_SIMPLE)
165 panel.SetBackgroundColour(BGCOLOUR)
166 sizer = wx.BoxSizer(wx.VERTICAL)
167 panel.SetSizer(sizer)
168 self.panels.append(panel)
169 button = FlatShadedNumberedButton(
170 panel,
171 label=lang.getstr("measure"),
172 bitmap=get_bitmap("theme/icons/10x10/record"),
173 index=index,
174 )
175 button.Bind(wx.EVT_BUTTON, self.measure)
176 self.buttons.append(button)
177 label = wx.StaticText(panel)
178 label.SetForegroundColour(wx.WHITE)
179 self.labels[index] = label
180 sizer.Add(label, 1, wx.ALIGN_CENTER)
181 sizer.Add(
182 button,
183 0,
184 wx.ALIGN_CENTER | wx.BOTTOM,
185 # | wx.LEFT | wx.RIGHT,
186 border=8,
187 )
188 self.sizer.Add(panel, 1, wx.EXPAND)
189 self.disable_buttons()
190
191 self.keyhandler = keyhandler
192 self.id_to_keycode = {}
193 if sys.platform == "darwin":
194 # Use an accelerator table for tab, space, 0-9, A-Z, numpad,
195 # navigation keys and processing keys
196 keycodes = [wx.WXK_TAB, wx.WXK_SPACE]
197 keycodes.extend(list(range(ord("0"), ord("9"))))
198 keycodes.extend(list(range(ord("A"), ord("Z"))))
199 keycodes.extend(NUMPAD_KEYCODES)
200 keycodes.extend(NAV_KEYCODES)
201 keycodes.extend(PROCESSING_KEYCODES)
202 for keycode in keycodes:
203 self.id_to_keycode[wx.Window.NewControlId()] = keycode
204 accels = []
205 for id_ in self.id_to_keycode:
206 keycode = self.id_to_keycode[id_]
207 self.Bind(wx.EVT_MENU, self.key_handler, id=id_)
208 accels.append((wx.ACCEL_NORMAL, keycode, id_))
209 if keycode == wx.WXK_TAB:
210 accels.append((wx.ACCEL_SHIFT, keycode, id_))
211 self.SetAcceleratorTable(wx.AcceleratorTable(accels))
212 else:
213 self.Bind(wx.EVT_CHAR_HOOK, self.key_handler)
214
215 # Event handlers
216 self.Bind(wx.EVT_CLOSE, self.OnClose, self)
217 self.Bind(wx.EVT_MOVE, self.OnMove, self)
218 self.timer = wx.Timer(self)
219 if handler:
220 self.Bind(wx.EVT_TIMER, handler, self.timer)
221 self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)
222
223 # Final initialization steps
224 self.logger = get_file_logger("uniformity")
225 self._setup()
226
227 self.Show()
228
229 if start_timer:
230 self.start_timer()
231
232 def EndModal(self, returncode=wx.ID_OK):
233 """End the modal state of the display uniformity frame.
234
235 Args:
236 returncode (int): The return code to indicate the result of the modal
237 operation. Default is wx.ID_OK.
238
239 Returns:
240 int: The return code indicating the result of the modal operation.
241 """
242 return returncode
243
244 def MakeModal(self, modal=False):
245 """Make the display uniformity frame modal.
246
247 Args:
248 modal (bool): If True, make the frame modal; if False, make it
249 non-modal.
250 """
251
252 def OnClose(self, event):
253 """Handle the close event for the display uniformity frame.
254
255 Args:
256 event (wx.Event): The close event triggered when the frame is closed.
257 """
258 if not self.timer.IsRunning():
259 self.Destroy()
260 else:
261 self.keepGoing = False
262
263 def OnDestroy(self, event):
264 """Handle the destruction of the display uniformity frame.
265
266 Args:
267 event (wx.Event): The destroy event triggered when the frame is closed.
268 """
269 self.stop_timer()
270 del self.timer
271 if not hasattr(wx.Window, "UnreserveControlId"):
272 return 0
273 for id_ in self.id_to_keycode:
274 if id_ >= 0:
275 continue
276 try:
277 wx.Window.UnreserveControlId(id_)
278 except wx.wxAssertionError as exception:
279 print(exception)
280 return 0
281
282 def OnMove(self, event):
283 """Handle the move event for the display uniformity frame.
284
285 Args:
286 event (wx.Event): The move event triggered when the frame is moved.
287 """
288
289 def Pulse(self, msg=""):
290 """Pulse the display uniformity frame with a message.
291
292 Args:
293 msg (str): The message to display during the pulse.
294 """
295 return self.keepGoing, False
296
297 def Resume(self):
298 """Resume the display uniformity frame."""
299 self.keepGoing = True
300
301 def Show(self, show=True):
302 """Show or hide the display uniformity frame.
303
304 Args:
305 show (bool): If True, show the frame; if False, hide it.
306 """
307 if show:
308 display_no = getcfg("display.number") - 1
309 if display_no < 0 or display_no > wx.Display.GetCount() - 1:
310 display_no = 0
311 else:
312 display_no = get_display_number(display_no)
313 x, y, w, h = wx.Display(display_no).ClientArea
314 # Place frame on correct display
315 self.SetPosition((x, y))
316 self.SetSize((w, h))
317 self.disable_buttons()
318 wx.CallAfter(self.Maximize)
319 wx.Frame.Show(self, show)
320 self.panels[0].SetFocus()
321
322 def UpdateProgress(self, value, msg=""):
323 """Update the progress of the display uniformity frame.
324
325 Args:
326 value (int): The progress value to update.
327 msg (str): The message to display during the progress update.
328
329 Returns:
330 bool: True if the pulse was successful, False otherwise.
331 """
332 return self.Pulse(msg)
333
334 def UpdatePulse(self, msg=""):
335 """Update the pulse with a message.
336
337 Args:
338 msg (str): The message to display during the pulse.
339 """
340 return self.Pulse(msg)
341
342 def disable_buttons(self):
343 """Disable all buttons in the display uniformity frame."""
344 self.enable_buttons(False)
345
346 def enable_buttons(self, enable=True):
347 """Enable or disable all buttons in the display uniformity frame.
348
349 Args:
350 enable (bool): If True, enable the buttons; if False, disable them.
351 """
352 for button in self.buttons:
353 button.Enable(enable)
354
355 def flush(self):
356 """Flush the output stream."""
357
358 get_display = MeasureFrame.__dict__["get_display"]
359
360 def has_worker_subprocess(self):
361 """Check if the worker subprocess exists.
362
363 Returns:
364 bool: True if the worker subprocess exists, False otherwise.
365 """
366 return bool(
367 getattr(self, "worker", None) and getattr(self.worker, "subprocess", None)
368 )
369
370 def hide_cursor(self):
371 """Hide the cursor and set it to a blank cursor."""
372 cursor_id = wx.CURSOR_BLANK
373 cursor = wx.StockCursor(cursor_id)
374 self.SetCursor(cursor)
375 for panel in self.panels:
376 panel.SetCursor(cursor)
377 for label in list(self.labels.values()):
378 label.SetCursor(cursor)
379 for button in self.buttons:
380 button.SetCursor(cursor)
381
382 def isatty(self):
383 """Check if the standard output is a terminal.
384
385 Returns:
386 bool: True if the standard output is a terminal, False otherwise.
387 """
388 return True
389
390 def key_handler(self, event):
391 """Handle key events for the display uniformity frame.
392
393 Args:
394 event (wx.Event): The key event to handle.
395 """
396 keycode = None
397 if event.GetEventType() in (
398 wx.EVT_CHAR.typeId,
399 wx.EVT_CHAR_HOOK.typeId,
400 wx.EVT_KEY_DOWN.typeId,
401 ):
402 keycode = event.GetKeyCode()
403 elif event.GetEventType() == wx.EVT_MENU.typeId:
404 keycode = self.id_to_keycode.get(event.GetId())
405 if keycode == wx.WXK_TAB:
406 self.global_navigate() or event.Skip()
407 elif keycode >= 0:
408 if self.has_worker_subprocess() and keycode < 256:
409 if keycode == wx.WXK_ESCAPE or chr(keycode) == "Q":
410 # ESC or Q
411 self.worker.abort_subprocess()
412 elif (
413 self.index > -1
414 and not self.is_measuring
415 and (
416 not isinstance(self.FindFocus(), wx.Control)
417 or keycode != wx.WXK_SPACE
418 )
419 ):
420 # Any other key
421 self.measure(
422 CustomEvent(wx.EVT_BUTTON.typeId, self.buttons[self.index])
423 )
424 else:
425 event.Skip()
426 else:
427 event.Skip()
428 else:
429 event.Skip()
430
431 def measure(self, event=None):
432 """Start measuring the uniformity grid.
433
434 Args:
435 event (wx.Event, optional): The event that triggered the
436 measurement. Defaults to None.
437 """
438 if event:
439 self.index = event.GetEventObject().index
440 print(f"{APPNAME}: Uniformity grid index {self.index}")
441 self.is_measuring = True
442 self.results[self.index] = []
443 self.labels[self.index].SetLabel("")
444 self.hide_cursor()
445 self.disable_buttons()
446 self.buttons[self.index].Hide()
447 self.panels[self.index].SetBackgroundColour(
448 self.colors[len(self.results[self.index])]
449 )
450 self.panels[self.index].Refresh()
451 self.panels[self.index].Update()
452 print(
453 f"{APPNAME}: About to measure uniformity grid index {self.index} "
454 f"@{self.colors[len(self.results[self.index])].red / 2.55}%"
455 )
456 # Use a delay to allow for TFT lag
457 wx.CallLater(200, self.safe_send, " ")
458
459 def parse_txt(self, txt):
460 """Parse the text output from the instrument.
461
462 Args:
463 txt (str): The text output from the instrument.
464 """
465 if not txt:
466 return
467 self.logger.info(f"{txt!r}")
468 if "Setting up the instrument" in txt:
469 self.Pulse(lang.getstr("instrument.initializing"))
470 if "Spot read failed" in txt:
471 self.last_error = txt
472 if "Result is XYZ:" in txt:
473 # Result is XYZ: d.dddddd d.dddddd d.dddddd, D50 Lab: d.dddddd d.dddddd d.dddddd # noqa: E501
474 # CCT = ddddK (Delta E d.dddddd)
475 # Closest Planckian temperature = ddddK (Delta E d.dddddd)
476 # Closest Daylight temperature = ddddK (Delta E d.dddddd)
477 XYZ = re.search(r"XYZ:\s+(\d+\.\d+)\s+(\d+\.\d+)\s+(\d+\.\d+)", txt)
478 self.results[self.index].append(
479 {"XYZ": [float(value) for value in XYZ.groups()]}
480 )
481 self.last_error = None
482 loci = {"t": "Daylight", "T": "Planckian"}
483 for locus in list(loci.values()):
484 if locus in txt:
485 CT = re.search(
486 rf"Closest\s+{locus}\s+temperature\s+=\s+(\d+)K", txt, re.I
487 )
488 self.results[self.index][-1][f"C{locus[0]}T"] = int(CT.groups()[0])
489 if "key to take a reading" not in txt or self.last_error:
490 return
491 print(f"{APPNAME}: Got 'key to take a reading'")
492 if not self.is_measuring:
493 self.enable_buttons()
494 return
495 if len(self.results[self.index]) < len(self.colors):
496 # Take readings at 5 different brightness levels per swatch
497 print(f"{APPNAME}: About to take next reading")
498 self.measure()
499 else:
500 self.is_measuring = False
501 self.show_cursor()
502 self.enable_buttons()
503 self.buttons[self.index].Show()
504 self.buttons[self.index].SetFocus()
505 self.buttons[self.index].SetBitmap(
506 get_bitmap("theme/icons/16x16/checkmark")
507 )
508 self.panels[self.index].SetBackgroundColour(BGCOLOUR)
509 self.panels[self.index].Refresh()
510 self.panels[self.index].Update()
511 if len(self.results) == self.rows * self.cols:
512 # All swatches have been measured, show results
513 # Let the user choose a location for the results html
514 display_no, geometry, client_area = self.get_display()
515 # Translate from wx display index to Argyll display index
516 geometry = f"{geometry[0]}, {geometry[1]}, {geometry[2]}x{geometry[3]}"
517 for i, display in enumerate(getcfg("displays")):
518 if display.find(f"@ {geometry}") > -1:
519 print(f"Found display {display} at index {i}")
520 break
521 display = display.replace(" [PRIMARY]", "")
522 defaultFile = "Uniformity Check {} — {} — {}".format(
523 APPVERSION,
524 re.sub(r"[\\/:*?\"<>|]+", "_", display),
525 strftime("%Y-%m-%d %H-%M.html"),
526 )
527 defaultDir = get_verified_path(
528 None, os.path.join(getcfg("profile.save_path"), defaultFile)
529 )[0]
530 dlg = wx.FileDialog(
531 self,
532 lang.getstr("save_as"),
533 defaultDir,
534 defaultFile,
535 wildcard=lang.getstr("filetype.html") + "|*.html;*.htm",
536 style=wx.SAVE | wx.FD_OVERWRITE_PROMPT,
537 )
538 dlg.Center(wx.BOTH)
539 result = dlg.ShowModal()
540 if result == wx.ID_OK:
541 path = dlg.GetPath()
542 if not waccess(path, os.W_OK):
543 from DisplayCAL.worker import show_result_dialog
544
545 show_result_dialog(
546 Error(lang.getstr("error.access_denied.write", path)),
547 self,
548 )
549 return
550 save_path = os.path.splitext(path)[0] + ".html"
551 setcfg("last_filedialog_path", save_path)
552 dlg.Destroy()
553 if result != wx.ID_OK:
554 return
555 locus = loci.get(getcfg("whitepoint.colortemp.locus"))
556 try:
557 report.create(
558 save_path,
559 {
560 "${REPORT_VERSION}": APPVERSION,
561 "${DISPLAY}": display,
562 "${DATETIME}": strftime("%Y-%m-%d %H:%M:%S"),
563 "${ROWS}": str(self.rows),
564 "${COLS}": str(self.cols),
565 "${RESULTS}": str(self.results),
566 "${LOCUS}": locus,
567 },
568 getcfg("report.pack_js"),
569 "uniformity",
570 )
571 except OSError as exception:
572 from DisplayCAL.worker import show_result_dialog
573
574 show_result_dialog(exception, self)
575 else:
576 launch_file(save_path)
577 if getcfg("uniformity.measure.continuous"):
578 self.measure(event=Event(self.buttons[self.index]))
579
580 def reset(self):
581 """Reset the display uniformity frame to its initial state."""
582 self._setup()
583 for panel in self.panels:
584 panel.SetBackgroundColour(BGCOLOUR)
585 for button in self.buttons:
586 button.SetBitmap(get_bitmap("theme/icons/10x10/record"))
587 button.Show()
588 for index in self.labels:
589 self.labels[index].SetLabel("")
590 self.labels[index].GetContainingSizer().Layout()
591 self.show_cursor()
592
593 def _setup(self):
594 self.logger.info("-" * 80)
595 self.index = 0
596 self.is_measuring = False
597 self.keepGoing = True
598 self.last_error = None
599 self.results = {}
600 self.display_rects = get_display_rects()
601
602 def safe_send(self, data):
603 """Safely send the data to the worker subprocess if it exists.
604
605 Args:
606 data (str): The data to send to the worker subprocess.
607 """
608 if self.has_worker_subprocess() and not self.worker.subprocess_abort:
609 if not self.worker.instrument_on_screen:
610 if not getattr(self, "wait_for_instrument_on_screen", False):
611 self.wait_for_instrument_on_screen = True
612 print(f"{APPNAME}: Waiting for instrument to be placed on screen")
613 wx.CallLater(200, self.safe_send, data)
614 else:
615 self.wait_for_instrument_on_screen = False
616 self.worker.safe_send(data)
617
618 def show_cursor(self):
619 """Show the cursor and reset it to the default arrow cursor."""
620 cursor = wx.StockCursor(wx.CURSOR_ARROW)
621 self.SetCursor(cursor)
622 for panel in self.panels:
623 panel.SetCursor(cursor)
624 for label in list(self.labels.values()):
625 label.SetCursor(cursor)
626 for button in self.buttons:
627 button.SetCursor(cursor)
628
629 def start_timer(self, ms=50):
630 """Start the timer with a specified interval in milliseconds.
631
632 Args:
633 ms (int): The interval in milliseconds for the timer. Default is 50 ms.
634 """
635 self.timer.Start(ms)
636
637 def stop_timer(self):
638 """Stop the timer."""
639 self.timer.Stop()
640
641 def write(self, txt):
642 """Write text to the display uniformity frame."""
643 wx.CallAfter(self.parse_txt, txt)
644
645
646 class Event:
647 """Custom event class to handle events in the DisplayUniformityFrame.
648
649 Args:
650 evtobj (wx.Events): The event object associated with this event.
651 """
652
653 def __init__(self, evtobj):
654 self.evtobj = evtobj
655
656 def GetEventObject(self):
657 """Return the event object.
658
659 Returns:
660 The event object associated with this event.
661 """
662 return self.evtobj