Debian Codegraph @

07p/python/auto/graphics/PmwColor.py

raw symbols SCIP
1 # Functions for converting colors and modifying the color scheme of
2 # an application.
3
4 import math
5 import sys
6 try:
7 import Tkinter
8 except ImportError:
9 import tkinter as Tkinter # Python 3
10
11 _PI = math.pi
12 _TWO_PI = _PI * 2
13 _THIRD_PI = _PI / 3
14 _SIXTH_PI = _PI / 6
15 _MAX_RGB = float(256 * 256 - 1) # max size of rgb values returned from Tk
16
17 def setscheme(root, background=None, **kw):
18 root = root._root()
19 palette = _calcPalette(root, background,**kw)
20 for option, value in palette.items():
21 root.option_add('*' + option, value, 'widgetDefault')
22
23 def getdefaultpalette(root):
24 # Return the default values of all options, using the defaults
25 # from a few widgets.
26
27 ckbtn = Tkinter.Checkbutton(root)
28 entry = Tkinter.Entry(root)
29 scbar = Tkinter.Scrollbar(root)
30
31 orig = {}
32 orig['activeBackground'] = str(ckbtn.configure('activebackground')[4])
33 orig['activeForeground'] = str(ckbtn.configure('activeforeground')[4])
34 orig['background'] = str(ckbtn.configure('background')[4])
35 orig['disabledForeground'] = str(ckbtn.configure('disabledforeground')[4])
36 orig['foreground'] = str(ckbtn.configure('foreground')[4])
37 orig['highlightBackground'] = str(ckbtn.configure('highlightbackground')[4])
38 orig['highlightColor'] = str(ckbtn.configure('highlightcolor')[4])
39 orig['insertBackground'] = str(entry.configure('insertbackground')[4])
40 orig['selectColor'] = str(ckbtn.configure('selectcolor')[4])
41 orig['selectBackground'] = str(entry.configure('selectbackground')[4])
42 orig['selectForeground'] = str(entry.configure('selectforeground')[4])
43 orig['troughColor'] = str(scbar.configure('troughcolor')[4])
44
45 ckbtn.destroy()
46 entry.destroy()
47 scbar.destroy()
48
49 return orig
50
51 #======================================================================
52
53 # Functions dealing with brightness, hue, saturation and intensity of colors.
54
55 def changebrightness(root, colorName, brightness):
56 # Convert the color name into its hue and back into a color of the
57 # required brightness.
58
59 rgb = name2rgb(root, colorName)
60 hue, saturation, intensity = rgb2hsi(rgb)
61 if saturation == 0.0:
62 hue = None
63 return hue2name(hue, brightness)
64
65 def hue2name(hue, brightness = None):
66 # Convert the requested hue and brightness into a color name. If
67 # hue is None, return a grey of the requested brightness.
68
69 if hue is None:
70 rgb = hsi2rgb(0.0, 0.0, brightness)
71 else:
72 while hue < 0:
73 hue = hue + _TWO_PI
74 while hue >= _TWO_PI:
75 hue = hue - _TWO_PI
76
77 rgb = hsi2rgb(hue, 1.0, 1.0)
78 if brightness is not None:
79 b = rgb2brightness(rgb)
80 i = 1.0 - (1.0 - brightness) * b
81 s = bhi2saturation(brightness, hue, i)
82 rgb = hsi2rgb(hue, s, i)
83
84 return rgb2name(rgb)
85
86 def bhi2saturation(brightness, hue, intensity):
87 while hue < 0:
88 hue = hue + _TWO_PI
89 while hue >= _TWO_PI:
90 hue = hue - _TWO_PI
91 hue = hue / _THIRD_PI
92 f = hue - math.floor(hue)
93
94 pp = intensity
95 pq = intensity * f
96 pt = intensity - intensity * f
97 pv = 0
98
99 hue = int(hue)
100 if hue == 0: rgb = (pv, pt, pp)
101 elif hue == 1: rgb = (pq, pv, pp)
102 elif hue == 2: rgb = (pp, pv, pt)
103 elif hue == 3: rgb = (pp, pq, pv)
104 elif hue == 4: rgb = (pt, pp, pv)
105 elif hue == 5: rgb = (pv, pp, pq)
106
107 return (intensity - brightness) / rgb2brightness(rgb)
108
109 def hsi2rgb(hue, saturation, intensity):
110 i = intensity
111 if saturation == 0:
112 rgb = [i, i, i]
113 else:
114 while hue < 0:
115 hue = hue + _TWO_PI
116 while hue >= _TWO_PI:
117 hue = hue - _TWO_PI
118 hue = hue / _THIRD_PI
119 f = hue - math.floor(hue)
120 p = i * (1.0 - saturation)
121 q = i * (1.0 - saturation * f)
122 t = i * (1.0 - saturation * (1.0 - f))
123
124 hue = int(hue)
125 if hue == 0: rgb = [i, t, p]
126 elif hue == 1: rgb = [q, i, p]
127 elif hue == 2: rgb = [p, i, t]
128 elif hue == 3: rgb = [p, q, i]
129 elif hue == 4: rgb = [t, p, i]
130 elif hue == 5: rgb = [i, p, q]
131
132 for index in range(3):
133 val = rgb[index]
134 if val < 0.0:
135 val = 0.0
136 if val > 1.0:
137 val = 1.0
138 rgb[index] = val
139
140 return rgb
141
142 def average(rgb1, rgb2, fraction):
143 return (
144 rgb2[0] * fraction + rgb1[0] * (1.0 - fraction),
145 rgb2[1] * fraction + rgb1[1] * (1.0 - fraction),
146 rgb2[2] * fraction + rgb1[2] * (1.0 - fraction)
147 )
148
149 def rgb2name(rgb):
150 return '#%02x%02x%02x' % \
151 (int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255))
152
153 def rgb2brightness(rgb):
154 # Return the perceived grey level of the color
155 # (0.0 == black, 1.0 == white).
156
157 rf = 0.299
158 gf = 0.587
159 bf = 0.114
160 return rf * rgb[0] + gf * rgb[1] + bf * rgb[2]
161
162 def rgb2hsi(rgb):
163 maxc = max(rgb[0], rgb[1], rgb[2])
164 minc = min(rgb[0], rgb[1], rgb[2])
165
166 intensity = maxc
167 if maxc != 0:
168 saturation = (maxc - minc) / maxc
169 else:
170 saturation = 0.0
171
172 hue = 0.0
173 if saturation != 0.0:
174 c = []
175 for index in range(3):
176 c.append((maxc - rgb[index]) / (maxc - minc))
177
178 if rgb[0] == maxc:
179 hue = c[2] - c[1]
180 elif rgb[1] == maxc:
181 hue = 2 + c[0] - c[2]
182 elif rgb[2] == maxc:
183 hue = 4 + c[1] - c[0]
184
185 hue = hue * _THIRD_PI
186 if hue < 0.0:
187 hue = hue + _TWO_PI
188
189 return (hue, saturation, intensity)
190
191 def name2rgb(root, colorName, asInt = 0):
192 if colorName[0] == '#':
193 # Extract rgb information from the color name itself, assuming
194 # it is either #rgb, #rrggbb, #rrrgggbbb, or #rrrrggggbbbb
195 # This is useful, since tk may return incorrect rgb values if
196 # the colormap is full - it will return the rbg values of the
197 # closest color available.
198 colorName = colorName[1:]
199 digits = len(colorName) / 3
200 factor = 16 ** (4 - digits)
201 rgb = (
202 int(colorName[0:digits], 16) * factor,
203 int(colorName[digits:digits * 2], 16) * factor,
204 int(colorName[digits * 2:digits * 3], 16) * factor,
205 )
206 else:
207 # We have no choice but to ask Tk what the rgb values are.
208 rgb = root.winfo_rgb(colorName)
209
210 if not asInt:
211 rgb = (rgb[0] / _MAX_RGB, rgb[1] / _MAX_RGB, rgb[2] / _MAX_RGB)
212 return rgb
213
214 def _calcPalette(root, background=None, **kw):
215 # Create a map that has the complete new palette. If some colors
216 # aren't specified, compute them from other colors that are specified.
217 new = {}
218 for key, value in kw.items():
219 new[key] = value
220 if background is not None:
221 new['background'] = background
222 if 'background' not in new:
223 raise ValueError('must specify a background color')
224
225 if 'foreground' not in new:
226 new['foreground'] = 'black'
227
228 bg = name2rgb(root, new['background'])
229 fg = name2rgb(root, new['foreground'])
230
231 for i in ('activeForeground', 'insertBackground', 'selectForeground',
232 'highlightColor'):
233 if i not in new:
234 new[i] = new['foreground']
235
236 if 'disabledForeground' not in new:
237 newCol = average(bg, fg, 0.3)
238 new['disabledForeground'] = rgb2name(newCol)
239
240 if 'highlightBackground' not in new:
241 new['highlightBackground'] = new['background']
242
243 # Set <lighterBg> to a color that is a little lighter that the
244 # normal background. To do this, round each color component up by
245 # 9% or 1/3 of the way to full white, whichever is greater.
246 lighterBg = []
247 for i in range(3):
248 lighterBg.append(bg[i])
249 inc1 = lighterBg[i] * 0.09
250 inc2 = (1.0 - lighterBg[i]) / 3
251 if inc1 > inc2:
252 lighterBg[i] = lighterBg[i] + inc1
253 else:
254 lighterBg[i] = lighterBg[i] + inc2
255 if lighterBg[i] > 1.0:
256 lighterBg[i] = 1.0
257
258 # Set <darkerBg> to a color that is a little darker that the
259 # normal background.
260 darkerBg = (bg[0] * 0.9, bg[1] * 0.9, bg[2] * 0.9)
261
262 if 'activeBackground' not in new:
263 # If the foreground is dark, pick a light active background.
264 # If the foreground is light, pick a dark active background.
265 # XXX This has been disabled, since it does not look very
266 # good with dark backgrounds. If this is ever fixed, the
267 # selectBackground and troughColor options should also be fixed.
268
269 if rgb2brightness(fg) < 0.5:
270 new['activeBackground'] = rgb2name(lighterBg)
271 else:
272 new['activeBackground'] = rgb2name(lighterBg)
273
274 if 'selectBackground' not in new:
275 new['selectBackground'] = rgb2name(darkerBg)
276 if 'troughColor' not in new:
277 new['troughColor'] = rgb2name(darkerBg)
278 if 'selectColor' not in new:
279 new['selectColor'] = 'yellow'
280
281 return new
282
283 def spectrum(numColors, correction = 1.0, saturation = 1.0, intensity = 1.0,
284 extraOrange = 1, returnHues = 0):
285 colorList = []
286 division = numColors / 7.0
287 for index in range(numColors):
288 if extraOrange:
289 if index < 2 * division:
290 hue = index / division
291 else:
292 hue = 2 + 2 * (index - 2 * division) / division
293 hue = hue * _SIXTH_PI
294 else:
295 hue = index * _TWO_PI / numColors
296 if returnHues:
297 colorList.append(hue)
298 else:
299 rgb = hsi2rgb(hue, saturation, intensity)
300 if correction != 1.0:
301 rgb = correct(rgb, correction)
302 name = rgb2name(rgb)
303 colorList.append(name)
304 return colorList
305
306 def correct(rgb, correction):
307 correction = float(correction)
308 rtn = []
309 for index in range(3):
310 rtn.append((1 - (1 - rgb[index]) ** correction) ** (1 / correction))
311 return rtn
312
313 #==============================================================================
314
315 def _recolorTree(widget, oldpalette, newcolors):
316 # Change the colors in a widget and its descendants.
317
318 # Change the colors in <widget> and all of its descendants,
319 # according to the <newcolors> dictionary. It only modifies
320 # colors that have their default values as specified by the
321 # <oldpalette> variable. The keys of the <newcolors> dictionary
322 # are named after widget configuration options and the values are
323 # the new value for that option.
324
325 for dbOption in newcolors:
326 option = dbOption.lower()
327 try:
328 value = str(widget.cget(option))
329 except:
330 continue
331 if oldpalette is None or value == oldpalette[dbOption]:
332 widget.configure(**{option : newcolors[dbOption]})
333
334 for child in widget.winfo_children():
335 _recolorTree(child, oldpalette, newcolors)
336
337 def changecolor(widget, background=None, **kw):
338 root = widget._root()
339 if not hasattr(widget, '_Pmw_oldpalette'):
340 widget._Pmw_oldpalette = getdefaultpalette(root)
341 newpalette = _calcPalette(root, background, **kw)
342 _recolorTree(widget, widget._Pmw_oldpalette, newpalette)
343 widget._Pmw_oldpalette = newpalette
344
345 def bordercolors(root, colorName):
346 # This is the same method that Tk uses for shadows, in TkpGetShadows.
347
348 lightRGB = []
349 darkRGB = []
350 for value in name2rgb(root, colorName, 1):
351 value40pc = (14 * value) / 10
352 if value40pc > _MAX_RGB:
353 value40pc = _MAX_RGB
354 valueHalfWhite = (_MAX_RGB + value) / 2;
355 lightRGB.append(max(value40pc, valueHalfWhite))
356
357 darkValue = (60 * value) / 100
358 darkRGB.append(darkValue)
359
360 return (
361 '#%04x%04x%04x' % (lightRGB[0], lightRGB[1], lightRGB[2]),
362 '#%04x%04x%04x' % (darkRGB[0], darkRGB[1], darkRGB[2])
363 )