gselect.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  1. """!
  2. @package gselect
  3. @brief Custom control that selects elements
  4. Classes:
  5. - Select
  6. - VectorSelect
  7. - TreeCrtlComboPopup
  8. - VectorDBInfo
  9. - LayerSelect
  10. - LayerNameSelect
  11. - DriverSelect
  12. - DatabaseSelect
  13. - ColumnSelect
  14. - LocationSelect
  15. - MapsetSelect
  16. - SubGroupSelect
  17. - FormatSelect
  18. - GdalSelect
  19. (C) 2007-2010 by the GRASS Development Team This program is free
  20. software under the GNU General Public License (>=v2). Read the file
  21. COPYING that comes with GRASS for details.
  22. @author Michael Barton
  23. @author Martin Landa <landa.martin gmail.com>
  24. """
  25. import os
  26. import sys
  27. import glob
  28. import wx
  29. import wx.combo
  30. import wx.lib.filebrowsebutton as filebrowse
  31. import globalvar
  32. grassPath = os.path.join(globalvar.ETCDIR, "python")
  33. sys.path.append(grassPath)
  34. import grass.script as grass
  35. import gcmd
  36. import utils
  37. from preferences import globalSettings as UserSettings
  38. class Select(wx.combo.ComboCtrl):
  39. def __init__(self, parent, id, size = globalvar.DIALOG_GSELECT_SIZE,
  40. type = None, multiple = False, mapsets = None, exclude = [],
  41. updateOnPopup = True):
  42. """!Custom control to create a ComboBox with a tree control
  43. to display and select GIS elements within acessible mapsets.
  44. Elements can be selected with mouse. Can allow multiple selections, when
  45. argument multiple=True. Multiple selections are separated by commas.
  46. """
  47. wx.combo.ComboCtrl.__init__(self, parent=parent, id=id, size=size)
  48. self.GetChildren()[0].SetName("Select")
  49. self.GetChildren()[0].type = type
  50. self.tcp = TreeCtrlComboPopup()
  51. self.SetPopupControl(self.tcp)
  52. self.SetPopupExtents(0,100)
  53. if type:
  54. self.tcp.SetData(type = type, mapsets = mapsets,
  55. exclude = exclude, multiple = multiple,
  56. updateOnPopup = updateOnPopup)
  57. def SetElementList(self, type, mapsets = None, exclude = []):
  58. """!Set element list
  59. @param type GIS element type
  60. @param mapsets list of acceptable mapsets (None for all in search path)
  61. @param exclude list of GIS elements to be excluded
  62. """
  63. self.tcp.SetData(type = type, mapsets = mapsets,
  64. exclude = exclude)
  65. def GetElementList(self):
  66. """!Load elements"""
  67. self.tcp.GetElementList()
  68. class VectorSelect(Select):
  69. def __init__(self, parent, ftype, **kwargs):
  70. """!Custom to create a ComboBox with a tree control to display and
  71. select vector maps. Control allows to filter vector maps. If you
  72. don't need this feature use Select class instead
  73. @ftype filter vector maps based on feature type
  74. """
  75. Select.__init__(self, parent = parent, id = wx.ID_ANY,
  76. type = 'vector', **kwargs)
  77. self.ftype = ftype
  78. # remove vector maps which do not contain given feature type
  79. self.tcp.SetFilter(self.__isElement)
  80. def __isElement(self, vectorName):
  81. """!Check if element should be filtered out"""
  82. try:
  83. if int(grass.vector_info_topo(vectorName)[self.ftype]) < 1:
  84. return False
  85. except KeyError:
  86. return False
  87. return True
  88. class TreeCtrlComboPopup(wx.combo.ComboPopup):
  89. """!Create a tree ComboBox for selecting maps and other GIS elements
  90. in accessible mapsets within the current location
  91. """
  92. # overridden ComboPopup methods
  93. def Init(self):
  94. self.value = [] # for multiple is False -> len(self.value) in [0,1]
  95. self.curitem = None
  96. self.multiple = False
  97. self.type = None
  98. self.mapsets = []
  99. self.exclude = []
  100. self.SetFilter(None)
  101. def Create(self, parent):
  102. self.seltree = wx.TreeCtrl(parent, style=wx.TR_HIDE_ROOT
  103. |wx.TR_HAS_BUTTONS
  104. |wx.TR_SINGLE
  105. |wx.TR_LINES_AT_ROOT
  106. |wx.SIMPLE_BORDER
  107. |wx.TR_FULL_ROW_HIGHLIGHT)
  108. self.seltree.Bind(wx.EVT_MOTION, self.OnMotion)
  109. self.seltree.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
  110. self.seltree.Bind(wx.EVT_TREE_ITEM_EXPANDING, self.mapsetExpanded)
  111. self.seltree.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.mapsetCollapsed)
  112. self.seltree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.mapsetActivated)
  113. self.seltree.Bind(wx.EVT_TREE_SEL_CHANGED, self.mapsetSelected)
  114. self.seltree.Bind(wx.EVT_TREE_DELETE_ITEM, lambda x: None)
  115. # the following dummy handler are needed to keep tree events from propagating up to
  116. # the parent GIS Manager layer tree
  117. def mapsetExpanded(self, event):
  118. pass
  119. def mapsetCollapsed(self, event):
  120. pass
  121. def mapsetActivated(self, event):
  122. pass
  123. def mapsetSelected(self, event):
  124. pass
  125. # end of dummy events
  126. def GetControl(self):
  127. return self.seltree
  128. def GetStringValue(self):
  129. str = ""
  130. for value in self.value:
  131. str += value + ","
  132. str = str.rstrip(',')
  133. return str
  134. def SetFilter(self, filter):
  135. """!Set filter for GIS elements, see e.g. VectorSelect"""
  136. self.filterElements = filter
  137. def OnPopup(self, force = False):
  138. """!Limited only for first selected"""
  139. if not force and not self.updateOnPopup:
  140. return
  141. self.GetElementList()
  142. def GetElementList(self):
  143. """!Get filtered list of GIS elements in accessible mapsets
  144. and display as tree with all relevant elements displayed
  145. beneath each mapset branch
  146. """
  147. # update list
  148. self.seltree.DeleteAllItems()
  149. self._getElementList(self.type, self.mapsets, self.exclude)
  150. if len(self.value) > 0:
  151. root = self.seltree.GetRootItem()
  152. if not root:
  153. return
  154. item = self.FindItem(root, self.value[0])
  155. try:
  156. self.seltree.EnsureVisible(item)
  157. self.seltree.SelectItem(item)
  158. except:
  159. pass
  160. def SetStringValue(self, value):
  161. # this assumes that item strings are unique...
  162. root = self.seltree.GetRootItem()
  163. if not root:
  164. return
  165. found = self.FindItem(root, value)
  166. if found:
  167. self.value.append(found)
  168. self.seltree.SelectItem(found)
  169. def GetAdjustedSize(self, minWidth, prefHeight, maxHeight):
  170. return wx.Size(minWidth, min(200, maxHeight))
  171. def _getElementList(self, element, mapsets=None, exclude=[]):
  172. """!Get list of GIS elements in accessible mapsets and display as tree
  173. with all relevant elements displayed beneath each mapset branch
  174. @param element GIS element
  175. @param mapsets list of acceptable mapsets (None for all mapsets in search path)
  176. @param exclude list of GIS elements to be excluded
  177. """
  178. # get current mapset
  179. curr_mapset = grass.gisenv()['MAPSET']
  180. # list of mapsets in current location
  181. if mapsets is None:
  182. mapsets = utils.ListOfMapsets()
  183. # map element types to g.mlist types
  184. elementdict = {'cell':'rast',
  185. 'raster':'rast',
  186. 'rast':'rast',
  187. 'raster files':'rast',
  188. 'grid3':'rast3d',
  189. 'rast3d':'rast3d',
  190. 'raster3D':'rast3d',
  191. 'raster3D files':'rast3d',
  192. 'vector':'vect',
  193. 'vect':'vect',
  194. 'binary vector files':'vect',
  195. 'dig':'oldvect',
  196. 'oldvect':'oldvect',
  197. 'old vector':'oldvect',
  198. 'dig_ascii':'asciivect',
  199. 'asciivect':'asciivect',
  200. 'asciivector':'asciivect',
  201. 'ascii vector files':'asciivect',
  202. 'icons':'icon',
  203. 'icon':'icon',
  204. 'paint icon files':'icon',
  205. 'paint/labels':'labels',
  206. 'labels':'labels',
  207. 'label':'labels',
  208. 'paint label files':'labels',
  209. 'site_lists':'sites',
  210. 'sites':'sites',
  211. 'site list':'sites',
  212. 'site list files':'sites',
  213. 'windows':'region',
  214. 'region':'region',
  215. 'region definition':'region',
  216. 'region definition files':'region',
  217. 'windows3d':'region3d',
  218. 'region3d':'region3d',
  219. 'region3D definition':'region3d',
  220. 'region3D definition files':'region3d',
  221. 'group':'group',
  222. 'imagery group':'group',
  223. 'imagery group files':'group',
  224. '3d.view':'3dview',
  225. '3dview':'3dview',
  226. '3D viewing parameters':'3dview',
  227. '3D view parameters':'3dview'}
  228. if element not in elementdict:
  229. self.AddItem(_('Not selectable element'))
  230. return
  231. # get directory tree nodes
  232. # reorder mapsets based on search path (TODO)
  233. for i in range(len(mapsets)):
  234. if i > 0 and mapsets[i] == curr_mapset:
  235. mapsets[i] = mapsets[0]
  236. mapsets[0] = curr_mapset
  237. if globalvar.have_mlist:
  238. filesdict = grass.mlist_grouped(elementdict[element])
  239. else:
  240. filesdict = grass.list_grouped(elementdict[element])
  241. first_dir = None
  242. for dir in mapsets:
  243. dir_node = self.AddItem('Mapset: ' + dir)
  244. if not first_dir:
  245. first_dir = dir_node
  246. self.seltree.SetItemTextColour(dir_node, wx.Colour(50, 50, 200))
  247. try:
  248. elem_list = filesdict[dir]
  249. elem_list.sort(key=str.lower)
  250. for elem in elem_list:
  251. if elem != '':
  252. fullqElem = elem + '@' + dir
  253. if len(exclude) > 0 and fullqElem in exclude:
  254. continue
  255. if self.filterElements:
  256. if self.filterElements(fullqElem):
  257. self.AddItem(fullqElem, parent=dir_node)
  258. else:
  259. self.AddItem(fullqElem, parent=dir_node)
  260. except:
  261. continue
  262. if self.seltree.ItemHasChildren(dir_node):
  263. sel = UserSettings.Get(group='general', key='elementListExpand',
  264. subkey='selection')
  265. collapse = True
  266. if sel == 0: # collapse all except PERMANENT and current
  267. if dir in ('PERMANENT', curr_mapset):
  268. collapse = False
  269. elif sel == 1: # collapse all except PERMANENT
  270. if dir == 'PERMANENT':
  271. collapse = False
  272. elif sel == 2: # collapse all except current
  273. if dir == curr_mapset:
  274. collapse = False
  275. elif sel == 3: # collapse all
  276. pass
  277. elif sel == 4: # expand all
  278. collapse = False
  279. if collapse:
  280. self.seltree.Collapse(dir_node)
  281. else:
  282. self.seltree.Expand(dir_node)
  283. if first_dir:
  284. # select first mapset (MSW hack)
  285. self.seltree.SelectItem(first_dir)
  286. # helpers
  287. def FindItem(self, parentItem, text):
  288. item, cookie = self.seltree.GetFirstChild(parentItem)
  289. while item:
  290. if self.seltree.GetItemText(item) == text:
  291. return item
  292. if self.seltree.ItemHasChildren(item):
  293. item = self.FindItem(item, text)
  294. item, cookie = self.seltree.GetNextChild(parentItem, cookie)
  295. return wx.TreeItemId()
  296. def AddItem(self, value, parent=None):
  297. if not parent:
  298. root = self.seltree.GetRootItem()
  299. if not root:
  300. root = self.seltree.AddRoot("<hidden root>")
  301. parent = root
  302. item = self.seltree.AppendItem(parent, text=value)
  303. return item
  304. def OnMotion(self, evt):
  305. # have the selection follow the mouse, like in a real combobox
  306. item, flags = self.seltree.HitTest(evt.GetPosition())
  307. if item and flags & wx.TREE_HITTEST_ONITEMLABEL:
  308. self.seltree.SelectItem(item)
  309. self.curitem = item
  310. evt.Skip()
  311. def OnLeftDown(self, evt):
  312. # do the combobox selection
  313. item, flags = self.seltree.HitTest(evt.GetPosition())
  314. if item and flags & wx.TREE_HITTEST_ONITEMLABEL:
  315. self.curitem = item
  316. if self.seltree.GetRootItem() == self.seltree.GetItemParent(item):
  317. self.value = [] # cannot select mapset item
  318. else:
  319. if self.multiple is True:
  320. # text item should be unique
  321. self.value.append(self.seltree.GetItemText(item))
  322. else:
  323. self.value = [self.seltree.GetItemText(item), ]
  324. self.Dismiss()
  325. evt.Skip()
  326. def SetData(self, **kargs):
  327. """!Set object properties"""
  328. if kargs.has_key('type'):
  329. self.type = kargs['type']
  330. if kargs.has_key('mapsets'):
  331. self.mapsets = kargs['mapsets']
  332. if kargs.has_key('exclude'):
  333. self.exclude = kargs['exclude']
  334. if kargs.has_key('multiple'):
  335. self.multiple = kargs['multiple']
  336. if kargs.has_key('updateOnPopup'):
  337. self.updateOnPopup = kargs['updateOnPopup']
  338. class VectorDBInfo:
  339. """!Class providing information about attribute tables
  340. linked to a vector map"""
  341. def __init__(self, map):
  342. self.map = map
  343. # dictionary of layer number and associated (driver, database, table)
  344. self.layers = {}
  345. # dictionary of table and associated columns (type, length, values, ids)
  346. self.tables = {}
  347. if not self.__CheckDBConnection(): # -> self.layers
  348. return
  349. self.__DescribeTables() # -> self.tables
  350. def __CheckDBConnection(self):
  351. """!Check DB connection"""
  352. nuldev = file(os.devnull, 'w+')
  353. self.layers = grass.vector_db(map=self.map, stderr=nuldev)
  354. nuldev.close()
  355. if (len(self.layers.keys()) == 0):
  356. return False
  357. return True
  358. def __DescribeTables(self):
  359. """!Describe linked tables"""
  360. for layer in self.layers.keys():
  361. # determine column names and types
  362. table = self.layers[layer]["table"]
  363. columns = {} # {name: {type, length, [values], [ids]}}
  364. i = 0
  365. for item in grass.db_describe(table = self.layers[layer]["table"],
  366. driver = self.layers[layer]["driver"],
  367. database = self.layers[layer]["database"])['cols']:
  368. name, type, length = item
  369. # FIXME: support more datatypes
  370. if type.lower() == "integer":
  371. ctype = int
  372. elif type.lower() == "double precision":
  373. ctype = float
  374. else:
  375. ctype = str
  376. columns[name.strip()] = { 'index' : i,
  377. 'type' : type.lower(),
  378. 'ctype' : ctype,
  379. 'length' : int(length),
  380. 'values' : [],
  381. 'ids' : []}
  382. i += 1
  383. # check for key column
  384. # v.db.connect -g/p returns always key column name lowercase
  385. if self.layers[layer]["key"] not in columns.keys():
  386. for col in columns.keys():
  387. if col.lower() == self.layers[layer]["key"]:
  388. self.layers[layer]["key"] = col.upper()
  389. break
  390. self.tables[table] = columns
  391. return True
  392. def Reset(self):
  393. """!Reset"""
  394. for layer in self.layers:
  395. table = self.layers[layer]["table"] # get table desc
  396. columns = self.tables[table]
  397. for name in self.tables[table].keys():
  398. self.tables[table][name]['values'] = []
  399. self.tables[table][name]['ids'] = []
  400. def GetName(self):
  401. """!Get vector name"""
  402. return self.map
  403. def GetKeyColumn(self, layer):
  404. """!Get key column of given layer
  405. @param layer vector layer number
  406. """
  407. return self.layers[layer]['key']
  408. def GetTable(self, layer):
  409. """!Get table name of given layer
  410. @param layer vector layer number
  411. """
  412. return self.layers[layer]['table']
  413. def GetDbSettings(self, layer):
  414. """!Get database settins
  415. @param layer layer number
  416. @return (driver, database)
  417. """
  418. return self.layers[layer]['driver'], self.layers[layer]['database']
  419. def GetTableDesc(self, table):
  420. """!Get table columns
  421. @param table table name
  422. """
  423. return self.tables[table]
  424. class LayerSelect(wx.Choice):
  425. def __init__(self, parent, id = wx.ID_ANY,
  426. size=globalvar.DIALOG_LAYER_SIZE,
  427. vector = None, choices = [], all = False, default = None):
  428. """!Creates widget for selecting vector map layer numbers
  429. @param vector vector map name or None
  430. @param choices list of predefined choices
  431. @param all adds layer '-1' (e.g., for d.vect)
  432. @param default default layer number
  433. """
  434. super(LayerSelect, self).__init__(parent, id, size = size,
  435. choices = choices)
  436. self.all = all
  437. self.SetName("LayerSelect")
  438. # default value
  439. self.default = default
  440. if len(choices) > 1:
  441. return
  442. if vector:
  443. self.InsertLayers(vector)
  444. else:
  445. if all:
  446. self.SetItems(['-1', '1'])
  447. else:
  448. self.SetItems(['1'])
  449. self.SetStringSelection('1')
  450. def InsertLayers(self, vector):
  451. """!Insert layers for a vector into the layer combobox"""
  452. layerchoices = utils.GetVectorNumberOfLayers(vector)
  453. if self.all:
  454. layerchoices.insert(0, '-1')
  455. if len(layerchoices) > 1:
  456. self.SetItems(layerchoices)
  457. self.SetStringSelection('1')
  458. else:
  459. self.SetItems(['1'])
  460. self.SetStringSelection('1')
  461. if self.default:
  462. self.SetStringSelection(str(self.default))
  463. class LayerNameSelect(wx.ComboBox):
  464. def __init__(self, parent, id = wx.ID_ANY,
  465. size = globalvar.DIALOG_COMBOBOX_SIZE,
  466. vector = None, dsn = None):
  467. """!Creates combo box for selecting vector map layer names
  468. @param vector vector map name (native or connected via v.external)
  469. @param dsn OGR data source name
  470. """
  471. super(LayerNameSelect, self).__init__(parent, id, size = size)
  472. self.SetName("LayerNameSelect")
  473. if vector:
  474. # -> native
  475. self.InsertLayers(vector = vector)
  476. elif dsn:
  477. self.InsertLayers(dsn = dsn)
  478. def InsertLayers(self, vector = None, dsn = None):
  479. """!Insert layers for a vector into the layer combobox
  480. @todo Implement native format
  481. @param vector vector map name (native or connected via v.external)
  482. @param dsn OGR data source name
  483. """
  484. layers = list()
  485. if vector:
  486. # TODO
  487. pass
  488. elif dsn:
  489. ret = gcmd.RunCommand('v.in.ogr',
  490. read = True,
  491. quiet = True,
  492. flags = 'l',
  493. dsn = dsn)
  494. if ret:
  495. layers = ret.splitlines()
  496. self.SetItems(layers)
  497. self.SetSelection(0)
  498. class DriverSelect(wx.ComboBox):
  499. """!Creates combo box for selecting database driver.
  500. """
  501. def __init__(self, parent, choices, value,
  502. id=wx.ID_ANY, pos=wx.DefaultPosition,
  503. size=globalvar.DIALOG_LAYER_SIZE, **kargs):
  504. super(DriverSelect, self).__init__(parent, id, value, pos, size,
  505. choices, style=wx.CB_READONLY)
  506. self.SetName("DriverSelect")
  507. self.SetStringSelection(value)
  508. class DatabaseSelect(wx.TextCtrl):
  509. """!Creates combo box for selecting database driver.
  510. """
  511. def __init__(self, parent, value='',
  512. id=wx.ID_ANY, pos=wx.DefaultPosition,
  513. size=globalvar.DIALOG_TEXTCTRL_SIZE, **kargs):
  514. super(DatabaseSelect, self).__init__(parent, id, value, pos, size)
  515. self.SetName("DatabaseSelect")
  516. class TableSelect(wx.ComboBox):
  517. """!Creates combo box for selecting attribute tables from the database
  518. """
  519. def __init__(self, parent,
  520. id=wx.ID_ANY, value='', pos=wx.DefaultPosition,
  521. size=globalvar.DIALOG_COMBOBOX_SIZE,
  522. choices=[]):
  523. super(TableSelect, self).__init__(parent, id, value, pos, size, choices,
  524. style=wx.CB_READONLY)
  525. self.SetName("TableSelect")
  526. if not choices:
  527. self.InsertTables()
  528. def InsertTables(self, driver=None, database=None):
  529. """!Insert attribute tables into combobox"""
  530. items = []
  531. if not driver or not database:
  532. connect = grass.db_connection()
  533. driver = connect['driver']
  534. database = connect['database']
  535. ret = gcmd.RunCommand('db.tables',
  536. flags = 'p',
  537. read = True,
  538. driver = driver,
  539. database = database)
  540. if ret:
  541. for table in ret.splitlines():
  542. items.append(table)
  543. self.SetItems(items)
  544. self.SetValue('')
  545. class ColumnSelect(wx.ComboBox):
  546. """!Creates combo box for selecting columns in the attribute table
  547. for a vector map.
  548. @param parent window parent
  549. @param id window id
  550. @param value default value
  551. @param size window size
  552. @param vector vector map name
  553. @param layer layer number
  554. @param param parameters list (see menuform.py)
  555. @param **kwags wx.ComboBox parameters
  556. """
  557. def __init__(self, parent, id = wx.ID_ANY, value = '',
  558. size=globalvar.DIALOG_COMBOBOX_SIZE,
  559. vector = None, layer = 1, param = None, **kwargs):
  560. self.defaultValue = value
  561. self.param = param
  562. super(ColumnSelect, self).__init__(parent, id, value, size = size, **kwargs)
  563. self.SetName("ColumnSelect")
  564. if vector:
  565. self.InsertColumns(vector, layer)
  566. def InsertColumns(self, vector, layer, excludeKey = False, type = None):
  567. """!Insert columns for a vector attribute table into the columns combobox
  568. @param vector vector name
  569. @param layer vector layer number
  570. @param excludeKey exclude key column from the list?
  571. @param type only columns of given type (given as list)
  572. """
  573. dbInfo = VectorDBInfo(vector)
  574. try:
  575. table = dbInfo.GetTable(int(layer))
  576. columnchoices = dbInfo.GetTableDesc(table)
  577. keyColumn = dbInfo.GetKeyColumn(int(layer))
  578. columns = len(columnchoices.keys()) * ['']
  579. for key, val in columnchoices.iteritems():
  580. columns[val['index']] = key
  581. if excludeKey: # exclude key column
  582. columns.remove(keyColumn)
  583. if type: # only selected column types
  584. for key, value in columnchoices.iteritems():
  585. if value['type'] not in type:
  586. columns.remove(key)
  587. except (KeyError, ValueError):
  588. columns = list()
  589. self.SetItems(columns)
  590. self.SetValue(self.defaultValue)
  591. if self.param:
  592. self.param['value'] = ''
  593. def InsertTableColumns(self, table, driver=None, database=None):
  594. """!Insert table columns
  595. @param table table name
  596. @param driver driver name
  597. @param database database name
  598. """
  599. columns = list()
  600. ret = gcmd.RunCommand('db.columns',
  601. read = True,
  602. driver = driver,
  603. database = database,
  604. table = table)
  605. if ret:
  606. columns = ret.splitlines()
  607. self.SetItems(columns)
  608. self.SetValue(self.defaultValue)
  609. if self.param:
  610. self.param['value'] = ''
  611. class LocationSelect(wx.ComboBox):
  612. """!Widget for selecting GRASS location"""
  613. def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_COMBOBOX_SIZE,
  614. gisdbase = None, **kwargs):
  615. super(LocationSelect, self).__init__(parent, id, size = size,
  616. style = wx.CB_READONLY, **kwargs)
  617. self.SetName("LocationSelect")
  618. if not gisdbase:
  619. self.gisdbase = grass.gisenv()['GISDBASE']
  620. else:
  621. self.gisdbase = gisdbase
  622. self.SetItems(utils.GetListOfLocations(self.gisdbase))
  623. class MapsetSelect(wx.ComboBox):
  624. """!Widget for selecting GRASS mapset"""
  625. def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_COMBOBOX_SIZE,
  626. gisdbase = None, location = None, setItems = True, **kwargs):
  627. super(MapsetSelect, self).__init__(parent, id, size = size,
  628. style = wx.CB_READONLY, **kwargs)
  629. self.SetName("MapsetSelect")
  630. if not gisdbase:
  631. self.gisdbase = grass.gisenv()['GISDBASE']
  632. else:
  633. self.gisdbase = gisdbase
  634. if not location:
  635. self.location = grass.gisenv()['LOCATION_NAME']
  636. else:
  637. self.location = location
  638. if setItems:
  639. self.SetItems(utils.GetListOfMapsets(self.gisdbase, self.location, selectable = True)) # selectable
  640. class SubGroupSelect(wx.ComboBox):
  641. """!Widget for selecting subgroups"""
  642. def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
  643. **kwargs):
  644. super(SubGroupSelect, self).__init__(parent, id, size = size,
  645. style = wx.CB_READONLY, **kwargs)
  646. self.SetName("SubGroupSelect")
  647. def Insert(self, group):
  648. """!Insert subgroups for defined group"""
  649. if not group:
  650. return
  651. gisenv = grass.gisenv()
  652. try:
  653. name, mapset = group.split('@', 1)
  654. except ValueError:
  655. name = group
  656. mapset = gisenv['MAPSET']
  657. path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], mapset,
  658. 'group', name, 'subgroup')
  659. try:
  660. self.SetItems(os.listdir(path))
  661. except OSError:
  662. self.SetItems([])
  663. self.SetValue('')
  664. class FormatSelect(wx.Choice):
  665. def __init__(self, parent, ogr = False,
  666. sourceType = None, id = wx.ID_ANY, size = globalvar.DIALOG_COMBOBOX_SIZE,
  667. **kwargs):
  668. """!Widget for selecting external (GDAL/OGR) format
  669. @param parent parent window
  670. @param sourceType source type ('file', 'directory', 'database', 'protocol') or None
  671. @param ogr True for OGR otherwise GDAL
  672. """
  673. super(FormatSelect, self).__init__(parent, id, size = size,
  674. style = wx.CB_READONLY, **kwargs)
  675. self.SetName("FormatSelect")
  676. if ogr:
  677. ftype = 'ogr'
  678. else:
  679. ftype = 'gdal'
  680. formats = list()
  681. for f in globalvar.formats[ftype].values():
  682. formats += f
  683. self.SetItems(formats)
  684. def GetExtension(self, name):
  685. """!Get file extension by format name"""
  686. formatToExt = {
  687. # raster
  688. 'GeoTIFF' : 'tif',
  689. 'Erdas Imagine Images (.img)' : '.img',
  690. 'Ground-based SAR Applications Testbed File Format (.gff)' : '.gff',
  691. 'Arc/Info Binary Grid' : 'adf',
  692. 'Portable Network Graphics' : 'png',
  693. 'JPEG JFIF' : 'jpg',
  694. 'Japanese DEM (.mem)' : 'mem',
  695. 'Graphics Interchange Format (.gif)' : 'gif',
  696. 'X11 PixMap Format' : 'xpm',
  697. 'MS Windows Device Independent Bitmap' : 'bmp',
  698. 'SPOT DIMAP' : '.dim',
  699. 'RadarSat 2 XML Product' : 'xml',
  700. 'EarthWatch .TIL' : '.til',
  701. 'ERMapper .ers Labelled' : '.ers',
  702. 'ERMapper Compressed Wavelets' : 'ecw',
  703. 'GRIdded Binary (.grb)' : 'grb',
  704. 'EUMETSAT Archive native (.nat)' : '.nat',
  705. 'Idrisi Raster A.1' : 'rst',
  706. 'Golden Software ASCII Grid (.grd)' : '.grd',
  707. 'Golden Software Binary Grid (.grd)' : 'grd',
  708. 'Golden Software 7 Binary Grid (.grd)' : 'grd',
  709. 'R Object Data Store' : 'r',
  710. 'USGS DOQ (Old Style)' : 'doq',
  711. 'USGS DOQ (New Style)' : 'doq',
  712. 'ENVI .hdr Labelled' : 'hdr',
  713. 'ESRI .hdr Labelled' : 'hdr',
  714. 'Generic Binary (.hdr Labelled)' : 'hdr',
  715. 'PCI .aux Labelled' : 'aux',
  716. 'EOSAT FAST Format' : 'fst',
  717. 'VTP .bt (Binary Terrain) 1.3 Format' : 'bt',
  718. 'FARSITE v.4 Landscape File (.lcp)' : 'lcp',
  719. 'Swedish Grid RIK (.rik)' : 'rik',
  720. 'USGS Optional ASCII DEM (and CDED)' : '.dem',
  721. 'Northwood Numeric Grid Format .grd/.tab' : '',
  722. 'Northwood Classified Grid Format .grc/.tab' : '',
  723. 'ARC Digitized Raster Graphics' : 'arc',
  724. 'Magellan topo (.blx)' : 'blx',
  725. 'SAGA GIS Binary Grid (.sdat)' : 'sdat',
  726. # vector
  727. 'ESRI Shapefile' : 'shp',
  728. 'UK .NTF' : 'ntf',
  729. 'SDTS' : 'ddf',
  730. 'DGN' : 'dgn',
  731. 'VRT' : 'vrt',
  732. 'REC' : 'rec',
  733. 'BNA' : 'bna',
  734. 'CSV' : 'csv',
  735. 'GML' : 'gml',
  736. 'GPX' : 'gpx',
  737. 'KML' : 'kml',
  738. 'GMT' : 'gmt',
  739. 'PGeo' : 'mdb',
  740. 'XPlane' : 'dat',
  741. 'AVCBin' : 'adf',
  742. 'AVCE00' : 'e00',
  743. 'DXF' : 'dxf',
  744. 'Geoconcept' : 'gxt',
  745. 'GeoRSS' : 'xml',
  746. 'GPSTrackMaker' : 'gtm',
  747. 'VFK' : 'vfk'
  748. }
  749. try:
  750. return formatToExt[name]
  751. except KeyError:
  752. return ''
  753. class GdalSelect(wx.Panel):
  754. def __init__(self, parent, panel, ogr = False,
  755. defSource = 'file',
  756. sources = [_("File"), _("Directory"),
  757. _("Database"), _("Protocol")],
  758. envHandler = None):
  759. """!Widget for selecting GDAL/OGR datasource, format
  760. @param parent parent window
  761. @param ogr use OGR selector instead of GDAL
  762. """
  763. self.parent = parent
  764. wx.Panel.__init__(self, parent = panel, id = wx.ID_ANY)
  765. self.inputBox = wx.StaticBox(parent = self, id=wx.ID_ANY,
  766. label=" %s " % _("Source name"))
  767. # source type
  768. self.source = wx.RadioBox(parent = self, id = wx.ID_ANY,
  769. label = _('Source type'),
  770. style = wx.RA_SPECIFY_COLS,
  771. choices = sources)
  772. self.source.SetSelection(0)
  773. self.source.Bind(wx.EVT_RADIOBOX, self.OnSetType)
  774. # dsn widgets
  775. if not ogr:
  776. filemask = 'GeoTIFF (*.tif)|*.tif'
  777. else:
  778. filemask = 'ESRI Shapefile (*.shp)|*.shp'
  779. dsnFile = filebrowse.FileBrowseButton(parent=self, id=wx.ID_ANY,
  780. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  781. dialogTitle=_('Choose input file'),
  782. buttonText=_('Browse'),
  783. startDirectory=os.getcwd(),
  784. changeCallback=self.OnSetDsn,
  785. fileMask=filemask)
  786. dsnFile.Hide()
  787. dsnDir = filebrowse.DirBrowseButton(parent=self, id=wx.ID_ANY,
  788. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  789. dialogTitle=_('Choose input directory'),
  790. buttonText=_('Browse'),
  791. startDirectory=os.getcwd(),
  792. changeCallback=self.OnSetDsn)
  793. dsnDir.Hide()
  794. dsnDbFile = filebrowse.FileBrowseButton(parent=self, id=wx.ID_ANY,
  795. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  796. dialogTitle=_('Choose file'),
  797. buttonText=_('Browse'),
  798. startDirectory=os.getcwd(),
  799. changeCallback=self.OnSetDsn)
  800. dsnDbFile.Hide()
  801. dsnDbText = wx.TextCtrl(parent = self, id = wx.ID_ANY)
  802. dsnDbText.Hide()
  803. dsnDbText.Bind(wx.EVT_TEXT, self.OnSetDsn)
  804. dsnDbChoice = wx.Choice(parent = self, id = wx.ID_ANY)
  805. dsnDbChoice.Hide()
  806. dsnDbChoice.Bind(wx.EVT_CHOICE, self.OnSetDsn)
  807. dsnPro = wx.TextCtrl(parent = self, id = wx.ID_ANY)
  808. dsnPro.Hide()
  809. dsnPro.Bind(wx.EVT_TEXT, self.OnSetDsn)
  810. # format
  811. self.format = FormatSelect(parent = self,
  812. ogr = ogr)
  813. self.format.Bind(wx.EVT_CHOICE, self.OnSetFormat)
  814. if ogr:
  815. fType = 'ogr'
  816. else:
  817. fType = 'gdal'
  818. self.input = { 'file' : [_("File:"),
  819. dsnFile,
  820. globalvar.formats[fType]['file']],
  821. 'dir' : [_("Directory:"),
  822. dsnDir,
  823. globalvar.formats[fType]['file']],
  824. 'db' : [_("Database:"),
  825. dsnDbFile,
  826. globalvar.formats[fType]['database']],
  827. 'pro' : [_("Protocol:"),
  828. dsnPro,
  829. globalvar.formats[fType]['protocol']],
  830. 'db-win' : { 'file' : dsnDbFile,
  831. 'text' : dsnDbText,
  832. 'choice' : dsnDbChoice },
  833. }
  834. self.dsnType = defSource
  835. self.input[self.dsnType][1].Show()
  836. self.format.SetItems(self.input[self.dsnType][2])
  837. if not ogr:
  838. self.format.SetStringSelection('GeoTIFF')
  839. else:
  840. self.format.SetStringSelection('ESRI Shapefile')
  841. self.dsnText = wx.StaticText(parent = self, id = wx.ID_ANY,
  842. label = self.input[self.dsnType][0],
  843. size = (75, -1))
  844. self.formatText = wx.StaticText(parent = self, id = wx.ID_ANY,
  845. label = _("Format:"))
  846. self._layout()
  847. def _layout(self):
  848. """!Layout"""
  849. mainSizer = wx.BoxSizer(wx.VERTICAL)
  850. inputSizer = wx.StaticBoxSizer(self.inputBox, wx.HORIZONTAL)
  851. self.dsnSizer = wx.GridBagSizer(vgap=3, hgap=3)
  852. self.dsnSizer.AddGrowableCol(1)
  853. self.dsnSizer.Add(item=self.dsnText,
  854. flag=wx.ALIGN_CENTER_VERTICAL,
  855. pos = (0, 0))
  856. self.dsnSizer.Add(item=self.input[self.dsnType][1],
  857. flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  858. pos = (0, 1))
  859. self.dsnSizer.Add(item=self.formatText,
  860. flag=wx.ALIGN_CENTER_VERTICAL,
  861. pos = (1, 0))
  862. self.dsnSizer.Add(item=self.format,
  863. pos = (1, 1))
  864. inputSizer.Add(item=self.dsnSizer, proportion=1,
  865. flag=wx.EXPAND | wx.ALL)
  866. mainSizer.Add(item=self.source, proportion=0,
  867. flag=wx.ALL | wx.EXPAND, border=5)
  868. mainSizer.Add(item=inputSizer, proportion=0,
  869. flag=wx.ALL | wx.EXPAND, border=5)
  870. self.SetSizer(mainSizer)
  871. mainSizer.Fit(self)
  872. def OnSetType(self, event):
  873. """!Datasource type changed"""
  874. sel = event.GetSelection()
  875. win = self.input[self.dsnType][1]
  876. self.dsnSizer.Remove(win)
  877. win.Hide()
  878. if sel == 0: # file
  879. self.dsnType = 'file'
  880. format = self.input[self.dsnType][2][0]
  881. try:
  882. ext = self.format.GetExtension(format)
  883. if not ext:
  884. raise KeyError
  885. format += ' (*.%s)|*.%s' % (ext, ext)
  886. except KeyError:
  887. format += ' (*.*)|*.*'
  888. win = filebrowse.FileBrowseButton(parent=self, id=wx.ID_ANY,
  889. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  890. dialogTitle=_('Choose input file'),
  891. buttonText=_('Browse'),
  892. startDirectory=os.getcwd(),
  893. changeCallback=self.OnSetDsn,
  894. fileMask = format)
  895. self.input[self.dsnType][1] = win
  896. elif sel == 1: # directory
  897. self.dsnType = 'dir'
  898. elif sel == 2: # database
  899. self.dsnType = 'db'
  900. elif sel == 3: # protocol
  901. self.dsnType = 'pro'
  902. # if self.importType != 'dxf':
  903. # self.dsnSizer.Add(item=self.formatText,
  904. # flag=wx.ALIGN_CENTER_VERTICAL)
  905. win = self.input[self.dsnType][1]
  906. self.dsnSizer.Add(item=self.input[self.dsnType][1],
  907. flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  908. pos = (0, 1))
  909. win.SetValue('')
  910. if self.parent.GetName() == 'MultiImportDialog':
  911. self.parent.list.DeleteAllItems()
  912. win.Show()
  913. self.dsnText.SetLabel(self.input[self.dsnType][0])
  914. self.format.SetItems(self.input[self.dsnType][2])
  915. self.format.SetSelection(0)
  916. self.dsnSizer.Layout()
  917. def OnSetDsn(self, event):
  918. """!Input DXF file/OGR dsn defined, update list of layer widget"""
  919. path = event.GetString()
  920. if not path:
  921. return
  922. data = list()
  923. # if self.importType == 'dxf':
  924. # ret = gcmd.RunCommand('v.in.dxf',
  925. # quiet = True,
  926. # parent = self,
  927. # read = True,
  928. # flags = 'l',
  929. # input = path)
  930. # if not ret:
  931. # self.list.LoadData()
  932. # self.btn_run.Enable(False)
  933. # return
  934. # for line in ret.splitlines():
  935. # layerId = line.split(':')[0].split(' ')[1]
  936. # layerName = line.split(':')[1].strip()
  937. # grassName = utils.GetValidLayerName(layerName)
  938. # data.append((layerId, layerName.strip(), grassName.strip()))
  939. layerId = 1
  940. if self.format.GetStringSelection() == 'PostgreSQL':
  941. dsn = 'PG:dbname=%s' % self.input[self.dsnType][1].GetStringSelection()
  942. else:
  943. dsn = self.input[self.dsnType][1].GetValue()
  944. if self.dsnType == 'file':
  945. baseName = os.path.basename(dsn)
  946. grassName = utils.GetValidLayerName(baseName.split('.', -1)[0])
  947. data.append((layerId, baseName, grassName))
  948. elif self.dsnType == 'dir':
  949. try:
  950. ext = self.format.GetExtension(self.format.GetStringSelection())
  951. except KeyError:
  952. ext = ''
  953. for file in glob.glob(os.path.join(dsn, "*.%s") % ext):
  954. baseName = os.path.basename(file)
  955. grassName = utils.GetValidLayerName(baseName.split('.', -1)[0])
  956. data.append((layerId, baseName, grassName))
  957. layerId += 1
  958. elif self.dsnType == 'db':
  959. ret = gcmd.RunCommand('v.in.ogr',
  960. quiet = True,
  961. parent = self,
  962. read = True,
  963. flags = 'l',
  964. dsn = dsn)
  965. if not ret:
  966. self.list.LoadData()
  967. self.btn_run.Enable(False)
  968. return
  969. layerId = 1
  970. for line in ret.splitlines():
  971. layerName = line.strip()
  972. grassName = utils.GetValidLayerName(layerName)
  973. data.append((layerId, layerName.strip(), grassName.strip()))
  974. layerId += 1
  975. if self.parent.GetName() == 'MultiImportDialog':
  976. self.parent.list.LoadData(data)
  977. if len(data) > 0:
  978. self.parent.btn_run.Enable(True)
  979. else:
  980. self.parent.btn_run.Enable(False)
  981. def OnSetFormat(self, event):
  982. """!Format changed"""
  983. if self.dsnType not in ['file', 'db']:
  984. return
  985. win = self.input[self.dsnType][1]
  986. self.dsnSizer.Remove(win)
  987. if self.dsnType == 'file':
  988. win.Destroy()
  989. else: # database
  990. win.Hide()
  991. format = event.GetString()
  992. if self.dsnType == 'file':
  993. try:
  994. ext = self.format.GetExtension(format)
  995. if not ext:
  996. raise KeyError
  997. format += ' (*.%s)|*.%s' % (ext, ext)
  998. except KeyError:
  999. format += ' (*.*)|*.*'
  1000. win = filebrowse.FileBrowseButton(parent=self, id=wx.ID_ANY,
  1001. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  1002. dialogTitle=_('Choose file'),
  1003. buttonText=_('Browse'),
  1004. startDirectory=os.getcwd(),
  1005. changeCallback=self.OnSetDsn,
  1006. fileMask = format)
  1007. else: # database
  1008. if format == 'SQLite':
  1009. win = self.input['db-win']['file']
  1010. elif format == 'PostgreSQL':
  1011. if grass.find_program('psql'):
  1012. win = self.input['db-win']['choice']
  1013. if not win.GetItems():
  1014. p = grass.Popen(['psql', '-ltA'], stdout = grass.PIPE)
  1015. ret = p.communicate()[0]
  1016. if ret:
  1017. db = list()
  1018. for line in ret.splitlines():
  1019. sline = line.split('|')
  1020. if len(sline) < 2:
  1021. continue
  1022. dbname = sline[0]
  1023. if dbname:
  1024. db.append(dbname)
  1025. win.SetItems(db)
  1026. else:
  1027. win = self.input['db-win']['text']
  1028. else:
  1029. win = self.input['db-win']['text']
  1030. self.input[self.dsnType][1] = win
  1031. if not win.IsShown():
  1032. win.Show()
  1033. self.dsnSizer.Add(item=self.input[self.dsnType][1],
  1034. flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
  1035. pos = (0, 1))
  1036. self.dsnSizer.Layout()
  1037. def GetType(self):
  1038. """!Get source type"""
  1039. return self.dsnType
  1040. def GetDsn(self):
  1041. """!Get DSN"""
  1042. if self.format.GetStringSelection() == 'PostgreSQL':
  1043. return 'PG:dbname=%s' % self.input[self.dsnType][1].GetStringSelection()
  1044. return self.input[self.dsnType][1].GetValue()
  1045. def SetDsnHandler(self):
  1046. """!Get DSN"""
  1047. def GetFormatExt(self):
  1048. """!Get format extension"""
  1049. return self.format.GetExtension(self.format.GetStringSelection())