Debian Codegraph @

DisplayCAL/wx_profile_info.py

raw
1 """Graphical interface for viewing and analyzing ICC profiles in DisplayCAL.
2
3 It includes features for visualizing color gamuts, tone response curves, and 3D
4 representations of profiles. The module integrates with wxPython for user
5 interaction and supports various color spaces and rendering intents.
6 """
7
8 import os
9 import re
10 import sys
11 import traceback
12
13 from DisplayCAL import colormath, config, x3dom
14 from DisplayCAL import localization as lang
15 from DisplayCAL import wx_enhanced_plot as plot
16 from DisplayCAL.argyll import check_set_argyll_bin, make_argyll_compatible_path
17 from DisplayCAL.config import (
18 DEFAULTS,
19 PROFILE_EXT,
20 get_argyll_display_number,
21 get_bitmap,
22 get_data_path,
23 get_display_profile,
24 get_display_rects,
25 get_icon,
26 get_verified_path,
27 getcfg,
28 setcfg,
29 writecfg,
30 )
31 from DisplayCAL.icc_profile import (
32 GAMUT_VOLUME_ADOBERGB,
33 GAMUT_VOLUME_SMPTE431_P3,
34 GAMUT_VOLUME_SRGB,
35 CurveType,
36 ICCProfile,
37 ICCProfileInvalidError,
38 NamedColor2Type,
39 ParametricCurveType,
40 VideoCardGammaType,
41 )
42 from DisplayCAL.meta import NAME as APPNAME
43 from DisplayCAL.options import DEBUG
44 from DisplayCAL.util_dict import dict_slice, dict_sort
45 from DisplayCAL.util_io import GzipFileProper
46 from DisplayCAL.util_list import intlist
47 from DisplayCAL.util_os import launch_file, make_win32_compatible_long_path, waccess
48 from DisplayCAL.util_str import strtr, universal_newlines, wrap
49 from DisplayCAL.worker import (
50 Error,
51 UnloggedError,
52 get_argyll_util,
53 show_result_dialog,
54 )
55 from DisplayCAL.wx_addons import get_platform_window_decoration_size, wx
56 from DisplayCAL.wx_fixes import GenBitmapButton as _GenBitmapButton
57 from DisplayCAL.wx_fixes import set_maxsize, wx_Panel
58 from DisplayCAL.wx_lut_viewer import LUTCanvas, LUTFrame
59 from DisplayCAL.wx_vrml_2_x3d import vrmlfile2x3dfile
60 from DisplayCAL.wx_windows import (
61 BaseApp,
62 BaseFrame,
63 BitmapBackgroundPanelText,
64 BitmapBackgroundPanelTextGamut,
65 CustomCheckBox,
66 CustomGrid,
67 CustomRowLabelRenderer,
68 FileDrop,
69 SimpleBook,
70 TwoWaySplitter,
71 )
72
73 BGCOLOUR = "#333333"
74 FGCOLOUR = "#999999"
75 TEXTCOLOUR = "#333333"
76 # Use conservative controls by default because some wx/SIP/native combinations
77 # can crash during widget construction across platforms.
78 SAFE_WX_UI = os.getenv("DISPLAYCAL_UNSAFE_WX_UI", "").strip() != "1"
79
80 if sys.platform == "darwin":
81 FONTSIZE_SMALL = 10
82 else:
83 FONTSIZE_SMALL = 8
84
85
86 class GamutCanvas(LUTCanvas):
87 """Canvas for displaying color gamuts and profiles."""
88
89 def __init__(self, *args, **kwargs):
90 LUTCanvas.__init__(self, *args, **kwargs)
91 self.SetEnableTitle(False)
92 self.SetFontSizeAxis(FONTSIZE_SMALL)
93 self.SetFontSizeLegend(FONTSIZE_SMALL)
94 self.pcs_data = []
95 self.profiles = {}
96 self.colorspace = "a*b*"
97 self.intent = ""
98 self.direction = ""
99 self.order = ""
100 self.reset()
101 self.resetzoom()
102
103 def DrawCanvas(
104 self,
105 title=None,
106 colorspace=None,
107 whitepoint=None,
108 center=False,
109 show_outline=True,
110 ):
111 """Draw the colorspace gamut plot.
112
113 Args:
114 title (str): Title of the plot.
115 colorspace (str): Colorspace to use for the plot.
116 whitepoint (int): Whitepoint type (1 for CIE 1931, 2 for Planckian).
117 center (bool): Whether to center the plot.
118 show_outline (bool): Whether to show the outline of the colorspace.
119 """
120 if not title:
121 title = ""
122 if colorspace:
123 self.colorspace = colorspace
124
125 # Defaults
126 poly = plot.PolyLine
127 poly._attributes["width"] = 3
128 polys = []
129
130 # L*a*b*
131 optimalcolors = colormath.OPTIMAL_COLORS_LAB
132
133 # CIE 1931 2-deg chromaticity coordinates
134 # http://www.cvrl.org/offercsvccs.php
135 xy = colormath.cie1931_2_xy
136
137 if self.colorspace == "xy":
138 label_x = "x"
139 label_y = "y"
140 if show_outline:
141 polys.append(
142 plot.PolySpline(
143 xy, colour=wx.Colour(102, 102, 102, 153), width=1.75
144 )
145 )
146 polys.append(
147 plot.PolyLine(
148 [xy[0], xy[-1]],
149 colour=wx.Colour(102, 102, 102, 153),
150 width=1.75,
151 )
152 )
153 max_x = 0.75
154 max_y = 0.85
155 min_x = -0.05
156 min_y = -0.05
157 step = 0.1
158 elif self.colorspace == "u'v'":
159 label_x = "u'"
160 label_y = "v'"
161 if show_outline:
162 uv = [colormath.xyY2Lu_v_(x, y, 100)[1:] for x, y in xy]
163 polys.append(
164 plot.PolySpline(
165 uv, colour=wx.Colour(102, 102, 102, 153), width=1.75
166 )
167 )
168 polys.append(
169 plot.PolyLine(
170 [uv[0], uv[-1]],
171 colour=wx.Colour(102, 102, 102, 153),
172 width=1.75,
173 )
174 )
175 max_x = 0.625
176 max_y = 0.6
177 min_x = -0.025
178 min_y = -0.025
179 step = 0.1
180 elif self.colorspace == "u*v*":
181 # Hard to present gamut projection appropriately in 2D
182 # because blue tones 'cave in' towards the center
183 label_x = "u*"
184 label_y = "v*"
185 max_x = 150.0
186 max_y = 150.0
187 min_x = -150.0
188 min_y = -150.0
189 step = 50
190 elif self.colorspace == "DIN99":
191 label_x = "a99"
192 label_y = "b99"
193 max_x = 50.0
194 max_y = 50.0
195 min_x = -50.0
196 min_y = -50.0
197 step = 25
198 elif self.colorspace in ("DIN99b", "DIN99c", "DIN99d"):
199 label_x = f"a{self.colorspace[3:]}"
200 label_y = f"b{self.colorspace[3:]}"
201 max_x = 65.0
202 max_y = 65.0
203 min_x = -65.0
204 min_y = -65.0
205 step = 25
206 elif self.colorspace == "ICtCp":
207 label_x = "Ct"
208 label_y = "Cp"
209 max_x = 0.4
210 max_y = 0.5
211 min_x = -0.5
212 min_y = -0.4
213 step = 0.1
214 elif self.colorspace == "IPT":
215 label_x = "P"
216 label_y = "T"
217 max_x = 1.0
218 max_y = 1.0
219 min_x = -1.0
220 min_y = -1.0
221 step = 0.25
222 else:
223 if self.colorspace == "Lpt":
224 label_x = "p"
225 label_y = "t"
226 else:
227 label_x = "a*"
228 label_y = "b*"
229 max_x = 150.0
230 max_y = 150.0
231 min_x = -150.0
232 min_y = -150.0
233 step = 50
234
235 convert2coords = {
236 "a*b*": lambda X, Y, Z: colormath.XYZ2Lab(*[v * 100 for v in (X, Y, Z)])[
237 1:
238 ],
239 "xy": lambda X, Y, Z: colormath.XYZ2xyY(X, Y, Z)[:2],
240 "u*v*": lambda X, Y, Z: colormath.XYZ2Luv(*[v * 100 for v in (X, Y, Z)])[
241 1:
242 ],
243 "u'v'": lambda X, Y, Z: colormath.XYZ2Lu_v_(X, Y, Z)[1:],
244 "DIN99": lambda X, Y, Z: colormath.XYZ2DIN99(*[v * 100 for v in (X, Y, Z)])[
245 1:
246 ],
247 "DIN99b": lambda X, Y, Z: colormath.XYZ2DIN99b(
248 *[v * 100 for v in (X, Y, Z)]
249 )[1:],
250 "DIN99c": lambda X, Y, Z: colormath.XYZ2DIN99c(
251 *[v * 100 for v in (X, Y, Z)]
252 )[1:],
253 "DIN99d": lambda X, Y, Z: colormath.XYZ2DIN99d(
254 *[v * 100 for v in (X, Y, Z)]
255 )[1:],
256 "ICtCp": lambda X, Y, Z: colormath.XYZ2ICtCp(X, Y, Z, clamp=False)[1:],
257 "IPT": lambda X, Y, Z: colormath.XYZ2IPT(X, Y, Z)[1:],
258 "Lpt": lambda X, Y, Z: colormath.XYZ2Lpt(*[v * 100 for v in (X, Y, Z)])[1:],
259 }[self.colorspace]
260
261 if show_outline and (
262 self.colorspace == "a*b*" or self.colorspace.startswith("DIN99")
263 ):
264 if self.colorspace == "a*b*":
265 optimalcolors = [Lab[1:] for Lab in optimalcolors]
266 else:
267 optimalcolors = [
268 convert2coords(*colormath.Lab2XYZ(L, a, b))
269 for L, a, b in optimalcolors
270 ]
271 polys.append(
272 plot.PolySpline(
273 optimalcolors, colour=wx.Colour(102, 102, 102, 153), width=1.75
274 )
275 )
276
277 # Add color temp graph
278 if whitepoint == 1:
279 colortemps = [
280 convert2coords(*colormath.CIEDCCT2XYZ(kelvin))
281 for kelvin in range(4000, 25001, 40)
282 ]
283 polys.append(
284 plot.PolyLine(
285 colortemps, colour=wx.Colour(255, 255, 255, 204), width=1.5
286 )
287 )
288 elif whitepoint == 2:
289 colortemps = []
290 # Stepsize 38 = endpoint 24999
291 for kelvin in range(1667, 25001, 38):
292 colortemps.append(convert2coords(*colormath.planckianCT2XYZ(kelvin)))
293 polys.append(
294 plot.PolyLine(
295 colortemps, colour=wx.Colour(255, 255, 255, 204), width=1.5
296 )
297 )
298
299 kwargs = {"scale": 255}
300
301 amount = len(self.pcs_data)
302
303 for i, pcs_triplets in enumerate(reversed(self.pcs_data)):
304 if not pcs_triplets or len(pcs_triplets) == 1:
305 amount -= 1
306 continue
307
308 # Convert xicclu output to coordinates
309 coords = [convert2coords(*pcs_triplet) for pcs_triplet in pcs_triplets]
310 profile = self.profiles.get(len(self.pcs_data) - 1 - i)
311 if (
312 profile
313 and profile.profileClass == b"nmcl"
314 and "ncl2" in profile.tags
315 and isinstance(profile.tags.ncl2, NamedColor2Type)
316 and profile.connectionColorSpace in (b"Lab", b"XYZ")
317 ):
318 # Named color profile
319 for j, (x, y) in enumerate(coords):
320 RGBA = colormath.XYZ2RGB(*pcs_triplets[j], **kwargs)
321 polys.append(
322 plot.PolyMarker(
323 [(x, y)],
324 colour=wx.Colour(*intlist(RGBA)),
325 size=2,
326 marker="plus",
327 width=1.75,
328 )
329 )
330 else:
331 xy = []
332 for x, y in coords[:-1]:
333 xy.append((x, y))
334 if i == 0 or amount == 1:
335 max_x = max(max_x, x)
336 max_y = max(max_y, y)
337 min_x = min(min_x, x)
338 min_y = min(min_y, y)
339
340 xy2 = []
341 for j, (x, y) in enumerate(xy):
342 xy2.append((x, y))
343 if len(xy2) == self.size:
344 xy3 = []
345 for k, (x, y) in enumerate(xy2):
346 xy3.append((x, y))
347 if len(xy3) == 2:
348 if i == 1:
349 # Draw comparison profile with grey outline
350 RGBA = 102, 102, 102, 255
351 w = 2
352 else:
353 RGBA = colormath.XYZ2RGB(
354 *pcs_triplets[j - len(xy2) + k], **kwargs
355 )
356 w = 3
357 polys.append(
358 poly(
359 list(xy3),
360 colour=wx.Colour(*intlist(RGBA)),
361 width=w,
362 )
363 )
364 xy3 = [] if i == 1 else xy3[1:]
365 xy2 = xy2[self.size :]
366
367 # Add whitepoint
368 x, y = coords[-1]
369 if i == 1:
370 # Draw comparison profile with grey outline
371 RGBA = 204, 204, 204, 102
372 marker = "cross"
373 s = 1.5
374 w = 1.75
375 else:
376 RGBA = colormath.XYZ2RGB(*pcs_triplets[-1], **kwargs)
377 marker = "plus"
378 s = 2
379 w = 1.75
380 polys.append(
381 plot.PolyMarker(
382 [(x, y)],
383 colour=wx.Colour(*intlist(RGBA)),
384 size=s,
385 marker=marker,
386 width=w,
387 )
388 )
389
390 xy_range = max(abs(min_x), abs(min_y)) + max(max_x, max_y)
391 if center or not self.last_draw:
392 self.axis_x = self.axis_y = (min(min_x, min_y), max(max_x, max_y))
393 self.spec_x = xy_range / step
394 self.spec_y = xy_range / step
395
396 if polys:
397 graphics = plot.PlotGraphics(polys, title, label_x, label_y)
398 p1, p2 = graphics.boundingBox()
399 spacer = plot.PolyMarker(
400 [
401 (p1[0] - xy_range / 20.0, p1[1] - xy_range / 20.0),
402 (p2[0] + xy_range / 20.0, p2[1] + xy_range / 20.0),
403 ],
404 colour=wx.Colour(0x33, 0x33, 0x33),
405 size=0,
406 )
407 graphics.objects.append(spacer)
408 if center or not self.last_draw:
409 boundingbox = spacer.boundingBox()
410 self.resetzoom(boundingbox)
411 self.center(boundingbox)
412 self._DrawCanvas(graphics)
413
414 def reset(self):
415 """Reset the canvas to its initial state."""
416 self.axis_x = self.axis_y = -128, 128
417
418 def set_pcs_data(self, i):
419 """Set the PCS data for the given index.
420
421 Args:
422 i (int): Index of the profile to set PCS data for.
423 """
424 if len(self.pcs_data) < i + 1:
425 self.pcs_data.append([])
426 else:
427 self.pcs_data[i] = []
428
429 def setup(
430 self, profiles=None, profile_no=None, intent="a", direction="f", order="n"
431 ):
432 """Setup the canvas with the given profiles and parameters.
433
434 Args:
435 profiles (list): List of ICCProfile objects to use.
436 profile_no (int): Index of the profile to draw.
437 intent (str): Rendering intent ('a', 'r', 'p', 's').
438 direction (str): Direction ('f' for forward, 'ib' for backward/inverted).
439 order (str): Order ('n' for normal, 'c' for chromatic adaptation).
440
441 Raises:
442 Exception: If there is an error setting up the canvas.
443 """
444 # Number of segments from one primary to the next secondary color
445 self.size = 40
446
447 if not check_set_argyll_bin():
448 return
449
450 # Setup xicclu
451 xicclu = get_argyll_util("xicclu")
452 if not xicclu:
453 return
454
455 cwd = self.worker.create_tempdir()
456 if isinstance(cwd, Exception):
457 raise cwd
458
459 if not profiles:
460 profiles = [
461 ICCProfile(get_data_path("ref/sRGB.icm")),
462 get_display_profile(),
463 ]
464
465 for i, profile in enumerate(profiles):
466 if profile_no is not None and i != profile_no:
467 continue
468
469 if (
470 not profile
471 or profile.profileClass == b"link"
472 or profile.connectionColorSpace not in (b"Lab", b"XYZ")
473 ):
474 self.set_pcs_data(i)
475 self.profiles[i] = None
476 continue
477
478 check = self.profiles.get(i)
479 if (
480 check
481 and profile.filename == check.filename
482 and profile.calculate_id(False) == check.ID
483 and intent == self.intent
484 and direction == self.direction
485 and order == self.order
486 ):
487 continue
488
489 self.profiles[i] = profile
490
491 self.set_pcs_data(i)
492
493 pcs_triplets = []
494 if (
495 profile.profileClass == b"nmcl"
496 and "ncl2" in profile.tags
497 and isinstance(profile.tags.ncl2, NamedColor2Type)
498 and profile.connectionColorSpace in (b"Lab", b"XYZ")
499 ):
500 for k in profile.tags.ncl2:
501 v = profile.tags.ncl2[k]
502 color = list(v.pcs.values())
503 if profile.connectionColorSpace == b"Lab":
504 # Need to convert to XYZ
505 color = colormath.Lab2XYZ(*color)
506 if intent == "a" and "wtpt" in profile.tags:
507 color = colormath.adapt(
508 color[0],
509 color[1],
510 color[2],
511 whitepoint_destination=list(profile.tags.wtpt.ir.values()),
512 )
513 pcs_triplets.append(color)
514 pcs_triplets.sort()
515 elif profile.version >= 4 and not profile.convert_iccv4_tags_to_iccv2():
516 self.profiles[i] = None
517 self.errors.append(
518 Error(
519 "\n".join(
520 [
521 lang.getstr("profile.iccv4.unsupported"),
522 profile.getDescription(),
523 ]
524 )
525 )
526 )
527 continue
528 else:
529 channels = {
530 b"XYZ": 3,
531 b"Lab": 3,
532 b"Luv": 3,
533 b"YCbr": 3,
534 b"Yxy": 3,
535 b"RGB": 3,
536 b"GRAY": 1,
537 b"HSV": 3,
538 b"HLS": 3,
539 b"CMYK": 4,
540 b"CMY": 3,
541 b"2CLR": 2,
542 b"3CLR": 3,
543 b"4CLR": 4,
544 b"5CLR": 5,
545 b"6CLR": 6,
546 b"7CLR": 7,
547 b"8CLR": 8,
548 b"9CLR": 9,
549 b"ACLR": 10,
550 b"BCLR": 11,
551 b"CCLR": 12,
552 b"DCLR": 13,
553 b"ECLR": 14,
554 b"FCLR": 15,
555 }.get(profile.colorSpace)
556
557 if not channels:
558 self.errors.append(
559 Error(
560 lang.getstr(
561 "profile.unsupported",
562 (
563 profile.profileClass.decode("utf-8"),
564 profile.colorSpace.decode("utf-8"),
565 ),
566 )
567 )
568 )
569 continue
570
571 # Create input values
572 device_values = []
573 if profile.colorSpace in (b"Lab", b"Luv", b"XYZ", b"Yxy"):
574 # Use ICC PCSXYZ encoding range
575 minv = 0.0
576 maxv = 0xFFFF / 32768.0
577 else:
578 minv = 0.0
579 maxv = 1.0
580 step = (maxv - minv) / (self.size - 1)
581 for j in range(min(3, channels)):
582 for k in range(min(3, channels)):
583 device_value = [0.0] * channels
584 device_value[j] = maxv
585 if j != k or channels == 1:
586 for l in range(self.size):
587 device_value[k] = minv + step * l
588 device_values.append(list(device_value))
589 if profile.colorSpace in (
590 b"HLS",
591 b"HSV",
592 b"Lab",
593 b"Luv",
594 b"YCbr",
595 b"Yxy",
596 ):
597 # Convert to actual color space
598 # TODO: Handle HLS and YCbr
599 tmp = list(device_values)
600 device_values = []
601 for values in tmp:
602 if profile.colorSpace == b"HSV":
603 HSV = list(colormath.RGB2HSV(*values))
604 device_values.append(HSV)
605 elif profile.colorSpace == b"Lab":
606 Lab = list(colormath.XYZ2Lab(*[v * 100 for v in values]))
607 device_values.append(Lab)
608 elif profile.colorSpace == b"Luv":
609 Luv = list(colormath.XYZ2Luv(*[v * 100 for v in values]))
610 device_values.append(Luv)
611 elif profile.colorSpace == b"Yxy":
612 xyY = list(colormath.XYZ2xyY(*values))
613 device_values.append(xyY)
614
615 # Add white
616 if profile.colorSpace == b"RGB":
617 device_values.append([1.0] * channels)
618 elif profile.colorSpace == b"HLS":
619 device_values.append([0, 1, 0])
620 elif profile.colorSpace == b"HSV":
621 device_values.append([0, 0, 1])
622 elif profile.colorSpace in (b"Lab", b"Luv", b"YCbr"):
623 if profile.colorSpace == b"YCbr":
624 device_values.append([1.0, 0.0, 0.0])
625 else:
626 device_values.append([100.0, 0.0, 0.0])
627 elif profile.colorSpace in (b"XYZ", b"Yxy"):
628 if profile.colorSpace == b"XYZ":
629 device_values.append(list(profile.tags.wtpt.pcs.values()))
630 else:
631 device_values.append(profile.tags.wtpt.pcs.xyY)
632 elif profile.colorSpace != b"GRAY":
633 device_values.append([0.0] * channels)
634
635 if DEBUG:
636 print("In:")
637 for v in device_values:
638 print(" ".join(("%3.4f",) * len(v)) % tuple(v))
639
640 # Lookup device -> XYZ values through profile using xicclu
641 fwd_intent = "r" if direction == "ib" and intent not in "ar" else intent
642 try:
643 # Device -> PCS, fwd
644 odata = self.worker.xicclu(
645 profile, device_values, intent, "f", order
646 )
647 if direction == "ib":
648 # PCS -> device, bwd
649 odata = self.worker.xicclu(profile, odata, intent, "b", order)
650 # Device -> PCS, fwd
651 odata = self.worker.xicclu(
652 profile, odata, fwd_intent, "f", order
653 )
654 except Exception as exception:
655 self.errors.append(Error(str(exception)))
656 continue
657
658 if DEBUG:
659 print("Out:")
660 for pcs_triplet in odata:
661 if DEBUG:
662 print(
663 " ".join(("%3.4f",) * len(pcs_triplet)) % tuple(pcs_triplet)
664 )
665 pcs_triplets.append(pcs_triplet)
666 if profile.connectionColorSpace == b"Lab":
667 pcs_triplets[-1] = list(colormath.Lab2XYZ(*pcs_triplets[-1]))
668
669 if len(self.pcs_data) < i + 1:
670 self.pcs_data.append(pcs_triplets)
671 else:
672 self.pcs_data[i] = pcs_triplets
673
674 # Remove temporary files
675 self.worker.wrapup(False)
676
677 self.intent = intent
678 self.direction = direction
679 self.order = order
680
681
682 class GamutViewOptions(wx_Panel):
683 """Panel for selecting options for the GamutView."""
684
685 def __init__(self, *args, **kwargs):
686 scale = getcfg("app.dpi") / config.get_default_dpi()
687 scale = max(scale, 1)
688
689 super().__init__(*args, **kwargs)
690 self.SetBackgroundColour(BGCOLOUR)
691
692 def _create_checkbox(parent, label):
693 # Avoid custom checkbox subclasses in safe mode where SIP/wx object
694 # conversion can crash while adding controls to sizers.
695 if SAFE_WX_UI:
696 return wx.CheckBox(parent, -1, label)
697 return CustomCheckBox(parent=parent, id=-1, label=label)
698
699 self.sizer = wx.FlexGridSizer(0, 3, 4, 0)
700 self.sizer.AddGrowableCol(0)
701 self.sizer.AddGrowableCol(1)
702 self.sizer.AddGrowableCol(2)
703 self.SetSizer(self.sizer)
704
705 self.sizer.Add((0, 0))
706 legendsizer = wx.BoxSizer(wx.HORIZONTAL)
707 self.sizer.Add(legendsizer)
708
709 # Avoid file-backed wx.Bitmap construction in safe mode.
710 def _create_marker(name, fallback_label):
711 if SAFE_WX_UI:
712 marker = wx.StaticText(self, -1, fallback_label)
713 marker.SetForegroundColour(FGCOLOUR)
714 return marker
715 return wx.StaticBitmap(self, -1, get_bitmap(name))
716
717 # Whitepoint legend
718 legendsizer.Add(
719 _create_marker("theme/cross-2px-12x12-fff", "+"),
720 flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
721 border=2,
722 )
723 self.whitepoint_legend = wx.StaticText(self, -1, lang.getstr("whitepoint"))
724 self.whitepoint_legend.SetMaxFontSize(11)
725 self.whitepoint_legend.SetForegroundColour(FGCOLOUR)
726 legendsizer.Add(
727 self.whitepoint_legend, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=10
728 )
729
730 # Comparison profile whitepoint legend
731 self.comparison_whitepoint_bmp = _create_marker("theme/x-2px-12x12-999", "x")
732 legendsizer.Add(
733 self.comparison_whitepoint_bmp,
734 flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
735 border=20,
736 )
737 self.comparison_whitepoint_legend = wx.StaticText(
738 self,
739 -1,
740 "{} ({})".format(
741 lang.getstr("whitepoint"), lang.getstr("comparison_profile")
742 ),
743 )
744 self.comparison_whitepoint_legend.SetMaxFontSize(11)
745 self.comparison_whitepoint_legend.SetForegroundColour(FGCOLOUR)
746 legendsizer.Add(
747 self.comparison_whitepoint_legend,
748 flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
749 border=8,
750 )
751 self.sizer.Add((0, 0))
752
753 # Empty 'row'
754 self.sizer.Add((0, 0))
755 self.sizer.Add((0, 0))
756 self.sizer.Add((0, 0))
757
758 self.sizer.Add((0, 0))
759 self.options_sizer = wx.FlexGridSizer(0, 3, 4, 8)
760 self.options_sizer.AddGrowableCol(2)
761 self.sizer.Add(self.options_sizer, flag=wx.EXPAND)
762
763 # Colorspace select
764 self.colorspace_outline_bmp = _create_marker("theme/solid-16x2-666", "-")
765 self.options_sizer.Add(
766 self.colorspace_outline_bmp, flag=wx.ALIGN_CENTER_VERTICAL
767 )
768 self.colorspace_label = wx.StaticText(self, -1, lang.getstr("colorspace"))
769 self.colorspace_label.SetMaxFontSize(11)
770 self.colorspace_label.SetForegroundColour(FGCOLOUR)
771 self.options_sizer.Add(self.colorspace_label, flag=wx.ALIGN_CENTER_VERTICAL)
772 self.colorspace_select = wx.Choice(
773 parent=self,
774 id=-1,
775 size=(150 * scale, -1),
776 choices=[
777 "CIE a*b*",
778 "CIE u*v*",
779 "CIE u'v'",
780 "CIE xy",
781 "DIN99",
782 "DIN99b",
783 "DIN99c",
784 "DIN99d",
785 "ICtCp",
786 "IPT",
787 "Lpt",
788 ],
789 )
790 self.options_sizer.Add(
791 self.colorspace_select, flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND
792 )
793 self.colorspace_select.Bind(wx.EVT_CHOICE, self.generic_select_handler)
794 self.colorspace_select.SetSelection(0)
795
796 # Colorspace outline
797 self.options_sizer.Add((0, 0))
798 self.options_sizer.Add((0, 0))
799 self.draw_gamut_outline_cb = _create_checkbox(
800 self, lang.getstr("colorspace.show_outline")
801 )
802 self.draw_gamut_outline_cb.Bind(
803 wx.EVT_CHECKBOX, self.draw_gamut_outline_handler
804 )
805 if hasattr(self.draw_gamut_outline_cb, "SetMaxFontSize"):
806 self.draw_gamut_outline_cb.SetMaxFontSize(11)
807 self.draw_gamut_outline_cb.SetForegroundColour(FGCOLOUR)
808 self.draw_gamut_outline_cb.SetValue(True)
809 self.options_sizer.Add(
810 self.draw_gamut_outline_cb,
811 flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
812 border=4,
813 )
814
815 # Colortemperature curve select
816 self.whitepoint_bmp = _create_marker("theme/solid-16x1-fff", "-")
817 self.options_sizer.Add(self.whitepoint_bmp, flag=wx.ALIGN_CENTER_VERTICAL)
818 self.whitepoint_label = wx.StaticText(
819 self, -1, lang.getstr("whitepoint.colortemp.locus.curve")
820 )
821 self.whitepoint_label.SetMaxFontSize(11)
822 self.whitepoint_label.SetForegroundColour(FGCOLOUR)
823 self.options_sizer.Add(self.whitepoint_label, flag=wx.ALIGN_CENTER_VERTICAL)
824 self.whitepoint_select = wx.Choice(
825 self,
826 -1,
827 size=(150 * scale, -1),
828 choices=[
829 lang.getstr("calibration.file.none"),
830 lang.getstr("whitepoint.colortemp.locus.daylight"),
831 lang.getstr("whitepoint.colortemp.locus.blackbody"),
832 ],
833 )
834 self.options_sizer.Add(
835 self.whitepoint_select, flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND
836 )
837 self.whitepoint_select.Bind(wx.EVT_CHOICE, self.generic_select_handler)
838 self.whitepoint_select.SetSelection(0)
839 self.whitepoint_bmp.Hide()
840
841 # Comparison profile select
842 self.comparison_profile_bmp = _create_marker("theme/dashed-16x2-666", "=")
843 self.options_sizer.Add(
844 self.comparison_profile_bmp, flag=wx.ALIGN_CENTER_VERTICAL
845 )
846 self.comparison_profile_label = wx.StaticText(
847 self, -1, lang.getstr("comparison_profile")
848 )
849 self.comparison_profile_label.SetMaxFontSize(11)
850 self.comparison_profile_label.SetForegroundColour(FGCOLOUR)
851 self.options_sizer.Add(
852 self.comparison_profile_label, flag=wx.ALIGN_CENTER_VERTICAL
853 )
854 self.comparison_profiles = {lang.getstr("calibration.file.none"): None}
855 srgb = None
856 try:
857 srgb = ICCProfile(get_data_path("ref/sRGB.icm"))
858 except OSError:
859 pass
860 except Exception as exception:
861 print(exception)
862 if srgb:
863 self.comparison_profiles[srgb.getDescription()] = srgb
864 for profile in config.get_standard_profiles():
865 desc = profile.getDescription()
866 if desc not in self.comparison_profiles:
867 self.comparison_profiles[desc] = profile
868 self.comparison_profile_select = wx.Choice(
869 parent=self, id=-1, size=(150 * scale, -1), choices=[]
870 )
871 self.comparison_profiles_sort()
872 self.options_sizer.Add(
873 self.comparison_profile_select, flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND
874 )
875 self.comparison_profile_select.Bind(
876 wx.EVT_CHOICE, self.comparison_profile_select_handler
877 )
878 droptarget = FileDrop(
879 self.TopLevelParent,
880 {
881 ".icc": self.comparison_profile_drop_handler,
882 ".icm": self.comparison_profile_drop_handler,
883 },
884 )
885 self.comparison_profile_select.SetDropTarget(droptarget)
886 if srgb:
887 self.comparison_profile_select.SetSelection(1)
888 self.comparison_profile_select.SetToolTipString(srgb.filename)
889
890 # Rendering intent select
891 self.options_sizer.Add((0, 0))
892 self.rendering_intent_label = wx.StaticText(
893 self, -1, lang.getstr("rendering_intent")
894 )
895 self.rendering_intent_label.SetMaxFontSize(11)
896 self.rendering_intent_label.SetForegroundColour(FGCOLOUR)
897 self.options_sizer.Add(
898 self.rendering_intent_label, flag=wx.ALIGN_CENTER_VERTICAL
899 )
900 self.rendering_intent_select = wx.Choice(
901 self,
902 -1,
903 size=(150 * scale, -1),
904 choices=[
905 lang.getstr("gamap.intents.a"),
906 lang.getstr("gamap.intents.r"),
907 lang.getstr("gamap.intents.p"),
908 lang.getstr("gamap.intents.s"),
909 ],
910 )
911 self.options_sizer.Add(
912 self.rendering_intent_select, flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND
913 )
914 self.rendering_intent_select.Bind(
915 wx.EVT_CHOICE, self.rendering_intent_select_handler
916 )
917 self.rendering_intent_select.SetSelection(0)
918
919 self.options_sizer.Add((0, 0))
920
921 # LUT toggle
922 self.toggle_clut = _create_checkbox(self, "LUT")
923 self.toggle_clut.SetForegroundColour(FGCOLOUR)
924 if hasattr(self.toggle_clut, "SetMaxFontSize"):
925 self.toggle_clut.SetMaxFontSize(11)
926 self.options_sizer.Add(self.toggle_clut, flag=wx.ALIGN_CENTER_VERTICAL)
927 self.toggle_clut.Bind(wx.EVT_CHECKBOX, self.toggle_clut_handler)
928 self.toggle_clut.Hide()
929
930 # Direction selection
931 self.direction_select = wx.Choice(
932 self,
933 -1,
934 size=(150 * scale, -1),
935 choices=[
936 lang.getstr("direction.forward"),
937 lang.getstr("direction.backward.inverted"),
938 ],
939 )
940 self.options_sizer.Add(
941 self.direction_select, flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND
942 )
943 self.direction_select.Bind(wx.EVT_CHOICE, self.direction_select_handler)
944 self.direction_select.SetSelection(0)
945
946 self.sizer.Add((0, 0))
947
948 def DrawCanvas(self, profile_no=None, reset=True):
949 """Draw the colorspace gamut plot.
950
951 Args:
952 profile_no (int): The index of the profile to draw.
953 reset (bool): Whether to reset the plot before drawing.
954 """
955 # Gamut plot
956 parent = self.TopLevelParent
957 parent.client.SetEnableCenterLines(False)
958 parent.client.SetEnableDiagonals(False)
959 parent.client.SetEnableGrid(True)
960 parent.client.SetEnablePointLabel(False)
961 try:
962 parent.client.setup(
963 [self.comparison_profile, parent.profile],
964 profile_no,
965 intent=self.intent,
966 direction=self.direction,
967 order=self.order,
968 )
969 except Exception as exception:
970 show_result_dialog(exception, parent)
971 if reset:
972 parent.client.reset()
973 parent.client.resetzoom()
974 wx.CallAfter(self.draw, center=reset)
975 wx.CallAfter(parent.handle_errors)
976
977 @property
978 def colorspace(self):
979 """Return the currently selected colorspace name.
980
981 Returns:
982 str: The name of the currently selected colorspace.
983 """
984 return self.get_colorspace()
985
986 @property
987 def comparison_profile(self) -> str:
988 """Return the currently selected comparison profile name.
989
990 Returns:
991 str: The current comparison profile name.
992 """
993 index = self.comparison_profile_select.GetSelection()
994 if index == -1: # Fix for #67
995 index = 0
996 self.comparison_profile_select.SetSelection(index)
997 return list(self.comparison_profiles.values())[index]
998
999 def comparison_profile_drop_handler(self, path):
1000 """Handle dropping a profile file onto the comparison profile select.
1001
1002 Args:
1003 path (str): The file path of the dropped profile.
1004 """
1005 try:
1006 profile = ICCProfile(path)
1007 except Exception as exception:
1008 show_result_dialog(exception, self.TopLevelParent)
1009 else:
1010 desc = profile.getDescription()
1011 self.comparison_profiles[desc] = profile
1012 self.comparison_profiles_sort()
1013 self.comparison_profile_select.SetSelection(
1014 list(self.comparison_profiles.keys()).index(desc)
1015 )
1016 self.comparison_profile_select_handler(None)
1017
1018 def comparison_profile_select_handler(self, event):
1019 """Handle the selection of a comparison profile.
1020
1021 Args:
1022 event (wx.Event): The event object.
1023 """
1024 index = self.comparison_profile_select.GetSelection()
1025 if index > 0:
1026 self.comparison_profile_select.SetToolTipString(
1027 self.comparison_profile.filename
1028 )
1029 else:
1030 self.comparison_profile_select.SetToolTip(None)
1031 self.comparison_whitepoint_bmp.Show(index > 0)
1032 self.comparison_whitepoint_legend.Show(index > 0)
1033 self.comparison_profile_bmp.Show(index > 0)
1034 self.DrawCanvas(0, reset=False)
1035
1036 def comparison_profiles_sort(self):
1037 """Sort the comparison profiles and update the selection."""
1038 comparison_profiles = dict_slice(self.comparison_profiles, 2)
1039 comparison_profiles = dict_sort(comparison_profiles, key=lambda s: s.lower())
1040 self.comparison_profiles = dict_slice(self.comparison_profiles, None, 2)
1041 self.comparison_profiles.update(comparison_profiles)
1042 self.comparison_profile_select.SetItems(list(self.comparison_profiles.keys()))
1043
1044 @property
1045 def direction(self):
1046 """Return the direction of the colorspace.
1047
1048 Returns:
1049 str: The direction, either "f" for forward or "ib" for backward/inverted.
1050 """
1051 index = self.direction_select.GetSelection()
1052 if index == -1: # Fix for #67
1053 index = 0
1054 self.direction_select.SetSelection(index)
1055 if self.direction_select.IsShown():
1056 return {0: "f", 1: "ib"}.get(self.direction_select.GetSelection())
1057 return "f"
1058
1059 def draw(self, center=False):
1060 """Draw the colorspace gamut.
1061
1062 Args:
1063 center (bool): Whether to center the plot.
1064 """
1065 index = self.whitepoint_select.GetSelection()
1066 if index == -1: # Fix for #67
1067 index = 0
1068 self.whitepoint_select.SetSelection(index)
1069 colorspace = self.colorspace
1070 parent = self.TopLevelParent
1071 parent.client.proportional = True
1072 parent.client.DrawCanvas(
1073 f"{colorspace} {lang.getstr('colorspace')}",
1074 colorspace,
1075 whitepoint=index,
1076 center=center,
1077 show_outline=self.draw_gamut_outline_cb.GetValue(),
1078 )
1079
1080 def draw_gamut_outline_handler(self, event):
1081 """Handle the toggle for drawing the colorspace outline.
1082
1083 Args:
1084 event (wx.Event): The event object.
1085 """
1086 self.colorspace_outline_bmp.Show(self.draw_gamut_outline_cb.GetValue())
1087 self.draw()
1088
1089 def generic_select_handler(self, event):
1090 """Handle generic selection changes in the options panel.
1091
1092 Args:
1093 event (wx.Event): The event object.
1094 """
1095 self.whitepoint_bmp.Show(self.whitepoint_select.GetSelection() > 0)
1096 parent = self.TopLevelParent
1097 if parent.client.profiles:
1098 self.draw(center=event.GetId() == self.colorspace_select.GetId())
1099 else:
1100 self.DrawCanvas()
1101
1102 def get_colorspace(self, dimensions: int = 2) -> str:
1103 """Return currently selected colorspace name.
1104
1105 Args:
1106 dimensions (int): The dimensions, default is 2.
1107
1108 Returns:
1109 str: The name of the currently selected colorspace.
1110 """
1111 index = self.colorspace_select.GetSelection()
1112 if index == -1: # Fix for #67
1113 index = 0
1114 self.colorspace_select.SetSelection(index)
1115 return {
1116 0: "a*b*" if dimensions == 2 else "Lab",
1117 1: "u*v*" if dimensions == 2 else "Luv",
1118 2: "u'v'" if dimensions == 2 else "Lu'v'",
1119 3: "xy" if dimensions == 2 else "xyY",
1120 4: "DIN99",
1121 5: "DIN99b",
1122 6: "DIN99c",
1123 7: "DIN99d",
1124 8: "ICtCp",
1125 9: "IPT",
1126 10: "Lpt",
1127 }.get(index, "a*b*" if dimensions == 2 else "Lab")
1128
1129 @property
1130 def intent(self) -> str:
1131 """Return rendering intent.
1132
1133 Returns:
1134 str: The single letter rendering intent.
1135 """
1136 index = self.rendering_intent_select.GetSelection()
1137 if index == -1: # Fix for #67
1138 index = 0
1139 self.rendering_intent_select.SetSelection(index)
1140 return {0: "a", 1: "r", 2: "p", 3: "s"}.get(index)
1141
1142 @property
1143 def order(self):
1144 """Return rendering order.
1145
1146 Returns:
1147 str: The rendering order, either "n" for normal or "r" for reverse.
1148 """
1149 parent = self.TopLevelParent
1150 return {True: "n", False: "r"}.get(
1151 (
1152 bool(parent.profile)
1153 and not ("B2A0" in parent.profile.tags or "A2B0" in parent.profile.tags)
1154 )
1155 or self.toggle_clut.GetValue()
1156 )
1157
1158 def rendering_intent_select_handler(self, event):
1159 """Handle rendering intent selection change.
1160
1161 Args:
1162 event (wx.Event): The event object.
1163 """
1164 self.DrawCanvas(reset=False)
1165
1166 def direction_select_handler(self, event):
1167 """Handle direction selection change.
1168
1169 Args:
1170 event (wx.Event): The event object.
1171 """
1172 self.DrawCanvas(reset=False)
1173
1174 def toggle_clut_handler(self, event):
1175 """Handle toggle for CLUT display.
1176
1177 Args:
1178 event (wx.Event): The event object.
1179 """
1180 parent = self.TopLevelParent
1181 self.Freeze()
1182 self.direction_select.Enable(
1183 bool(parent.profile)
1184 and "B2A0" in parent.profile.tags
1185 and "A2B0" in parent.profile.tags
1186 and self.toggle_clut.GetValue()
1187 )
1188 self.DrawCanvas(reset=False)
1189 self.Thaw()
1190
1191
1192 class PIFrame2WaySplitter(TwoWaySplitter):
1193 """Two-way splitter for profile info frame."""
1194
1195 def OnLeftDClick(self, event):
1196 """Handle left double-click event.
1197
1198 Args:
1199 event (wx.Event): The event object.
1200 """
1201 if not self.IsEnabled():
1202 return
1203
1204 pt = event.GetPosition()
1205
1206 if self.GetMode(pt):
1207 _barSize = self._GetSashSize()
1208 winborder, titlebar = get_platform_window_decoration_size()
1209 win0w = self.GetTopLeft().Size[0]
1210 self.Freeze()
1211 TwoWaySplitter.OnLeftDClick(self, event)
1212 if self._expanded < 0:
1213 self.Parent.SetMinSize(
1214 (
1215 DEFAULTS["size.profile_info.split.w"] + winborder * 2,
1216 self.Parent.GetMinSize()[1],
1217 )
1218 )
1219 if (
1220 not self.Parent.IsMaximized()
1221 and self.Parent.ClientSize[0] < self.GetSplitSize()[0]
1222 ):
1223 self.Parent.ClientSize = (
1224 self.GetSplitSize()[0],
1225 self.Parent.ClientSize[1],
1226 )
1227 else:
1228 self.Parent.SetMinSize(
1229 (
1230 DEFAULTS["size.profile_info.w"] + winborder * 2,
1231 self.Parent.GetMinSize()[1],
1232 )
1233 )
1234 w = max(self.GetExpandedSize()[0], self._splitx)
1235 if not self.Parent.IsMaximized() and self.Parent.ClientSize[0] > w:
1236 self.Parent.ClientSize = (w, self.Parent.ClientSize[1])
1237 if os.getenv("XDG_SESSION_TYPE") == "wayland":
1238 self.Parent.MaxSize = self.Parent.Size
1239 wx.CallAfter(set_maxsize, self.Parent, (-1, -1))
1240 if self.GetTopLeft().Size[0] != win0w:
1241 self.Parent.redraw()
1242 self.Parent.resize_grid()
1243 self.Thaw()
1244
1245
1246 class ProfileInfoFrame(LUTFrame):
1247 """Profile info frame."""
1248
1249 def _create_plot_toolbar_button(
1250 self,
1251 parent,
1252 bitmap_provider,
1253 label,
1254 tooltip,
1255 border,
1256 handler,
1257 context_handler=None,
1258 ):
1259 """Create a safe toolbar button for the plot controls."""
1260 # Use plain text buttons in safe mode to avoid bitmap-related crashes.
1261 if SAFE_WX_UI:
1262 button = wx.Button(parent, -1, label=label, style=wx.BU_EXACTFIT)
1263 else:
1264 bitmap = bitmap_provider()
1265 button = _GenBitmapButton(parent, -1, bitmap, style=wx.NO_BORDER)
1266 button.SetBackgroundColour(BGCOLOUR)
1267 button.Bind(wx.EVT_BUTTON, handler)
1268 if context_handler:
1269 button.Bind(wx.EVT_CONTEXT_MENU, context_handler)
1270 button.SetToolTip(tooltip)
1271 self.plot_mode_sizer.Add(
1272 button, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=border
1273 )
1274 return button
1275
1276 def __init__(self, *args, **kwargs):
1277 if len(args) < 3 and "title" not in kwargs:
1278 kwargs["title"] = lang.getstr("profile.info")
1279 if "name" not in kwargs:
1280 kwargs["name"] = "profile_info"
1281
1282 BaseFrame.__init__(self, *args, **kwargs)
1283 if not SAFE_WX_UI:
1284 self.SetIcons(
1285 config.get_icon_bundle([256, 48, 32, 16], f"{APPNAME}-profile-info")
1286 )
1287
1288 self.profile = None
1289 self.xLabel = lang.getstr("in")
1290 self.yLabel = lang.getstr("out")
1291
1292 self.sizer = wx.BoxSizer(wx.VERTICAL)
1293 self.SetSizer(self.sizer)
1294 self.splitter = PIFrame2WaySplitter(
1295 self, -1, agw_style=wx.SP_LIVE_UPDATE | wx.SP_NOSASH
1296 )
1297 self.sizer.Add(self.splitter, 1, flag=wx.EXPAND)
1298
1299 p1 = wx_Panel(self.splitter, name="canvaspanel")
1300 p1.SetBackgroundColour(BGCOLOUR)
1301 p1.sizer = wx.BoxSizer(wx.VERTICAL)
1302 p1.SetSizer(p1.sizer)
1303 self.splitter.AppendWindow(p1)
1304
1305 self.plot_mode_sizer = wx.BoxSizer(wx.HORIZONTAL)
1306 p1.sizer.Add(self.plot_mode_sizer, flag=wx.ALIGN_CENTER | wx.TOP, border=12)
1307
1308 # The order of the choice items is significant for compatibility
1309 # with LUTFrame:
1310 # 0 = vcgt,
1311 # 1 = [rgb]TRC
1312 # 2 = gamut
1313 self.plot_mode_select = wx.Choice(
1314 p1,
1315 -1,
1316 choices=[
1317 lang.getstr("vcgt"),
1318 lang.getstr("[rgb]TRC"),
1319 lang.getstr("gamut"),
1320 ],
1321 )
1322 self.plot_mode_sizer.Add(self.plot_mode_select, flag=wx.ALIGN_CENTER_VERTICAL)
1323 self.plot_mode_select.Bind(wx.EVT_CHOICE, self.plot_mode_select_handler)
1324 self.plot_mode_select.Disable()
1325
1326 self.tooltip_btn = self._create_plot_toolbar_button(
1327 p1,
1328 lambda: get_icon(16, "question-inverted"),
1329 "?",
1330 lang.getstr("gamut_plot.tooltip"),
1331 8,
1332 self.tooltip_handler,
1333 )
1334
1335 self.save_plot_btn = self._create_plot_toolbar_button(
1336 p1,
1337 lambda: get_icon(16, "image-x-generic-inverted"),
1338 "Save",
1339 f"{lang.getstr('save_as')} (*.bmp, *.xbm, *.xpm, *.jpg, *.png)",
1340 8,
1341 self.SaveFile,
1342 )
1343 self.save_plot_btn.Disable()
1344
1345 self.view_3d_btn = self._create_plot_toolbar_button(
1346 p1,
1347 lambda: get_icon(16, "3D"),
1348 "3D",
1349 lang.getstr("view.3d"),
1350 12,
1351 self.view_3d,
1352 self.view_3d_format_popup,
1353 )
1354 self.view_3d_btn.Disable()
1355
1356 self.view_3d_format_btn = self._create_plot_toolbar_button(
1357 p1,
1358 lambda: get_bitmap("theme/dropdown-arrow"),
1359 "v",
1360 lang.getstr("view.3d"),
1361 4,
1362 self.view_3d_format_popup,
1363 self.view_3d_format_popup,
1364 )
1365 self.view_3d_format_btn.MinSize = (-1, self.view_3d_btn.Size[1])
1366 self.view_3d_format_btn.Disable()
1367
1368 self.client = GamutCanvas(p1)
1369 p1.sizer.Add(
1370 self.client,
1371 1,
1372 flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP | wx.BOTTOM,
1373 border=4,
1374 )
1375 self.options_panel = SimpleBook(p1)
1376 self.options_panel.SetBackgroundColour(BGCOLOUR)
1377 p1.sizer.Add(self.options_panel, flag=wx.EXPAND | wx.BOTTOM, border=8)
1378
1379 self.status = BitmapBackgroundPanelText(p1)
1380 self.status.SetMaxFontSize(11)
1381 self.status.label_y = 0
1382 self.status.textshadow = False
1383 self.status.SetBackgroundColour(BGCOLOUR)
1384 self.status.SetForegroundColour(FGCOLOUR)
1385 h = self.status.GetTextExtent("Ig")[1]
1386 self.status.SetMinSize((0, h * 2 + 10))
1387 p1.sizer.Add(self.status, flag=wx.EXPAND)
1388 self.gamut_status = BitmapBackgroundPanelTextGamut(p1)
1389 self.gamut_status.SetMaxFontSize(11)
1390 self.gamut_status.label_y = 0
1391 self.gamut_status.textshadow = False
1392 self.gamut_status.SetBackgroundColour(BGCOLOUR)
1393 self.gamut_status.SetForegroundColour(FGCOLOUR)
1394 h = self.gamut_status.GetTextExtent("Ig")[1]
1395 self.gamut_status.SetMinSize((0, h * 2 + 10))
1396 p1.sizer.Add(self.gamut_status, flag=wx.EXPAND)
1397 # Gamut view options
1398 self.gamut_view_options = GamutViewOptions(p1)
1399 self.options_panel.AddPage(self.gamut_view_options, "")
1400
1401 # Curve view options
1402 self.lut_view_options = wx_Panel(p1, name="lut_view_options")
1403 self.lut_view_options.SetBackgroundColour(BGCOLOUR)
1404 self.lut_view_options_sizer = self.box_sizer = wx.FlexGridSizer(0, 3, 4, 4)
1405 self.lut_view_options_sizer.AddGrowableCol(0)
1406 self.lut_view_options_sizer.AddGrowableCol(2)
1407 self.lut_view_options.SetSizer(self.lut_view_options_sizer)
1408 self.options_panel.AddPage(self.lut_view_options, "")
1409
1410 self.lut_view_options_sizer.Add((0, 0))
1411
1412 hsizer = wx.BoxSizer(wx.HORIZONTAL)
1413
1414 self.lut_view_options_sizer.Add(
1415 hsizer, flag=wx.ALIGN_CENTER | wx.BOTTOM, border=8
1416 )
1417
1418 self.rendering_intent_select = wx.Choice(
1419 self.lut_view_options,
1420 -1,
1421 choices=[
1422 lang.getstr("gamap.intents.a"),
1423 lang.getstr("gamap.intents.r"),
1424 lang.getstr("gamap.intents.p"),
1425 lang.getstr("gamap.intents.s"),
1426 ],
1427 )
1428 hsizer.Add((10, self.rendering_intent_select.Size[1]))
1429 hsizer.Add(self.rendering_intent_select, flag=wx.ALIGN_CENTER_VERTICAL)
1430 self.rendering_intent_select.Bind(
1431 wx.EVT_CHOICE, self.rendering_intent_select_handler
1432 )
1433 self.rendering_intent_select.SetSelection(1)
1434
1435 self.direction_select = wx.Choice(
1436 self.lut_view_options,
1437 -1,
1438 choices=[
1439 lang.getstr("direction.backward"),
1440 lang.getstr("direction.forward.inverted"),
1441 ],
1442 )
1443 hsizer.Add(
1444 self.direction_select, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=10
1445 )
1446 self.direction_select.Bind(wx.EVT_CHOICE, self.direction_select_handler)
1447 self.direction_select.SetSelection(0)
1448
1449 self.lut_view_options_sizer.Add((0, 0))
1450
1451 self.lut_view_options_sizer.Add((0, 0))
1452
1453 hsizer = wx.BoxSizer(wx.HORIZONTAL)
1454
1455 self.lut_view_options_sizer.Add(hsizer, flag=wx.ALIGN_CENTER)
1456
1457 hsizer.Add((16, 0))
1458
1459 if SAFE_WX_UI:
1460 self.show_as_L = wx.CheckBox(self.lut_view_options, -1, "L* \u2192")
1461 else:
1462 self.show_as_L = CustomCheckBox(self.lut_view_options, -1, "L* \u2192")
1463 self.show_as_L.SetForegroundColour(FGCOLOUR)
1464 self.show_as_L.SetValue(True)
1465 hsizer.Add(self.show_as_L, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=4)
1466 self.show_as_L.Bind(wx.EVT_CHECKBOX, self.DrawLUT)
1467
1468 self.add_toggles(self.lut_view_options, hsizer)
1469
1470 if SAFE_WX_UI:
1471 self.toggle_clut = wx.CheckBox(self.lut_view_options, -1, "LUT")
1472 else:
1473 self.toggle_clut = CustomCheckBox(self.lut_view_options, -1, "LUT")
1474 self.toggle_clut.SetForegroundColour(FGCOLOUR)
1475 hsizer.Add(self.toggle_clut, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=16)
1476 self.toggle_clut.Bind(wx.EVT_CHECKBOX, self.toggle_clut_handler)
1477
1478 self.lut_view_options_sizer.Add((0, 0))
1479
1480 p2 = wx_Panel(self.splitter, name="gridpanel")
1481 p2.sizer = wx.BoxSizer(wx.VERTICAL)
1482 p2.SetSizer(p2.sizer)
1483 self.splitter.AppendWindow(p2)
1484
1485 # Avoid CustomGrid subclassing path on macOS + Python 3.14 where
1486 # frame initialization still traps in native code.
1487 if SAFE_WX_UI:
1488 self.grid = wx.grid.Grid(p2, -1)
1489 else:
1490 self.grid = CustomGrid(p2, -1)
1491 self.grid.alternate_row_label_background_color = wx.Colour(230, 230, 230)
1492 self.grid.alternate_cell_background_color = (
1493 self.grid.alternate_row_label_background_color
1494 )
1495 self.grid.draw_horizontal_grid_lines = False
1496 self.grid.draw_vertical_grid_lines = False
1497 self.grid.draw_row_labels = False
1498 self.grid.show_cursor_outline = False
1499 self.grid.style = ""
1500 self.grid.CreateGrid(0, 2)
1501 self.grid.SetCellHighlightPenWidth(0)
1502 self.grid.SetCellHighlightROPenWidth(0)
1503 self.grid.SetDefaultCellBackgroundColour(self.grid.GetLabelBackgroundColour())
1504 if not SAFE_WX_UI:
1505 font = self.grid.GetDefaultCellFont()
1506 if font.PointSize > 11:
1507 font.PointSize = 11
1508 self.grid.SetDefaultCellFont(font)
1509 self.grid.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
1510 if not SAFE_WX_UI:
1511 self.grid.SetRowLabelSize(self.grid.GetDefaultRowSize())
1512 self.grid.SetColLabelSize(0)
1513 self.grid.DisableDragRowSize()
1514 self.grid.EnableDragColSize()
1515 self.grid.EnableEditing(False)
1516 self.grid.EnableGridLines(False)
1517 self.grid.Bind(wx.grid.EVT_GRID_COL_SIZE, self.resize_grid)
1518 p2.sizer.Add(self.grid, 1, flag=wx.EXPAND)
1519
1520 drophandlers = {".icc": self.drop_handler, ".icm": self.drop_handler}
1521 self.droptarget = FileDrop(self, drophandlers)
1522 self.client.SetDropTarget(self.droptarget)
1523 droptarget = FileDrop(self, drophandlers)
1524 self.grid.SetDropTarget(droptarget)
1525
1526 min_w = max(
1527 self.options_panel.GetBestSize()[0] + 24,
1528 DEFAULTS["size.profile_info.w"] - self.splitter._GetSashSize(),
1529 )
1530
1531 self.splitter.SetMinimumPaneSize(min_w)
1532 self.splitter.SetHSplit(0)
1533
1534 border, titlebar = get_platform_window_decoration_size()
1535 self.SetSaneGeometry(
1536 getcfg("position.profile_info.x"),
1537 getcfg("position.profile_info.y"),
1538 DEFAULTS["size.profile_info.split.w"],
1539 getcfg("size.profile_info.h"),
1540 )
1541 self.SetMinSize(
1542 (min_w + border * 2, DEFAULTS["size.profile_info.h"] + titlebar + border)
1543 )
1544 self.splitter.SetSplitSize(
1545 (DEFAULTS["size.profile_info.split.w"], self.ClientSize[1])
1546 )
1547 self.splitter.SetExpandedSize(self.ClientSize)
1548
1549 self.client.canvas.Bind(wx.EVT_MOTION, self.OnMotion)
1550 self.Bind(wx.EVT_CLOSE, self.OnClose)
1551 self.Bind(wx.EVT_MOVE, self.OnMove)
1552 self.Bind(wx.EVT_SIZE, self.OnSize)
1553 self.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGING, self.OnSashPosChanging)
1554
1555 self.display_no = -1
1556 self.display_rects = get_display_rects()
1557
1558 children = list(self.GetAllChildren())
1559
1560 self.Bind(wx.EVT_KEY_DOWN, self.key_handler)
1561 for child in children:
1562 if isinstance(child, wx.Choice):
1563 child.SetMaxFontSize(11)
1564 child.Bind(wx.EVT_KEY_DOWN, self.key_handler)
1565 child.Bind(wx.EVT_MOUSEWHEEL, self.OnWheel)
1566 if (
1567 sys.platform == "win32"
1568 and sys.getwindowsversion() >= (6,)
1569 and isinstance(child, wx.Panel)
1570 ):
1571 # No need to enable double buffering under Linux and Mac OS X.
1572 # Under Windows, enabling double buffering on the panel seems
1573 # to work best to reduce flicker.
1574 child.SetDoubleBuffered(True)
1575
1576 def DrawCanvas(self, profile_no=None, reset=True):
1577 """Draw the canvas with the current profile and settings.
1578
1579 Args:
1580 profile_no (int): The profile number to draw, if applicable.
1581 reset (bool): Whether to reset the canvas before drawing.
1582 """
1583 self.SetStatusText("")
1584 if self.plot_mode_select.GetSelection() == self.plot_mode_select.GetCount() - 1:
1585 # Gamut plot
1586 self.plot_mode_sizer.Show(self.view_3d_btn)
1587 self.plot_mode_sizer.Show(self.view_3d_format_btn)
1588 self.options_panel.GetCurrentPage().DrawCanvas(reset=reset)
1589 self.save_plot_btn.Enable()
1590 self.view_3d_btn.Enable()
1591 self.view_3d_format_btn.Enable()
1592 else:
1593 # Curves plot
1594 self.plot_mode_sizer.Hide(self.view_3d_btn)
1595 self.plot_mode_sizer.Hide(self.view_3d_format_btn)
1596 self.client.SetEnableCenterLines(True)
1597 self.client.SetEnableDiagonals("Bottomleft-Topright")
1598 self.client.SetEnableGrid(False)
1599 self.client.SetEnablePointLabel(True)
1600 if (
1601 isinstance(self.profile.tags.get("vcgt"), VideoCardGammaType)
1602 or (self.rTRC and self.gTRC and self.bTRC)
1603 or ("B2A0" in self.profile.tags or "A2B0" in self.profile.tags)
1604 ):
1605 self.DrawLUT()
1606 self.handle_errors()
1607 else:
1608 self.client.DrawLUT()
1609 self.splitter.GetTopLeft().sizer.Layout()
1610 self.splitter.GetTopLeft().Refresh()
1611
1612 def LoadProfile(self, profile, reset=True):
1613 """Load a profile and update the canvas.
1614
1615 Args:
1616 profile (str or ICCProfile): The profile to load, either as a file path
1617 or as an ICCProfile object.
1618 reset (bool): Whether to reset the canvas before loading the profile.
1619 """
1620 if not isinstance(profile, ICCProfile):
1621 try:
1622 profile = ICCProfile(profile)
1623 except (OSError, ICCProfileInvalidError):
1624 show_result_dialog(
1625 Error(f"{lang.getstr('profile.invalid')}\n{profile}"), self
1626 )
1627 self.DrawCanvas(reset=reset)
1628 return
1629 if (
1630 not reset
1631 and getattr(self, "profile", None)
1632 and self.profile.colorSpace != profile.colorSpace
1633 ):
1634 reset = True
1635 self.profile = profile
1636 cinfo = []
1637 vinfo = []
1638 if "meta" in profile.tags:
1639 # for key in ("avg", "max", "rms"):
1640 # try:
1641 # dE = float(profile.tags.meta.getvalue(f"ACCURACY_dE76_{key}"))
1642 # except (TypeError, ValueError):
1643 # pass
1644
1645 gamuts = (
1646 ("srgb", "sRGB", GAMUT_VOLUME_SRGB),
1647 ("adobe-rgb", "Adobe RGB", GAMUT_VOLUME_ADOBERGB),
1648 ("dci-p3", "DCI P3", GAMUT_VOLUME_SMPTE431_P3),
1649 )
1650 for key, name, _volume in gamuts:
1651 try:
1652 gamut_coverage = profile.tags.meta.getvalue(
1653 f"GAMUT_coverage({key})"
1654 )
1655 gamut_coverage = (
1656 float(gamut_coverage)
1657 if gamut_coverage is not None
1658 else gamut_coverage
1659 )
1660 except (TypeError, ValueError):
1661 traceback.print_exc()
1662 gamut_coverage = None
1663 if gamut_coverage:
1664 cinfo.append(f"{gamut_coverage * 100:.1f}% {name}")
1665 try:
1666 gamut_volume = float(profile.tags.meta.getvalue("GAMUT_volume"))
1667 except (TypeError, ValueError):
1668 traceback.print_exc()
1669 gamut_volume = None
1670 if gamut_volume:
1671 for _key, name, volume in gamuts:
1672 vinfo.append(
1673 f"{gamut_volume * GAMUT_VOLUME_SRGB / volume * 100:.1f}% {name}"
1674 )
1675 if len(vinfo) == len(cinfo):
1676 break
1677
1678 if gamut_coverage and gamut_volume:
1679 gamut_cov_text = f"{cinfo[0]} {cinfo[1]} {cinfo[2]}"
1680 self.SetGamutStatusText(gamut_cov_text)
1681
1682 for channel in "rgb":
1683 trc = profile.tags.get(f"{channel}TRC", profile.tags.get("kTRC"))
1684 if isinstance(trc, ParametricCurveType):
1685 trc = trc.get_trc()
1686 setattr(self, f"{channel}TRC", trc)
1687 setattr(self, f"tf_{channel}TRC", trc)
1688 self.trc = None
1689
1690 self.gamut_view_options.direction_select.Enable(
1691 "B2A0" in self.profile.tags and "A2B0" in self.profile.tags
1692 )
1693 if not self.gamut_view_options.direction_select.Enabled:
1694 self.gamut_view_options.direction_select.SetSelection(0)
1695 self.gamut_view_options.toggle_clut.SetValue(
1696 "B2A0" in profile.tags or "A2B0" in profile.tags
1697 )
1698 self.gamut_view_options.toggle_clut.Show(
1699 "B2A0" in profile.tags or "A2B0" in profile.tags
1700 )
1701 self.gamut_view_options.toggle_clut.Enable(
1702 isinstance(self.rTRC, CurveType)
1703 and isinstance(self.gTRC, CurveType)
1704 and isinstance(self.bTRC, CurveType)
1705 )
1706 self.toggle_clut.SetValue("B2A0" in profile.tags or "A2B0" in profile.tags)
1707
1708 plot_mode = self.plot_mode_select.GetStringSelection()
1709 choice = []
1710 info = profile.get_info()
1711 self.client.errors = []
1712 if (self.rTRC and self.gTRC and self.bTRC) or (
1713 self.toggle_clut.GetValue()
1714 and profile.colorSpace in (b"RGB", b"GRAY", b"CMYK")
1715 ):
1716 if "vcgt" in profile.tags or "MS00" in profile.tags:
1717 choice.append(lang.getstr("vcgt"))
1718 try:
1719 self.lookup_tone_response_curves()
1720 except Exception as exception:
1721 wx.CallAfter(show_result_dialog, exception, self)
1722 else:
1723 choice.append(lang.getstr("[rgb]TRC"))
1724 choice = self.add_shaper_curves(choice)
1725 choice.append(lang.getstr("gamut"))
1726 self.Freeze()
1727 self.plot_mode_select.SetItems(choice)
1728 if not self.plot_mode_select.SetStringSelection(plot_mode):
1729 self.plot_mode_select.SetSelection(self.plot_mode_select.GetCount() - 1)
1730 reset = True
1731 self.select_current_page()
1732 self.plot_mode_select.Enable()
1733
1734 self.SetTitle(
1735 " \u2014 ".join([lang.getstr("profile.info"), profile.getDescription()])
1736 )
1737
1738 rows = [("", "")]
1739 lines = []
1740 for label, value in info:
1741 label = label.replace("\0", "")
1742 if value is None:
1743 value = ""
1744 elif not isinstance(value, str):
1745 value = str(value, "ascii")
1746 value = (
1747 wrap(universal_newlines(value.strip()).replace("\t", "\n"), 52)
1748 .replace("\0", "")
1749 .split("\n")
1750 )
1751 linecount = len(value)
1752 for i, line in enumerate(value):
1753 value[i] = line.strip()
1754 label = universal_newlines(label).split("\n")
1755 while len(label) < linecount:
1756 label.append("")
1757 lines.extend(list(zip(label, value)))
1758 for line in lines:
1759 line = list(line)
1760 indent = re.match(r"\s+", line[0])
1761 for j, v in enumerate(line):
1762 if v.endswith("_"):
1763 continue
1764 key = re.sub(
1765 r"[^0-9A-Za-z]+",
1766 "_",
1767 strtr(v, {"\u0394E": "Delta E"}).lower().strip(),
1768 count=0,
1769 ).strip("_")
1770 val = lang.getstr(key)
1771 if key != val:
1772 line[j] = val
1773 if indent:
1774 # if i + 1 < len(lines) and lines[i + 1][0].startswith(" "):
1775 # marker = u" ├ "
1776 # else:
1777 # marker = u" └ "
1778 line[0] = indent.group() + line[0].strip()
1779 elif line[0]:
1780 # if i + 1 < len(lines) and lines[i + 1][0].startswith(" "):
1781 # marker = u"▼ "
1782 # else:
1783 # marker = u"► "
1784 pass
1785 rows.append(line)
1786
1787 rows.append(("", ""))
1788
1789 if self.grid.GetNumberRows():
1790 self.grid.DeleteRows(0, self.grid.GetNumberRows())
1791 self.grid.AppendRows(len(rows))
1792 labelcolor = self.grid.GetLabelTextColour()
1793 alpha = 102
1794 namedcolor = False
1795 for i, (label, value) in enumerate(rows):
1796 self.grid.SetCellValue(i, 0, f" {label}")
1797 bgcolor = self.grid.GetCellBackgroundColour(i, 0)
1798 bgblend = (255 - alpha) / 255.0
1799 blend = alpha / 255.0
1800 textcolor = wx.Colour(
1801 round(bgblend * bgcolor.Red() + blend * labelcolor.Red()),
1802 round(bgblend * bgcolor.Green() + blend * labelcolor.Green()),
1803 round(bgblend * bgcolor.Blue() + blend * labelcolor.Blue()),
1804 )
1805 if label == lang.getstr("named_colors"):
1806 namedcolor = True
1807 elif label.strip() and label.lstrip() == label:
1808 namedcolor = False
1809 if namedcolor:
1810 color = re.match(r"(Lab|XYZ)((?:\s+-?\d+(?:\.\d+)){3,})", value)
1811 else:
1812 color = None
1813 if color:
1814 if color.groups()[0] == "Lab":
1815 color = colormath.Lab2RGB(
1816 *[float(v) for v in color.groups()[1].strip().split()],
1817 scale=255,
1818 )
1819 else:
1820 # XYZ
1821 color = colormath.XYZ2RGB(
1822 *[float(v) for v in color.groups()[1].strip().split()],
1823 scale=255,
1824 )
1825 labelbgcolor = wx.Colour(*[round(v) for v in color])
1826 rowlabelrenderer = CustomRowLabelRenderer(labelbgcolor)
1827 else:
1828 rowlabelrenderer = None
1829 if not SAFE_WX_UI:
1830 self.grid.SetRowLabelRenderer(i, rowlabelrenderer)
1831 self.grid.SetCellTextColour(i, 0, textcolor)
1832 self.grid.SetCellValue(i, 1, value)
1833
1834 self.grid.AutoSizeColumn(0)
1835 self.resize_grid()
1836 self.grid.ClearSelection()
1837 self.Layout()
1838 self.DrawCanvas(reset=reset)
1839 self.Thaw()
1840
1841 def OnClose(self, event):
1842 """Handle the close event for the profile info frame.
1843
1844 Args:
1845 event (wx.Event): The close event that triggered this method.
1846 """
1847 if getattr(self.worker, "thread", None) and self.worker.thread.is_alive():
1848 self.worker.abort_subprocess(True)
1849 return
1850 self.worker.wrapup(False)
1851 writecfg(
1852 module="profile-info",
1853 options=(
1854 "3d.format",
1855 "last_cal_or_icc_path",
1856 "last_icc_path",
1857 "position.profile_info",
1858 "size.profile_info",
1859 ),
1860 )
1861 # Hide first (looks nicer)
1862 self.Hide()
1863 # Need to use CallAfter to prevent hang under Windows if minimized
1864 wx.CallAfter(self.Destroy)
1865
1866 def OnMotion(self, event):
1867 """Handle mouse motion events for the profile info module.
1868
1869 Args:
1870 event (wx.MouseEvent): The mouse event that triggered this method.
1871 """
1872 xy = self.client._getXY(event) if isinstance(event, wx.MouseEvent) else event
1873 if self.plot_mode_select.GetSelection() < self.plot_mode_select.GetCount() - 1:
1874 # Curves plot
1875 if isinstance(event, wx.MouseEvent):
1876 if not event.LeftIsDown():
1877 self.UpdatePointLabel(xy)
1878 else:
1879 self.client.erase_pointlabel()
1880 else:
1881 # Gamut plot
1882 page = self.options_panel.GetCurrentPage()
1883 if page.colorspace in ("a*b*", "u*v*") or page.colorspace.startswith(
1884 "DIN99"
1885 ):
1886 format_ = "{:.2f} {:.2f}"
1887 else:
1888 format_ = "{:.4f} {:.4f}"
1889 whitepoint_no = page.whitepoint_select.GetSelection()
1890 if whitepoint_no > 0:
1891 if page.colorspace == "a*b*":
1892 x, y, Y = colormath.Lab2xyY(100.0, xy[0], xy[1])
1893 elif page.colorspace == "u*v*":
1894 X, Y, Z = colormath.Luv2XYZ(100.0, xy[0], xy[1])
1895 x, y = colormath.XYZ2xyY(X, Y, Z)[:2]
1896 elif page.colorspace == "u'v'":
1897 x, y = colormath.u_v_2xy(xy[0], xy[1])
1898 elif page.colorspace.startswith("DIN99"):
1899 # DIN99
1900 L99 = colormath.Lab2DIN99(100, 0, 0)[0]
1901 if page.colorspace == "DIN99b":
1902 # DIN99b
1903 a, b = colormath.DIN99b2Lab(L99, xy[0], xy[1])[1:]
1904 elif page.colorspace == "DIN99c":
1905 # DIN99c
1906 a, b = colormath.DIN99c2Lab(L99, xy[0], xy[1])[1:]
1907 elif page.colorspace == "DIN99d":
1908 # DIN99d
1909 a, b = colormath.DIN99d2Lab(L99, xy[0], xy[1])[1:]
1910 else:
1911 # DIN99
1912 a, b = colormath.DIN992Lab(L99, xy[0], xy[1])[1:]
1913 x, y = colormath.Lab2xyY(100.0, a, b)[:2]
1914 elif page.colorspace == "ICtCp":
1915 X, Y, Z = colormath.ICtCp2XYZ(1.0, xy[0], xy[1])
1916 x, y = colormath.XYZ2xyY(X, Y, Z)[:2]
1917 elif page.colorspace == "IPT":
1918 X, Y, Z = colormath.IPT2XYZ(1.0, xy[0], xy[1])
1919 x, y = colormath.XYZ2xyY(X, Y, Z)[:2]
1920 elif page.colorspace == "Lpt":
1921 X, Y, Z = colormath.Lpt2XYZ(100.0, xy[0], xy[1])
1922 x, y = colormath.XYZ2xyY(X, Y, Z)[:2]
1923 else:
1924 # xy
1925 x, y = xy
1926 cct, delta = colormath.xy_CCT_delta(x, y, daylight=whitepoint_no == 1)
1927 status = format_.format(*xy)
1928 if cct:
1929 if delta:
1930 locus = {"Blackbody": "blackbody", "Daylight": "daylight"}.get(
1931 page.whitepoint_select.GetStringSelection(),
1932 page.whitepoint_select.GetStringSelection(),
1933 )
1934 status = "{}, CCT {} ({} {:.2f})".format(
1935 format_.format(*xy),
1936 cct,
1937 lang.getstr("delta_e_to_locus", locus),
1938 delta["E"],
1939 )
1940 else:
1941 status = f"{format_.format(*xy)}, CCT {cct}"
1942 self.SetStatusText(status)
1943 else:
1944 self.SetStatusText(format_.format(*xy))
1945 if isinstance(event, wx.MouseEvent):
1946 event.Skip() # Go to next handler
1947
1948 def OnMove(self, event=None):
1949 """Handle move events for the profile info module.
1950
1951 Args:
1952 event (wx.Event, optional): The event that triggered this method.
1953 """
1954 if self.IsShownOnScreen() and not self.IsMaximized() and not self.IsIconized():
1955 x, y = self.GetScreenPosition()
1956 setcfg("position.profile_info.x", x)
1957 setcfg("position.profile_info.y", y)
1958 if event:
1959 event.Skip()
1960
1961 def OnSashPosChanging(self, event):
1962 """Handle sash position changing events for the profile info module.
1963
1964 Args:
1965 event (wx.Event): The event that triggered this method.
1966 """
1967 self.splitter.SetExpandedSize(
1968 (self.splitter._splitx + self.splitter._GetSashSize(), self.ClientSize[1])
1969 )
1970 setcfg(
1971 "size.profile_info.w", self.splitter._splitx + self.splitter._GetSashSize()
1972 )
1973 wx.CallAfter(self.redraw)
1974 wx.CallAfter(self.resize_grid)
1975
1976 def OnSize(self, event=None):
1977 """Handle size events for the profile info module.
1978
1979 Args:
1980 event (wx.Event, optional): The event that triggered this method.
1981 """
1982 if (
1983 self.IsShownOnScreen()
1984 and self.IsMaximized()
1985 and self.splitter._expanded < 0
1986 ):
1987 self.splitter.AdjustLayout()
1988 self.splitter.Refresh()
1989 wx.CallAfter(self.redraw)
1990 wx.CallAfter(self.resize_grid)
1991 if self.IsShownOnScreen() and not self.IsIconized():
1992 wx.CallAfter(self._setsize)
1993 if event:
1994 event.Skip()
1995
1996 def OnWheel(self, event):
1997 """Handle mouse wheel events for zooming in/out on the canvas.
1998
1999 Args:
2000 event (wx.Event): The event that triggered this method.
2001 """
2002 xy = wx.GetMousePosition()
2003 if not self.client.GetClientRect().Contains(self.client.ScreenToClient(xy)):
2004 if self.grid.GetClientRect().Contains(self.grid.ScreenToClient(xy)):
2005 self.grid.SetFocus()
2006 event.Skip()
2007 elif self.client.last_draw:
2008 direction = 1.0 if event.WheelRotation < 0 else -1.0
2009 self.client.zoom(direction)
2010
2011 def _setsize(self):
2012 """Set the size of the profile info module based on the current state."""
2013 if self.IsMaximized():
2014 return
2015 w, h = self.ClientSize
2016 if self.splitter._expanded < 0:
2017 self.splitter.SetExpandedSize(
2018 (self.splitter._splitx + self.splitter._GetSashSize(), h)
2019 )
2020 self.splitter.SetSplitSize((w, h))
2021 setcfg(
2022 "size.profile_info.w",
2023 self.splitter._splitx + self.splitter._GetSashSize(),
2024 )
2025 setcfg("size.profile_info.split.w", w)
2026 else:
2027 self.splitter.SetExpandedSize((w, h))
2028 setcfg("size.profile_info.w", w)
2029 setcfg("size.profile_info.h", h)
2030
2031 def drop_handler(self, path):
2032 """Handle Drag'n'drop for .cal/.icc/.icm files.
2033
2034 Args:
2035 path (str): The file path of the dropped file.
2036 """
2037 reset = (
2038 self.plot_mode_select.GetSelection() == self.plot_mode_select.GetCount() - 1
2039 )
2040 self.LoadProfile(path, reset=reset)
2041
2042 def get_platform_window_size(
2043 self, defaultwidth=None, defaultheight=None, split=False
2044 ):
2045 """Get the platform-specific window size for the profile info module.
2046
2047 Args:
2048 defaultwidth (int, optional): Default width if not specified.
2049 defaultheight (int, optional): Default height if not specified.
2050 split (bool, optional): Whether to get the size for the split view.
2051
2052 Returns:
2053 tuple: A tuple containing the width and height of the window.
2054 """
2055 name = ".split" if split else ""
2056 if not defaultwidth:
2057 defaultwidth = DEFAULTS[f"size.profile_info{name}.w"]
2058 if not defaultheight:
2059 defaultheight = DEFAULTS["size.profile_info.h"]
2060 border, titlebar = get_platform_window_decoration_size()
2061 # return (max(max(getcfg("size.profile_info{name}.w"),
2062 # defaultwidth), self.GetMinSize()[0] - border * 2),
2063 # max(getcfg("size.profile_info.h"),
2064 # defaultheight))
2065 if split:
2066 w, h = self.splitter.GetSplitSize()
2067 else:
2068 w, h = self.splitter.GetExpandedSize()
2069 return (
2070 max(w, defaultwidth, self.GetMinSize()[0] - border * 2),
2071 max(h, defaultheight),
2072 )
2073
2074 def key_handler(self, event):
2075 """Handle key events for the profile info module.
2076
2077 Args:
2078 event (wx.Event): The event that triggered this method.
2079 """
2080 # AltDown
2081 # CmdDown
2082 # ControlDown
2083 # GetKeyCode
2084 # GetModifiers
2085 # GetPosition
2086 # GetRawKeyCode
2087 # GetRawKeyFlags
2088 # GetUniChar
2089 # GetUnicodeKey
2090 # GetX
2091 # GetY
2092 # HasModifiers
2093 # KeyCode
2094 # MetaDown
2095 # Modifiers
2096 # Position
2097 # RawKeyCode
2098 # RawKeyFlags
2099 # ShiftDown
2100 # UnicodeKey
2101 # X
2102 # Y
2103 key = event.GetKeyCode()
2104 if (
2105 event.ControlDown() or event.CmdDown()
2106 ): # CTRL (Linux/Mac/Windows) / CMD (Mac)
2107 focus = self.FindFocus()
2108 if focus and self.grid in (
2109 focus,
2110 focus.GetParent(),
2111 focus.GetGrandParent(),
2112 ):
2113 event.Skip()
2114 if key == 83 and self.profile: # S
2115 self.SaveFile()
2116 return
2117 event.Skip()
2118 elif key in (43, wx.WXK_NUMPAD_ADD):
2119 # + key zoom in
2120 self.client.zoom(-1)
2121 elif key in (45, wx.WXK_NUMPAD_SUBTRACT):
2122 # - key zoom out
2123 self.client.zoom(1)
2124 else:
2125 event.Skip()
2126
2127 def plot_mode_select_handler(self, event):
2128 """Handle changes in the plot mode selection.
2129
2130 Args:
2131 event (wx.Event): The event that triggered this method.
2132 """
2133 self.Freeze()
2134 self.select_current_page()
2135 reset = (
2136 self.plot_mode_select.GetSelection() == self.plot_mode_select.GetCount() - 1
2137 )
2138 self.DrawCanvas(reset=reset)
2139 self.Thaw()
2140
2141 def get_commands(self):
2142 """Get a list of commands that this module can process.
2143
2144 Returns:
2145 list: A list of command strings that this module can process.
2146 """
2147 return [
2148 *self.get_common_commands(),
2149 "profile-info [filename]",
2150 "load <filename>",
2151 ]
2152
2153 def process_data(self, data):
2154 """Process commands from the command line or other sources.
2155
2156 Args:
2157 data (list): A list of strings containing the command and its
2158 arguments.
2159
2160 Returns:
2161 str: "ok" if the command was processed successfully, "fail" if it
2162 failed, or "invalid" if the command was not recognized.
2163 """
2164 if (data[0] == "profile-info" and len(data) < 3) or (
2165 data[0] == "load" and len(data) == 2
2166 ):
2167 if self.IsIconized():
2168 self.Restore()
2169 self.Raise()
2170 if len(data) == 2:
2171 path = data[1]
2172 if not os.path.isfile(path) and not os.path.isabs(path):
2173 path = get_data_path(path)
2174 if not path:
2175 return "fail"
2176 self.droptarget.OnDropFiles(0, 0, [path])
2177 return "ok"
2178 return "invalid"
2179
2180 def redraw(self):
2181 """Redraw the canvas if the plot mode is set to gamut."""
2182 if (
2183 self.plot_mode_select.GetSelection() == self.plot_mode_select.GetCount() - 1
2184 and self.client.last_draw
2185 ):
2186 # Update gamut plot
2187 self.client.Parent.Freeze()
2188 self.client._DrawCanvas(self.client.last_draw[0])
2189 self.client.Parent.Thaw()
2190
2191 def resize_grid(self, event=None):
2192 """Resize the grid to fit the available space.
2193
2194 Args:
2195 event (wx.Event, optional): The event that triggered this method.
2196 Defaults to None.
2197 """
2198 self.grid.SetColSize(
2199 1,
2200 max(
2201 self.grid.GetSize()[0]
2202 - self.grid.GetRowLabelSize()
2203 - self.grid.GetColSize(0)
2204 - wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X),
2205 0,
2206 ),
2207 )
2208 self.grid.SetMargins(
2209 0 - wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X),
2210 0 - wx.SystemSettings_GetMetric(wx.SYS_HSCROLL_Y),
2211 )
2212 self.grid.ForceRefresh()
2213
2214 def select_current_page(self):
2215 """Select the current page in the options panel based on the plot mode."""
2216 if self.plot_mode_select.GetSelection() == self.plot_mode_select.GetCount() - 1:
2217 # Gamut plot
2218 self.options_panel.SetSelection(0)
2219 else:
2220 # Curves plot
2221 self.options_panel.SetSelection(1)
2222 self.splitter.GetTopLeft().Layout()
2223
2224 def view_3d(self, event):
2225 """View 3D visualization of the gamut.
2226
2227 Args:
2228 event (wx.Event): The event that triggered this method.
2229 """
2230 profile = self.profile
2231 if not profile:
2232 defaultDir, defaultFile = get_verified_path("last_icc_path")
2233 dlg = wx.FileDialog(
2234 self,
2235 lang.getstr("profile.choose"),
2236 defaultDir=defaultDir,
2237 defaultFile=defaultFile,
2238 wildcard=f"{lang.getstr('filetype.icc')}|*.icc;*.icm",
2239 style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
2240 )
2241 dlg.Center(wx.BOTH)
2242 result = dlg.ShowModal()
2243 path = dlg.GetPath()
2244 dlg.Destroy()
2245 if result != wx.ID_OK:
2246 return
2247 try:
2248 profile = ICCProfile(path)
2249 except (OSError, ICCProfileInvalidError):
2250 show_result_dialog(
2251 Error(f"{lang.getstr('profile.invalid')}\n{path}"), self
2252 )
2253 else:
2254 setcfg("last_icc_path", path)
2255 setcfg("last_cal_or_icc_path", path)
2256 if profile:
2257 view_3d_format = getcfg("3d.format")
2258 if view_3d_format == "HTML":
2259 x3d = True
2260 html = True
2261 elif view_3d_format == "X3D":
2262 x3d = True
2263 html = False
2264 else:
2265 x3d = False
2266 html = False
2267 profile_path = None
2268 if profile.filename and os.path.isfile(profile.filename):
2269 profile_path = profile.filename
2270 if not profile_path or not waccess(os.path.dirname(profile_path), os.W_OK):
2271 result = self.worker.create_tempdir()
2272 if isinstance(result, Exception):
2273 show_result_dialog(result, self)
2274 return
2275 desc = profile.getDescription()
2276 profile_path = os.path.join(
2277 self.worker.tempdir,
2278 f"{make_argyll_compatible_path(desc, is_name=True)}{PROFILE_EXT}",
2279 )
2280 profile.write(profile_path)
2281 profile_mtime = os.stat(profile_path).st_mtime
2282 filename, ext = os.path.splitext(profile_path)
2283 comparison_profile = self.gamut_view_options.comparison_profile
2284 comparison_profile_path = None
2285 comparison_profile_mtime = 0
2286 if comparison_profile:
2287 comparison_profile_path = comparison_profile.filename
2288 if comparison_profile_path and not waccess(
2289 os.path.dirname(comparison_profile_path), os.W_OK
2290 ):
2291 result = self.worker.create_tempdir()
2292 if isinstance(result, Exception):
2293 show_result_dialog(result, self)
2294 return
2295 comparison_profile_path = os.path.join(
2296 self.worker.tempdir,
2297 make_argyll_compatible_path(
2298 os.path.basename(comparison_profile_path), is_name=True
2299 ),
2300 )
2301 comparison_profile.write(comparison_profile_path)
2302 comparison_profile_mtime = os.stat(comparison_profile_path).st_mtime
2303 mods = []
2304 intent = self.gamut_view_options.intent
2305 if intent != "r":
2306 mods.append(intent)
2307 direction = self.gamut_view_options.direction[-1]
2308 if direction != "f":
2309 mods.append(direction)
2310 order = self.gamut_view_options.order
2311 if order != "n":
2312 mods.append(order)
2313 if mods:
2314 filename = "{} {}".format(
2315 filename, "".join([f"[{mod.upper()}]" for mod in mods])
2316 )
2317 if comparison_profile_path:
2318 filename += (
2319 " vs "
2320 + os.path.splitext(os.path.basename(comparison_profile_path))[0]
2321 )
2322 if mods:
2323 filename = "{} {}".format(
2324 filename, "".join([f"[{mod.upper()}]" for mod in mods])
2325 )
2326 for vrmlext in (".vrml", ".vrml.gz", ".wrl", ".wrl.gz", ".wrz"):
2327 vrmlpath = f"{filename}{vrmlext}"
2328 if sys.platform == "win32":
2329 vrmlpath = make_win32_compatible_long_path(vrmlpath)
2330 if os.path.isfile(vrmlpath):
2331 break
2332 outfilename = filename
2333 colorspace = self.gamut_view_options.get_colorspace(3)
2334 if colorspace != "Lab":
2335 outfilename = f"{outfilename} {colorspace}"
2336 vrmloutpath = f"{outfilename}{vrmlext}"
2337 x3dpath = f"{outfilename}.x3d"
2338 if html:
2339 finalpath = f"{x3dpath}.html"
2340 elif x3d:
2341 finalpath = x3dpath
2342 else:
2343 finalpath = vrmloutpath
2344 if sys.platform == "win32":
2345 vrmloutpath = make_win32_compatible_long_path(vrmloutpath)
2346 x3dpath = make_win32_compatible_long_path(x3dpath)
2347 finalpath = make_win32_compatible_long_path(finalpath)
2348 for outpath in (finalpath, vrmloutpath, vrmlpath):
2349 if os.path.isfile(outpath):
2350 mtime = os.stat(outpath).st_mtime
2351 if profile_mtime > mtime or comparison_profile_mtime > mtime:
2352 # Profile(s) have changed, delete existing 3D visualization
2353 # so it will be re-generated
2354 os.remove(outpath)
2355 if os.path.isfile(finalpath):
2356 launch_file(finalpath)
2357 elif os.path.isfile(vrmloutpath):
2358 self.view_3d_consumer(True, None, None, vrmloutpath, x3d, x3dpath, html)
2359 elif os.path.isfile(vrmlpath):
2360 self.view_3d_consumer(
2361 True, colorspace, None, vrmlpath, x3d, x3dpath, html
2362 )
2363 else:
2364 # Create VRML file
2365 profile_paths = [profile_path]
2366 if comparison_profile_path:
2367 profile_paths.append(comparison_profile_path)
2368 self.worker.start(
2369 self.view_3d_consumer,
2370 self.worker.calculate_gamut,
2371 cargs=(colorspace, filename, None, x3d, x3dpath, html),
2372 wargs=(profile_paths, intent, direction, order, False),
2373 progress_msg=lang.getstr("gamut.view.create"),
2374 continue_next=x3d,
2375 fancy=False,
2376 )
2377
2378 def view_3d_consumer(
2379 self, result, colorspace, filename, vrmlpath, x3d, x3dpath, html
2380 ):
2381 """Consumer function for viewing 3D formats.
2382
2383 Args:
2384 result (bool): Indicates if the VRML file was successfully created.
2385 colorspace (str): The colorspace to use for the VRML file.
2386 filename (str): The base filename for the VRML file.
2387 vrmlpath (str): The path to the VRML file.
2388 x3d (bool): If True, convert to X3D format.
2389 x3dpath (str): The path for the X3D file.
2390 html (bool): If True, embed in HTML.
2391 """
2392 if filename:
2393 if getcfg("vrml.compress"):
2394 vrmlpath = f"{filename}.wrz"
2395 else:
2396 vrmlpath = f"{filename}.wrl"
2397 if os.path.isfile(vrmlpath) and colorspace not in ("Lab", None):
2398 filename, ext = os.path.splitext(vrmlpath)
2399 cls = GzipFileProper if ext.lower() in (".gz", ".wrz") else open
2400 with cls(vrmlpath, "rb") as vrmlfile:
2401 vrml = vrmlfile.read()
2402 vrml = x3dom.update_vrml(vrml, colorspace)
2403 vrmlpath = f"{filename} {colorspace}{ext}"
2404 with cls(vrmlpath, "wb") as vrmlfile:
2405 vrmlfile.write(vrml)
2406 if not os.path.isfile(vrmlpath):
2407 if self.worker.errors:
2408 result = UnloggedError("".join(self.worker.errors).strip())
2409 else:
2410 result = Error(lang.getstr("file.missing", vrmlpath))
2411 if isinstance(result, Exception):
2412 self.worker.stop_progress()
2413 show_result_dialog(result, self)
2414 elif x3d:
2415 vrmlfile2x3dfile(
2416 vrmlpath,
2417 x3dpath,
2418 embed=getcfg("x3dom.embed"),
2419 html=html,
2420 view=True,
2421 force=False,
2422 cache=getcfg("x3dom.cache"),
2423 worker=self.worker,
2424 )
2425 else:
2426 launch_file(vrmlpath)
2427
2428 def view_3d_format_popup(self, event):
2429 """Show a popup menu to select the 3D format for viewing.
2430
2431 Args:
2432 event (wx.MouseEvent): The event that triggered the popup menu.
2433 """
2434 menu = wx.Menu()
2435 for file_format in config.VALID_VALUES["3d.format"]:
2436 item = menu.AppendRadioItem(-1, file_format)
2437 item.Check(file_format == getcfg("3d.format"))
2438 self.Bind(wx.EVT_MENU, self.view_3d_format_handler, id=item.Id)
2439
2440 self.PopupMenu(menu)
2441 for item in menu.MenuItems:
2442 self.Unbind(wx.EVT_MENU, id=item.Id)
2443 menu.Destroy()
2444
2445 def view_3d_format_handler(self, event):
2446 """Handle the 3D format selection popup menu.
2447
2448 Args:
2449 event (wx.CommandEvent): The event triggered by the menu selection.
2450 """
2451 for item in event.EventObject.MenuItems:
2452 if item.IsChecked():
2453 setcfg("3d.format", item.GetItemLabelText())
2454
2455 self.view_3d(None)
2456
2457
2458 def main():
2459 """Main function to run the ProfileInfoFrame application."""
2460 config.initcfg("profile-info")
2461 lang.init()
2462 lang.update_defaults()
2463 app = BaseApp(0)
2464 app.TopWindow = ProfileInfoFrame(None, -1)
2465 if sys.platform == "darwin":
2466 app.TopWindow.init_menubar()
2467 wx.CallLater(1, _main, app)
2468 app.MainLoop()
2469
2470
2471 def _main(app):
2472 app.TopWindow.listen()
2473 display_no = get_argyll_display_number(app.TopWindow.get_display()[1])
2474 for arg in sys.argv[1:]:
2475 if os.path.isfile(arg):
2476 app.TopWindow.drop_handler(str(os.path.abspath(arg)))
2477 break
2478 else:
2479 app.TopWindow.LoadProfile(get_display_profile(display_no))
2480 app.TopWindow.Show()
2481
2482
2483 if __name__ == "__main__":
2484 main()