gdialogs.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. """
  2. @package gdialogs.py
  3. @brief Common dialog used in wxGUI.
  4. List of classes:
  5. - NewVectorDialog
  6. - SavedRegion
  7. - DecorationDialog
  8. - TextLayerDialog
  9. - LoadMapLayersDialog
  10. - MultiImportDialog
  11. - LayerList (used by MultiImport)
  12. - SetOpacityDialog
  13. (C) 2008 by the GRASS Development Team
  14. This program is free software under the GNU General Public
  15. License (>=v2). Read the file COPYING that comes with GRASS
  16. for details.
  17. @author Martin Landa <landa.martin gmail.com>
  18. """
  19. import os
  20. import sys
  21. import re
  22. import glob
  23. import wx
  24. import wx.lib.filebrowsebutton as filebrowse
  25. import wx.lib.mixins.listctrl as listmix
  26. import gcmd
  27. import grassenv
  28. import globalvar
  29. import gselect
  30. import menuform
  31. import utils
  32. import grass
  33. from preferences import globalSettings as UserSettings
  34. class NewVectorDialog(wx.Dialog):
  35. """Create new vector map layer"""
  36. def __init__(self, parent, id, title,
  37. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  38. wx.Dialog.__init__(self, parent, id, title, style=style)
  39. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  40. self.btnCancel = wx.Button(self.panel, wx.ID_CANCEL)
  41. self.btnOK = wx.Button(self.panel, wx.ID_OK)
  42. self.btnOK.SetDefault()
  43. self.btnOK.Enable(False)
  44. self.label = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  45. label=_("Name for new vector map:"))
  46. self.mapName = gselect.Select(parent=self.panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  47. type='vector', mapsets=[grassenv.GetGRASSVariable('MAPSET'),])
  48. self.mapName.Bind(wx.EVT_TEXT, self.OnMapName)
  49. self.__Layout()
  50. self.SetMinSize(self.GetSize())
  51. def OnMapName(self, event):
  52. """Name for vector map layer given"""
  53. if len(event.GetString()) > 0:
  54. self.btnOK.Enable(True)
  55. else:
  56. self.btnOK.Enable(False)
  57. def __Layout(self):
  58. """Do layout"""
  59. sizer = wx.BoxSizer(wx.VERTICAL)
  60. dataSizer = wx.BoxSizer(wx.VERTICAL)
  61. dataSizer.Add(self.label, proportion=0,
  62. flag=wx.ALL, border=1)
  63. dataSizer.Add(self.mapName, proportion=0,
  64. flag=wx.EXPAND | wx.ALL, border=1)
  65. # buttons
  66. btnSizer = wx.StdDialogButtonSizer()
  67. btnSizer.AddButton(self.btnCancel)
  68. btnSizer.AddButton(self.btnOK)
  69. btnSizer.Realize()
  70. sizer.Add(item=dataSizer, proportion=1,
  71. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  72. sizer.Add(item=btnSizer, proportion=0,
  73. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  74. self.panel.SetSizer(sizer)
  75. sizer.Fit(self)
  76. def GetName(self):
  77. """Return (mapName, overwrite)"""
  78. mapName = self.mapName.GetValue().split('@', 1)[0]
  79. return mapName
  80. def CreateNewVector(parent, cmdDef, title=_('Create new vector map'),
  81. exceptMap=None, log=None):
  82. """Create new vector map layer
  83. @cmdList tuple/list (cmd list, output paramater)
  84. @return name of create vector map
  85. @return None of failure
  86. """
  87. cmd = cmdDef[0]
  88. dlg = NewVectorDialog(parent=parent, id=wx.ID_ANY, title=title)
  89. if dlg.ShowModal() == wx.ID_OK:
  90. outmap = dlg.GetName()
  91. if outmap == exceptMap:
  92. wx.MessageBox(parent=parent,
  93. message=_("Unable to create vector map <%s>.") % outmap,
  94. caption=_("Error"),
  95. style=wx.ID_OK | wx.ICON_ERROR | wx.CENTRE)
  96. return False
  97. if outmap == '': # should not happen
  98. return False
  99. cmd.append("%s=%s" % (cmdDef[1], outmap))
  100. if not UserSettings.Get(group='cmd', key='overwrite', subkey='enabled') and \
  101. outmap in grass.list_grouped('vect')[grass.gisenv()['MAPSET']]:
  102. dlg = wx.MessageDialog(parent, message=_("Vector map <%s> already exists "
  103. "in the current mapset. "
  104. "Do you want to overwrite it?") % outmap,
  105. caption=_("Overwrite?"),
  106. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  107. if dlg.ShowModal() == wx.ID_YES:
  108. cmd.append('--overwrite')
  109. else:
  110. dlg.Destroy()
  111. return False
  112. if UserSettings.Get(group='cmd', key='overwrite', subkey='enabled') is True:
  113. cmd.append('--overwrite')
  114. try:
  115. gcmd.Command(cmd)
  116. except gcmd.CmdError, e:
  117. print >> sys.stderr, e
  118. return None
  119. # return fully qualified map name
  120. if '@' not in outmap:
  121. outmap += '@' + grassenv.GetGRASSVariable('MAPSET')
  122. if log:
  123. log.WriteLog(_("New vector map <%s> created") % outmap)
  124. return outmap
  125. return None
  126. class SavedRegion(wx.Dialog):
  127. def __init__(self, parent, id, title="", pos=wx.DefaultPosition, size=wx.DefaultSize,
  128. style=wx.DEFAULT_DIALOG_STYLE,
  129. loadsave='load'):
  130. """
  131. Loading and saving of display extents to saved region file
  132. """
  133. wx.Dialog.__init__(self, parent, id, title, pos, size, style)
  134. self.loadsave = loadsave
  135. self.wind = ''
  136. sizer = wx.BoxSizer(wx.VERTICAL)
  137. box = wx.BoxSizer(wx.HORIZONTAL)
  138. if loadsave == 'load':
  139. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Load region:"))
  140. box.Add(item=label, proportion=0, flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
  141. self.selection = gselect.Select(parent=self, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  142. type='windows')
  143. box.Add(item=self.selection, proportion=0, flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
  144. self.selection.Bind(wx.EVT_TEXT, self.OnSelection)
  145. elif loadsave == 'save':
  146. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Save region:"))
  147. box.Add(item=label, proportion=0, flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
  148. self.textentry = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="",
  149. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  150. box.Add(item=self.textentry, proportion=0, flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
  151. self.textentry.Bind(wx.EVT_TEXT, self.OnText)
  152. sizer.Add(item=box, proportion=0, flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL,
  153. border=5)
  154. line = wx.StaticLine(parent=self, id=wx.ID_ANY, size=(20, -1), style=wx.LI_HORIZONTAL)
  155. sizer.Add(item=line, proportion=0,
  156. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border=5)
  157. btnsizer = wx.StdDialogButtonSizer()
  158. btn = wx.Button(self, wx.ID_OK)
  159. btn.SetDefault()
  160. btnsizer.AddButton(btn)
  161. btn = wx.Button(self, wx.ID_CANCEL)
  162. btnsizer.AddButton(btn)
  163. btnsizer.Realize()
  164. sizer.Add(item=btnsizer, proportion=0, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  165. self.SetSizer(sizer)
  166. sizer.Fit(self)
  167. def OnSelection(self, event):
  168. self.wind = event.GetString()
  169. def OnText(self, event):
  170. self.wind = event.GetString()
  171. class DecorationDialog(wx.Dialog):
  172. """
  173. Controls setting options and displaying/hiding map overlay decorations
  174. """
  175. def __init__(self, parent, ovlId, title, cmd, name=None,
  176. pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE,
  177. checktxt='', ctrltxt=''):
  178. wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style)
  179. self.ovlId = ovlId # PseudoDC id
  180. self.cmd = cmd
  181. self.name = name # overlay name
  182. self.parent = parent # MapFrame
  183. sizer = wx.BoxSizer(wx.VERTICAL)
  184. box = wx.BoxSizer(wx.HORIZONTAL)
  185. self.chkbox = wx.CheckBox(parent=self, id=wx.ID_ANY, label=checktxt)
  186. if self.parent.Map.GetOverlay(self.ovlId) is None:
  187. self.chkbox.SetValue(True)
  188. else:
  189. self.chkbox.SetValue(self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive())
  190. box.Add(item=self.chkbox, proportion=0,
  191. flag=wx.ALIGN_CENTRE|wx.ALL, border=5)
  192. sizer.Add(item=box, proportion=0,
  193. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border=5)
  194. box = wx.BoxSizer(wx.HORIZONTAL)
  195. optnbtn = wx.Button(parent=self, id=wx.ID_ANY, label=_("Set options"))
  196. box.Add(item=optnbtn, proportion=0, flag=wx.ALIGN_CENTRE|wx.ALL, border=5)
  197. sizer.Add(item=box, proportion=0,
  198. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border=5)
  199. box = wx.BoxSizer(wx.HORIZONTAL)
  200. label = wx.StaticText(parent=self, id=wx.ID_ANY,
  201. label=_("Drag %s with mouse in pointer mode to position.\n"
  202. "Double-click to change options." % ctrltxt))
  203. if self.name == 'legend':
  204. label.SetLabel(label.GetLabel() + _('\nDefine raster map name for legend in '
  205. 'properties dialog.'))
  206. box.Add(item=label, proportion=0,
  207. flag=wx.ALIGN_CENTRE|wx.ALL, border=5)
  208. sizer.Add(item=box, proportion=0,
  209. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border=5)
  210. line = wx.StaticLine(parent=self, id=wx.ID_ANY, size=(20,-1), style=wx.LI_HORIZONTAL)
  211. sizer.Add(item=line, proportion=0,
  212. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border=5)
  213. # buttons
  214. btnsizer = wx.StdDialogButtonSizer()
  215. self.btnOK = wx.Button(parent=self, id=wx.ID_OK)
  216. self.btnOK.SetDefault()
  217. if self.name == 'legend':
  218. self.btnOK.Enable(False)
  219. btnsizer.AddButton(self.btnOK)
  220. btnCancel = wx.Button(parent=self, id=wx.ID_CANCEL)
  221. btnsizer.AddButton(btnCancel)
  222. btnsizer.Realize()
  223. sizer.Add(item=btnsizer, proportion=0,
  224. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  225. #
  226. # bindings
  227. #
  228. self.Bind(wx.EVT_BUTTON, self.OnOptions, optnbtn)
  229. self.Bind(wx.EVT_BUTTON, self.OnCancel, btnCancel)
  230. self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)
  231. self.SetSizer(sizer)
  232. sizer.Fit(self)
  233. # create overlay if doesn't exist
  234. self._CreateOverlay()
  235. if len(self.parent.MapWindow.overlays[self.ovlId]['cmd']) > 1:
  236. mapName = utils.GetLayerNameFromCmd(self.parent.MapWindow.overlays[self.ovlId]['cmd'])
  237. if self.parent.MapWindow.overlays[self.ovlId]['propwin'] is None and mapName:
  238. # build properties dialog
  239. menuform.GUI().ParseCommand(cmd=self.cmd,
  240. completed=(self.GetOptData, self.name, ''),
  241. parentframe=self.parent, show=False)
  242. if mapName:
  243. # enable 'OK' button
  244. self.btnOK.Enable()
  245. # set title
  246. self.SetTitle(_('Legend of raster map <%s>') % \
  247. mapName)
  248. def _CreateOverlay(self):
  249. if not self.parent.Map.GetOverlay(self.ovlId):
  250. overlay = self.parent.Map.AddOverlay(id=self.ovlId, type=self.name,
  251. command=self.cmd,
  252. l_active=False, l_render=False, l_hidden=True)
  253. self.parent.MapWindow.overlays[self.ovlId] = {}
  254. self.parent.MapWindow.overlays[self.ovlId] = { 'layer' : overlay,
  255. 'params' : None,
  256. 'propwin' : None,
  257. 'cmd' : self.cmd,
  258. 'coords': (10, 10),
  259. 'pdcType': 'image' }
  260. else:
  261. if self.parent.MapWindow.overlays[self.ovlId]['propwin'] == None:
  262. return
  263. self.parent.MapWindow.overlays[self.ovlId]['propwin'].get_dcmd = self.GetOptData
  264. def OnOptions(self, event):
  265. """ self.SetSizer(sizer)
  266. sizer.Fit(self)
  267. Sets option for decoration map overlays
  268. """
  269. if self.parent.MapWindow.overlays[self.ovlId]['propwin'] is None:
  270. # build properties dialog
  271. menuform.GUI().ParseCommand(cmd=self.cmd,
  272. completed=(self.GetOptData, self.name, ''),
  273. parentframe=self.parent)
  274. else:
  275. if self.parent.MapWindow.overlays[self.ovlId]['propwin'].IsShown():
  276. self.parent.MapWindow.overlays[self.ovlId]['propwin'].SetFocus()
  277. else:
  278. self.parent.MapWindow.overlays[self.ovlId]['propwin'].Show()
  279. def OnCancel(self, event):
  280. """Cancel dialog"""
  281. self.parent.dialogs['barscale'] = None
  282. self.Destroy()
  283. def OnOK(self, event):
  284. """Button 'OK' pressed"""
  285. # enable or disable overlay
  286. self.parent.Map.GetOverlay(self.ovlId).SetActive(self.chkbox.IsChecked())
  287. # update map
  288. self.parent.MapWindow.UpdateMap()
  289. # close dialog
  290. self.OnCancel(None)
  291. def GetOptData(self, dcmd, layer, params, propwin):
  292. """Process decoration layer data"""
  293. # update layer data
  294. if params:
  295. self.parent.MapWindow.overlays[self.ovlId]['params'] = params
  296. if dcmd:
  297. self.parent.MapWindow.overlays[self.ovlId]['cmd'] = dcmd
  298. self.parent.MapWindow.overlays[self.ovlId]['propwin'] = propwin
  299. # change parameters for item in layers list in render.Map
  300. # "Use mouse..." (-m) flag causes GUI freeze and is pointless here, trac #119
  301. try:
  302. self.parent.MapWindow.overlays[self.ovlId]['cmd'].remove('-m')
  303. except ValueError:
  304. pass
  305. self.parent.Map.ChangeOverlay(id=self.ovlId, type=self.name,
  306. command=self.parent.MapWindow.overlays[self.ovlId]['cmd'],
  307. l_active=self.parent.MapWindow.overlays[self.ovlId]['layer'].IsActive(),
  308. l_render=False, l_hidden=True)
  309. if self.name == 'legend':
  310. if params and not self.btnOK.IsEnabled():
  311. self.btnOK.Enable()
  312. #self.SetTitle(_('Legend of raster map <%s>') % \
  313. # utils.GetLayerNameFromCmd(self.parent.MapWindow.overlays[self.ovlId]['cmd']))
  314. class TextLayerDialog(wx.Dialog):
  315. """
  316. Controls setting options and displaying/hiding map overlay decorations
  317. """
  318. def __init__(self, parent, ovlId, title, name='text',
  319. pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE):
  320. wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style)
  321. self.ovlId = ovlId
  322. self.parent = parent
  323. if self.ovlId in self.parent.MapWindow.textdict:
  324. self.currText, self.currFont, self.currClr, self.currRot = self.parent.MapWindow.textdict[drawid]
  325. else:
  326. self.currClr = wx.BLACK
  327. self.currText = ''
  328. self.currFont = self.GetFont()
  329. self.currRot = 0.0
  330. sizer = wx.BoxSizer(wx.VERTICAL)
  331. box = wx.GridBagSizer(vgap=5, hgap=5)
  332. # text entry
  333. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Enter text:"))
  334. box.Add(item=label,
  335. flag=wx.ALIGN_CENTER_VERTICAL,
  336. pos=(0, 0))
  337. self.textentry = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(300,-1))
  338. self.textentry.SetFont(self.currFont)
  339. self.textentry.SetForegroundColour(self.currClr)
  340. self.textentry.SetValue(self.currText)
  341. box.Add(item=self.textentry,
  342. pos=(0, 1))
  343. # rotation
  344. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Rotation:"))
  345. box.Add(item=label,
  346. flag=wx.ALIGN_CENTER_VERTICAL,
  347. pos=(1, 0))
  348. self.rotation = wx.SpinCtrl(parent=self, id=wx.ID_ANY, value="", pos=(30, 50),
  349. size=(75,-1), style=wx.SP_ARROW_KEYS)
  350. self.rotation.SetRange(-360, 360)
  351. self.rotation.SetValue(int(self.currRot))
  352. box.Add(item=self.rotation,
  353. flag=wx.ALIGN_RIGHT,
  354. pos=(1, 1))
  355. # font
  356. fontbtn = wx.Button(parent=self, id=wx.ID_ANY, label=_("Set font"))
  357. box.Add(item=fontbtn,
  358. flag=wx.ALIGN_RIGHT,
  359. pos=(2, 1))
  360. sizer.Add(item=box, proportion=1,
  361. flag=wx.ALL, border=10)
  362. # note
  363. box = wx.BoxSizer(wx.HORIZONTAL)
  364. label = wx.StaticText(parent=self, id=wx.ID_ANY,
  365. label=_("Drag text with mouse in pointer mode "
  366. "to position.\nDouble-click to change options"))
  367. box.Add(item=label, proportion=0,
  368. flag=wx.ALIGN_CENTRE | wx.ALL, border=5)
  369. sizer.Add(item=box, proportion=0,
  370. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.ALL, border=5)
  371. line = wx.StaticLine(parent=self, id=wx.ID_ANY,
  372. size=(20,-1), style=wx.LI_HORIZONTAL)
  373. sizer.Add(item=line, proportion=0,
  374. flag=wx.EXPAND | wx.ALIGN_CENTRE | wx.ALL, border=5)
  375. btnsizer = wx.StdDialogButtonSizer()
  376. btn = wx.Button(parent=self, id=wx.ID_OK)
  377. btn.SetDefault()
  378. btnsizer.AddButton(btn)
  379. btn = wx.Button(parent=self, id=wx.ID_CANCEL)
  380. btnsizer.AddButton(btn)
  381. btnsizer.Realize()
  382. sizer.Add(item=btnsizer, proportion=0,
  383. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  384. self.SetSizer(sizer)
  385. sizer.Fit(self)
  386. # bindings
  387. self.Bind(wx.EVT_BUTTON, self.OnSelectFont, fontbtn)
  388. self.Bind(wx.EVT_TEXT, self.OnText, self.textentry)
  389. self.Bind(wx.EVT_SPINCTRL, self.OnRotation, self.rotation)
  390. def OnText(self, event):
  391. """Change text string"""
  392. self.currText = event.GetString()
  393. def OnRotation(self, event):
  394. """Change rotation"""
  395. self.currRot = event.GetInt()
  396. event.Skip()
  397. def OnSelectFont(self, event):
  398. """Change font"""
  399. data = wx.FontData()
  400. data.EnableEffects(True)
  401. data.SetColour(self.currClr) # set colour
  402. data.SetInitialFont(self.currFont)
  403. dlg = wx.FontDialog(self, data)
  404. if dlg.ShowModal() == wx.ID_OK:
  405. data = dlg.GetFontData()
  406. self.currFont = data.GetChosenFont()
  407. self.currClr = data.GetColour()
  408. self.textentry.SetFont(self.currFont)
  409. self.textentry.SetForegroundColour(self.currClr)
  410. self.Layout()
  411. dlg.Destroy()
  412. def GetValues(self):
  413. """Get text properties"""
  414. return (self.currText, self.currFont,
  415. self.currClr, self.currRot)
  416. class LoadMapLayersDialog(wx.Dialog):
  417. """Load selected map layers (raster, vector) into layer tree"""
  418. def __init__(self, parent, title, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  419. wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=title, style=style)
  420. self.parent = parent # GMFrame
  421. #
  422. # dialog body
  423. #
  424. self.bodySizer = self.__createDialogBody()
  425. # update list of layer to be loaded
  426. self.map_layers = [] # list of map layers (full list type/mapset)
  427. self.LoadMapLayers(self.layerType.GetStringSelection()[:4],
  428. self.mapset.GetStringSelection())
  429. #
  430. # buttons
  431. #
  432. btnCancel = wx.Button(self, wx.ID_CANCEL)
  433. btnOk = wx.Button(self, wx.ID_OK, _("Load") )
  434. btnOk.SetDefault()
  435. #
  436. # bindigs
  437. #
  438. #btnOk.Bind(wx.EVT_BUTTON, self.OnOK)
  439. #btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  440. #
  441. # sizers & do layout
  442. #
  443. btnSizer = wx.StdDialogButtonSizer()
  444. btnSizer.AddButton(btnCancel)
  445. btnSizer.AddButton(btnOk)
  446. btnSizer.Realize()
  447. mainSizer = wx.BoxSizer(wx.VERTICAL)
  448. mainSizer.Add(item=self.bodySizer, proportion=1,
  449. flag=wx.EXPAND | wx.ALL, border=5)
  450. mainSizer.Add(item=btnSizer, proportion=0,
  451. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  452. self.SetSizer(mainSizer)
  453. mainSizer.Fit(self)
  454. # set dialog min size
  455. self.SetMinSize(self.GetSize())
  456. def __createDialogBody(self):
  457. bodySizer = wx.GridBagSizer(vgap=3, hgap=3)
  458. bodySizer.AddGrowableCol(1)
  459. bodySizer.AddGrowableRow(3)
  460. # layer type
  461. bodySizer.Add(item=wx.StaticText(parent=self, label=_("Map layer type:")),
  462. flag=wx.ALIGN_CENTER_VERTICAL,
  463. pos=(0,0))
  464. self.layerType = wx.Choice(parent=self, id=wx.ID_ANY,
  465. choices=['raster', 'vector'], size=(100,-1))
  466. self.layerType.SetSelection(0)
  467. bodySizer.Add(item=self.layerType,
  468. pos=(0,1))
  469. # mapset filter
  470. bodySizer.Add(item=wx.StaticText(parent=self, label=_("Mapset:")),
  471. flag=wx.ALIGN_CENTER_VERTICAL,
  472. pos=(1,0))
  473. self.mapset = wx.ComboBox(parent=self, id=wx.ID_ANY,
  474. style=wx.CB_SIMPLE | wx.CB_READONLY,
  475. choices=utils.ListOfMapsets(),
  476. size=(250,-1))
  477. self.mapset.SetStringSelection(grassenv.GetGRASSVariable("MAPSET"))
  478. bodySizer.Add(item=self.mapset,
  479. pos=(1,1))
  480. # map name filter
  481. bodySizer.Add(item=wx.StaticText(parent=self, label=_("Filter:")),
  482. flag=wx.ALIGN_CENTER_VERTICAL,
  483. pos=(2,0))
  484. self.filter = wx.TextCtrl(parent=self, id=wx.ID_ANY,
  485. value="",
  486. size=(250,-1))
  487. bodySizer.Add(item=self.filter,
  488. flag=wx.EXPAND,
  489. pos=(2,1))
  490. # layer list
  491. bodySizer.Add(item=wx.StaticText(parent=self, label=_("List of maps:")),
  492. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_TOP,
  493. pos=(3,0))
  494. self.layers = wx.CheckListBox(parent=self, id=wx.ID_ANY,
  495. size=(250, 100),
  496. choices=[])
  497. bodySizer.Add(item=self.layers,
  498. flag=wx.EXPAND,
  499. pos=(3,1))
  500. # bindings
  501. self.layerType.Bind(wx.EVT_CHOICE, self.OnChangeParams)
  502. self.mapset.Bind(wx.EVT_COMBOBOX, self.OnChangeParams)
  503. self.layers.Bind(wx.EVT_RIGHT_DOWN, self.OnMenu)
  504. self.filter.Bind(wx.EVT_TEXT, self.OnFilter)
  505. return bodySizer
  506. def LoadMapLayers(self, type, mapset):
  507. """Load list of map layers
  508. @param type layer type ('raster' or 'vector')
  509. @param mapset mapset name
  510. """
  511. list = gcmd.Command(['g.mlist',
  512. 'type=%s' % type,
  513. 'mapset=%s' % mapset])
  514. self.map_layers = []
  515. for map in list.ReadStdOutput():
  516. self.map_layers.append(map)
  517. self.layers.Set(self.map_layers)
  518. # check all items by default
  519. for item in range(self.layers.GetCount()):
  520. self.layers.Check(item)
  521. def OnChangeParams(self, event):
  522. """Filter parameters changed by user"""
  523. # update list of layer to be loaded
  524. self.LoadMapLayers(self.layerType.GetStringSelection()[:4],
  525. self.mapset.GetStringSelection())
  526. event.Skip()
  527. def OnMenu(self, event):
  528. """Table description area, context menu"""
  529. if not hasattr(self, "popupID1"):
  530. self.popupDataID1 = wx.NewId()
  531. self.popupDataID2 = wx.NewId()
  532. self.Bind(wx.EVT_MENU, self.OnSelectAll, id=self.popupDataID1)
  533. self.Bind(wx.EVT_MENU, self.OnDeselectAll, id=self.popupDataID2)
  534. # generate popup-menu
  535. menu = wx.Menu()
  536. menu.Append(self.popupDataID1, _("Select all"))
  537. menu.Append(self.popupDataID2, _("Deselect all"))
  538. self.PopupMenu(menu)
  539. menu.Destroy()
  540. def OnSelectAll(self, event):
  541. """Select all map layer from list"""
  542. for item in range(self.layers.GetCount()):
  543. self.layers.Check(item, True)
  544. def OnDeselectAll(self, event):
  545. """Select all map layer from list"""
  546. for item in range(self.layers.GetCount()):
  547. self.layers.Check(item, False)
  548. def OnFilter(self, event):
  549. """Apply filter for map names"""
  550. if len(event.GetString()) == 0:
  551. self.layers.Set(self.map_layers)
  552. return
  553. list = []
  554. for layer in self.map_layers:
  555. if re.compile('^' + event.GetString()).search(layer):
  556. list.append(layer)
  557. self.layers.Set(list)
  558. event.Skip()
  559. def GetMapLayers(self):
  560. """Return list of checked map layers"""
  561. layerNames = []
  562. for indx in self.layers.GetSelections():
  563. # layers.append(self.layers.GetStringSelec(indx))
  564. pass
  565. # return fully qualified map names
  566. mapset = self.mapset.GetStringSelection()
  567. for item in range(self.layers.GetCount()):
  568. if not self.layers.IsChecked(item):
  569. continue
  570. layerNames.append(self.layers.GetString(item) + '@' + mapset)
  571. return layerNames
  572. def GetLayerType(self):
  573. """Get selected layer type"""
  574. return self.layerType.GetStringSelection()
  575. class MultiImportDialog(wx.Dialog):
  576. """Import dxf layers"""
  577. def __init__(self, parent, type,
  578. id=wx.ID_ANY, title=_("Multiple import"),
  579. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  580. self.parent = parent # GMFrame
  581. self.inputType = type
  582. wx.Dialog.__init__(self, parent, id, title, style=style)
  583. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  584. #
  585. # input
  586. #
  587. if self.inputType == 'dxf':
  588. self.inputTitle = _("Input DXF file")
  589. self.inputText = wx.StaticText(self.panel, id=wx.ID_ANY, label=_("Choose DXF file:"))
  590. self.input = filebrowse.FileBrowseButton(parent=self.panel, id=wx.ID_ANY,
  591. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  592. dialogTitle=_('Choose DXF file to import'),
  593. buttonText=_('Browse'),
  594. startDirectory=os.getcwd(), fileMode=0,
  595. changeCallback=self.OnSetInput,
  596. fileMask="*.dxf")
  597. else:
  598. self.inputTitle = _("Input directory")
  599. self.inputText = wx.StaticText(self.panel, id=wx.ID_ANY, label=_("Choose directory:"))
  600. self.input = filebrowse.DirBrowseButton(parent=self.panel, id=wx.ID_ANY,
  601. size=globalvar.DIALOG_GSELECT_SIZE, labelText='',
  602. dialogTitle=_('Choose input directory'),
  603. buttonText=_('Browse'),
  604. startDirectory=os.getcwd(),
  605. changeCallback=self.OnSetInput)
  606. self.formatText = wx.StaticText(self.panel, id=wx.ID_ANY, label=_("Choose file extension:"))
  607. self.format = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY, size=(100, -1),
  608. value="")
  609. if self.inputType == 'gdal':
  610. self.format.SetValue('tif')
  611. else: # ogr
  612. self.format.SetValue('shp')
  613. self.format.Bind(wx.EVT_TEXT, self.OnSetInput)
  614. #
  615. # list of layers
  616. #
  617. self.list = LayersList(self.panel)
  618. self.list.LoadData()
  619. self.add = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
  620. label=_("Add imported layers into layer tree"))
  621. self.add.SetValue(UserSettings.Get(group='cmd', key='addNewLayer', subkey='enabled'))
  622. #
  623. # buttons
  624. #
  625. # cancel
  626. self.btn_cancel = wx.Button(parent=self.panel, id=wx.ID_CANCEL)
  627. self.btn_cancel.SetToolTipString(_("Close dialog"))
  628. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  629. # run
  630. self.btn_run = wx.Button(parent=self.panel, id=wx.ID_OK, label= _("&Import"))
  631. self.btn_run.SetToolTipString(_("Import selected layers"))
  632. self.btn_run.SetDefault()
  633. self.btn_run.Enable(False)
  634. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  635. self.__doLayout()
  636. self.Layout()
  637. def __doLayout(self):
  638. dialogSizer = wx.BoxSizer(wx.VERTICAL)
  639. #
  640. # input
  641. #
  642. inputBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  643. label=" %s " % self.inputTitle)
  644. inputSizer = wx.StaticBoxSizer(inputBox, wx.HORIZONTAL)
  645. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  646. gridSizer.Add(item=self.inputText,
  647. flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
  648. gridSizer.Add(item=self.input,
  649. flag=wx.EXPAND, pos=(0, 1))
  650. if self.inputType != 'dxf':
  651. gridSizer.Add(item=self.formatText,
  652. flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
  653. gridSizer.Add(item=self.format,
  654. pos=(1, 1))
  655. gridSizer.AddGrowableCol(1)
  656. inputSizer.Add(item=gridSizer, proportion=0,
  657. flag=wx.EXPAND)
  658. dialogSizer.Add(item=inputSizer, proportion=0,
  659. flag=wx.ALL | wx.EXPAND, border=5)
  660. #
  661. # list of DXF layers
  662. #
  663. layerBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  664. label=_(" List of %s layers ") % self.inputType.upper())
  665. layerSizer = wx.StaticBoxSizer(layerBox, wx.HORIZONTAL)
  666. layerSizer.Add(item=self.list, proportion=1,
  667. flag=wx.ALL | wx.EXPAND, border=5)
  668. dialogSizer.Add(item=layerSizer, proportion=1,
  669. flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
  670. dialogSizer.Add(item=self.add, proportion=0,
  671. flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)
  672. #
  673. # buttons
  674. #
  675. btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)
  676. btnsizer.Add(item=self.btn_cancel, proportion=0,
  677. flag=wx.ALL | wx.ALIGN_CENTER,
  678. border=10)
  679. btnsizer.Add(item=self.btn_run, proportion=0,
  680. flag=wx.ALL | wx.ALIGN_CENTER,
  681. border=10)
  682. dialogSizer.Add(item=btnsizer, proportion=0,
  683. flag=wx.ALIGN_CENTER)
  684. # dialogSizer.SetSizeHints(self.panel)
  685. self.panel.SetAutoLayout(True)
  686. self.panel.SetSizer(dialogSizer)
  687. dialogSizer.Fit(self.panel)
  688. self.Layout()
  689. # auto-layout seems not work here - FIXME
  690. self.SetMinSize((globalvar.DIALOG_GSELECT_SIZE[0] + 175, 300))
  691. width = self.GetSize()[0]
  692. self.list.SetColumnWidth(col=1, width=width/2 - 50)
  693. def OnCancel(self, event=None):
  694. """Close dialog"""
  695. self.Close()
  696. def OnRun(self, event):
  697. """Import data (each layes as separate vector map)"""
  698. data = self.list.GetLayers()
  699. # hide dialog
  700. self.Hide()
  701. for layer, output in data:
  702. if self.inputType == 'dxf':
  703. cmd = ['v.in.dxf',
  704. 'input=%s' % self.input.GetValue(),
  705. 'layers=%s' % layer,
  706. 'output=%s' % output]
  707. elif self.inputType == 'ogr':
  708. cmd = ['v.in.ogr',
  709. 'dsn=%s' % (os.path.join(self.input.GetValue(), layer)),
  710. 'output=%s' % output]
  711. else:
  712. cmd = ['r.in.gdal', '-o', # override projection by default
  713. 'input=%s' % (os.path.join(self.input.GetValue(), layer)),
  714. 'output=%s' % output]
  715. if UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'):
  716. cmd.append('--overwrite')
  717. # run in Layer Manager
  718. self.parent.goutput.RunCmd(cmd)
  719. if self.add.IsChecked():
  720. maptree = self.parent.curr_page.maptree
  721. for layer, output in data:
  722. if '@' not in output:
  723. name = output + '@' + grass.gisenv()['MAPSET']
  724. else:
  725. name = output
  726. # add imported layers into layer tree
  727. if self.inputType == 'gdal':
  728. cmd = ['d.rast',
  729. 'map=%s' % name]
  730. if UserSettings.Get(group='cmd', key='rasterOverlay', subkey='enabled'):
  731. cmd.append('-o')
  732. maptree.AddLayer(ltype='raster',
  733. lname=name,
  734. lcmd=cmd)
  735. else:
  736. maptree.AddLayer(ltype='vector',
  737. lname=name,
  738. lcmd=['d.vect',
  739. 'map=%s' % name])
  740. wx.CallAfter(self.parent.notebook.SetSelection, 0)
  741. self.OnCancel()
  742. def OnAbort(self, event):
  743. """Abort running import
  744. @todo not yet implemented
  745. """
  746. pass
  747. def OnSetInput(self, event):
  748. """Input DXF file/OGR dsn defined, update list of layer widget"""
  749. path = event.GetString()
  750. if self.inputType == 'dxf':
  751. try:
  752. cmd = gcmd.Command(['v.in.dxf',
  753. 'input=%s' % path,
  754. '-l', '--q'], stderr=None)
  755. except gcmd.CmdError, e:
  756. wx.MessageBox(parent=self, message=_("File <%(file)s>: Unable to get list of DXF layers.\n\n%(details)s") % \
  757. { 'file' : path, 'details' : e.message },
  758. caption=_("Error"), style=wx.ID_OK | wx.ICON_ERROR | wx.CENTRE)
  759. self.list.LoadData()
  760. self.btn_run.Enable(False)
  761. return
  762. data = []
  763. if self.inputType == 'dxf':
  764. for line in cmd.ReadStdOutput():
  765. layerId = line.split(':')[0].split(' ')[1]
  766. layerName = line.split(':')[1].strip()
  767. grassName = utils.GetValidLayerName(layerName)
  768. data.append((layerId, layerName.strip(), grassName.strip()))
  769. else: # gdal/ogr (for ogr maybe to use v.in.ogr -l)
  770. layerId = 1
  771. for file in glob.glob(os.path.join(self.input.GetValue(), "*.%s") % self.format.GetValue()):
  772. baseName = os.path.basename(file)
  773. grassName = utils.GetValidLayerName(baseName.split('.', -1)[0])
  774. data.append((layerId, baseName, grassName))
  775. layerId += 1
  776. self.list.LoadData(data)
  777. if len(data) > 0:
  778. self.btn_run.Enable(True)
  779. else:
  780. self.btn_run.Enable(False)
  781. class LayersList(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin,
  782. listmix.CheckListCtrlMixin):
  783. # listmix.CheckListCtrlMixin, listmix.TextEditMixin):
  784. """List of layers to be imported (dxf, shp...)"""
  785. def __init__(self, parent, pos=wx.DefaultPosition,
  786. log=None):
  787. self.parent = parent
  788. wx.ListCtrl.__init__(self, parent, wx.ID_ANY,
  789. style=wx.LC_REPORT)
  790. listmix.CheckListCtrlMixin.__init__(self)
  791. self.log = log
  792. # setup mixins
  793. listmix.ListCtrlAutoWidthMixin.__init__(self)
  794. # listmix.TextEditMixin.__init__(self)
  795. self.InsertColumn(0, _('Layer'))
  796. self.InsertColumn(1, _('Layer name'))
  797. self.InsertColumn(2, _('Output vector map name'))
  798. self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnPopupMenu) #wxMSW
  799. self.Bind(wx.EVT_RIGHT_UP, self.OnPopupMenu) #wxGTK
  800. def LoadData(self, data=None):
  801. """Load data into list"""
  802. if data is None:
  803. return
  804. self.DeleteAllItems()
  805. for id, name, grassName in data:
  806. index = self.InsertStringItem(sys.maxint, str(id))
  807. self.SetStringItem(index, 1, "%s" % str(name))
  808. self.SetStringItem(index, 2, "%s" % str(grassName))
  809. # check by default
  810. self.CheckItem(index, True)
  811. self.SetColumnWidth(col=0, width=wx.LIST_AUTOSIZE_USEHEADER)
  812. def OnPopupMenu(self, event):
  813. """Show popup menu"""
  814. if self.GetItemCount() < 1:
  815. return
  816. if not hasattr(self, "popupDataID1"):
  817. self.popupDataID1 = wx.NewId()
  818. self.popupDataID2 = wx.NewId()
  819. self.Bind(wx.EVT_MENU, self.OnSelectAll, id=self.popupDataID1)
  820. self.Bind(wx.EVT_MENU, self.OnSelectNone, id=self.popupDataID2)
  821. # generate popup-menu
  822. menu = wx.Menu()
  823. menu.Append(self.popupDataID1, _("Select all"))
  824. menu.Append(self.popupDataID2, _("Deselect all"))
  825. self.PopupMenu(menu)
  826. menu.Destroy()
  827. def OnSelectAll(self, event):
  828. """Select all items"""
  829. item = -1
  830. while True:
  831. item = self.GetNextItem(item)
  832. if item == -1:
  833. break
  834. self.CheckItem(item, True)
  835. event.Skip()
  836. def OnSelectNone(self, event):
  837. """Deselect items"""
  838. item = -1
  839. while True:
  840. item = self.GetNextItem(item, wx.LIST_STATE_SELECTED)
  841. if item == -1:
  842. break
  843. self.CheckItem(item, False)
  844. event.Skip()
  845. def GetLayers(self):
  846. """Get list of layers (layer name, output name)"""
  847. data = []
  848. item = -1
  849. while True:
  850. item = self.GetNextItem(item)
  851. if item == -1:
  852. break
  853. if self.IsChecked(item):
  854. # layer / output name
  855. data.append((self.GetItem(item, 1).GetText(),
  856. self.GetItem(item, 2).GetText()))
  857. return data
  858. class SetOpacityDialog(wx.Dialog):
  859. """Set opacity of map layers"""
  860. def __init__(self, parent, id=wx.ID_ANY, title=_("Set Map Layer Opacity"),
  861. size=wx.DefaultSize, pos=wx.DefaultPosition,
  862. style=wx.DEFAULT_DIALOG_STYLE, opacity=100):
  863. self.parent = parent # GMFrame
  864. self.opacity = opacity # current opacity
  865. super(SetOpacityDialog, self).__init__(parent, id=id, pos=pos,
  866. size=size, style=style, title=title)
  867. panel = wx.Panel(parent=self, id=wx.ID_ANY)
  868. sizer = wx.BoxSizer(wx.VERTICAL)
  869. box = wx.GridBagSizer(vgap=5, hgap=5)
  870. self.value = wx.Slider(panel, id=wx.ID_ANY, value=self.opacity,
  871. style=wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | \
  872. wx.SL_TOP | wx.SL_LABELS,
  873. minValue=0, maxValue=100,
  874. size=(350, -1))
  875. box.Add(item=self.value,
  876. flag=wx.ALIGN_CENTRE, pos=(0, 0), span=(1, 2))
  877. box.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
  878. label=_("transparent")),
  879. pos=(1, 0))
  880. box.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
  881. label=_("opaque")),
  882. flag=wx.ALIGN_RIGHT,
  883. pos=(1, 1))
  884. sizer.Add(item=box, proportion=0,
  885. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  886. line = wx.StaticLine(parent=panel, id=wx.ID_ANY,
  887. style=wx.LI_HORIZONTAL)
  888. sizer.Add(item=line, proportion=0,
  889. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  890. # buttons
  891. btnsizer = wx.StdDialogButtonSizer()
  892. btnOK = wx.Button(parent=panel, id=wx.ID_OK)
  893. btnOK.SetDefault()
  894. btnsizer.AddButton(btnOK)
  895. btnCancel = wx.Button(parent=panel, id=wx.ID_CANCEL)
  896. btnsizer.AddButton(btnCancel)
  897. btnsizer.Realize()
  898. sizer.Add(item=btnsizer, proportion=0,
  899. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  900. panel.SetSizer(sizer)
  901. sizer.Fit(panel)
  902. self.SetSize(self.GetBestSize())
  903. self.Layout()
  904. def GetOpacity(self):
  905. """Button 'OK' pressed"""
  906. # return opacity value
  907. opacity = float(self.value.GetValue()) / 100
  908. return opacity