gdialogs.py 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733
  1. """!
  2. @package gdialogs.py
  3. @brief Various dialogs used in wxGUI.
  4. List of classes:
  5. - ElementDialog
  6. - LocationDialog
  7. - MapsetDialog
  8. - NewVectorDialog
  9. - SavedRegion
  10. - DecorationDialog
  11. - TextLayerDialog
  12. - AddMapLayersDialog
  13. - ImportDialog
  14. - GdalImportDialog
  15. - DxfImportDialog
  16. - LayersList (used by MultiImport)
  17. - SetOpacityDialog
  18. - StaticWrapText
  19. - ImageSizeDialog
  20. - SqlQueryFrame
  21. (C) 2008-2011 by the GRASS Development Team
  22. This program is free software under the GNU General Public
  23. License (>=v2). Read the file COPYING that comes with GRASS
  24. for details.
  25. @author Martin Landa <landa.martin gmail.com>
  26. """
  27. import os
  28. import sys
  29. import re
  30. import wx
  31. import wx.lib.filebrowsebutton as filebrowse
  32. import wx.lib.mixins.listctrl as listmix
  33. from grass.script import core as grass
  34. from grass.script import task as gtask
  35. import gcmd
  36. import globalvar
  37. import gselect
  38. import menuform
  39. import utils
  40. from preferences import globalSettings as UserSettings
  41. class ElementDialog(wx.Dialog):
  42. """!General dialog to choose given element (location, mapset, vector map, etc.)"""
  43. def __init__(self, parent, title, label, id = wx.ID_ANY,
  44. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  45. **kwargs):
  46. wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
  47. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  48. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  49. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  50. self.btnOK.SetDefault()
  51. self.btnOK.Enable(False)
  52. self.label = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  53. label = label)
  54. self.element = None # must be defined
  55. self.__Layout()
  56. def PostInit(self):
  57. self.element.SetFocus()
  58. self.element.Bind(wx.EVT_TEXT, self.OnElement)
  59. def OnElement(self, event):
  60. """!Name for vector map layer given"""
  61. if len(event.GetString()) > 0:
  62. self.btnOK.Enable(True)
  63. else:
  64. self.btnOK.Enable(False)
  65. def __Layout(self):
  66. """!Do layout"""
  67. self.sizer = wx.BoxSizer(wx.VERTICAL)
  68. self.dataSizer = wx.BoxSizer(wx.VERTICAL)
  69. self.dataSizer.Add(self.label, proportion=0,
  70. flag=wx.ALL, border=1)
  71. # buttons
  72. btnSizer = wx.StdDialogButtonSizer()
  73. btnSizer.AddButton(self.btnCancel)
  74. btnSizer.AddButton(self.btnOK)
  75. btnSizer.Realize()
  76. self.sizer.Add(item=self.dataSizer, proportion=1,
  77. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  78. self.sizer.Add(item=btnSizer, proportion=0,
  79. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  80. def GetElement(self):
  81. """!Return (mapName, overwrite)"""
  82. return self.element.GetValue()
  83. class LocationDialog(ElementDialog):
  84. """!Dialog used to select location"""
  85. def __init__(self, parent, title = _("Select GRASS location and mapset"), id = wx.ID_ANY):
  86. ElementDialog.__init__(self, parent, title, label = _("Name of GRASS location:"))
  87. self.element = gselect.LocationSelect(parent = self.panel, id = wx.ID_ANY,
  88. size = globalvar.DIALOG_GSELECT_SIZE)
  89. self.element1 = gselect.MapsetSelect(parent = self.panel, id = wx.ID_ANY,
  90. size = globalvar.DIALOG_GSELECT_SIZE,
  91. setItems = False)
  92. self.PostInit()
  93. self.__Layout()
  94. self.SetMinSize(self.GetSize())
  95. def __Layout(self):
  96. """!Do layout"""
  97. self.dataSizer.Add(self.element, proportion=0,
  98. flag=wx.EXPAND | wx.ALL, border=1)
  99. self.dataSizer.Add(wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  100. label = _("Name of mapset:")), proportion=0,
  101. flag=wx.EXPAND | wx.ALL, border=1)
  102. self.dataSizer.Add(self.element1, proportion=0,
  103. flag=wx.EXPAND | wx.ALL, border=1)
  104. self.panel.SetSizer(self.sizer)
  105. self.sizer.Fit(self)
  106. def OnElement(self, event):
  107. """!Select mapset given location name"""
  108. location = event.GetString()
  109. if location:
  110. dbase = grass.gisenv()['GISDBASE']
  111. self.element1.SetItems(utils.GetListOfMapsets(dbase, location, selectable = True))
  112. self.element1.SetSelection(0)
  113. mapset = self.element1.GetStringSelection()
  114. if location and mapset:
  115. self.btnOK.Enable(True)
  116. else:
  117. self.btnOK.Enable(False)
  118. def GetValues(self):
  119. """!Get location, mapset"""
  120. return (self.GetElement(), self.element1.GetStringSelection())
  121. class MapsetDialog(ElementDialog):
  122. """!Dialog used to select mapset"""
  123. def __init__(self, parent, title = _("Select mapset in GRASS location"),
  124. location = None, id = wx.ID_ANY):
  125. ElementDialog.__init__(self, parent, title, label = _("Name of mapset:"))
  126. if location:
  127. self.SetTitle(self.GetTitle() + ' <%s>' % location)
  128. else:
  129. self.SetTitle(self.GetTitle() + ' <%s>' % grass.gisenv()['LOCATION_NAME'])
  130. self.element = gselect.MapsetSelect(parent = self.panel, id = wx.ID_ANY,
  131. size = globalvar.DIALOG_GSELECT_SIZE)
  132. self.PostInit()
  133. self.__Layout()
  134. self.SetMinSize(self.GetSize())
  135. def __Layout(self):
  136. """!Do layout"""
  137. self.dataSizer.Add(self.element, proportion=0,
  138. flag=wx.EXPAND | wx.ALL, border=1)
  139. self.panel.SetSizer(self.sizer)
  140. self.sizer.Fit(self)
  141. def GetMapset(self):
  142. return self.GetElement()
  143. class NewVectorDialog(ElementDialog):
  144. """!Dialog for creating new vector map"""
  145. def __init__(self, parent, id, title, disableAdd=False, disableTable=False,
  146. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  147. ElementDialog.__init__(self, parent, title, label = _("Name for new vector map:"))
  148. self.element = gselect.Select(parent=self.panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  149. type='vector', mapsets=[grass.gisenv()['MAPSET'],])
  150. self.table = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  151. label = _("Create attribute table"))
  152. self.table.SetValue(True)
  153. if disableTable:
  154. self.table.Enable(False)
  155. self.addbox = wx.CheckBox(parent = self.panel,
  156. label = _('Add created map into layer tree'), style = wx.NO_BORDER)
  157. if disableAdd:
  158. self.addbox.SetValue(True)
  159. self.addbox.Enable(False)
  160. else:
  161. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  162. self.PostInit()
  163. self.__Layout()
  164. self.SetMinSize(self.GetSize())
  165. def OnMapName(self, event):
  166. """!Name for vector map layer given"""
  167. self.OnElement(event)
  168. def __Layout(self):
  169. """!Do layout"""
  170. self.dataSizer.Add(self.element, proportion=0,
  171. flag=wx.EXPAND | wx.ALL, border=1)
  172. self.dataSizer.Add(self.table, proportion=0,
  173. flag=wx.EXPAND | wx.ALL, border=1)
  174. self.dataSizer.AddSpacer(5)
  175. self.dataSizer.Add(item=self.addbox, proportion=0,
  176. flag=wx.EXPAND | wx.ALL, border=1)
  177. self.panel.SetSizer(self.sizer)
  178. self.sizer.Fit(self)
  179. def GetName(self):
  180. """!Return (mapName, overwrite)"""
  181. return self.GetElement().split('@', 1)[0]
  182. def CreateNewVector(parent, cmd, title=_('Create new vector map'),
  183. exceptMap=None, log=None, disableAdd=False, disableTable=False):
  184. """!Create new vector map layer
  185. @cmd cmd (prog, **kwargs)
  186. @return tuple (name of create vector map, add to layer tree)
  187. @return None of failure
  188. """
  189. dlg = NewVectorDialog(parent, wx.ID_ANY, title,
  190. disableAdd, disableTable)
  191. if dlg.ShowModal() == wx.ID_OK:
  192. outmap = dlg.GetName()
  193. if outmap == exceptMap:
  194. wx.MessageBox(parent=parent,
  195. message=_("Unable to create vector map <%s>.") % outmap,
  196. caption=_("Error"),
  197. style=wx.ID_OK | wx.ICON_ERROR | wx.CENTRE)
  198. return (None, None)
  199. if outmap == '': # should not happen
  200. return (None, None)
  201. cmd[1][cmd[2]] = outmap
  202. try:
  203. listOfVectors = grass.list_grouped('vect')[grass.gisenv()['MAPSET']]
  204. except KeyError:
  205. listOfVectors = []
  206. overwrite = False
  207. if not UserSettings.Get(group='cmd', key='overwrite', subkey='enabled') and \
  208. outmap in listOfVectors:
  209. dlgOw = wx.MessageDialog(parent, message=_("Vector map <%s> already exists "
  210. "in the current mapset. "
  211. "Do you want to overwrite it?") % outmap,
  212. caption=_("Overwrite?"),
  213. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  214. if dlgOw.ShowModal() == wx.ID_YES:
  215. overwrite = True
  216. else:
  217. dlgOw.Destroy()
  218. return (None, None)
  219. if UserSettings.Get(group='cmd', key='overwrite', subkey='enabled') is True:
  220. overwrite = True
  221. try:
  222. gcmd.RunCommand(prog = cmd[0],
  223. overwrite = overwrite,
  224. **cmd[1])
  225. except gcmd.GException, e:
  226. gcmd.GError(parent = self,
  227. message = e.value)
  228. return (None, None)
  229. #
  230. # create attribute table
  231. #
  232. if dlg.table.IsEnabled() and dlg.table.IsChecked():
  233. key = UserSettings.Get(group='atm', key='keycolumn', subkey='value')
  234. sql = 'CREATE TABLE %s (%s INTEGER)' % (outmap, key)
  235. gcmd.RunCommand('db.connect',
  236. flags = 'c')
  237. gcmd.RunCommand('db.execute',
  238. quiet = True,
  239. parent = parent,
  240. input = '-',
  241. stdin = sql)
  242. gcmd.RunCommand('v.db.connect',
  243. quiet = True,
  244. parent = parent,
  245. map = outmap,
  246. table = outmap,
  247. key = key,
  248. layer = '1')
  249. # return fully qualified map name
  250. if '@' not in outmap:
  251. outmap += '@' + grass.gisenv()['MAPSET']
  252. if log:
  253. log.WriteLog(_("New vector map <%s> created") % outmap)
  254. return (outmap, dlg.addbox.IsChecked())
  255. return (None, dlg.addbox.IsChecked())
  256. class SavedRegion(wx.Dialog):
  257. def __init__(self, parent, id = wx.ID_ANY, title="", loadsave='load',
  258. **kwargs):
  259. """!Loading and saving of display extents to saved region file
  260. @param loadsave load or save region?
  261. """
  262. wx.Dialog.__init__(self, parent, id, title, **kwargs)
  263. self.loadsave = loadsave
  264. self.wind = ''
  265. sizer = wx.BoxSizer(wx.VERTICAL)
  266. box = wx.BoxSizer(wx.HORIZONTAL)
  267. label = wx.StaticText(parent=self, id=wx.ID_ANY)
  268. box.Add(item=label, proportion=0, flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
  269. if loadsave == 'load':
  270. label.SetLabel(_("Load region:"))
  271. selection = gselect.Select(parent=self, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  272. type='windows')
  273. elif loadsave == 'save':
  274. label.SetLabel(_("Save region:"))
  275. selection = gselect.Select(parent=self, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  276. type='windows', mapsets = [grass.gisenv()['MAPSET']])
  277. box.Add(item=selection, proportion=0, flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
  278. selection.SetFocus()
  279. selection.Bind(wx.EVT_TEXT, self.OnRegion)
  280. sizer.Add(item=box, proportion=0, flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL,
  281. border=5)
  282. line = wx.StaticLine(parent=self, id=wx.ID_ANY, size=(20, -1), style=wx.LI_HORIZONTAL)
  283. sizer.Add(item=line, proportion=0,
  284. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border=5)
  285. btnsizer = wx.StdDialogButtonSizer()
  286. btn = wx.Button(parent = self, id = wx.ID_OK)
  287. btn.SetDefault()
  288. btnsizer.AddButton(btn)
  289. btn = wx.Button(parent = self, id = wx.ID_CANCEL)
  290. btnsizer.AddButton(btn)
  291. btnsizer.Realize()
  292. sizer.Add(item=btnsizer, proportion=0, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  293. self.SetSizer(sizer)
  294. sizer.Fit(self)
  295. self.Layout()
  296. def OnRegion(self, event):
  297. self.wind = event.GetString()
  298. class DecorationDialog(wx.Dialog):
  299. """
  300. Controls setting options and displaying/hiding map overlay decorations
  301. """
  302. def __init__(self, parent, ovlId, title, cmd, name=None,
  303. pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE,
  304. checktxt='', ctrltxt=''):
  305. wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style)
  306. self.ovlId = ovlId # PseudoDC id
  307. self.cmd = cmd
  308. self.name = name # overlay name
  309. self.parent = parent # MapFrame
  310. sizer = wx.BoxSizer(wx.VERTICAL)
  311. box = wx.BoxSizer(wx.HORIZONTAL)
  312. self.chkbox = wx.CheckBox(parent=self, id=wx.ID_ANY, label=checktxt)
  313. if self.parent.Map.GetOverlay(self.ovlId) is None:
  314. self.chkbox.SetValue(True)
  315. else:
  316. self.chkbox.SetValue(self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive())
  317. box.Add(item=self.chkbox, proportion=0,
  318. flag=wx.ALIGN_CENTRE|wx.ALL, border=5)
  319. sizer.Add(item=box, proportion=0,
  320. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border=5)
  321. box = wx.BoxSizer(wx.HORIZONTAL)
  322. optnbtn = wx.Button(parent=self, id=wx.ID_ANY, label=_("Set options"))
  323. box.Add(item=optnbtn, proportion=0, flag=wx.ALIGN_CENTRE|wx.ALL, border=5)
  324. sizer.Add(item=box, proportion=0,
  325. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border=5)
  326. box = wx.BoxSizer(wx.HORIZONTAL)
  327. label = wx.StaticText(parent=self, id=wx.ID_ANY,
  328. label=_("Drag %s with mouse in pointer mode to position.\n"
  329. "Double-click to change options." % ctrltxt))
  330. if self.name == 'legend':
  331. label.SetLabel(label.GetLabel() + _('\nDefine raster map name for legend in '
  332. 'properties dialog.'))
  333. box.Add(item=label, proportion=0,
  334. flag=wx.ALIGN_CENTRE|wx.ALL, border=5)
  335. sizer.Add(item=box, proportion=0,
  336. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border=5)
  337. line = wx.StaticLine(parent=self, id=wx.ID_ANY, size=(20,-1), style=wx.LI_HORIZONTAL)
  338. sizer.Add(item=line, proportion=0,
  339. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border=5)
  340. # buttons
  341. btnsizer = wx.StdDialogButtonSizer()
  342. self.btnOK = wx.Button(parent=self, id=wx.ID_OK)
  343. self.btnOK.SetDefault()
  344. if self.name == 'legend':
  345. self.btnOK.Enable(False)
  346. btnsizer.AddButton(self.btnOK)
  347. btnCancel = wx.Button(parent=self, id=wx.ID_CANCEL)
  348. btnsizer.AddButton(btnCancel)
  349. btnsizer.Realize()
  350. sizer.Add(item=btnsizer, proportion=0,
  351. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  352. #
  353. # bindings
  354. #
  355. self.Bind(wx.EVT_BUTTON, self.OnOptions, optnbtn)
  356. self.Bind(wx.EVT_BUTTON, self.OnCancel, btnCancel)
  357. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  358. self.SetSizer(sizer)
  359. sizer.Fit(self)
  360. # create overlay if doesn't exist
  361. self._CreateOverlay()
  362. if len(self.parent.MapWindow.overlays[self.ovlId]['cmd']) > 1:
  363. mapName, found = utils.GetLayerNameFromCmd(self.parent.MapWindow.overlays[self.ovlId]['cmd'])
  364. if self.parent.MapWindow.overlays[self.ovlId]['propwin'] is None and mapName:
  365. # build properties dialog
  366. menuform.GUI(parent = self.parent, show = False).ParseCommand(cmd=self.cmd,
  367. completed=(self.GetOptData, self.name, ''))
  368. if found:
  369. # enable 'OK' button
  370. self.btnOK.Enable()
  371. if name == 'legend':
  372. # set title
  373. self.SetTitle(_('Legend of raster map <%s>') % \
  374. mapName)
  375. def _CreateOverlay(self):
  376. if not self.parent.Map.GetOverlay(self.ovlId):
  377. overlay = self.parent.Map.AddOverlay(id=self.ovlId, type=self.name,
  378. command=self.cmd,
  379. l_active=False, l_render=False, l_hidden=True)
  380. prop = { 'layer' : overlay,
  381. 'params' : None,
  382. 'propwin' : None,
  383. 'cmd' : self.cmd,
  384. 'coords': (10, 10),
  385. 'pdcType': 'image' }
  386. self.parent.MapWindow2D.overlays[self.ovlId] = prop
  387. if self.parent.MapWindow3D:
  388. self.parent.MapWindow3D.overlays[self.ovlId] = prop
  389. else:
  390. if self.parent.MapWindow.overlays[self.ovlId]['propwin'] == None:
  391. return
  392. self.parent.MapWindow.overlays[self.ovlId]['propwin'].get_dcmd = self.GetOptData
  393. def OnOptions(self, event):
  394. """ self.SetSizer(sizer)
  395. sizer.Fit(self)
  396. Sets option for decoration map overlays
  397. """
  398. if self.parent.MapWindow.overlays[self.ovlId]['propwin'] is None:
  399. # build properties dialog
  400. menuform.GUI(parent = self.parent).ParseCommand(cmd=self.cmd,
  401. completed=(self.GetOptData, self.name, ''))
  402. else:
  403. if self.parent.MapWindow.overlays[self.ovlId]['propwin'].IsShown():
  404. self.parent.MapWindow.overlays[self.ovlId]['propwin'].SetFocus()
  405. else:
  406. self.parent.MapWindow.overlays[self.ovlId]['propwin'].Show()
  407. def OnCancel(self, event):
  408. """!Cancel dialog"""
  409. self.parent.dialogs['barscale'] = None
  410. self.Destroy()
  411. def OnOK(self, event):
  412. """!Button 'OK' pressed"""
  413. # enable or disable overlay
  414. self.parent.Map.GetOverlay(self.ovlId).SetActive(self.chkbox.IsChecked())
  415. # update map
  416. if self.parent.MapWindow.parent.toolbars['nviz']:
  417. self.parent.MapWindow.UpdateOverlays()
  418. self.parent.MapWindow.UpdateMap()
  419. # close dialog
  420. self.OnCancel(None)
  421. def GetOptData(self, dcmd, layer, params, propwin):
  422. """!Process decoration layer data"""
  423. # update layer data
  424. if params:
  425. self.parent.MapWindow.overlays[self.ovlId]['params'] = params
  426. if dcmd:
  427. self.parent.MapWindow.overlays[self.ovlId]['cmd'] = dcmd
  428. self.parent.MapWindow.overlays[self.ovlId]['propwin'] = propwin
  429. # change parameters for item in layers list in render.Map
  430. # "Use mouse..." (-m) flag causes GUI freeze and is pointless here, trac #119
  431. try:
  432. self.parent.MapWindow.overlays[self.ovlId]['cmd'].remove('-m')
  433. except ValueError:
  434. pass
  435. self.parent.Map.ChangeOverlay(id=self.ovlId, type=self.name,
  436. command=self.parent.MapWindow.overlays[self.ovlId]['cmd'],
  437. l_active=self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive(),
  438. l_render=False, l_hidden=True)
  439. if self.name == 'legend':
  440. if params and not self.btnOK.IsEnabled():
  441. self.btnOK.Enable()
  442. class TextLayerDialog(wx.Dialog):
  443. """
  444. Controls setting options and displaying/hiding map overlay decorations
  445. """
  446. def __init__(self, parent, ovlId, title, name='text',
  447. pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE):
  448. wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style)
  449. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  450. self.ovlId = ovlId
  451. self.parent = parent
  452. if self.ovlId in self.parent.MapWindow.textdict.keys():
  453. self.currText = self.parent.MapWindow.textdict[self.ovlId]['text']
  454. self.currFont = self.parent.MapWindow.textdict[self.ovlId]['font']
  455. self.currClr = self.parent.MapWindow.textdict[self.ovlId]['color']
  456. self.currRot = self.parent.MapWindow.textdict[self.ovlId]['rotation']
  457. self.currCoords = self.parent.MapWindow.textdict[self.ovlId]['coords']
  458. else:
  459. self.currClr = wx.BLACK
  460. self.currText = ''
  461. self.currFont = self.GetFont()
  462. self.currRot = 0.0
  463. self.currCoords = [10, 10, 10, 10]
  464. self.sizer = wx.BoxSizer(wx.VERTICAL)
  465. box = wx.GridBagSizer(vgap=5, hgap=5)
  466. # show/hide
  467. self.chkbox = wx.CheckBox(parent=self, id=wx.ID_ANY, \
  468. label='Show text object')
  469. if self.parent.Map.GetOverlay(self.ovlId) is None:
  470. self.chkbox.SetValue(True)
  471. else:
  472. self.chkbox.SetValue(self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive())
  473. box.Add(item=self.chkbox, span=(1,2),
  474. flag=wx.ALIGN_LEFT|wx.ALL, border=5,
  475. pos=(0, 0))
  476. # text entry
  477. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Enter text:"))
  478. box.Add(item=label,
  479. flag=wx.ALIGN_CENTER_VERTICAL,
  480. pos=(1, 0))
  481. self.textentry = ExpandoTextCtrl(parent=self, id=wx.ID_ANY, value="", size=(300,-1))
  482. self.textentry.SetFont(self.currFont)
  483. self.textentry.SetForegroundColour(self.currClr)
  484. self.textentry.SetValue(self.currText)
  485. # get rid of unneeded scrollbar when text box first opened
  486. self.textentry.SetClientSize((300,-1))
  487. box.Add(item=self.textentry,
  488. pos=(1, 1))
  489. # rotation
  490. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Rotation:"))
  491. box.Add(item=label,
  492. flag=wx.ALIGN_CENTER_VERTICAL,
  493. pos=(2, 0))
  494. self.rotation = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="", pos=(30, 50),
  495. size=(75,-1), style=wx.SP_ARROW_KEYS)
  496. self.rotation.SetRange(-360, 360)
  497. self.rotation.SetValue(int(self.currRot))
  498. box.Add(item=self.rotation,
  499. flag=wx.ALIGN_RIGHT,
  500. pos=(2, 1))
  501. # font
  502. fontbtn = wx.Button(parent=self, id=wx.ID_ANY, label=_("Set font"))
  503. box.Add(item=fontbtn,
  504. flag=wx.ALIGN_RIGHT,
  505. pos=(3, 1))
  506. self.sizer.Add(item=box, proportion=1,
  507. flag=wx.ALL, border=10)
  508. # note
  509. box = wx.BoxSizer(wx.HORIZONTAL)
  510. label = wx.StaticText(parent=self, id=wx.ID_ANY,
  511. label=_("Drag text with mouse in pointer mode "
  512. "to position.\nDouble-click to change options"))
  513. box.Add(item=label, proportion=0,
  514. flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
  515. self.sizer.Add(item=box, proportion=0,
  516. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border=5)
  517. line = wx.StaticLine(parent=self, id=wx.ID_ANY,
  518. size=(20,-1), style=wx.LI_HORIZONTAL)
  519. self.sizer.Add(item=line, proportion=0,
  520. flag=wx.EXPAND | wx.ALIGN_CENTRE | wx.ALL, border=5)
  521. btnsizer = wx.StdDialogButtonSizer()
  522. btn = wx.Button(parent=self, id=wx.ID_OK)
  523. btn.SetDefault()
  524. btnsizer.AddButton(btn)
  525. btn = wx.Button(parent=self, id=wx.ID_CANCEL)
  526. btnsizer.AddButton(btn)
  527. btnsizer.Realize()
  528. self.sizer.Add(item=btnsizer, proportion=0,
  529. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  530. self.SetSizer(self.sizer)
  531. self.sizer.Fit(self)
  532. # bindings
  533. self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnRefit, self.textentry)
  534. self.Bind(wx.EVT_BUTTON, self.OnSelectFont, fontbtn)
  535. self.Bind(wx.EVT_TEXT, self.OnText, self.textentry)
  536. self.Bind(wx.EVT_SPINCTRL, self.OnRotation, self.rotation)
  537. def OnRefit(self, event):
  538. """!Resize text entry to match text"""
  539. self.sizer.Fit(self)
  540. def OnText(self, event):
  541. """!Change text string"""
  542. self.currText = event.GetString()
  543. def OnRotation(self, event):
  544. """!Change rotation"""
  545. self.currRot = event.GetInt()
  546. event.Skip()
  547. def OnSelectFont(self, event):
  548. """!Change font"""
  549. data = wx.FontData()
  550. data.EnableEffects(True)
  551. data.SetColour(self.currClr) # set colour
  552. data.SetInitialFont(self.currFont)
  553. dlg = wx.FontDialog(self, data)
  554. if dlg.ShowModal() == wx.ID_OK:
  555. data = dlg.GetFontData()
  556. self.currFont = data.GetChosenFont()
  557. self.currClr = data.GetColour()
  558. self.textentry.SetFont(self.currFont)
  559. self.textentry.SetForegroundColour(self.currClr)
  560. self.Layout()
  561. dlg.Destroy()
  562. def GetValues(self):
  563. """!Get text properties"""
  564. return { 'text' : self.currText,
  565. 'font' : self.currFont,
  566. 'color' : self.currClr,
  567. 'rotation' : self.currRot,
  568. 'coords' : self.currCoords,
  569. 'active' : self.chkbox.IsChecked() }
  570. class AddMapLayersDialog(wx.Dialog):
  571. """!Add selected map layers (raster, vector) into layer tree"""
  572. def __init__(self, parent, title, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  573. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title, style=style)
  574. self.parent = parent # GMFrame
  575. #
  576. # dialog body
  577. #
  578. self.bodySizer = self.__createDialogBody()
  579. # update list of layer to be loaded
  580. self.map_layers = [] # list of map layers (full list type/mapset)
  581. self.LoadMapLayers(self.layerType.GetStringSelection()[:4],
  582. self.mapset.GetStringSelection())
  583. #
  584. # buttons
  585. #
  586. btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  587. btnOk = wx.Button(parent = self, id = wx.ID_OK, label = _("&Add"))
  588. btnOk.SetDefault()
  589. btnOk.SetToolTipString(_("Add selected map layers to current display"))
  590. #
  591. # sizers & do layout
  592. #
  593. btnSizer = wx.StdDialogButtonSizer()
  594. btnSizer.AddButton(btnCancel)
  595. btnSizer.AddButton(btnOk)
  596. btnSizer.Realize()
  597. mainSizer = wx.BoxSizer(wx.VERTICAL)
  598. mainSizer.Add(item=self.bodySizer, proportion=1,
  599. flag=wx.EXPAND | wx.ALL, border=5)
  600. mainSizer.Add(item=btnSizer, proportion=0,
  601. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  602. self.SetSizer(mainSizer)
  603. mainSizer.Fit(self)
  604. # set dialog min size
  605. self.SetMinSize(self.GetSize())
  606. def __createDialogBody(self):
  607. bodySizer = wx.GridBagSizer(vgap=3, hgap=3)
  608. bodySizer.AddGrowableCol(1)
  609. bodySizer.AddGrowableRow(3)
  610. # layer type
  611. bodySizer.Add(item=wx.StaticText(parent=self, label=_("Map layer type:")),
  612. flag=wx.ALIGN_CENTER_VERTICAL,
  613. pos=(0,0))
  614. self.layerType = wx.Choice(parent=self, id=wx.ID_ANY,
  615. choices=['raster', 'vector'], size=(100,-1))
  616. self.layerType.SetSelection(0)
  617. bodySizer.Add(item=self.layerType,
  618. pos=(0,1))
  619. # select toggle
  620. self.toggle = wx.CheckBox(parent=self, id=wx.ID_ANY,
  621. label=_("Select toggle"))
  622. self.toggle.SetValue(True)
  623. bodySizer.Add(item=self.toggle,
  624. flag=wx.ALIGN_CENTER_VERTICAL,
  625. pos=(0,2))
  626. # mapset filter
  627. bodySizer.Add(item=wx.StaticText(parent=self, label=_("Mapset:")),
  628. flag=wx.ALIGN_CENTER_VERTICAL,
  629. pos=(1,0))
  630. self.mapset = gselect.MapsetSelect(parent = self)
  631. self.mapset.SetStringSelection(grass.gisenv()['MAPSET'])
  632. bodySizer.Add(item=self.mapset,
  633. pos=(1,1), span=(1, 2))
  634. # map name filter
  635. bodySizer.Add(item=wx.StaticText(parent=self, label=_("Filter:")),
  636. flag=wx.ALIGN_CENTER_VERTICAL,
  637. pos=(2,0))
  638. self.filter = wx.TextCtrl(parent=self, id=wx.ID_ANY,
  639. value="",
  640. size=(250,-1))
  641. bodySizer.Add(item=self.filter,
  642. flag=wx.EXPAND,
  643. pos=(2,1), span=(1, 2))
  644. # layer list
  645. bodySizer.Add(item=wx.StaticText(parent=self, label=_("List of maps:")),
  646. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_TOP,
  647. pos=(3,0))
  648. self.layers = wx.CheckListBox(parent=self, id=wx.ID_ANY,
  649. size=(250, 100),
  650. choices=[])
  651. bodySizer.Add(item=self.layers,
  652. flag=wx.EXPAND,
  653. pos=(3,1), span=(1, 2))
  654. # bindings
  655. self.layerType.Bind(wx.EVT_CHOICE, self.OnChangeParams)
  656. self.mapset.Bind(wx.EVT_COMBOBOX, self.OnChangeParams)
  657. self.layers.Bind(wx.EVT_RIGHT_DOWN, self.OnMenu)
  658. self.filter.Bind(wx.EVT_TEXT, self.OnFilter)
  659. self.toggle.Bind(wx.EVT_CHECKBOX, self.OnToggle)
  660. return bodySizer
  661. def LoadMapLayers(self, type, mapset):
  662. """!Load list of map layers
  663. @param type layer type ('raster' or 'vector')
  664. @param mapset mapset name
  665. """
  666. self.map_layers = grass.mlist(type = type, mapset = mapset)
  667. self.layers.Set(self.map_layers)
  668. # check all items by default
  669. for item in range(self.layers.GetCount()):
  670. self.layers.Check(item)
  671. def OnChangeParams(self, event):
  672. """!Filter parameters changed by user"""
  673. # update list of layer to be loaded
  674. self.LoadMapLayers(self.layerType.GetStringSelection()[:4],
  675. self.mapset.GetStringSelection())
  676. event.Skip()
  677. def OnMenu(self, event):
  678. """!Table description area, context menu"""
  679. if not hasattr(self, "popupID1"):
  680. self.popupDataID1 = wx.NewId()
  681. self.popupDataID2 = wx.NewId()
  682. self.popupDataID3 = wx.NewId()
  683. self.Bind(wx.EVT_MENU, self.OnSelectAll, id=self.popupDataID1)
  684. self.Bind(wx.EVT_MENU, self.OnSelectInvert, id=self.popupDataID2)
  685. self.Bind(wx.EVT_MENU, self.OnDeselectAll, id=self.popupDataID3)
  686. # generate popup-menu
  687. menu = wx.Menu()
  688. menu.Append(self.popupDataID1, _("Select all"))
  689. menu.Append(self.popupDataID2, _("Invert selection"))
  690. menu.Append(self.popupDataID3, _("Deselect all"))
  691. self.PopupMenu(menu)
  692. menu.Destroy()
  693. def OnSelectAll(self, event):
  694. """!Select all map layer from list"""
  695. for item in range(self.layers.GetCount()):
  696. self.layers.Check(item, True)
  697. def OnSelectInvert(self, event):
  698. """!Invert current selection"""
  699. for item in range(self.layers.GetCount()):
  700. if self.layers.IsChecked(item):
  701. self.layers.Check(item, False)
  702. else:
  703. self.layers.Check(item, True)
  704. def OnDeselectAll(self, event):
  705. """!Select all map layer from list"""
  706. for item in range(self.layers.GetCount()):
  707. self.layers.Check(item, False)
  708. def OnFilter(self, event):
  709. """!Apply filter for map names"""
  710. if len(event.GetString()) == 0:
  711. self.layers.Set(self.map_layers)
  712. return
  713. list = []
  714. for layer in self.map_layers:
  715. try:
  716. if re.compile('^' + event.GetString()).search(layer):
  717. list.append(layer)
  718. except:
  719. pass
  720. self.layers.Set(list)
  721. self.OnSelectAll(None)
  722. event.Skip()
  723. def OnToggle(self, event):
  724. """!Select toggle (check or uncheck all layers)"""
  725. check = event.Checked()
  726. for item in range(self.layers.GetCount()):
  727. self.layers.Check(item, check)
  728. event.Skip()
  729. def GetMapLayers(self):
  730. """!Return list of checked map layers"""
  731. layerNames = []
  732. for indx in self.layers.GetSelections():
  733. # layers.append(self.layers.GetStringSelec(indx))
  734. pass
  735. # return fully qualified map names
  736. mapset = self.mapset.GetStringSelection()
  737. for item in range(self.layers.GetCount()):
  738. if not self.layers.IsChecked(item):
  739. continue
  740. layerNames.append(self.layers.GetString(item) + '@' + mapset)
  741. return layerNames
  742. def GetLayerType(self):
  743. """!Get selected layer type"""
  744. return self.layerType.GetStringSelection()
  745. class ImportDialog(wx.Dialog):
  746. """!Dialog for bulk import of various data (base class)"""
  747. def __init__(self, parent, itype,
  748. id = wx.ID_ANY, title = _("Multiple import"),
  749. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  750. self.parent = parent # GMFrame
  751. self.importType = itype
  752. self.options = dict() # list of options
  753. self.commandId = -1 # id of running command
  754. wx.Dialog.__init__(self, parent, id, title, style=style,
  755. name = "MultiImportDialog")
  756. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  757. self.layerBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  758. label=_(" List of %s layers ") % self.importType.upper())
  759. #
  760. # list of layers
  761. #
  762. self.list = LayersList(self.panel)
  763. self.list.LoadData()
  764. self.optionBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  765. label="%s" % _("Options"))
  766. cmd = self._getCommand()
  767. task = gtask.parse_interface(cmd)
  768. for f in task.get_options()['flags']:
  769. name = f.get('name', '')
  770. desc = f.get('label', '')
  771. if not desc:
  772. desc = f.get('description', '')
  773. if not name and not desc:
  774. continue
  775. if cmd == 'r.in.gdal' and name not in ('o', 'e', 'l', 'k'):
  776. continue
  777. elif cmd == 'r.external' and name not in ('o', 'e', 'r', 'h', 'v'):
  778. continue
  779. elif cmd == 'v.in.ogr' and name not in ('c', 'z', 't', 'o', 'r', 'e', 'w'):
  780. continue
  781. elif cmd == 'v.external' and name not in ('b'):
  782. continue
  783. elif cmd == 'v.in.dxf' and name not in ('e', 't', 'b', 'f', 'i'):
  784. continue
  785. self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  786. label = desc)
  787. self.overwrite = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
  788. label=_("Allow output files to overwrite existing files"))
  789. self.overwrite.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  790. self.add = wx.CheckBox(parent=self.panel, id=wx.ID_ANY)
  791. #
  792. # buttons
  793. #
  794. # cancel
  795. self.btn_cancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
  796. self.btn_cancel.SetToolTipString(_("Close dialog"))
  797. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  798. # run
  799. self.btn_run = wx.Button(parent=self.panel, id=wx.ID_OK, label = _("&Import"))
  800. self.btn_run.SetToolTipString(_("Import selected layers"))
  801. self.btn_run.SetDefault()
  802. self.btn_run.Enable(False)
  803. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  804. # run command dialog
  805. self.btn_cmd = wx.Button(parent = self.panel, id = wx.ID_ANY,
  806. label = _("Command dialog"))
  807. self.btn_cmd.Bind(wx.EVT_BUTTON, self.OnCmdDialog)
  808. def doLayout(self):
  809. """!Do layout"""
  810. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  811. # dsn input
  812. dialogSizer.Add(item = self.dsnInput, proportion = 0,
  813. flag = wx.EXPAND)
  814. #
  815. # list of DXF layers
  816. #
  817. layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)
  818. layerSizer.Add(item=self.list, proportion=1,
  819. flag=wx.ALL | wx.EXPAND, border=5)
  820. dialogSizer.Add(item=layerSizer, proportion=1,
  821. flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
  822. # options
  823. optionSizer = wx.StaticBoxSizer(self.optionBox, wx.VERTICAL)
  824. for key in self.options.keys():
  825. optionSizer.Add(item=self.options[key], proportion=0)
  826. dialogSizer.Add(item=optionSizer, proportion=0,
  827. flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
  828. dialogSizer.Add(item=self.overwrite, proportion=0,
  829. flag=wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
  830. dialogSizer.Add(item=self.add, proportion=0,
  831. flag=wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
  832. #
  833. # buttons
  834. #
  835. btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
  836. btnsizer.Add(item=self.btn_cmd, proportion=0,
  837. flag=wx.ALL | wx.ALIGN_CENTER,
  838. border=10)
  839. btnsizer.Add(item=self.btn_run, proportion=0,
  840. flag=wx.ALL | wx.ALIGN_CENTER,
  841. border=10)
  842. btnsizer.Add(item=self.btn_cancel, proportion=0,
  843. flag=wx.ALL | wx.ALIGN_CENTER,
  844. border=10)
  845. dialogSizer.Add(item=btnsizer, proportion=0,
  846. flag=wx.ALIGN_CENTER)
  847. # dialogSizer.SetSizeHints(self.panel)
  848. self.panel.SetAutoLayout(True)
  849. self.panel.SetSizer(dialogSizer)
  850. dialogSizer.Fit(self.panel)
  851. # auto-layout seems not work here - FIXME
  852. size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 225, 550)
  853. self.SetMinSize(size)
  854. self.SetSize((size.width, size.height + 100))
  855. width = self.GetSize()[0]
  856. self.list.SetColumnWidth(col=1, width=width/2 - 50)
  857. self.Layout()
  858. def _getCommand(self):
  859. """!Get command"""
  860. return ''
  861. def OnCancel(self, event=None):
  862. """!Close dialog"""
  863. self.Close()
  864. def OnRun(self, event):
  865. """!Import/Link data (each layes as separate vector map)"""
  866. pass
  867. def OnCmdDialog(self, event):
  868. """!Show command dialog"""
  869. pass
  870. def AddLayers(self, returncode, cmd = None):
  871. """!Add imported/linked layers into layer tree"""
  872. self.commandId += 1
  873. if not self.add.IsChecked() or returncode != 0:
  874. return
  875. maptree = self.parent.curr_page.maptree
  876. layer, output = self.list.GetLayers()[self.commandId]
  877. if '@' not in output:
  878. name = output + '@' + grass.gisenv()['MAPSET']
  879. else:
  880. name = output
  881. # add imported layers into layer tree
  882. if self.importType == 'gdal':
  883. cmd = ['d.rast',
  884. 'map=%s' % name]
  885. if UserSettings.Get(group='cmd', key='rasterOverlay', subkey='enabled'):
  886. cmd.append('-o')
  887. item = maptree.AddLayer(ltype='raster',
  888. lname=name,
  889. lcmd=cmd)
  890. else:
  891. item = maptree.AddLayer(ltype='vector',
  892. lname=name,
  893. lcmd=['d.vect',
  894. 'map=%s' % name])
  895. maptree.mapdisplay.MapWindow.ZoomToMap()
  896. def OnAbort(self, event):
  897. """!Abort running import
  898. @todo not yet implemented
  899. """
  900. pass
  901. class GdalImportDialog(ImportDialog):
  902. """!Dialog for bulk import of various raster/vector data"""
  903. def __init__(self, parent, ogr = False, link = False):
  904. self.link = link
  905. self.ogr = ogr
  906. if ogr:
  907. ImportDialog.__init__(self, parent, itype = 'ogr')
  908. if link:
  909. self.SetTitle(_("Link external vector data"))
  910. else:
  911. self.SetTitle(_("Import vector data"))
  912. else:
  913. ImportDialog.__init__(self, parent, itype = 'gdal')
  914. if link:
  915. self.SetTitle(_("Link external raster data"))
  916. else:
  917. self.SetTitle(_("Import raster data"))
  918. self.dsnInput = gselect.GdalSelect(parent = self, panel = self.panel, ogr = ogr)
  919. if link:
  920. self.add.SetLabel(_("Add linked layers into layer tree"))
  921. else:
  922. self.add.SetLabel(_("Add imported layers into layer tree"))
  923. self.add.SetValue(UserSettings.Get(group='cmd', key='addNewLayer', subkey='enabled'))
  924. if link:
  925. self.btn_run.SetLabel(_("&Link"))
  926. self.btn_run.SetToolTipString(_("Link selected layers"))
  927. if ogr:
  928. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'v.external')
  929. else:
  930. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'r.external')
  931. else:
  932. self.btn_run.SetLabel(_("&Import"))
  933. self.btn_run.SetToolTipString(_("Import selected layers"))
  934. if ogr:
  935. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'v.in.ogr')
  936. else:
  937. self.btn_cmd.SetToolTipString(_('Open %s dialog') % 'r.in.gdal')
  938. self.doLayout()
  939. def OnRun(self, event):
  940. """!Import/Link data (each layes as separate vector map)"""
  941. data = self.list.GetLayers()
  942. # hide dialog
  943. self.Hide()
  944. dsn = self.dsnInput.GetDsn()
  945. ext = self.dsnInput.GetFormatExt()
  946. for layer, output in data:
  947. if self.importType == 'ogr':
  948. if ext and layer.rfind(ext) > -1:
  949. layer = layer.replace('.' + ext, '')
  950. if self.link:
  951. cmd = ['v.external',
  952. 'dsn=%s' % dsn,
  953. 'output=%s' % output,
  954. 'layer=%s' % layer]
  955. else:
  956. cmd = ['v.in.ogr',
  957. 'dsn=%s' % dsn,
  958. 'layer=%s' % layer,
  959. 'output=%s' % output]
  960. else: # gdal
  961. if self.dsnInput.GetType() == 'dir':
  962. idsn = os.path.join(dsn, layer)
  963. else:
  964. idsn = dsn
  965. if self.link:
  966. cmd = ['r.external',
  967. 'input=%s' % idsn,
  968. 'output=%s' % output]
  969. else:
  970. cmd = ['r.in.gdal',
  971. 'input=%s' % idsn,
  972. 'output=%s' % output]
  973. if self.overwrite.IsChecked():
  974. cmd.append('--overwrite')
  975. for key in self.options.keys():
  976. if self.options[key].IsChecked():
  977. cmd.append('-%s' % key)
  978. if UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'):
  979. cmd.append('--overwrite')
  980. # run in Layer Manager
  981. self.parent.goutput.RunCmd(cmd, switchPage = True,
  982. onDone = self.AddLayers)
  983. self.OnCancel()
  984. def _getCommand(self):
  985. """!Get command"""
  986. if self.link:
  987. if self.ogr:
  988. return 'v.external'
  989. else:
  990. return 'r.external'
  991. else:
  992. if self.ogr:
  993. return 'v.in.ogr'
  994. else:
  995. return 'r.in.gdal'
  996. return ''
  997. def OnCmdDialog(self, event):
  998. """!Show command dialog"""
  999. name = self._getCommand()
  1000. menuform.GUI(parent = self, modal = True).ParseCommand(cmd = [name])
  1001. class DxfImportDialog(ImportDialog):
  1002. """!Dialog for bulk import of DXF layers"""
  1003. def __init__(self, parent):
  1004. ImportDialog.__init__(self, parent, itype = 'dxf',
  1005. title = _("Import DXF layers"))
  1006. self.dsnInput = filebrowse.FileBrowseButton(parent=self.panel, id=wx.ID_ANY,
  1007. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  1008. dialogTitle=_('Choose DXF file to import'),
  1009. buttonText=_('Browse'),
  1010. startDirectory=os.getcwd(), fileMode=0,
  1011. changeCallback=self.OnSetDsn,
  1012. fileMask="DXF File (*.dxf)|*.dxf")
  1013. self.add.SetLabel(_("Add imported layers into layer tree"))
  1014. self.add.SetValue(UserSettings.Get(group='cmd', key='addNewLayer', subkey='enabled'))
  1015. self.doLayout()
  1016. def _getCommand(self):
  1017. """!Get command"""
  1018. return 'v.in.dxf'
  1019. def OnRun(self, event):
  1020. """!Import/Link data (each layes as separate vector map)"""
  1021. data = self.list.GetLayers()
  1022. # hide dialog
  1023. self.Hide()
  1024. inputDxf = self.dsnInput.GetValue()
  1025. for layer, output in data:
  1026. cmd = ['v.in.dxf',
  1027. 'input=%s' % inputDxf,
  1028. 'layers=%s' % layer,
  1029. 'output=%s' % output]
  1030. for key in self.options.keys():
  1031. if self.options[key].IsChecked():
  1032. cmd.append('-%s' % key)
  1033. if self.overwrite.IsChecked() or \
  1034. UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'):
  1035. cmd.append('--overwrite')
  1036. # run in Layer Manager
  1037. self.parent.goutput.RunCmd(cmd, switchPage=True,
  1038. onDone = self.AddLayers)
  1039. self.OnCancel()
  1040. def OnSetDsn(self, event):
  1041. """!Input DXF file defined, update list of layer widget"""
  1042. path = event.GetString()
  1043. if not path:
  1044. return
  1045. data = list()
  1046. ret = gcmd.RunCommand('v.in.dxf',
  1047. quiet = True,
  1048. parent = self,
  1049. read = True,
  1050. flags = 'l',
  1051. input = path)
  1052. if not ret:
  1053. self.list.LoadData()
  1054. self.btn_run.Enable(False)
  1055. return
  1056. for line in ret.splitlines():
  1057. layerId = line.split(':')[0].split(' ')[1]
  1058. layerName = line.split(':')[1].strip()
  1059. grassName = utils.GetValidLayerName(layerName)
  1060. data.append((layerId, layerName.strip(), grassName.strip()))
  1061. self.list.LoadData(data)
  1062. if len(data) > 0:
  1063. self.btn_run.Enable(True)
  1064. else:
  1065. self.btn_run.Enable(False)
  1066. def OnCmdDialog(self, event):
  1067. """!Show command dialog"""
  1068. menuform.GUI(parent = self, modal = True).ParseCommand(cmd = ['v.in.dxf'])
  1069. class LayersList(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin,
  1070. listmix.CheckListCtrlMixin, listmix.TextEditMixin):
  1071. """!List of layers to be imported (dxf, shp...)"""
  1072. def __init__(self, parent, pos = wx.DefaultPosition,
  1073. log = None):
  1074. self.parent = parent
  1075. wx.ListCtrl.__init__(self, parent, wx.ID_ANY,
  1076. style=wx.LC_REPORT)
  1077. listmix.CheckListCtrlMixin.__init__(self)
  1078. self.log = log
  1079. # setup mixins
  1080. listmix.ListCtrlAutoWidthMixin.__init__(self)
  1081. listmix.TextEditMixin.__init__(self)
  1082. self.InsertColumn(0, _('Layer'))
  1083. self.InsertColumn(1, _('Layer name'))
  1084. self.InsertColumn(2, _('Name for GRASS map'))
  1085. self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnPopupMenu) #wxMSW
  1086. self.Bind(wx.EVT_RIGHT_UP, self.OnPopupMenu) #wxGTK
  1087. def LoadData(self, data=None):
  1088. """!Load data into list"""
  1089. if data is None:
  1090. return
  1091. self.DeleteAllItems()
  1092. for id, name, grassName in data:
  1093. index = self.InsertStringItem(sys.maxint, str(id))
  1094. self.SetStringItem(index, 1, "%s" % str(name))
  1095. self.SetStringItem(index, 2, "%s" % str(grassName))
  1096. # check by default
  1097. self.CheckItem(index, True)
  1098. self.SetColumnWidth(col=0, width=wx.LIST_AUTOSIZE_USEHEADER)
  1099. def OnPopupMenu(self, event):
  1100. """!Show popup menu"""
  1101. if self.GetItemCount() < 1:
  1102. return
  1103. if not hasattr(self, "popupDataID1"):
  1104. self.popupDataID1 = wx.NewId()
  1105. self.popupDataID2 = wx.NewId()
  1106. self.Bind(wx.EVT_MENU, self.OnSelectAll, id=self.popupDataID1)
  1107. self.Bind(wx.EVT_MENU, self.OnSelectNone, id=self.popupDataID2)
  1108. # generate popup-menu
  1109. menu = wx.Menu()
  1110. menu.Append(self.popupDataID1, _("Select all"))
  1111. menu.Append(self.popupDataID2, _("Deselect all"))
  1112. self.PopupMenu(menu)
  1113. menu.Destroy()
  1114. def OnSelectAll(self, event):
  1115. """!Select all items"""
  1116. item = -1
  1117. while True:
  1118. item = self.GetNextItem(item)
  1119. if item == -1:
  1120. break
  1121. self.CheckItem(item, True)
  1122. event.Skip()
  1123. def OnSelectNone(self, event):
  1124. """!Deselect items"""
  1125. item = -1
  1126. while True:
  1127. item = self.GetNextItem(item, wx.LIST_STATE_SELECTED)
  1128. if item == -1:
  1129. break
  1130. self.CheckItem(item, False)
  1131. event.Skip()
  1132. def GetLayers(self):
  1133. """!Get list of layers (layer name, output name)"""
  1134. data = []
  1135. item = -1
  1136. while True:
  1137. item = self.GetNextItem(item)
  1138. if item == -1:
  1139. break
  1140. if self.IsChecked(item):
  1141. # layer / output name
  1142. data.append((self.GetItem(item, 1).GetText(),
  1143. self.GetItem(item, 2).GetText()))
  1144. return data
  1145. class SetOpacityDialog(wx.Dialog):
  1146. """!Set opacity of map layers"""
  1147. def __init__(self, parent, id=wx.ID_ANY, title=_("Set Map Layer Opacity"),
  1148. size=wx.DefaultSize, pos=wx.DefaultPosition,
  1149. style=wx.DEFAULT_DIALOG_STYLE, opacity=100):
  1150. self.parent = parent # GMFrame
  1151. self.opacity = opacity # current opacity
  1152. super(SetOpacityDialog, self).__init__(parent, id=id, pos=pos,
  1153. size=size, style=style, title=title)
  1154. panel = wx.Panel(parent=self, id=wx.ID_ANY)
  1155. sizer = wx.BoxSizer(wx.VERTICAL)
  1156. box = wx.GridBagSizer(vgap=5, hgap=5)
  1157. self.value = wx.Slider(panel, id=wx.ID_ANY, value=self.opacity,
  1158. style=wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | \
  1159. wx.SL_TOP | wx.SL_LABELS,
  1160. minValue=0, maxValue=100,
  1161. size=(350, -1))
  1162. box.Add(item=self.value,
  1163. flag=wx.ALIGN_CENTRE, pos=(0, 0), span=(1, 2))
  1164. box.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
  1165. label=_("transparent")),
  1166. pos=(1, 0))
  1167. box.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
  1168. label=_("opaque")),
  1169. flag=wx.ALIGN_RIGHT,
  1170. pos=(1, 1))
  1171. sizer.Add(item=box, proportion=0,
  1172. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  1173. line = wx.StaticLine(parent=panel, id=wx.ID_ANY,
  1174. style=wx.LI_HORIZONTAL)
  1175. sizer.Add(item=line, proportion=0,
  1176. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  1177. # buttons
  1178. btnsizer = wx.StdDialogButtonSizer()
  1179. btnOK = wx.Button(parent=panel, id=wx.ID_OK)
  1180. btnOK.SetDefault()
  1181. btnsizer.AddButton(btnOK)
  1182. btnCancel = wx.Button(parent=panel, id=wx.ID_CANCEL)
  1183. btnsizer.AddButton(btnCancel)
  1184. btnsizer.Realize()
  1185. sizer.Add(item=btnsizer, proportion=0,
  1186. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  1187. panel.SetSizer(sizer)
  1188. sizer.Fit(panel)
  1189. self.SetSize(self.GetBestSize())
  1190. self.Layout()
  1191. def GetOpacity(self):
  1192. """!Button 'OK' pressed"""
  1193. # return opacity value
  1194. opacity = float(self.value.GetValue()) / 100
  1195. return opacity
  1196. def GetImageHandlers(image):
  1197. """!Get list of supported image handlers"""
  1198. lext = list()
  1199. ltype = list()
  1200. for h in image.GetHandlers():
  1201. lext.append(h.GetExtension())
  1202. filetype = ''
  1203. if 'png' in lext:
  1204. filetype += "PNG file (*.png)|*.png|"
  1205. ltype.append({ 'type' : wx.BITMAP_TYPE_PNG,
  1206. 'ext' : 'png' })
  1207. filetype += "BMP file (*.bmp)|*.bmp|"
  1208. ltype.append({ 'type' : wx.BITMAP_TYPE_BMP,
  1209. 'ext' : 'bmp' })
  1210. if 'gif' in lext:
  1211. filetype += "GIF file (*.gif)|*.gif|"
  1212. ltype.append({ 'type' : wx.BITMAP_TYPE_GIF,
  1213. 'ext' : 'gif' })
  1214. if 'jpg' in lext:
  1215. filetype += "JPG file (*.jpg)|*.jpg|"
  1216. ltype.append({ 'type' : wx.BITMAP_TYPE_JPEG,
  1217. 'ext' : 'jpg' })
  1218. if 'pcx' in lext:
  1219. filetype += "PCX file (*.pcx)|*.pcx|"
  1220. ltype.append({ 'type' : wx.BITMAP_TYPE_PCX,
  1221. 'ext' : 'pcx' })
  1222. if 'pnm' in lext:
  1223. filetype += "PNM file (*.pnm)|*.pnm|"
  1224. ltype.append({ 'type' : wx.BITMAP_TYPE_PNM,
  1225. 'ext' : 'pnm' })
  1226. if 'tif' in lext:
  1227. filetype += "TIF file (*.tif)|*.tif|"
  1228. ltype.append({ 'type' : wx.BITMAP_TYPE_TIF,
  1229. 'ext' : 'tif' })
  1230. if 'xpm' in lext:
  1231. filetype += "XPM file (*.xpm)|*.xpm"
  1232. ltype.append({ 'type' : wx.BITMAP_TYPE_XPM,
  1233. 'ext' : 'xpm' })
  1234. return filetype, ltype
  1235. class StaticWrapText(wx.StaticText):
  1236. """!A Static Text field that wraps its text to fit its width,
  1237. enlarging its height if necessary.
  1238. """
  1239. def __init__(self, parent, id = wx.ID_ANY, label = '', *args, **kwds):
  1240. self.parent = parent
  1241. self.originalLabel = label
  1242. wx.StaticText.__init__(self, parent, id, label = '', *args, **kwds)
  1243. self.SetLabel(label)
  1244. self.Bind(wx.EVT_SIZE, self.OnResize)
  1245. def SetLabel(self, label):
  1246. self.originalLabel = label
  1247. self.wrappedSize = None
  1248. self.OnResize(None)
  1249. def OnResize(self, event):
  1250. if not getattr(self, "resizing", False):
  1251. self.resizing = True
  1252. newSize = wx.Size(self.parent.GetSize().width - 50,
  1253. self.GetSize().height)
  1254. if self.wrappedSize != newSize:
  1255. wx.StaticText.SetLabel(self, self.originalLabel)
  1256. self.Wrap(newSize.width)
  1257. self.wrappedSize = newSize
  1258. self.SetSize(self.wrappedSize)
  1259. del self.resizing
  1260. class ImageSizeDialog(wx.Dialog):
  1261. """!Set size for saved graphic file"""
  1262. def __init__(self, parent, id = wx.ID_ANY, title=_("Set image size"),
  1263. style = wx.DEFAULT_DIALOG_STYLE, **kwargs):
  1264. self.parent = parent
  1265. wx.Dialog.__init__(self, parent, id = id, style=style, title=title, **kwargs)
  1266. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1267. self.box = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1268. label = ' % s' % _("Image size"))
  1269. size = self.parent.GetWindow().GetClientSize()
  1270. self.width = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1271. style = wx.SP_ARROW_KEYS)
  1272. self.width.SetRange(20, 1e6)
  1273. self.width.SetValue(size.width)
  1274. wx.CallAfter(self.width.SetFocus)
  1275. self.height = wx.SpinCtrl(parent = self.panel, id = wx.ID_ANY,
  1276. style = wx.SP_ARROW_KEYS)
  1277. self.height.SetRange(20, 1e6)
  1278. self.height.SetValue(size.height)
  1279. self.template = wx.Choice(parent = self.panel, id = wx.ID_ANY,
  1280. size = (125, -1),
  1281. choices = [ "",
  1282. "640x480",
  1283. "800x600",
  1284. "1024x768",
  1285. "1280x960",
  1286. "1600x1200",
  1287. "1920x1440" ])
  1288. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  1289. self.btnOK.SetDefault()
  1290. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1291. self.template.Bind(wx.EVT_CHOICE, self.OnTemplate)
  1292. self._layout()
  1293. self.SetSize(self.GetBestSize())
  1294. def _layout(self):
  1295. """!Do layout"""
  1296. sizer = wx.BoxSizer(wx.VERTICAL)
  1297. # body
  1298. box = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
  1299. fbox = wx.FlexGridSizer(cols = 2, vgap = 5, hgap = 5)
  1300. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1301. label = _("Width:")),
  1302. flag = wx.ALIGN_CENTER_VERTICAL)
  1303. fbox.Add(item = self.width)
  1304. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1305. label = _("Height:")),
  1306. flag = wx.ALIGN_CENTER_VERTICAL)
  1307. fbox.Add(item = self.height)
  1308. fbox.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  1309. label = _("Template:")),
  1310. flag = wx.ALIGN_CENTER_VERTICAL)
  1311. fbox.Add(item = self.template)
  1312. box.Add(item = fbox, proportion = 1,
  1313. flag = wx.EXPAND | wx.ALL, border = 5)
  1314. sizer.Add(item = box, proportion = 1,
  1315. flag=wx.EXPAND | wx.ALL, border = 3)
  1316. # buttons
  1317. btnsizer = wx.StdDialogButtonSizer()
  1318. btnsizer.AddButton(self.btnOK)
  1319. btnsizer.AddButton(self.btnCancel)
  1320. btnsizer.Realize()
  1321. sizer.Add(item = btnsizer, proportion = 0,
  1322. flag = wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL, border=5)
  1323. self.panel.SetSizer(sizer)
  1324. sizer.Fit(self.panel)
  1325. self.Layout()
  1326. def GetValues(self):
  1327. """!Get width/height values"""
  1328. return self.width.GetValue(), self.height.GetValue()
  1329. def OnTemplate(self, event):
  1330. """!Template selected"""
  1331. sel = event.GetString()
  1332. if not sel:
  1333. width, height = self.parent.GetWindow().GetClientSize()
  1334. else:
  1335. width, height = map(int, sel.split('x'))
  1336. self.width.SetValue(width)
  1337. self.height.SetValue(height)
  1338. class SqlQueryFrame(wx.Frame):
  1339. def __init__(self, parent, id = wx.ID_ANY,
  1340. title = _("GRASS GIS SQL Query Utility"),
  1341. *kwargs):
  1342. """!SQL Query Utility window
  1343. """
  1344. self.parent = parent
  1345. wx.Frame.__init__(self, parent = parent, id = id, title = title, *kwargs)
  1346. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
  1347. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  1348. self.sqlBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  1349. label = _(" SQL statement "))
  1350. self.sql = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
  1351. style = wx.TE_MULTILINE)
  1352. self.btnApply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  1353. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  1354. self.Bind(wx.EVT_BUTTON, self.OnCloseWindow, self.btnCancel)
  1355. self._layout()
  1356. self.SetMinSize(wx.Size(300, 150))
  1357. self.SetSize(wx.Size(500, 200))
  1358. def _layout(self):
  1359. """!Do layout"""
  1360. sizer = wx.BoxSizer(wx.VERTICAL)
  1361. sqlSizer = wx.StaticBoxSizer(self.sqlBox, wx.HORIZONTAL)
  1362. sqlSizer.Add(item = self.sql, proportion = 1,
  1363. flag = wx.EXPAND)
  1364. btnSizer = wx.StdDialogButtonSizer()
  1365. btnSizer.AddButton(self.btnApply)
  1366. btnSizer.AddButton(self.btnCancel)
  1367. btnSizer.Realize()
  1368. sizer.Add(item = sqlSizer, proportion = 1,
  1369. flag = wx.EXPAND | wx.ALL, border = 5)
  1370. sizer.Add(item = btnSizer, proportion = 0,
  1371. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  1372. self.panel.SetSizer(sizer)
  1373. self.Layout()
  1374. def OnCloseWindow(self, event):
  1375. """!Close window
  1376. """
  1377. self.Close()