Debian Codegraph @

DisplayCAL/wx_untethered_frame.py

raw
1 """Interactive display calibration UI."""
2
3 import os
4 import re
5 import sys
6 import time
7
8 from DisplayCAL import audio, colormath, config
9 from DisplayCAL import localization as lang
10 from DisplayCAL.config import (
11 get_bitmap,
12 get_data_path,
13 get_icon,
14 get_icon_bundle,
15 getcfg,
16 setcfg,
17 )
18 from DisplayCAL.log import get_file_logger
19 from DisplayCAL.meta import NAME as APPNAME
20 from DisplayCAL.options import DEBUG, TEST, VERBOSE
21 from DisplayCAL.wx_addons import wx
22 from DisplayCAL.wx_windows import (
23 NAV_KEYCODES,
24 NUMPAD_KEYCODES,
25 PROCESSING_KEYCODES,
26 BaseFrame,
27 BitmapBackgroundPanel,
28 CustomCheckBox,
29 CustomGrid,
30 FlatShadedButton,
31 wx_Panel,
32 )
33
34 BGCOLOUR = wx.Colour(0x33, 0x33, 0x33)
35 FGCOLOUR = wx.Colour(0x99, 0x99, 0x99)
36
37
38 class UntetheredFrame(BaseFrame):
39 """Untethered measurement frame."""
40
41 def __init__(self, parent=None, handler=None, keyhandler=None, start_timer=True):
42 BaseFrame.__init__(
43 self,
44 parent,
45 wx.ID_ANY,
46 lang.getstr("measurement.untethered"),
47 style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL,
48 name="untetheredframe",
49 )
50 self.SetIcons(get_icon_bundle([256, 48, 32, 16], APPNAME))
51 self.sizer = wx.FlexGridSizer(2, 1, 0, 0)
52 self.sizer.AddGrowableCol(0)
53 self.sizer.AddGrowableRow(0)
54 self.sizer.AddGrowableRow(1)
55 self.panel = wx_Panel(self)
56 self.SetSizer(self.sizer)
57 self.sizer.Add(self.panel, 1, wx.EXPAND)
58 self.panel.SetBackgroundColour(BGCOLOUR)
59 panelsizer = wx.FlexGridSizer(3, 2, 8, 8)
60 panelsizer.AddGrowableCol(0)
61 panelsizer.AddGrowableCol(1)
62 panelsizer.AddGrowableRow(1)
63 self.panel.SetSizer(panelsizer)
64 self.label_RGB = wx.StaticText(self.panel, wx.ID_ANY, " ")
65 self.label_RGB.SetForegroundColour(FGCOLOUR)
66 panelsizer.Add(self.label_RGB, 0, wx.TOP | wx.LEFT | wx.EXPAND, border=8)
67 self.label_XYZ = wx.StaticText(self.panel, wx.ID_ANY, " ")
68 self.label_XYZ.SetForegroundColour(FGCOLOUR)
69 panelsizer.Add(self.label_XYZ, 0, wx.TOP | wx.RIGHT | wx.EXPAND, border=8)
70 if sys.platform == "darwin":
71 style = wx.BORDER_THEME
72 else:
73 style = wx.BORDER_SIMPLE
74 self.panel_RGB = BitmapBackgroundPanel(self.panel, size=(256, 256), style=style)
75 self.panel_RGB.scalebitmap = (True, True)
76 self.panel_RGB.SetBitmap(get_bitmap("theme/checkerboard-32x32x5-333-444"))
77 panelsizer.Add(self.panel_RGB, 1, wx.LEFT | wx.EXPAND, border=8)
78 self.panel_XYZ = BitmapBackgroundPanel(self.panel, size=(256, 256), style=style)
79 self.panel_XYZ.scalebitmap = (True, True)
80 self.panel_XYZ.SetBitmap(get_bitmap("theme/checkerboard-32x32x5-333-444"))
81 panelsizer.Add(self.panel_XYZ, 1, wx.RIGHT | wx.EXPAND, border=8)
82 sizer = wx.BoxSizer(wx.HORIZONTAL)
83 self.back_btn = FlatShadedButton(
84 self.panel, bitmap=get_icon(10, "back"), label="", fgcolour=FGCOLOUR
85 )
86 self.back_btn.Bind(wx.EVT_BUTTON, self.back_btn_handler)
87 sizer.Add(self.back_btn, 0, wx.LEFT | wx.RIGHT, border=8)
88 self.label_index = wx.StaticText(self.panel, wx.ID_ANY, " ")
89 self.label_index.SetForegroundColour(FGCOLOUR)
90 sizer.Add(self.label_index, 0, wx.ALIGN_CENTER_VERTICAL)
91 self.next_btn = FlatShadedButton(
92 self.panel, bitmap=get_icon(10, "play"), label="", fgcolour=FGCOLOUR
93 )
94 self.next_btn.Bind(wx.EVT_BUTTON, self.next_btn_handler)
95 sizer.Add(self.next_btn, 0, wx.LEFT, border=8)
96 sizer.Add((12, 1), 1)
97 self.measure_auto_cb = CustomCheckBox(
98 self.panel, wx.ID_ANY, lang.getstr("auto")
99 )
100 self.measure_auto_cb.SetForegroundColour(FGCOLOUR)
101 self.measure_auto_cb.Bind(wx.EVT_CHECKBOX, self.measure_auto_ctrl_handler)
102 # only vertical alignment flags can be used with a horizontal sizer
103 sizer.Add(self.measure_auto_cb, 0, wx.ALIGN_CENTER_VERTICAL)
104 panelsizer.Add(sizer, 0, wx.BOTTOM | wx.EXPAND, border=8)
105 sizer = wx.BoxSizer(wx.HORIZONTAL)
106 self.measure_btn = FlatShadedButton(
107 self.panel,
108 bitmap=get_icon(10, "play"),
109 label=lang.getstr("measure"),
110 fgcolour=FGCOLOUR,
111 )
112 self.measure_btn.Bind(wx.EVT_BUTTON, self.measure_btn_handler)
113 sizer.Add(self.measure_btn, 0, wx.RIGHT, border=6)
114 # Sound when measuring
115 # Needs to be stereo!
116 self.measurement_sound = audio.Sound(get_data_path("beep.wav"))
117 self.commit_sound = audio.Sound(get_data_path("camera_shutter.wav"))
118 bitmap = self.get_sound_on_off_btn_bitmap()
119 self.sound_on_off_btn = FlatShadedButton(
120 self.panel, bitmap=bitmap, fgcolour=FGCOLOUR
121 )
122 self.sound_on_off_btn.SetToolTipString(lang.getstr("measurement.play_sound"))
123 self.sound_on_off_btn.Bind(wx.EVT_BUTTON, self.measurement_play_sound_handler)
124 sizer.Add(self.sound_on_off_btn, 0)
125 sizer.Add((12, 1), 1)
126 self.finish_btn = FlatShadedButton(
127 self.panel, label=lang.getstr("finish"), fgcolour=FGCOLOUR
128 )
129 self.finish_btn.Bind(wx.EVT_BUTTON, self.finish_btn_handler)
130 sizer.Add(self.finish_btn, 0, wx.RIGHT, border=8)
131 panelsizer.Add(sizer, 0, wx.BOTTOM | wx.EXPAND, border=8)
132
133 self.grid = CustomGrid(self, -1, size=(536, 256))
134 self.grid.DisableDragColSize()
135 self.grid.DisableDragRowSize()
136 self.grid.SetScrollRate(0, 5)
137 self.grid.SetCellHighlightROPenWidth(0)
138 self.grid.SetColLabelSize(self.grid.GetDefaultRowSize())
139 self.grid.SetDefaultCellAlignment(wx.ALIGN_CENTER, wx.ALIGN_CENTER)
140 self.grid.SetRowLabelAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
141 self.grid.draw_horizontal_grid_lines = False
142 self.grid.draw_vertical_grid_lines = False
143 self.grid.style = ""
144 self.grid.CreateGrid(0, 9)
145 self.grid.SetRowLabelSize(62)
146 for i in range(9):
147 if i in (3, 4):
148 size = self.grid.GetDefaultRowSize()
149 if i == 4:
150 attr = wx.grid.GridCellAttr()
151 attr.SetBackgroundColour(wx.Colour(0, 0, 0, 0))
152 self.grid.SetColAttr(i, attr)
153 else:
154 size = 62
155 self.grid.SetColSize(i, size)
156 for i, label in enumerate(["R", "G", "B", "", "", "L*", "a*", "b*", ""]):
157 self.grid.SetColLabelValue(i, label)
158 self.grid.SetCellHighlightPenWidth(0)
159 self.grid.SetDefaultCellBackgroundColour(self.grid.GetLabelBackgroundColour())
160 font = self.grid.GetDefaultCellFont()
161 if font.PointSize > 11:
162 font.PointSize = 11
163 self.grid.SetDefaultCellFont(font)
164 self.grid.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
165 self.grid.EnableEditing(False)
166 self.grid.EnableGridLines(False)
167 self.grid.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.grid_left_click_handler)
168 self.grid.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.grid_left_click_handler)
169 self.sizer.Add(self.grid, 1, wx.EXPAND)
170
171 self.Fit()
172 self.SetMinSize(self.GetSize())
173
174 self.keyhandler = keyhandler
175 self.id_to_keycode = {}
176 if sys.platform == "darwin":
177 # Use an accelerator table for tab, space, 0-9, A-Z, numpad,
178 # navigation keys and processing keys
179 keycodes = [wx.WXK_TAB, wx.WXK_SPACE]
180 keycodes.extend(list(range(ord("0"), ord("9"))))
181 keycodes.extend(list(range(ord("A"), ord("Z"))))
182 keycodes.extend(NUMPAD_KEYCODES)
183 keycodes.extend(NAV_KEYCODES)
184 keycodes.extend(PROCESSING_KEYCODES)
185 for keycode in keycodes:
186 self.id_to_keycode[wx.Window.NewControlId()] = keycode
187 accels = []
188 for id_ in self.id_to_keycode:
189 keycode = self.id_to_keycode[id_]
190 self.Bind(wx.EVT_MENU, self.key_handler, id=id_)
191 accels.append((wx.ACCEL_NORMAL, keycode, id_))
192 if keycode == wx.WXK_TAB:
193 accels.append((wx.ACCEL_SHIFT, keycode, id_))
194 self.SetAcceleratorTable(wx.AcceleratorTable(accels))
195 else:
196 self.Bind(wx.EVT_CHAR_HOOK, self.key_handler)
197
198 self.Bind(wx.EVT_KEY_DOWN, self.key_handler)
199
200 # Event handlers
201 self.Bind(wx.EVT_CLOSE, self.OnClose, self)
202 self.Bind(wx.EVT_MOVE, self.OnMove, self)
203 self.Bind(wx.EVT_SIZE, self.OnResize, self)
204 self.timer = wx.Timer(self)
205 if handler:
206 self.Bind(wx.EVT_TIMER, handler, self.timer)
207 self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)
208
209 # Final initialization steps
210 for child in list(self.GetAllChildren()):
211 if (
212 sys.platform == "win32"
213 and sys.getwindowsversion() >= (6,)
214 and isinstance(child, wx.Panel)
215 ):
216 # No need to enable double buffering under Linux and Mac OS X.
217 # Under Windows, enabling double buffering on the panel seems
218 # to work best to reduce flicker.
219 child.SetDoubleBuffered(True)
220 self.logger = get_file_logger("untethered")
221 self._setup()
222
223 self.Show()
224
225 if start_timer:
226 self.start_timer()
227
228 def EndModal(self, returncode=wx.ID_OK):
229 """End the untethered frame modal state.
230
231 Args:
232 returncode (int): The return code to indicate the result of the
233 operation.
234 """
235 return returncode
236
237 def MakeModal(self, modal=False):
238 """Make the untethered frame modal or not.
239
240 Args:
241 modal (bool): Whether to make the untethered frame modal.
242 """
243
244 def OnClose(self, event):
245 """Handle the close event to stop the timer and save configuration.
246
247 Args:
248 event (wx.Event): The event that triggered the action.
249 """
250 config.writecfg()
251 if not self.timer.IsRunning():
252 self.Destroy()
253 else:
254 self.keepGoing = False
255
256 def OnDestroy(self, event):
257 """Handle the destruction of the untethered frame.
258
259 Args:
260 event (wx.Event): The event that triggered the action.
261
262 Returns:
263 int: Return code indicating the success of the operation.
264 """
265 self.stop_timer()
266 del self.timer
267 if not hasattr(wx.Window, "UnreserveControlId"):
268 return 0
269
270 for id_ in self.id_to_keycode:
271 if id_ >= 0:
272 continue
273 try:
274 wx.Window.UnreserveControlId(id_)
275 except wx.wxAssertionError as exception:
276 print(exception)
277
278 return 0
279
280 def OnMove(self, event):
281 """Handle the move event to save the position of the untethered frame.
282
283 Args:
284 event (wx.Event): The event that triggered the action.
285 """
286 if (
287 self.IsShownOnScreen()
288 and not self.IsIconized()
289 and (not self.GetParent() or not self.GetParent().IsShownOnScreen())
290 ):
291 prev_x = getcfg("position.progress.x")
292 prev_y = getcfg("position.progress.y")
293 x, y = self.GetScreenPosition()
294 if x != prev_x or y != prev_y:
295 setcfg("position.progress.x", x)
296 setcfg("position.progress.y", y)
297
298 def OnResize(self, event):
299 """Handle the resize event to adjust the grid size.
300
301 Args:
302 event (wx.Event): The event that triggered the action.
303 """
304 wx.CallAfter(self.resize_grid)
305 event.Skip()
306
307 def Pulse(self, msg=""):
308 """Pulse the untethered frame with a message.
309
310 Args:
311 msg (str): The message to display in the pulse.
312
313 Returns:
314 tuple: A tuple containing a boolean indicating whether to keep going
315 """
316 self.label_RGB.SetLabel(msg)
317 if msg == lang.getstr("instrument.initializing"):
318 self.label_RGB.SetLabel(msg)
319 return self.keepGoing, False
320
321 def Resume(self):
322 """Resume the untethered frame after a pause."""
323 self.keepGoing = True
324 self.set_sound_on_off_btn_bitmap()
325
326 def UpdateProgress(self, value, msg=""):
327 """Update the progress with a value and a message.
328
329 Args:
330 value (int): The value to display in the progress bar.
331 msg (str): The message to display in the progress bar.
332
333 Returns:
334 tuple: A tuple containing a boolean indicating whether to keep going
335 """
336 return self.Pulse(msg)
337
338 def UpdatePulse(self, msg=""):
339 """Update the pulse with a message.
340
341 Args:
342 msg (str): The message to display in the pulse.
343
344 Returns:
345 tuple: A tuple containing a boolean indicating whether to keep going
346 """
347 return self.Pulse(msg)
348
349 def back_btn_handler(self, event):
350 """Handle the back button click event.
351
352 Args:
353 event (wx.Event): The event that triggered the action, if any.
354 """
355 if self.index > 0:
356 self.update(self.index - 1)
357
358 def enable_btns(self, enable=True, enable_measure_button=False):
359 """Enable or disable buttons based on the measurement state.
360
361 Args:
362 enable (bool): Whether to enable the buttons.
363 enable_measure_button (bool): Whether to enable the measure button.
364 """
365 self.is_measuring = not enable and enable_measure_button
366 self.back_btn.Enable(enable and self.index > 0)
367 self.next_btn.Enable(enable and self.index < self.index_max)
368 self.measure_btn._bitmap = get_icon(
369 10, {True: "play", False: "pause"}.get(enable)
370 )
371 self.measure_btn.Enable(enable or enable_measure_button)
372 self.measure_btn.SetDefault()
373 if self.measure_btn.Enabled and not isinstance(
374 self.FindFocus(), (wx.Control, CustomGrid)
375 ):
376 self.measure_btn.SetFocus()
377
378 def finish_btn_handler(self, event):
379 """Handle the finish button click event.
380
381 Args:
382 event (wx.Event): The event that triggered the action, if any.
383 """
384 self.finish_btn.Disable()
385 self.cgats[0].type = b"CTI3"
386 self.cgats[0].add_keyword("COLOR_REP", "RGB_XYZ")
387 if self.white_XYZ[1] > 0:
388 # Normalize to Y = 100
389 query = self.cgats[0].DATA
390 for i in query:
391 XYZ = query[i]["XYZ_X"], query[i]["XYZ_Y"], query[i]["XYZ_Z"]
392 XYZ = [v / self.white_XYZ[1] * 100 for v in XYZ]
393 query[i]["XYZ_X"], query[i]["XYZ_Y"], query[i]["XYZ_Z"] = XYZ
394 normalized = "YES"
395 else:
396 normalized = "NO"
397 self.cgats[0].add_keyword("NORMALIZED_TO_Y_100", normalized)
398 self.cgats[0].add_keyword("DEVICE_CLASS", "DISPLAY")
399 self.cgats[0].add_keyword("INSTRUMENT_TYPE_SPECTRAL", "NO")
400 if hasattr(self.cgats[0], "APPROX_WHITE_POINT"):
401 self.cgats[0].remove_keyword("APPROX_WHITE_POINT")
402 # Remove L*a*b* from DATA_FORMAT if present
403 for i, label in reversed(list(self.cgats[0].DATA_FORMAT.items())):
404 if label.startswith(b"LAB_"):
405 self.cgats[0].DATA_FORMAT.pop(i)
406 # Add XYZ to DATA_FORMAT if not yet present
407 for label in (b"XYZ_X", b"XYZ_Y", b"XYZ_Z"):
408 if label not in list(self.cgats[0].DATA_FORMAT.values()):
409 self.cgats[0].DATA_FORMAT.add_data((label,))
410 self.cgats[0].write(os.path.splitext(self.cgats.filename)[0] + ".ti3")
411 self.safe_send("Q")
412 time.sleep(0.5)
413 self.safe_send("Q")
414
415 def flush(self):
416 """Flush the worker subprocess output."""
417
418 def get_Lab_RGB(self):
419 """Calculate the Lab and RGB values for the current patch.
420
421 Returns:
422 tuple: A tuple containing the Lab and RGB values for the current patch.
423 """
424 row = self.cgats[0].DATA[self.index]
425 XYZ = row["XYZ_X"], row["XYZ_Y"], row["XYZ_Z"]
426 self.last_XYZ = XYZ
427 Lab = colormath.XYZ2Lab(*XYZ)
428 if self.white_XYZ[1] > 0:
429 XYZ = [v / self.white_XYZ[1] * 100 for v in XYZ]
430 white_XYZ_Y100 = [v / self.white_XYZ[1] * 100 for v in self.white_XYZ]
431 white_CCT = colormath.XYZ2CCT(*white_XYZ_Y100)
432 if white_CCT:
433 DXYZ = colormath.CIEDCCT2XYZ(white_CCT, scale=100.0)
434 if DXYZ:
435 white_CIEDCCT_Lab = colormath.XYZ2Lab(*DXYZ)
436 PXYZ = colormath.planckianCT2XYZ(white_CCT, scale=100.0)
437 if PXYZ:
438 white_planckianCCT_Lab = colormath.XYZ2Lab(*PXYZ)
439 white_Lab = colormath.XYZ2Lab(*white_XYZ_Y100)
440 if (
441 DXYZ
442 and PXYZ
443 and (
444 colormath.delta(*white_CIEDCCT_Lab + white_Lab)["E"] < 6
445 or colormath.delta(*white_planckianCCT_Lab + white_Lab)["E"] < 6
446 )
447 ):
448 # Is white close enough to daylight or planckian locus?
449 XYZ = colormath.adapt(XYZ[0], XYZ[1], XYZ[2], white_XYZ_Y100, "D65")
450 X, Y, Z = [v / 100.0 for v in XYZ]
451 color = [round(v) for v in colormath.XYZ2RGB(X, Y, Z, scale=255)]
452 return Lab, color
453
454 def grid_left_click_handler(self, event):
455 """Handle left click events on the grid.
456
457 Args:
458 event (wx.grid.GridEvent): The event that triggered the action.
459 """
460 if not self.is_measuring:
461 row, col = event.GetRow(), event.GetCol()
462 if row == -1 and col > -1: # col label clicked
463 pass
464 elif row > -1: # row clicked
465 if not (event.CmdDown() or event.ControlDown() or event.ShiftDown()):
466 self.update(row)
467 event.Skip()
468
469 def has_worker_subprocess(self):
470 """Check if the untethered frame has a worker subprocess.
471
472 Returns:
473 bool: True if the frame has a worker subprocess, False otherwise.
474 """
475 return bool(
476 getattr(self, "worker", None) and getattr(self.worker, "subprocess", None)
477 )
478
479 def isatty(self):
480 """Check if the untethered frame is interactive.
481
482 Returns:
483 bool: True if the frame is interactive, False otherwise.
484 """
485 return True
486
487 def key_handler(self, event):
488 """Handle key events for navigation and measurement control.
489
490 Args:
491 event (wx.KeyEvent): The event that triggered the action.
492 """
493 keycode = None
494 is_key_event = event.GetEventType() in (
495 wx.EVT_CHAR.typeId,
496 wx.EVT_CHAR_HOOK.typeId,
497 wx.EVT_KEY_DOWN.typeId,
498 )
499 if is_key_event:
500 keycode = event.GetKeyCode()
501 elif event.GetEventType() == wx.EVT_MENU.typeId:
502 keycode = self.id_to_keycode.get(event.GetId())
503 if keycode == wx.WXK_TAB:
504 self.global_navigate() or event.Skip()
505 elif keycode >= 0:
506 if keycode in (wx.WXK_UP, wx.WXK_NUMPAD_UP):
507 self.back_btn_handler(None)
508 elif keycode in (wx.WXK_DOWN, wx.WXK_NUMPAD_DOWN):
509 self.next_btn_handler(None)
510 elif keycode in (wx.WXK_HOME, wx.WXK_NUMPAD_HOME):
511 if self.index > -1:
512 self.update(0)
513 elif keycode in (wx.WXK_END, wx.WXK_NUMPAD_END):
514 if self.index_max > -1:
515 self.update(self.index_max)
516 elif keycode in (wx.WXK_PAGEDOWN, wx.WXK_NUMPAD_PAGEDOWN):
517 if self.index > -1:
518 self.grid.MovePageDown()
519 self.update(self.grid.GetGridCursorRow())
520 elif keycode in (wx.WXK_PAGEUP, wx.WXK_NUMPAD_PAGEUP):
521 if self.index > -1:
522 self.grid.MovePageUp()
523 self.update(self.grid.GetGridCursorRow())
524 elif is_key_event and (event.ControlDown() or event.CmdDown()):
525 event.Skip()
526 elif self.has_worker_subprocess() and keycode < 256:
527 if keycode == wx.WXK_ESCAPE or chr(keycode) == "Q":
528 # ESC or Q
529 self.worker.abort_subprocess()
530 elif (
531 not isinstance(self.FindFocus(), wx.Control)
532 or keycode != wx.WXK_SPACE
533 ):
534 # Any other key
535 self.measure_btn_handler(None)
536 else:
537 event.Skip()
538 else:
539 event.Skip()
540 else:
541 event.Skip()
542
543 def measure(self, event=None):
544 """Start or stop the measurement process.
545
546 Args:
547 event (wx.Event): The event that triggered the action, if any.
548 """
549 self.enable_btns(False, True)
550 # Use a delay to allow for TFT lag
551 wx.CallLater(200, self.safe_send, " ")
552
553 def measure_auto_ctrl_handler(self, event):
554 """Handle the auto measurement checkbox change event.
555
556 Args:
557 event (wx.Event): The event that triggered the action, if any.
558 """
559 auto = self.measure_auto_cb.GetValue()
560 setcfg("untethered.measure.auto", int(auto))
561
562 def measure_btn_handler(self, event):
563 """Handle the measure button click event.
564
565 Args:
566 event (wx.Event): The event that triggered the action, if any.
567 """
568 if self.is_measuring:
569 self.is_measuring = False
570 else:
571 self.last_XYZ = (-1, -1, -1)
572 self.measure_count = 1
573 self.measure()
574
575 def measurement_play_sound_handler(self, event):
576 """Toggle the sound on/off setting and update the button bitmap.
577
578 Args:
579 event (wx.Event): The event that triggered the action, if any.
580 """
581 setcfg(
582 "measurement.play_sound", int(not (bool(getcfg("measurement.play_sound"))))
583 )
584 self.set_sound_on_off_btn_bitmap()
585
586 def get_sound_on_off_btn_bitmap(self):
587 """Get the bitmap for the sound on/off button based on the current setting.
588
589 Returns:
590 wx.Bitmap: The bitmap for the sound on/off button.
591 """
592 if getcfg("measurement.play_sound"):
593 bitmap = get_icon(16, "sound_volume_full")
594 else:
595 bitmap = get_icon(16, "sound_off")
596 return bitmap
597
598 def set_sound_on_off_btn_bitmap(self):
599 """Set the bitmap for the sound on/off button based on the current setting."""
600 bitmap = self.get_sound_on_off_btn_bitmap()
601 self.sound_on_off_btn._bitmap = bitmap
602
603 def next_btn_handler(self, event):
604 """Handle the next button click event.
605
606 Args:
607 event (wx.Event): The event that triggered the action, if any.
608 """
609 if self.index < self.index_max:
610 self.update(self.index + 1)
611
612 def parse_txt(self, txt):
613 """Parse the text output from the worker subprocess.
614
615 Args:
616 txt (str): The text output to parse.
617 """
618 if not txt:
619 return
620 self.logger.info(f"{txt!r}")
621 data_len = len(self.cgats[0].DATA)
622 if self.grid.GetNumberRows() < data_len:
623 self.index = 0
624 self.index_max = data_len - 1
625 self.grid.AppendRows(data_len - self.grid.GetNumberRows())
626 for i in self.cgats[0].DATA:
627 self.grid.SetRowLabelValue(i, f"{i + 1}")
628 row = self.cgats[0].DATA[i]
629 RGB = []
630 for j, label in enumerate("RGB"):
631 value = round(row[f"RGB_{label}"] / 100.0 * 255)
632 self.grid.SetCellValue(row.SAMPLE_ID - 1, j, f"{value}")
633 RGB.append(value)
634 self.grid.SetCellBackgroundColour(row.SAMPLE_ID - 1, 3, wx.Colour(*RGB))
635 if "Connecting to the instrument" in txt:
636 self.Pulse(lang.getstr("instrument.initializing"))
637 if "Spot read needs a calibration" in txt:
638 self.is_measuring = False
639 if "Spot read failed" in txt:
640 self.last_error = txt
641
642 # Result is XYZ: d.dddddd d.dddddd d.dddddd, D50 Lab: d.dddddd d.dddddd d.dddddd
643 if "Result is XYZ:" in txt:
644 self.last_error = None
645 if getcfg("measurement.play_sound"):
646 self.measurement_sound.safe_play()
647 XYZ = re.search(
648 r"XYZ:\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)", txt
649 )
650 if not XYZ:
651 return
652
653 def is_white(r):
654 return r["RGB_R"] == 100 and r["RGB_G"] == 100 and r["RGB_B"] == 100
655
656 XYZ = [float(v) for v in XYZ.groups()]
657 row = self.cgats[0].DATA[self.index]
658 if is_white(row) and XYZ[1] > 0:
659 self.cgats[0].add_keyword(
660 "LUMINANCE_XYZ_CDM2", "{:.6f} {:.6f} {:.6f}".format(*tuple(XYZ))
661 )
662 self.white_XYZ = XYZ
663 Lab1 = colormath.XYZ2Lab(*self.last_XYZ)
664 Lab2 = colormath.XYZ2Lab(*XYZ)
665 delta = colormath.delta(*Lab1 + Lab2)
666 if DEBUG or TEST or VERBOSE > 1:
667 print("Last recorded Lab: {:.4f} {:.4f} {:.4f}".format(*Lab1))
668 print("Current Lab: {:.4f} {:.4f} {:.4f}".format(*Lab2))
669 print(f"Delta E to last recorded Lab: {delta['E']:.4f}")
670 print(f"Abs. delta L to last recorded Lab: {abs(delta['L']):.4f}")
671 print(f"Abs. delta C to last recorded Lab: {abs(delta['C']):.4f}")
672 consecutive_white_patch = (
673 self.index
674 and is_white(row)
675 and is_white(self.cgats[0].DATA[self.index - 1])
676 )
677 measurement_exceeds_delta = delta["E"] > getcfg("untethered.min_delta") or (
678 abs(delta["L"]) > getcfg("untethered.min_delta.lightness")
679 and abs(delta["C"]) < getcfg("untethered.max_delta.chroma")
680 )
681 if consecutive_white_patch or measurement_exceeds_delta:
682 self.measure_count += 1
683 if self.measure_count == 2:
684 if getcfg("measurement.play_sound"):
685 self.commit_sound.safe_play()
686 self.measure_count = 0
687 # Reset row label
688 self.grid.SetRowLabelValue(self.index, f"{self.index + 1}")
689 # Update CGATS
690 query = self.cgats[0].queryi1(
691 {
692 "RGB_R": row["RGB_R"],
693 "RGB_G": row["RGB_G"],
694 "RGB_B": row["RGB_B"],
695 "SAMPLE_ID": row["SAMPLE_ID"],
696 }
697 )
698 if query:
699 index = query.SAMPLE_ID - 1
700 if index not in self.measured:
701 self.measured.append(index)
702 query["XYZ_X"], query["XYZ_Y"], query["XYZ_Z"] = XYZ
703 if getcfg("untethered.measure.auto"):
704 self.show_RGB(False, False)
705 self.show_XYZ()
706 Lab, color = self.get_Lab_RGB()
707 self.grid.SetCellBackgroundColour(
708 query.SAMPLE_ID - 1, 4, wx.Colour(*color)
709 )
710 for j in range(3):
711 self.grid.SetCellValue(
712 query.SAMPLE_ID - 1, 5 + j, f"{Lab[j]:.2f}"
713 )
714 self.grid.MakeCellVisible(self.index, 0)
715 self.grid.ForceRefresh()
716 if len(self.measured) == data_len:
717 self.finished = True
718 self.finish_btn.Enable()
719 else:
720 # Jump to the next or previous unmeasured patch, if any
721 index = self.index
722 for i in range(self.index + 1, data_len):
723 if (
724 getcfg("untethered.measure.auto")
725 or i not in self.measured
726 ):
727 self.index = i
728 break
729 if self.index == index:
730 for i in range(self.index - 1, -1, -1):
731 if i not in self.measured:
732 self.index = i
733 break
734 if self.index != index:
735 # Mark the row containing the next/previous patch
736 self.grid.SetRowLabelValue(
737 self.index, f"\u25ba {self.index + 1}"
738 )
739 self.grid.MakeCellVisible(self.index, 0)
740 if "key to take a reading" in txt and not self.last_error:
741 if getcfg("untethered.measure.auto") and self.is_measuring:
742 if not self.finished and self.keepGoing:
743 self.measure()
744 else:
745 self.enable_btns()
746 else:
747 show_XYZ = self.index in self.measured
748 delay = getcfg("untethered.measure.manual.delay") * 1000
749 wx.CallLater(delay, self.show_RGB, not show_XYZ)
750 if show_XYZ:
751 wx.CallLater(delay, self.show_XYZ)
752 wx.CallLater(delay, self.enable_btns)
753
754 def pause_continue_handler(self, event=None):
755 """Handle pause/continue action.
756
757 Args:
758 event: The event that triggered the action, if any.
759 """
760 if not event:
761 self.parse_txt(self.worker.lastmsg.read())
762
763 @property
764 def paused(self):
765 """Check if the untethered frame is paused.
766
767 Returns:
768 bool: True if the frame is paused, False otherwise.
769 """
770 return False
771
772 def reset(self):
773 """Reset the untethered frame to its initial state."""
774 self._setup()
775
776 def resize_grid(self):
777 """Resize the grid to fit the window."""
778 num_cols = self.grid.GetNumberCols()
779 if not num_cols:
780 return
781 grid_w = self.grid.GetSize()[0] - self.grid.GetDefaultRowSize() * 2
782 col_w = round(grid_w / (num_cols - 1))
783 last_col_w = grid_w - col_w * (num_cols - 2)
784 self.grid.SetRowLabelSize(col_w)
785 for i in range(num_cols):
786 if i in (3, 4):
787 w = self.grid.GetDefaultRowSize()
788 elif i == num_cols - 1:
789 w = last_col_w - wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X)
790 else:
791 w = col_w
792 self.grid.SetColSize(i, w)
793 self.grid.SetMargins(0 - wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X), 0)
794 self.grid.ForceRefresh()
795
796 def _setup(self):
797 """Initial setup of the untethered frame."""
798 self.logger.info("-" * 80)
799 self.is_measuring = False
800 self.keepGoing = True
801 self.last_error = None
802 self.index = -1
803 self.index_max = -1
804 self.last_XYZ = (-1, -1, -1)
805 self.white_XYZ = (-1, -1, -1)
806 self.measure_count = 0
807 self.measured = []
808 self.finished = False
809 self.label_RGB.SetLabel(" ")
810 self.label_XYZ.SetLabel(" ")
811 self.panel_RGB.SetBackgroundColour(BGCOLOUR)
812 self.panel_RGB.Refresh()
813 self.panel_RGB.Update()
814 self.panel_XYZ.SetBackgroundColour(BGCOLOUR)
815 self.panel_XYZ.Refresh()
816 self.panel_XYZ.Update()
817 self.label_index.SetLabel(" ")
818 self.enable_btns(False)
819 self.measure_auto_cb.SetValue(bool(getcfg("untethered.measure.auto")))
820 self.finish_btn.Disable()
821
822 if self.grid.GetNumberRows():
823 self.grid.DeleteRows(0, self.grid.GetNumberRows())
824
825 # Set position
826 x = getcfg("position.progress.x")
827 y = getcfg("position.progress.y")
828 self.SetSaneGeometry(x, y)
829
830 def safe_send(self, bytes_):
831 """Send bytes to the worker subprocess if it exists and is not aborted.
832
833 Args:
834 bytes_ (bytes): The bytes to send.
835 """
836 if self.has_worker_subprocess() and not self.worker.subprocess_abort:
837 self.worker.safe_send(bytes_)
838
839 def show_RGB(self, clear_XYZ=True, mark_current_row=True):
840 """Display the RGB values and color for the current patch.
841
842 Args:
843 clear_XYZ (bool): Whether to clear the XYZ display.
844 mark_current_row (bool): Whether to mark the current row in the
845 grid.
846 """
847 row = self.cgats[0].DATA[self.index]
848 self.label_RGB.SetLabel(
849 "RGB {} {} {}".format(
850 round(row["RGB_R"] / 100.0 * 255),
851 round(row["RGB_G"] / 100.0 * 255),
852 round(row["RGB_B"] / 100.0 * 255),
853 )
854 )
855 color = [
856 round(v / 100.0 * 255) for v in (row["RGB_R"], row["RGB_G"], row["RGB_B"])
857 ]
858 self.panel_RGB.SetBackgroundColour(wx.Colour(*color))
859 self.panel_RGB.SetBitmap(None)
860 self.panel_RGB.Refresh()
861 self.panel_RGB.Update()
862 if clear_XYZ:
863 self.label_XYZ.SetLabel(" ")
864 self.panel_XYZ.SetBackgroundColour(BGCOLOUR)
865 self.panel_XYZ.SetBitmap(get_bitmap("theme/checkerboard-32x32x5-333-444"))
866 self.panel_XYZ.Refresh()
867 self.panel_XYZ.Update()
868 if mark_current_row:
869 self.grid.SetRowLabelValue(self.index, f"\u25ba {self.index + 1}")
870 self.grid.MakeCellVisible(self.index, 0)
871 if self.index not in self.grid.GetSelectedRows():
872 self.grid.SelectRow(self.index)
873 self.grid.SetGridCursor(self.index, 0)
874 self.label_index.SetLabel(f"{self.index + 1}/{len(self.cgats[0].DATA)}")
875 self.label_index.GetContainingSizer().Layout()
876
877 def show_XYZ(self):
878 """Display the XYZ values and color for the current patch."""
879 Lab, color = self.get_Lab_RGB()
880 self.label_XYZ.SetLabel("L*a*b* {:.2f} {:.2f} {:.2f}".format(*Lab))
881 self.panel_XYZ.SetBackgroundColour(wx.Colour(*color))
882 self.panel_XYZ.SetBitmap(None)
883 self.panel_XYZ.Refresh()
884 self.panel_XYZ.Update()
885
886 def start_timer(self, ms=50):
887 """Start the timer with the given interval in milliseconds.
888
889 Args:
890 ms (int): The interval in milliseconds to trigger the timer.
891 """
892 self.timer.Start(ms)
893
894 def stop_timer(self):
895 """Stop the timer."""
896 self.timer.Stop()
897
898 def update(self, index):
899 """Update the display with the given index.
900
901 Args:
902 index (int): The index of the patch to update.
903 """
904 # Reset row label
905 self.grid.SetRowLabelValue(self.index, f"{self.index + 1}")
906
907 self.index = index
908 show_XYZ = self.index in self.measured
909 self.show_RGB(not show_XYZ)
910 if show_XYZ:
911 self.show_XYZ()
912 self.enable_btns()
913
914 def write(self, txt):
915 """Write text to the untethered frame.
916
917 Args:
918 txt (str): The text to write.
919 """
920 wx.CallAfter(self.parse_txt, txt)