Debian Codegraph @

DisplayCAL/wx_synth_icc_frame.py

raw
1 """wxPython GUI for creating synthetic ICC profiles.
2
3 It supports customization of color spaces, luminance, transfer functions, and
4 other ICC profile attributes. The interface allows users to manipulate color
5 settings, drop files for processing, and save profiles in various
6 configurations.
7 """
8
9 import math
10 import os
11 import sys
12 from functools import partial
13
14 from wx import xrc
15
16 from DisplayCAL import (
17 colormath,
18 config,
19 floatspin,
20 worker,
21 xh_bitmapctrls,
22 xh_floatspin,
23 )
24 from DisplayCAL import localization as lang
25 from DisplayCAL.argyll_cgats import extract_device_gray_primaries
26 from DisplayCAL.cgats import (
27 CGATS,
28 CGATSInvalidError,
29 )
30 from DisplayCAL.config import (
31 ENC,
32 PROFILE_EXT,
33 get_data_path,
34 get_verified_path,
35 getcfg,
36 hascfg,
37 setcfg,
38 )
39 from DisplayCAL.debughelpers import Error
40 from DisplayCAL.icc_profile import (
41 CIIS,
42 PROFILE_CLASS,
43 TECH,
44 CurveType,
45 ICCProfile,
46 ICCProfileInvalidError,
47 SignatureType,
48 Text,
49 XYZType,
50 create_synthetic_hdr_clut_profile,
51 s15f16_is_equal,
52 )
53 from DisplayCAL.log import LOG
54 from DisplayCAL.meta import NAME as APPNAME
55 from DisplayCAL.options import DEBUG
56 from DisplayCAL.util_dict import dict_sort
57 from DisplayCAL.util_io import Files
58 from DisplayCAL.util_os import waccess
59 from DisplayCAL.worker import (
60 FilteredStream,
61 LineBufferedStream,
62 show_result_dialog,
63 )
64 from DisplayCAL.wx_fixes import TempXmlResource
65 from DisplayCAL.wx_lut_3d_frame import LUT3DMixin
66 from DisplayCAL.wx_windows import (
67 BaseApp,
68 BaseFrame,
69 ConfirmDialog,
70 FileDrop,
71 wx,
72 )
73
74
75 class SynthICCFrame(BaseFrame, LUT3DMixin):
76 """Synthetic ICC creation window.
77
78 Args:
79 parent (wx.Window, optional): The parent window. Defaults to None.
80 """
81
82 cfg = config.CFG
83
84 def __init__(self, parent=None):
85 self.res = TempXmlResource(get_data_path(os.path.join("xrc", "synthicc.xrc")))
86 self.res.InsertHandler(xh_floatspin.FloatSpinCtrlXmlHandler())
87 self.res.InsertHandler(xh_bitmapctrls.BitmapButton())
88 self.res.InsertHandler(xh_bitmapctrls.StaticBitmap())
89 if hasattr(wx, "PreFrame"):
90 # Classic
91 pre = wx.PreFrame()
92 self.res.LoadOnFrame(pre, parent, "synthiccframe")
93 self.PostCreate(pre)
94 else:
95 # Phoenix
96 wx.Frame.__init__(self)
97 self.res.LoadFrame(self, parent, "synthiccframe")
98 self.init()
99 self.Bind(wx.EVT_CLOSE, self.OnClose)
100 if sys.platform == "win32":
101 self.Bind(wx.EVT_SIZE, self.OnSize)
102
103 self.SetIcons(
104 config.get_icon_bundle([256, 48, 32, 16], APPNAME + "-synthprofile")
105 )
106
107 self.set_child_ctrls_as_attrs(self)
108
109 self.panel = xrc.XRCCTRL(self, "panel")
110
111 self._updating_ctrls = False
112
113 # Presets
114 presets = ["", *sorted(colormath.rgb_spaces.keys())]
115 self.preset_ctrl.SetItems(presets)
116
117 self.set_default_cat()
118
119 self.worker = worker.Worker(self)
120
121 # Drop targets
122 self.droptarget = FileDrop(self)
123 self.droptarget.drophandlers = {
124 ".icc": self.drop_handler,
125 ".icm": self.drop_handler,
126 ".ti3": self.drop_handler,
127 }
128 self.panel.SetDropTarget(self.droptarget)
129
130 # Bind event handlers
131 self.preset_ctrl.Bind(wx.EVT_CHOICE, self.preset_ctrl_handler)
132 for color in ("red", "green", "blue", "white", "black"):
133 for component in "XYZxy":
134 handler = "xy" if component in "xy" else "XYZ"
135 self.Bind(
136 floatspin.EVT_FLOATSPIN,
137 getattr(self, f"{color}_{handler}_ctrl_handler"),
138 getattr(self, f"{color}_{component}"),
139 )
140 self.black_point_cb.Bind(wx.EVT_CHECKBOX, self.black_point_enable_handler)
141 self.chromatic_adaptation_btn.Bind(
142 wx.EVT_BUTTON, self.chromatic_adaptation_btn_handler
143 )
144 self.trc_ctrl.Bind(wx.EVT_CHOICE, self.trc_ctrl_handler)
145 self.trc_gamma_ctrl.Bind(wx.EVT_COMBOBOX, self.trc_gamma_ctrl_handler)
146 self.trc_gamma_ctrl.Bind(wx.EVT_KILL_FOCUS, self.trc_gamma_ctrl_handler)
147 self.trc_gamma_type_ctrl.Bind(wx.EVT_CHOICE, self.trc_gamma_type_ctrl_handler)
148 self.lut3d_bind_hdr_trc_handlers()
149 self.black_output_offset_ctrl.Bind(
150 wx.EVT_SLIDER, self.black_output_offset_ctrl_handler
151 )
152 self.black_output_offset_intctrl.Bind(
153 wx.EVT_TEXT, self.black_output_offset_ctrl_handler
154 )
155 self.colorspace_rgb_ctrl.Bind(wx.EVT_RADIOBUTTON, self.colorspace_ctrl_handler)
156 self.colorspace_gray_ctrl.Bind(wx.EVT_RADIOBUTTON, self.colorspace_ctrl_handler)
157 self.black_luminance_ctrl.Bind(
158 floatspin.EVT_FLOATSPIN, self.black_luminance_ctrl_handler
159 )
160 self.luminance_ctrl.Bind(floatspin.EVT_FLOATSPIN, self.luminance_ctrl_handler)
161 self.save_as_btn.Bind(wx.EVT_BUTTON, self.save_as_btn_handler)
162
163 self.save_as_btn.SetDefault()
164
165 self.setup_language()
166
167 self.update_controls()
168 self.update_layout()
169 scrollrate_x = 2 if self.panel.VirtualSize[0] > self.panel.Size[0] else 0
170 self.panel.SetScrollRate(scrollrate_x, 2)
171
172 self.save_btn.Hide()
173
174 config.DEFAULTS.update(
175 {
176 "position.synthiccframe.x": self.GetDisplay().ClientArea[0] + 40,
177 "position.synthiccframe.y": self.GetDisplay().ClientArea[1] + 60,
178 "size.synthiccframe.w": self.ClientSize[0],
179 "size.synthiccframe.h": self.ClientSize[1],
180 }
181 )
182
183 if (
184 self.hascfg("position.synthiccframe.x")
185 and self.hascfg("position.synthiccframe.y")
186 and self.hascfg("size.synthiccframe.w")
187 and self.hascfg("size.synthiccframe.h")
188 ):
189 self.SetSaneGeometry(
190 int(self.getcfg("position.synthiccframe.x")),
191 int(self.getcfg("position.synthiccframe.y")),
192 int(self.getcfg("size.synthiccframe.w")),
193 int(self.getcfg("size.synthiccframe.h")),
194 )
195 else:
196 self.Center()
197
198 def OnSize(self, event):
199 """Handles the size event of the frame.
200
201 Args:
202 event (wx.Event): The event object that triggered this handler.
203 """
204 event.Skip()
205 self.Refresh() # Prevents distorted drawing under Windows
206
207 def OnClose(self, event=None):
208 """Handles the close event of the frame.
209
210 Args:
211 event (wx.Event, optional): The event object that triggered this
212 handler. Defaults to None.
213 """
214 if sys.platform == "darwin" or DEBUG:
215 self.focus_handler(event)
216 if self.IsShownOnScreen() and not self.IsMaximized() and not self.IsIconized():
217 x, y = self.GetScreenPosition()
218 self.setcfg("position.synthiccframe.x", x)
219 self.setcfg("position.synthiccframe.y", y)
220 self.setcfg("size.synthiccframe.w", self.ClientSize[0])
221 self.setcfg("size.synthiccframe.h", self.ClientSize[1])
222 config.writecfg(
223 module="synthprofile",
224 options=(
225 "synthprofile.",
226 "last_icc_path",
227 "position.synthiccframe",
228 "size.synthiccframe",
229 "3dlut.hdr_",
230 ),
231 cfg=self.cfg,
232 )
233 if event:
234 # Hide first (looks nicer)
235 self.Hide()
236 # Need to use CallAfter to prevent hang under Windows if minimized
237 if wx.GetApp().TopWindow is self:
238 # XXX: Weird wxPython Phoenix bug under Windows: Destroying the
239 # frame seems to affect subsequently loaded XRC resources
240 # (wrong control classes used).
241 # More investigation is needed, but it is clear this is a
242 # Phoenix or wxWidgets bug because it does not happen with
243 # wxPython classic (3.0.2).
244 # Workaround: Only destroy the frame if running standalone.
245 wx.CallAfter(self.Destroy)
246
247 def black_luminance_ctrl_handler(self, event):
248 """Handles changes in the black luminance control.
249
250 Args:
251 event (wx.Event or bool): The event object that triggered this
252 handler. Can also be True to force a layout update.
253 """
254 v = self.black_luminance_ctrl.GetValue()
255 white_Y = self.getcfg("synthprofile.luminance")
256 if v >= white_Y * 0.9:
257 if event:
258 wx.Bell()
259 v = white_Y * 0.9
260 if event:
261 min_Y = 0.000001 # (1 / 65535.0) * 100
262 increment = 0.000001 # (1 / 65535.0) * white_Y
263 if increment < min_Y:
264 increment = min_Y * (white_Y / 100.0)
265 min_inc = 1.0 / (10.0 ** self.black_luminance_ctrl.GetDigits())
266 increment = max(increment, min_inc)
267 self.black_luminance_ctrl.SetIncrement(increment)
268 fmt = f"{{:.{self.black_luminance_ctrl.GetDigits()}f}}"
269 if fmt.format(0) < fmt.format(v) < fmt.format(increment):
270 v = increment if event else 0
271 elif fmt.format(v) == fmt.format(0):
272 v = 0
273 v = round(v / increment) * increment
274 self.black_luminance_ctrl.SetValue(v)
275
276 old = self.getcfg("synthprofile.black_luminance")
277 self.setcfg("synthprofile.black_luminance", v)
278 if event:
279 self.black_xy_ctrl_handler(None)
280 self.black_point_cb.Enable(v > 0)
281 self.black_point_enable_handler(None)
282 if (v != old and (old == 0 or v == 0)) or event is True:
283 self.Freeze()
284 i = self.trc_ctrl.GetSelection()
285 self.trc_gamma_type_ctrl.Show(i in (0, 5) and bool(v))
286 if not v:
287 self.bpc_ctrl.SetValue(False)
288 self.bpc_ctrl.Enable(bool(v))
289 black_output_offset_show = i in (0, 5, 7, 8) and bool(v)
290 self.black_output_offset_label.Show(black_output_offset_show)
291 self.black_output_offset_ctrl.Show(black_output_offset_show)
292 self.black_output_offset_intctrl.Show(black_output_offset_show)
293 self.black_output_offset_intctrl_label.Show(black_output_offset_show)
294 self.panel.GetSizer().Layout()
295 self.update_layout()
296 self.Thaw()
297
298 def black_output_offset_ctrl_handler(self, event):
299 """Handler for black output offset control changes.
300
301 Args:
302 event (wx.Event): The event that triggered this handler.
303 """
304 if event.GetId() == self.black_output_offset_intctrl.GetId():
305 self.black_output_offset_ctrl.SetValue(
306 self.black_output_offset_intctrl.GetValue()
307 )
308 else:
309 self.black_output_offset_intctrl.SetValue(
310 self.black_output_offset_ctrl.GetValue()
311 )
312 v = self.black_output_offset_ctrl.GetValue() / 100.0
313 self.setcfg("synthprofile.trc_output_offset", v)
314 self.update_trc_control()
315
316 def black_point_enable_handler(self, event):
317 """Enable or disable black point controls based on the checkbox state.
318
319 Args:
320 event (wx.Event): The event that triggered this handler.
321 """
322 v = self.getcfg("synthprofile.black_luminance")
323 for component in "XYZxy":
324 getattr(self, f"black_{component}").Enable(
325 v > 0 and self.black_point_cb.Value
326 )
327
328 def black_XYZ_ctrl_handler(self, event):
329 """Handler for black XYZ control changes.
330
331 Args:
332 event (wx.Event): The event that triggered this handler.
333 """
334 luminance = self.getcfg("synthprofile.luminance")
335 XYZ = []
336 for component in "XYZ":
337 XYZ.append(getattr(self, f"black_{component}").GetValue() / 100.0)
338 if component == "Y":
339 self.black_luminance_ctrl.SetValue(XYZ[-1] * luminance)
340 self.black_luminance_ctrl_handler(None)
341 if not XYZ[-1]:
342 XYZ = [0, 0, 0]
343 for i in range(3):
344 getattr(self, "black_{}".format("XYZ"[i])).SetValue(0)
345 break
346 self.parse_XYZ("black")
347
348 def black_xy_ctrl_handler(self, event):
349 """Handler for black xy control changes.
350
351 Args:
352 event (wx.Event): The event that triggered this handler.
353 """
354 # Black Y scaled to 0..1 range
355 Y = self.getcfg("synthprofile.black_luminance") / self.getcfg(
356 "synthprofile.luminance"
357 )
358 xy = []
359 for component in "xy":
360 xy.append(getattr(self, f"black_{component}").GetValue() or 1.0 / 3)
361 getattr(self, f"black_{component}").SetValue(xy[-1])
362 for i, v in enumerate(colormath.xyY2XYZ(*[*xy, Y])):
363 getattr(self, "black_{}".format("XYZ"[i])).SetValue(v * 100)
364
365 def blue_XYZ_ctrl_handler(self, event):
366 """Handler for blue XYZ control changes.
367
368 Args:
369 event (wx.Event): The event that triggered this handler.
370 """
371 self.parse_XYZ("blue")
372
373 def blue_xy_ctrl_handler(self, event):
374 """Handler for blue xy control changes.
375
376 Args:
377 event (wx.Event): The event that triggered this handler.
378 """
379 self.parse_xy("blue")
380
381 def chromatic_adaptation_btn_handler(self, event):
382 """Handler for the chromatic adaptation button click event.
383
384 Args:
385 event (wx.Event): The event that triggered this handler.
386 """
387 scale = self.getcfg("app.dpi") / config.get_default_dpi()
388 scale = max(scale, 1)
389 dlg = ConfirmDialog(
390 self,
391 title=lang.getstr("chromatic_adaptation"),
392 msg=lang.getstr("whitepoint.xy"),
393 ok=lang.getstr("apply"),
394 cancel=lang.getstr("cancel"),
395 )
396 sizer = wx.BoxSizer(wx.HORIZONTAL)
397 dlg.sizer3.Add(sizer, 0, flag=wx.TOP | wx.ALIGN_LEFT, border=8)
398 x_ctrl = floatspin.FloatSpin(
399 dlg,
400 -1,
401 size=(75 * scale, -1),
402 min_val=0.00001,
403 max_val=1,
404 increment=0.00001,
405 value=self.white_x.GetValue(),
406 )
407 sizer.Add(x_ctrl, 0, flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=4)
408 sizer.Add(
409 wx.StaticText(dlg, -1, "x"),
410 0,
411 flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
412 border=12,
413 )
414 y_ctrl = floatspin.FloatSpin(
415 dlg,
416 -1,
417 size=(75 * scale, -1),
418 min_val=0.00001,
419 max_val=1,
420 increment=0.00001,
421 value=self.white_y.GetValue(),
422 )
423 sizer.Add(y_ctrl, 0, flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=4)
424 sizer.Add(
425 wx.StaticText(dlg, -1, "y"),
426 0,
427 flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
428 border=12,
429 )
430 dlg.sizer3.Add(
431 wx.StaticText(dlg, -1, lang.getstr("chromatic_adaptation_transform")),
432 0,
433 flag=wx.TOP | wx.ALIGN_LEFT,
434 border=12,
435 )
436 if self.getcfg("show_advanced_options"):
437 # Only offer those that seem suitable in an ICC workflow
438 # (i.e. blue primary not too far from default Bradford to
439 # prevent 'blue turns purple' problems)
440 cat_choices = ["Bradford", "CAT02BS"]
441 else:
442 cat_choices = ["Bradford"]
443 cat_choices_ab = dict(
444 get_mapping(((k, k) for k in colormath.CAT_MATRICES), cat_choices)
445 )
446 cat_choices_ba = {v: k for k, v in cat_choices_ab.items()}
447 cat_ctrl = wx.Choice(dlg, -1, choices=list(cat_choices_ab.values()))
448 cat_ctrl.SetStringSelection(cat_choices_ab[self.cat])
449 dlg.sizer3.Add(cat_ctrl, 0, flag=wx.TOP | wx.ALIGN_LEFT, border=8)
450 dlg.sizer0.SetSizeHints(dlg)
451 dlg.sizer0.Layout()
452 result = dlg.ShowModal()
453 x = x_ctrl.GetValue()
454 y = y_ctrl.GetValue()
455 cat = cat_choices_ba[cat_ctrl.GetStringSelection()]
456 dlg.Destroy()
457 if result != wx.ID_OK:
458 return
459 wp_src = [getattr(self, "white_" + component).GetValue() for component in "XYZ"]
460 wp_tgt = colormath.xyY2XYZ(x, y)
461 self.cat = cat
462 for color in ("red", "green", "blue", "white", "black"):
463 ctrls = [getattr(self, f"{color}_{component}") for component in "XYZ"]
464 X, Y, Z = (ctrl.GetValue() for ctrl in ctrls)
465 XYZa = colormath.adapt(X, Y, Z, wp_src, wp_tgt, cat)
466 for i, ctrl in enumerate(ctrls):
467 ctrl.SetValue(XYZa[i])
468 self.parse_XYZ(color, False)
469
470 def colorspace_ctrl_handler(self, event):
471 """Handler for colorspace control changes.
472
473 Args:
474 event (wx.Event): The event that triggered this handler.
475 """
476 self.Freeze()
477 show = bool(self.colorspace_rgb_ctrl.Value)
478 for color in ("red", "green", "blue"):
479 getattr(self, f"label_{color}").Show(show)
480 for component in "XYZxy":
481 getattr(self, f"{color}_{component}").Show(show)
482 self.enable_btns()
483 self.update_layout()
484 self.Thaw()
485
486 def drop_handler(self, path):
487 """File dropped."""
488 fn, ext = os.path.splitext(path)
489 if ext.lower() == ".ti3":
490 self.ti3_drop_handler(path)
491 else:
492 self.icc_drop_handler(path)
493
494 def icc_drop_handler(self, path):
495 """ICC profile dropped."""
496 try:
497 profile = ICCProfile(path)
498 except (OSError, ICCProfileInvalidError):
499 show_result_dialog(
500 Error(lang.getstr("profile.invalid") + "\n" + path), self
501 )
502 else:
503 if profile.version >= 4 and not profile.convert_iccv4_tags_to_iccv2():
504 show_result_dialog(
505 Error(lang.getstr("profile.iccv4.unsupported")), self
506 )
507 return
508 if profile.colorSpace not in (
509 b"RGB",
510 b"GRAY",
511 ) or profile.connectionColorSpace not in (b"Lab", b"XYZ"):
512 show_result_dialog(
513 Error(
514 lang.getstr(
515 "profile.unsupported",
516 (
517 profile.profileClass.decode("utf-8"),
518 profile.colorSpace.decode("utf-8"),
519 ),
520 )
521 ),
522 self,
523 )
524 return
525 rgb = [(1, 1, 1), (0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)]
526 rgb.extend(
527 (1.0 / 255 * i, 1.0 / 255 * i, 1.0 / 255 * i) for i in range(256)
528 )
529 try:
530 colors = self.worker.xicclu(profile, rgb, intent="a", pcs="x")
531 except Exception as exception:
532 show_result_dialog(exception, self)
533 else:
534 luminance = profile.tags.lumi.Y if "lumi" in profile.tags else 100
535 if not colors[1][1] and isinstance(profile.tags.get("targ"), Text):
536 # The profile may not reflect the actual black point.
537 # Get it from the embedded TI3 instead if zero from lookup.
538 XYZbp = profile.get_chardata_bkpt(True)
539 if XYZbp:
540 # Use wtpt chromaticity
541 colors[1] = [v * XYZbp[1] for v in colors[0]]
542 self.set_colors(colors, luminance, profile.colorSpace)
543
544 def set_colors(self, colors, luminance, colorspace):
545 """Set controls according to args."""
546 self.panel.Freeze()
547 for ctrl, value in [
548 (self.colorspace_rgb_ctrl, colorspace == "RGB"),
549 (self.colorspace_gray_ctrl, colorspace == "GRAY"),
550 ]:
551 ctrl.SetValue(value)
552 self.colorspace_ctrl_handler(None)
553 self.setcfg("synthprofile.luminance", luminance)
554 self.luminance_ctrl.SetValue(luminance)
555 for i, color in enumerate(("white", "black")):
556 for j, component in enumerate("XYZ"):
557 getattr(self, f"{color}_{component}").SetValue(
558 colors[i][j] / colors[0][1] * 100
559 )
560 self.parse_XYZ(color)
561 for i, color in enumerate(("red", "green", "blue")):
562 xyY = colormath.XYZ2xyY(*colors[2 + i])
563 for j, component in enumerate("xy"):
564 getattr(self, f"{color}_{component}").SetValue(xyY[j])
565 self.parse_xy(None)
566 self.black_XYZ_ctrl_handler(None)
567 if len(colors[5:]) > 2:
568 trc = CurveType()
569 for XYZ in colors[5:]:
570 trc.append(XYZ[1] / colors[0][1] * 65535)
571 transfer_function = trc.get_transfer_function(outoffset=1.0)
572 if transfer_function and transfer_function[1] >= 0.95:
573 # Use detected transfer function
574 gamma = transfer_function[0][1]
575 else:
576 # Use 50% gamma value
577 gamma = math.log(colors[132][1]) / math.log(128.0 / 255)
578 self.set_trc(round(gamma, 2))
579 self.setcfg("synthprofile.trc_gamma_type", "g")
580 self.trc_gamma_type_ctrl.SetSelection(self.trc_gamma_types_ba["g"])
581 self.panel.Thaw()
582
583 def ti3_drop_handler(self, path):
584 """Handle TI3 file dropped.
585
586 Args:
587 path (str): The path to the TI3 file.
588 """
589 try:
590 ti3 = CGATS(path)
591 except (OSError, CGATSInvalidError):
592 show_result_dialog(
593 Error(lang.getstr("error.measurement.file_invalid", path)), self
594 )
595 return
596 ti3[0].normalize_to_y_100()
597 rgb = [(100, 100, 100), (0, 0, 0), (100, 0, 0), (0, 100, 0), (0, 0, 100)]
598 colors = []
599 for R, G, B in rgb:
600 result = ti3.queryi1({"RGB_R": R, "RGB_G": G, "RGB_B": B})
601 if result:
602 color = []
603 for component in "XYZ":
604 label = "XYZ_" + component
605 if label in result:
606 color.append(result[label])
607 if not result or len(color) < 3:
608 color = (0, 0, 0)
609 colors.append(color)
610 try:
611 (
612 ti3_extracted,
613 RGB_XYZ_extracted,
614 RGB_XYZ_remaining,
615 ) = extract_device_gray_primaries(ti3)
616 except Error as exception:
617 show_result_dialog(exception, self)
618 else:
619 RGB_XYZ_extracted = dict_sort(RGB_XYZ_extracted)
620 colors.extend(list(RGB_XYZ_extracted.values()))
621 luminance = ti3.queryv1("LUMINANCE_XYZ_CDM2")
622 if luminance:
623 try:
624 luminance = float(luminance.split()[1])
625 except (TypeError, ValueError):
626 luminance = 100
627 else:
628 luminance = 100
629 self.set_colors(colors, luminance, "RGB")
630
631 def enable_btns(self):
632 """Enable or disable buttons based on the current state of controls."""
633 enable = bool(self.get_XYZ())
634 self.save_as_btn.Enable(enable)
635 self.chromatic_adaptation_btn.Enable(enable)
636
637 def get_XYZ(self):
638 """Get XYZ in 0..1 range.
639
640 Returns:
641 None | dict: A dictionary containing XYZ values for white, red,
642 green, blue, and black colors, or None if the values are not
643 valid.
644 """
645 XYZ = {}
646 black_Y = self.getcfg("synthprofile.black_luminance") / self.getcfg(
647 "synthprofile.luminance"
648 )
649 for color in ("white", "red", "green", "blue", "black"):
650 for component in "XYZ":
651 v = getattr(self, f"{color}_{component}").GetValue() / 100.0
652 if color == "black":
653 key = "k"
654 if not self.black_point_cb.Value:
655 v = XYZ[f"w{component}"] * black_Y
656 else:
657 key = color[0]
658 XYZ[key + component] = v
659 if (
660 XYZ["wX"]
661 and XYZ["wY"]
662 and XYZ["wZ"]
663 and (
664 self.colorspace_gray_ctrl.Value
665 or (XYZ["rX"] and XYZ["gY"] and XYZ["bZ"])
666 )
667 ):
668 return XYZ
669 return None
670
671 def green_XYZ_ctrl_handler(self, event):
672 """Handler for green XYZ control changes.
673
674 Args:
675 event (wx.Event): The event that triggered this handler.
676 """
677 self.parse_XYZ("green")
678
679 def green_xy_ctrl_handler(self, event):
680 """Handler for green xy control changes.
681
682 Args:
683 event (wx.Event): The event that triggered this handler.
684 """
685 self.parse_xy("green")
686
687 def luminance_ctrl_handler(self, event):
688 """Handler for luminance control changes.
689
690 Args:
691 event (wx.Event): The event that triggered this handler.
692 """
693 v = self.luminance_ctrl.GetValue()
694 self.setcfg("synthprofile.luminance", v)
695 target_peak = v
696 maxmll = self.lut3d_hdr_maxmll_ctrl.GetValue()
697 if maxmll < target_peak:
698 self.setcfg("3dlut.hdr_maxmll", target_peak)
699 self.lut3d_hdr_maxmll_ctrl.SetRange(target_peak, 10000)
700 self.lut3d_set_option("3dlut.hdr_peak_luminance", v)
701 self.black_luminance_ctrl_handler(event)
702
703 def parse_XYZ(self, name, set_blackpoint=None):
704 """Parse XYZ values and update controls accordingly.
705
706 Args:
707 name (str): The name of the color space to update (e.g., "white").
708 set_blackpoint (bool): Whether to set the black point based on the
709 white point.
710 """
711 if set_blackpoint is None:
712 set_blackpoint = not self.black_point_cb.Value
713 if not self._updating_ctrls:
714 self.preset_ctrl.SetSelection(0)
715 XYZ = {}
716 # Black Y scaled to 0..1 range
717 black_Y = self.getcfg("synthprofile.black_luminance") / self.getcfg(
718 "synthprofile.luminance"
719 )
720 for component in "XYZ":
721 v = getattr(self, f"{name}_{component}").GetValue()
722 XYZ[component] = v
723 if name == "white" and set_blackpoint:
724 getattr(self, f"black_{component}").SetValue(v * black_Y)
725 if "X" in XYZ and "Y" in XYZ and "Z" in XYZ:
726 if XYZ["X"] + XYZ["Y"] + XYZ["Z"] == 0:
727 # Set black chromaticity to white chromaticity if XYZ is 0
728 xyY = [
729 getattr(self, f"white_{component}").GetValue() for component in "xy"
730 ]
731 else:
732 xyY = colormath.XYZ2xyY(XYZ["X"], XYZ["Y"], XYZ["Z"])
733 for i, component in enumerate("xy"):
734 getattr(self, f"{name}_{component}").SetValue(xyY[i])
735 if name == "white" and set_blackpoint:
736 getattr(self, f"black_{component}").SetValue(xyY[i])
737 self.enable_btns()
738
739 def parse_xy(self, name=None, set_blackpoint=False):
740 """Parse xy values and update controls accordingly.
741
742 Args:
743 name (str): The name of the color space to update (e.g., "white").
744 set_blackpoint (bool): Whether to set the black point based on the
745 white point.
746 """
747 if not set_blackpoint:
748 set_blackpoint = not self.black_point_cb.Value
749 if not self._updating_ctrls:
750 self.preset_ctrl.SetSelection(0)
751 xy = {}
752 for color in ("white", "red", "green", "blue"):
753 for component in "xy":
754 v = getattr(self, f"{color}_{component}").GetValue()
755 xy[color[0] + component] = v
756 if name == "white":
757 wXYZ = colormath.xyY2XYZ(xy["wx"], xy["wy"], 1.0)
758 else:
759 wXYZ = []
760 for component in "XYZ":
761 wXYZ.append(getattr(self, f"white_{component}").GetValue() / 100.0)
762 if name == "white":
763 # Black Y scaled to 0..1 range
764 black_Y = self.getcfg("synthprofile.black_luminance") / self.getcfg(
765 "synthprofile.luminance"
766 )
767 for i, component in enumerate("XYZ"):
768 getattr(self, f"white_{component}").SetValue(wXYZ[i] * 100)
769 if set_blackpoint:
770 getattr(self, f"black_{component}").SetValue(
771 wXYZ[i] * black_Y * 100
772 )
773 has_rgb_xy = True
774 # Calculate RGB to XYZ matrix from chromaticities and white
775 try:
776 mtx = colormath.rgb_to_xyz_matrix(
777 xy["rx"], xy["ry"], xy["gx"], xy["gy"], xy["bx"], xy["by"], wXYZ
778 )
779 except ZeroDivisionError:
780 # Singular matrix
781 has_rgb_xy = False
782 rgb = {"r": (1.0, 0.0, 0.0), "g": (0.0, 1.0, 0.0), "b": (0.0, 0.0, 1.0)}
783 XYZ = {}
784 for color in ("red", "green", "blue"):
785 if has_rgb_xy:
786 # Calculate XYZ for primaries
787 v = mtx * rgb[color[0]]
788 if not has_rgb_xy:
789 v = (0, 0, 0)
790 XYZ[color[0]] = v
791 for i, component in enumerate("XYZ"):
792 getattr(self, f"{color}_{component}").SetValue(XYZ[color[0]][i] * 100)
793 self.enable_btns()
794
795 def preset_ctrl_handler(self, event):
796 """Handler for preset control changes.
797
798 Args:
799 event (wx.Event): The event that triggered this handler.
800 """
801 preset_name = self.preset_ctrl.GetStringSelection()
802 if not preset_name:
803 return
804 self.set_default_cat()
805 gamma, white, red, green, blue = colormath.rgb_spaces[preset_name]
806 white = colormath.get_whitepoint(white)
807 self._updating_ctrls = True
808 self.panel.Freeze()
809 if self.preset_ctrl.GetStringSelection() == "DCI P3":
810 tech = self.tech["dcpj"]
811 else:
812 tech = self.tech[""]
813 self.tech_ctrl.SetStringSelection(tech)
814
815 self.white_X.SetValue(white[0] * 100)
816 self.white_Y.SetValue(white[1] * 100)
817 self.white_Z.SetValue(white[2] * 100)
818
819 self.parse_XYZ("white", True)
820
821 self.red_x.SetValue(red[0])
822 self.red_y.SetValue(red[1])
823 self.green_x.SetValue(green[0])
824 self.green_y.SetValue(green[1])
825 self.blue_x.SetValue(blue[0])
826 self.blue_y.SetValue(blue[1])
827
828 self.parse_xy(None)
829 self.set_trc(gamma)
830 self.panel.Thaw()
831 self._updating_ctrls = False
832
833 def get_commands(self):
834 """Get a list of commands that this frame can process.
835
836 Returns:
837 list: A list of command strings that this frame can handle.
838 """
839 return [
840 *self.get_common_commands(),
841 "synthprofile [filename]",
842 "load <filename>",
843 ]
844
845 def process_data(self, data):
846 """Process commands from the command line or other sources.
847
848 Args:
849 data (list): A list of strings, where the first element is the command
850 and the subsequent elements are arguments for that command.
851
852 Returns:
853 str: "ok" if the command was processed successfully, "fail" if it failed,
854 or "invalid" if the command was not recognized.
855 """
856 if (data[0] == "synthprofile" and len(data) < 3) or (
857 data[0] == "load" and len(data) == 2
858 ):
859 if self.IsIconized():
860 self.Restore()
861 self.Raise()
862 if len(data) == 2:
863 path = data[1]
864 if not os.path.isfile(path) and not os.path.isabs(path):
865 path = get_data_path(path)
866 if not path:
867 return "fail"
868 self.droptarget.OnDropFiles(0, 0, [path])
869 return "ok"
870 return "invalid"
871
872 def set_default_cat(self):
873 """Set the default chromatic adaptation transform."""
874 self.cat = "Bradford"
875
876 def set_trc(self, gamma):
877 """Set the transfer function control to the given gamma value.
878
879 Args:
880 gamma (float or int): The gamma value to set. Special values:
881 -1023: DICOM
882 -2.0: HLG
883 -3.0: L*
884 -709: Rec. 709
885 -1886: Rec. 1886
886 -240: SMPTE 240M
887 -2084: SMPTE 2084 (roll-off clip)
888 -2.4: sRGB
889 """
890 if gamma == -1023:
891 # DICOM
892 self.trc_ctrl.SetSelection(1)
893 elif gamma == -2.0:
894 # HLG
895 self.trc_ctrl.SetSelection(2)
896 elif gamma == -3.0:
897 # L*
898 self.trc_ctrl.SetSelection(3)
899 elif gamma == -709:
900 # Rec. 709
901 self.trc_ctrl.SetSelection(4)
902 elif gamma == -1886:
903 # Rec. 1886
904 self.trc_ctrl.SetSelection(5)
905 self.trc_ctrl_handler()
906 elif gamma == -240:
907 # SMPTE 240M
908 self.trc_ctrl.SetSelection(6)
909 elif gamma == -2084:
910 # SMPTE 2084, roll-off clip
911 self.trc_ctrl.SetSelection(8)
912 elif gamma == -2.4:
913 # sRGB
914 self.trc_ctrl.SetSelection(9)
915 else:
916 # Gamma
917 self.trc_ctrl.SetSelection(0)
918 self.setcfg("synthprofile.trc_gamma", gamma)
919 self.update_trc_controls()
920
921 def profile_name_ctrl_handler(self, event):
922 """Handler for profile name control changes.
923
924 Args:
925 event (wx.Event): The event that triggered this handler.
926 """
927 self.enable_btns()
928
929 def red_XYZ_ctrl_handler(self, event):
930 """Handler for red XYZ control changes.
931
932 Args:
933 event (wx.Event): The event that triggered this handler.
934 """
935 self.parse_XYZ("red")
936
937 def red_xy_ctrl_handler(self, event):
938 """Handler for red xy control changes.
939
940 Args:
941 event (wx.Event): The event that triggered this handler.
942 """
943 self.parse_xy("red")
944
945 def save_as_btn_handler(self, event):
946 """Save as ICC profile.
947
948 Args:
949 event (wx.Event): The event that triggered this handler.
950 """
951 try:
952 gamma = float(self.trc_gamma_ctrl.Value)
953 except ValueError:
954 wx.Bell()
955 gamma = 2.2
956 self.trc_gamma_ctrl.Value = str(gamma)
957
958 defaultDir, defaultFile = get_verified_path("last_icc_path")
959 defaultFile = lang.getstr("unnamed")
960 path = None
961 icc_file_type_wildcard = f"{lang.getstr('filetype.icc')}|*{PROFILE_EXT}"
962 save_dialog_title = lang.getstr("save_as")
963
964 dlg = wx.FileDialog(
965 self,
966 save_dialog_title,
967 defaultDir=defaultDir,
968 defaultFile=defaultFile,
969 wildcard=icc_file_type_wildcard,
970 style=wx.SAVE | wx.FD_OVERWRITE_PROMPT,
971 )
972 dlg.Center(wx.BOTH)
973 result = dlg.ShowModal()
974
975 if result == wx.ID_OK:
976 path = dlg.GetPath()
977 dlg.Destroy()
978
979 if path:
980 if os.path.splitext(path)[1].lower() not in (".icc", ".icm"):
981 path += PROFILE_EXT
982 if not waccess(path, os.W_OK):
983 show_result_dialog(
984 Error(lang.getstr("error.access_denied.write", path)), self
985 )
986 return
987 self.setcfg("last_icc_path", path)
988 else:
989 return
990
991 XYZ = self.get_XYZ()
992 if self.trc_ctrl.GetSelection() in (0, 5):
993 # 0 = Gamma
994 # 5 = Rec. 1886 - trc set here is only used if black = 0
995 trc = gamma
996 elif self.trc_ctrl.GetSelection() == 1:
997 # DICOM
998 trc = -1
999 elif self.trc_ctrl.GetSelection() == 2:
1000 # HLG
1001 trc = -2
1002 elif self.trc_ctrl.GetSelection() == 3:
1003 # L*
1004 trc = -3.0
1005 elif self.trc_ctrl.GetSelection() == 4:
1006 # Rec. 709
1007 trc = -709
1008 elif self.trc_ctrl.GetSelection() == 6:
1009 # SMPTE 240M
1010 trc = -240
1011 elif self.trc_ctrl.GetSelection() in (7, 8):
1012 # SMPTE 2084
1013 trc = -2084
1014 elif self.trc_ctrl.GetSelection() == 9:
1015 # sRGB
1016 trc = -2.4
1017 rolloff = self.trc_ctrl.GetSelection() == 8
1018 class_i = self.profile_class_ctrl.GetSelection()
1019 tech_i = self.tech_ctrl.GetSelection()
1020 ciis_i = self.ciis_ctrl.GetSelection()
1021
1022 def consumer(result, parent):
1023 if isinstance(result, Exception):
1024 show_result_dialog(result, parent)
1025
1026 wargs = (XYZ, trc, path)
1027 wkwargs = {
1028 "rgb": self.colorspace_rgb_ctrl.Value,
1029 "rolloff": rolloff,
1030 "bpc": self.bpc_ctrl.Value,
1031 "profile_class": list(self.profile_classes.keys())[class_i],
1032 "tech": list(self.tech.keys())[tech_i],
1033 "ciis": list(self.ciis.keys())[ciis_i],
1034 }
1035 if (trc == -2084 and rolloff) or trc == -2:
1036 msg = "smpte2084.rolloffclip" if trc == -2084 else "hlg"
1037 self.worker.recent.write(lang.getstr("trc." + msg) + "\n")
1038 self.worker.start(
1039 partial(consumer, parent=self),
1040 self.create_profile,
1041 wargs=(XYZ, trc, path),
1042 wkwargs=wkwargs,
1043 progress_msg=lang.getstr("synthicc.create"),
1044 )
1045 else:
1046 consumer(self.create_profile(*wargs, **wkwargs), parent=self)
1047
1048 def create_profile(
1049 self,
1050 XYZ,
1051 trc,
1052 path,
1053 rgb=True,
1054 rolloff=True,
1055 bpc=False,
1056 profile_class=b"mntr",
1057 tech=None,
1058 ciis=None,
1059 ):
1060 """Create ICC profile from XYZ and TRC.
1061
1062 Args:
1063 XYZ (dict): Dictionary with XYZ values for r, g, b, w, k.
1064 trc (float): Transfer function value or special value for DICOM,
1065 HLG, etc.
1066 path (str): Path to save the profile to.
1067 rgb (bool): Whether to create a color profile or grayscale.
1068 rolloff (bool): Whether to use roll-off for HDR profiles.
1069 bpc (bool): Whether to use black point compensation.
1070 profile_class (bytes): Profile class as bytes.
1071 tech (str): Technology string for the profile.
1072 ciis (str): CIIS string for the profile.
1073
1074 Returns:
1075 ICCProfile: The created ICC profile.
1076 """
1077 white = XYZ["wX"], XYZ["wY"], XYZ["wZ"]
1078 if rgb:
1079 # Color profile
1080 profile = ICCProfile.from_XYZ(
1081 (XYZ["rX"], XYZ["rY"], XYZ["rZ"]),
1082 (XYZ["gX"], XYZ["gY"], XYZ["gZ"]),
1083 (XYZ["bX"], XYZ["bY"], XYZ["bZ"]),
1084 (XYZ["wX"], XYZ["wY"], XYZ["wZ"]),
1085 1.0,
1086 "",
1087 self.getcfg("copyright"),
1088 cat=self.cat,
1089 profile_class=profile_class,
1090 )
1091 black = colormath.adapt(XYZ["kX"], XYZ["kY"], XYZ["kZ"], white)
1092 profile.tags.rTRC = CurveType(profile=profile)
1093 profile.tags.gTRC = CurveType(profile=profile)
1094 profile.tags.bTRC = CurveType(profile=profile)
1095 channels = "rgb"
1096 else:
1097 # Grayscale profile
1098 profile = ICCProfile()
1099 # Profile class
1100 profile.profileClass = profile_class
1101 if not s15f16_is_equal(
1102 (XYZ["wX"], XYZ["wY"], XYZ["wZ"]), colormath.get_whitepoint("D50")
1103 ) and (
1104 profile.profileClass not in (b"mntr", b"prtr")
1105 or colormath.is_similar_matrix(
1106 colormath.get_cat_matrix(self.cat),
1107 colormath.get_cat_matrix("Bradford"),
1108 )
1109 ):
1110 profile.version = 2.2 # Match ArgyllCMS
1111 profile.colorSpace = b"GRAY"
1112 profile.setCopyright(self.getcfg("copyright"))
1113 profile.set_wtpt((XYZ["wX"], XYZ["wY"], XYZ["wZ"]), self.cat)
1114 black = [
1115 XYZ["wY"]
1116 * (
1117 self.getcfg("synthprofile.black_luminance")
1118 / self.getcfg("synthprofile.luminance")
1119 )
1120 ] * 3
1121 profile.tags.kTRC = CurveType(profile=profile)
1122 channels = "k"
1123 # HLG
1124 outoffset = 1 if trc == -2 else self.getcfg("synthprofile.trc_output_offset")
1125 if trc == -1:
1126 # DICOM
1127 # Absolute luminance values!
1128 try:
1129 if rgb:
1130 # Color profile
1131 profile.set_dicom_trc(
1132 [v * self.getcfg("synthprofile.luminance") for v in black],
1133 self.getcfg("synthprofile.luminance"),
1134 )
1135 else:
1136 # Grayscale profile
1137 profile.tags.kTRC.set_dicom_trc(
1138 self.getcfg("synthprofile.black_luminance"),
1139 self.getcfg("synthprofile.luminance"),
1140 )
1141 except ValueError as exception:
1142 return exception
1143 elif trc > -1 and black != [0, 0, 0]:
1144 # Gamma with output offset or Rec. 1886-like
1145 if rgb:
1146 # Color profile
1147 profile.set_bt1886_trc(
1148 black, outoffset, trc, self.getcfg("synthprofile.trc_gamma_type")
1149 )
1150 else:
1151 # Grayscale profile
1152 profile.tags.kTRC.set_bt1886_trc(
1153 black[1], outoffset, trc, self.getcfg("synthprofile.trc_gamma_type")
1154 )
1155 elif trc in (-2084, -2):
1156 # SMPTE 2084 or HLG
1157 hdr_format = "PQ" if trc == -2084 else "HLG"
1158 minmll = self.getcfg("3dlut.hdr_minmll")
1159 if rolloff:
1160 maxmll = self.getcfg("3dlut.hdr_maxmll")
1161 else:
1162 maxmll = self.getcfg("synthprofile.luminance")
1163 if rgb:
1164 # Color profile
1165 if trc == -2084:
1166 profile.set_smpte2084_trc(
1167 [
1168 v * self.getcfg("synthprofile.luminance") * (1 - outoffset)
1169 for v in black
1170 ],
1171 self.getcfg("synthprofile.luminance"),
1172 minmll,
1173 maxmll,
1174 self.getcfg("3dlut.hdr_maxmll_alt_clip"),
1175 rolloff=True,
1176 blend_blackpoint=False,
1177 )
1178 else:
1179 # HLG
1180 profile.set_hlg_trc(
1181 (0, 0, 0),
1182 self.getcfg("synthprofile.luminance"),
1183 1.2,
1184 self.getcfg("3dlut.hdr_ambient_luminance"),
1185 blend_blackpoint=False,
1186 )
1187 if rolloff or trc == -2:
1188 rgb_space = profile.get_rgb_space()
1189 rgb_space[0] = 1.0 # Set gamma to 1.0 (not actually used)
1190 rgb_space = colormath.get_rgb_space(rgb_space)
1191 linebuffered_logfiles = []
1192 if (
1193 sys.stdout
1194 and hasattr(sys.stdout, "isatty")
1195 and sys.stdout.isatty()
1196 ):
1197 linebuffered_logfiles.append(print)
1198 else:
1199 linebuffered_logfiles.append(LOG)
1200 logfiles = Files(
1201 [
1202 LineBufferedStream(
1203 FilteredStream(
1204 Files(linebuffered_logfiles),
1205 ENC,
1206 discard="",
1207 linesep_in="\n",
1208 triggers=[],
1209 )
1210 ),
1211 self.worker.recent,
1212 self.worker.lastmsg,
1213 ]
1214 )
1215 quality = self.getcfg("profile.quality")
1216 clutres = {"m": 17, "l": 9}.get(quality, 33)
1217 hdr_clut_profile = create_synthetic_hdr_clut_profile(
1218 hdr_format,
1219 rgb_space,
1220 "",
1221 self.getcfg("synthprofile.black_luminance") * (1 - outoffset),
1222 self.getcfg("synthprofile.luminance"),
1223 minmll,
1224 maxmll,
1225 self.getcfg("3dlut.hdr_maxmll_alt_clip"),
1226 1.2,
1227 self.getcfg("3dlut.hdr_ambient_luminance"),
1228 clutres=clutres,
1229 sat=self.getcfg("3dlut.hdr_sat"),
1230 hue=self.getcfg("3dlut.hdr_hue"),
1231 generate_B2A=trc == -2,
1232 worker=self.worker,
1233 logfile=logfiles,
1234 cat=self.cat,
1235 )
1236 profile.tags.A2B0 = hdr_clut_profile.tags.A2B0
1237 if trc == -2:
1238 # HLG
1239 profile.tags.B2A0 = hdr_clut_profile.tags.B2A0
1240 if black != [0, 0, 0] and outoffset and not bpc:
1241 profile.apply_black_offset(black)
1242 else:
1243 # Grayscale profile
1244 if trc == -2084:
1245 profile.tags.kTRC.set_smpte2084_trc(
1246 self.getcfg("synthprofile.black_luminance") * (1 - outoffset),
1247 self.getcfg("synthprofile.luminance"),
1248 minmll,
1249 maxmll,
1250 self.getcfg("3dlut.hdr_maxmll_alt_clip"),
1251 rolloff=True,
1252 )
1253 else:
1254 # HLG
1255 profile.tags.kTRC.set_hlg_trc(
1256 0,
1257 self.getcfg("synthprofile.luminance"),
1258 1.2,
1259 self.getcfg("3dlut.hdr_ambient_luminance"),
1260 )
1261 if black != [0, 0, 0] and outoffset and not bpc:
1262 profile.tags.kTRC.apply_bpc(black[1])
1263 elif black != [0, 0, 0]:
1264 # Color profile if rgb is True, else grayscale profile
1265 vmin = 0 if rgb else black[1]
1266 for channel in channels:
1267 TRC = profile.tags[f"{channel}TRC"]
1268 TRC.set_trc(trc, 1024, vmin=vmin * 65535)
1269 if rgb:
1270 profile.apply_black_offset(black)
1271 else:
1272 for channel in channels:
1273 profile.tags[f"{channel}TRC"].set_trc(trc, 1)
1274 if black != [0, 0, 0] and bpc:
1275 if rgb:
1276 profile.apply_black_offset((0, 0, 0))
1277 else:
1278 profile.tags.kTRC.apply_bpc()
1279 for tagname in ("lumi", "bkpt"):
1280 if tagname == "lumi":
1281 # Absolute
1282 X, Y, Z = [
1283 (v / XYZ["wY"]) * self.getcfg("synthprofile.luminance")
1284 for v in (XYZ["wX"], XYZ["wY"], XYZ["wZ"])
1285 ]
1286 else:
1287 X, Y, Z = (XYZ["kX"], XYZ["kY"], XYZ["kZ"])
1288 profile.tags[tagname] = XYZType()
1289 (
1290 profile.tags[tagname].X,
1291 profile.tags[tagname].Y,
1292 profile.tags[tagname].Z,
1293 ) = (X, Y, Z)
1294 # Technology type
1295 if tech:
1296 if not isinstance(tech, bytes):
1297 tech = tech.encode("utf-8")
1298 profile.tags.tech = SignatureType(b"sig \0\0\0\0" + tech, "tech")
1299 # Colorimetric intent image state
1300 if ciis:
1301 if not isinstance(ciis, bytes):
1302 ciis = ciis.encode("utf-8")
1303 profile.tags.ciis = SignatureType(b"sig \0\0\0\0" + ciis, "ciis")
1304 profile.setDescription(os.path.splitext(os.path.basename(path))[0])
1305 profile.calculate_id()
1306 try:
1307 profile.write(path)
1308 except Exception as exception:
1309 return exception
1310
1311 def setup_language(self):
1312 """Setup language for the frame."""
1313 BaseFrame.setup_language(self)
1314
1315 items = [lang.getstr(item) for item in self.trc_ctrl.Items]
1316 self.trc_ctrl.SetItems(items)
1317 self.trc_ctrl.SetSelection(0)
1318
1319 self.trc_gamma_types_ab = {0: "g", 1: "G"}
1320 self.trc_gamma_types_ba = {"g": 0, "G": 1}
1321 self.trc_gamma_type_ctrl.SetItems(
1322 [lang.getstr("trc.type.relative"), lang.getstr("trc.type.absolute")]
1323 )
1324
1325 self.profile_classes = dict(
1326 get_mapping(list(PROFILE_CLASS.items()), [b"mntr", b"scnr"])
1327 )
1328 self.profile_class_ctrl.SetItems(list(self.profile_classes.values()))
1329 self.profile_class_ctrl.SetSelection(0)
1330
1331 self.tech = dict(
1332 get_mapping(
1333 [("", "unspecified"), *list(TECH.items())],
1334 [
1335 "",
1336 "fscn",
1337 "dcam",
1338 "rscn",
1339 "vidm",
1340 "vidc",
1341 "pjtv",
1342 "CRT ",
1343 "PMD ",
1344 "AMD ",
1345 "mpfs",
1346 "dmpc",
1347 "dcpj",
1348 ],
1349 )
1350 )
1351 self.tech_ctrl.SetItems(list(self.tech.values()))
1352 self.tech_ctrl.SetSelection(0)
1353
1354 self.ciis = dict(
1355 get_mapping(
1356 [("", "unspecified"), *list(CIIS.items())],
1357 ["", "scoe", "sape", "fpce"],
1358 )
1359 )
1360 self.ciis_ctrl.SetItems(list(self.ciis.values()))
1361 self.ciis_ctrl.SetSelection(0)
1362
1363 def trc_ctrl_handler(self, event=None):
1364 """Handler for TRC control.
1365
1366 Args:
1367 event (wx.Event, optional): The event object. Defaults to None.
1368 """
1369 if not self._updating_ctrls:
1370 self.preset_ctrl.SetSelection(0)
1371 i = self.trc_ctrl.GetSelection()
1372 if i == 5:
1373 # BT.1886
1374 self.setcfg("synthprofile.trc_gamma", 2.4)
1375 self.setcfg("synthprofile.trc_gamma_type", "G")
1376 self.setcfg("synthprofile.trc_output_offset", 0.0)
1377 if not self._updating_ctrls:
1378 self.update_trc_controls()
1379
1380 def trc_gamma_type_ctrl_handler(self, event):
1381 """Handler for TRC gamma type control.
1382
1383 Args:
1384 event (wx.Event): The event object.
1385 """
1386 self.setcfg(
1387 "synthprofile.trc_gamma_type",
1388 self.trc_gamma_types_ab[self.trc_gamma_type_ctrl.GetSelection()],
1389 )
1390 self.update_trc_control()
1391
1392 def trc_gamma_ctrl_handler(self, event):
1393 """Handler for TRC gamma control.
1394
1395 Args:
1396 event (wx.Event): The event object.
1397 """
1398 if self._updating_ctrls:
1399 event.Skip()
1400 return
1401 try:
1402 v = float(self.trc_gamma_ctrl.GetValue().replace(",", "."))
1403 if (
1404 v < config.VALID_RANGES["gamma"][0]
1405 or v > config.VALID_RANGES["gamma"][1]
1406 ):
1407 raise ValueError
1408 except ValueError:
1409 wx.Bell()
1410 self.trc_gamma_ctrl.SetValue(str(self.getcfg("synthprofile.trc_gamma")))
1411 else:
1412 if str(v) != self.trc_gamma_ctrl.GetValue():
1413 self.trc_gamma_ctrl.SetValue(str(v))
1414 self.setcfg("synthprofile.trc_gamma", float(self.trc_gamma_ctrl.GetValue()))
1415 self.preset_ctrl.SetSelection(0)
1416 self.update_trc_control()
1417 event.Skip()
1418
1419 def update_controls(self):
1420 """Update controls with values from the configuration."""
1421 self.luminance_ctrl.SetValue(self.getcfg("synthprofile.luminance"))
1422 self.black_luminance_ctrl.SetValue(self.getcfg("synthprofile.black_luminance"))
1423 self.update_trc_control()
1424 self.update_trc_controls()
1425
1426 def update_trc_control(self):
1427 """Update TRC control based on the current configuration."""
1428 if self.trc_ctrl.GetSelection() in (0, 5):
1429 if (
1430 self.getcfg("synthprofile.trc_gamma_type") == "G"
1431 and self.getcfg("synthprofile.trc_output_offset") == 0
1432 and self.getcfg("synthprofile.trc_gamma") == 2.4
1433 ):
1434 self.trc_ctrl.SetSelection(5) # BT.1886
1435 else:
1436 self.trc_ctrl.SetSelection(0) # Gamma
1437
1438 def update_trc_controls(self):
1439 """Update TRC controls with values from the configuration."""
1440 i = self.trc_ctrl.GetSelection()
1441 self.panel.Freeze()
1442 self.trc_gamma_label.Show(i in (0, 5))
1443 self.trc_gamma_ctrl.SetValue(str(self.getcfg("synthprofile.trc_gamma")))
1444 self.trc_gamma_ctrl.Show(i in (0, 5))
1445 self.trc_gamma_type_ctrl.SetSelection(
1446 self.trc_gamma_types_ba[self.getcfg("synthprofile.trc_gamma_type")]
1447 )
1448 if i in (0, 5, 7, 8):
1449 # Gamma, BT.1886, SMPTE 2084 (PQ)
1450 outoffset = int(self.getcfg("synthprofile.trc_output_offset") * 100)
1451 else:
1452 outoffset = 100
1453 self.black_output_offset_ctrl.SetValue(outoffset)
1454 self.black_output_offset_intctrl.SetValue(outoffset)
1455 target_peak = self.getcfg("synthprofile.luminance")
1456 maxmll = self.getcfg("3dlut.hdr_maxmll")
1457 # Don't allow maxmll < target peak. Technically this restriction does
1458 # not exist, but practically maxmll < target peak doesn't make sense.
1459 if maxmll < target_peak:
1460 maxmll = target_peak
1461 self.setcfg("3dlut.hdr_maxmll", maxmll)
1462 self.lut3d_hdr_maxmll_ctrl.SetRange(target_peak, 10000)
1463 self.luminance_ctrl.SetValue(target_peak)
1464 self.lut3d_hdr_minmll_ctrl.SetValue(self.getcfg("3dlut.hdr_minmll"))
1465 self.lut3d_hdr_maxmll_ctrl.SetValue(maxmll)
1466 self.lut3d_hdr_maxmll_alt_clip_cb.SetValue(
1467 not bool(self.getcfg("3dlut.hdr_maxmll_alt_clip"))
1468 )
1469 self.lut3d_hdr_sat_ctrl.SetValue(round(self.getcfg("3dlut.hdr_sat") * 100))
1470 self.lut3d_hdr_update_sat_val()
1471 hue = round(self.getcfg("3dlut.hdr_sat") * 100)
1472 self.lut3d_hdr_hue_ctrl.SetValue(hue)
1473 self.lut3d_hdr_hue_intctrl.SetValue(hue)
1474 self.setcfg("3dlut.hdr_peak_luminance", self.getcfg("synthprofile.luminance"))
1475 self.lut3d_hdr_update_diffuse_white()
1476 self.lut3d_hdr_ambient_luminance_ctrl.SetValue(
1477 self.getcfg("3dlut.hdr_ambient_luminance")
1478 )
1479 self.lut3d_hdr_update_system_gamma()
1480 self.lut3d_hdr_minmll_label.Show(i in (7, 8)) # SMPTE 2084 (PQ)
1481 self.lut3d_hdr_minmll_ctrl.Show(i in (7, 8)) # SMPTE 2084 (PQ)
1482 self.lut3d_hdr_minmll_ctrl_label.Show(i in (7, 8)) # SMPTE 2084 (PQ)
1483 self.lut3d_hdr_maxmll_label.Show(i == 8) # SMPTE 2084 (PQ)
1484 self.lut3d_hdr_maxmll_ctrl.Show(i == 8) # SMPTE 2084 (PQ)
1485 self.lut3d_hdr_maxmll_ctrl_label.Show(i == 8) # SMPTE 2084 (PQ)
1486 self.lut3d_show_hdr_maxmll_alt_clip_ctrl()
1487 self.lut3d_hdr_diffuse_white_label.Show(i == 8) # SMPTE 2084 (PQ)
1488 self.lut3d_hdr_diffuse_white_txt.Show(i == 8) # SMPTE 2084 (PQ)
1489 self.lut3d_hdr_diffuse_white_txt_label.Show(i == 8) # SMPTE 2084 (PQ)
1490 sizer = self.lut3d_hdr_sat_ctrl.ContainingSizer
1491 sizer.ShowItems(i == 8) # SMPTE 2084 (PQ)
1492 sizer = self.lut3d_hdr_hue_ctrl.ContainingSizer
1493 sizer.ShowItems(i == 8) # SMPTE 2084 (PQ)
1494 self.lut3d_hdr_ambient_luminance_label.Show(i == 2) # HLG
1495 self.lut3d_hdr_ambient_luminance_ctrl.Show(i == 2) # HLG
1496 self.lut3d_hdr_ambient_luminance_ctrl_label.Show(i == 2) # HLG
1497 self.lut3d_hdr_system_gamma_label.Show(i == 2) # HLG
1498 self.lut3d_hdr_system_gamma_txt.Show(i == 2) # HLG
1499 self.black_luminance_ctrl_handler(True)
1500 if i in (4, 6):
1501 # Rec 709 or SMPTE 240M
1502 # Match Adobe 'video' profiles
1503 self.profile_class_ctrl.SetStringSelection(self.profile_classes[b"scnr"])
1504 self.tech_ctrl.SetStringSelection(self.tech["vidc"])
1505 self.ciis_ctrl.SetStringSelection(self.ciis["fpce"])
1506 elif (
1507 self.profile_class_ctrl.GetStringSelection()
1508 == self.profile_classes[b"scnr"]
1509 ):
1510 # If 'input' profile, reset class/tech/colorimetric intent image state
1511 self.profile_class_ctrl.SetStringSelection(self.profile_classes[b"mntr"])
1512 self.tech_ctrl.SetStringSelection(self.tech[""])
1513 self.ciis_ctrl.SetStringSelection(self.ciis[""])
1514 self.panel.GetSizer().Layout()
1515 self.panel.Thaw()
1516
1517 def white_XYZ_ctrl_handler(self, event):
1518 """Handler for white XYZ controls.
1519
1520 Args:
1521 event: The event triggered by the control change.
1522 """
1523 self.parse_XYZ("white")
1524 self.parse_xy()
1525
1526 def white_xy_ctrl_handler(self, event):
1527 """Handler for white xy controls.
1528
1529 Args:
1530 event: The event triggered by the control change.
1531 """
1532 self.parse_xy("white")
1533
1534 def getcfg(self, name, fallback=True, raw=False, cfg=None):
1535 """Get a configuration value.
1536
1537 Args:
1538 name (str): The name of the configuration setting.
1539 fallback (bool, optional): Whether to return a fallback value if
1540 the setting does not exist. Defaults to True.
1541 raw (bool, optional): Whether to return the raw value without
1542 processing. Defaults to False.
1543 cfg (dict, optional): The configuration dictionary to retrieve from.
1544 Defaults to self.cfg.
1545
1546 Returns:
1547 The value of the configuration setting, or a fallback value if it
1548 does not exist.
1549 """
1550 if not cfg:
1551 cfg = self.cfg
1552 return getcfg(name, fallback, raw, cfg)
1553
1554 def hascfg(self, name, fallback=True, cfg=None):
1555 """Check if a configuration value exists.
1556
1557 Args:
1558 name (str): The name of the configuration setting.
1559 fallback (bool, optional): Whether to return a fallback value if
1560 the setting does not exist. Defaults to True.
1561 cfg (dict, optional): The configuration dictionary to check.
1562 Defaults to self.cfg.
1563
1564 Returns:
1565 bool: True if the configuration setting exists, False otherwise.
1566 """
1567 if not cfg:
1568 cfg = self.cfg
1569 return hascfg(name, fallback, cfg)
1570
1571 def setcfg(self, name, value, cfg=None):
1572 """Set a configuration value.
1573
1574 Args:
1575 name (str): The name of the configuration setting.
1576 value: The value to set for the configuration setting.
1577 cfg (dict, optional): The configuration dictionary to modify.
1578 Defaults to self.cfg.
1579 """
1580 if not cfg:
1581 cfg = self.cfg
1582 setcfg(name, value, cfg)
1583
1584
1585 def get_mapping(mapping, keys):
1586 """Get a mapping of keys to values."""
1587 return sorted(
1588 [
1589 (k, lang.getstr(v.lower().replace(" ", "_")))
1590 for k, v in [item for item in mapping if item[0] in keys]
1591 ],
1592 key=lambda item: item[0],
1593 )
1594
1595
1596 def main():
1597 """Main function to run the application."""
1598 config.initcfg("synthprofile")
1599 lang.init()
1600 lang.update_defaults()
1601 app = BaseApp(0)
1602 app.TopWindow = SynthICCFrame()
1603 if sys.platform == "darwin":
1604 app.TopWindow.init_menubar()
1605 wx.CallLater(1, _main, app)
1606 app.MainLoop()
1607
1608
1609 def _main(app):
1610 app.TopWindow.listen()
1611 app.process_argv(1)
1612 app.TopWindow.Show()
1613
1614
1615 if __name__ == "__main__":
1616 main()