Debian Codegraph @

DisplayCAL/wx_measure_frame.py

raw
1 """Graphical interface for setting the measurement area in DisplayCAL.
2
3 It includes functionality for resizing, centering, and zooming the measurement
4 frame, as well as handling display geometry and configurations. The module
5 integrates with wxPython for user interaction and supports various display
6 environments.
7 """
8
9 import math
10 import os
11 import sys
12 import time
13 import warnings
14
15 from DisplayCAL import config
16 from DisplayCAL import localization as lang
17 from DisplayCAL.config import (
18 DEFAULTS,
19 SCALE_ADJUSTMENT_FACTOR,
20 get_argyll_display_number,
21 get_default_dpi,
22 get_display_number,
23 get_display_rects,
24 get_icon,
25 getcfg,
26 setcfg,
27 writecfg,
28 )
29 from DisplayCAL.debughelpers import handle_error
30 from DisplayCAL.meta import NAME as APPNAME
31 from DisplayCAL.options import DEBUG
32 from DisplayCAL.util_list import floatlist, strlist
33 from DisplayCAL.wx_addons import wx
34 from DisplayCAL.wx_fixes import GenBitmapButton as BitmapButton
35 from DisplayCAL.wx_windows import (
36 BaseApp,
37 BitmapBackgroundPanel,
38 ConfirmDialog,
39 InfoDialog,
40 InvincibleFrame,
41 )
42
43 try:
44 from DisplayCAL import real_display_size_mm
45 except ImportError as exception:
46 real_display_size_mm = None
47 warnings.warn(str(exception), Warning, stacklevel=2)
48
49
50 def get_default_size():
51 """Get and return the default size for the window in pixels.
52
53 The default size is always equivalent to 100 x 100 mm according
54 to the display's size as returned by the real_display_size_mm() function,
55 which uses the same code as Argyll to determine that size.
56
57 This function is used internally.
58 """
59 display_sizes = []
60 display_sizes_mm = []
61 for display_no in range(len(getcfg("displays"))):
62 display_no = get_display_number(display_no)
63 display_size = wx.Display(display_no).Geometry[2:]
64 display_size_mm = []
65 if real_display_size_mm:
66 try:
67 display_size_mm = real_display_size_mm.real_display_size_mm(display_no)
68 except Exception as exception:
69 handle_error(
70 f"Error - real_display_size_mm() failed: {exception}", silent=True
71 )
72 else:
73 display_size_mm = floatlist(display_size_mm)
74 if DEBUG:
75 print("[D] display_size_mm:", display_size_mm)
76 if not len(display_size_mm) or 0 in display_size_mm:
77 ppi_def = get_default_dpi()
78 method = 1
79 if method == 0:
80 # use configurable screen diagonal
81 inch = 20.0
82 mm = inch * 25.4
83 f = mm / math.sqrt(
84 math.pow(display_size[0], 2) + math.pow(display_size[1], 2)
85 )
86 w_mm = math.sqrt(math.pow(mm, 2) - math.pow(display_size[1] * f, 2))
87 h_mm = math.sqrt(math.pow(mm, 2) - math.pow(display_size[0] * f, 2))
88 display_size_mm = w_mm, h_mm
89 elif method == 1:
90 # use the first display
91 display_size_1st = wx.DisplaySize()
92 display_size_mm = floatlist(wx.DisplaySizeMM())
93 if 0 in display_size_mm:
94 # bogus
95 display_size_mm = [
96 float(display_size_1st[0]) / ppi_def * 25.4,
97 float(display_size_1st[1]) / ppi_def * 25.4,
98 ]
99 if display_no > 0:
100 display_size_mm[0] = float(display_size[0]) / (
101 display_size_1st[0] / display_size_mm[0]
102 )
103 display_size_mm[1] = float(display_size[1]) / (
104 display_size_1st[1] / display_size_mm[1]
105 )
106 else:
107 # use assumed ppi
108 display_size_mm = (
109 float(display_size[0]) / ppi_def * 25.4,
110 float(display_size[1]) / ppi_def * 25.4,
111 )
112 display_sizes.append(display_size)
113 display_sizes_mm.append(display_size_mm)
114 if (
115 sum(mm[0] for mm in display_sizes_mm) / len(display_sizes_mm)
116 == display_sizes_mm[0][0]
117 and sum(mm[1] for mm in display_sizes_mm) / len(display_sizes_mm)
118 == display_sizes_mm[0][1]
119 ):
120 # display_size_mm is the same for all screens, use the 1st one
121 display_size = display_sizes[0]
122 display_size_mm = display_sizes_mm[0]
123 else:
124 if getcfg("display_lut.link"):
125 display_no = getcfg("display.number") - 1
126 else:
127 display_no = getcfg("display_lut.number") - 1
128 display_size = display_sizes[display_no]
129 display_size_mm = display_sizes_mm[display_no]
130 px_per_mm = (
131 display_size[0] / display_size_mm[0],
132 display_size[1] / display_size_mm[1],
133 )
134 if DEBUG:
135 print("[D] H px_per_mm:", px_per_mm[0])
136 print("[D] V px_per_mm:", px_per_mm[1])
137 return round(100.0 * max(px_per_mm))
138
139
140 class MeasureFrame(InvincibleFrame):
141 """A rectangular window to set the measure area size for dispcal/dispread."""
142
143 exitcode = 1
144
145 def __init__(self, parent=None, id=-1): # noqa: A002
146 style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)
147 if os.getenv("XDG_SESSION_TYPE") != "wayland" and getcfg(
148 "patterngenerator.use_pattern_window"
149 ):
150 style |= wx.STAY_ON_TOP
151 InvincibleFrame.__init__(
152 self,
153 parent,
154 id,
155 lang.getstr("measureframe.title"),
156 style=style,
157 name="measureframe",
158 )
159 self.SetIcons(config.get_icon_bundle([256, 48, 32, 16], APPNAME))
160 self.Bind(wx.EVT_CLOSE, self.close_handler, self)
161 if os.getenv("XDG_SESSION_TYPE") != "wayland":
162 self.Bind(wx.EVT_MOVE, self.move_handler, self)
163 self.Bind(wx.EVT_SHOW, self.show_handler)
164 self.Bind(wx.EVT_KILL_FOCUS, self.focus_lost_handler)
165 self.Bind(wx.EVT_SET_FOCUS, self.focus_handler)
166 self.panel = BitmapBackgroundPanel(self)
167 self.panel.scalebitmap = (False, False)
168
169 if os.getenv("XDG_SESSION_TYPE") == "wayland":
170 self.sizer = wx.FlexGridSizer(3, 1, 0, 0)
171 self.sizer.AddGrowableCol(0)
172 self.sizer.AddGrowableRow(1)
173 else:
174 self.sizer = wx.GridSizer(3, 1, 0, 0)
175 self.panel.SetSizer(self.sizer)
176
177 self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
178 self.sizer.Add(self.hsizer, flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_TOP)
179
180 self.zoommaxbutton = BitmapButton(
181 self.panel,
182 -1,
183 get_icon(16, "zoom-best-fit"),
184 style=wx.NO_BORDER,
185 name="zoommaxbutton",
186 )
187 self.zoommaxbutton.Bind(wx.EVT_KILL_FOCUS, self.focus_lost_handler)
188 self.Bind(wx.EVT_BUTTON, self.zoommax_handler, self.zoommaxbutton)
189 self.hsizer.Add(
190 self.zoommaxbutton,
191 flag=wx.ALIGN_CENTER | wx.LEFT | wx.TOP | wx.BOTTOM,
192 border=10,
193 )
194 self.zoommaxbutton.SetToolTipString(lang.getstr("measureframe.zoommax"))
195
196 self.hsizer.Add((8, 0))
197
198 self.zoominbutton = BitmapButton(
199 self.panel,
200 -1,
201 get_icon(16, "zoom-in"),
202 style=wx.NO_BORDER,
203 name="zoominbutton",
204 )
205 self.zoominbutton.Bind(wx.EVT_KILL_FOCUS, self.focus_lost_handler)
206 self.Bind(wx.EVT_BUTTON, self.zoomin_handler, self.zoominbutton)
207 self.hsizer.Add(
208 self.zoominbutton, flag=wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, border=10
209 )
210 self.zoominbutton.SetToolTipString(lang.getstr("measureframe.zoomin"))
211
212 self.hsizer.Add((8, 0))
213
214 self.zoomnormalbutton = BitmapButton(
215 self.panel,
216 -1,
217 get_icon(16, "zoom-original"),
218 style=wx.NO_BORDER,
219 name="zoomnormalbutton",
220 )
221 self.zoomnormalbutton.Bind(wx.EVT_KILL_FOCUS, self.focus_lost_handler)
222 self.Bind(wx.EVT_BUTTON, self.zoomnormal_handler, self.zoomnormalbutton)
223 self.hsizer.Add(
224 self.zoomnormalbutton, flag=wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, border=10
225 )
226 self.zoomnormalbutton.SetToolTipString(lang.getstr("measureframe.zoomnormal"))
227
228 self.hsizer.Add((8, 0))
229
230 self.zoomoutbutton = BitmapButton(
231 self.panel,
232 -1,
233 get_icon(16, "zoom-out"),
234 style=wx.NO_BORDER,
235 name="zoomoutbutton",
236 )
237 self.zoomoutbutton.Bind(wx.EVT_KILL_FOCUS, self.focus_lost_handler)
238 self.Bind(wx.EVT_BUTTON, self.zoomout_handler, self.zoomoutbutton)
239 self.hsizer.Add(
240 self.zoomoutbutton,
241 flag=wx.ALIGN_CENTER | wx.RIGHT | wx.TOP | wx.BOTTOM,
242 border=10,
243 )
244 self.zoomoutbutton.SetToolTipString(lang.getstr("measureframe.zoomout"))
245
246 if os.getenv("XDG_SESSION_TYPE") == "wayland":
247 # No manual centering under Wayland...
248 self.centermsg = wx.StaticText(
249 self.panel,
250 -1,
251 lang.getstr("measureframe.center.manual"),
252 style=wx.ALIGN_CENTER_HORIZONTAL,
253 )
254 self.centermsg.Wrap(self.hsizer.MinSize[0] - 20)
255 self.sizer.Add(
256 self.centermsg, flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT, border=10
257 )
258 else:
259 self.centerbutton = BitmapButton(
260 self.panel,
261 -1,
262 get_icon(16, "window-center"),
263 style=wx.NO_BORDER,
264 name="centerbutton",
265 )
266 self.centerbutton.Bind(wx.EVT_KILL_FOCUS, self.focus_lost_handler)
267 self.Bind(wx.EVT_BUTTON, self.center_handler, self.centerbutton)
268 self.sizer.Add(
269 self.centerbutton, flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT, border=10
270 )
271 self.centerbutton.SetToolTipString(lang.getstr("measureframe.center"))
272
273 self.vsizer = wx.BoxSizer(wx.VERTICAL)
274 self.sizer.Add(self.vsizer, flag=wx.ALIGN_BOTTOM | wx.ALIGN_CENTER_HORIZONTAL)
275
276 if os.getenv("XDG_SESSION_TYPE") != "wayland" or config.is_virtual_display():
277 self.measure_darken_background_cb = wx.CheckBox(
278 self.panel, -1, lang.getstr("measure.darken_background")
279 )
280 self.measure_darken_background_cb.SetValue(
281 bool(int(getcfg("measure.darken_background")))
282 )
283 self.measure_darken_background_cb.Bind(
284 wx.EVT_KILL_FOCUS, self.focus_lost_handler
285 )
286 self.Bind(
287 wx.EVT_CHECKBOX,
288 self.measure_darken_background_ctrl_handler,
289 id=self.measure_darken_background_cb.GetId(),
290 )
291 self.vsizer.Add(
292 self.measure_darken_background_cb,
293 flag=wx.ALIGN_CENTER_HORIZONTAL | wx.LEFT | wx.RIGHT,
294 border=10,
295 )
296 else:
297 self.vsizer.Add((10, 10))
298
299 self.measurebutton = wx.Button(
300 self.panel,
301 -1,
302 lang.getstr("measureframe.measurebutton"),
303 name="measurebutton",
304 )
305 self.measurebutton.Bind(wx.EVT_KILL_FOCUS, self.focus_lost_handler)
306 self.Bind(wx.EVT_BUTTON, self.measure_handler, self.measurebutton)
307 self.vsizer.Add(
308 self.measurebutton,
309 # flag=wx.ALIGN_BOTTOM | wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
310 flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
311 border=10,
312 )
313 self.measurebutton.SetMaxFontSize(11)
314 self.measurebutton.SetDefault()
315 self.last_focused = self.measurebutton
316
317 self.display_no = wx.Display.GetFromWindow(self)
318 self.display_rects = get_display_rects()
319
320 self.sizer.SetSizeHints(self)
321
322 def measure_darken_background_ctrl_handler(self, event):
323 """Handle the checkbox event for darkening the background during measurement.
324
325 Args:
326 event (wx.Event): The event object containing information about the
327 checkbox event.
328 """
329 if self.measure_darken_background_cb.GetValue() and getcfg(
330 "measure.darken_background.show_warning"
331 ):
332 dlg = ConfirmDialog(
333 self,
334 msg=lang.getstr("measure.darken_background.warning"),
335 ok=lang.getstr("ok"),
336 cancel=lang.getstr("cancel"),
337 bitmap=get_icon(32, "dialog-warning"),
338 )
339 chk = wx.CheckBox(dlg, -1, lang.getstr("dialog.do_not_show_again"))
340 dlg.Bind(
341 wx.EVT_CHECKBOX,
342 self.measure_darken_background_warning_handler,
343 id=chk.GetId(),
344 )
345 dlg.sizer3.Add(chk, flag=wx.TOP | wx.ALIGN_LEFT, border=12)
346 dlg.sizer0.SetSizeHints(dlg)
347 dlg.sizer0.Layout()
348 rslt = dlg.ShowModal()
349 if rslt == wx.ID_CANCEL:
350 self.measure_darken_background_cb.SetValue(False)
351 setcfg(
352 "measure.darken_background",
353 int(self.measure_darken_background_cb.GetValue()),
354 )
355
356 def measure_darken_background_warning_handler(self, event):
357 """Handle the warning checkbox event for darkening the background.
358
359 Args:
360 event (wx.Event): The event object containing information about the
361 checkbox event.
362 """
363 setcfg(
364 "measure.darken_background.show_warning",
365 int(not event.GetEventObject().GetValue()),
366 )
367
368 def info_handler(self, event):
369 """Handle the info button click event.
370
371 Args:
372 event (wx.Event): The event object containing information about the
373 info button click event.
374 """
375 InfoDialog(
376 self,
377 msg=lang.getstr("measureframe.info"),
378 ok=lang.getstr("ok"),
379 bitmap=get_icon(32, "dialog-information"),
380 log=False,
381 )
382
383 def measure_handler(self, event):
384 """Handle the measure button click event.
385
386 Args:
387 event (wx.Event): The event object containing information about the
388 measure button click event.
389 """
390 if self.Parent and hasattr(self.Parent, "call_pending_function"):
391 self.Parent.call_pending_function()
392 else:
393 MeasureFrame.exitcode = 255
394 self.Close()
395
396 def Show(self, show=True):
397 """Show or hide the measure frame.
398
399 Args:
400 show (bool, optional): If True, show the measure frame; if False,
401 hide it. Defaults to True.
402 """
403 if show:
404 self.show_controls()
405 if hasattr(self, "measure_darken_background_cb"):
406 self.measure_darken_background_cb.SetValue(
407 bool(int(getcfg("measure.darken_background")))
408 )
409 if self.Parent and hasattr(self.Parent, "display_ctrl"):
410 display_no = self.Parent.display_ctrl.GetSelection()
411 else:
412 display_no = getcfg("display.number") - 1
413 if display_no < 0 or display_no > wx.Display.GetCount() - 1:
414 display_no = 0
415 else:
416 display_no = get_display_number(display_no)
417 x, y = wx.Display(display_no).Geometry[:2]
418 self.SetPosition((x, y)) # place measure frame on correct display
419 self.place_n_zoom(*floatlist(getcfg("dimensions.measureframe").split(",")))
420 self.display_no = wx.Display.GetFromWindow(self)
421 elif self.IsShownOnScreen():
422 setcfg("dimensions.measureframe", self.get_dimensions())
423 if self.Parent and hasattr(self.Parent, "get_set_display"):
424 self.Parent.get_set_display()
425 if isinstance(self, wx.Dialog):
426 if show:
427 self.ShowModal()
428 elif self.IsModal():
429 self.EndModal(wx.ID_OK)
430 else:
431 wx.Dialog.Hide(self)
432 else:
433 wx.Frame.Show(self, show)
434
435 def Hide(self):
436 """Hide the measure frame and save its dimensions."""
437 self.Show(False)
438
439 def place_n_zoom(self, x=None, y=None, scale=None):
440 """Place and scale the window.
441
442 x, y and scale need to be in Argyll coordinates (0.0...1.0)
443 if given. Without arguments, they are read from the user
444 configuration.
445
446 Args:
447 x (float, optional): The horizontal position of the measure frame
448 relative to the display (0.0...1.0). Defaults to None.
449 y (float, optional): The vertical position of the measure frame
450 relative to the display (0.0...1.0). Defaults to None.
451 scale (float, optional): The scale factor for the measure frame
452 (0.0...50.0). Defaults to None.
453 """
454 if DEBUG:
455 print("[D] measureframe.place_n_zoom")
456 if None in (x, y, scale):
457 cur_x, cur_y, cur_scale = floatlist(self.get_dimensions().split(","))
458 if x is None:
459 x = cur_x
460 if y is None:
461 y = cur_y
462 if scale is None:
463 scale = cur_scale
464 scale = min(scale, 50.0) # Argyll max
465 if DEBUG:
466 print("[D] x:", x)
467 print("[D] y:", y)
468 print("[D] scale:", scale)
469 print("[D] scale_adjustment_factor:", SCALE_ADJUSTMENT_FACTOR)
470 scale /= float(SCALE_ADJUSTMENT_FACTOR)
471 if DEBUG:
472 print("[D] scale / scale_adjustment_factor:", scale)
473 display = self.get_display(getcfg("display.number") - 1)
474 display_client_rect = display[2]
475 display_client_size = display_client_rect[2:]
476 if DEBUG:
477 print("[D] display_client_rect:", display_client_rect)
478 print("[D] display_client_size:", display_client_size)
479 measureframe_min_size = [max(self.sizer.GetMinSize())] * 2
480 if DEBUG:
481 print("[D] measureframe_min_size:", measureframe_min_size)
482 default_measureframe_size = get_default_size()
483 DEFAULTS["size.measureframe"] = default_measureframe_size
484 size = [
485 min(display_client_size[0], default_measureframe_size * scale),
486 min(display_client_size[1], default_measureframe_size * scale),
487 ]
488 if measureframe_min_size[0] > size[0]:
489 size = measureframe_min_size
490 size[0] = min(size[0], display_client_size[0])
491 size[1] = min(size[1], display_client_size[1])
492 if max(size) >= max(display_client_size):
493 scale = 50
494 if DEBUG:
495 print("[D] measureframe_size:", size)
496 size[0] = size[1] = int(max(size))
497 # Save the size we're about to set (in wx.Display.Geometry coordinate units).
498 # get_dimensions() uses this to detect and correct for any mismatch between
499 # Display.Geometry and GetSize()/GetScreenPosition() on Windows with DPI scaling.
500 self._last_set_size = size[0]
501 if (
502 sys.platform not in ("darwin", "win32")
503 and os.getenv("XDG_SESSION_TYPE") != "wayland"
504 and not os.getenv("XDG_CURRENT_DESKTOP", "").startswith("KDE")
505 and hasattr(self, "MaxClientSize")
506 ):
507 self.SetMaxClientSize((-1, -1))
508 self.SetMinClientSize(size)
509 self.SetClientSize(size)
510 self.SetMaxClientSize(size)
511 else:
512 self.SetMaxSize((-1, -1))
513 self.SetMinSize(size)
514 self.SetSize(size)
515 self.SetMaxSize(size)
516 display_rect = display[1]
517 if DEBUG:
518 print("[D] display_rect:", display_rect)
519 display_size = display_rect[2:]
520 if DEBUG:
521 print("[D] display_size:", display_size)
522 if sys.platform in ("darwin", "win32"):
523 titlebar = 0 # size already includes window decorations
524 else:
525 titlebar = 25 # assume titlebar height of 25px
526 measureframe_pos = [
527 display_rect[0] + round((display_size[0] - size[0]) * x),
528 display_rect[1] + round((display_size[1] - size[1]) * y) - titlebar,
529 ]
530 measureframe_pos[0] = max(measureframe_pos[0], display_client_rect[0])
531 measureframe_pos[1] = max(measureframe_pos[1], display_client_rect[1])
532 if DEBUG:
533 print("[D] measureframe_pos:", measureframe_pos)
534 setcfg("dimensions.measureframe", ",".join(strlist((x, y, scale))))
535 self.SetPosition(measureframe_pos)
536
537 def zoomin_handler(self, event):
538 """Handle the zoom in event for the measure frame.
539
540 Args:
541 event (wx.Event): The event object containing information about
542 the zoom in event.
543 """
544 if DEBUG:
545 print("[D] measureframe_zoomin_handler")
546 # We can't use self.get_dimensions() here because if we are near
547 # fullscreen, next magnification step will be larger than normal
548 display_size = self.get_display()[1][2:]
549 default_measureframe_size = float(get_default_size())
550 size = floatlist(self.GetSize())
551 x, y = None, None
552 scale = (float(display_size[0]) / default_measureframe_size) / (
553 float(display_size[0]) / size[0]
554 ) + 0.125
555 self.place_n_zoom(
556 x,
557 y,
558 scale=scale,
559 )
560
561 def zoomout_handler(self, event):
562 """Handle the zoom out event for the measure frame.
563
564 Args:
565 event (wx.Event): The event object containing information about
566 the zoom out event.
567 """
568 if DEBUG:
569 print("[D] measureframe_zoomout_handler")
570 # We can't use self.get_dimensions() here because if we are
571 # fullscreen, scale will be 50, thus changes won't be visible quickly
572 display_size = self.get_display()[1][2:]
573 default_measureframe_size = float(get_default_size())
574 size = floatlist(self.GetSize())
575 x, y = None, None
576 scale = (float(display_size[0]) / default_measureframe_size) / (
577 float(display_size[0]) / size[0]
578 ) - 0.125
579 self.place_n_zoom(
580 x,
581 y,
582 scale=scale,
583 )
584
585 def zoomnormal_handler(self, event):
586 """Handle the zoom normal event for the measure frame.
587
588 Args:
589 event (wx.Event): The event object containing information about
590 the zoom normal event.
591 """
592 if DEBUG:
593 print("[D] measureframe_zoomnormal_handler")
594 x, y = None, None
595 scale = floatlist(DEFAULTS["dimensions.measureframe"].split(","))[2]
596 self.place_n_zoom(x, y, scale=scale)
597
598 def zoommax_handler(self, event):
599 """Handle the zoom max event for the measure frame.
600
601 Args:
602 event (wx.Event): The event object containing information about
603 the zoom max event.
604 """
605 if DEBUG:
606 print("[D] measureframe_zoommax_handler")
607 display_client_rect = self.get_display()[2]
608 if DEBUG:
609 print("[D] display_client_rect:", display_client_rect)
610 display_client_size = display_client_rect[2:]
611 if DEBUG:
612 print("[D] display_client_size:", display_client_size)
613 size = self.GetSize()
614 if DEBUG:
615 print(" size:", size)
616 if max(size) >= max(display_client_size) - 50:
617 dim = getcfg("dimensions.measureframe.unzoomed")
618 self.place_n_zoom(*floatlist(dim.split(",")))
619 else:
620 setcfg("dimensions.measureframe.unzoomed", self.get_dimensions())
621 self.place_n_zoom(x=0.5, y=0.5, scale=50.0)
622
623 def center_handler(self, event):
624 """Handle the center event for the measure frame.
625
626 Args:
627 event (wx.Event): The event object containing information about
628 the center event.
629 """
630 if DEBUG:
631 print("[D] measureframe_center_handler")
632 x, y = floatlist(DEFAULTS["dimensions.measureframe"].split(","))[:2]
633 self.place_n_zoom(x, y)
634
635 def close_handler(self, event):
636 """Handle the close event for the measure frame.
637
638 Args:
639 event (wx.CloseEvent): The event object containing information
640 about the close event.
641 """
642 if DEBUG:
643 print("[D] measureframe_close_handler")
644 if self.Parent:
645 if self.Parent.worker.is_working():
646 self.Parent.worker.abort_subprocess(confirm=True)
647 return
648 self.Hide()
649 self.Parent.Show()
650 if hasattr(self.Parent, "restore_measurement_mode"):
651 self.Parent.restore_measurement_mode()
652 if hasattr(self.Parent, "restore_testchart"):
653 self.Parent.restore_testchart()
654 else:
655 self.Hide()
656 writecfg()
657 self.Destroy()
658 if MeasureFrame.exitcode != 255:
659 MeasureFrame.exitcode = 0
660
661 def get_display(self, display_no=None):
662 """Return display number, geometry, and client area, handling multi-screen setups.
663
664 Args:
665 display_no (int, optional): The display number to get the geometry
666 for. If None, the current display is used.
667
668 Returns:
669 tuple: A tuple containing the display number, geometry (wx.Rect),
670 and client area (wx.Rect).
671 """ # noqa: E501
672 if wx.Display.GetCount() == 1 and len(self.display_rects) > 1:
673 # Separate X screens, TwinView or similar
674 display = wx.Display(0)
675 geometry = display.Geometry
676 union = wx.Rect()
677 xy = []
678 for rect in self.display_rects:
679 if rect[:2] in xy or rect[2:] == geometry[2:]:
680 # Overlapping x y coordinates or screen filling whole
681 # reported geometry, so assume separate X screens
682 union = None
683 break
684 xy.append(rect[:2])
685 union = union.Union(rect)
686 if union == geometry:
687 # Assume TwinView or similar where Argyll enumerates 1+n
688 # displays but wx only 'sees' one that is the union of them
689 framerect = self.Rect
690 if display_no is not None:
691 geometry = self.display_rects[display_no]
692 else:
693 display_no = 0
694 for i, coord in enumerate(framerect[:2]):
695 if coord < 0:
696 framerect[i] = 0
697 elif coord > geometry[i + 2]:
698 framerect[i] = geometry[i]
699 for i, display_rect in enumerate(self.display_rects):
700 if display_rect.Contains(framerect[:2]):
701 display_no = i
702 geometry = display_rect
703 break
704 elif display_no is None:
705 # Assume separate X screens
706 display_no = 0
707 client_rect = wx.Rect(*tuple(geometry)).Intersect(
708 display.GetRealClientArea()
709 )
710 else:
711 display_no = wx.Display.GetFromWindow(self)
712 display = self.GetDisplay()
713 geometry = display.Geometry
714 client_rect = display.GetRealClientArea()
715 return display_no, geometry, client_rect
716
717 def move_handler(self, event):
718 """Handle the move event for the measure frame.
719
720 Args:
721 event (wx.MoveEvent): The event object containing information
722 about the move event.
723 """
724 if not self.IsShownOnScreen():
725 return
726 display_no, geometry, client_area = self.get_display()
727 if display_no == self.display_no:
728 return
729 self.display_no = display_no
730 if config.is_virtual_display():
731 return
732 # Translate from wx display index to Argyll display index
733 n = get_argyll_display_number(geometry)
734 if n is not None:
735 # Save Argyll display index to configuration
736 setcfg("display.number", n + 1)
737
738 def focus_handler(self, event=None):
739 """Handle the focus event for the measure frame.
740
741 Args:
742 event (wx.FocusEvent, optional): The event object containing
743 information about the focus event. Defaults to None.
744 """
745 event.Skip()
746 if DEBUG:
747 print("SET_FOCUS", event.EventObject.Name)
748 if event.EventObject is self and getattr(self, "last_focused", None) not in (
749 None,
750 self,
751 ):
752 self.last_focused.SetFocus()
753 if DEBUG:
754 print(self.last_focused.Name + ".SetFocus()")
755
756 def focus_lost_handler(self, event):
757 """Handle the focus lost event for the measure frame.
758
759 Args:
760 event (wx.FocusEvent): The event object containing information
761 about the focus lost event.
762 """
763 event.Skip()
764 if DEBUG:
765 print("KILL_FOCUS", event.EventObject.Name)
766 if event.EventObject is not self:
767 self.last_focused = event.EventObject
768 if DEBUG and self.last_focused:
769 print("last_focused", self.last_focused.Name)
770
771 def show_handler(self, e):
772 """Handle the show event for the measure frame.
773
774 Args:
775 e (wx.ShowEvent): The event object containing information about the
776 show event.
777 """
778 e.Skip()
779 if getattr(e, "IsShown", getattr(e, "GetShow", bool))():
780 self.measurebutton.SetFocus()
781
782 def show_controls(self, show=True):
783 """Show or hide the controls in the measure frame.
784
785 Args:
786 show (bool): If True, show the controls; if False, hide them.
787 """
788 self.panel.Freeze()
789 for ctrl in self.panel.Children:
790 ctrl.Show(show)
791 if show:
792 self.panel.SetBitmap(None)
793 self.panel.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))
794 else:
795 self.panel.SetCursor(wx.StockCursor(wx.CURSOR_BLANK))
796 self.panel.Layout()
797 self.panel.Thaw()
798
799 def show_rgb(self, rgb):
800 """Show the RGB color in the measure frame.
801
802 The RGB values should be in the range 0.0...1.0.
803
804 Args:
805 rgb (tuple): A tuple of three floats representing the RGB color.
806
807 """
808 if getcfg("patterngenerator.use_video_levels"):
809 minv = 16
810 maxv = 235
811 else:
812 minv = 0
813 maxv = 255
814 rgb = tuple(minv + v * (maxv - minv) for v in rgb)
815 floor = tuple(math.floor(v) for v in rgb)
816 ceil = tuple(math.ceil(v) for v in rgb)
817 if floor != ceil:
818 # Dither using simple ordered pattern
819 print(
820 f"Dither 8 bit {rgb[0]:.6f} {rgb[1]:.6f} {rgb[2]:.6f} -> "
821 f"{floor[0]} {floor[1]} {floor[2]} | {ceil[0]} {ceil[1]} {ceil[2]}"
822 )
823 img = wx.EmptyImage(*self.ClientSize, clear=False)
824 buf = img.GetDataBuffer()
825 buflen = len(buf)
826 # Intervals in pixels per each R, G and B
827 intervals = tuple(
828 (buflen / (buflen * (rgb[i] - floor[i])) if rgb[i] - floor[i] else 0)
829 for i in range(3)
830 )
831 print("Intervals {:.6f} {:.6f} {:.6f}".format(*intervals))
832 floorbytes = tuple(chr(v) for v in floor)
833 ceilbytes = tuple(chr(v) for v in ceil)
834 n = 0
835 # XXX: Generating the dithered image can take nontrivial amounts
836 # of time if the image is large
837 ts = time.time()
838 for i, _byte in enumerate(buf):
839 m = intervals[i % 3]
840 color = ceilbytes if m and n % m < 1 else floorbytes
841 buf[i] = color[i % 3]
842 if i % 3 == 2:
843 n += 1
844 print("Generating dithered image took %.3fs" % (time.time() - ts))
845 bmp = img.ConvertToBitmap()
846 else:
847 # Exact
848 print("Exact 8 bit {:.6f} {:.6f} {:.6f}".format(*rgb))
849 bmp = wx.EmptyBitmapRGBA(*tuple(self.ClientSize) + floor, alpha=255)
850 self.panel.SetBitmap(bmp)
851 self.panel.Refresh()
852 if self.Parent:
853 self.Parent.worker._patterngenerator_wait = False
854
855 def get_dimensions(self):
856 """Calculate and return the relative dimensions from the pixel values.
857
858 Returns x, y and scale in Argyll coordinates (0.0...1.0).
859 """
860 if DEBUG:
861 print("[D] measureframe.get_dimensions")
862 display = self.get_display()
863 display_rect = display[1]
864 display_size = display_rect[2:]
865 display_client_rect = display[2]
866 display_client_size = display_client_rect[2:]
867 if DEBUG:
868 print("[D] display_size:", display_size)
869 print("[D] display_client_size:", display_client_size)
870 default_measureframe_size = float(get_default_size())
871 if DEBUG:
872 print("[D] default_measureframe_size:", default_measureframe_size)
873 measureframe_pos = floatlist(self.GetScreenPosition())
874 measureframe_pos[0] -= display_rect[0]
875 measureframe_pos[1] -= display_rect[1]
876 if DEBUG:
877 print("[D] measureframe_pos:", measureframe_pos)
878 size = floatlist(self.GetSize())
879 if DEBUG:
880 print(" size:", size)
881 # On Windows with certain wxPython versions, wx.Display.Geometry returns
882 # DIP (logical) pixels while GetSize()/GetScreenPosition() return physical
883 # pixels. This causes the computed x, y fractions to be wrong (e.g. the
884 # window at the display center maps to x=1.0 instead of x=0.5 at 175% DPI).
885 # Detect this by comparing GetSize() against the size we passed to SetSize()
886 # during place_n_zoom() - both should be in the same coordinate system as
887 # Display.Geometry. If they differ, apply the ratio as a correction factor.
888 last_set_size = getattr(self, "_last_set_size", None)
889 if last_set_size and size[0] and abs(size[0] - last_set_size) > 1:
890 coord_scale = last_set_size / size[0]
891 measureframe_pos = [p * coord_scale for p in measureframe_pos]
892 size = [s * coord_scale for s in size]
893 if DEBUG:
894 print(
895 f"[D] coord_scale {coord_scale:.4f} applied "
896 f"(last_set_size={last_set_size}, GetSize={size[0] / coord_scale:.0f})"
897 )
898 if max(size) >= max(display_client_size) - 50:
899 # Fullscreen?
900 scale = 50.0 # Argyll max is 50
901 measureframe_pos = [0.5, 0.5]
902 else:
903 scale = (float(display_size[0]) / default_measureframe_size) / (
904 float(display_size[0]) / size[0]
905 )
906 if DEBUG:
907 print("[D] scale:", scale)
908 print("[D] scale_adjustment_factor:", SCALE_ADJUSTMENT_FACTOR)
909 scale *= float(SCALE_ADJUSTMENT_FACTOR)
910 if size[0] >= display_client_size[0]:
911 measureframe_pos[0] = 0.5
912 elif measureframe_pos[0] != 0:
913 measureframe_pos[0] = min(
914 measureframe_pos[0], display_size[0] - size[0]
915 )
916 measureframe_pos[0] = 1.0 / (
917 (float(display_size[0]) - size[0]) / (measureframe_pos[0])
918 )
919 if size[1] >= display_client_size[1]:
920 measureframe_pos[1] = 0.5
921 elif measureframe_pos[1] != 0:
922 measureframe_pos[1] = min(
923 measureframe_pos[1], display_size[1] - size[1]
924 )
925 if sys.platform in ("darwin", "win32"):
926 titlebar = 0 # size already includes window decorations
927 else:
928 titlebar = 25 # assume titlebar height of 25px
929 measureframe_pos[1] = 1.0 / (
930 (float(display_size[1] - size[1]))
931 / (float(measureframe_pos[1] + titlebar))
932 )
933 if DEBUG:
934 print("[D] scale:", scale)
935 if DEBUG:
936 print("[D] measureframe_pos:", measureframe_pos)
937 measureframe_dimensions = ",".join(
938 str(max(0, n)) for n in [*measureframe_pos, scale]
939 )
940 if DEBUG:
941 print("[D] measureframe_dimensions:", measureframe_dimensions)
942 return measureframe_dimensions
943
944
945 def main():
946 """Main function to run the wxPython application."""
947 config.initcfg()
948 lang.init()
949 app = BaseApp(0)
950 app.TopWindow = MeasureFrame()
951 app.TopWindow.Show()
952 if "--test-dither" in sys.argv[1:]:
953 print("Testing thourhg the `--test-dither` argument is not supported.")
954 app.MainLoop()
955
956
957 if __name__ == "__main__":
958 main()
959 sys.exit(MeasureFrame.exitcode)