Debian Codegraph @

DisplayCAL/wx_lut_viewer.py

raw
1 """Graphical interface for viewing and analyzing LUTs and TRCs in DisplayCAL.
2
3 It provides functionality for loading, visualizing, and interacting with LUTs
4 and ICC profiles, supporting various color spaces and rendering intents. The
5 module integrates with wxPython for plotting and user interaction.
6 """
7
8 import math
9 import os
10 import sys
11
12 import numpy
13
14 from DisplayCAL import (
15 colormath,
16 config,
17 )
18 from DisplayCAL import localization as lang
19 from DisplayCAL import wx_enhanced_plot as plot
20 from DisplayCAL.argyll import make_argyll_compatible_path
21 from DisplayCAL.argyll_cgats import cal_to_fake_profile, vcgt_to_cal
22 from DisplayCAL.config import (
23 get_argyll_display_number,
24 get_data_path,
25 get_display_profile,
26 get_display_rects,
27 get_icon,
28 get_verified_path,
29 getcfg,
30 setcfg,
31 )
32 from DisplayCAL.icc_profile import (
33 CurveType,
34 ICCProfile,
35 ICCProfileInvalidError,
36 LUT16Type,
37 ParametricCurveType,
38 TextDescriptionType,
39 VideoCardGammaTableType,
40 VideoCardGammaType,
41 WcsProfilesTagType,
42 )
43 from DisplayCAL.meta import NAME as APPNAME
44 from DisplayCAL.util_decimal import float2dec
45 from DisplayCAL.util_os import waccess
46 from DisplayCAL.worker import (
47 Error,
48 UnloggedError,
49 Worker,
50 show_result_dialog,
51 )
52 from DisplayCAL.wx_addons import get_platform_window_decoration_size, wx
53 from DisplayCAL.wx_fixes import GenBitmapButton as _GenBitmapButton
54 from DisplayCAL.wx_fixes import wx_Panel
55 from DisplayCAL.wx_measure_frame import MeasureFrame
56 from DisplayCAL.wx_windows import (
57 BaseApp,
58 BaseFrame,
59 BitmapBackgroundPanelText,
60 BitmapBackgroundPanelTextGamut,
61 CustomCheckBox,
62 FileDrop,
63 InfoDialog,
64 TooltipWindow,
65 )
66
67 BGCOLOUR = "#333333"
68 FGCOLOUR = "#999999"
69 GRIDCOLOUR = "#444444"
70 # Use conservative controls by default because some wx/SIP/native combinations
71 # can crash during widget construction across platforms.
72 SAFE_WX_UI = os.getenv("DISPLAYCAL_UNSAFE_WX_UI", "").strip() != "1"
73
74 if sys.platform == "darwin":
75 FONTSIZE_LARGE = 11
76 FONTSIZE_SMALL = 10
77 else:
78 FONTSIZE_LARGE = 9
79 FONTSIZE_SMALL = 8
80
81
82 class CoordinateType(list):
83 """List of coordinates.
84
85 [(Y, x)] where Y is in the range 0..100 and x in the range 0..255
86
87 """
88
89 def __init__(self, profile=None):
90 super().__init__()
91 self.profile = profile
92 self._transfer_function = {}
93
94 def get_gamma(
95 self,
96 use_vmin_vmax=False,
97 average=True,
98 least_squares=False,
99 slice_=(0.01, 0.99),
100 ):
101 """Return average or least squares gamma or a list of gamma values.
102
103 Args:
104 use_vmin_vmax (bool): If True, use the minimum and maximum values
105 from the coordinates for gamma calculation.
106 average (bool): If True, return the average gamma value.
107 least_squares (bool): If True, return the least squares gamma value.
108 slice_ (tuple): Tuple with start and end percentage to use for
109 calculating the gamma.
110
111 Returns:
112 float | list: If average or least_squares is True, returns a single
113 gamma value. Otherwise, returns a list of gamma values for the
114 specified slice.
115 """
116 if len(self):
117 start = slice_[0] * 100
118 end = slice_[1] * 100
119 values = []
120 for y, x in self:
121 n = colormath.XYZ2Lab(0, y, 0)[0]
122 if start <= n <= end:
123 values.append((x / 255.0 * 100, y))
124 else:
125 # Identity
126 if average or least_squares:
127 return 1.0
128 return [1.0]
129 vmin = 0
130 vmax = 100.0
131 if use_vmin_vmax and len(self) > 2:
132 vmin = self[0][0]
133 vmax = self[-1][0]
134 return colormath.get_gamma(values, 100.0, vmin, vmax, average, least_squares)
135
136 def get_transfer_function(self, best=True, slice_=(0.05, 0.95), outoffset=None):
137 """Return transfer function name, exponent and match percentage.
138
139 Args:
140 best (bool): If True, return the best match transfer function.
141 If False, return a list of all transfer functions.
142 slice_ (tuple): Tuple with start and end percentage to use for
143 calculating the transfer function.
144 outoffset (float): Output offset to apply to the transfer function.
145
146 Returns:
147 tuple: A tuple containing the transfer function name, exponent,
148 and match percentage if best is True. If best is False, returns
149 a list of tuples with transfer function name, exponent, and
150 match percentage for each transfer function.
151 """
152 transfer_function = self._transfer_function.get((best, slice_))
153 if transfer_function:
154 return transfer_function
155 xp = []
156 fp = []
157 for y, x in self:
158 xp.append(x)
159 fp.append(y)
160 interp = colormath.Interp(xp, fp, use_numpy=True)
161 otrc = CurveType(profile=self.profile)
162 for i in range(len(self)):
163 otrc.append(interp(i / (len(self) - 1.0) * 255) / 100 * 65535)
164 match = otrc.get_transfer_function(best, slice_, outoffset=outoffset)
165 self._transfer_function[(best, slice_)] = match
166 return match
167
168 def set_trc(self, power=2.2, values=(), vmin=0, vmax=100):
169 """Set the response to a certain function.
170
171 Positive power, or -2.4 = sRGB, -3.0 = L*, -240 = SMPTE 240M,
172 -601 = Rec. 601, -709 = Rec. 709 (Rec. 601 and 709 transfer functions are
173 identical)
174
175 Args:
176 power (float): The power to raise the input value to.
177 values (list): List of tuples with (Y, x) values to set.
178 vmin (float): Minimum value for Y.
179 vmax (float): Maximum value for Y.
180 """
181 self[:] = [[y, x] for y, x in values]
182 for i in range(len(self)):
183 self[i][0] = vmin + colormath.special_pow(self[i][1] / 255.0, power) * (
184 vmax - vmin
185 )
186
187
188 class PolyBox(plot.PolyLine):
189 """Box for drawing rectangles."""
190
191 def __init__(self, x, y, w, h, **attr):
192 plot.PolyLine.__init__(
193 self, [(x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)], **attr
194 )
195
196
197 class LUTCanvas(plot.PlotCanvas):
198 """Canvas for displaying LUTs and TRCs."""
199
200 def __init__(self, *args, **kwargs):
201 self.colors = {
202 "RGB_R": "red",
203 "RGB_G": "#00FF00",
204 "RGB_B": "#0080FF",
205 "CMYK_C": "cyan",
206 "CMYK_M": "magenta",
207 "CMYK_Y": "yellow",
208 "CMYK_K": "black",
209 "nCLR_0": "cyan",
210 "nCLR_1": "magenta",
211 "nCLR_2": "yellow",
212 "nCLR_3": "black",
213 "nCLR_4": "red",
214 "nCLR_5": "#00FF00",
215 "nCLR_6": "blue",
216 "nCLR_7": "#FF8000",
217 "nCLR_8": "#80FF00",
218 "nCLR_9": "#00FF80",
219 "XYZ_X": "red",
220 "XYZ_Y": "#00FF00",
221 "XYZ_Z": "#0080FF",
222 "Lab_L*": "#CCCCCC",
223 "Lab_a*": "#FF0080",
224 "Lab_a*-": "#00CC80",
225 "Lab_b*": "#FFEE00",
226 "Lab_b*-": "#0080FF",
227 }
228 plot.PlotCanvas.__init__(self, *args, **kwargs)
229 self.Unbind(wx.EVT_SCROLL_THUMBTRACK)
230 self.Unbind(wx.EVT_SCROLL_PAGEUP)
231 self.Unbind(wx.EVT_SCROLL_PAGEDOWN)
232 self.Unbind(wx.EVT_SCROLL_LINEUP)
233 self.Unbind(wx.EVT_SCROLL_LINEDOWN)
234 self.HandCursor = wx.StockCursor(wx.CURSOR_CROSS)
235 self.GrabHandCursor = wx.StockCursor(wx.CURSOR_SIZING)
236 self.SetBackgroundColour(BGCOLOUR)
237 self.SetEnableAntiAliasing(True)
238 self.SetEnableHiRes(True)
239 self.SetEnableCenterLines(True)
240 self.SetEnableDiagonals("Bottomleft-Topright")
241 self.SetEnableDrag(True)
242 self.SetEnableGrid(False)
243 self.SetEnablePointLabel(True)
244 self.SetEnableTitle(False)
245 self.SetForegroundColour(FGCOLOUR)
246 self.SetFontSizeAxis(FONTSIZE_SMALL)
247 self.SetFontSizeLegend(FONTSIZE_SMALL)
248 self.SetFontSizeTitle(FONTSIZE_LARGE)
249 self.SetGridColour(GRIDCOLOUR)
250 self.setLogScale((False, False))
251 self.SetPointLabelFunc(self.DrawPointLabel)
252 self.canvas.BackgroundColour = BGCOLOUR
253 if sys.platform == "win32" and sys.getwindowsversion() >= (6,):
254 # Enable/disable double buffering on-the-fly to make pointlabel work
255 self.canvas.Bind(wx.EVT_ENTER_WINDOW, self._disabledoublebuffer)
256 self.canvas.Bind(wx.EVT_LEAVE_WINDOW, self._enabledoublebuffer)
257 self.worker = Worker(self.TopLevelParent)
258 self.errors = []
259 self.resetzoom()
260
261 def DrawLUT(
262 self,
263 vcgt=None,
264 title=None,
265 xLabel=None,
266 yLabel=None,
267 channels=None,
268 colorspace=b"RGB",
269 connection_colorspace=b"RGB",
270 ):
271 """Draw a LUT or TRC on the canvas.
272
273 Args:
274 vcgt (VideoCardGammaType or VideoCardGammaTableType): The video
275 card gamma table or type to draw.
276 title (str): Title of the plot.
277 xLabel (str): Label for the X-axis.
278 yLabel (str): Label for the Y-axis.
279 channels (dict): Dictionary of channels to plot, e.g. {0: "R", 1:
280 "G", 2: "B"}.
281 colorspace (bytes): Colorspace of the LUT, e.g. b"RGB", b"CMYK".
282 connection_colorspace (bytes): Colorspace used for connection,
283 e.g. b"RGB".
284
285 Raises:
286 ValueError: If the colorspace is not supported or if the vcgt is
287 invalid.
288 UnloggedError: If the vcgt is not a valid VideoCardGammaType or
289 VideoCardGammaTableType.
290 """
291 if not title:
292 title = ""
293 if not xLabel:
294 xLabel = ""
295 if not yLabel:
296 yLabel = ""
297
298 detect_increments = False
299 Plot = plot.PolyLine
300 Plot._attributes["width"] = 1
301
302 maxv = 4095
303 linear_points = []
304
305 if colorspace in (b"YCbr", b"RGB", b"GRAY", b"HSV", b"HLS"):
306 axis_y = 255.0
307 axis_x = 100.0 if connection_colorspace in (b"Lab", b"XYZ") else 255.0
308 else:
309 axis_y = 100.0
310 axis_x = 100.0
311 if getattr(self, "axis_x", None) != (0, axis_x) or getattr(
312 self, "axis_y", None
313 ) != (0, axis_y):
314 self.resetzoom()
315 wx.CallAfter(self.center)
316 self.axis_x, self.axis_y = (0, axis_x), (0, axis_y)
317 if not self.last_draw:
318 self.center_x = axis_x / 2.0
319 self.center_y = axis_y / 2.0
320 self.proportional = False
321 self.spec_x = self.spec_y = 5
322
323 lines = [PolyBox(0, 0, axis_x, axis_y, colour=GRIDCOLOUR, width=1)]
324
325 # Use a point grid, so we can get the whole set of output values for
326 # each channel for any single given input value.
327 # The point grid keys are quantized to 12 bits to avoid floating point
328 # inaccuracy
329 self.point_grid = {}
330 points = {}
331 if not channels:
332 channels = {}
333 for channel in channels:
334 channel_name = channels[channel]
335 if channel_name:
336 self.point_grid[channel] = {}
337 points[channel] = []
338
339 if not vcgt:
340 irange = list(range(256))
341 elif "data" in vcgt: # table
342 data = list(vcgt["data"])
343 while len(data) < len(channels):
344 data.append(data[0])
345 if not isinstance(vcgt, VideoCardGammaTableType) and not isinstance(
346 data[0], CurveType
347 ):
348 # Coordinate list
349 irange = list(range(len(data[0])))
350 set_linear_points = True
351 for channel in range(len(data)):
352 if channel in points:
353 for n, y in data[channel]:
354 if not detect_increments and set_linear_points:
355 linear_points.append([n, n])
356 if connection_colorspace == b"Lab":
357 n = colormath.XYZ2Lab(0, n / axis_x * 100, 0)[0] * (
358 axis_x / 100.0
359 )
360 points[channel].append([n, y])
361 idx = round(n / 255.0 * 4095)
362 self.point_grid[channel][idx] = y
363 set_linear_points = False
364 else:
365 irange = list(range(vcgt["entryCount"]))
366 maxv = math.pow(256, vcgt["entrySize"]) - 1
367 for i in irange:
368 j = i * (axis_y / (vcgt["entryCount"] - 1))
369 if not detect_increments:
370 linear_points.append([j, j])
371 for channel in points:
372 values = points[channel]
373 n = float(data[channel][i]) / maxv * axis_x
374 if (
375 not detect_increments
376 or not values
377 or i == vcgt["entryCount"] - 1
378 or n != i
379 ):
380 if (
381 detect_increments
382 and n != i
383 and len(values) == 1
384 and i > 1
385 and values[-1][0] == values[-1][1]
386 ):
387 values.append([i - 1, i - 1])
388 if connection_colorspace == b"Lab":
389 n = colormath.XYZ2Lab(0, n / axis_x * 100, 0)[0] * (
390 axis_x / 100.0
391 )
392 if connection_colorspace in (b"Lab", b"XYZ"):
393 values.append([n, j])
394 idx = round(n / 255.0 * 4095)
395 self.point_grid[channel][idx] = j
396 else:
397 values.append([j, n])
398 idx = round(j / 255.0 * 4095)
399 self.point_grid[channel][idx] = n
400 else: # formula
401 irange = list(range(256))
402 step = 100.0 / axis_y
403 for i in irange:
404 # float2dec(v) fixes miniscule deviations in the calculated gamma
405 # n = float2dec(n, 8)
406 if not detect_increments:
407 linear_points.append([i, i])
408 for channel, color in enumerate(("red", "green", "blue")):
409 if channel not in points:
410 continue
411 vmin = float2dec(vcgt[f"{color}Min"] * axis_x)
412 v = float2dec(math.pow(step * i / 100.0, vcgt[f"{color}Gamma"]))
413 vmax = float2dec(vcgt[f"{color}Max"] * axis_x)
414 n = vmin + v * (vmax - vmin)
415 if connection_colorspace == b"Lab":
416 n = colormath.XYZ2Lab(0, float(n) / axis_x * 100, 0)[0] * (
417 axis_x / 100.0
418 )
419 if connection_colorspace in (b"Lab", b"XYZ"):
420 points[channel].append([n, i])
421 idx = round(float(n) / 255.0 * 4095)
422 self.point_grid[channel][idx] = i
423 else:
424 points[channel].append([i, n])
425 idx = round(i / 255.0 * 4095)
426 self.point_grid[channel][idx] = float(n)
427
428 # for n in sorted(self.point_grid[0]):
429 # print(
430 # n,
431 # self.point_grid[0].get(n),
432 # self.point_grid[1].get(n),
433 # self.point_grid[2].get(n)
434 # )
435
436 self.entryCount = irange[-1] + 1
437
438 linear = [[0, 0], [irange[-1], irange[-1]]]
439
440 if not vcgt:
441 for values in points.values():
442 if detect_increments:
443 values[:] = linear
444 else:
445 values[:] = linear_points
446
447 # Note: We need to make sure each point is a float because it
448 # might be a decimal.Decimal, which can't be divided by floats!
449 self.unique = {}
450 for channel in points:
451 values = points[channel]
452 self.unique[channel] = len(
453 {round(float(y) / axis_y * irange[-1]) for x, y in values}
454 )
455
456 legend = []
457 color = "white"
458
459 if len(points) > 1:
460 values0 = next(iter(points.values())) # first value
461 # identical = all(values == values0
462 # for values in points.itervalues())
463 identical = all(
464 all(
465 x == values0[i][0] and abs(y - values0[i][1]) < 0.005
466 for i, (x, y) in enumerate(values)
467 )
468 for values in points.values()
469 )
470 else:
471 identical = False
472
473 if identical:
474 channels_label = "".join(list(channels.values()))
475 color = self.get_color(channels_label, color)
476 legend.extend(
477 channel_name for channel_name in list(channels.values()) if channel_name
478 )
479 linear_points = [(i, round(v / axis_y * maxv)) for i, v in linear_points]
480 seen_values = []
481 seen_labels = []
482 for channel in points:
483 values = points[channel]
484 channel_label = channels[channel]
485 if not identical:
486 color = self.colors.get(
487 f"{colorspace.decode('utf-8')}_{channel_label}", "white"
488 )
489 # Note: We need to make sure each point is a float because it
490 # might be a decimal.Decimal, which can't be divided by floats!
491 points_quantized = [(i, round(float(v) / axis_y * maxv)) for i, v in values]
492 line2 = None
493 if identical:
494 label = "=".join(legend)
495 suffix = (
496 (", {}".format(lang.getstr("linear").capitalize()))
497 if points_quantized
498 == (linear if detect_increments else linear_points)
499 else ""
500 )
501 else:
502 label = channel_label
503 suffix = ""
504 if channel_label in ("a*", "b*") and len(values) > 1:
505 half = len(values) / 2
506 values2 = values[:half]
507 values = values[half:]
508 center_x = (values[0][0] + values2[-1][0]) / 2.0
509 center_y = (values[0][1] + values2[-1][1]) / 2.0
510 center = [center_x, center_y]
511 if values[0] != center:
512 values.insert(0, center)
513 if values2[-1] != center:
514 values2.append(center)
515 idx = round(center_x / 255.0 * 4095)
516 self.point_grid[channel][idx] = center_y
517 color2 = self.colors[f"Lab_{channel_label}-"]
518 line2 = Plot(values2, legend=label + suffix, colour=color2)
519 elif seen_values:
520 # Check if same line (+- 0.005 tolerance) has been seen
521 for seen in seen_values:
522 match = True
523 for i, (x, y) in enumerate(seen):
524 if x != values[i][0] or abs(y - values[i][1]) > 0.005:
525 match = False
526 break
527 if match:
528 break
529 else:
530 match = False
531 if match:
532 idx = len(seen_values) - 1
533 seen_label = seen_labels[idx]
534 lines[idx + 1].attributes["colour"] = self.get_color(
535 seen_label + channel_label
536 )
537 continue
538 line = Plot(values, legend=label + suffix, colour=color)
539 if (colorspace == "CMYK" and label == "K") or (
540 colorspace == "Lab" and label in ("a*", "b*")
541 ):
542 # CMYK -> KCMY, Lab -> baL for better visibilty
543 lines.insert(1, line)
544 seen_values.insert(0, values)
545 seen_labels.insert(0, label)
546 if line2:
547 lines.insert(1, line2)
548 else:
549 lines.append(line)
550 seen_values.append(values)
551 seen_labels.append(label)
552 if line2:
553 lines.append(line2)
554 if identical:
555 break
556
557 self._DrawCanvas(
558 plot.PlotGraphics(
559 lines,
560 title,
561 " ".join([xLabel, lang.getstr("in")]),
562 " ".join([yLabel, lang.getstr("out")]),
563 )
564 )
565
566 def get_color(self, channels_label, default="white"):
567 """Get color based on channels label.
568
569 Args:
570 channels_label (str): The label of the channels.
571 default (str): Default color if no specific color is found.
572
573 Returns:
574 str: The color.
575 """
576 if channels_label in ("RGB", "CMYK", "XYZ"):
577 return "white"
578 if channels_label in ("RG", "XY"):
579 return "yellow"
580 if channels_label in ("RB", "XZ"):
581 return "magenta"
582 if channels_label in ("GB", "YZ"):
583 return "cyan"
584 if channels_label == "CM":
585 return "#0080FF"
586 if channels_label == "CY":
587 return "#00FF00"
588 if channels_label == "MY":
589 return "red"
590 return default
591
592 def DrawPointLabel(self, dc, mDataDict):
593 """Draw point labels.
594
595 Args:
596 dc (wx.DC): DC that will be passed.
597 mDataDict (dict): Dictionary of data that you want to use for the
598 pointLabel.
599 """
600 if not self.last_draw:
601 return
602 graphics, xAxis, yAxis = self.last_draw
603 # sizes axis to axis type, create lower left and upper right corners of plot
604 if xAxis is None or yAxis is None:
605 # One or both axis not specified in Draw
606 p1, p2 = graphics.boundingBox() # min, max points of graphics
607 if xAxis is None:
608 xAxis = self._axisInterval(self._xSpec, p1[0], p2[0]) # in user units
609 if yAxis is None:
610 yAxis = self._axisInterval(self._ySpec, p1[1], p2[1])
611 # Adjust bounding box for axis spec
612 p1[0], p1[1] = (
613 xAxis[0],
614 yAxis[0],
615 ) # lower left corner user scale (xmin,ymin)
616 p2[0], p2[1] = (
617 xAxis[1],
618 yAxis[1],
619 ) # upper right corner user scale (xmax,ymax)
620 else:
621 # Both axis specified in Draw
622 p1 = numpy.array(
623 [xAxis[0], yAxis[0]]
624 ) # lower left corner user scale (xmin,ymin)
625 p2 = numpy.array(
626 [xAxis[1], yAxis[1]]
627 ) # upper right corner user scale (xmax,ymax)
628 ptx, pty, rectWidth, rectHeight = self._point2ClientCoord(p1, p2)
629 # allow graph to overlap axis lines by adding units to width and height
630 dc.SetClippingRegion(
631 int(ptx), int(pty), int(rectWidth + 2), int(rectHeight + 2)
632 )
633
634 dc.SetPen(wx.Pen(wx.WHITE, 1, wx.PENSTYLE_DOT))
635 dc.SetBrush(wx.Brush(wx.WHITE, wx.BRUSHSTYLE_SOLID))
636
637 sx, sy = mDataDict["scaledXY"] # Scaled x, y of closest point
638 dc.DrawLine(0, int(sy), int(ptx + rectWidth + 2), int(sy))
639 dc.DrawLine(int(sx), 0, int(sx), int(pty + rectHeight + 2))
640
641 def GetClosestPoints(self, pntXY, pointScaled=True):
642 """Get closest points in all curves to a given point.
643
644 Return a list with [curveNumber, legend, index of closest point,
645 pointXY, scaledXY, distance] list for each curve.
646 Returns [] if no curves are being plotted.
647
648 x, y in user coords
649 if pointScaled == True based on screen coords
650 if pointScaled == False based on user coords
651
652 Args;
653 pntXY (tuple): The point coordinates (x, y) to find the closest
654 points to.
655 pointScaled (bool): Whether the point coordinates are scaled or not.
656
657 Returns:
658 list: A list of lists, each containing information about the
659 closest point in each curve.
660 """
661 if self.last_draw is None:
662 # no graph available
663 return []
664 graphics, xAxis, yAxis = self.last_draw
665 l = []
666 for curveNum, obj in enumerate(graphics):
667 # check there are points in the curve
668 if len(obj.points) == 0 or isinstance(obj, PolyBox):
669 continue # go to next obj
670 # [curveNumber, legend, index of closest point, pointXY, scaledXY, distance]
671 cn = [curveNum, obj.getLegend(), *obj.getClosestPoint(pntXY, pointScaled)]
672 l.append(cn)
673 return l
674
675 def _disabledoublebuffer(self, event):
676 """Disable double buffering for the canvas and its parent windows.
677
678 Args:
679 event (wx.Event): The event that triggered this method.
680 """
681 window = self
682 while window:
683 if not isinstance(window, wx.TopLevelWindow):
684 window.SetDoubleBuffered(False)
685 window = window.Parent
686 event.Skip()
687
688 def _enabledoublebuffer(self, event):
689 """Enable double buffering for the canvas and its parent windows.
690
691 Args:
692 event (wx.Event): The event that triggered this method.
693 """
694 window = self
695 while window:
696 if not isinstance(window, wx.TopLevelWindow):
697 window.SetDoubleBuffered(True)
698 window = window.Parent
699 event.Skip()
700
701 def OnMouseDoubleClick(self, event):
702 """Handle mouse double click event.
703
704 Args:
705 event (wx.Event): The mouse double click event.
706 """
707 boundingbox = self.last_draw[0].boundingBox() if self.last_draw else None
708 self.resetzoom(boundingbox=boundingbox)
709 if self.last_draw:
710 self.center()
711
712 def OnMouseLeftDown(self, event):
713 """Handle mouse left button down event.
714
715 Args:
716 event (wx.Event): The mouse left button down event.
717 """
718 self.erase_pointlabel()
719 self._zoomCorner1[0], self._zoomCorner1[1] = self._getXY(event)
720 self._screenCoordinates = numpy.array(event.GetPosition())
721 if self._dragEnabled:
722 self.SetCursor(self.GrabHandCursor)
723 self.canvas.CaptureMouse()
724
725 def OnMouseLeftUp(self, event):
726 """Handle mouse left button release event.
727
728 Args:
729 event (wx.Event): The mouse left button release event.
730 """
731 if self._dragEnabled:
732 self.SetCursor(self.HandCursor)
733 if self.canvas.HasCapture():
734 self.canvas.ReleaseMouse()
735 self._set_center()
736 if hasattr(self.TopLevelParent, "OnMotion"):
737 self.TopLevelParent.OnMotion(event)
738
739 def _DrawCanvas(self, graphics):
740 """Draw proportionally correct, center and zoom."""
741 w = float(self.GetSize()[0] or 1)
742 h = float(self.GetSize()[1] or 1)
743 if w > 45:
744 w -= 45
745 if h > 20:
746 h -= 20
747 ratio = [w / h, h / w]
748 axis_x, axis_y = self.axis_x, self.axis_y
749 spec_x = self.spec_x
750 spec_y = self.spec_y
751 if self._zoomfactor < 1:
752 while spec_x * self._zoomfactor < self.spec_x / 2.0:
753 spec_x *= 2
754 while spec_y * self._zoomfactor < self.spec_y / 2.0:
755 spec_y *= 2
756 else:
757 while spec_x * self._zoomfactor > self.spec_x * 2:
758 spec_x /= 2
759 while spec_y * self._zoomfactor > self.spec_y * 2:
760 spec_y /= 2
761 if self.proportional:
762 if ratio[0] > ratio[1]:
763 self.SetXSpec(spec_x * self._zoomfactor * ratio[0])
764 else:
765 self.SetXSpec(spec_x * self._zoomfactor)
766 if ratio[0] > 1:
767 axis_x = tuple([v * ratio[0] for v in axis_x])
768 if ratio[1] > ratio[0]:
769 self.SetYSpec(spec_y * self._zoomfactor * ratio[1])
770 else:
771 self.SetYSpec(spec_y * self._zoomfactor)
772 if ratio[1] > 1:
773 axis_y = tuple([v * ratio[1] for v in axis_y])
774 else:
775 self.SetXSpec(spec_x * self._zoomfactor)
776 self.SetYSpec(spec_y * self._zoomfactor)
777 x, y = self.center_x, self.center_y
778 w = (axis_x[1] - axis_x[0]) * self._zoomfactor
779 h = (axis_y[1] - axis_y[0]) * self._zoomfactor
780 axis_x = (x - w / 2, x + w / 2)
781 axis_y = (y - h / 2, y + h / 2)
782 self.Draw(graphics, axis_x, axis_y)
783
784 def _set_center(self):
785 """Set center position from current X and Y axis."""
786 if not self.last_draw:
787 return
788 axis_x = self.GetXCurrentRange()
789 axis_y = self.GetYCurrentRange()
790 if axis_x[0] < 0:
791 if axis_x[1] < 0:
792 x = axis_x[0] + (abs(axis_x[0]) - abs(axis_x[1])) / 2.0
793 else:
794 x = axis_x[0] + (abs(axis_x[1]) + abs(axis_x[0])) / 2.0
795 else:
796 x = axis_x[0] + (abs(axis_x[1]) - abs(axis_x[0])) / 2.0
797 if axis_y[0] < 0:
798 if axis_y[1] < 0:
799 y = axis_y[0] + (abs(axis_y[0]) - abs(axis_y[1])) / 2.0
800 else:
801 y = axis_y[0] + (abs(axis_y[1]) + abs(axis_y[0])) / 2.0
802 else:
803 y = axis_y[0] + (abs(axis_y[1]) - abs(axis_y[0])) / 2.0
804 self.center_x, self.center_y = x, y
805
806 def center(self, boundingbox=None):
807 """Center the current graphic.
808
809 Args:
810 boundingbox (tuple): Optional bounding box to center the graphic to.
811 If not provided, the current axis range will be used.
812 """
813 if boundingbox:
814 # Min, max points of graphics
815 p1, p2 = boundingbox
816 # In user units
817 min_x, max_x = self._axisInterval(self._xSpec, p1[0], p2[0])
818 min_y, max_y = self._axisInterval(self._ySpec, p1[1], p2[1])
819 else:
820 min_x, max_x = self.GetXMaxRange()
821 min_y, max_y = self.GetYMaxRange()
822 self.center_x = 0 + sum((min_x, max_x)) / 2.0
823 self.center_y = 0 + sum((min_y, max_y)) / 2.0
824 if not boundingbox:
825 self.erase_pointlabel()
826 self._DrawCanvas(self.last_draw[0])
827
828 def erase_pointlabel(self):
829 """Erase the point label if it exists."""
830 if self.GetEnablePointLabel() and self.last_PointLabel:
831 # Erase point label
832 self._drawPointLabel(self.last_PointLabel)
833 self.last_PointLabel = None
834
835 def resetzoom(self, boundingbox=None):
836 """Reset zoom to fit bounding box.
837
838 Args:
839 boundingbox (tuple): Optional bounding box to fit the zoom to.
840 If not provided, the current axis range will be used.
841 """
842 self.center_x = 0
843 self.center_y = 0
844 self._zoomfactor = 1.0
845 if not boundingbox:
846 return
847 # Min, max points of graphics
848 p1, p2 = boundingbox
849 # In user units
850 min_x, max_x = self._axisInterval(self._xSpec, p1[0], p2[0])
851 min_y, max_y = self._axisInterval(self._ySpec, p1[1], p2[1])
852 max_abs_x = abs(min_x) + max_x
853 max_abs_y = abs(min_y) + max_y
854 max_abs_axis_x = abs(self.axis_x[0]) + self.axis_x[1]
855 max_abs_axis_y = abs(self.axis_y[0]) + self.axis_y[1]
856 w = float(self.GetSize()[0] or 1)
857 h = float(self.GetSize()[1] or 1)
858 if w > 45:
859 w -= 45
860 if h > 20:
861 h -= 20
862 ratio = [w / h, h / w]
863 if ratio[0] > 1:
864 max_abs_axis_x *= ratio[0]
865 if ratio[1] > 1:
866 max_abs_axis_y *= ratio[1]
867 if max_abs_x / max_abs_y > max_abs_axis_x / max_abs_axis_y:
868 self._zoomfactor = max_abs_x / max_abs_axis_x
869 else:
870 self._zoomfactor = max_abs_y / max_abs_axis_y
871
872 def zoom(self, direction=1.0):
873 """Zoom in or out.
874
875 Args:
876 direction (float): 1.0 for zoom in, -1.0 for zoom out.
877 """
878 _zoomfactor = 0.025 * direction
879 if 0 < self._zoomfactor + _zoomfactor <= 5:
880 self._zoomfactor += _zoomfactor
881 self._set_center()
882 self.erase_pointlabel()
883 self._DrawCanvas(self.last_draw[0])
884
885
886 class LUTFrame(BaseFrame):
887 """LUTFrame."""
888
889 def _create_toolbar_button(
890 self,
891 parent,
892 bitmap_provider,
893 label,
894 tooltip,
895 handler,
896 sizer,
897 add_kwargs=None,
898 ):
899 """Create a toolbar button with a safe fallback."""
900 add_kwargs = add_kwargs or {}
901 if SAFE_WX_UI:
902 button = wx.Button(parent, -1, label=label, style=wx.BU_EXACTFIT)
903 else:
904 bitmap = bitmap_provider()
905 button = _GenBitmapButton(parent, -1, bitmap, style=wx.NO_BORDER)
906 button.SetBackgroundColour(BGCOLOUR)
907 sizer.Add(button, **add_kwargs)
908 button.Bind(wx.EVT_BUTTON, handler)
909 button.SetToolTip(tooltip)
910 return button
911
912 def __init__(self, *args, **kwargs):
913 if len(args) < 3 and "title" not in kwargs:
914 kwargs["title"] = lang.getstr("calibration.lut_viewer.title")
915 if "name" not in kwargs:
916 kwargs["name"] = "lut_viewer"
917
918 BaseFrame.__init__(self, *args, **kwargs)
919
920 if not SAFE_WX_UI:
921 self.SetIcons(
922 config.get_icon_bundle([256, 48, 32, 16], f"{APPNAME}-curve-viewer")
923 )
924
925 self.profile = None
926 self.xLabel = lang.getstr("in")
927 self.yLabel = lang.getstr("out")
928
929 self.sizer = wx.BoxSizer(wx.VERTICAL)
930 self.SetSizer(self.sizer)
931
932 panel = wx_Panel(self)
933 panel.SetBackgroundColour(BGCOLOUR)
934 self.sizer.Add(panel, flag=wx.EXPAND)
935 panel.SetSizer(wx.FlexGridSizer(0, 5, 0, 8))
936 panel.Sizer.AddGrowableCol(0)
937 panel.Sizer.AddGrowableCol(4)
938
939 panel.Sizer.Add((1, 1))
940 panel.Sizer.Add((1, 12))
941 panel.Sizer.Add((1, 12))
942 panel.Sizer.Add((1, 12))
943 panel.Sizer.Add((1, 1))
944
945 panel.Sizer.Add((1, 1))
946
947 self.plot_mode_select = wx.Choice(panel, -1, size=(-1, -1), choices=[])
948 panel.Sizer.Add(self.plot_mode_select, flag=wx.ALIGN_CENTER_VERTICAL)
949 self.Bind(
950 wx.EVT_CHOICE,
951 self.plot_mode_select_handler,
952 id=self.plot_mode_select.GetId(),
953 )
954
955 self.tooltip_btn = self._create_toolbar_button(
956 panel,
957 lambda: get_icon(16, "question-inverted"),
958 "?",
959 lang.getstr("gamut_plot.tooltip"),
960 self.tooltip_handler,
961 panel.Sizer,
962 {"flag": wx.ALIGN_CENTER_VERTICAL},
963 )
964
965 self.save_plot_btn = self._create_toolbar_button(
966 panel,
967 lambda: get_icon(16, "image-x-generic-inverted"),
968 "Save",
969 f"{lang.getstr('save_as')} (*.bmp, *.xbm, *.xpm, *.jpg, *.png)",
970 self.SaveFile,
971 panel.Sizer,
972 {"flag": wx.ALIGN_CENTER_VERTICAL},
973 )
974 self.save_plot_btn.Disable()
975
976 panel.Sizer.Add((1, 1))
977
978 panel.Sizer.Add((1, 1))
979 panel.Sizer.Add((1, 4))
980 panel.Sizer.Add((1, 4))
981 panel.Sizer.Add((1, 4))
982 panel.Sizer.Add((1, 1))
983
984 self.client = LUTCanvas(self)
985 self.sizer.Add(self.client, 1, wx.EXPAND)
986
987 self.box_panel = wx_Panel(self)
988 self.box_panel.SetBackgroundColour(BGCOLOUR)
989 self.sizer.Add(self.box_panel, flag=wx.EXPAND)
990
991 self.status = BitmapBackgroundPanelText(self, name="statuspanel")
992 self.gamut_status = BitmapBackgroundPanelTextGamut(self, name="statuspanel")
993 self.status.SetMaxFontSize(11)
994 self.status.label_y = 8
995 self.status.textshadow = False
996 self.status.SetBackgroundColour(BGCOLOUR)
997 self.status.SetForegroundColour(FGCOLOUR)
998 h = self.status.GetTextExtent("Ig")[1]
999 self.status.SetMinSize((0, h * 2 + 18))
1000 self.sizer.Add(self.status, flag=wx.EXPAND)
1001
1002 self.box_sizer = wx.FlexGridSizer(0, 3, 4, 4)
1003 self.box_sizer.AddGrowableCol(0)
1004 self.box_sizer.AddGrowableCol(2)
1005 self.box_panel.SetSizer(self.box_sizer)
1006
1007 self.box_sizer.Add((0, 0))
1008
1009 hsizer = wx.BoxSizer(wx.HORIZONTAL)
1010
1011 self.box_sizer.Add(
1012 hsizer,
1013 # flag=wx.ALIGN_CENTER | wx.BOTTOM | wx.TOP, border=4)
1014 flag=wx.BOTTOM | wx.TOP,
1015 border=4,
1016 )
1017
1018 self.rendering_intent_select = wx.Choice(
1019 self.box_panel,
1020 -1,
1021 choices=[
1022 lang.getstr("gamap.intents.a"),
1023 lang.getstr("gamap.intents.r"),
1024 lang.getstr("gamap.intents.p"),
1025 lang.getstr("gamap.intents.s"),
1026 ],
1027 )
1028 hsizer.Add((10, self.rendering_intent_select.Size[1]))
1029 hsizer.Add(self.rendering_intent_select, flag=wx.ALIGN_CENTER_VERTICAL)
1030 self.rendering_intent_select.Bind(
1031 wx.EVT_CHOICE, self.rendering_intent_select_handler
1032 )
1033 self.rendering_intent_select.SetSelection(1)
1034
1035 self.direction_select = wx.Choice(
1036 self.box_panel,
1037 -1,
1038 choices=[
1039 lang.getstr("direction.backward"),
1040 lang.getstr("direction.forward.inverted"),
1041 ],
1042 )
1043 hsizer.Add(
1044 self.direction_select, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=10
1045 )
1046 self.direction_select.Bind(wx.EVT_CHOICE, self.direction_select_handler)
1047 self.direction_select.SetSelection(0)
1048
1049 self.show_actual_lut_cb = CustomCheckBox(
1050 self.box_panel, -1, lang.getstr("calibration.show_actual_lut")
1051 )
1052 self.show_actual_lut_cb.SetForegroundColour(FGCOLOUR)
1053 self.show_actual_lut_cb.SetMaxFontSize(11)
1054 hsizer.Add(
1055 self.show_actual_lut_cb,
1056 # flag=wx.ALIGN_CENTER |
1057 flag=wx.ALIGN_CENTER_VERTICAL,
1058 )
1059 self.show_actual_lut_cb.Bind(wx.EVT_CHECKBOX, self.show_actual_lut_handler)
1060
1061 self.box_sizer.Add((0, 0))
1062
1063 self.box_sizer.Add((0, 0))
1064
1065 self.cbox_sizer = wx.BoxSizer(wx.HORIZONTAL)
1066 self.box_sizer.Add(
1067 self.cbox_sizer,
1068 # flag=wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.TOP,
1069 flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP,
1070 border=4,
1071 )
1072
1073 self.box_sizer.Add((0, 0))
1074
1075 self.cbox_sizer.Add((10, 0))
1076
1077 self.reload_vcgt_btn = self._create_toolbar_button(
1078 self.box_panel,
1079 lambda: get_icon(16, "stock_refresh-inverted"),
1080 "Reload",
1081 lang.getstr("calibration.load_from_display_profile"),
1082 self.reload_vcgt_handler,
1083 self.cbox_sizer,
1084 {"flag": wx.ALIGN_CENTER_VERTICAL, "border": 8},
1085 )
1086 self.reload_vcgt_btn.Disable()
1087
1088 self.apply_bpc_btn = self._create_toolbar_button(
1089 self.box_panel,
1090 lambda: get_icon(16, "color-inverted"),
1091 "BPC",
1092 lang.getstr("black_point_compensation"),
1093 self.apply_bpc_handler,
1094 self.cbox_sizer,
1095 {"flag": wx.ALIGN_CENTER_VERTICAL, "border": 8},
1096 )
1097 self.apply_bpc_btn.Disable()
1098
1099 self.install_vcgt_btn = self._create_toolbar_button(
1100 self.box_panel,
1101 lambda: get_icon(16, "install-inverted"),
1102 "Apply",
1103 lang.getstr("apply_cal"),
1104 self.install_vcgt_handler,
1105 self.cbox_sizer,
1106 {"flag": wx.ALIGN_CENTER_VERTICAL, "border": 8},
1107 )
1108 self.install_vcgt_btn.Disable()
1109
1110 self.save_vcgt_btn = self._create_toolbar_button(
1111 self.box_panel,
1112 lambda: get_icon(16, "document-save-as-inverted"),
1113 "Save CAL",
1114 f"{lang.getstr('save_as')} (*.cal)",
1115 self.SaveFile,
1116 self.cbox_sizer,
1117 {"flag": wx.ALIGN_CENTER_VERTICAL, "border": 20},
1118 )
1119 self.save_vcgt_btn.Disable()
1120
1121 self.show_as_L = CustomCheckBox(self.box_panel, -1, "L* \u2192")
1122 self.show_as_L.SetForegroundColour(FGCOLOUR)
1123 self.show_as_L.SetMaxFontSize(11)
1124 self.show_as_L.SetValue(True)
1125 self.cbox_sizer.Add(
1126 self.show_as_L,
1127 # flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
1128 flag=wx.ALIGN_CENTER_VERTICAL,
1129 border=4,
1130 )
1131 self.show_as_L.Bind(wx.EVT_CHECKBOX, self.DrawLUT)
1132
1133 self.add_toggles(self.box_panel, self.cbox_sizer)
1134
1135 self.toggle_clut = CustomCheckBox(self.box_panel, -1, "LUT")
1136 self.toggle_clut.SetForegroundColour(FGCOLOUR)
1137 self.toggle_clut.SetMaxFontSize(11)
1138 self.cbox_sizer.Add(
1139 self.toggle_clut,
1140 # flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
1141 flag=wx.ALIGN_CENTER_VERTICAL,
1142 border=16,
1143 )
1144 self.toggle_clut.Bind(wx.EVT_CHECKBOX, self.toggle_clut_handler)
1145
1146 self.client.canvas.Bind(wx.EVT_MOTION, self.OnMotion)
1147
1148 self.droptarget = FileDrop(self)
1149 self.droptarget.drophandlers = {
1150 ".cal": self.drop_handler,
1151 ".icc": self.drop_handler,
1152 ".icm": self.drop_handler,
1153 }
1154 self.client.SetDropTarget(self.droptarget)
1155
1156 border, titlebar = get_platform_window_decoration_size()
1157 self.MinSize = (
1158 config.DEFAULTS["size.lut_viewer.w"] + border * 2,
1159 config.DEFAULTS["size.lut_viewer.h"] + titlebar + border,
1160 )
1161 self.SetSaneGeometry(
1162 getcfg("position.lut_viewer.x"),
1163 getcfg("position.lut_viewer.y"),
1164 getcfg("size.lut_viewer.w"),
1165 getcfg("size.lut_viewer.h"),
1166 )
1167
1168 self.Bind(wx.EVT_MOVE, self.OnMove)
1169 self.Bind(wx.EVT_SIZE, self.OnSize)
1170
1171 children = list(self.GetAllChildren())
1172
1173 self.Bind(wx.EVT_KEY_DOWN, self.key_handler)
1174 for child in children:
1175 if isinstance(child, wx.Choice):
1176 child.SetMaxFontSize(11)
1177 child.Bind(wx.EVT_KEY_DOWN, self.key_handler)
1178 child.Bind(wx.EVT_MOUSEWHEEL, self.OnWheel)
1179 if (
1180 sys.platform == "win32"
1181 and sys.getwindowsversion() >= (6,)
1182 and isinstance(child, wx.Panel)
1183 ):
1184 # No need to enable double buffering under Linux and Mac OS X.
1185 # Under Windows, enabling double buffering on the panel seems
1186 # to work best to reduce flicker.
1187 child.SetDoubleBuffered(True)
1188
1189 self.display_no = -1
1190 self.display_rects = get_display_rects()
1191
1192 def apply_bpc_handler(self, event):
1193 """Apply black point compensation to the current profile.
1194
1195 Args:
1196 event (wx.Event): The event triggered by the button.
1197 """
1198 cal = vcgt_to_cal(self.profile)
1199 cal.filename = self.profile.filename or ""
1200 cal.apply_bpc(weight=True)
1201 self.LoadProfile(cal_to_fake_profile(cal))
1202
1203 def drop_handler(self, path):
1204 """Handle drag'n'drop for .cal/.icc/.icm files."""
1205 filename, ext = os.path.splitext(path)
1206 if ext.lower() not in (".icc", ".icm"):
1207 profile = cal_to_fake_profile(path)
1208 if not profile:
1209 InfoDialog(
1210 self,
1211 msg=lang.getstr("error.file.open", path),
1212 ok=lang.getstr("ok"),
1213 bitmap=get_icon(32, "dialog-error"),
1214 )
1215 profile = None
1216 else:
1217 try:
1218 profile = ICCProfile(path)
1219 except (OSError, ICCProfileInvalidError):
1220 InfoDialog(
1221 self,
1222 msg=f"{lang.getstr('profile.invalid')}\n{path}",
1223 ok=lang.getstr("ok"),
1224 bitmap=get_icon(32, "dialog-error"),
1225 )
1226 profile = None
1227 self.show_actual_lut_cb.SetValue(False)
1228 self.current_cal = profile
1229 self.LoadProfile(profile)
1230
1231 get_display = MeasureFrame.__dict__["get_display"]
1232
1233 def handle_errors(self):
1234 """Handle errors from the client."""
1235 if not self.client.errors:
1236 return
1237 show_result_dialog(
1238 Error(
1239 "\n\n".join([f"{e}" for e in set(self.client.errors) if e is not None])
1240 ),
1241 self,
1242 )
1243 self.client.errors = []
1244
1245 def install_vcgt_handler(self, event):
1246 """Install the VCGT from the current profile to the display.
1247
1248 Args:
1249 event (wx.Event): The event triggered by the button.
1250 """
1251 cwd = self.worker.create_tempdir()
1252 if isinstance(cwd, Exception):
1253 show_result_dialog(cwd, self)
1254 else:
1255 cal = os.path.join(
1256 cwd,
1257 make_argyll_compatible_path(
1258 self.profile.getDescription() or "Video LUT", is_name=True
1259 ),
1260 )
1261 vcgt_to_cal(self.profile).write(cal)
1262 cmd, args = self.worker.prepare_dispwin(cal)
1263 if isinstance(cmd, Exception):
1264 show_result_dialog(cmd, self)
1265 elif cmd:
1266 result = self.worker.exec_cmd(
1267 cmd, args, capture_output=True, skip_scripts=True
1268 )
1269 if isinstance(result, Exception):
1270 show_result_dialog(result, self)
1271 elif not result:
1272 show_result_dialog(Error("".join(self.worker.errors)), self)
1273 # Important:
1274 # Make sure to only delete the temporary cal file we created
1275 try:
1276 os.remove(cal)
1277 except Exception as exception:
1278 print(
1279 f"Warning - temporary file '{cal}' could not be removed: "
1280 f"{exception}"
1281 )
1282
1283 def key_handler(self, event):
1284 """Handle key events for the LUT viewer.
1285
1286 Args:
1287 event (wx.Event): The event triggered by the key press.
1288 """
1289 # AltDown
1290 # CmdDown
1291 # ControlDown
1292 # GetKeyCode
1293 # GetModifiers
1294 # GetPosition
1295 # GetRawKeyCode
1296 # GetRawKeyFlags
1297 # GetUniChar
1298 # GetUnicodeKey
1299 # GetX
1300 # GetY
1301 # HasModifiers
1302 # KeyCode
1303 # MetaDown
1304 # Modifiers
1305 # Position
1306 # RawKeyCode
1307 # RawKeyFlags
1308 # ShiftDown
1309 # UnicodeKey
1310 # X
1311 # Y
1312 key = event.GetKeyCode()
1313 if (
1314 event.ControlDown() or event.CmdDown()
1315 ): # CTRL (Linux/Mac/Windows) / CMD (Mac)
1316 if key == 83 and self.profile: # S
1317 self.SaveFile()
1318 return
1319 event.Skip()
1320 elif key in (43, wx.WXK_NUMPAD_ADD):
1321 # + key zoom in
1322 self.client.zoom(-1)
1323 elif key in (45, wx.WXK_NUMPAD_SUBTRACT):
1324 # - key zoom out
1325 self.client.zoom(1)
1326 else:
1327 event.Skip()
1328
1329 def direction_select_handler(self, event):
1330 """Handle the direction selection.
1331
1332 Args:
1333 event (wx.Event): The event triggered by the choice selection.
1334 """
1335 self.toggle_clut_handler(event)
1336
1337 def rendering_intent_select_handler(self, event):
1338 """Handle the rendering intent selection.
1339
1340 Args:
1341 event (wx.Event): The event triggered by the choice selection.
1342 """
1343 self.toggle_clut_handler(event)
1344
1345 def toggle_clut_handler(self, event):
1346 """Handle the toggle CLUT checkbox.
1347
1348 Args:
1349 event (wx.Event): The event triggered by the checkbox.
1350 """
1351 try:
1352 self.lookup_tone_response_curves()
1353 except Exception as exception:
1354 import traceback
1355
1356 print(traceback.format_exc())
1357 show_result_dialog(exception, self)
1358 else:
1359 self.trc = None
1360 self.DrawLUT()
1361 self.handle_errors()
1362
1363 def tooltip_handler(self, event):
1364 """Handle the tooltip button.
1365
1366 Args:
1367 event (wx.Event): The event triggered by the button.
1368 """
1369 if not hasattr(self, "tooltip_window"):
1370 self.tooltip_window = TooltipWindow(
1371 self,
1372 msg=event.EventObject.ToolTip.Tip,
1373 title=event.EventObject.TopLevelParent.Title,
1374 bitmap=get_icon(32, "dialog-information"),
1375 )
1376 else:
1377 self.tooltip_window.Show()
1378 self.tooltip_window.Raise()
1379
1380 def show_actual_lut_handler(self, event):
1381 """Handle the show actual LUT checkbox.
1382
1383 Args:
1384 event (wx.Event): The event triggered by the checkbox.
1385 """
1386 setcfg("lut_viewer.show_actual_lut", int(self.show_actual_lut_cb.GetValue()))
1387 profile = self.current_cal if hasattr(self, "current_cal") else None
1388 self.load_lut(profile=profile)
1389
1390 def load_lut(self, profile=None):
1391 """Load LUT from profile.
1392
1393 Args:
1394 profile (ICCProfile): The profile to load the LUT from.
1395 """
1396 self.current_cal = profile
1397 if (
1398 getcfg("lut_viewer.show_actual_lut")
1399 and (
1400 self.worker.argyll_version[0:3] > [1, 1, 0]
1401 or (
1402 self.worker.argyll_version[0:3] == [1, 1, 0]
1403 and "Beta" not in self.worker.argyll_version_string
1404 )
1405 )
1406 and not config.is_untethered_display()
1407 ):
1408 tmp = self.worker.create_tempdir()
1409 if isinstance(tmp, Exception):
1410 show_result_dialog(tmp, self)
1411 return
1412 outfilename = os.path.join(
1413 tmp,
1414 make_argyll_compatible_path(
1415 config.get_display_name(include_geometry=True) or "Video LUT",
1416 is_name=True,
1417 ),
1418 )
1419 result = self.worker.save_current_video_lut(
1420 self.worker.get_display(),
1421 outfilename,
1422 silent=__name__ != "__main__",
1423 )
1424 if not isinstance(result, Exception) and result:
1425 profile = cal_to_fake_profile(outfilename)
1426 elif isinstance(result, Exception):
1427 print(result)
1428 # Important: lut_viewer_load_lut is called after measurements,
1429 # so make sure to only delete the temporary cal file we created
1430 try:
1431 os.remove(outfilename)
1432 except Exception as exception:
1433 print(
1434 f"Warning - temporary file '{outfilename}' could not be removed: "
1435 f"{exception}"
1436 )
1437 if profile and (
1438 profile.is_loaded
1439 or not profile.filename
1440 or os.path.isfile(profile.filename)
1441 ):
1442 if (
1443 not self.profile
1444 or self.profile.filename != profile.filename
1445 or not self.profile.is_same(profile)
1446 ):
1447 self.LoadProfile(profile)
1448 else:
1449 self.LoadProfile(None)
1450
1451 def lookup_tone_response_curves(self, intent="r"):
1452 """Lookup Y -> RGB tone values through TRC tags or LUT.
1453
1454 Args:
1455 intent (str): Rendering intent, one of 'a', 'r', 'p', 's'.
1456 """
1457 profile = self.profile
1458
1459 # Final number of coordinates
1460 if profile.connectionColorSpace == b"RGB":
1461 size = 256
1462 elif profile.connectionColorSpace == b"Lab":
1463 size = 1001
1464 else:
1465 size = 1024
1466
1467 if hasattr(self, "rendering_intent_select"):
1468 intent = {0: "a", 1: "r", 2: "p", 3: "s"}.get(
1469 self.rendering_intent_select.GetSelection()
1470 )
1471
1472 use_trc_tags = (
1473 intent == "r"
1474 and (
1475 not ("B2A0" in self.profile.tags or "A2B0" in self.profile.tags)
1476 or not self.toggle_clut.GetValue()
1477 )
1478 and isinstance(self.rTRC, CurveType)
1479 and isinstance(self.gTRC, CurveType)
1480 and isinstance(self.bTRC, CurveType)
1481 and len(self.rTRC) == len(self.gTRC) == len(self.bTRC)
1482 )
1483 has_same_trc = self.rTRC == self.gTRC == self.bTRC
1484
1485 if profile.version >= 4 and not profile.convert_iccv4_tags_to_iccv2():
1486 self.client.errors.append(
1487 Error(
1488 "\n".join(
1489 [
1490 lang.getstr("profile.iccv4.unsupported"),
1491 profile.getDescription(),
1492 ]
1493 )
1494 )
1495 )
1496 return
1497
1498 if profile.colorSpace not in (
1499 b"RGB",
1500 b"GRAY",
1501 b"CMYK",
1502 ) or profile.connectionColorSpace not in (b"Lab", b"XYZ", b"RGB"):
1503 if profile.colorSpace not in (b"RGB", b"GRAY", b"CMYK"):
1504 unsupported_colorspace = profile.colorSpace
1505 else:
1506 unsupported_colorspace = profile.connectionColorSpace
1507 self.client.errors.append(
1508 Error(
1509 lang.getstr(
1510 "profile.unsupported",
1511 (
1512 profile.profileClass.decode("utf-8"),
1513 unsupported_colorspace.decode("utf-8"),
1514 ),
1515 )
1516 )
1517 )
1518 return
1519
1520 if profile.colorSpace == b"GRAY":
1521 direction = "b"
1522 elif profile.connectionColorSpace == b"RGB":
1523 direction = "f"
1524 elif "B2A0" in profile.tags:
1525 index = self.direction_select.GetSelection()
1526 if index == -1: # Fix for #31
1527 index = 0
1528 self.direction_select.SetSelection(index)
1529 direction = {0: "b", 1: "if", 2: "f", 3: "ib"}.get(
1530 self.direction_select.GetSelection()
1531 )
1532 else:
1533 direction = "if"
1534
1535 # Prepare input Lab values
1536 XYZ_triplets = []
1537 Lab_triplets = []
1538 devicevalues = []
1539 for i in range(size):
1540 if direction in ("b", "if"):
1541 if intent == "a":
1542 # For display profiles, identical to relcol
1543 # For print profiles, makes max L* match paper white
1544 XYZwp_ir = list(profile.tags.wtpt.ir.values())
1545 Labwp_ir = profile.tags.wtpt.ir.Lab
1546 XYZwp_D50 = colormath.Lab2XYZ(Labwp_ir[0], 0, 0)
1547 X, Y, Z = colormath.Lab2XYZ(
1548 min(i * (100.0 / (size - 1)), Labwp_ir[0]), 0, 0
1549 )
1550 L, a, b = colormath.XYZ2Lab(
1551 *[
1552 v * 100
1553 for v in colormath.adapt(X, Y, Z, XYZwp_D50, XYZwp_ir)
1554 ]
1555 )
1556 else:
1557 L = i * (100.0 / (size - 1))
1558 a = b = 0
1559 Lab_triplets.append([L, a, b])
1560 else:
1561 devicevalues.append([i * (1.0 / (size - 1))] * len(profile.colorSpace))
1562 if profile.colorSpace == "GRAY":
1563 use_icclu = True
1564 pcs = "x"
1565 XYZ_triplets.extend(colormath.Lab2XYZ(*Lab) for Lab in Lab_triplets)
1566 elif profile.connectionColorSpace == b"RGB":
1567 use_icclu = False
1568 pcs = None
1569 intent = None
1570 else:
1571 use_icclu = False
1572 pcs = "l"
1573 if direction in ("b", "if"):
1574 idata = Lab_triplets if pcs == "l" else XYZ_triplets
1575 else:
1576 idata = devicevalues
1577
1578 order = {True: "n", False: "r"}.get(
1579 ("B2A0" in self.profile.tags or "A2B0" in self.profile.tags)
1580 and self.toggle_clut.GetValue()
1581 )
1582
1583 # Lookup values through 'input' profile using xicclu
1584 try:
1585 odata = self.worker.xicclu(
1586 profile,
1587 idata,
1588 intent,
1589 direction,
1590 order,
1591 pcs,
1592 use_icclu=use_icclu,
1593 get_clip=direction == "if",
1594 )
1595 except Exception as exception:
1596 self.client.errors.append(Error(exception))
1597
1598 if self.client.errors:
1599 return
1600
1601 if direction in ("b", "if") or profile.connectionColorSpace == b"RGB":
1602 if direction == "if" and profile.colorSpace == b"RGB":
1603 Lbp = self.worker.xicclu(
1604 profile, [[0, 0, 0]], intent, "f", order, "l", use_icclu=use_icclu
1605 )[0][0]
1606 maxval = size - 1.0
1607
1608 # Deal with values that got clipped (below black as well as white)
1609 # XXX: We should not clip these when plotting, because our input
1610 # values are all a = b = 0
1611 do_low_clip = False
1612 make_mono = True
1613 # Keep the max amount of useful information from Lbp onwards
1614 mono_end = 0
1615 for i, values in enumerate(odata):
1616 if values[3] is True or i == 0:
1617 if (do_low_clip and (i / maxval * 100 < Lbp or i == 0)) or (
1618 make_mono and i == 0
1619 ):
1620 # Set to black
1621 values[:] = [0.0, 0.0, 0.0]
1622 elif i == maxval and [round(v, 4) for v in values[:3]] == [
1623 1,
1624 1,
1625 1,
1626 ]:
1627 # Set to white
1628 values[:] = [1.0, 1.0, 1.0]
1629 elif i / maxval * 100 < Lbp:
1630 mono_end = i + 2
1631 else:
1632 # First non-clipping value disables low clipping
1633 do_low_clip = False
1634 if len(values) > 3:
1635 values.pop()
1636
1637 if mono_end and mono_end < len(odata):
1638 # Make segment from first non-zero value to Lbp
1639 # monotonically increasing
1640 mono = [[], [], []]
1641 for values in odata:
1642 for j in range(3):
1643 mono[j].append(values[j])
1644 for j, values in enumerate(mono):
1645 for v in values:
1646 if v:
1647 break
1648 if i:
1649 i -= 1
1650 if i + 2 < mono_end:
1651 mono[j][i:mono_end] = (
1652 colormath.make_monotonically_increasing(
1653 values[i:mono_end]
1654 )
1655 )
1656 odata = []
1657 for i in range(len(mono[0])):
1658 values = []
1659 for j in range(3):
1660 values.append(mono[j][i])
1661 odata.append(values)
1662
1663 devicevalues = odata
1664 else:
1665 Lab_triplets = odata
1666
1667 maxv = 255 if profile.colorSpace in (b"RGB", b"GRAY") else 100
1668 self.rTRC = CoordinateType(self.profile)
1669 self.gTRC = CoordinateType(self.profile)
1670 self.bTRC = CoordinateType(self.profile)
1671 self.kTRC = CoordinateType(self.profile)
1672 for j, sample in enumerate(devicevalues):
1673 for i, v in enumerate(sample):
1674 v = min(v, 1.0)
1675 if (
1676 not v
1677 and j < len(devicevalues) - 1
1678 and not min(devicevalues[j + 1][i], 1.0)
1679 ):
1680 continue
1681 v *= maxv
1682 if profile.connectionColorSpace == b"RGB":
1683 x = j / (size - 1.0) * maxv
1684 if i == 0:
1685 self.rTRC.append([x, v])
1686 elif i == 1:
1687 self.gTRC.append([x, v])
1688 elif i == 2:
1689 self.bTRC.append([x, v])
1690 else:
1691 X, Y, Z = colormath.Lab2XYZ(*Lab_triplets[j], scale=100)
1692 if direction in ("b", "if"):
1693 X = Z = Y
1694 elif intent == "a":
1695 wp = list(profile.tags.wtpt.ir.values())
1696 X, Y, Z = colormath.adapt(X, Y, Z, wp, (1, 1, 1))
1697 elif intent != "a":
1698 wp = list(profile.tags.wtpt.ir.values())
1699 X, Y, Z = colormath.adapt(X, Y, Z, "D50", (1, 1, 1))
1700 if i == 0:
1701 self.rTRC.append([X, v])
1702 elif i == 1:
1703 self.gTRC.append([Y, v])
1704 elif i == 2:
1705 self.bTRC.append([Z, v])
1706 elif i == 3:
1707 self.kTRC.append([Y, v])
1708 if profile.connectionColorSpace == b"RGB":
1709 return
1710 if use_trc_tags:
1711 if has_same_trc:
1712 self.bTRC = self.gTRC = self.rTRC
1713 return
1714 # Generate interpolated TRCs for transfer function detection
1715 prev = None
1716 for sig in ("rTRC", "gTRC", "bTRC", "kTRC"):
1717 x, xp, y, yp = [], [], [], []
1718 # First, get actual values
1719 for Y, v in getattr(self, sig):
1720 # if not i or Y >= trc[sig][i - 1]:
1721 xp.append(v)
1722 yp.append(Y)
1723 setattr(self, f"tf_{sig}", CoordinateType(self.profile))
1724 if not xp or not yp:
1725 if prev:
1726 getattr(self, f"tf_{sig}")[:] = prev
1727 continue
1728 # Second, interpolate to given size and use the same y axis
1729 # for all channels
1730 for i in range(size):
1731 x.append(i / (size - 1.0) * maxv)
1732 y.append(colormath.Lab2XYZ(i / (size - 1.0) * 100, 0, 0)[1] * 100)
1733 xi = numpy.interp(y, yp, xp)
1734 yi = numpy.interp(x, xi, y)
1735 prev = getattr(self, f"tf_{sig}")
1736 for Y, v in zip(yi, x):
1737 Y = max(yp[0], Y) # noqa: SIM300
1738 prev.append([Y, v])
1739
1740 def move_handler(self, event):
1741 """Handle the move event to update the display number and load the LUT.
1742
1743 Args:
1744 event (wx.Event): The event that triggered this handler.
1745 """
1746 if not self.IsShownOnScreen():
1747 return
1748 display_no, geometry, client_area = self.get_display()
1749 if display_no != self.display_no:
1750 self.display_no = display_no
1751 # Translate from wx display index to Argyll display index
1752 n = get_argyll_display_number(geometry)
1753 if n is not None:
1754 # Save Argyll display index to configuration
1755 setcfg("display.number", n + 1)
1756 # Load profile
1757 self.load_lut(get_display_profile(n))
1758 event.Skip()
1759
1760 def plot_mode_select_handler(self, event):
1761 """Handle selection of the plot mode from the dropdown.
1762
1763 Args:
1764 event (wx.Event): The event that triggered this handler.
1765 """
1766 # self.client.resetzoom()
1767 self.DrawLUT()
1768
1769 def get_commands(self):
1770 """Get a list of commands that can be used with this frame."""
1771 return [
1772 *self.get_common_commands(),
1773 "curve-viewer [filename]",
1774 "load <filename>",
1775 ]
1776
1777 def process_data(self, data):
1778 """Process commands from the command line or other sources.
1779
1780 Args:
1781 data (list): A list of strings containing the command and its
1782 arguments.
1783
1784 Returns:
1785 str: "ok" if the command was processed successfully, "fail" if
1786 the command failed, or "invalid" if the command is not
1787 recognized.
1788 """
1789 if (data[0] == "curve-viewer" and len(data) < 3) or (
1790 data[0] == "load" and len(data) == 2
1791 ):
1792 if self.IsIconized():
1793 self.Restore()
1794 self.Raise()
1795 if len(data) == 2:
1796 path = data[1]
1797 if not os.path.isfile(path) and not os.path.isabs(path):
1798 path = get_data_path(path)
1799 if not path:
1800 return "fail"
1801 self.droptarget.OnDropFiles(0, 0, [path])
1802 return "ok"
1803 return "invalid"
1804
1805 def reload_vcgt_handler(self, event):
1806 """Reload the VCGT from the display profile.
1807
1808 Args:
1809 event (wx.Event): The event that triggered this handler.
1810 """
1811 cmd, args = self.worker.prepare_dispwin(True)
1812 if isinstance(cmd, Exception):
1813 show_result_dialog(cmd, self)
1814 elif cmd:
1815 result = self.worker.exec_cmd(
1816 cmd, args, capture_output=True, skip_scripts=True
1817 )
1818 if isinstance(result, Exception):
1819 show_result_dialog(result, self)
1820 elif not result:
1821 show_result_dialog(UnloggedError("".join(self.worker.errors)), self)
1822 else:
1823 self.load_lut(get_display_profile())
1824
1825 def LoadProfile(self, profile):
1826 """Load a profile and update the LUT viewer.
1827
1828 Args:
1829 profile (ICCProfile or str): The ICC profile to load, either as an
1830 ICCProfile object or a file path.
1831 """
1832 if profile and not isinstance(profile, ICCProfile):
1833 try:
1834 profile = ICCProfile(profile)
1835 except (OSError, ICCProfileInvalidError):
1836 show_result_dialog(
1837 Error(f"{lang.getstr('profile.invalid')}\n{profile}"), self
1838 )
1839 profile = None
1840 if not profile:
1841 profile = ICCProfile()
1842 profile._data = "\0" * 128
1843 profile._tags.desc = TextDescriptionType(b"", "desc")
1844 profile.size = len(profile.data)
1845 profile.is_loaded = True
1846 center = False
1847 if (
1848 getattr(self, "profile", None)
1849 and self.profile.colorSpace != profile.colorSpace
1850 ):
1851 center = True
1852 if profile.getDescription():
1853 title = " \u2014 ".join(
1854 [lang.getstr("calibration.lut_viewer.title"), profile.getDescription()]
1855 )
1856 else:
1857 title = lang.getstr("calibration.lut_viewer.title")
1858 self.SetTitle(title)
1859 self.profile = profile
1860 for channel in "rgb":
1861 trc = profile.tags.get(f"{channel}TRC", profile.tags.get("kTRC"))
1862 if isinstance(trc, ParametricCurveType):
1863 trc = trc.get_trc()
1864 setattr(self, f"{channel}TRC", trc)
1865 setattr(self, f"tf_{channel}TRC", trc)
1866 self.trc = None
1867 curves = []
1868 if (
1869 "vcgt" in profile.tags
1870 or "MS00" in profile.tags
1871 or self.__class__ is LUTFrame
1872 ):
1873 curves.append(lang.getstr("vcgt"))
1874 self.client.errors = []
1875 self.toggle_clut.SetValue("B2A0" in profile.tags or "A2B0" in profile.tags)
1876 if (self.rTRC and self.gTRC and self.bTRC) or (
1877 self.toggle_clut.GetValue()
1878 and profile.colorSpace in (b"RGB", b"GRAY", b"CMYK")
1879 ):
1880 try:
1881 self.lookup_tone_response_curves()
1882 except Exception as exception:
1883 wx.CallAfter(show_result_dialog, exception, self)
1884 else:
1885 curves.append(lang.getstr("[rgb]TRC"))
1886 curves = self.add_shaper_curves(curves)
1887 selection = self.plot_mode_select.GetStringSelection()
1888 self.plot_mode_select.SetItems(curves)
1889 self.plot_mode_select.Enable(len(curves) > 1)
1890 if curves and not self.plot_mode_select.SetStringSelection(selection):
1891 self.plot_mode_select.SetSelection(0)
1892 center = True
1893 self.plot_mode_select.ContainingSizer.Layout()
1894 self.cbox_sizer.Layout()
1895 self.box_sizer.Layout()
1896 self.DrawLUT()
1897 if center:
1898 wx.CallAfter(self.client.center)
1899 wx.CallAfter(self.handle_errors)
1900
1901 def add_shaper_curves(self, curves):
1902 """Add shaper curves to the list of curves if available.
1903
1904 Args:
1905 curves (list): The list of curves to which shaper curves will be
1906 added.
1907
1908 Returns:
1909 list: The updated list of curves including shaper curves if they
1910 are available.
1911 """
1912 if getcfg("show_advanced_options"):
1913 if isinstance(self.profile.tags.get("A2B0"), LUT16Type):
1914 curves.append(lang.getstr("profile.tags.A2B0.shaper_curves.input"))
1915 curves.append(lang.getstr("profile.tags.A2B0.shaper_curves.output"))
1916 if isinstance(self.profile.tags.get("A2B1"), LUT16Type):
1917 curves.append(lang.getstr("profile.tags.A2B1.shaper_curves.input"))
1918 curves.append(lang.getstr("profile.tags.A2B1.shaper_curves.output"))
1919 if isinstance(self.profile.tags.get("A2B2"), LUT16Type):
1920 curves.append(lang.getstr("profile.tags.A2B2.shaper_curves.input"))
1921 curves.append(lang.getstr("profile.tags.A2B2.shaper_curves.output"))
1922 if isinstance(self.profile.tags.get("B2A0"), LUT16Type):
1923 curves.append(lang.getstr("profile.tags.B2A0.shaper_curves.input"))
1924 curves.append(lang.getstr("profile.tags.B2A0.shaper_curves.output"))
1925 if isinstance(self.profile.tags.get("B2A1"), LUT16Type):
1926 curves.append(lang.getstr("profile.tags.B2A1.shaper_curves.input"))
1927 curves.append(lang.getstr("profile.tags.B2A1.shaper_curves.output"))
1928 if isinstance(self.profile.tags.get("B2A2"), LUT16Type):
1929 curves.append(lang.getstr("profile.tags.B2A2.shaper_curves.input"))
1930 curves.append(lang.getstr("profile.tags.B2A2.shaper_curves.output"))
1931 return curves
1932
1933 def add_toggles(self, parent, sizer):
1934 """Add toggle checkboxes for up to 16 channels.
1935
1936 Args:
1937 parent (wx.Panel): The parent panel to which the toggles will be added.
1938 sizer (wx.Sizer): The sizer to which the toggles will be added.
1939 """
1940 # Add toggle checkboxes for up to 16 channels
1941 self.toggles = []
1942 for i in range(16):
1943 if SAFE_WX_UI:
1944 toggle = wx.CheckBox(parent, -1, "", name=f"toggle_channel_{i}")
1945 else:
1946 toggle = CustomCheckBox(parent, -1, "", name=f"toggle_channel_{i}")
1947 toggle.SetForegroundColour(FGCOLOUR)
1948 if hasattr(toggle, "SetMaxFontSize"):
1949 toggle.SetMaxFontSize(11)
1950 toggle.SetValue(True)
1951 sizer.Add(
1952 toggle,
1953 flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
1954 border=4 if i < 15 else 0,
1955 )
1956 toggle.Bind(wx.EVT_CHECKBOX, self.DrawLUT)
1957 self.toggles.append(toggle)
1958 toggle.Hide()
1959
1960 def add_tone_values(self, legend):
1961 """Add tone values to the legend.
1962
1963 Args:
1964 legend (list): The legend to which tone values will be added.
1965 """
1966 if not self.profile:
1967 return
1968 colorants = legend[0]
1969 if (
1970 self.plot_mode_select.GetStringSelection() == lang.getstr("vcgt")
1971 and "vcgt" in self.profile.tags
1972 ):
1973 if "R" in colorants or "G" in colorants or "B" in colorants:
1974 legend.append(lang.getstr("tone_values"))
1975 if False: # "=" in colorants: # NEVER
1976 unique = []
1977 if 0 in self.client.unique: # Red
1978 unique.append(self.client.unique[0])
1979 if 1 in self.client.unique: # Green
1980 unique.append(self.client.unique[1])
1981 if 2 in self.client.unique: # Blue
1982 unique.append(self.client.unique[2])
1983 unique = min(unique)
1984 legend[-1] += " {:.1f}% ({}/{})".format( # noqa: UP032
1985 unique / (self.client.entryCount / 100.0),
1986 unique,
1987 self.client.entryCount,
1988 )
1989 else:
1990 if 0 in self.client.unique: # Red
1991 legend[-1] += " {:.1f}% ({}/{})".format( # noqa: UP032
1992 self.client.unique[0] / (self.client.entryCount / 100.0),
1993 self.client.unique[0],
1994 self.client.entryCount,
1995 )
1996 if 1 in self.client.unique: # Green
1997 legend[-1] += " {:.1f}% ({}/{})".format( # noqa: UP032
1998 self.client.unique[1] / (self.client.entryCount / 100.0),
1999 self.client.unique[1],
2000 self.client.entryCount,
2001 )
2002 if 2 in self.client.unique: # Blue
2003 legend[-1] += " {:.1f}% ({}/{})".format( # noqa: UP032
2004 self.client.unique[2] / (self.client.entryCount / 100.0),
2005 self.client.unique[2],
2006 self.client.entryCount,
2007 )
2008 unique = list(self.client.unique.values())
2009 if 0 not in unique and "R=G=B" not in colorants:
2010 unique = min(unique)
2011 legend[-1] += ", {} {:.1f}% ({}/{})".format(
2012 lang.getstr("grayscale"),
2013 unique / (self.client.entryCount / 100.0),
2014 unique,
2015 self.client.entryCount,
2016 )
2017 elif (
2018 self.plot_mode_select.GetStringSelection() == lang.getstr("[rgb]TRC")
2019 and isinstance(self.tf_rTRC, (CurveType, CoordinateType))
2020 and len(self.tf_rTRC) > 1
2021 and isinstance(self.tf_gTRC, (CurveType, CoordinateType))
2022 and len(self.tf_gTRC) > 1
2023 and isinstance(self.tf_bTRC, (CurveType, CoordinateType))
2024 and len(self.tf_bTRC) > 1
2025 ):
2026 transfer_function = None
2027 if not getattr(self, "trc", None) and len(self.tf_rTRC) == len(
2028 self.tf_gTRC
2029 ) == len(self.tf_bTRC):
2030 if isinstance(self.tf_rTRC, CurveType):
2031 self.trc = CurveType(profile=self.profile)
2032 for i in range(len(self.tf_rTRC)):
2033 self.trc.append(
2034 (self.tf_rTRC[i] + self.tf_gTRC[i] + self.tf_bTRC[i]) / 3.0
2035 )
2036 else:
2037 self.trc = CoordinateType(self.profile)
2038 for i in range(len(self.tf_rTRC)):
2039 self.trc.append(
2040 [
2041 (
2042 self.tf_rTRC[i][0]
2043 + self.tf_gTRC[i][0]
2044 + self.tf_bTRC[i][0]
2045 )
2046 / 3.0,
2047 (
2048 self.tf_rTRC[i][1]
2049 + self.tf_gTRC[i][1]
2050 + self.tf_bTRC[i][1]
2051 )
2052 / 3.0,
2053 ]
2054 )
2055 if getattr(self, "trc", None):
2056 transfer_function = self.trc.get_transfer_function(
2057 slice_=(0.00, 1.00), outoffset=1.0
2058 )
2059 # if "R" in colorants and "G" in colorants and "B" in colorants:
2060 # if (self.profile.tags.rTRC == self.profile.tags.gTRC ==
2061 # self.profile.tags.bTRC):
2062 # transfer_function = self.profile.tags.rTRC.get_transfer_function()
2063 # elif ("R" in colorants and (not "G" in colorants or
2064 # self.profile.tags.rTRC == self.profile.tags.gTRC) and
2065 # (not "B" in colorants or
2066 # self.profile.tags.rTRC == self.profile.tags.bTRC)):
2067 # transfer_function = self.profile.tags.rTRC.get_transfer_function()
2068 # elif ("G" in colorants and (not "R" in colorants or
2069 # self.profile.tags.gTRC == self.profile.tags.rTRC) and
2070 # (not "B" in colorants or
2071 # self.profile.tags.gTRC == self.profile.tags.bTRC)):
2072 # transfer_function = self.profile.tags.gTRC.get_transfer_function()
2073 # elif ("B" in colorants and (not "G" in colorants or
2074 # self.profile.tags.bTRC == self.profile.tags.gTRC) and
2075 # (not "R" in colorants or
2076 # self.profile.tags.bTRC == self.profile.tags.rTRC)):
2077 # transfer_function = self.profile.tags.bTRC.get_transfer_function()
2078 if transfer_function and transfer_function[1] >= 0.95:
2079 if self.tf_rTRC == self.tf_gTRC == self.tf_bTRC:
2080 label = lang.getstr("rgb.trc")
2081 else:
2082 label = lang.getstr("rgb.trc.averaged")
2083 if round(transfer_function[1], 2) == 1.0:
2084 value = f"{transfer_function[0][0]}"
2085 else:
2086 value = (
2087 f"≈ {transfer_function[0][0]} "
2088 f"(Δ {1 - transfer_function[1]:.2%})"
2089 )
2090 legend.append(f"{label} {value}")
2091
2092 def DrawLUT(self, event=None):
2093 """Draw the LUT in the client area.
2094
2095 Args:
2096 event: The event that triggered the redraw, if any.
2097 """
2098 self.SetStatusText("")
2099 self.Freeze()
2100 curves = None
2101 curves_colorspace = self.profile.colorSpace
2102 connection_colorspace = b"RGB"
2103 if self.profile and self.plot_mode_select.Items:
2104 if self.plot_mode_select.GetStringSelection() == lang.getstr("vcgt"):
2105 # Convert calibration information from embedded WCS profile
2106 # (if present) to VideCardFormulaType if the latter is not present
2107 if (
2108 isinstance(self.profile.tags.get("MS00"), WcsProfilesTagType)
2109 and "vcgt" not in self.profile.tags
2110 ):
2111 vcgt = self.profile.tags["MS00"].get_vcgt()
2112 if vcgt:
2113 self.profile.tags["vcgt"] = vcgt
2114 if "vcgt" in self.profile.tags:
2115 curves = self.profile.tags["vcgt"]
2116 else:
2117 curves = None
2118 elif self.plot_mode_select.GetStringSelection() == lang.getstr("[rgb]TRC"):
2119 if not (
2120 isinstance(self.rTRC, (CurveType, CoordinateType))
2121 and isinstance(self.gTRC, (CurveType, CoordinateType))
2122 and isinstance(self.bTRC, (CurveType, CoordinateType))
2123 ):
2124 curves = None
2125 elif (
2126 len(self.rTRC) == 1 and len(self.gTRC) == 1 and len(self.bTRC) == 1
2127 ):
2128 # gamma
2129 curves = {
2130 "redMin": 0.0,
2131 "redGamma": self.rTRC[0],
2132 "redMax": 1.0,
2133 "greenMin": 0.0,
2134 "greenGamma": self.gTRC[0],
2135 "greenMax": 1.0,
2136 "blueMin": 0.0,
2137 "blueGamma": self.bTRC[0],
2138 "blueMax": 1.0,
2139 }
2140 else:
2141 # curves
2142 data = [self.rTRC, self.gTRC, self.bTRC]
2143 if hasattr(self, "kTRC"):
2144 data.append(self.kTRC)
2145 curves = {
2146 "data": data,
2147 "entryCount": len(self.rTRC),
2148 "entrySize": 2,
2149 }
2150 elif self.plot_mode_select.GetStringSelection() != lang.getstr("gamut"):
2151 to_pcs = False
2152 if self.plot_mode_select.GetStringSelection() == lang.getstr(
2153 "profile.tags.A2B0.shaper_curves.input"
2154 ):
2155 tables = self.profile.tags.A2B0.input
2156 elif self.plot_mode_select.GetStringSelection() == lang.getstr(
2157 "profile.tags.A2B0.shaper_curves.output"
2158 ):
2159 tables = self.profile.tags.A2B0.output
2160 curves_colorspace = self.profile.connectionColorSpace
2161 to_pcs = True
2162 elif self.plot_mode_select.GetStringSelection() == lang.getstr(
2163 "profile.tags.A2B1.shaper_curves.input"
2164 ):
2165 tables = self.profile.tags.A2B1.input
2166 elif self.plot_mode_select.GetStringSelection() == lang.getstr(
2167 "profile.tags.A2B1.shaper_curves.output"
2168 ):
2169 tables = self.profile.tags.A2B1.output
2170 curves_colorspace = self.profile.connectionColorSpace
2171 to_pcs = True
2172 elif self.plot_mode_select.GetStringSelection() == lang.getstr(
2173 "profile.tags.A2B2.shaper_curves.input"
2174 ):
2175 tables = self.profile.tags.A2B2.input
2176 elif self.plot_mode_select.GetStringSelection() == lang.getstr(
2177 "profile.tags.A2B2.shaper_curves.output"
2178 ):
2179 tables = self.profile.tags.A2B2.output
2180 curves_colorspace = self.profile.connectionColorSpace
2181 to_pcs = True
2182 elif self.plot_mode_select.GetStringSelection() == lang.getstr(
2183 "profile.tags.B2A0.shaper_curves.input"
2184 ):
2185 tables = self.profile.tags.B2A0.input
2186 curves_colorspace = self.profile.connectionColorSpace
2187 elif self.plot_mode_select.GetStringSelection() == lang.getstr(
2188 "profile.tags.B2A0.shaper_curves.output"
2189 ):
2190 tables = self.profile.tags.B2A0.output
2191 elif self.plot_mode_select.GetStringSelection() == lang.getstr(
2192 "profile.tags.B2A1.shaper_curves.input"
2193 ):
2194 tables = self.profile.tags.B2A1.input
2195 curves_colorspace = self.profile.connectionColorSpace
2196 elif self.plot_mode_select.GetStringSelection() == lang.getstr(
2197 "profile.tags.B2A1.shaper_curves.output"
2198 ):
2199 tables = self.profile.tags.B2A1.output
2200 elif self.plot_mode_select.GetStringSelection() == lang.getstr(
2201 "profile.tags.B2A2.shaper_curves.input"
2202 ):
2203 tables = self.profile.tags.B2A2.input
2204 curves_colorspace = self.profile.connectionColorSpace
2205 elif self.plot_mode_select.GetStringSelection() == lang.getstr(
2206 "profile.tags.B2A2.shaper_curves.output"
2207 ):
2208 tables = self.profile.tags.B2A2.output
2209 entry_count = len(tables[0])
2210 maxv = 100 if curves_colorspace != b"RGB" else 255
2211 lin = [v / (entry_count - 1.0) * maxv for v in range(entry_count)]
2212 data = []
2213 for i, table in enumerate(tables):
2214 xp = lin
2215 if curves_colorspace == b"Lab" and i == 0:
2216 if to_pcs:
2217 table = [v / 65280.0 * 65535.0 for v in table]
2218 else:
2219 xp = [
2220 min(
2221 v / (entry_count - 1.0) * (100 + 25500 / 65280.0),
2222 maxv,
2223 )
2224 for v in range(entry_count)
2225 ]
2226 yp = [v / 65535.0 * maxv for v in table]
2227 if curves_colorspace == b"Lab" and i == 0:
2228 # Interpolate to given size and use the same y axis
2229 # for all channels
2230 xi = numpy.interp(lin, yp, xp)
2231 yi = numpy.interp(lin, xi, lin)
2232 else:
2233 yi = yp
2234 xy = []
2235 for Y, v in zip(yi, lin):
2236 Y = max(yp[0], Y) # noqa: SIM300
2237 xy.append([v, Y])
2238 data.append(xy)
2239 curves = {"data": data, "entryCount": entry_count, "entrySize": 2}
2240 yLabel = []
2241 numchannels = {
2242 b"XYZ": 3,
2243 b"Lab": 3,
2244 b"Luv": 3,
2245 b"YCbr": 3,
2246 b"Yxy": 3,
2247 b"RGB": 3,
2248 b"GRAY": 1,
2249 b"HSV": 3,
2250 b"HLS": 3,
2251 b"CMYK": 4,
2252 b"CMY": 3,
2253 b"2CLR": 2,
2254 b"3CLR": 3,
2255 b"4CLR": 4,
2256 b"5CLR": 5,
2257 b"6CLR": 6,
2258 b"7CLR": 7,
2259 b"8CLR": 8,
2260 b"9CLR": 9,
2261 b"ACLR": 10,
2262 b"BCLR": 11,
2263 b"CCLR": 12,
2264 b"DCLR": 13,
2265 b"ECLR": 14,
2266 b"FCLR": 15,
2267 }.get(curves_colorspace, 3)
2268 is_ktrc = (
2269 self.plot_mode_select.GetStringSelection() == lang.getstr("[rgb]TRC")
2270 and curves_colorspace != b"RGB"
2271 and False
2272 )
2273 if is_ktrc:
2274 curves_colorspace = b"GRAY"
2275 numchannels = 1
2276 for channel, toggle in enumerate(self.toggles):
2277 toggle.Show(channel < numchannels)
2278 if channel < numchannels:
2279 if curves_colorspace == b"GRAY":
2280 toggle.Label = "R=G=B"
2281 elif curves_colorspace == b"YCbr":
2282 toggle.Label = ("Y", "Cb", "Cr")[channel]
2283 elif curves_colorspace.endswith(b"CLR"):
2284 curves_colorspace = b"nCLR"
2285 toggle.Label = f"{channel}"
2286 elif curves_colorspace == b"Lab":
2287 toggle.Label = ("L*", "a*", "b*")[channel]
2288 else:
2289 toggle.Label = curves_colorspace[channel : channel + 1].decode(
2290 "utf-8"
2291 )
2292 if toggle.GetValue():
2293 yLabel.append(toggle.Label)
2294 toggle.Enable(bool(curves))
2295 if self.plot_mode_select.GetStringSelection() not in (
2296 lang.getstr("[rgb]TRC"),
2297 lang.getstr("gamut"),
2298 ) or (self.profile and self.profile.connectionColorSpace == b"RGB"):
2299 self.xLabel = "".join(yLabel)
2300 elif self.show_as_L.GetValue():
2301 connection_colorspace = b"Lab"
2302 self.xLabel = "L*"
2303 else:
2304 connection_colorspace = b"XYZ"
2305 self.xLabel = "Y"
2306 self.yLabel = "".join(yLabel)
2307
2308 self.show_as_L.Enable(bool(curves))
2309 self.show_as_L.Show(
2310 self.plot_mode_select.GetStringSelection() == lang.getstr("[rgb]TRC")
2311 and self.profile.connectionColorSpace != b"RGB"
2312 )
2313 self.toggle_clut.Show(
2314 self.profile.colorSpace == b"RGB"
2315 and self.profile.connectionColorSpace != b"RGB"
2316 and self.plot_mode_select.GetStringSelection() == lang.getstr("[rgb]TRC")
2317 and ("B2A0" in self.profile.tags or b"A2B0" in self.profile.tags)
2318 )
2319 self.toggle_clut.Enable(
2320 self.profile.connectionColorSpace != b"RGB"
2321 and self.plot_mode_select.GetStringSelection() == lang.getstr("[rgb]TRC")
2322 and isinstance(self.profile.tags.get("rTRC"), CurveType)
2323 and isinstance(self.profile.tags.get("gTRC"), CurveType)
2324 and isinstance(self.profile.tags.get("bTRC"), CurveType)
2325 )
2326 self.save_plot_btn.Enable(bool(curves))
2327 if hasattr(self, "reload_vcgt_btn"):
2328 self.reload_vcgt_btn.Enable(
2329 self.plot_mode_select.GetStringSelection() == lang.getstr("vcgt")
2330 and bool(self.profile)
2331 )
2332 self.reload_vcgt_btn.Show(
2333 self.plot_mode_select.GetStringSelection() == lang.getstr("vcgt")
2334 )
2335 if hasattr(self, "apply_bpc_btn"):
2336 enable_bpc = (
2337 self.plot_mode_select.GetStringSelection() == lang.getstr("vcgt")
2338 and bool(self.profile)
2339 and isinstance(self.profile.tags.get("vcgt"), VideoCardGammaType)
2340 )
2341 if enable_bpc:
2342 values = self.profile.tags.vcgt.getNormalizedValues()
2343 self.apply_bpc_btn.Enable(enable_bpc and values[0] != (0, 0, 0))
2344 self.apply_bpc_btn.Show(
2345 self.plot_mode_select.GetStringSelection() == lang.getstr("vcgt")
2346 )
2347 if hasattr(self, "install_vcgt_btn"):
2348 self.install_vcgt_btn.Enable(
2349 self.plot_mode_select.GetStringSelection() == lang.getstr("vcgt")
2350 and bool(self.profile)
2351 and isinstance(self.profile.tags.get("vcgt"), VideoCardGammaType)
2352 )
2353 self.install_vcgt_btn.Show(
2354 self.plot_mode_select.GetStringSelection() == lang.getstr("vcgt")
2355 )
2356 if hasattr(self, "save_vcgt_btn"):
2357 self.save_vcgt_btn.Enable(
2358 self.plot_mode_select.GetStringSelection() == lang.getstr("vcgt")
2359 and bool(self.profile)
2360 and isinstance(self.profile.tags.get("vcgt"), VideoCardGammaType)
2361 )
2362 self.save_vcgt_btn.Show(
2363 self.plot_mode_select.GetStringSelection() == lang.getstr("vcgt")
2364 )
2365 if hasattr(self, "show_actual_lut_cb"):
2366 self.show_actual_lut_cb.Show(
2367 self.plot_mode_select.GetStringSelection() == lang.getstr("vcgt")
2368 )
2369 if hasattr(self, "rendering_intent_select"):
2370 self.rendering_intent_select.Show(
2371 self.plot_mode_select.GetStringSelection() == lang.getstr("[rgb]TRC")
2372 and self.profile.connectionColorSpace != b"RGB"
2373 )
2374 if hasattr(self, "direction_select"):
2375 self.direction_select.Show(
2376 self.rendering_intent_select.IsShown()
2377 and "B2A0" in self.profile.tags
2378 and "A2B0" in self.profile.tags
2379 )
2380 self.show_as_L.GetContainingSizer().Layout()
2381 if hasattr(self, "cbox_sizer"):
2382 self.cbox_sizer.Layout()
2383 if hasattr(self, "box_sizer"):
2384 self.box_sizer.Layout()
2385 if self.client.last_PointLabel is not None:
2386 self.client._drawPointLabel(self.client.last_PointLabel) # erase old
2387 self.client.last_PointLabel = None
2388 channels = {}
2389 for channel, toggle in enumerate(self.toggles):
2390 channels[channel] = (
2391 toggle.IsShown() and toggle.GetValue() and toggle.Label
2392 ) or ""
2393 wx.CallAfter(
2394 self.client.DrawLUT,
2395 curves,
2396 xLabel=self.xLabel,
2397 yLabel=self.yLabel,
2398 channels=channels,
2399 colorspace=curves_colorspace,
2400 connection_colorspace=connection_colorspace,
2401 )
2402 self.Thaw()
2403
2404 def OnClose(self, event):
2405 """Handle the window close event.
2406
2407 Args:
2408 event (wx.CloseEvent): The close event.
2409 """
2410 self.listening = False
2411 if self.worker.tempdir and os.path.isdir(self.worker.tempdir):
2412 self.worker.wrapup(False)
2413 config.writecfg(
2414 module="curve-viewer",
2415 options=("display.number", "position.lut_viewer", "size.lut_viewer"),
2416 )
2417 # Hide first (looks nicer)
2418 self.Hide()
2419 # Need to use CallAfter to prevent hang under Windows if minimized
2420 wx.CallAfter(self.Destroy)
2421
2422 def OnMotion(self, event):
2423 """Handle mouse motion events.
2424
2425 Args:
2426 event (wx.MouseEvent): The mouse motion event.
2427 """
2428 if not isinstance(event, wx.MouseEvent):
2429 return
2430 if not event.LeftIsDown():
2431 self.UpdatePointLabel(self.client._getXY(event))
2432 else:
2433 self.client.erase_pointlabel()
2434 event.Skip() # Go to next handler
2435
2436 def OnMove(self, event=None):
2437 """Handle window move events.
2438
2439 Args:
2440 event (wx.MoveEvent, optional): The move event. Defaults to None.
2441 """
2442 if self.IsShownOnScreen() and not self.IsMaximized() and not self.IsIconized():
2443 x, y = self.GetScreenPosition()
2444 setcfg("position.lut_viewer.x", x)
2445 setcfg("position.lut_viewer.y", y)
2446 if event:
2447 event.Skip()
2448
2449 def OnSize(self, event=None):
2450 """Handle window size changes.
2451
2452 Args:
2453 event (wx.SizeEvent, optional): The size event. Defaults to None.
2454 """
2455 if self.IsShownOnScreen() and not self.IsMaximized() and not self.IsIconized():
2456 w, h = self.ClientSize
2457 setcfg("size.lut_viewer.w", w)
2458 setcfg("size.lut_viewer.h", h)
2459 if event:
2460 event.Skip()
2461 if sys.platform == "win32":
2462 # Needed under Windows when using double buffering
2463 self.Refresh()
2464
2465 def OnWheel(self, event):
2466 """Handle mouse wheel events for zooming.
2467
2468 Args:
2469 event (wx.MouseEvent): The mouse wheel event.
2470 """
2471 _xy = wx.GetMousePosition()
2472 if self.client.last_draw:
2473 direction = 1.0 if event.WheelRotation < 0 else -1.0
2474 self.client.zoom(direction)
2475
2476 def SaveFile(self, event=None):
2477 """Save the file to the type specified in the extension.
2478
2479 If no file name is specified a dialog box is provided. Returns True if
2480 sucessful, otherwise False.
2481
2482 .bmp Save a Windows bitmap file.
2483 .xbm Save an X bitmap file.
2484 .xpm Save an XPM bitmap file.
2485 .png Save a Portable Network Graphics file.
2486 .jpg Save a Joint Photographic Experts Group file.
2487 """
2488 fileName = " ".join(
2489 [
2490 self.plot_mode_select.GetStringSelection(),
2491 os.path.basename(
2492 os.path.splitext(self.profile.filename or lang.getstr("unnamed"))[0]
2493 ),
2494 ]
2495 )
2496 if (
2497 event
2498 and hasattr(self, "save_vcgt_btn")
2499 and event.GetId() == self.save_vcgt_btn.GetId()
2500 ):
2501 extensions = {"cal": 1}
2502 defType = "cal"
2503 else:
2504 extensions = {
2505 "bmp": wx.BITMAP_TYPE_BMP, # Save a Windows bitmap file.
2506 "xbm": wx.BITMAP_TYPE_XBM, # Save an X bitmap file.
2507 "xpm": wx.BITMAP_TYPE_XPM, # Save an XPM bitmap file.
2508 "jpg": wx.BITMAP_TYPE_JPEG, # Save a JPG file.
2509 "png": wx.BITMAP_TYPE_PNG, # Save a PNG file.
2510 }
2511 defType = "png"
2512
2513 fileName = f"{fileName}.{defType}"
2514
2515 fType = None
2516 dlg1 = None
2517 while fType not in extensions:
2518 if dlg1: # FileDialog exists: Check for extension
2519 InfoDialog(
2520 self,
2521 msg=lang.getstr("error.file_type_unsupported"),
2522 ok=lang.getstr("ok"),
2523 bitmap=get_icon(32, "dialog-error"),
2524 )
2525 else: # FileDialog doesn't exist: just check one
2526 dlg1 = wx.FileDialog(
2527 self,
2528 lang.getstr("save_as"),
2529 get_verified_path("last_filedialog_path")[0],
2530 fileName,
2531 "|".join(
2532 [
2533 f"{ext.upper()} (*.{ext})|*.{ext}"
2534 for ext in sorted(extensions.keys())
2535 ]
2536 ),
2537 wx.SAVE | wx.OVERWRITE_PROMPT,
2538 )
2539 dlg1.SetFilterIndex(sorted(extensions.keys()).index(defType))
2540
2541 if dlg1.ShowModal() == wx.ID_OK:
2542 fileName = dlg1.GetPath()
2543 if not waccess(fileName, os.W_OK):
2544 show_result_dialog(
2545 Error(lang.getstr("error.access_denied.write", fileName)), self
2546 )
2547 return None
2548 fType = fileName[-3:].lower()
2549 setcfg("last_filedialog_path", fileName)
2550 else: # exit without saving
2551 dlg1.Destroy()
2552 return False
2553
2554 if dlg1:
2555 dlg1.Destroy()
2556
2557 # Save Bitmap
2558 if (
2559 event
2560 and hasattr(self, "save_vcgt_btn")
2561 and event.GetId() == self.save_vcgt_btn.GetId()
2562 ):
2563 res = vcgt_to_cal(self.profile)
2564 res.write(fileName)
2565 else:
2566 res = self.client._Buffer.SaveFile(fileName, extensions.get(fType, ".png"))
2567 return res
2568
2569 def SetStatusText(self, text):
2570 """Set the text for the status label.
2571
2572 Args:
2573 text (str): The text to display in the status label.
2574 """
2575 self.status.Label = text
2576 self.status.Refresh()
2577
2578 def SetGamutStatusText(self, text):
2579 """Set the text for the gamut status label.
2580
2581 Args:
2582 text (str): The text to display in the gamut status label.
2583 """
2584 self.gamut_status.Label = text
2585 self.status.Refresh()
2586
2587 def UpdatePointLabel(self, xy):
2588 """Update point label with the closest point information.
2589
2590 Args:
2591 xy (tuple): The x and y coordinates of the point to label.
2592 """
2593 if not self.client.GetEnablePointLabel():
2594 return
2595 # Show closest point (when enbled)
2596 # Make up dict with info for the point label
2597 dlst = self.client.GetClosestPoint(xy, pointScaled=True)
2598 if dlst == [] or not hasattr(self.client, "point_grid"):
2599 return
2600 curveNum, legend, pIndex, pointXY, scaledXY, distance = dlst
2601 legend = legend.split(", ")
2602 channels = {}
2603 value = []
2604 for channel in self.client.point_grid:
2605 toggle = self.toggles[channel]
2606 channels[channel] = toggle.Label or ""
2607 x = round(pointXY[0] / 255.0 * 4095)
2608 v = self.client.point_grid[channel].get(x, 0)
2609 if toggle.Label in ("a*", "b*"):
2610 v = -128 + v / 100.0 * (255 + 255 / 256.0)
2611 value.append((toggle.Label, v))
2612 identical = len(value) > 1 and all(v[1] == value[0][1] for v in value)
2613 if True:
2614 joiner = " \u2192 "
2615 label = [_f for _f in list(channels.values()) if _f]
2616 if (
2617 self.plot_mode_select.GetStringSelection() == lang.getstr("[rgb]TRC")
2618 and self.profile.connectionColorSpace != b"RGB"
2619 ):
2620 if self.show_as_L.GetValue():
2621 format_ = "L* %.2f", "%s %.2f"
2622 else:
2623 format_ = "Y %.4f", "%s %.2f"
2624 axis_y = 100.0
2625 elif "L*" in label and ("a*" in label or "b*" in label):
2626 a = b = -128 + pointXY[0] / 100.0 * (255 + 255 / 256.0)
2627 if label == ["L*", "a*", "b*"]:
2628 format_ = f"L* %.2f a* {a:.2f} b* {b:.2f}", "%s %.2f"
2629 elif label == ["L*", "a*"]:
2630 format_ = f"L* %.2f a* {a:.2f}", "%s %.2f"
2631 elif label == ["L*", "b*"]:
2632 format_ = f"L* %.2f b* {b:.2f}", "%s %.2f"
2633 axis_y = self.client.axis_y[1]
2634 else:
2635 format_ = "{} %.2f".format("=".join(label)), "%s %.2f"
2636 axis_y = self.client.axis_y[1]
2637 if identical:
2638 # if value[0][1] is None:
2639 vout = pointXY[1]
2640 if "L*" not in label and ("a*" in label or "b*" in label):
2641 vout = -128 + vout / 100.0 * (255 + 255 / 256.0)
2642 RGB = " ".join(["=".join(label), f"{vout:.2f}"])
2643 # else:
2644 # RGB = "R=G=B %.2f" % value[0][1]
2645 else:
2646 RGB = " ".join(
2647 [
2648 format_[1] % (v, s)
2649 for v, s in [v for v in value if v[1] is not None]
2650 ]
2651 )
2652 vin = pointXY[0]
2653 if "L*" not in label and ("a*" in label or "b*" in label):
2654 vin = -128 + pointXY[0] / 100.0 * (255 + 255 / 256.0)
2655 legend[0] = joiner.join([format_[0] % vin, RGB])
2656 if (
2657 self.plot_mode_select.GetStringSelection() == lang.getstr("[rgb]TRC")
2658 and self.profile.connectionColorSpace != b"RGB"
2659 ):
2660 pointXY = pointXY[1], pointXY[0]
2661 else:
2662 joiner = " \u2192 "
2663 format_ = "{:.2f}", "{:.2f}"
2664 axis_y = self.client.axis_y[1]
2665 legend[0] = "{} {}".format(
2666 legend[0],
2667 joiner.join(
2668 [format_[i].format(point) for i, point in enumerate(pointXY)]
2669 ),
2670 )
2671 if len(legend) == 1:
2672 # Calculate gamma
2673 axis_x = self.client.axis_y[1]
2674 gamma = []
2675 for label, v in value:
2676 if v is None or label in ("a*", "b*"):
2677 continue
2678 if (
2679 self.plot_mode_select.GetStringSelection()
2680 == lang.getstr("[rgb]TRC")
2681 and self.profile.connectionColorSpace != b"RGB"
2682 ):
2683 x = v
2684 y = pointXY[1]
2685 if self.show_as_L.GetValue():
2686 y = colormath.Lab2XYZ(y, 0, 0)[1] * 100
2687 else:
2688 x = pointXY[0]
2689 y = v
2690 if x <= 0 or x >= axis_x or y <= 0 or y >= axis_y:
2691 continue
2692 if identical:
2693 label = "=".join(
2694 [
2695 f"{s}"
2696 for s, v in [s_v for s_v in value if s_v[1] is not None]
2697 ]
2698 )
2699 # Note: We need to make sure each point is a float because it
2700 # might be a decimal.Decimal, which can't be divided by floats!
2701 gamma.append(
2702 "{} {:.2f}".format(
2703 label,
2704 round(
2705 math.log(float(y) / axis_y) / math.log(x / axis_x),
2706 2,
2707 ),
2708 )
2709 )
2710 if "=" in label:
2711 break
2712 if gamma:
2713 legend.append("Gamma {}".format(" ".join(gamma)))
2714 if self.profile.connectionColorSpace != b"RGB":
2715 self.add_tone_values(legend)
2716 legend = [", ".join(legend[:-1]), legend[-1]]
2717 self.SetStatusText("\n".join(legend))
2718 # Make up dictionary to pass to DrawPointLabel
2719 mDataDict = {
2720 "curveNum": curveNum,
2721 "legend": legend,
2722 "pIndex": pIndex,
2723 "pointXY": pointXY,
2724 "scaledXY": scaledXY,
2725 }
2726 # Pass dict to update the point label
2727 self.client.UpdatePointLabel(mDataDict)
2728
2729 def update_controls(self):
2730 """Update the controls based on the current state of the worker."""
2731 self.show_actual_lut_cb.Enable(
2732 (
2733 self.worker.argyll_version[0:3] > [1, 1, 0]
2734 or (
2735 self.worker.argyll_version[0:3] == [1, 1, 0]
2736 and "Beta" not in self.worker.argyll_version_string
2737 )
2738 )
2739 and not config.is_untethered_display()
2740 )
2741 self.show_actual_lut_cb.SetValue(
2742 bool(getcfg("lut_viewer.show_actual_lut"))
2743 and not config.is_untethered_display()
2744 )
2745
2746 @property
2747 def worker(self):
2748 """Get the worker instance for the LUT viewer.
2749
2750 Returns:
2751 Worker: The worker instance.
2752 """
2753 return self.client.worker
2754
2755 def display_changed(self, event):
2756 """Handle display change events.
2757
2758 Args:
2759 event (wx.Event): The display change event.
2760 """
2761 self.worker.enumerate_displays_and_ports(
2762 check_lut_access=False, enumerate_ports=False, include_network_devices=False
2763 )
2764
2765
2766 def main():
2767 """Main function to run the LUT viewer application."""
2768 config.initcfg("curve-viewer")
2769 # Backup display config
2770 _cfg_display = getcfg("display.number")
2771 lang.init()
2772 lang.update_defaults()
2773 app = BaseApp(0)
2774 app.TopWindow = LUTFrame(None, -1)
2775 app.TopWindow.Bind(wx.EVT_CLOSE, app.TopWindow.OnClose, app.TopWindow)
2776 if sys.platform == "darwin":
2777 app.TopWindow.init_menubar()
2778 wx.CallLater(1, _main, app)
2779 app.MainLoop()
2780
2781
2782 def _main(app):
2783 app.TopWindow.listen()
2784 app.TopWindow.display_changed(None)
2785 app.TopWindow.Bind(wx.EVT_DISPLAY_CHANGED, app.TopWindow.display_changed)
2786 app.TopWindow.display_no, geometry, client_area = app.TopWindow.get_display()
2787 app.TopWindow.Bind(wx.EVT_MOVE, app.TopWindow.move_handler, app.TopWindow)
2788 display_no = get_argyll_display_number(geometry)
2789 if display_no is not None:
2790 setcfg("display.number", display_no + 1)
2791 app.TopWindow.update_controls()
2792 for arg in sys.argv[1:]:
2793 if os.path.isfile(arg):
2794 app.TopWindow.drop_handler(os.path.abspath(arg))
2795 break
2796 else:
2797 app.TopWindow.load_lut(get_display_profile(display_no))
2798 app.TopWindow.Show()
2799
2800
2801 if __name__ == "__main__":
2802 main()