Debian Codegraph @

DisplayCAL/wx_visual_whitepoint_editor.py

raw
1 """Visual whitepoint editor.
2
3 Based on wx.lib.agw.cubecolourdialog 0.4 by Andrea Gavana @ 26 Feb 2012
4
5 License: wxPython license
6 """
7
8 from __future__ import annotations
9
10 import colorsys
11 import os
12 import platform
13 import re
14 import sys
15 import threading
16 from math import atan2, cos, pi, sin, sqrt
17 from time import sleep
18 from typing import Any, ClassVar
19
20 from wx.lib.agw import aui
21 from wx.lib.intctrl import IntCtrl
22
23 from DisplayCAL import localization as lang
24 from DisplayCAL.config import (
25 DEFAULTS,
26 FS_ENC,
27 PROFILE_EXT,
28 get_argyll_display_number,
29 get_bitmap,
30 get_default_dpi,
31 get_display_name,
32 get_icon,
33 get_icon_bundle,
34 getcfg,
35 initcfg,
36 setcfg,
37 )
38 from DisplayCAL.icc_profile import (
39 ICCProfile,
40 ICCProfileInvalidError,
41 VideoCardGammaType,
42 WcsProfilesTagType,
43 get_display_profile,
44 )
45 from DisplayCAL.meta import NAME as APPNAME
46 from DisplayCAL.util_list import intlist
47 from DisplayCAL.util_str import safe_asciize, wrap
48 from DisplayCAL.worker import (
49 Error,
50 UnloggedError,
51 Warn,
52 Worker,
53 get_argyll_util,
54 show_result_dialog,
55 )
56 from DisplayCAL.wx_fixes import (
57 GenBitmapButton as BitmapButton,
58 )
59 from DisplayCAL.wx_fixes import (
60 get_bitmap_disabled,
61 get_bitmap_hover,
62 get_bitmap_pressed,
63 wx,
64 wx_Panel,
65 )
66 from DisplayCAL.wx_windows import (
67 FlatShadedButton,
68 HStretchStaticBitmap,
69 TaskBarNotification,
70 )
71
72 try:
73 from DisplayCAL import real_display_size_mm
74 except ImportError:
75 real_display_size_mm = None
76
77 # Use non-native mini frames on all platforms
78 aui.framemanager.AuiManager_UseNativeMiniframes = lambda manager: (
79 (manager.GetAGWFlags() & aui.AUI_MGR_USE_NATIVE_MINIFRAMES)
80 == aui.AUI_MGR_USE_NATIVE_MINIFRAMES
81 )
82
83 COLOUR_ATTRIBUTES = ["r", "g", "b", "h", "s", "v"]
84 COLOUR_MAX_VALUES = [255, 255, 255, 359, 255, 255]
85
86
87 def rad2deg(x: float) -> float:
88 """Transform radians into degrees.
89
90 Args:
91 x (float): a float representing an angle in radians.
92
93 Returns:
94 float: The angle in degrees.
95 """
96 return 180.0 * x / pi
97
98
99 def deg2rad(x: float) -> float:
100 """Transform degrees into radians.
101
102 Args:
103 x (float): A float representing an angle in degrees.
104
105 Returns:
106 float: The angle in radians.
107 """
108 return x * pi / 180.0
109
110
111 def s(i) -> int:
112 """Scale for HiDPI if necessary."""
113 return int(i * max(getcfg("app.dpi") / get_default_dpi(), 1))
114
115
116 def update_patterngenerator(self):
117 """Update the Chromecast pattern generator."""
118 while self and wx.App.IsMainLoopRunning():
119 if self.update_patterngenerator_event.wait(0.05):
120 self.update_patterngenerator_event.clear()
121 x, y, size = self.patterngenerator_config
122 self.patterngenerator.send(
123 (
124 self._colour.r / 255.0,
125 self._colour.g / 255.0,
126 self._colour.b / 255.0,
127 ),
128 (
129 self._bgcolour.r / 255.0,
130 self._bgcolour.g / 255.0,
131 self._bgcolour.b / 255.0,
132 ),
133 x=x,
134 y=y,
135 w=size,
136 h=size,
137 )
138 sleep(0.05)
139
140
141 def _show_result_after(*args, **kwargs):
142 wx.CallAfter(show_result_dialog, *args, **kwargs)
143
144
145 def _wait_thread(fn, *args, **kwargs):
146 # Wait until thread is finished. Yield while waiting.
147 thread = threading.Thread(
148 target=fn, name="VisualWhitepointEditorMaintenance", args=args, kwargs=kwargs
149 )
150 thread.start()
151 while thread.is_alive():
152 wx.Yield()
153 sleep(0.05)
154
155
156 def Distance(pt1, pt2):
157 """Return the distance between 2 points.
158
159 Args:
160 pt1: an instance of :class:`Point`;
161 pt2: another instance of :class:`Point`.
162 """
163 distance = sqrt((pt1.x - pt2.x) ** 2.0 + (pt1.y - pt2.y) ** 2.0)
164 return round(distance)
165
166
167 def AngleFromPoint(pt, center):
168 """Return angle between x-axis and line from center to pt.
169
170 Args:
171 pt: an instance of :class:`Point`;
172 center: a float value representing the center.
173 """
174 y = -1 * (pt.y - center.y)
175 x = pt.x - center.x
176 if x == 0 and y == 0:
177 return 0.0
178
179 return atan2(y, x)
180
181
182 class AuiDarkDockArt(aui.dockart.AuiDefaultDockArt):
183 """AuiDefaultDockArt with dark theme."""
184
185 def __init__(self, *args, **kwargs):
186 aui.dockart.AuiDefaultDockArt.__init__(self, *args, **kwargs)
187 if hasattr(self, "SetDefaultColours"):
188 self.SetDefaultColours(wx.Colour(51, 51, 51))
189 else:
190 self.SetColour(
191 aui.dockart.AUI_DOCKART_INACTIVE_CAPTION_COLOUR, wx.Colour(43, 43, 43)
192 )
193 self.SetColour(
194 aui.dockart.AUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR,
195 wx.Colour(153, 153, 153),
196 )
197 self.SetColour(aui.dockart.AUI_DOCKART_BORDER_COLOUR, wx.Colour(51, 102, 204))
198 if hasattr(aui, "AUI_DOCKART_HINT_WINDOW_COLOUR"):
199 self.SetColour(
200 aui.dockart.AUI_DOCKART_HINT_WINDOW_COLOUR, wx.Colour(102, 153, 204)
201 )
202 self.SetMetric(aui.AUI_DOCKART_GRADIENT_TYPE, aui.AUI_GRADIENT_NONE)
203 self.SetCustomPaneBitmap(
204 get_icon(16, "button-pin"), aui.dockart.AUI_BUTTON_CLOSE, False
205 )
206 self.SetCustomPaneBitmap(
207 get_icon(16, "button-pin"), aui.dockart.AUI_BUTTON_PIN, False
208 )
209
210 def DrawBackground(
211 self, dc: wx.DC, window: wx.Window, orient: int, rect: wx.Rect
212 ) -> None:
213 """Draw a background.
214
215 Args:
216 dc (wx.DC): A :class:`DC` device context.
217 window (wx.Window): An instance of :class:`Window`.
218 orient (int): The gradient (if any) orientation.
219 rect (wx.Rect): The background rectangle.
220 """
221 dc.SetPen(wx.TRANSPARENT_PEN)
222 dc.SetBrush(wx.Brush(wx.Colour(51, 51, 51)))
223 dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)
224
225 def DrawPaneButton(
226 self,
227 dc: wx.DC,
228 window: wx.Window,
229 button: int,
230 button_state: int,
231 _rect: wx.Rect,
232 pane,
233 ):
234 """Draw a pane button in the pane caption area.
235
236 Args:
237 dc (wx.DC): A :class:`DC` device context.
238 window (wx.Window): An instance of :class:`Window`.
239 button (int): The button to be drawn.
240 button_state (int): The pane button state.
241 _rect (wx.Rect): The pane caption rectangle.
242 pane : The pane for which the button is drawn.
243 """
244 if not pane:
245 return
246
247 if button == aui.dockart.AUI_BUTTON_CLOSE:
248 if pane.state & aui.dockart.optionActive:
249 bmp = self._active_close_bitmap
250 else:
251 bmp = self._inactive_close_bitmap
252
253 elif button == aui.dockart.AUI_BUTTON_PIN:
254 if pane.state & aui.dockart.optionActive:
255 bmp = self._active_pin_bitmap
256 else:
257 bmp = self._inactive_pin_bitmap
258
259 elif button == aui.dockart.AUI_BUTTON_MAXIMIZE_RESTORE:
260 if pane.IsMaximized():
261 if pane.state & aui.dockart.optionActive:
262 bmp = self._active_restore_bitmap
263 else:
264 bmp = self._inactive_restore_bitmap
265 elif pane.state & aui.dockart.optionActive:
266 bmp = self._active_maximize_bitmap
267 else:
268 bmp = self._inactive_maximize_bitmap
269
270 elif button == aui.dockart.AUI_BUTTON_MINIMIZE:
271 if pane.state & aui.dockart.optionActive:
272 bmp = self._active_minimize_bitmap
273 else:
274 bmp = self._inactive_minimize_bitmap
275
276 isVertical = pane.HasCaptionLeft()
277
278 rect = wx.Rect(*_rect)
279
280 if isVertical:
281 old_x = rect.x
282 rect.x = int(rect.x + (rect.width / 2) - (bmp.GetWidth() / 2))
283 rect.width = old_x + rect.width - rect.x - 1
284 else:
285 old_y = rect.y
286 rect.y = int(rect.y + (rect.height / 2) - (bmp.GetHeight() / 2))
287 rect.height = old_y + rect.height - rect.y - 1
288
289 if button_state == aui.dockart.AUI_BUTTON_STATE_PRESSED:
290 rect.x += 1
291 rect.y += 1
292
293 if button_state == aui.dockart.AUI_BUTTON_STATE_HOVER:
294 bmp = get_bitmap_hover(bmp)
295 elif button_state == aui.dockart.AUI_BUTTON_STATE_PRESSED:
296 bmp = get_bitmap_pressed(bmp)
297
298 if isVertical:
299 bmp = wx.ImageFromBitmap(bmp).Rotate90(clockwise=False).ConvertToBitmap()
300
301 # draw the button itself
302 dc.DrawBitmap(bmp, rect.x, rect.y, True)
303
304 def SetCustomPaneBitmap(self, bmp, button, active, maximize=False):
305 """Set a custom button bitmap for the pane button.
306
307 Args:
308 bmp (Bitmap): The actual bitmap to set.
309 button (int): The button identifier.
310 active (bool): Whether it is the bitmap for the active button or not.
311 maximize (bool): Used to distinguish between the maximize and restore
312 bitmaps.
313 """
314 if button == aui.dockart.AUI_BUTTON_CLOSE:
315 if active:
316 self._active_close_bitmap = bmp
317 else:
318 self._inactive_close_bitmap = bmp
319
320 if wx.Platform == "__WXMAC__":
321 self._custom_pane_bitmaps = True
322
323 elif button == aui.dockart.AUI_BUTTON_PIN:
324 if active:
325 self._active_pin_bitmap = bmp
326 else:
327 self._inactive_pin_bitmap = bmp
328
329 elif button == aui.dockart.AUI_BUTTON_MAXIMIZE_RESTORE:
330 if maximize:
331 if active:
332 self._active_maximize_bitmap = bmp
333 else:
334 self._inactive_maximize_bitmap = bmp
335 elif active:
336 self._active_restore_bitmap = bmp
337 else:
338 self._inactive_restore_bitmap = bmp
339
340 elif button == aui.dockart.AUI_BUTTON_MINIMIZE:
341 if active:
342 self._active_minimize_bitmap = bmp
343 else:
344 self._inactive_minimize_bitmap = bmp
345
346
347 class AuiManagerLRDocking(aui.AuiManager):
348 """AuiManager with only left/right docking.
349
350 Also, it is not necessary to hover the drop guide, a drop hint will show
351 near the edges regardless.
352 """
353
354 def CreateGuideWindows(self):
355 """Create the guide windows for docking."""
356 self.DestroyGuideWindows()
357
358 def DoDrop(self, docks, panes, target, pt, offset=None):
359 """Take a mouse position and determine where the panes new position would be.
360
361 This is an important function. If the pane is to be dropped, it performs
362 the drop operation using the specified dock and pane arrays. By
363 specifying copy dock and pane arrays when calling, a "what-if" scenario
364 can be performed, giving precise coordinates for drop hints.
365
366 Args:
367 docks (AuiDocInfo): A list of :class:`AuiDockInfo` classes.
368 panes (AuiPaneInfo): A list of :class:`AuiPaneInfo` instances.
369 target (AuiPaneInfo): The target pane containing the toolbar.
370 pt (Point): A mouse position to check for a drop operation.
371 offset (Point): A possible offset from the input point `pt`.
372 """
373 if offset is None:
374 offset = wx.Point(0, 0)
375
376 if target.IsToolbar():
377 return self.DoDropToolbar(docks, panes, target, pt, offset)
378 if target.IsFloating():
379 allow, hint = self.DoDropFloatingPane(docks, panes, target, pt)
380 if allow:
381 return allow, hint
382 return self.DoDropNonFloatingPane(docks, panes, target, pt)
383
384 def DoDropNonFloatingPane(self, docks, panes, target, pt):
385 """Handle the situation in which the dropped pane is not floating.
386
387 Args:
388 docks (list[AuiDockInfo]): A list of :class:`AuiDockInfo` classes.
389 panes (list[AuiPaneInfo]): A list of :class:`AuiPaneInfo` instances.
390 target (AuiPaneInfo): The target pane containing the toolbar.
391 pt (Point): A mouse position to check for a drop operation.
392 """
393 # The ONLY change from
394 # wx.lib.framemanager.FrameManager.DoDropNonFloatingPane
395 # is the removal of top offset by setting new_row_pixels_y to 0.
396 # This way, the drag hint is shown when the mouse is near the right
397 # frame side irrespective of mouse Y position.
398
399 # screenPt = self._frame.ClientToScreen(pt)
400 # clientSize = self._frame.GetClientSize()
401 # frameRect = aui.GetInternalFrameRect(self._frame, self._docks)
402
403 drop = self.CopyTarget(target)
404
405 # The result should always be shown
406 drop.Show()
407
408 part = self.HitTest(pt.x, pt.y)
409
410 if not part:
411 return False, target
412
413 if part.type == aui.AuiDockUIPart.typeDockSizer:
414 if len(part.dock.panes) != 1:
415 return False, target
416
417 part = self.GetPanePart(part.dock.panes[0].window)
418 if not part:
419 return False, target
420
421 if not part.pane:
422 return False, target
423
424 part = self.GetPanePart(part.pane.window)
425 if not part:
426 return False, target
427
428 insert_dock_row = False
429 insert_row = part.pane.dock_row
430 insert_dir = part.pane.dock_direction
431 insert_layer = part.pane.dock_layer
432
433 direction = part.pane.dock_direction
434
435 if direction == aui.AUI_DOCK_TOP:
436 if part.rect.y <= pt.y < part.rect.y + aui.auiInsertRowPixels:
437 insert_dock_row = True
438
439 elif direction == aui.AUI_DOCK_BOTTOM:
440 if (
441 part.rect.y + part.rect.height - aui.auiInsertRowPixels
442 < pt.y
443 <= part.rect.y + part.rect.height
444 ):
445 insert_dock_row = True
446
447 elif direction == aui.AUI_DOCK_LEFT:
448 if part.rect.x <= pt.x < part.rect.x + aui.auiInsertRowPixels:
449 insert_dock_row = True
450
451 elif direction == aui.AUI_DOCK_RIGHT:
452 if (
453 part.rect.x + part.rect.width - aui.auiInsertRowPixels
454 < pt.x
455 <= part.rect.x + part.rect.width
456 ):
457 insert_dock_row = True
458
459 elif direction == aui.AUI_DOCK_CENTER:
460 # "new row pixels" will be set to the default, but
461 # must never exceed 20% of the window size
462 new_row_pixels_x = s(20)
463 new_row_pixels_y = 0
464
465 new_row_pixels_x = min(new_row_pixels_x, (part.rect.width * 20) / 100)
466
467 new_row_pixels_y = min(new_row_pixels_y, (part.rect.height * 20) / 100)
468
469 # determine if the mouse pointer is in a location that
470 # will cause a new row to be inserted. The hot spot positions
471 # are along the borders of the center pane
472
473 insert_layer = 0
474 insert_dock_row = True
475 pr = part.rect
476
477 if pr.x <= pt.x < pr.x + new_row_pixels_x:
478 insert_dir = aui.AUI_DOCK_LEFT
479 elif pr.y <= pt.y < pr.y + new_row_pixels_y:
480 insert_dir = aui.AUI_DOCK_TOP
481 elif pr.x + pr.width - new_row_pixels_x <= pt.x < pr.x + pr.width:
482 insert_dir = aui.AUI_DOCK_RIGHT
483 elif pr.y + pr.height - new_row_pixels_y <= pt.y < pr.y + pr.height:
484 insert_dir = aui.AUI_DOCK_BOTTOM
485 else:
486 return False, target
487
488 insert_row = aui.GetMaxRow(panes, insert_dir, insert_layer) + 1
489
490 if insert_dock_row:
491 panes = aui.DoInsertDockRow(panes, insert_dir, insert_layer, insert_row)
492 drop.Dock().Direction(insert_dir).Layer(insert_layer).Row(
493 insert_row
494 ).Position(0)
495
496 return self.ProcessDockResult(target, drop)
497
498 # determine the mouse offset and the pane size, both in the
499 # direction of the dock itself, and perpendicular to the dock
500
501 if part.orientation == wx.VERTICAL:
502 offset = pt.y - part.rect.y
503 size = part.rect.GetHeight()
504
505 else:
506 offset = pt.x - part.rect.x
507 size = part.rect.GetWidth()
508
509 drop_position = part.pane.dock_pos
510
511 # if we are in the top/left part of the pane,
512 # insert the pane before the pane being hovered over
513 if offset <= size / 2:
514 drop_position = part.pane.dock_pos
515 panes = aui.DoInsertPane(
516 panes,
517 part.pane.dock_direction,
518 part.pane.dock_layer,
519 part.pane.dock_row,
520 part.pane.dock_pos,
521 )
522
523 # if we are in the bottom/right part of the pane,
524 # insert the pane before the pane being hovered over
525 if offset > size / 2:
526 drop_position = part.pane.dock_pos + 1
527 panes = aui.DoInsertPane(
528 panes,
529 part.pane.dock_direction,
530 part.pane.dock_layer,
531 part.pane.dock_row,
532 part.pane.dock_pos + 1,
533 )
534
535 drop.Dock().Direction(part.dock.dock_direction).Layer(part.dock.dock_layer).Row(
536 part.dock.dock_row
537 ).Position(drop_position)
538
539 return self.ProcessDockResult(target, drop)
540
541
542 class Colour:
543 """Colour class with RGB and HSV conversion methods.
544
545 This is a class similar to :class:`Colour`, which adds Hue, Saturation and
546 Brightness capability. It contains also methods to convert RGB triplets
547 into HSB triplets and vice-versa.
548
549 Args:
550 colour: a standard :class:`Colour`.
551 """
552
553 def __init__(self, colour):
554 self.r = colour.Red()
555 self.g = colour.Green()
556 self.b = colour.Blue()
557 self._alpha = colour.Alpha()
558
559 self.ToHSV()
560
561 def ToRGB(self) -> None:
562 """Convert a HSV triplet into a RGB triplet."""
563 maxVal = self.v
564 delta = (maxVal * self.s) / 255.0
565 minVal = maxVal - delta
566
567 hue = float(self.h)
568
569 if self.h > 300 or self.h <= 60:
570 self.r = maxVal
571
572 if self.h > 300:
573 self.g = round(minVal)
574 hue = (hue - 360.0) / 60.0
575 self.b = round(-(hue * delta - minVal))
576
577 else:
578 self.b = round(minVal)
579 hue = hue / 60.0
580 self.g = round(hue * delta + minVal)
581
582 elif 60 < self.h < 180:
583 self.g = round(maxVal)
584
585 if self.h < 120:
586 self.b = round(minVal)
587 hue = (hue / 60.0 - 2.0) * delta
588 self.r = round(minVal - hue)
589
590 else:
591 self.r = round(minVal)
592 hue = (hue / 60.0 - 2.0) * delta
593 self.b = round(minVal + hue)
594
595 else:
596 self.b = round(maxVal)
597
598 if self.h < 240:
599 self.r = round(minVal)
600 hue = (hue / 60.0 - 4.0) * delta
601 self.g = round(minVal - hue)
602
603 else:
604 self.g = round(minVal)
605 hue = (hue / 60.0 - 4.0) * delta
606 self.r = round(minVal + hue)
607
608 def ToHSV(self) -> None:
609 """Convert a RGB triplet into a HSV triplet."""
610 minVal = float(min(self.r, min(self.g, self.b)))
611 maxVal = float(max(self.r, max(self.g, self.b)))
612 delta = maxVal - minVal
613
614 self.v = round(maxVal)
615
616 if abs(delta) < 1e-6:
617 self.h = self.s = 0
618 return
619
620 temp = delta / maxVal
621 self.s = round(temp * 255.0)
622
623 if self.r == round(maxVal):
624 temp = float(self.g - self.b) / delta
625
626 elif self.g == round(maxVal):
627 temp = 2.0 + (float(self.b - self.r) / delta)
628
629 else:
630 temp = 4.0 + (float(self.r - self.g) / delta)
631
632 temp *= 60
633 if temp < 0:
634 temp += 360
635
636 elif temp >= 360.0:
637 temp = 0
638
639 self.h = round(temp)
640
641 def GetPyColour(self):
642 """Return the wxPython :class:`Colour` associated with this instance."""
643 return wx.Colour(int(self.r), int(self.g), int(self.b), int(self._alpha))
644
645
646 class BasePyControl(wx.PyControl):
647 """Base class for HSB colour wheel and RGB colour cube.
648
649 Args:
650 parent (wx.Window): The control parent;
651 bitmap (wx.Bitmap): The background bitmap for this custom control.
652 """
653
654 def __init__(self, parent, bitmap=None):
655 wx.PyControl.__init__(self, parent, style=wx.NO_BORDER)
656 self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
657
658 self._bitmap = bitmap
659
660 self._mainFrame = wx.GetTopLevelParent(self)
661
662 self.Bind(wx.EVT_SIZE, self.OnSize)
663 self.Bind(wx.EVT_PAINT, self.OnPaint)
664 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
665 self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
666 self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
667 self.Bind(wx.EVT_MOTION, self.OnMotion)
668
669 def OnPaint(self, event: wx.PaintEvent) -> None:
670 """Handle the ``wx.EVT_PAINT`` for :class:`BasePyControl`.
671
672 Args:
673 event (wx.PainEvent): A :class:`PaintEvent` event to be processed.
674 """
675 dc = wx.AutoBufferedPaintDC(self)
676 self.Draw(dc)
677
678 def Draw(self, dc):
679 """Draw the background bitmap.
680
681 Args:
682 dc (wx.DC): an instance of :class:`DC`.
683 """
684 if "gtk3" in wx.PlatformInfo:
685 bgcolour = self.Parent.BackgroundColour
686 else:
687 bgcolour = self.BackgroundColour
688 dc.SetBackground(wx.Brush(bgcolour))
689
690 dc.Clear()
691 dc.DrawBitmap(self._bitmap, 0, 0, True)
692
693 def OnEraseBackground(self, event: wx.EraseEvent) -> None:
694 """Handle the ``wx.EVT_ERASE_BACKGROUND`` for :class:`BasePyControl`.
695
696 :note: This is intentionally empty to reduce flicker.
697
698 Args:
699 event (wx.EraseEvent): a :class:`EraseEvent` event to be processed.
700 """
701
702 def DrawMarkers(self, dc=None):
703 """Draw the markers on top of the background bitmap.
704
705 :note: This method must be overridden in derived classes.
706
707 Args:
708 dc (wx.DC): an instance of :class:`DC`.
709 """
710
711 def DrawLines(self, dc):
712 """Draw the lines connecting the markers on top of the background bitmap.
713
714 :note: This method must be overridden in derived classes.
715
716 Args:
717 dc (wx.DC): an instance of :class:`DC`.
718 """
719
720 def AcceptsFocusFromKeyboard(self):
721 """Return whether this window can be given focus by keyboard navigation.
722
723 Can this window be given focus by keyboard navigation? If not, the
724 only way to give it focus (provided it accepts it at all) is to click
725 it.
726
727 :note: This method always returns ``False`` as we do not accept focus from
728 the keyboard.
729
730 :note: Overridden from :class:`PyControl`.
731 """
732 return False
733
734 def AcceptsFocus(self):
735 """Can this window be given focus by mouse click?
736
737 :note: This method always returns ``False`` as we do not accept focus from
738 mouse click.
739
740 :note: Overridden from :class:`PyControl`.
741 """
742 return False
743
744 def OnLeftDown(self, event):
745 """Handle the ``wx.EVT_LEFT_DOWN`` for :class:`BasePyControl`.
746
747 Args:
748 event: a :class:`MouseEvent` event to be processed.
749
750 :note: This method must be overridden in derived classes.
751 """
752
753 def OnLeftUp(self, event):
754 """Handle the ``wx.EVT_LEFT_UP`` for :class:`BasePyControl`.
755
756 Args:
757 event: a :class:`MouseEvent` event to be processed.
758
759 :note: This method must be overridden in derived classes.
760 """
761
762 def OnMotion(self, event):
763 """Handle the ``wx.EVT_MOTION`` for :class:`BasePyControl`.
764
765 Args:
766 event: a :class:`MouseEvent` event to be processed.
767
768 :note: This method must be overridden in derived classes.
769 """
770
771 def OnSize(self, event):
772 """Handle the ``wx.EVT_SIZE`` for :class:`BasePyControl`.
773
774 Args:
775 event: a :class:`SizeEvent` event to be processed.
776 """
777 self.Refresh()
778
779 def DoGetBestSize(self):
780 """Overridden base class virtual.
781
782 Determines the best size of the control based on the bitmap size.
783
784 :note: Overridden from :class:`PyControl`.
785 """
786 return wx.Size(self._bitmap.GetWidth(), self._bitmap.GetHeight())
787
788
789 class BasePyButton(BasePyControl):
790 """Common base for HSB colour wheel and RGB colour cube."""
791
792 def __init__(self, parent, bitmap):
793 BasePyControl.__init__(self, parent, bitmap)
794 self._bitmap_enabled = bitmap
795 self._bitmap_disabled = get_bitmap_disabled(bitmap)
796 self._bitmap_hover = get_bitmap_hover(bitmap)
797 self._bitmap_pressed = get_bitmap_pressed(bitmap)
798 self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter)
799 self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
800
801 def OnLeftDown(self, event):
802 """Handle the ``wx.EVT_LEFT_DOWN`` for :class:`BasePyButton`.
803
804 Args:
805 event: a :class:`MouseEvent` event to be processed.
806 """
807 if self.Enabled:
808 self._bitmap = self._bitmap_pressed
809 self.Refresh()
810 event.Skip()
811
812 def OnLeftUp(self, event):
813 """Handle the ``wx.EVT_LEFT_UP`` for :class:`BasePyButton`.
814
815 Args:
816 event: a :class:`MouseEvent` event to be processed.
817 """
818 if self.Enabled:
819 self._bitmap = self._bitmap_hover
820 self.Refresh()
821 event.Skip()
822
823 def OnMouseEnter(self, event):
824 """Handle the ``wx.EVT_ENTER_WINDOW`` for :class:`BasePyButton`.
825
826 Args:
827 event: a :class:`MouseEvent` event to be processed.
828 """
829 if self.Enabled:
830 if self.HasCapture():
831 self._bitmap = self._bitmap_pressed
832 else:
833 self._bitmap = self._bitmap_hover
834 self.Refresh()
835 event.Skip()
836
837 def OnMouseLeave(self, event):
838 """Handle the ``wx.EVT_LEAVE_WINDOW`` for :class:`BasePyButton`.
839
840 Args:
841 event: a :class:`MouseEvent` event to be processed.
842 """
843 if self.Enabled:
844 self._bitmap = self._bitmap_enabled
845 self.Refresh()
846 event.Skip()
847
848 def Enable(self, enable=True):
849 """Enable or disable the control.
850
851 Args:
852 enable (bool): If ``True``, the control will be enabled, otherwise
853 it will be disabled.
854 """
855 if enable == self.Enabled:
856 return
857 BasePyControl.Enable(self, enable)
858 if self.Enabled:
859 self._bitmap = self._bitmap_enabled
860 else:
861 self._bitmap = self._bitmap_disabled
862 self.Refresh()
863
864
865 class HSVWheel(BasePyControl):
866 """Custom control to select a colour in the HSV colour space.
867
868 Implement the drawing, mouse handling and sizing routines for the HSV
869 colour wheel.
870
871 Args:
872 parent: the control parent window.
873 """
874
875 def __init__(self, parent, bgcolour):
876 BasePyControl.__init__(self, parent, bitmap=get_bitmap("theme/colorwheel"))
877 self._bitmap = (
878 self._bitmap.ConvertToImage()
879 .AdjustChannels(0.8, 0.8, 0.8)
880 .ConvertToBitmap()
881 )
882 self._mouseIn = False
883 self._buffer = wx.EmptyBitmap(self._bitmap.Width, self._bitmap.Height)
884 self._bg = wx.EmptyBitmap(self._bitmap.Width, self._bitmap.Height)
885 self._bgdc = wx.MemoryDC(self._bg)
886 self.BackgroundColour = bgcolour
887 self.Draw(self._bgdc)
888
889 def DrawMarkers(self, dc=None):
890 """Draw the markers on top of the background bitmap.
891
892 Args:
893 dc (wx.DC): An :class:`DC` instance.
894 """
895 if dc is None:
896 dc = wx.ClientDC(self)
897 if sys.platform != "darwin":
898 dc = wx.BufferedDC(dc, self._buffer)
899
900 # Blit the DC with our background to the current DC.
901 # Much faster than redrawing the background every time.
902 dc.Blit(0, 0, self._bg.Width, self._bg.Height, self._bgdc, 0, 0)
903
904 brightMark = self._mainFrame._currentRect
905 darkMarkOuter = wx.Rect(
906 brightMark.x - 1,
907 brightMark.y - 1,
908 brightMark.width + 2,
909 brightMark.height + 2,
910 )
911 darkMarkInner = wx.Rect(
912 brightMark.x + 1,
913 brightMark.y + 1,
914 brightMark.width - 2,
915 brightMark.height - 2,
916 )
917 dc.SetBrush(wx.TRANSPARENT_BRUSH)
918
919 for pencolour, rect in (
920 (wx.Colour(34, 34, 34), darkMarkOuter),
921 (wx.LIGHT_GREY, brightMark),
922 (wx.Colour(34, 34, 34), darkMarkInner),
923 ):
924 dc.SetPen(wx.Pen(pencolour, 1))
925
926 dc.DrawRectangle(rect)
927
928 def OnLeftDown(self, event):
929 """Handle the ``wx.EVT_LEFT_DOWN`` for :class:`HSVWheel`.
930
931 Args:
932 event: a :class:`MouseEvent` event to be processed.
933 """
934 point = wx.Point(event.GetX(), event.GetY())
935 self._mouseIn = False
936
937 if self.InCircle(point):
938 self._mouseIn = True
939
940 if self._mouseIn:
941 self.CaptureMouse()
942 self.TrackPoint(point)
943
944 def OnLeftUp(self, event):
945 """Handle the ``wx.EVT_LEFT_UP`` for :class:`HSVWheel`.
946
947 Args:
948 event: a :class:`MouseEvent` event to be processed.
949 """
950 if self.GetCapture():
951 self.ReleaseMouse()
952 self._mouseIn = False
953
954 def OnMotion(self, event):
955 """Handle the ``wx.EVT_MOTION`` for :class:`HSVWheel`.
956
957 Args:
958 event: a :class:`MouseEvent` event to be processed.
959 """
960 point = wx.Point(event.GetX(), event.GetY())
961
962 if self.GetCapture() and self._mouseIn:
963 self.TrackPoint(point)
964
965 def OnPaint(self, event):
966 """Handle the ``wx.EVT_PAINT`` for :class:`BasePyControl`.
967
968 Args:
969 event: a :class:`PaintEvent` event to be processed.
970 """
971 dc = wx.AutoBufferedPaintDC(self)
972
973 if self._mainFrame._initOver:
974 self.DrawMarkers(dc)
975 else:
976 self.Draw(dc)
977
978 def InCircle(self, pt):
979 """Return whether a point is inside the HSV wheel or not.
980
981 Args:
982 pt: an instance of :class:`Point`.
983 """
984 return Distance(pt, self._mainFrame._centre) <= (self._bitmap.Size[0]) / 2
985
986 def TrackPoint(self, pt):
987 """Track a mouse event inside the HSV colour wheel.
988
989 Args:
990 pt: an instance of :class:`Point`.
991 """
992 if not self._mouseIn:
993 return
994
995 mainFrame = self._mainFrame
996 colour = mainFrame._colour
997
998 colour.h = round(rad2deg(AngleFromPoint(pt, mainFrame._centre)))
999 if colour.h < 0:
1000 colour.h += 360
1001
1002 colour.s = round(
1003 Distance(pt, mainFrame._centre)
1004 * 255.0
1005 / ((self._bitmap.Size[0] - s(12)) / 2)
1006 * 0.2
1007 )
1008 colour.s = min(colour.s, 255)
1009
1010 mainFrame.CalcRects()
1011 self.DrawMarkers()
1012 colour.ToRGB()
1013 mainFrame.SetSpinVals()
1014
1015 mainFrame.DrawBright()
1016
1017
1018 class BaseLineCtrl(wx.PyControl):
1019 """Base class for alpha and brightness controls.
1020
1021 Args:
1022 parent: the control parent window.
1023 """
1024
1025 def __init__(self, parent, size=wx.DefaultSize):
1026 wx.PyControl.__init__(self, parent, size=size, style=wx.NO_BORDER)
1027 self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
1028
1029 self._mainFrame = wx.GetTopLevelParent(self)
1030
1031 self.Bind(wx.EVT_SIZE, self.OnSize)
1032 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
1033 self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
1034 self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
1035 self.Bind(wx.EVT_MOTION, self.OnMotion)
1036
1037 def OnEraseBackground(self, event):
1038 """Handle the ``wx.EVT_ERASE_BACKGROUND`` for :class:`BaseLineCtrl`.
1039
1040 Args:
1041 event: a :class:`EraseEvent` event to be processed.
1042
1043 :note: This is intentionally empty to reduce flicker.
1044 """
1045
1046 def OnLeftDown(self, event):
1047 """Handle the ``wx.EVT_LEFT_DOWN`` for :class:`BaseLineCtrl`.
1048
1049 Args:
1050 event: a :class:`MouseEvent` event to be processed.
1051 """
1052 point = wx.Point(event.GetX(), event.GetY())
1053 theRect = self.GetClientRect()
1054
1055 if not theRect.Contains(point):
1056 event.Skip()
1057 return
1058
1059 self.CaptureMouse()
1060 self.TrackPoint(point)
1061
1062 def OnLeftUp(self, event):
1063 """Handle the ``wx.EVT_LEFT_UP`` for :class:`BaseLineCtrl`.
1064
1065 Args:
1066 event: a :class:`MouseEvent` event to be processed.
1067 """
1068 if self.GetCapture():
1069 self.ReleaseMouse()
1070 self.Refresh() # Needed for proper redrawing after click under OS X
1071
1072 def OnMotion(self, event):
1073 """Handle the ``wx.EVT_MOTION`` for :class:`BaseLineCtrl`.
1074
1075 Args:
1076 event: a :class:`MouseEvent` event to be processed.
1077 """
1078 point = wx.Point(event.GetX(), event.GetY())
1079
1080 if self.GetCapture():
1081 self.TrackPoint(point)
1082
1083 def OnSize(self, event):
1084 """Handle the ``wx.EVT_SIZE`` for :class:`BaseLineCtrl`.
1085
1086 Args:
1087 event: a :class:`SizeEvent` event to be processed.
1088 """
1089 self.Refresh()
1090
1091 def BuildRect(self):
1092 """Build a rectangle that is used to draw the brightness palette."""
1093 brightRect = wx.Rect(*self.GetClientRect())
1094 brightRect.x += s(2)
1095 brightRect.y += s(2)
1096 brightRect.width -= s(4)
1097 brightRect.height -= s(4)
1098
1099 return brightRect
1100
1101 def AcceptsFocusFromKeyboard(self):
1102 """Return whether this window can be given focus by keyboard navigation.
1103
1104 Can this window be given focus by keyboard navigation? If not, the
1105 only way to give it focus (provided it accepts it at all) is to click
1106 it.
1107
1108 :note: This method always returns ``False`` as we do not accept focus from
1109 the keyboard.
1110
1111 :note: Overridden from :class:`PyControl`.
1112 """
1113 return False
1114
1115 def AcceptsFocus(self):
1116 """Can this window be given focus by mouse click?
1117
1118 :note: This method always returns ``False`` as we do not accept focus from
1119 mouse click.
1120
1121 :note: Overridden from :class:`PyControl`.
1122 """
1123 return False
1124
1125
1126 class BrightCtrl(BaseLineCtrl):
1127 """A control used to select the brightness of a colour.
1128
1129 Implement the drawing, mouse handling and sizing routines for the
1130 brightness palette control.
1131
1132 Args:
1133 parent (wx.Window): the control parent window.
1134 colour (wx.Colour): an instance of :class:`Colour` to be used for the
1135 palette.
1136 """
1137
1138 def __init__(self, parent, colour=None):
1139 BaseLineCtrl.__init__(self, parent, size=(s(20), s(102)))
1140 self._colour = colour or self._mainFrame._colour
1141 self.Bind(wx.EVT_PAINT, self.OnPaint)
1142 self.Bind(wx.EVT_MOUSEWHEEL, self.mousewheel_handler)
1143
1144 def OnPaint(self, event):
1145 """Handle the ``wx.EVT_PAINT`` for :class:`BrightCtrl`.
1146
1147 Args:
1148 event: a :class:`PaintEvent` event to be processed.
1149 """
1150 dc = wx.AutoBufferedPaintDC(self)
1151
1152 self.DrawMarkers(dc)
1153
1154 def DoGetBestSize(self):
1155 """Overridden base class virtual. Determines the best size of the control.
1156
1157 :note: Overridden from :class:`PyControl`.
1158 """
1159 return wx.Size(s(20), s(102))
1160
1161 def Draw(self, dc):
1162 """Draw the brightness palette control.
1163
1164 Args:
1165 dc (wx.DC): an instance of :class:`DC`.
1166 """
1167 if "gtk3" in wx.PlatformInfo:
1168 bgcolour = self.Parent.BackgroundColour
1169 else:
1170 bgcolour = self.BackgroundColour
1171 dc.SetBackground(wx.Brush(bgcolour))
1172 dc.Clear()
1173
1174 colour = self._colour.GetPyColour()
1175 brightRect = self.BuildRect()
1176
1177 target_red = colour.Red()
1178 target_green = colour.Green()
1179 target_blue = colour.Blue()
1180
1181 h, s, v = colorsys.rgb_to_hsv(
1182 target_red / 255.0, target_green / 255.0, target_blue / 255.0
1183 )
1184 v = 0.8
1185 vstep = v / (brightRect.height - 1)
1186
1187 for y_pos in range(brightRect.y, brightRect.height + brightRect.y):
1188 r, g, b = [round(c * 255.0) for c in colorsys.hsv_to_rgb(h, s, v)]
1189 colour = wx.Colour(int(r), int(g), int(b))
1190 dc.SetPen(wx.Pen(colour, 1, wx.PENSTYLE_SOLID))
1191 dc.DrawRectangle(brightRect.x, y_pos, brightRect.width, 1)
1192 v = v - vstep
1193
1194 dc.SetPen(wx.TRANSPARENT_PEN)
1195 dc.SetBrush(wx.TRANSPARENT_BRUSH)
1196 dc.DrawRectangle(brightRect)
1197
1198 def TrackPoint(self, pt):
1199 """Track a mouse action inside the palette control.
1200
1201 Args:
1202 pt: an instance of :class:`Point`.
1203 """
1204 brightRect = self.BuildRect()
1205 d = brightRect.GetBottom() - pt.y
1206 d *= 255
1207 d /= brightRect.height
1208 d = max(d, 0)
1209 d = min(d, 255)
1210
1211 mainFrame = self._mainFrame
1212 colour = self._colour
1213
1214 colour.v = round(d)
1215 mainFrame.DrawMarkers()
1216
1217 colour.ToRGB()
1218 mainFrame.SetSpinVals()
1219
1220 def DrawMarkers(self, dc=None):
1221 """Draw square markers used with mouse gestures.
1222
1223 Args:
1224 dc: an instance of :class:`DC`.
1225 """
1226 if dc is None:
1227 dc = wx.ClientDC(self)
1228 if sys.platform != "darwin":
1229 dc = wx.BufferedDC(dc)
1230 self.Draw(dc)
1231
1232 colour = self._colour
1233 brightRect = self.BuildRect()
1234
1235 y = round(colour.v / 255.0 * (brightRect.height - s(6)))
1236 y = brightRect.height - s(4) - 1 - y
1237 h = s(8)
1238 darkMarkOuter = wx.Rect(brightRect.x - 2, y - 1, brightRect.width + 4, h)
1239 brightMark = wx.Rect(brightRect.x - 1, y, brightRect.width + 2, h - 2)
1240 darkMarkInner = wx.Rect(brightRect.x, y + 1, brightRect.width, h - 4)
1241
1242 dc.SetBrush(wx.TRANSPARENT_BRUSH)
1243 for pencolour, rect in (
1244 (wx.Colour(34, 34, 34), darkMarkOuter),
1245 (wx.LIGHT_GREY, brightMark),
1246 (wx.Colour(34, 34, 34), darkMarkInner),
1247 ):
1248 dc.SetPen(wx.Pen(pencolour, 1))
1249
1250 dc.DrawRectangle(rect)
1251
1252 def mousewheel_handler(self, event):
1253 """Handle the ``wx.EVT_MOUSEWHEEL`` for :class:`BrightCtrl`.
1254
1255 Args:
1256 event: a :class:`MouseEvent` event to be processed.
1257 """
1258 self._spin(event.GetWheelRotation())
1259
1260 def _spin(self, direction):
1261 if direction > 0:
1262 if self._colour.v < 255:
1263 self._colour.v += 1
1264 elif self._colour.v > 0:
1265 self._colour.v -= 1
1266
1267 self._mainFrame.DrawMarkers()
1268
1269 self._colour.ToRGB()
1270 self._mainFrame.SetSpinVals()
1271
1272
1273 class HSlider(BaseLineCtrl):
1274 """A horizontal slider for selecting a value within a range.
1275
1276 Args:
1277 parent (wx.Window): the control parent window.
1278 value (int): The initial value of the slider.
1279 minval (int): The minimum value of the slider.
1280 maxval (int): The maximum value of the slider.
1281 onchange (callable): A callback function to be called when the value
1282 changes.
1283 """
1284
1285 def __init__(self, parent, value=0, minval=0, maxval=100, onchange=None):
1286 BaseLineCtrl.__init__(self, parent, size=(s(140), s(8)))
1287 self.value = value
1288 self.minval = minval
1289 self.maxval = maxval
1290 self.onchange = onchange
1291 self._hasfocus = False
1292 self.Bind(wx.EVT_PAINT, self.OnPaint)
1293 self.Bind(wx.EVT_SET_FOCUS, self.focus_handler)
1294 self.Bind(wx.EVT_KILL_FOCUS, self.focus_handler)
1295 self.Bind(wx.EVT_KEY_DOWN, self.key_handler)
1296 self.Bind(wx.EVT_KEY_UP, self.key_handler)
1297 self.Bind(wx.EVT_MOUSEWHEEL, self.mousewheel_handler)
1298
1299 def OnPaint(self, event):
1300 """Handle the ``wx.EVT_PAINT`` for :class:`BrightCtrl`.
1301
1302 Args:
1303 event: a :class:`PaintEvent` event to be processed.
1304 """
1305 dc = wx.AutoBufferedPaintDC(self)
1306
1307 self.DrawMarkers(dc)
1308
1309 def DoGetBestSize(self):
1310 """Overridden base class virtual. Determines the best size of the control.
1311
1312 :note: Overridden from :class:`PyControl`.
1313 """
1314 return wx.Size(s(140), s(8))
1315
1316 def BuildRect(self):
1317 """Build the rectangle used to draw the slider.
1318
1319 Returns:
1320 wx.Rect: The rectangle used to draw the slider.
1321 """
1322 brightRect = self.GetClientRect()
1323 brightRect.y += int((brightRect.height - 8) / 2.0)
1324 brightRect.height = s(8)
1325
1326 return brightRect
1327
1328 def Draw(self, dc):
1329 """Draw the slider control.
1330
1331 Args:
1332 dc (wx.DC): an instance of :class:`DC`.
1333 """
1334 if "gtk3" in wx.PlatformInfo:
1335 bgcolour = self.Parent.BackgroundColour
1336 else:
1337 bgcolour = self.BackgroundColour
1338 dc.SetBackground(wx.Brush(bgcolour))
1339 dc.Clear()
1340
1341 brightRect = self.BuildRect()
1342
1343 dc.SetPen(wx.TRANSPARENT_PEN)
1344 dc.SetBrush(wx.Brush(wx.Colour(76, 76, 76)))
1345 dc.DrawRectangle(brightRect)
1346
1347 def TrackPoint(self, pt):
1348 """Track a mouse action inside the palette control.
1349
1350 Args:
1351 pt: an instance of :class:`Point`.
1352 """
1353 brightRect = self.BuildRect()
1354 d = pt.x
1355 d *= self.maxval
1356 d /= brightRect.width
1357 d = max(d, self.minval)
1358 d = min(d, self.maxval)
1359 self.value = d
1360
1361 self.DrawMarkers()
1362
1363 if callable(self.onchange):
1364 self.onchange()
1365
1366 def DrawMarkers(self, dc=None):
1367 """Draw square markers used with mouse gestures.
1368
1369 Args:
1370 dc: an instance of :class:`DC`.
1371 """
1372 if dc is None:
1373 dc = wx.ClientDC(self)
1374 if sys.platform != "darwin":
1375 dc = wx.BufferedDC(dc)
1376 self.Draw(dc)
1377
1378 brightRect = self.BuildRect()
1379
1380 w = s(8)
1381 x = round(
1382 (self.value - self.minval)
1383 / float(self.maxval - self.minval)
1384 * (brightRect.width - w)
1385 )
1386 brightMark = wx.Rect(x, brightRect.y, w, brightRect.height)
1387
1388 dc.SetBrush(wx.Brush(wx.Colour(153, 153, 153)))
1389 dc.DrawRectangle(brightMark)
1390
1391 def GetValue(self):
1392 """Get the value of the slider.
1393
1394 Returns:
1395 int: The current value of the slider.
1396 """
1397 return self.value
1398
1399 def SetValue(self, value):
1400 """Set the value of the slider.
1401
1402 Args:
1403 value (int): The new value for the slider.
1404 """
1405 self.value = value
1406 self.DrawMarkers()
1407
1408 @property
1409 def Value(self):
1410 """Get the value of the slider.
1411
1412 Returns:
1413 int: The current value of the slider.
1414 """
1415 return self.GetValue()
1416
1417 @Value.setter
1418 def Value(self, value):
1419 """Set the value of the slider.
1420
1421 Args:
1422 value (int): The new value for the slider.
1423 """
1424 self.SetValue(value)
1425
1426 def GetMax(self):
1427 """Get the maximum value of the slider.
1428
1429 Returns:
1430 int: The maximum value of the slider.
1431 """
1432 return self.maxval
1433
1434 def GetMin(self):
1435 """Get the minimum value of the slider.
1436
1437 Returns:
1438 int: The minimum value of the slider.
1439 """
1440 return self.minval
1441
1442 def SetMax(self, maxval):
1443 """Set the maximum value of the slider.
1444
1445 Args:
1446 maxval (int): The new maximum value for the slider.
1447 """
1448 self.maxval = maxval
1449 self.Refresh()
1450
1451 @property
1452 def Max(self):
1453 """Get the maximum value of the slider.
1454
1455 Returns:
1456 int: The maximum value of the slider.
1457 """
1458 return self.GetMax()
1459
1460 @Max.setter
1461 def Max(self, value):
1462 """Set the maximum value of the slider.
1463
1464 Args:
1465 value (int): The new maximum value for the slider.
1466 """
1467 self.SetMax(value)
1468
1469 def focus_handler(self, event):
1470 """Handle focus events to update the focus state.
1471
1472 Args:
1473 event (wx.Event): The focus event that triggered the handler.
1474 """
1475 self._hasfocus = event.GetEventType() == wx.EVT_SET_FOCUS.evtType[0]
1476
1477 def key_handler(self, event):
1478 """Handle key events to spin the slider value.
1479
1480 Args:
1481 event (wx.Event): The key event that triggered the handler.
1482 """
1483 if event.KeyCode in (wx.WXK_RIGHT, wx.WXK_NUMPAD_RIGHT):
1484 self._spin(1)
1485 elif event.KeyCode in (wx.WXK_LEFT, wx.WXK_NUMPAD_LEFT):
1486 self._spin(-1)
1487 else:
1488 event.Skip()
1489
1490 def mousewheel_handler(self, event):
1491 """Handle mouse wheel events to spin the slider value.
1492
1493 Args:
1494 event (wx.Event): The mouse wheel event that triggered the handler.
1495 """
1496 self._spin(event.GetWheelRotation())
1497
1498 def _spin(self, direction):
1499 inc = (self.maxval - self.minval) / self.ClientSize[0]
1500 if direction > 0:
1501 if self.Value < self.maxval:
1502 self.Value += inc
1503 elif self.Value > self.minval:
1504 self.Value -= inc
1505 self._mainFrame.area_handler()
1506
1507
1508 class NumSpin(wx_Panel):
1509 """A numeric spinner using IntCtrl and up/down buttons.
1510
1511 It is a replacement for wx.SpinCtrl that uses a custom IntCtrl instead of
1512 the default one. It also supports mouse wheel scrolling and keyboard input.
1513 """
1514
1515 def __init__(self, parent, id=-1, *args, **kwargs): # noqa: A002
1516 wx_Panel.__init__(self, parent)
1517 self.BackgroundColour = "#404040"
1518 self.Sizer = wx.BoxSizer(wx.HORIZONTAL)
1519 self.numctrl = IntCtrl(self, -1, *args, **kwargs)
1520 self.numctrl.BackgroundColour = self.BackgroundColour
1521 self.numctrl.SetColors("#999999", "#CC0000")
1522 self.numctrl.Bind(wx.EVT_KEY_DOWN, self.key_handler)
1523 self.numctrl.Bind(wx.EVT_MOUSEWHEEL, self.mousewheel_handler)
1524 self.Sizer.Add(self.numctrl, 1, wx.ALIGN_CENTER_VERTICAL | wx.ALL, s(5))
1525 vsizer = wx.BoxSizer(wx.VERTICAL)
1526 self.Sizer.Add(vsizer, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, s(2))
1527 self.spinup = BasePyButton(self, get_icon(10, "spin_up"))
1528 self.spinup.BackgroundColour = self.BackgroundColour
1529 self.spinup.Bind(wx.EVT_LEFT_DOWN, self.left_down_handler)
1530 self.spinup.Bind(wx.EVT_LEFT_UP, self.left_up_handler)
1531 vsizer.Add(self.spinup, 0, wx.BOTTOM, s(1))
1532 self.spindn = BasePyButton(self, get_icon(10, "spin_down"))
1533 self.spindn.BackgroundColour = self.BackgroundColour
1534 self.spindn.Bind(wx.EVT_LEFT_DOWN, self.left_down_handler)
1535 self.spindn.Bind(wx.EVT_LEFT_UP, self.left_up_handler)
1536 vsizer.Add(self.spindn, 0, wx.ALIGN_TOP | wx.TOP, s(1))
1537 self._left_down_count = 0
1538 self._left_up_count = 0
1539
1540 def __getattr__(self, name) -> Any:
1541 """Get the attribute from the IntCtrl.
1542
1543 Args:
1544 name (str): The name of the attribute to get.
1545
1546 Returns:
1547 Any: The value of the attribute from the IntCtrl.
1548 """
1549 return getattr(self.numctrl, name)
1550
1551 def is_button_pressed(self, btn):
1552 """Check if the button is pressed and the mouse is within its bounds.
1553
1554 Args:
1555 btn (BasePyButton): The button to check.
1556
1557 Returns:
1558 bool: True if the button is pressed and the mouse is within its bounds,
1559 False otherwise.
1560 """
1561 return (
1562 btn.Enabled
1563 and btn.HasCapture()
1564 and btn.ClientRect.Contains(btn.ScreenToClient(wx.GetMousePosition()))
1565 )
1566
1567 def left_down_handler(self, event):
1568 """Handle the left button down event for the spin buttons.
1569
1570 Args:
1571 event (wx.Event): The event that triggered the handler.
1572 """
1573 self._left_down_count += 1
1574 if self._capture_mouse(event):
1575 if event.GetEventObject() is self.spinup:
1576 self._spin(1, event, bell=False)
1577 else:
1578 self._spin(-1, event, bell=False)
1579 event.Skip()
1580
1581 def left_up_handler(self, event):
1582 """Handle the left button up event for the spin buttons.
1583
1584 Args:
1585 event (wx.Event): The event that triggered the handler.
1586 """
1587 self._left_up_count += 1
1588 while self._left_up_count > self._left_down_count:
1589 # Broken platform (wxMac?) :-(
1590 # print 'UP', self._left_up_count, 'DN', self._left_down_count
1591 self.left_down_handler(event)
1592 obj = event.GetEventObject()
1593 if obj.HasCapture():
1594 obj.ReleaseMouse()
1595 event.Skip()
1596
1597 def key_handler(self, event):
1598 """Handle key events to spin the IntCtrl value.
1599
1600 Args:
1601 event (wx.Event): The key event that triggered the handler.
1602 """
1603 if event.KeyCode in (wx.WXK_UP, wx.WXK_NUMPAD_UP):
1604 self._spin(1, event, bell=False)
1605 elif event.KeyCode in (wx.WXK_DOWN, wx.WXK_NUMPAD_DOWN):
1606 self._spin(-1, event, bell=False)
1607 else:
1608 event.Skip()
1609
1610 def mousewheel_handler(self, event):
1611 """Handle mouse wheel events to spin the IntCtrl value.
1612
1613 Args:
1614 event (wx.Event): The mouse wheel event that triggered the handler.
1615 """
1616 if event.GetWheelRotation() > 0:
1617 self._spin(1, event, bell=False)
1618 else:
1619 self._spin(-1, event, bell=False)
1620
1621 def _capture_mouse(self, event):
1622 """Capture the mouse if the event is valid and the control is enabled.
1623
1624 Args:
1625 event (wx.Event): The event that triggered the capture.
1626
1627 Returns:
1628 bool: True if the mouse was captured, False otherwise.
1629 """
1630 obj = event.GetEventObject()
1631 if obj.Enabled and not obj.HasCapture():
1632 point = wx.Point(event.GetX(), event.GetY())
1633 if obj.ClientRect.Contains(point):
1634 obj.CaptureMouse()
1635 return True
1636 return obj.Enabled and obj.HasCapture()
1637
1638 def _spin(self, inc, event, n=None, delay=500, bell=True):
1639 """Spin the IntCtrl value up or down.
1640
1641 Args:
1642 inc (int): The increment value, positive for up, negative for down.
1643 event (wx.Event): The event that triggered the spin.
1644 n (int, optional): The target value to set. If None, it will be
1645 calculated based on the current value and increment.
1646 delay (int, optional): The delay in milliseconds before the next
1647 spin action. Defaults to 500.
1648 bell (bool, optional): Whether to ring the bell if the value cannot
1649 be set. Defaults to True.
1650 """
1651 current = self.numctrl.GetValue()
1652 if n is None:
1653 n = current + inc
1654 btn = self.spinup if inc > 0 else self.spindn
1655 if event or self.is_button_pressed(btn):
1656 if n == current or (inc > 0 and n < current) or (inc < 0 and n > current):
1657 # print '!_spin', current, inc, n, delay, bell
1658 pass
1659 elif self.numctrl.GetMin() <= n <= self.numctrl.GetMax():
1660 # print '_spin', current, inc, n, delay, bell
1661 self.SetValue(n)
1662 elif bell:
1663 wx.Bell()
1664 if btn.Enabled and btn.HasCapture():
1665 current = self.numctrl.GetValue()
1666 wx.CallLater(delay, self._spin, inc, None, current + inc, 100)
1667
1668 def GetValue(self):
1669 """Get the value of the IntCtrl.
1670
1671 Returns:
1672 int: The current value of the IntCtrl.
1673 """
1674 return self.numctrl.GetValue()
1675
1676 def SetValue(self, value):
1677 """Set the value of the IntCtrl and update the spin buttons accordingly.
1678
1679 Args:
1680 value (int): The value to set in the IntCtrl.
1681 """
1682 self.numctrl.SetValue(value)
1683 if self.numctrl.GetMax() <= value:
1684 self.spinup.HasCapture() and self.spinup.ReleaseMouse()
1685 if self.numctrl.GetMin() >= value:
1686 self.spindn.HasCapture() and self.spindn.ReleaseMouse()
1687 self.spinup.Enable(self.numctrl.GetMax() > value)
1688 self.spindn.Enable(self.numctrl.GetMin() < value)
1689
1690 @property
1691 def Value(self):
1692 """Get or set the value of the IntCtrl.
1693
1694 Returns:
1695 int: The current value of the IntCtrl.
1696 """
1697 return self.GetValue()
1698
1699 @Value.setter
1700 def Value(self, value):
1701 self.SetValue(value)
1702
1703
1704 class ProfileManager:
1705 """Manage profiles associated with the display that a window is on.
1706
1707 Clears calibration on the display we're on, and restores it when moved
1708 to another display or the window is closed.
1709
1710 """
1711
1712 managers: ClassVar[list] = []
1713
1714 def __init__(self, window, geometry=None, profile=None):
1715 self._display = window.GetDisplay()
1716 self._lock = threading.Lock()
1717 self._profiles = {}
1718 self._srgb_profile = ICCProfile.from_named_rgb_space("sRGB")
1719 self._srgb_profile.setDescription(
1720 f"{APPNAME} Visual Whitepoint Editor Temporary Profile"
1721 )
1722 self._srgb_profile.calculate_id()
1723 self._window = window
1724 self._window.Bind(wx.EVT_CLOSE, self.window_close_handler)
1725 self._window.Bind(wx.EVT_MOVE, self.window_move_handler)
1726 self._window.Bind(wx.EVT_DISPLAY_CHANGED, self.display_changed_handler)
1727 self._worker = Worker()
1728 ProfileManager.managers.append(self)
1729 self.update(False)
1730 self._profiles_overridden = {}
1731 if geometry and profile:
1732 self._profiles_overridden[geometry] = profile
1733
1734 def _manage_display(self, display_no, geometry):
1735 # Has to be thread-safe!
1736 with self._lock:
1737 try:
1738 display_profile = get_display_profile(display_no)
1739 except (OSError, ICCProfileInvalidError, IndexError) as exception:
1740 print(
1741 f"Could not get display profile for display {display_no + 1}",
1742 f"@ {geometry[0]}, {geometry[1]}, {geometry[2]}x{geometry[3]}:",
1743 exception,
1744 )
1745 else:
1746 profile = self._profiles_overridden.get(geometry)
1747 if not profile:
1748 profile = display_profile
1749 if display_profile and display_profile.ID != self._srgb_profile.ID:
1750 # Set initial whitepoint according to vcgt
1751 # Convert calibration information from embedded WCS
1752 # profile (if present) to VideCardGammaType if the
1753 # latter is not present
1754 if (
1755 isinstance(profile.tags.get("MS00"), WcsProfilesTagType)
1756 and "vcgt" not in profile.tags
1757 ):
1758 profile.tags["vcgt"] = profile.tags["MS00"].get_vcgt()
1759 if isinstance(profile.tags.get("vcgt"), VideoCardGammaType):
1760 values = profile.tags.vcgt.getNormalizedValues()
1761 (
1762 self._window._colour.r,
1763 self._window._colour.g,
1764 self._window._colour.b,
1765 ) = (round(values[-1][i] * 255) for i in range(3))
1766 self._window._colour.ToHSV()
1767 wx.CallAfter(self._window.DrawAll)
1768 # Remember profile, but discard profile filename
1769 # (Important - can't re-install profile from same path
1770 # where it is installed!)
1771 if not self._set_profile_temp_filename(display_profile):
1772 return
1773 self._profiles[geometry] = display_profile
1774 self._install_profile(display_no, self._srgb_profile)
1775
1776 def _install_profile(self, display_no, profile, wrapup=False):
1777 # Has to be thread-safe!
1778 if self._window.patterngenerator:
1779 return
1780 dispwin = get_argyll_util("dispwin")
1781 if not dispwin:
1782 _show_result_after(Error(lang.getstr("argyll.util.not_found", "dispwin")))
1783 return
1784 if not profile.filename or not os.path.isfile(profile.filename):
1785 if not self._set_profile_temp_filename(profile):
1786 return
1787 profile.write()
1788 result = self._worker.exec_cmd(
1789 dispwin,
1790 ["-v", f"-d{display_no + 1}", "-I", profile.filename],
1791 capture_output=True,
1792 dry_run=False,
1793 )
1794 if not result:
1795 result = UnloggedError("".join(self._worker.errors))
1796 if isinstance(result, Exception):
1797 _show_result_after(result, wrap=120)
1798 if wrapup:
1799 self._worker.wrapup(False) # Remove temporary profiles
1800 ProfileManager.managers.remove(self)
1801
1802 def _install_profile_locked(self, display_no, profile, wrapup=False):
1803 # Has to be thread-safe!
1804 with self._lock:
1805 self._install_profile(display_no, profile, wrapup)
1806
1807 def _set_profile_temp_filename(self, profile):
1808 temp = self._worker.create_tempdir()
1809 if isinstance(temp, Exception):
1810 _show_result_after(temp)
1811 return None
1812 if profile.filename:
1813 profile_name = os.path.basename(profile.filename)
1814 else:
1815 profile_name = profile.getDescription() + PROFILE_EXT
1816 if (
1817 sys.platform in ("win32", "darwin")
1818 or FS_ENC.upper() not in ("UTF8", "UTF-8")
1819 ) and re.search(r"[^\x20-\x7e]", profile_name):
1820 profile_name = safe_asciize(profile_name)
1821 profile.filename = os.path.join(temp, profile_name)
1822 return True
1823
1824 def _stop_timer(self):
1825 if hasattr(self, "_update_timer") and self._update_timer.IsRunning():
1826 self._update_timer.Stop()
1827
1828 def update(self, restore_display_profiles=True):
1829 """Update the display manager.
1830
1831 Clear calibration on the current display, and restore it on the
1832 previous one (if any)
1833
1834 Args:
1835 restore_display_profiles (bool): Whether to restore display
1836 profiles when the display changes.
1837 """
1838 if restore_display_profiles:
1839 self.restore_display_profiles()
1840 display_no = get_argyll_display_number(self._display.Geometry)
1841 if display_no is not None:
1842 geometry = self._display.Geometry.Get()
1843 threading.Thread(
1844 target=self._manage_display,
1845 name=(
1846 f"VisualWhitepointEditor.DisplayManager[Display {display_no} @ "
1847 f"{geometry[0]}, {geometry[1]}, {geometry[2]}x{geometry[3]}]"
1848 ),
1849 args=(display_no, geometry),
1850 ).start()
1851 if not self._window.patterngenerator:
1852 display_name = get_display_name(display_no, True)
1853 if display_name:
1854 display_name = display_name.replace(
1855 "[PRIMARY]", lang.getstr("display.primary")
1856 )
1857 self._window.SetTitle(
1858 f"{display_name} - {lang.getstr('whitepoint.visual_editor')}"
1859 )
1860 else:
1861 msg = lang.getstr("whitepoint.visual_editor.display_changed.warning")
1862 print(msg)
1863
1864 def restore_display_profiles(self, wrapup=False, wait=False):
1865 """Reinstall memorized display profiles, restore calibration."""
1866 while self._profiles:
1867 geometry, profile = self._profiles.popitem()
1868 display_no = get_argyll_display_number(geometry)
1869 if display_no is not None:
1870 thread = threading.Thread(
1871 target=self._install_profile_locked,
1872 name="VisualWhitepointEditor.ProfileInstallation[Display"
1873 f" {display_no} @ "
1874 f"{geometry[0]}, {geometry[1]}, {geometry[2]}x{geometry[3]}]",
1875 args=(display_no, profile, wrapup),
1876 )
1877 thread.start()
1878 if wait:
1879 thread.join()
1880 else:
1881 msg = lang.getstr("whitepoint.visual_editor.display_changed.warning")
1882 print(msg)
1883
1884 def display_changed_handler(self, event):
1885 """Handle the ``wx.EVT_DISPLAY_CHANGED`` event.
1886
1887 Args:
1888 event: a :class:`DisplayEvent` event to be processed.
1889 """
1890
1891 # Houston, we (may) have a problem! Memorized profile associations may
1892 # no longer be correct.
1893 def warn_update():
1894 msg = lang.getstr("whitepoint.visual_editor.display_changed.warning")
1895 show_result_dialog(Warn(msg))
1896 self and self.update()
1897
1898 wx.CallLater(1000, warn_update)
1899
1900 def window_close_handler(self, event):
1901 """Restore profile(s) when the managed window is closed."""
1902 self._stop_timer()
1903 self.restore_display_profiles(True, True)
1904 event.Skip()
1905
1906 def window_move_handler(self, event):
1907 """Handle the ``wx.EVT_MOVE`` event.
1908
1909 Clear calibration on the current display, and restore it on the
1910 previous one (if any) when the window is moved from one to another
1911 display.
1912
1913 Args:
1914 event (wx.Event): The move event that triggered the handler.
1915 """
1916 display = self._window.GetDisplay()
1917 if not self._display or display.Geometry != self._display.Geometry:
1918 self._display = display
1919 self._stop_timer()
1920
1921 def update():
1922 self._window and self.update()
1923
1924 self._update_timer = wx.CallLater(50, update)
1925 event.Skip()
1926
1927
1928 class VisualWhitepointEditor(wx.Frame):
1929 """VisualWhitepointEditor main class implementation.
1930
1931 Args:
1932 parent (wx.Window): The parent window.
1933 colourData (ColourData): A standard :class:`ColourData` (as used in
1934 :class:`ColourFrame`) to hide the alpha channel control or not.
1935 title (str): The title of the window.
1936 pos (wx.Point): The position of the window.
1937 patterngenerator (Patterngenerator): A patterngenerator object.
1938 geometry (tuple): The geometry of the display the profile is assigned to.
1939 profile (ICCProfile): The profile of the display with the given geometry.
1940 """
1941
1942 def __init__(
1943 self,
1944 parent,
1945 colourData=None,
1946 title=wx.EmptyString,
1947 pos=wx.DefaultPosition,
1948 patterngenerator=None,
1949 geometry=None,
1950 profile=None,
1951 ):
1952 self.patterngenerator = patterngenerator
1953 self.update_patterngenerator_event = threading.Event()
1954
1955 style = wx.DEFAULT_FRAME_STYLE
1956 if patterngenerator:
1957 style &= ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)
1958
1959 wx.Frame.__init__(
1960 self,
1961 parent,
1962 id=wx.ID_ANY,
1963 title=title or lang.getstr("whitepoint.visual_editor"),
1964 pos=pos,
1965 style=style,
1966 name="VisualWhitepointEditor",
1967 )
1968
1969 if not patterngenerator:
1970 self._mgr = AuiManagerLRDocking(
1971 self,
1972 aui.AUI_MGR_DEFAULT
1973 | aui.AUI_MGR_LIVE_RESIZE
1974 | aui.AUI_MGR_SMOOTH_DOCKING,
1975 )
1976 self._mgr.SetArtProvider(AuiDarkDockArt())
1977
1978 self.SetIcons(get_icon_bundle([256, 48, 32, 16], APPNAME))
1979
1980 if colourData:
1981 self._colourData = colourData
1982 else:
1983 self._colourData = wx.ColourData()
1984 RGB = [
1985 getcfg(f"whitepoint.visual_editor.{attribute}") for attribute in "rgb"
1986 ]
1987 self._colourData.SetColour(wx.Colour(*RGB))
1988
1989 self._colour = Colour(self._colourData.GetColour())
1990 self._bgcolour = Colour(self._colourData.GetColour())
1991 self._bgcolour.v = getcfg("whitepoint.visual_editor.bg_v")
1992 self._bgcolour.ToRGB()
1993
1994 self._inMouse = False
1995 self._initOver = False
1996 self._inDrawAll = False
1997
1998 self.mainPanel = wx_Panel(self, -1)
1999 self.mainPanel.BackgroundColour = "#333333"
2000 self.mainPanel.ForegroundColour = "#999999"
2001 self.bgPanel = wx_Panel(self, -1)
2002 self.bgPanel.Show(not patterngenerator)
2003
2004 self.hsvBitmap = HSVWheel(self.mainPanel, self.mainPanel.BackgroundColour)
2005 self.brightCtrl = BrightCtrl(self.mainPanel)
2006 self.brightCtrl.BackgroundColour = self.mainPanel.BackgroundColour
2007 self.bgBrightCtrl = BrightCtrl(self.mainPanel, self._bgcolour)
2008 self.bgBrightCtrl.BackgroundColour = self.mainPanel.BackgroundColour
2009 if sys.platform == "win32" and sys.getwindowsversion() >= (6,):
2010 # No need to enable double buffering under Linux and Mac OS X.
2011 # Under Windows, enabling double buffering on the panel seems
2012 # to work best to reduce flicker.
2013 self.mainPanel.SetDoubleBuffered(True)
2014 self.bgPanel.SetDoubleBuffered(True)
2015
2016 self.newColourPanel = wx_Panel(self.bgPanel, style=wx.SIMPLE_BORDER)
2017
2018 self.redSpin = NumSpin(
2019 self.mainPanel, -1, min=0, max=255, style=wx.NO_BORDER | wx.ALIGN_RIGHT
2020 )
2021 self.greenSpin = NumSpin(
2022 self.mainPanel, -1, min=0, max=255, style=wx.NO_BORDER | wx.ALIGN_RIGHT
2023 )
2024 self.blueSpin = NumSpin(
2025 self.mainPanel, -1, min=0, max=255, style=wx.NO_BORDER | wx.ALIGN_RIGHT
2026 )
2027 self.hueSpin = NumSpin(
2028 self.mainPanel, -1, min=0, max=359, style=wx.NO_BORDER | wx.ALIGN_RIGHT
2029 )
2030 self.saturationSpin = NumSpin(
2031 self.mainPanel, -1, min=0, max=255, style=wx.NO_BORDER | wx.ALIGN_RIGHT
2032 )
2033 self.brightnessSpin = NumSpin(
2034 self.mainPanel, -1, min=0, max=255, style=wx.NO_BORDER | wx.ALIGN_RIGHT
2035 )
2036 self.reset_btn = FlatShadedButton(
2037 self.mainPanel, -1, label=lang.getstr("reset"), fgcolour="#999999"
2038 )
2039 x, y, scale = (
2040 float(v)
2041 for v in getcfg("dimensions.measureframe.whitepoint.visual_editor").split(
2042 ","
2043 )
2044 )
2045
2046 self.area_size_slider = HSlider(
2047 self.mainPanel, min(scale * 100, 1000), 10, 1000, self.area_handler
2048 )
2049
2050 self.display_size_mm = {}
2051 self.set_area_size_slider_max()
2052 self.set_default_size()
2053
2054 self.area_size_slider.BackgroundColour = self.mainPanel.BackgroundColour
2055
2056 size = (16, 16) if "gtk3" in wx.PlatformInfo else (-1, -1)
2057 self.zoomnormalbutton = BitmapButton(
2058 self.mainPanel,
2059 -1,
2060 get_icon(16, "zoom-original-outline"),
2061 size=size,
2062 style=wx.NO_BORDER,
2063 )
2064 self.zoomnormalbutton.BackgroundColour = self.mainPanel.BackgroundColour
2065 self.Bind(wx.EVT_BUTTON, self.zoomnormal_handler, self.zoomnormalbutton)
2066 self.zoomnormalbutton.SetToolTipString(lang.getstr("measureframe.zoomnormal"))
2067 self.area_x_slider = HSlider(
2068 self.mainPanel, round(x * 1000), 0, 1000, self.area_handler
2069 )
2070 self.area_x_slider.BackgroundColour = self.mainPanel.BackgroundColour
2071 self.center_x_button = BitmapButton(
2072 self.mainPanel,
2073 -1,
2074 get_icon(16, "window-center-outline"),
2075 size=size,
2076 style=wx.NO_BORDER,
2077 )
2078 self.center_x_button.BackgroundColour = self.mainPanel.BackgroundColour
2079 self.Bind(wx.EVT_BUTTON, self.center_x_handler, self.center_x_button)
2080 self.center_x_button.SetToolTipString(lang.getstr("measureframe.center"))
2081 self.area_y_slider = HSlider(
2082 self.mainPanel, round(y * 1000), 0, 1000, self.area_handler
2083 )
2084 self.area_y_slider.BackgroundColour = self.mainPanel.BackgroundColour
2085 self.center_y_button = BitmapButton(
2086 self.mainPanel,
2087 -1,
2088 get_icon(16, "window-center-outline"),
2089 size=size,
2090 style=wx.NO_BORDER,
2091 )
2092 self.center_y_button.BackgroundColour = self.mainPanel.BackgroundColour
2093 self.Bind(wx.EVT_BUTTON, self.center_y_handler, self.center_y_button)
2094 self.center_y_button.SetToolTipString(lang.getstr("measureframe.center"))
2095 self.measure_btn = FlatShadedButton(
2096 self.mainPanel,
2097 -1,
2098 label=lang.getstr("measure"),
2099 name="visual_whitepoint_editor_measure_btn",
2100 fgcolour="#999999",
2101 )
2102 self.measure_btn.SetDefault()
2103
2104 self.Bind(wx.EVT_SIZE, self.size_handler)
2105
2106 self.SetProperties()
2107 self.DoLayout()
2108
2109 self.spinCtrls = [
2110 self.redSpin,
2111 self.greenSpin,
2112 self.blueSpin,
2113 self.hueSpin,
2114 self.saturationSpin,
2115 self.brightnessSpin,
2116 ]
2117
2118 for spin in self.spinCtrls:
2119 spin.Bind(wx.EVT_TEXT, self.OnSpinCtrl)
2120
2121 self.reset_btn.Bind(wx.EVT_BUTTON, self.reset_handler)
2122
2123 self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
2124 self.Bind(wx.EVT_SHOW, self.show_handler)
2125 self.Bind(wx.EVT_MAXIMIZE, self.maximize_handler)
2126 self.Bind(wx.EVT_CHAR_HOOK, self.OnKeyDown)
2127
2128 # Set up panes
2129 self.mainPanel.Fit()
2130 mainPanelSize = (self.mainPanel.Size[0], self.mainPanel.Size[1] + s(10))
2131 if not patterngenerator:
2132 self._mgr.AddPane(
2133 self.mainPanel,
2134 aui.AuiPaneInfo()
2135 .Name("mainPanel")
2136 .Fixed()
2137 .Left()
2138 .TopDockable(False)
2139 .BottomDockable(False)
2140 .PaneBorder(False)
2141 .CloseButton(False)
2142 .PinButton(True)
2143 .MinSize(mainPanelSize),
2144 )
2145 self._mgr.AddPane(
2146 self.bgPanel,
2147 aui.AuiPaneInfo()
2148 .Name("bgPanel")
2149 .CenterPane()
2150 .CloseButton(False)
2151 .PaneBorder(False),
2152 )
2153 self._mgr.Update()
2154
2155 self.Bind(aui.EVT_AUI_PANE_CLOSE, self.close_pane_handler)
2156 self.Bind(aui.EVT_AUI_PANE_FLOATED, self.float_pane_handler)
2157 self.Bind(aui.EVT_AUI_PANE_DOCKED, self.float_pane_handler)
2158
2159 # Account for pane titlebar
2160 self.Sizer.SetSizeHints(self)
2161 self.Sizer.Layout()
2162 if not patterngenerator:
2163 if hasattr(self, "MinClientSize"):
2164 # wxPython 2.9+
2165 minClientSize = self.MinClientSize
2166 else:
2167 minClientSize = self.WindowToClientSize(self.MinSize)
2168 w, h = self.newColourPanel.Size
2169 self.ClientSize = (
2170 mainPanelSize[0] + w + s(26),
2171 max(minClientSize[1], h + s(26)),
2172 )
2173 if sys.platform not in ("win32", "darwin"):
2174 correction = s(40)
2175 else:
2176 correction = 0
2177 w, h = (round(self.default_size),) * 2
2178 minClientSize = (
2179 mainPanelSize[0] + max(minClientSize[1], w + s(26)),
2180 max(minClientSize[1], h + s(26)) + correction,
2181 )
2182 if hasattr(self, "MinClientSize"):
2183 # wxPython 2.9+
2184 self.MinClientSize = minClientSize
2185 else:
2186 self.MinSize = self.ClientToWindowSize(minClientSize)
2187
2188 x, y = self.Position
2189 w, h = self.Size
2190
2191 if not patterngenerator and (
2192 self.newColourPanel.Size[0]
2193 > min(
2194 self.bgPanel.Size[0], self.GetDisplay().ClientArea[2] - mainPanelSize[0]
2195 )
2196 or self.newColourPanel.Size[1]
2197 > min(self.bgPanel.Size[1], self.GetDisplay().ClientArea[3])
2198 ):
2199 w, h = self.GetDisplay().ClientArea[2:]
2200
2201 self.SetSaneGeometry(x, y, w, h)
2202
2203 if patterngenerator:
2204 self.update_patterngenerator_thread = threading.Thread(
2205 target=update_patterngenerator,
2206 name="VisualWhitepointEditorPatternGeneratorUpdateThread",
2207 args=(self,),
2208 )
2209 self.update_patterngenerator_thread.start()
2210
2211 self._pm = ProfileManager(self, geometry, profile)
2212 self.Bind(wx.EVT_MOVE, self.move_handler)
2213
2214 wx.CallAfter(self.InitFrame)
2215
2216 self.keepGoing = True
2217
2218 self.measure_btn.Bind(wx.EVT_BUTTON, self.measure)
2219
2220 def SetProperties(self):
2221 """Set some initial properties (sizes, values)."""
2222 min_w = self.redSpin.numctrl.GetTextExtent("255")[0] + s(30)
2223 self.redSpin.SetMinSize((min_w, -1))
2224 self.greenSpin.SetMinSize((min_w, -1))
2225 self.blueSpin.SetMinSize((min_w, -1))
2226 self.hueSpin.SetMinSize((min_w, -1))
2227 self.saturationSpin.SetMinSize((min_w, -1))
2228 self.brightnessSpin.SetMinSize((min_w, -1))
2229
2230 def DoLayout(self):
2231 """Layout all the controls in the :class:`VisualWhitepointEditor`."""
2232 margin = s(12)
2233
2234 dialogSizer = wx.FlexGridSizer(1, 2, 0, 0)
2235 dialogSizer.AddGrowableRow(0)
2236 dialogSizer.AddGrowableCol(1)
2237 mainSizer = wx.BoxSizer(wx.VERTICAL)
2238
2239 shadow = HStretchStaticBitmap(
2240 self.mainPanel, -1, get_bitmap("theme/shadow-bordertop")
2241 )
2242 mainSizer.Add(shadow, 0, wx.EXPAND)
2243 label = wx.StaticText(self.mainPanel, -1, lang.getstr("whitepoint"))
2244 label.SetMaxFontSize(11)
2245 font = label.Font
2246 font.SetWeight(wx.FONTWEIGHT_BOLD)
2247 label.Font = font
2248 mainSizer.Add(label, 0, wx.LEFT, margin)
2249
2250 hsvGridSizer = wx.GridSizer(2, 3, margin, margin)
2251 hsvSizer = wx.BoxSizer(wx.HORIZONTAL)
2252
2253 hsvSizer.Add(self.hsvBitmap, 0, wx.ALL, margin)
2254 hsvSizer.Add(self.brightCtrl, 0, wx.TOP | wx.BOTTOM, margin + s(5) + 2)
2255 hsvSizer.Add((margin + s(5), 1))
2256 hsvSizer.Add(self.bgBrightCtrl, 0, wx.TOP | wx.BOTTOM, margin + s(5) + 2)
2257 hsvSizer.Add((margin + s(5), 1))
2258 mainSizer.Add(hsvSizer, 0, wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER, margin)
2259
2260 for channel in ("red", "green", "blue", "hue", "saturation", "brightness"):
2261 label = wx.StaticText(self.mainPanel, -1, lang.getstr(channel))
2262 label.SetMaxFontSize(11)
2263 sizer = wx.BoxSizer(wx.VERTICAL)
2264 sizer.Add(label)
2265 sizer.Add(getattr(self, channel + "Spin"), 0, wx.TOP | wx.EXPAND, s(4))
2266 hsvGridSizer.Add(sizer, 0, wx.EXPAND)
2267 mainSizer.Add(hsvGridSizer, 0, wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER, margin)
2268 mainSizer.Add(self.reset_btn, 0, wx.ALL | wx.ALIGN_CENTER, margin)
2269
2270 shadow = HStretchStaticBitmap(
2271 self.mainPanel, -1, get_bitmap("theme/shadow-bordertop")
2272 )
2273 mainSizer.Add(shadow, 0, wx.EXPAND, margin)
2274 area_slider_label = wx.StaticText(
2275 self.mainPanel, -1, lang.getstr("measureframe.title")
2276 )
2277 area_slider_label.SetMaxFontSize(11)
2278 font = area_slider_label.Font
2279 font.SetWeight(wx.FONTWEIGHT_BOLD)
2280 area_slider_label.Font = font
2281 mainSizer.Add(area_slider_label, 0, wx.LEFT | wx.BOTTOM, margin)
2282 vmargin = margin if "gtk3" in wx.PlatformInfo else s(6)
2283 slider_sizer = wx.FlexGridSizer(3, 3, vmargin, margin)
2284 slider_sizer.AddGrowableCol(1)
2285 mainSizer.Add(slider_sizer, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, margin)
2286 area_size_label = wx.StaticText(self.mainPanel, -1, lang.getstr("size"))
2287 area_size_label.SetMaxFontSize(11)
2288 slider_sizer.Add(area_size_label, 0, wx.ALIGN_CENTER_VERTICAL)
2289 slider_sizer.Add(self.area_size_slider, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
2290 slider_sizer.Add(self.zoomnormalbutton, 0, wx.ALIGN_CENTER_VERTICAL)
2291 area_x_label = wx.StaticText(self.mainPanel, -1, "X")
2292 area_x_label.SetMaxFontSize(11)
2293 slider_sizer.Add(area_x_label, 0, wx.ALIGN_CENTER_VERTICAL)
2294 slider_sizer.Add(self.area_x_slider, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
2295 slider_sizer.Add(self.center_x_button, 0, wx.ALIGN_CENTER_VERTICAL)
2296 area_y_label = wx.StaticText(self.mainPanel, -1, "Y")
2297 area_y_label.SetMaxFontSize(11)
2298 slider_sizer.Add(area_y_label, 0, wx.ALIGN_CENTER_VERTICAL)
2299 slider_sizer.Add(self.area_y_slider, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
2300 slider_sizer.Add(self.center_y_button, 0, wx.ALIGN_CENTER_VERTICAL)
2301 mainSizer.Add(self.measure_btn, 0, wx.ALL | wx.ALIGN_CENTER, margin)
2302
2303 self.mainPanel.SetAutoLayout(True)
2304 self.mainPanel.SetSizer(mainSizer)
2305 mainSizer.Fit(self.mainPanel)
2306 mainSizer.SetSizeHints(self.mainPanel)
2307
2308 dialogSizer.Add(self.mainPanel, 0, wx.EXPAND)
2309 if self.bgPanel.IsShown():
2310 dialogSizer.Add(self.bgPanel, 1, wx.EXPAND, 0)
2311 self.SetAutoLayout(True)
2312 self.SetSizer(dialogSizer)
2313 dialogSizer.Fit(self)
2314 dialogSizer.SetSizeHints(self)
2315 self.Layout()
2316
2317 self.mainSizer = mainSizer
2318 self.dialogSizer = dialogSizer
2319
2320 def InitFrame(self):
2321 """Initialize the :class:`VisualWhitepointEditor`."""
2322 hsvRect = self.hsvBitmap.GetClientRect()
2323 self._centre = wx.Point(
2324 int(hsvRect.x + hsvRect.width / 2), int(hsvRect.y + hsvRect.height / 2)
2325 )
2326
2327 self.CalcRects()
2328
2329 self.SetSpinVals()
2330
2331 self._initOver = True
2332 wx.CallAfter(self.Refresh)
2333
2334 def show_handler(self, event):
2335 """Handle the ``wx.EVT_SHOW`` event for :class:`VisualWhitepointEditor`.
2336
2337 Args:
2338 event: a :class:`ShowEvent` event to be processed.
2339 """
2340 if (
2341 not self.patterngenerator
2342 and getattr(event, "IsShown", getattr(event, "GetShow", bool))()
2343 and sys.platform == "darwin"
2344 and intlist(platform.mac_ver()[0].split(".")) >= [10, 10]
2345 ):
2346 # Under Yosemite and up, if users use the default titlebar zoom
2347 # button to go fullscreen, they will be left with a black screen
2348 # after the window has been closed (shortcoming of wxMac).
2349 # It is possible to switch back to normal view by alt-tabbing,
2350 # but users need to be made aware of it.
2351 wx.CallAfter(
2352 self.notify,
2353 wrap(lang.getstr("fullscreen.osx.warning"), 80),
2354 icon=get_icon(32, "dialog-warning"),
2355 timeout=0,
2356 )
2357 event.Skip()
2358
2359 def CalcRects(self):
2360 """Calculate the brightness control user-selected rect."""
2361 RECT_WIDTH = s(5)
2362
2363 pt = self.PtFromAngle(self._colour.h, self._colour.s, self._centre)
2364 self._currentRect = wx.Rect(
2365 pt.x - RECT_WIDTH, pt.y - RECT_WIDTH, 2 * RECT_WIDTH, 2 * RECT_WIDTH
2366 )
2367
2368 def DrawMarkers(self, dc=None):
2369 """Draw the markers for all the controls.
2370
2371 Args:
2372 dc (DC): If `dc` is ``None``, a :class:`ClientDC` is created on the
2373 fly.
2374 """
2375 self.hsvBitmap.DrawMarkers(dc)
2376 self.brightCtrl.DrawMarkers(dc)
2377 self.bgBrightCtrl.DrawMarkers(dc)
2378
2379 def DrawHSB(self):
2380 """Refreshe the HSB colour wheel."""
2381 self.hsvBitmap.Refresh()
2382
2383 def DrawBright(self):
2384 """Refreshe the brightness control."""
2385 self.brightCtrl.Refresh()
2386 self.bgBrightCtrl.Refresh()
2387
2388 def SetSpinVals(self):
2389 """Set the values for all the spin controls."""
2390 self.redSpin.SetValue(self._colour.r)
2391 self.greenSpin.SetValue(self._colour.g)
2392 self.blueSpin.SetValue(self._colour.b)
2393
2394 self.hueSpin.SetValue(self._colour.h)
2395 self.saturationSpin.SetValue(self._colour.s)
2396 self.brightnessSpin.SetValue(self._colour.v)
2397
2398 self.SetPanelColours()
2399 self.update_patterngenerator()
2400
2401 def update_patterngenerator(self):
2402 """Update the patterngenerator configuration if it is available."""
2403 if self.patterngenerator:
2404 size = min(
2405 (
2406 self.area_size_slider.GetValue()
2407 / float(
2408 self.area_size_slider.GetMax() - self.area_size_slider.GetMin()
2409 )
2410 ),
2411 1,
2412 )
2413 x = max(
2414 self.area_x_slider.GetValue()
2415 / float(self.area_x_slider.GetMax())
2416 * (1 - size),
2417 0,
2418 )
2419 y = max(
2420 self.area_y_slider.GetValue()
2421 / float(self.area_y_slider.GetMax())
2422 * (1 - size),
2423 0,
2424 )
2425 self.patterngenerator_config = x, y, size
2426 self.update_patterngenerator_event.set()
2427
2428 def SetPanelColours(self):
2429 """Assign colours to the colour panels."""
2430 self.newColourPanel.BackgroundColour = self._colour.GetPyColour()
2431 self._bgcolour.h = self._colour.h
2432 self._bgcolour.s = self._colour.s
2433 self._bgcolour.ToRGB()
2434 self.bgPanel.BackgroundColour = self._bgcolour.GetPyColour()
2435 self.bgPanel.Refresh()
2436
2437 def OnCloseWindow(self, event):
2438 """Handle the ``wx.EVT_CLOSE`` event for :class:`VisualWhitepointEditor`.
2439
2440 Args:
2441 event: a :class:`CloseEvent` event to be processed.
2442 """
2443 if self.IsFullScreen():
2444 self.ShowFullScreen(False)
2445 event.Skip()
2446
2447 def OnKeyDown(self, event):
2448 """Handle the ``wx.EVT_CHAR_HOOK`` event for :class:`VisualWhitepointEditor`.
2449
2450 Args:
2451 event: a :class:`KeyEvent` event to be processed.
2452 """
2453 if event.GetKeyCode() == wx.WXK_ESCAPE:
2454 if self.IsFullScreen():
2455 self.ShowFullScreen(False)
2456 self.Restore()
2457 else:
2458 self.Close()
2459 # elif event.KeyCode in (wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_UP, wx.WXK_DOWN):
2460 # self._colour.h += {
2461 # wx.WXK_LEFT: 1,
2462 # wx.WXK_RIGHT: -1,
2463 # wx.WXK_UP: 0,
2464 # wx.WXK_DOWN: 0
2465 # }[event.KeyCode]
2466 # if self._colour.h > 359:
2467 # self._colour.h = 0
2468 # elif self._colour.h < 0:
2469 # self._colour.h = 359
2470 # self._colour.s += {
2471 # wx.WXK_LEFT: 0,
2472 # wx.WXK_RIGHT: 0,
2473 # wx.WXK_UP: 1,
2474 # wx.WXK_DOWN: -1
2475 # }[event.KeyCode]
2476 # if self._colour.s > 255:
2477 # self._colour.s = 255
2478 # elif self._colour.s < 0:
2479 # self._colour.s = 0
2480 # print(self._colour.h, self._colour.s)
2481 # self._colour.ToRGB()
2482 # self.DrawAll()
2483 else:
2484 event.Skip()
2485
2486 def PtFromAngle(self, angle, sat, center):
2487 """Return a point based on the angle and saturation.
2488
2489 Args:
2490 angle (float): a float representing an angle;
2491 sat (float): a float representing the colour saturation value;
2492 center (float): a float value representing the center.
2493
2494 Returns:
2495 wx.Point: A point calculated from the angle and saturation.
2496 """
2497 angle = deg2rad(angle)
2498 sat = min(
2499 sat * ((self.hsvBitmap._bitmap.Size[0] - s(12)) / 2) / 51.0,
2500 ((self.hsvBitmap._bitmap.Size[0] - s(12)) / 2),
2501 )
2502
2503 x = sat * cos(angle)
2504 y = sat * sin(angle)
2505
2506 pt = wx.Point(round(x), -round(y))
2507 pt.x += center.x
2508 pt.y += center.y
2509
2510 return pt
2511
2512 def OnSpinCtrl(self, event):
2513 """Handle the ``wx.EVT_SPINCTRL`` event for RGB and HSB colours.
2514
2515 Args:
2516 event: a :class:`SpinEvent` event to be processed.
2517 """
2518 obj = event.GetEventObject().Parent
2519 position = self.spinCtrls.index(obj)
2520 colourVal = event.GetString()
2521 try:
2522 colourVal = int(colourVal)
2523 except Exception:
2524 wx.Bell()
2525 return
2526
2527 attribute, maxVal = COLOUR_ATTRIBUTES[position], COLOUR_MAX_VALUES[position]
2528
2529 self.AssignColourValue(attribute, colourVal, maxVal, position)
2530
2531 def AssignColourValue(self, attribute, colourVal, maxVal, position):
2532 """Common code to handle spin control changes."""
2533 originalVal = getattr(self._colour, attribute)
2534 if colourVal != originalVal and self._initOver:
2535 colourVal = max(colourVal, 0)
2536 colourVal = min(colourVal, maxVal)
2537
2538 setattr(self._colour, attribute, colourVal)
2539 if position < 3:
2540 self._colour.ToHSV()
2541 else:
2542 self._colour.ToRGB()
2543
2544 self.DrawAll()
2545
2546 def DrawAll(self):
2547 """Draw all the custom controls after a colour change."""
2548 if self._initOver and not self._inDrawAll:
2549 self._inDrawAll = True
2550
2551 self.hsvBitmap.DrawMarkers()
2552
2553 self.brightCtrl.DrawMarkers()
2554
2555 self.CalcRects()
2556
2557 self.DrawHSB()
2558 self.DrawBright()
2559
2560 self.SetSpinVals()
2561 self._inDrawAll = False
2562
2563 def GetColourData(self):
2564 """Return a wxPython compatible :class:`ColourData`."""
2565 self._colourData.SetColour(self._colour.GetPyColour())
2566 return self._colourData
2567
2568 def GetRGBAColour(self) -> tuple[float, float, float, float]:
2569 """Return a tuple of red, green, blue, alpha components.
2570
2571 Returns:
2572 tuple[float, float, float, float]: A tuple containing the red, green,
2573 blue, and alpha components of the colour.
2574 """
2575 return (self._colour.r, self._colour.g, self._colour.b, self._colour._alpha)
2576
2577 def GetHSVAColour(self) -> tuple[float, float, float, float]:
2578 """Return a tuple of hue, saturation, brightness, alpha components.
2579
2580 Returns:
2581 tuple[float, float, float, float]: A tuple containing the hue, saturation,
2582 brightness, and alpha components of the colour.
2583 """
2584 return (self._colour.h, self._colour.s, self._colour.v, self._colour._alpha)
2585
2586 def EndModal(self, returncode=wx.ID_OK):
2587 """End the modal state of the :class:`VisualWhitepointEditor`.
2588
2589 Args:
2590 returncode (int): The return code to be used when ending the modal state.
2591 """
2592 return returncode
2593
2594 def MakeModal(self, modal=False):
2595 """Make the VisualWhitepointEditor modal or not.
2596
2597 Args:
2598 modal (bool): If ``True``, make the editor modal.
2599 """
2600
2601 def Pulse(self, msg=""):
2602 """Pulse the progress of the operation.
2603
2604 Args:
2605 msg (str): The message to be displayed during the pulse.
2606 """
2607 return self.keepGoing, False
2608
2609 def Resume(self):
2610 """Resume the pulse operation."""
2611 self.keepGoing = True
2612
2613 def UpdateProgress(self, value=None, msg=""):
2614 """Update the progress of the pulse with a message.
2615
2616 Args:
2617 value (int): The value to be set for the progress.
2618 msg (str): The message to be displayed.
2619 """
2620 return self.Pulse(msg)
2621
2622 def UpdatePulse(self, msg=""):
2623 """Update the pulse with a message.
2624
2625 Args:
2626 msg (str): The message to be displayed.
2627 """
2628 return self.Pulse(msg)
2629
2630 def area_handler(self, event=None):
2631 """Handle the area size and position sliders.
2632
2633 Args:
2634 event (Event): An event to be processed, if any.
2635 """
2636 scale = self.area_size_slider.Value / 100.0
2637 x = self.area_x_slider.Value / 1000.0
2638 y = self.area_y_slider.Value / 1000.0
2639 w, h = (round(self.default_size * scale),) * 2
2640 self.bgPanel.MinSize = -1, -1
2641 self.newColourPanel.Size = w, h
2642 self.bgPanel.MinSize = w + s(24), h + s(24)
2643 bg_w, bg_h = (float(v) for v in self.bgPanel.Size)
2644 self.newColourPanel.Position = (int((bg_w - (w)) * x)), int((bg_h - (h)) * y)
2645 if event:
2646 event.Skip()
2647 if event and event.GetEventType() == wx.EVT_SIZE.evtType[0]:
2648 wx.CallAfter(self.area_handler)
2649 else:
2650 self.bgPanel.Refresh()
2651 self.update_patterngenerator()
2652
2653 def center_x_handler(self, event):
2654 """Handle the centering of the X-axis area slider.
2655
2656 Args:
2657 event (ButtonEvent): A ButtonEvent event to be processed.
2658 """
2659 self.area_x_slider.SetValue(500)
2660 self.area_handler()
2661
2662 def center_y_handler(self, event):
2663 """Handle the centering of the Y-axis area slider.
2664
2665 Args:
2666 event (ButtonEvent): A ButtonEvent event to be processed.
2667 """
2668 self.area_y_slider.SetValue(500)
2669 self.area_handler()
2670
2671 def close_pane_handler(self, event):
2672 """Handle the closing of the main panel pane.
2673
2674 Args:
2675 event (AuiEvent): An AuiEvent event to be processed.
2676 """
2677 event.Veto() # Prevent closing of pane
2678 self.dock_pane()
2679
2680 def dock_pane(self):
2681 """Dock the main panel pane."""
2682 self._mgr.GetPane("mainPanel").Dock().CloseButton(False)
2683 self._mgr.Update()
2684 self.mainPanel.Refresh()
2685 self.area_handler()
2686
2687 def float_pane_handler(self, event):
2688 """Handle the floating of the main panel pane.
2689
2690 Args:
2691 event (AuiEvent): An AuiEvent event to be processed.
2692 """
2693 if event.GetEventType() == aui.EVT_AUI_PANE_FLOATED.evtType[0]:
2694 pos = [
2695 self.Position[i]
2696 + (self.Size[i] - self.ClientSize[i]) / {0: 2, 1: 1}[i]
2697 + s(10)
2698 for i in (0, 1)
2699 ]
2700 pos[0] += self.mainPanel.Position[0]
2701 pos[1] -= (self.Size[0] - self.ClientSize[0]) / 2
2702 self._mgr.GetPane("mainPanel").FloatingPosition(pos).CloseButton(True)
2703 wx.CallAfter(self.area_handler)
2704 else:
2705 wx.CallAfter(self.dock_pane)
2706
2707 def flush(self):
2708 """Flush the :class:`VisualWhitepointEditor`."""
2709
2710 def maximize_handler(self, event):
2711 """Handle maximize and fullscreen events.
2712
2713 Args:
2714 event (MaximizeEvent): A MaximizeEvent event to be processed.
2715 """
2716 # print '_isfullscreen?', getattr(self, "_isfullscreen", False)
2717 if not getattr(self, "_isfullscreen", False):
2718 self._isfullscreen = True
2719 # print 'Setting fullscreen...'
2720 self.ShowFullScreen(True)
2721 # print '...done setting fullscreen.'
2722 wx.CallAfter(self.notify, lang.getstr("fullscreen.message"))
2723
2724 def move_handler(self, event):
2725 """Handle the move event for the :class:`VisualWhitepointEditor`.
2726
2727 Args:
2728 event (MoveEvent): A MoveEvent event to be processed.
2729 """
2730 event.Skip()
2731 display = self.GetDisplay()
2732 if not self._pm._display or display.Geometry != self._pm._display.Geometry:
2733 self.set_area_size_slider_max()
2734 self.set_default_size()
2735 self.area_handler()
2736
2737 def measure(self, event):
2738 """Handle the measure button click event.
2739
2740 Args:
2741 event (ButtonEvent): A ButtonEvent event to be processed.
2742 """
2743 if (
2744 not self.Parent
2745 or not hasattr(self.Parent, "ambient_measure_handler")
2746 or not self.Parent.worker.displays
2747 or not self.Parent.worker.instruments
2748 ):
2749 wx.Bell()
2750 return
2751 self.measure_btn.Disable()
2752 self.setcfg()
2753 self.Parent.ambient_measure_handler(event)
2754
2755 def notify(self, msg, title=None, icon=None, timeout=-1):
2756 """Show a notification message.
2757
2758 Args:
2759 msg (str): The message to be displayed.
2760 title (str): The title of the notification.
2761 icon (str): The icon to be displayed in the notification.
2762 timeout (int): The timeout for the notification in milliseconds.
2763 """
2764 # Notification needs to have this frame as toplevel parent so key events
2765 # bubble to parent
2766 # print 'Showing fullscreen notification'
2767 if getattr(self, "notification", None):
2768 self.notification.fade("out")
2769 self.notification = TaskBarNotification(
2770 icon or get_icon(32, "dialog-information"),
2771 title or self.Title,
2772 msg,
2773 self.bgPanel,
2774 (-1, s(32)),
2775 timeout,
2776 )
2777 self.notification.Center(wx.HORIZONTAL)
2778
2779 def size_handler(self, event):
2780 """Handle the resize event for the :class:`VisualWhitepointEditor`.
2781
2782 Args:
2783 event (SizeEvent): A SizeEvent event to be processed.
2784 """
2785 if getattr(self, "_isfullscreen", False) and getattr(
2786 self, "notification", None
2787 ):
2788 # print 'Fading out notification'
2789 self.notification.fade("out")
2790 wx.CallAfter(self._check_fullscreen)
2791 self.area_handler(event)
2792
2793 def _check_fullscreen(self):
2794 """Check if the window is in fullscreen mode and update the state."""
2795 # print '_isfullscreen?', getattr(self, "_isfullscreen", False)
2796 if getattr(self, "_isfullscreen", False):
2797 self._isfullscreen = self.IsFullScreen()
2798 # print 'IsFullScreen()?', self._isfullscreen
2799
2800 def start_timer(self, ms=50):
2801 """Start a timer to update the display.
2802
2803 Args:
2804 ms (int): The interval in milliseconds to update the display.
2805 """
2806
2807 def stop_timer(self):
2808 """Stop the timer if it is running."""
2809
2810 def reset_handler(self, event):
2811 """Reset the colour and background colour to the default values."""
2812 RGB = [DEFAULTS[f"whitepoint.visual_editor.{attribute}"] for attribute in "rgb"]
2813 self._colourData.SetColour(wx.Colour(*RGB))
2814 self._colour.r, self._colour.g, self._colour.b = self._colourData.GetColour()[
2815 :3
2816 ]
2817 self._colour.ToHSV()
2818 self._bgcolour.v = DEFAULTS["whitepoint.visual_editor.bg_v"]
2819 self.DrawAll()
2820
2821 def set_area_size_slider_max(self):
2822 """Set the maximum value for the area size slider based on the display size."""
2823 # Set max value according to display size
2824 maxv = 1000
2825 if real_display_size_mm:
2826 geometry = self.GetDisplay().Geometry.Get()
2827 display_no = get_argyll_display_number(geometry)
2828 if display_no is not None:
2829 size_mm = real_display_size_mm.real_display_size_mm(display_no)
2830 if 0 not in size_mm:
2831 self.display_size_mm[geometry] = [float(v) for v in size_mm]
2832 maxv = round(max(size_mm) / 100.0 * 100)
2833 if maxv > 100:
2834 self.area_size_slider.SetMax(maxv)
2835 if self.area_size_slider.GetValue() > self.area_size_slider.GetMax():
2836 self.area_size_slider.SetValue(maxv)
2837
2838 def set_default_size(self):
2839 """Set the default size for the area based on the display size."""
2840 geometry = self.GetDisplay().Geometry.Get()
2841 size_mm = self.display_size_mm.get(geometry)
2842 if size_mm:
2843 px_per_mm = max(geometry[2] / size_mm[0], geometry[3] / size_mm[1])
2844 self.default_size = px_per_mm * 100
2845 else:
2846 self.default_size = 300
2847
2848 def setcfg(self):
2849 """Store the current colour and area settings in the configuration."""
2850 for attribute in "rgb":
2851 value = getattr(self._colour, attribute)
2852 setcfg("whitepoint.visual_editor." + attribute, value)
2853 setcfg("whitepoint.visual_editor.bg_v", self._bgcolour.v)
2854 x, y = (
2855 ctrl.Value / 1000.0 for ctrl in (self.area_x_slider, self.area_y_slider)
2856 )
2857 scale = self.area_size_slider.Value / 100.0
2858 setcfg(
2859 "dimensions.measureframe.whitepoint.visual_editor",
2860 f"{x:f},{y:f},{scale:f}",
2861 )
2862
2863 def write(self, txt):
2864 """Write text to the console or log.
2865
2866 Args:
2867 txt (str): The text to be written.
2868 """
2869
2870 def zoomnormal_handler(self, event):
2871 """Handle the zoom to normal button click event.
2872
2873 Args:
2874 event (ButtonEvent): A ButtonEvent event to be processed.
2875 """
2876 scale = float(
2877 DEFAULTS["dimensions.measureframe.whitepoint.visual_editor"].split(",")[2]
2878 )
2879 self.area_size_slider.SetValue(round(scale * 100))
2880 self.area_handler()
2881
2882
2883 if __name__ == "__main__":
2884 from DisplayCAL.wx_windows import BaseApp
2885
2886 initcfg()
2887 lang.init()
2888 app = BaseApp(0)
2889 worker = Worker()
2890 worker.enumerate_displays_and_ports(check_lut_access=False, enumerate_ports=False)
2891 app.TopWindow = VisualWhitepointEditor(None)
2892 app.TopWindow.Show()
2893 app.MainLoop()