You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

273 lines
8.6 KiB

29 years ago
29 years ago
29 years ago
29 years ago
28 years ago
29 years ago
Merged revisions 60151-60159,60161-60168,60170,60172-60173,60175 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r60151 | christian.heimes | 2008-01-21 14:11:15 +0100 (Mon, 21 Jan 2008) | 1 line A bunch of header files were not listed as dependencies for object files. Changes to files like Parser/parser.h weren't picked up by make. ........ r60152 | georg.brandl | 2008-01-21 15:16:46 +0100 (Mon, 21 Jan 2008) | 3 lines #1087741: make mmap.mmap the type of mmap objects, not a factory function. Allow it to be subclassed. ........ r60153 | georg.brandl | 2008-01-21 15:18:14 +0100 (Mon, 21 Jan 2008) | 2 lines mmap is an extension module. ........ r60154 | georg.brandl | 2008-01-21 17:28:13 +0100 (Mon, 21 Jan 2008) | 2 lines Fix example. ........ r60155 | georg.brandl | 2008-01-21 17:34:07 +0100 (Mon, 21 Jan 2008) | 2 lines #1555501: document plistlib and move it to the general library. ........ r60156 | georg.brandl | 2008-01-21 17:36:00 +0100 (Mon, 21 Jan 2008) | 2 lines Add a stub for bundlebuilder documentation. ........ r60157 | georg.brandl | 2008-01-21 17:46:58 +0100 (Mon, 21 Jan 2008) | 2 lines Removing bundlebuilder docs again -- it's not to be used anymore (see #779825). ........ r60158 | georg.brandl | 2008-01-21 17:51:51 +0100 (Mon, 21 Jan 2008) | 2 lines #997912: acknowledge nested scopes in tutorial. ........ r60159 | vinay.sajip | 2008-01-21 18:02:26 +0100 (Mon, 21 Jan 2008) | 1 line Fix: #1836: Off-by-one bug in TimedRotatingFileHandler rollover calculation. Patch thanks to Kathryn M. Kowalski. ........ r60161 | georg.brandl | 2008-01-21 18:13:03 +0100 (Mon, 21 Jan 2008) | 2 lines Adapt pydoc to new doc URLs. ........ r60162 | georg.brandl | 2008-01-21 18:17:00 +0100 (Mon, 21 Jan 2008) | 2 lines Fix old link. ........ r60163 | georg.brandl | 2008-01-21 18:22:06 +0100 (Mon, 21 Jan 2008) | 2 lines #1726198: replace while 1: fp.readline() with file iteration. ........ r60164 | georg.brandl | 2008-01-21 18:29:23 +0100 (Mon, 21 Jan 2008) | 2 lines Clarify $ behavior in re docstring. #1631394. ........ r60165 | vinay.sajip | 2008-01-21 18:39:22 +0100 (Mon, 21 Jan 2008) | 1 line Minor documentation change - hyperlink tidied up. ........ r60166 | georg.brandl | 2008-01-21 18:42:40 +0100 (Mon, 21 Jan 2008) | 2 lines #1530959: change distutils build dir for --with-pydebug python builds. ........ r60167 | vinay.sajip | 2008-01-21 19:16:05 +0100 (Mon, 21 Jan 2008) | 1 line Updated to include news on recent logging fixes and documentation changes. ........ r60168 | georg.brandl | 2008-01-21 19:35:49 +0100 (Mon, 21 Jan 2008) | 3 lines Issue #1882: when compiling code from a string, encoding cookies in the second line of code were not always recognized correctly. ........ r60170 | georg.brandl | 2008-01-21 19:36:51 +0100 (Mon, 21 Jan 2008) | 2 lines Add NEWS entry for #1882. ........ r60172 | georg.brandl | 2008-01-21 19:41:24 +0100 (Mon, 21 Jan 2008) | 2 lines Use original location of document, which has translations. ........ r60173 | walter.doerwald | 2008-01-21 21:18:04 +0100 (Mon, 21 Jan 2008) | 2 lines Follow PEP 8 in module docstring. ........ r60175 | georg.brandl | 2008-01-21 21:20:53 +0100 (Mon, 21 Jan 2008) | 2 lines Adapt to latest doctools refactoring. ........
19 years ago
29 years ago
29 years ago
29 years ago
29 years ago
29 years ago
29 years ago
29 years ago
29 years ago
29 years ago
29 years ago
28 years ago
29 years ago
29 years ago
28 years ago
28 years ago
29 years ago
29 years ago
  1. """Color Database.
  2. This file contains one class, called ColorDB, and several utility functions.
  3. The class must be instantiated by the get_colordb() function in this file,
  4. passing it a filename to read a database out of.
  5. The get_colordb() function will try to examine the file to figure out what the
  6. format of the file is. If it can't figure out the file format, or it has
  7. trouble reading the file, None is returned. You can pass get_colordb() an
  8. optional filetype argument.
  9. Supporte file types are:
  10. X_RGB_TXT -- X Consortium rgb.txt format files. Three columns of numbers
  11. from 0 .. 255 separated by whitespace. Arbitrary trailing
  12. columns used as the color name.
  13. The utility functions are useful for converting between the various expected
  14. color formats, and for calculating other color values.
  15. """
  16. import sys
  17. import re
  18. from types import *
  19. import operator
  20. class BadColor(Exception):
  21. pass
  22. DEFAULT_DB = None
  23. SPACE = ' '
  24. COMMASPACE = ', '
  25. # generic class
  26. class ColorDB:
  27. def __init__(self, fp):
  28. lineno = 2
  29. self.__name = fp.name
  30. # Maintain several dictionaries for indexing into the color database.
  31. # Note that while Tk supports RGB intensities of 4, 8, 12, or 16 bits,
  32. # for now we only support 8 bit intensities. At least on OpenWindows,
  33. # all intensities in the /usr/openwin/lib/rgb.txt file are 8-bit
  34. #
  35. # key is (red, green, blue) tuple, value is (name, [aliases])
  36. self.__byrgb = {}
  37. # key is name, value is (red, green, blue)
  38. self.__byname = {}
  39. # all unique names (non-aliases). built-on demand
  40. self.__allnames = None
  41. for line in fp:
  42. # get this compiled regular expression from derived class
  43. mo = self._re.match(line)
  44. if not mo:
  45. print('Error in', fp.name, ' line', lineno, file=sys.stderr)
  46. lineno += 1
  47. continue
  48. # extract the red, green, blue, and name
  49. red, green, blue = self._extractrgb(mo)
  50. name = self._extractname(mo)
  51. keyname = name.lower()
  52. # BAW: for now the `name' is just the first named color with the
  53. # rgb values we find. Later, we might want to make the two word
  54. # version the `name', or the CapitalizedVersion, etc.
  55. key = (red, green, blue)
  56. foundname, aliases = self.__byrgb.get(key, (name, []))
  57. if foundname != name and foundname not in aliases:
  58. aliases.append(name)
  59. self.__byrgb[key] = (foundname, aliases)
  60. # add to byname lookup
  61. self.__byname[keyname] = key
  62. lineno = lineno + 1
  63. # override in derived classes
  64. def _extractrgb(self, mo):
  65. return [int(x) for x in mo.group('red', 'green', 'blue')]
  66. def _extractname(self, mo):
  67. return mo.group('name')
  68. def filename(self):
  69. return self.__name
  70. def find_byrgb(self, rgbtuple):
  71. """Return name for rgbtuple"""
  72. try:
  73. return self.__byrgb[rgbtuple]
  74. except KeyError:
  75. raise BadColor(rgbtuple)
  76. def find_byname(self, name):
  77. """Return (red, green, blue) for name"""
  78. name = name.lower()
  79. try:
  80. return self.__byname[name]
  81. except KeyError:
  82. raise BadColor(name)
  83. def nearest(self, red, green, blue):
  84. """Return the name of color nearest (red, green, blue)"""
  85. # BAW: should we use Voronoi diagrams, Delaunay triangulation, or
  86. # octree for speeding up the locating of nearest point? Exhaustive
  87. # search is inefficient, but seems fast enough.
  88. nearest = -1
  89. nearest_name = ''
  90. for name, aliases in self.__byrgb.values():
  91. r, g, b = self.__byname[name.lower()]
  92. rdelta = red - r
  93. gdelta = green - g
  94. bdelta = blue - b
  95. distance = rdelta * rdelta + gdelta * gdelta + bdelta * bdelta
  96. if nearest == -1 or distance < nearest:
  97. nearest = distance
  98. nearest_name = name
  99. return nearest_name
  100. def unique_names(self):
  101. # sorted
  102. if not self.__allnames:
  103. self.__allnames = []
  104. for name, aliases in self.__byrgb.values():
  105. self.__allnames.append(name)
  106. self.__allnames.sort(key=str.lower)
  107. return self.__allnames
  108. def aliases_of(self, red, green, blue):
  109. try:
  110. name, aliases = self.__byrgb[(red, green, blue)]
  111. except KeyError:
  112. raise BadColor((red, green, blue))
  113. return [name] + aliases
  114. class RGBColorDB(ColorDB):
  115. _re = re.compile(
  116. '\s*(?P<red>\d+)\s+(?P<green>\d+)\s+(?P<blue>\d+)\s+(?P<name>.*)')
  117. class HTML40DB(ColorDB):
  118. _re = re.compile('(?P<name>\S+)\s+(?P<hexrgb>#[0-9a-fA-F]{6})')
  119. def _extractrgb(self, mo):
  120. return rrggbb_to_triplet(mo.group('hexrgb'))
  121. class LightlinkDB(HTML40DB):
  122. _re = re.compile('(?P<name>(.+))\s+(?P<hexrgb>#[0-9a-fA-F]{6})')
  123. def _extractname(self, mo):
  124. return mo.group('name').strip()
  125. class WebsafeDB(ColorDB):
  126. _re = re.compile('(?P<hexrgb>#[0-9a-fA-F]{6})')
  127. def _extractrgb(self, mo):
  128. return rrggbb_to_triplet(mo.group('hexrgb'))
  129. def _extractname(self, mo):
  130. return mo.group('hexrgb').upper()
  131. # format is a tuple (RE, SCANLINES, CLASS) where RE is a compiled regular
  132. # expression, SCANLINES is the number of header lines to scan, and CLASS is
  133. # the class to instantiate if a match is found
  134. FILETYPES = [
  135. (re.compile('Xorg'), RGBColorDB),
  136. (re.compile('XConsortium'), RGBColorDB),
  137. (re.compile('HTML'), HTML40DB),
  138. (re.compile('lightlink'), LightlinkDB),
  139. (re.compile('Websafe'), WebsafeDB),
  140. ]
  141. def get_colordb(file, filetype=None):
  142. colordb = None
  143. fp = open(file)
  144. try:
  145. line = fp.readline()
  146. if not line:
  147. return None
  148. # try to determine the type of RGB file it is
  149. if filetype is None:
  150. filetypes = FILETYPES
  151. else:
  152. filetypes = [filetype]
  153. for typere, class_ in filetypes:
  154. mo = typere.search(line)
  155. if mo:
  156. break
  157. else:
  158. # no matching type
  159. return None
  160. # we know the type and the class to grok the type, so suck it in
  161. colordb = class_(fp)
  162. finally:
  163. fp.close()
  164. # save a global copy
  165. global DEFAULT_DB
  166. DEFAULT_DB = colordb
  167. return colordb
  168. _namedict = {}
  169. def rrggbb_to_triplet(color):
  170. """Converts a #rrggbb color to the tuple (red, green, blue)."""
  171. rgbtuple = _namedict.get(color)
  172. if rgbtuple is None:
  173. if color[0] != '#':
  174. raise BadColor(color)
  175. red = color[1:3]
  176. green = color[3:5]
  177. blue = color[5:7]
  178. rgbtuple = int(red, 16), int(green, 16), int(blue, 16)
  179. _namedict[color] = rgbtuple
  180. return rgbtuple
  181. _tripdict = {}
  182. def triplet_to_rrggbb(rgbtuple):
  183. """Converts a (red, green, blue) tuple to #rrggbb."""
  184. global _tripdict
  185. hexname = _tripdict.get(rgbtuple)
  186. if hexname is None:
  187. hexname = '#%02x%02x%02x' % rgbtuple
  188. _tripdict[rgbtuple] = hexname
  189. return hexname
  190. _maxtuple = (256.0,) * 3
  191. def triplet_to_fractional_rgb(rgbtuple):
  192. return list(map(operator.__div__, rgbtuple, _maxtuple))
  193. def triplet_to_brightness(rgbtuple):
  194. # return the brightness (grey level) along the scale 0.0==black to
  195. # 1.0==white
  196. r = 0.299
  197. g = 0.587
  198. b = 0.114
  199. return r*rgbtuple[0] + g*rgbtuple[1] + b*rgbtuple[2]
  200. if __name__ == '__main__':
  201. colordb = get_colordb('/usr/openwin/lib/rgb.txt')
  202. if not colordb:
  203. print('No parseable color database found')
  204. sys.exit(1)
  205. # on my system, this color matches exactly
  206. target = 'navy'
  207. red, green, blue = rgbtuple = colordb.find_byname(target)
  208. print(target, ':', red, green, blue, triplet_to_rrggbb(rgbtuple))
  209. name, aliases = colordb.find_byrgb(rgbtuple)
  210. print('name:', name, 'aliases:', COMMASPACE.join(aliases))
  211. r, g, b = (1, 1, 128) # nearest to navy
  212. r, g, b = (145, 238, 144) # nearest to lightgreen
  213. r, g, b = (255, 251, 250) # snow
  214. print('finding nearest to', target, '...')
  215. import time
  216. t0 = time.time()
  217. nearest = colordb.nearest(r, g, b)
  218. t1 = time.time()
  219. print('found nearest color', nearest, 'in', t1-t0, 'seconds')
  220. # dump the database
  221. for n in colordb.unique_names():
  222. r, g, b = colordb.find_byname(n)
  223. aliases = colordb.aliases_of(r, g, b)
  224. print('%20s: (%3d/%3d/%3d) == %s' % (n, r, g, b,
  225. SPACE.join(aliases[1:])))