ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/ns_dev/Python/NinoCode/Active_prgs/PmwColor.py
Revision: 8
Committed: Sat May 5 04:21:19 2012 UTC (13 years, 10 months ago) by ninoborges
Content type: text/x-python
File size: 11456 byte(s)
Log Message:
Initial Import

File Contents

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