utils.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. """!
  2. @package core.utils
  3. @brief Misc utilities for wxGUI
  4. (C) 2007-2009, 2011 by the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. @author Martin Landa <landa.martin gmail.com>
  8. @author Jachym Cepicky
  9. """
  10. import os
  11. import sys
  12. import platform
  13. import string
  14. import glob
  15. import shlex
  16. import re
  17. from core.globalvar import ETCDIR
  18. sys.path.append(os.path.join(ETCDIR, "python"))
  19. from grass.script import core as grass
  20. from grass.script import task as gtask
  21. from core.gcmd import RunCommand
  22. from core.debug import Debug
  23. # from core.settings import UserSettings
  24. def normalize_whitespace(text):
  25. """!Remove redundant whitespace from a string"""
  26. return string.join(string.split(text), ' ')
  27. def split(s):
  28. """!Platform spefic shlex.split"""
  29. if sys.version_info >= (2, 6):
  30. return shlex.split(s, posix = (sys.platform != "win32"))
  31. elif sys.platform == "win32":
  32. return shlex.split(s.replace('\\', r'\\'))
  33. else:
  34. return shlex.split(s)
  35. def GetTempfile(pref=None):
  36. """!Creates GRASS temporary file using defined prefix.
  37. @todo Fix path on MS Windows/MSYS
  38. @param pref prefer the given path
  39. @return Path to file name (string) or None
  40. """
  41. ret = RunCommand('g.tempfile',
  42. read = True,
  43. pid = os.getpid())
  44. tempfile = ret.splitlines()[0].strip()
  45. # FIXME
  46. # ugly hack for MSYS (MS Windows)
  47. if platform.system() == 'Windows':
  48. tempfile = tempfile.replace("/", "\\")
  49. try:
  50. path, file = os.path.split(tempfile)
  51. if pref:
  52. return os.path.join(pref, file)
  53. else:
  54. return tempfile
  55. except:
  56. return None
  57. def GetLayerNameFromCmd(dcmd, fullyQualified = False, param = None,
  58. layerType = None):
  59. """!Get map name from GRASS command
  60. Parameter dcmd can be modified when first parameter is not
  61. defined.
  62. @param dcmd GRASS command (given as list)
  63. @param fullyQualified change map name to be fully qualified
  64. @param param params directory
  65. @param layerType check also layer type ('raster', 'vector', '3d-raster', ...)
  66. @return tuple (name, found)
  67. """
  68. mapname = ''
  69. found = True
  70. if len(dcmd) < 1:
  71. return mapname, False
  72. if 'd.grid' == dcmd[0]:
  73. mapname = 'grid'
  74. elif 'd.geodesic' in dcmd[0]:
  75. mapname = 'geodesic'
  76. elif 'd.rhumbline' in dcmd[0]:
  77. mapname = 'rhumb'
  78. else:
  79. params = list()
  80. for idx in range(len(dcmd)):
  81. try:
  82. p, v = dcmd[idx].split('=', 1)
  83. except ValueError:
  84. continue
  85. if p == param:
  86. params = [(idx, p, v)]
  87. break
  88. if p in ('map', 'input', 'layer',
  89. 'red', 'blue', 'green',
  90. 'h_map', 's_map', 'i_map',
  91. 'reliefmap', 'labels'):
  92. params.append((idx, p, v))
  93. if len(params) < 1:
  94. if len(dcmd) > 1:
  95. i = 1
  96. while i < len(dcmd):
  97. if '=' not in dcmd[i] and not dcmd[i].startswith('-'):
  98. task = gtask.parse_interface(dcmd[0])
  99. # this expects the first parameter to be the right one
  100. p = task.get_options()['params'][0].get('name', '')
  101. params.append((i, p, dcmd[i]))
  102. break
  103. i += 1
  104. else:
  105. return mapname, False
  106. if len(params) < 1:
  107. return mapname, False
  108. mapname = params[0][2]
  109. mapset = ''
  110. if fullyQualified and '@' not in mapname:
  111. if layerType in ('raster', 'vector', '3d-raster', 'rgb', 'his'):
  112. try:
  113. if layerType in ('raster', 'rgb', 'his'):
  114. findType = 'cell'
  115. else:
  116. findType = layerType
  117. mapset = grass.find_file(mapname, element = findType)['mapset']
  118. except AttributeError, e: # not found
  119. return '', False
  120. if not mapset:
  121. found = False
  122. else:
  123. mapset = grass.gisenv()['MAPSET']
  124. # update dcmd
  125. for i, p, v in params:
  126. if p == 'layer':
  127. continue
  128. dcmd[i] = p + '=' + v
  129. if mapset:
  130. dcmd[i] += '@' + mapset
  131. maps = list()
  132. ogr = False
  133. for i, p, v in params:
  134. if v.lower().rfind('@ogr') > -1:
  135. ogr = True
  136. if p == 'layer' and not ogr:
  137. continue
  138. maps.append(dcmd[i].split('=', 1)[1])
  139. mapname = '\n'.join(maps)
  140. return mapname, found
  141. def GetValidLayerName(name):
  142. """!Make layer name SQL compliant, based on G_str_to_sql()
  143. @todo: Better use directly GRASS Python SWIG...
  144. """
  145. retName = str(name).strip()
  146. # check if name is fully qualified
  147. if '@' in retName:
  148. retName, mapset = retName.split('@')
  149. else:
  150. mapset = None
  151. cIdx = 0
  152. retNameList = list(retName)
  153. for c in retNameList:
  154. if not (c >= 'A' and c <= 'Z') and \
  155. not (c >= 'a' and c <= 'z') and \
  156. not (c >= '0' and c <= '9'):
  157. retNameList[cIdx] = '_'
  158. cIdx += 1
  159. retName = ''.join(retNameList)
  160. if not (retName[0] >= 'A' and retName[0] <= 'Z') and \
  161. not (retName[0] >= 'a' and retName[0] <= 'z'):
  162. retName = 'x' + retName[1:]
  163. if mapset:
  164. retName = retName + '@' + mapset
  165. return retName
  166. def ListOfCatsToRange(cats):
  167. """!Convert list of category number to range(s)
  168. Used for example for d.vect cats=[range]
  169. @param cats category list
  170. @return category range string
  171. @return '' on error
  172. """
  173. catstr = ''
  174. try:
  175. cats = map(int, cats)
  176. except:
  177. return catstr
  178. i = 0
  179. while i < len(cats):
  180. next = 0
  181. j = i + 1
  182. while j < len(cats):
  183. if cats[i + next] == cats[j] - 1:
  184. next += 1
  185. else:
  186. break
  187. j += 1
  188. if next > 1:
  189. catstr += '%d-%d,' % (cats[i], cats[i + next])
  190. i += next + 1
  191. else:
  192. catstr += '%d,' % (cats[i])
  193. i += 1
  194. return catstr.strip(',')
  195. def ListOfMapsets(get = 'ordered'):
  196. """!Get list of available/accessible mapsets
  197. @param get method ('all', 'accessible', 'ordered')
  198. @return list of mapsets
  199. @return None on error
  200. """
  201. mapsets = []
  202. if get == 'all' or get == 'ordered':
  203. ret = RunCommand('g.mapsets',
  204. read = True,
  205. quiet = True,
  206. flags = 'l',
  207. fs = 'newline')
  208. if ret:
  209. mapsets = ret.splitlines()
  210. ListSortLower(mapsets)
  211. else:
  212. return None
  213. if get == 'accessible' or get == 'ordered':
  214. ret = RunCommand('g.mapsets',
  215. read = True,
  216. quiet = True,
  217. flags = 'p',
  218. fs = 'newline')
  219. if ret:
  220. if get == 'accessible':
  221. mapsets = ret.splitlines()
  222. else:
  223. mapsets_accessible = ret.splitlines()
  224. for mapset in mapsets_accessible:
  225. mapsets.remove(mapset)
  226. mapsets = mapsets_accessible + mapsets
  227. else:
  228. return None
  229. return mapsets
  230. def ListSortLower(list):
  231. """!Sort list items (not case-sensitive)"""
  232. list.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
  233. def GetVectorNumberOfLayers(parent, vector):
  234. """!Get list of vector layers"""
  235. layers = list()
  236. if not vector:
  237. return layers
  238. fullname = grass.find_file(name = vector, element = 'vector')['fullname']
  239. if not fullname:
  240. Debug.msg(5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector)
  241. return layers
  242. ret, out, msg = RunCommand('v.db.connect',
  243. getErrorMsg = True,
  244. read = True,
  245. flags = 'g',
  246. map = fullname,
  247. fs = ';')
  248. if ret != 0:
  249. sys.stderr.write(_("Vector map <%(map)s>: %(msg)s\n") % { 'map' : fullname, 'msg' : msg })
  250. return layers
  251. else:
  252. Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret)
  253. for line in ret.splitlines():
  254. try:
  255. layer = line.split(';')[0]
  256. if '/' in layer:
  257. layer = layer.split('/')[0]
  258. layers.append(layer)
  259. except IndexError:
  260. pass
  261. Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" % \
  262. (fullname, ','.join(layers)))
  263. return layers
  264. def Deg2DMS(lon, lat, string = True, hemisphere = True, precision = 3):
  265. """!Convert deg value to dms string
  266. @param lon longitude (x)
  267. @param lat latitude (y)
  268. @param string True to return string otherwise tuple
  269. @param hemisphere print hemisphere
  270. @param precision seconds precision
  271. @return DMS string or tuple of values
  272. @return empty string on error
  273. """
  274. try:
  275. flat = float(lat)
  276. flon = float(lon)
  277. except ValueError:
  278. if string:
  279. return ''
  280. else:
  281. return None
  282. # fix longitude
  283. while flon > 180.0:
  284. flon -= 360.0
  285. while flon < -180.0:
  286. flon += 360.0
  287. # hemisphere
  288. if hemisphere:
  289. if flat < 0.0:
  290. flat = abs(flat)
  291. hlat = 'S'
  292. else:
  293. hlat = 'N'
  294. if flon < 0.0:
  295. hlon = 'W'
  296. flon = abs(flon)
  297. else:
  298. hlon = 'E'
  299. else:
  300. flat = abs(flat)
  301. flon = abs(flon)
  302. hlon = ''
  303. hlat = ''
  304. slat = __ll_parts(flat, precision = precision)
  305. slon = __ll_parts(flon, precision = precision)
  306. if string:
  307. return slon + hlon + '; ' + slat + hlat
  308. return (slon + hlon, slat + hlat)
  309. def DMS2Deg(lon, lat):
  310. """!Convert dms value to deg
  311. @param lon longitude (x)
  312. @param lat latitude (y)
  313. @return tuple of converted values
  314. @return ValueError on error
  315. """
  316. x = __ll_parts(lon, reverse = True)
  317. y = __ll_parts(lat, reverse = True)
  318. return (x, y)
  319. def __ll_parts(value, reverse = False, precision = 3):
  320. """!Converts deg to d:m:s string
  321. @param value value to be converted
  322. @param reverse True to convert from d:m:s to deg
  323. @param precision seconds precision (ignored if reverse is True)
  324. @return converted value (string/float)
  325. @return ValueError on error (reverse == True)
  326. """
  327. if not reverse:
  328. if value == 0.0:
  329. return '%s%.*f' % ('00:00:0', precision, 0.0)
  330. d = int(int(value))
  331. m = int((value - d) * 60)
  332. s = ((value - d) * 60 - m) * 60
  333. if m < 0:
  334. m = '00'
  335. elif m < 10:
  336. m = '0' + str(m)
  337. else:
  338. m = str(m)
  339. if s < 0:
  340. s = '00.0000'
  341. elif s < 10.0:
  342. s = '0%.*f' % (precision, s)
  343. else:
  344. s = '%.*f' % (precision, s)
  345. return str(d) + ':' + m + ':' + s
  346. else: # -> reverse
  347. try:
  348. d, m, s = value.split(':')
  349. hs = s[-1]
  350. s = s[:-1]
  351. except ValueError:
  352. try:
  353. d, m = value.split(':')
  354. hs = m[-1]
  355. m = m[:-1]
  356. s = '0.0'
  357. except ValueError:
  358. try:
  359. d = value
  360. hs = d[-1]
  361. d = d[:-1]
  362. m = '0'
  363. s = '0.0'
  364. except ValueError:
  365. raise ValueError
  366. if hs not in ('N', 'S', 'E', 'W'):
  367. raise ValueError
  368. coef = 1.0
  369. if hs in ('S', 'W'):
  370. coef = -1.0
  371. fm = int(m) / 60.0
  372. fs = float(s) / (60 * 60)
  373. return coef * (float(d) + fm + fs)
  374. def GetCmdString(cmd):
  375. """
  376. Get GRASS command as string.
  377. @param cmd GRASS command given as dictionary
  378. @return command string
  379. """
  380. scmd = ''
  381. if not cmd:
  382. return scmd
  383. scmd = cmd[0]
  384. if 'flags' in cmd[1]:
  385. for flag in cmd[1]['flags']:
  386. scmd += ' -' + flag
  387. for flag in ('verbose', 'quiet', 'overwrite'):
  388. if flag in cmd[1] and cmd[1][flag] is True:
  389. scmd += ' --' + flag
  390. for k, v in cmd[1].iteritems():
  391. if k in ('flags', 'verbose', 'quiet', 'overwrite'):
  392. continue
  393. scmd += ' %s=%s' % (k, v)
  394. return scmd
  395. def CmdToTuple(cmd):
  396. """!Convert command list to tuple for gcmd.RunCommand()"""
  397. if len(cmd) < 1:
  398. return None
  399. dcmd = {}
  400. for item in cmd[1:]:
  401. if '=' in item: # params
  402. key, value = item.split('=', 1)
  403. dcmd[str(key)] = str(value).replace('"', '')
  404. elif item[:2] == '--': # long flags
  405. flag = item[2:]
  406. if flag in ('verbose', 'quiet', 'overwrite'):
  407. dcmd[str(flag)] = True
  408. else: # -> flags
  409. if 'flags' not in dcmd:
  410. dcmd['flags'] = ''
  411. dcmd['flags'] += item.replace('-', '')
  412. return (cmd[0],
  413. dcmd)
  414. def PathJoin(*args):
  415. """!Check path created by os.path.join"""
  416. path = os.path.join(*args)
  417. if platform.system() == 'Windows' and \
  418. '/' in path:
  419. return path[1].upper() + ':\\' + path[3:].replace('/', '\\')
  420. return path
  421. def ReadEpsgCodes(path):
  422. """!Read EPSG code from the file
  423. @param path full path to the file with EPSG codes
  424. @return dictionary of EPSG code
  425. @return string on error
  426. """
  427. epsgCodeDict = dict()
  428. try:
  429. try:
  430. f = open(path, "r")
  431. except IOError:
  432. return _("failed to open '%s'" % path)
  433. i = 0
  434. code = None
  435. for line in f.readlines():
  436. line = line.strip()
  437. if len(line) < 1:
  438. continue
  439. if line[0] == '#':
  440. descr = line[1:].strip()
  441. elif line[0] == '<':
  442. code, params = line.split(" ", 1)
  443. try:
  444. code = int(code.replace('<', '').replace('>', ''))
  445. except ValueError:
  446. return e
  447. if code is not None:
  448. epsgCodeDict[code] = (descr, params)
  449. code = None
  450. i += 1
  451. f.close()
  452. except StandardError, e:
  453. return e
  454. return epsgCodeDict
  455. def ReprojectCoordinates(coord, projOut, projIn = None, flags = ''):
  456. """!Reproject coordinates
  457. @param coord coordinates given as tuple
  458. @param projOut output projection
  459. @param projIn input projection (use location projection settings)
  460. @return reprojected coordinates (returned as tuple)
  461. """
  462. coors = RunCommand('m.proj',
  463. flags = flags,
  464. input = '-',
  465. proj_input = projIn,
  466. proj_output = projOut,
  467. fs = ';',
  468. stdin = '%f;%f' % (coord[0], coord[1]),
  469. read = True)
  470. if coors:
  471. coors = coors.split(';')
  472. e = coors[0]
  473. n = coors[1]
  474. try:
  475. proj = projOut.split(' ')[0].split('=')[1]
  476. except IndexError:
  477. proj = ''
  478. if proj in ('ll', 'latlong', 'longlat') and 'd' not in flags:
  479. return (proj, (e, n))
  480. else:
  481. try:
  482. return (proj, (float(e), float(n)))
  483. except ValueError:
  484. return (None, None)
  485. return (None, None)
  486. def GetListOfLocations(dbase):
  487. """!Get list of GRASS locations in given dbase
  488. @param dbase GRASS database path
  489. @return list of locations (sorted)
  490. """
  491. listOfLocations = list()
  492. try:
  493. for location in glob.glob(os.path.join(dbase, "*")):
  494. try:
  495. if os.path.join(location, "PERMANENT") in glob.glob(os.path.join(location, "*")):
  496. listOfLocations.append(os.path.basename(location))
  497. except:
  498. pass
  499. except UnicodeEncodeError, e:
  500. raise e
  501. ListSortLower(listOfLocations)
  502. return listOfLocations
  503. def GetListOfMapsets(dbase, location, selectable = False):
  504. """!Get list of mapsets in given GRASS location
  505. @param dbase GRASS database path
  506. @param location GRASS location
  507. @param selectable True to get list of selectable mapsets, otherwise all
  508. @return list of mapsets - sorted (PERMANENT first)
  509. """
  510. listOfMapsets = list()
  511. if selectable:
  512. ret = RunCommand('g.mapset',
  513. read = True,
  514. flags = 'l',
  515. location = location,
  516. gisdbase = dbase)
  517. if not ret:
  518. return listOfMapsets
  519. for line in ret.rstrip().splitlines():
  520. listOfMapsets += line.split(' ')
  521. else:
  522. for mapset in glob.glob(os.path.join(dbase, location, "*")):
  523. if os.path.isdir(mapset) and \
  524. os.path.isfile(os.path.join(dbase, location, mapset, "WIND")):
  525. listOfMapsets.append(os.path.basename(mapset))
  526. ListSortLower(listOfMapsets)
  527. return listOfMapsets
  528. def GetColorTables():
  529. """!Get list of color tables"""
  530. ret = RunCommand('r.colors',
  531. read = True,
  532. flags = 'l')
  533. if not ret:
  534. return list()
  535. return ret.splitlines()
  536. def _getGDALFormats():
  537. """!Get dictionary of avaialble GDAL drivers"""
  538. ret = grass.read_command('r.in.gdal',
  539. quiet = True,
  540. flags = 'f')
  541. return _parseFormats(ret), _parseFormats(ret, writableOnly = True)
  542. def _getOGRFormats():
  543. """!Get dictionary of avaialble OGR drivers"""
  544. ret = grass.read_command('v.in.ogr',
  545. quiet = True,
  546. flags = 'f')
  547. return _parseFormats(ret), _parseFormats(ret, writableOnly = True)
  548. def _parseFormats(output, writableOnly = False):
  549. """!Parse r.in.gdal/v.in.ogr -f output"""
  550. formats = { 'file' : list(),
  551. 'database' : list(),
  552. 'protocol' : list()
  553. }
  554. if not output:
  555. return formats
  556. patt = None
  557. if writableOnly:
  558. patt = re.compile('\(rw\+?\)$', re.IGNORECASE)
  559. for line in output.splitlines():
  560. key, name = map(lambda x: x.strip(), line.strip().rsplit(':', -1))
  561. if writableOnly and not patt.search(key):
  562. continue
  563. if name in ('Memory', 'Virtual Raster', 'In Memory Raster'):
  564. continue
  565. if name in ('PostgreSQL', 'SQLite',
  566. 'ODBC', 'ESRI Personal GeoDatabase',
  567. 'Rasterlite',
  568. 'PostGIS WKT Raster driver',
  569. 'CouchDB'):
  570. formats['database'].append(name)
  571. elif name in ('GeoJSON',
  572. 'OGC Web Coverage Service',
  573. 'OGC Web Map Service',
  574. 'WFS',
  575. 'GeoRSS',
  576. 'HTTP Fetching Wrapper'):
  577. formats['protocol'].append(name)
  578. else:
  579. formats['file'].append(name)
  580. for items in formats.itervalues():
  581. items.sort()
  582. return formats
  583. formats = None
  584. def GetFormats(writableOnly = False):
  585. """!Get GDAL/OGR formats"""
  586. global formats
  587. if not formats:
  588. gdalAll, gdalWritable = _getGDALFormats()
  589. ogrAll, ogrWritable = _getOGRFormats()
  590. formats = {
  591. 'all' : {
  592. 'gdal' : gdalAll,
  593. 'ogr' : ogrAll,
  594. },
  595. 'writable' : {
  596. 'gdal' : gdalWritable,
  597. 'ogr' : ogrWritable,
  598. },
  599. }
  600. if writableOnly:
  601. return formats['writable']
  602. return formats['all']
  603. def GetSettingsPath():
  604. """!Get full path to the settings directory
  605. """
  606. try:
  607. verFd = open(os.path.join(ETCDIR, "VERSIONNUMBER"))
  608. version = int(verFd.readlines()[0].split(' ')[0].split('.')[0])
  609. except (IOError, ValueError, TypeError, IndexError), e:
  610. sys.exit(_("ERROR: Unable to determine GRASS version. Details: %s") % e)
  611. verFd.close()
  612. # keep location of settings files rc and wx in sync with lib/init/grass.py
  613. if sys.platform == 'win32':
  614. return os.path.join(os.getenv('APPDATA'), 'grass%d' % version)
  615. return os.path.join(os.getenv('HOME'), '.grass%d' % version)
  616. # From lib/gis/col_str.c, except purple which is mentioned
  617. # there but not given RGB values
  618. str2rgb = {'aqua': (100, 128, 255),
  619. 'black': (0, 0, 0),
  620. 'blue': (0, 0, 255),
  621. 'brown': (180, 77, 25),
  622. 'cyan': (0, 255, 255),
  623. 'gray': (128, 128, 128),
  624. 'green': (0, 255, 0),
  625. 'grey': (128, 128, 128),
  626. 'indigo': (0, 128, 255),
  627. 'magenta': (255, 0, 255),
  628. 'orange': (255, 128, 0),
  629. 'purple': (128, 0, 128),
  630. 'red': (255, 0, 0),
  631. 'violet': (128, 0, 255),
  632. 'white': (255, 255, 255),
  633. 'yellow': (255, 255, 0)}
  634. rgb2str = {}
  635. for (s,r) in str2rgb.items():
  636. rgb2str[ r ] = s
  637. def color_resolve(color):
  638. if len(color) > 0 and color[0] in "0123456789":
  639. rgb = tuple(map(int, color.split(':')))
  640. label = color
  641. else:
  642. # Convert color names to RGB
  643. try:
  644. rgb = str2rgb[color]
  645. label = color
  646. except KeyError:
  647. rgb = (200, 200, 200)
  648. label = _('Select Color')
  649. return (rgb, label)