toolbars.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. """
  2. @package vdigit.toolbars
  3. @brief wxGUI vector digitizer toolbars
  4. List of classes:
  5. - toolbars::VDigitToolbar
  6. (C) 2007-2014 by the GRASS Development Team
  7. This program is free software under the GNU General Public License
  8. (>=v2). Read the file COPYING that comes with GRASS for details.
  9. @author Martin Landa <landa.martin gmail.com>
  10. @author Stepan Turek <stepan.turek seznam.cz> (handlers support)
  11. """
  12. import wx
  13. from grass import script as grass
  14. from grass.pydispatch.signal import Signal
  15. from gui_core.toolbars import BaseToolbar, BaseIcons
  16. from gui_core.dialogs import CreateNewVector, VectorDialog
  17. from vdigit.preferences import VDigitSettingsDialog
  18. from core.debug import Debug
  19. from core.settings import UserSettings
  20. from core.gcmd import GError, RunCommand
  21. from core.utils import _
  22. from icons.icon import MetaIcon
  23. from iclass.digit import IClassVDigit
  24. from core.giface import Notification
  25. class VDigitToolbar(BaseToolbar):
  26. """Toolbar for digitization
  27. """
  28. def __init__(self, parent, toolSwitcher, MapWindow, digitClass, giface,
  29. tools=[]):
  30. self.MapWindow = MapWindow
  31. self.Map = MapWindow.GetMap() # Map class instance
  32. self.tools = tools
  33. self.digitClass = digitClass
  34. BaseToolbar.__init__(self, parent, toolSwitcher)
  35. self.digit = None
  36. self._giface = giface
  37. self.fType = None # feature type for simple features editing
  38. self.editingStarted = Signal("VDigitToolbar.editingStarted")
  39. self.editingStopped = Signal("VDigitToolbar.editingStopped")
  40. self.editingBgMap = Signal("VDigitToolbar.editingBgMap")
  41. layerTree = self._giface.GetLayerTree()
  42. if layerTree:
  43. self.editingStarted.connect(layerTree.StartEditing)
  44. self.editingStopped.connect(layerTree.StopEditing)
  45. self.editingBgMap.connect(layerTree.SetBgMapForEditing)
  46. # currently selected map layer for editing (reference to MapLayer instance)
  47. self.mapLayer = None
  48. # list of vector layers from Layer Manager (only in the current mapset)
  49. self.layers = []
  50. self.comboid = self.combo = None
  51. self.undo = -1
  52. self.redo = -1
  53. # only one dialog can be open
  54. self.settingsDialog = None
  55. # create toolbars (two rows optionally)
  56. self.InitToolbar(self._toolbarData())
  57. self._default = -1
  58. # default action (digitize new point, line, etc.)
  59. self.action = { 'desc' : '',
  60. 'type' : '',
  61. 'id' : -1 }
  62. self._currentAreaActionType = None
  63. # list of available vector maps
  64. self.UpdateListOfLayers(updateTool = True)
  65. for tool in ('addPoint', 'addLine', 'addBoundary', 'addCentroid', 'addArea',
  66. 'addVertex', 'deleteLine', 'deleteArea', 'displayAttr', 'displayCats',
  67. 'editLine', 'moveLine', 'moveVertex', 'removeVertex', 'additionalTools'):
  68. if hasattr(self, tool):
  69. tool = getattr(self, tool)
  70. self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
  71. else:
  72. Debug.msg(1, '%s skipped' % tool)
  73. # custom button for digitization of area/boundary/centroid
  74. # TODO: could this be somehow generalized?
  75. nAreaTools = 0
  76. if self.tools and 'addBoundary' in self.tools: nAreaTools += 1
  77. if self.tools and 'addCentroid' in self.tools: nAreaTools += 1
  78. if self.tools and 'addArea' in self.tools: nAreaTools += 1
  79. if nAreaTools != 1:
  80. self.areaButton = self.CreateSelectionButton(_("Select area/boundary/centroid tool"))
  81. self.areaButtonId = self.InsertControl(5, self.areaButton)
  82. self.areaButton.Bind(wx.EVT_BUTTON, self.OnAddAreaMenu)
  83. # realize toolbar
  84. self.Realize()
  85. # workaround for Mac bug. May be fixed by 2.8.8, but not before then.
  86. if self.combo:
  87. self.combo.Hide()
  88. self.combo.Show()
  89. # disable undo/redo
  90. if self.undo > 0:
  91. self.EnableTool(self.undo, False)
  92. if self.redo > 0:
  93. self.EnableTool(self.redo, False)
  94. self.FixSize(width = 105)
  95. def _toolbarData(self):
  96. """Toolbar data
  97. """
  98. data = []
  99. self.icons = {
  100. 'addPoint' : MetaIcon(img = 'point-create',
  101. label = _('Digitize new point'),
  102. desc = _('Left: new point')),
  103. 'addLine' : MetaIcon(img = 'line-create',
  104. label = _('Digitize new line'),
  105. desc = _('Left: new point; Ctrl+Left: undo last point; Right: close line')),
  106. 'addBoundary' : MetaIcon(img = 'boundary-create',
  107. label = _('Digitize new boundary'),
  108. desc = _('Left: new point; Ctrl+Left: undo last point; Right: close line')),
  109. 'addCentroid' : MetaIcon(img = 'centroid-create',
  110. label = _('Digitize new centroid'),
  111. desc = _('Left: new point')),
  112. 'addArea' : MetaIcon(img = 'polygon-create',
  113. label = _('Digitize new area (boundary without category)'),
  114. desc = _('Left: new point')),
  115. 'addVertex' : MetaIcon(img = 'vertex-create',
  116. label = _('Add new vertex to line or boundary'),
  117. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  118. 'deleteLine' : MetaIcon(img = 'line-delete',
  119. label = _('Delete selected point(s), line(s), boundary(ies) or centroid(s)'),
  120. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  121. 'deleteArea' : MetaIcon(img = 'polygon-delete',
  122. label = _('Delete selected area(s)'),
  123. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  124. 'displayAttr' : MetaIcon(img = 'attributes-display',
  125. label = _('Display/update attributes'),
  126. desc = _('Left: Select')),
  127. 'displayCats' : MetaIcon(img = 'cats-display',
  128. label = _('Display/update categories'),
  129. desc = _('Left: Select')),
  130. 'editLine' : MetaIcon(img = 'line-edit',
  131. label = _('Edit selected line/boundary'),
  132. desc = _('Left: new point; Ctrl+Left: undo last point; Right: close line')),
  133. 'moveLine' : MetaIcon(img = 'line-move',
  134. label = _('Move selected point(s), line(s), boundary(ies) or centroid(s)'),
  135. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  136. 'moveVertex' : MetaIcon(img = 'vertex-move',
  137. label = _('Move selected vertex'),
  138. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  139. 'removeVertex' : MetaIcon(img = 'vertex-delete',
  140. label = _('Remove selected vertex'),
  141. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  142. 'settings' : BaseIcons['settings'].SetLabel(_('Digitization settings')),
  143. 'quit' : BaseIcons['quit'].SetLabel(label = _('Quit digitizer'),
  144. desc = _('Quit digitizer and save changes')),
  145. 'help' : BaseIcons['help'].SetLabel(label = _('Vector Digitizer manual'),
  146. desc = _('Show Vector Digitizer manual')),
  147. 'additionalTools' : MetaIcon(img = 'tools',
  148. label = _('Additional tools '
  149. '(copy, flip, connect, etc.)'),
  150. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  151. 'undo' : MetaIcon(img = 'undo',
  152. label = _('Undo'),
  153. desc = _('Undo previous changes')),
  154. 'redo' : MetaIcon(img = 'redo',
  155. label = _('Redo'),
  156. desc = _('Redo previous changes')),
  157. }
  158. if not self.tools or 'selector' in self.tools:
  159. data.append((None, ))
  160. if not self.tools or 'addPoint' in self.tools:
  161. data.append(("addPoint", self.icons["addPoint"],
  162. self.OnAddPoint,
  163. wx.ITEM_CHECK))
  164. if not self.tools or 'addLine' in self.tools:
  165. data.append(("addLine", self.icons["addLine"],
  166. self.OnAddLine,
  167. wx.ITEM_CHECK))
  168. if not self.tools or 'addArea' in self.tools:
  169. data.append(("addArea", self.icons["addArea"],
  170. self.OnAddAreaTool,
  171. wx.ITEM_CHECK))
  172. if not self.tools or 'deleteLine' in self.tools:
  173. data.append(("deleteLine", self.icons["deleteLine"],
  174. self.OnDeleteLine,
  175. wx.ITEM_CHECK))
  176. if not self.tools or 'deleteArea' in self.tools:
  177. data.append(("deleteArea", self.icons["deleteArea"],
  178. self.OnDeleteArea,
  179. wx.ITEM_CHECK))
  180. if not self.tools or 'moveVertex' in self.tools:
  181. data.append(("moveVertex", self.icons["moveVertex"],
  182. self.OnMoveVertex,
  183. wx.ITEM_CHECK))
  184. if not self.tools or 'addVertex' in self.tools:
  185. data.append(("addVertex", self.icons["addVertex"],
  186. self.OnAddVertex,
  187. wx.ITEM_CHECK))
  188. if not self.tools or 'removeVertex' in self.tools:
  189. data.append(("removeVertex", self.icons["removeVertex"],
  190. self.OnRemoveVertex,
  191. wx.ITEM_CHECK))
  192. if not self.tools or 'editLine' in self.tools:
  193. data.append(("editLine", self.icons["editLine"],
  194. self.OnEditLine,
  195. wx.ITEM_CHECK))
  196. if not self.tools or 'moveLine' in self.tools:
  197. data.append(("moveLine", self.icons["moveLine"],
  198. self.OnMoveLine,
  199. wx.ITEM_CHECK))
  200. if not self.tools or 'displayCats' in self.tools:
  201. data.append(("displayCats", self.icons["displayCats"],
  202. self.OnDisplayCats,
  203. wx.ITEM_CHECK))
  204. if not self.tools or 'displayAttr' in self.tools:
  205. data.append(("displayAttr", self.icons["displayAttr"],
  206. self.OnDisplayAttr,
  207. wx.ITEM_CHECK))
  208. if not self.tools or 'additionalSelf.Tools' in self.tools:
  209. data.append(("additionalTools", self.icons["additionalTools"],
  210. self.OnAdditionalToolMenu,
  211. wx.ITEM_CHECK))
  212. if not self.tools or 'undo' in self.tools or \
  213. 'redo' in self.tools:
  214. data.append((None, ))
  215. if not self.tools or 'undo' in self.tools:
  216. data.append(("undo", self.icons["undo"],
  217. self.OnUndo))
  218. if not self.tools or 'redo' in self.tools:
  219. data.append(("redo", self.icons["redo"],
  220. self.OnRedo))
  221. if not self.tools or 'settings' in self.tools or \
  222. 'help' in self.tools or \
  223. 'quit' in self.tools:
  224. data.append((None, ))
  225. if not self.tools or 'settings' in self.tools:
  226. data.append(("settings", self.icons["settings"],
  227. self.OnSettings))
  228. if not self.tools or 'help' in self.tools:
  229. data.append(("help", self.icons["help"],
  230. self.OnHelp))
  231. if not self.tools or 'quit' in self.tools:
  232. data.append(("quit", self.icons["quit"],
  233. self.OnExit))
  234. return self._getToolbarData(data)
  235. def OnTool(self, event):
  236. """Tool selected -> untoggles previusly selected tool in
  237. toolbar"""
  238. Debug.msg(3, "VDigitToolbar.OnTool(): id = %s" % event.GetId())
  239. # set cursor
  240. self.MapWindow.SetNamedCursor('cross')
  241. self.MapWindow.mouse['box'] = 'point'
  242. self.MapWindow.mouse['use'] = 'pointer'
  243. aId = self.action.get('id', -1)
  244. BaseToolbar.OnTool(self, event)
  245. # clear tmp canvas
  246. if self.action['id'] != aId or aId == -1:
  247. self.MapWindow.polycoords = []
  248. self.MapWindow.ClearLines(pdc = self.MapWindow.pdcTmp)
  249. if self.digit and \
  250. len(self.MapWindow.digit.GetDisplay().GetSelected()) > 0:
  251. # cancel action
  252. self.MapWindow.OnMiddleDown(None)
  253. # set no action
  254. if self.action['id'] == -1:
  255. self.action = { 'desc' : '',
  256. 'type' : '',
  257. 'id' : -1 }
  258. # set focus
  259. self.MapWindow.SetFocus()
  260. def OnAddPoint(self, event):
  261. """Add point to the vector map Laier"""
  262. Debug.msg (2, "VDigitToolbar.OnAddPoint()")
  263. self.action = { 'desc' : "addLine",
  264. 'type' : "point",
  265. 'id' : self.addPoint }
  266. self.MapWindow.mouse['box'] = 'point'
  267. def OnAddLine(self, event):
  268. """Add line to the vector map layer"""
  269. Debug.msg (2, "VDigitToolbar.OnAddLine()")
  270. self.action = { 'desc' : "addLine",
  271. 'type' : "line",
  272. 'id' : self.addLine }
  273. self.MapWindow.mouse['box'] = 'line'
  274. ### self.MapWindow.polycoords = [] # reset temp line
  275. def OnAddBoundary(self, event):
  276. """Add boundary to the vector map layer"""
  277. Debug.msg (2, "VDigitToolbar.OnAddBoundary()")
  278. self._toggleAreaIfNeeded()
  279. # reset temp line
  280. if self.action['desc'] != 'addLine' or \
  281. self.action['type'] != 'boundary':
  282. self.MapWindow.polycoords = []
  283. # update icon and tooltip
  284. self.SetToolNormalBitmap(self.addArea, self.icons['addBoundary'].GetBitmap())
  285. self.SetToolShortHelp(self.addArea, self.icons['addBoundary'].GetLabel())
  286. # set action
  287. self.action = { 'desc' : "addLine",
  288. 'type' : "boundary",
  289. 'id' : self.addArea }
  290. self.MapWindow.mouse['box'] = 'line'
  291. self._currentAreaActionType = 'boundary'
  292. def OnAddCentroid(self, event):
  293. """Add centroid to the vector map layer"""
  294. Debug.msg (2, "VDigitToolbar.OnAddCentroid()")
  295. self._toggleAreaIfNeeded()
  296. # update icon and tooltip
  297. self.SetToolNormalBitmap(self.addArea, self.icons['addCentroid'].GetBitmap())
  298. self.SetToolShortHelp(self.addArea, self.icons['addCentroid'].GetLabel())
  299. # set action
  300. self.action = { 'desc' : "addLine",
  301. 'type' : "centroid",
  302. 'id' : self.addArea }
  303. self.MapWindow.mouse['box'] = 'point'
  304. self._currentAreaActionType = 'centroid'
  305. def OnAddArea(self, event):
  306. """Add area to the vector map layer"""
  307. Debug.msg (2, "VDigitToolbar.OnAddArea()")
  308. self._toggleAreaIfNeeded()
  309. # update icon and tooltip
  310. self.SetToolNormalBitmap(self.addArea, self.icons['addArea'].GetBitmap())
  311. self.SetToolShortHelp(self.addArea, self.icons['addArea'].GetLabel())
  312. # set action
  313. self.action = { 'desc' : "addLine",
  314. 'type' : "area",
  315. 'id' : self.addArea }
  316. self.MapWindow.mouse['box'] = 'line'
  317. self._currentAreaActionType = 'area'
  318. def _toggleAreaIfNeeded(self):
  319. """In some cases, the area tool is not toggled, we have to do it manually."""
  320. if not self.GetToolState(self.addArea):
  321. self.ToggleTool(self.addArea, True)
  322. self.toolSwitcher.ToolChanged(self.addArea)
  323. def OnAddAreaTool(self, event):
  324. """Area tool activated."""
  325. Debug.msg (2, "VDigitToolbar.OnAddAreaTool()")
  326. # we need the previous id
  327. if not self._currentAreaActionType or self._currentAreaActionType == 'area': # default action
  328. self.OnAddArea(event)
  329. elif self._currentAreaActionType == 'boundary':
  330. self.OnAddBoundary(event)
  331. elif self._currentAreaActionType == 'centroid':
  332. self.OnAddCentroid(event)
  333. def OnAddAreaMenu(self, event):
  334. """Digitize area menu (add area/boundary/centroid)"""
  335. menuItems = []
  336. if not self.tools or 'addArea' in self.tools:
  337. menuItems.append((self.icons["addArea"], self.OnAddArea))
  338. if not self.fType and not self.tools or 'addBoundary' in self.tools:
  339. menuItems.append((self.icons["addBoundary"], self.OnAddBoundary))
  340. if not self.fType and not self.tools or 'addCentroid' in self.tools:
  341. menuItems.append((self.icons["addCentroid"], self.OnAddCentroid))
  342. self._onMenu(menuItems)
  343. def OnExit (self, event = None):
  344. """Quit digitization tool"""
  345. # stop editing of the currently selected map layer
  346. if self.mapLayer:
  347. self.StopEditing()
  348. # close dialogs if still open
  349. if self.settingsDialog:
  350. self.settingsDialog.OnCancel(None)
  351. # set default mouse settings
  352. self.parent.GetMapToolbar().SelectDefault()
  353. self.MapWindow.polycoords = []
  354. # TODO: replace this by binding wx event in parent (or use signals...)
  355. if not self.parent.IsStandalone():
  356. # disable the toolbar
  357. self.parent.RemoveToolbar("vdigit")
  358. else:
  359. self.parent.Close()
  360. def OnMoveVertex(self, event):
  361. """Move line vertex"""
  362. Debug.msg(2, "Digittoolbar.OnMoveVertex():")
  363. self.action = { 'desc' : "moveVertex",
  364. 'id' : self.moveVertex }
  365. self.MapWindow.mouse['box'] = 'point'
  366. def OnAddVertex(self, event):
  367. """Add line vertex"""
  368. Debug.msg(2, "Digittoolbar.OnAddVertex():")
  369. self.action = { 'desc' : "addVertex",
  370. 'id' : self.addVertex }
  371. self.MapWindow.mouse['box'] = 'point'
  372. def OnRemoveVertex(self, event):
  373. """Remove line vertex"""
  374. Debug.msg(2, "Digittoolbar.OnRemoveVertex():")
  375. self.action = { 'desc' : "removeVertex",
  376. 'id' : self.removeVertex }
  377. self.MapWindow.mouse['box'] = 'point'
  378. def OnEditLine(self, event):
  379. """Edit line"""
  380. Debug.msg(2, "Digittoolbar.OnEditLine():")
  381. self.action = { 'desc' : "editLine",
  382. 'id' : self.editLine }
  383. self.MapWindow.mouse['box'] = 'line'
  384. def OnMoveLine(self, event):
  385. """Move line"""
  386. Debug.msg(2, "Digittoolbar.OnMoveLine():")
  387. self.action = { 'desc' : "moveLine",
  388. 'id' : self.moveLine }
  389. self.MapWindow.mouse['box'] = 'box'
  390. def OnDeleteLine(self, event):
  391. """Delete line"""
  392. Debug.msg(2, "Digittoolbar.OnDeleteLine():")
  393. self.action = { 'desc' : "deleteLine",
  394. 'id' : self.deleteLine }
  395. self.MapWindow.mouse['box'] = 'box'
  396. def OnDeleteArea(self, event):
  397. """Delete Area"""
  398. Debug.msg(2, "Digittoolbar.OnDeleteArea():")
  399. self.action = { 'desc' : "deleteArea",
  400. 'id' : self.deleteArea }
  401. self.MapWindow.mouse['box'] = 'box'
  402. def OnDisplayCats(self, event):
  403. """Display/update categories"""
  404. Debug.msg(2, "Digittoolbar.OnDisplayCats():")
  405. self.action = { 'desc' : "displayCats",
  406. 'id' : self.displayCats }
  407. self.MapWindow.mouse['box'] = 'point'
  408. def OnDisplayAttr(self, event):
  409. """Display/update attributes"""
  410. Debug.msg(2, "Digittoolbar.OnDisplayAttr():")
  411. self.action = { 'desc' : "displayAttrs",
  412. 'id' : self.displayAttr }
  413. self.MapWindow.mouse['box'] = 'point'
  414. def OnUndo(self, event):
  415. """Undo previous changes"""
  416. self.digit.Undo()
  417. event.Skip()
  418. def OnRedo(self, event):
  419. """Undo previous changes"""
  420. self.digit.Undo(level = 1)
  421. event.Skip()
  422. def EnableUndo(self, enable = True):
  423. """Enable 'Undo' in toolbar
  424. :param enable: False for disable
  425. """
  426. self._enableTool(self.undo, enable)
  427. def EnableRedo(self, enable = True):
  428. """Enable 'Redo' in toolbar
  429. :param enable: False for disable
  430. """
  431. self._enableTool(self.redo, enable)
  432. def _enableTool(self, tool, enable):
  433. if not self.FindById(tool):
  434. return
  435. if enable:
  436. if self.GetToolEnabled(tool) is False:
  437. self.EnableTool(tool, True)
  438. else:
  439. if self.GetToolEnabled(tool) is True:
  440. self.EnableTool(tool, False)
  441. def GetAction(self, type = 'desc'):
  442. """Get current action info"""
  443. return self.action.get(type, '')
  444. def OnSettings(self, event):
  445. """Show settings dialog"""
  446. if self.digit is None:
  447. try:
  448. self.digit = self.MapWindow.digit = self.digitClass(mapwindow = self.MapWindow)
  449. except SystemExit:
  450. self.digit = self.MapWindow.digit = None
  451. if not self.settingsDialog:
  452. self.settingsDialog = VDigitSettingsDialog(parent = self.parent, giface = self._giface)
  453. self.settingsDialog.Show()
  454. def OnHelp(self, event):
  455. """Show digitizer help page in web browser"""
  456. self._giface.Help('wxGUI.vdigit')
  457. def OnAdditionalToolMenu(self, event):
  458. """Menu for additional tools"""
  459. point = wx.GetMousePosition()
  460. toolMenu = wx.Menu()
  461. for label, itype, handler, desc in (
  462. (_('Break selected lines/boundaries at intersection'),
  463. wx.ITEM_CHECK, self.OnBreak, "breakLine"),
  464. (_('Connect selected lines/boundaries'),
  465. wx.ITEM_CHECK, self.OnConnect, "connectLine"),
  466. (_('Copy categories'),
  467. wx.ITEM_CHECK, self.OnCopyCats, "copyCats"),
  468. (_('Copy features from (background) vector map'),
  469. wx.ITEM_CHECK, self.OnCopy, "copyLine"),
  470. (_('Copy attributes'),
  471. wx.ITEM_CHECK, self.OnCopyAttrb, "copyAttrs"),
  472. (_('Feature type conversion'),
  473. wx.ITEM_CHECK, self.OnTypeConversion, "typeConv"),
  474. (_('Flip selected lines/boundaries'),
  475. wx.ITEM_CHECK, self.OnFlip, "flipLine"),
  476. (_('Merge selected lines/boundaries'),
  477. wx.ITEM_CHECK, self.OnMerge, "mergeLine"),
  478. (_('Snap selected lines/boundaries (only to nodes)'),
  479. wx.ITEM_CHECK, self.OnSnap, "snapLine"),
  480. (_('Split line/boundary'),
  481. wx.ITEM_CHECK, self.OnSplitLine, "splitLine"),
  482. (_('Query features'),
  483. wx.ITEM_CHECK, self.OnQuery, "queryLine"),
  484. (_('Z bulk-labeling of 3D lines'),
  485. wx.ITEM_CHECK, self.OnZBulk, "zbulkLine")):
  486. # Add items to the menu
  487. item = wx.MenuItem(parentMenu = toolMenu, id = wx.ID_ANY,
  488. text = label,
  489. kind = itype)
  490. toolMenu.AppendItem(item)
  491. self.MapWindow.Bind(wx.EVT_MENU, handler, item)
  492. if self.action['desc'] == desc:
  493. item.Check(True)
  494. # Popup the menu. If an item is selected then its handler
  495. # will be called before PopupMenu returns.
  496. self.MapWindow.PopupMenu(toolMenu)
  497. toolMenu.Destroy()
  498. if self.action['desc'] == 'addPoint':
  499. self.ToggleTool(self.additionalTools, False)
  500. def OnCopy(self, event):
  501. """Copy selected features from (background) vector map"""
  502. if not self.digit:
  503. GError(_("No vector map open for editing."), self.parent)
  504. return
  505. # select background map
  506. dlg = VectorDialog(self.parent, title = _("Select background vector map"),
  507. layerTree = self._giface.GetLayerTree())
  508. if dlg.ShowModal() != wx.ID_OK:
  509. dlg.Destroy()
  510. return
  511. mapName = dlg.GetName(full=True)
  512. dlg.Destroy()
  513. # close open background map if any
  514. bgMap = UserSettings.Get(group = 'vdigit', key = 'bgmap', subkey = 'value',
  515. settings_type='internal')
  516. if bgMap:
  517. self.digit.CloseBackgroundMap()
  518. self.editingBgMap.emit(mapName = bgMap, unset=True)
  519. # open background map for reading
  520. UserSettings.Set(group = 'vdigit', key = 'bgmap', subkey = 'value',
  521. value=str(mapName), settings_type='internal')
  522. self.digit.OpenBackgroundMap(mapName)
  523. self.editingBgMap.emit(mapName = mapName)
  524. if self.action['desc'] == 'copyLine': # select previous action
  525. self.ToggleTool(self.addPoint, True)
  526. self.ToggleTool(self.additionalTools, False)
  527. self.OnAddPoint(event)
  528. return
  529. Debug.msg(2, "Digittoolbar.OnCopy():")
  530. self.action = { 'desc' : "copyLine",
  531. 'id' : self.additionalTools }
  532. self.MapWindow.mouse['box'] = 'box'
  533. def OnSplitLine(self, event):
  534. """Split line"""
  535. if self.action['desc'] == 'splitLine': # select previous action
  536. self.ToggleTool(self.addPoint, True)
  537. self.ToggleTool(self.additionalTools, False)
  538. self.OnAddPoint(event)
  539. return
  540. Debug.msg(2, "Digittoolbar.OnSplitLine():")
  541. self.action = { 'desc' : "splitLine",
  542. 'id' : self.additionalTools }
  543. self.MapWindow.mouse['box'] = 'point'
  544. def OnCopyCats(self, event):
  545. """Copy categories"""
  546. if self.action['desc'] == 'copyCats': # select previous action
  547. self.ToggleTool(self.addPoint, True)
  548. self.ToggleTool(self.copyCats, False)
  549. self.OnAddPoint(event)
  550. return
  551. Debug.msg(2, "Digittoolbar.OnCopyCats():")
  552. self.action = { 'desc' : "copyCats",
  553. 'id' : self.additionalTools }
  554. self.MapWindow.mouse['box'] = 'point'
  555. def OnCopyAttrb(self, event):
  556. """Copy attributes"""
  557. if self.action['desc'] == 'copyAttrs': # select previous action
  558. self.ToggleTool(self.addPoint, True)
  559. self.ToggleTool(self.copyCats, False)
  560. self.OnAddPoint(event)
  561. return
  562. Debug.msg(2, "Digittoolbar.OnCopyAttrb():")
  563. self.action = { 'desc' : "copyAttrs",
  564. 'id' : self.additionalTools }
  565. self.MapWindow.mouse['box'] = 'point'
  566. def OnFlip(self, event):
  567. """Flip selected lines/boundaries"""
  568. if self.action['desc'] == 'flipLine': # select previous action
  569. self.ToggleTool(self.addPoint, True)
  570. self.ToggleTool(self.additionalTools, False)
  571. self.OnAddPoint(event)
  572. return
  573. Debug.msg(2, "Digittoolbar.OnFlip():")
  574. self.action = { 'desc' : "flipLine",
  575. 'id' : self.additionalTools }
  576. self.MapWindow.mouse['box'] = 'box'
  577. def OnMerge(self, event):
  578. """Merge selected lines/boundaries"""
  579. if self.action['desc'] == 'mergeLine': # select previous action
  580. self.ToggleTool(self.addPoint, True)
  581. self.ToggleTool(self.additionalTools, False)
  582. self.OnAddPoint(event)
  583. return
  584. Debug.msg(2, "Digittoolbar.OnMerge():")
  585. self.action = { 'desc' : "mergeLine",
  586. 'id' : self.additionalTools }
  587. self.MapWindow.mouse['box'] = 'box'
  588. def OnBreak(self, event):
  589. """Break selected lines/boundaries"""
  590. if self.action['desc'] == 'breakLine': # select previous action
  591. self.ToggleTool(self.addPoint, True)
  592. self.ToggleTool(self.additionalTools, False)
  593. self.OnAddPoint(event)
  594. return
  595. Debug.msg(2, "Digittoolbar.OnBreak():")
  596. self.action = { 'desc' : "breakLine",
  597. 'id' : self.additionalTools }
  598. self.MapWindow.mouse['box'] = 'box'
  599. def OnSnap(self, event):
  600. """Snap selected features"""
  601. if self.action['desc'] == 'snapLine': # select previous action
  602. self.ToggleTool(self.addPoint, True)
  603. self.ToggleTool(self.additionalTools, False)
  604. self.OnAddPoint(event)
  605. return
  606. Debug.msg(2, "Digittoolbar.OnSnap():")
  607. self.action = { 'desc' : "snapLine",
  608. 'id' : self.additionalTools }
  609. self.MapWindow.mouse['box'] = 'box'
  610. def OnConnect(self, event):
  611. """Connect selected lines/boundaries"""
  612. if self.action['desc'] == 'connectLine': # select previous action
  613. self.ToggleTool(self.addPoint, True)
  614. self.ToggleTool(self.additionalTools, False)
  615. self.OnAddPoint(event)
  616. return
  617. Debug.msg(2, "Digittoolbar.OnConnect():")
  618. self.action = { 'desc' : "connectLine",
  619. 'id' : self.additionalTools }
  620. self.MapWindow.mouse['box'] = 'box'
  621. def OnQuery(self, event):
  622. """Query selected lines/boundaries"""
  623. if self.action['desc'] == 'queryLine': # select previous action
  624. self.ToggleTool(self.addPoint, True)
  625. self.ToggleTool(self.additionalTools, False)
  626. self.OnAddPoint(event)
  627. return
  628. Debug.msg(2, "Digittoolbar.OnQuery(): %s" % \
  629. UserSettings.Get(group = 'vdigit', key = 'query', subkey = 'selection'))
  630. self.action = { 'desc' : "queryLine",
  631. 'id' : self.additionalTools }
  632. self.MapWindow.mouse['box'] = 'box'
  633. def OnZBulk(self, event):
  634. """Z bulk-labeling selected lines/boundaries"""
  635. if not self.digit.IsVector3D():
  636. GError(parent = self.parent,
  637. message = _("Vector map is not 3D. Operation canceled."))
  638. return
  639. if self.action['desc'] == 'zbulkLine': # select previous action
  640. self.ToggleTool(self.addPoint, True)
  641. self.ToggleTool(self.additionalTools, False)
  642. self.OnAddPoint(event)
  643. return
  644. Debug.msg(2, "Digittoolbar.OnZBulk():")
  645. self.action = { 'desc' : "zbulkLine",
  646. 'id' : self.additionalTools }
  647. self.MapWindow.mouse['box'] = 'line'
  648. def OnTypeConversion(self, event):
  649. """Feature type conversion
  650. Supported conversions:
  651. - point <-> centroid
  652. - line <-> boundary
  653. """
  654. if self.action['desc'] == 'typeConv': # select previous action
  655. self.ToggleTool(self.addPoint, True)
  656. self.ToggleTool(self.additionalTools, False)
  657. self.OnAddPoint(event)
  658. return
  659. Debug.msg(2, "Digittoolbar.OnTypeConversion():")
  660. self.action = { 'desc' : "typeConv",
  661. 'id' : self.additionalTools }
  662. self.MapWindow.mouse['box'] = 'box'
  663. def OnSelectMap (self, event):
  664. """Select vector map layer for editing
  665. If there is a vector map layer already edited, this action is
  666. firstly terminated. The map layer is closed. After this the
  667. selected map layer activated for editing.
  668. """
  669. if event.GetSelection() == 0: # create new vector map layer
  670. if self.mapLayer:
  671. openVectorMap = self.mapLayer.GetName(fullyQualified = False)['name']
  672. else:
  673. openVectorMap = None
  674. dlg = CreateNewVector(self.parent,
  675. exceptMap=openVectorMap, giface=self._giface,
  676. cmd=(('v.edit',
  677. {'tool': 'create'},
  678. 'map')),
  679. disableAdd = True)
  680. if dlg and dlg.GetName():
  681. # add layer to map layer tree
  682. if self._giface.GetLayerTree():
  683. mapName = dlg.GetName() + '@' + grass.gisenv()['MAPSET']
  684. self._giface.GetLayerList().AddLayer(ltype='vector',
  685. name=mapName,
  686. cmd=['d.vect', 'map=%s' % mapName])
  687. vectLayers = self.UpdateListOfLayers(updateTool = True)
  688. selection = vectLayers.index(mapName)
  689. # create table ?
  690. if dlg.IsChecked('table'):
  691. # TODO: replace this by signal
  692. # also note that starting of tools such as atm, iclass,
  693. # plots etc. should be handled in some better way
  694. # than starting randomly from mapdisp and lmgr
  695. lmgr = self.parent.GetLayerManager()
  696. if lmgr:
  697. lmgr.OnShowAttributeTable(None, selection = 'table')
  698. dlg.Destroy()
  699. else:
  700. self.combo.SetValue(_('Select vector map'))
  701. if dlg:
  702. dlg.Destroy()
  703. return
  704. else:
  705. selection = event.GetSelection() - 1 # first option is 'New vector map'
  706. # skip currently selected map
  707. if self.layers[selection] == self.mapLayer:
  708. return
  709. if self.mapLayer:
  710. # deactive map layer for editing
  711. self.StopEditing()
  712. # select the given map layer for editing
  713. self.StartEditing(self.layers[selection])
  714. event.Skip()
  715. def StartEditing(self, mapLayer):
  716. """Start editing selected vector map layer.
  717. :param mapLayer: MapLayer to be edited
  718. """
  719. # check if topology is available (skip for hidden - temporary
  720. # maps, see iclass for details)
  721. if not mapLayer.IsHidden() and grass.vector_info(mapLayer.GetName())['level'] != 2:
  722. dlg = wx.MessageDialog(parent = self.MapWindow,
  723. message = _("Topology for vector map <%s> is not available. "
  724. "Topology is required by digitizer.\nDo you want to "
  725. "rebuild topology (takes some time) and open the vector map "
  726. "for editing?") % mapLayer.GetName(),
  727. caption=_("Digitizer error"),
  728. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  729. if dlg.ShowModal() == wx.ID_YES:
  730. RunCommand('v.build', map=mapLayer.GetName())
  731. else:
  732. return
  733. # deactive layer
  734. self.Map.ChangeLayerActive(mapLayer, False)
  735. # clean map canvas
  736. self.MapWindow.EraseMap()
  737. # unset background map if needed
  738. if mapLayer:
  739. if UserSettings.Get(group = 'vdigit', key = 'bgmap',
  740. subkey = 'value', settings_type='internal') == mapLayer.GetName():
  741. UserSettings.Set(group = 'vdigit', key = 'bgmap',
  742. subkey='value', value='', settings_type='internal')
  743. self.parent.SetStatusText(_("Please wait, "
  744. "opening vector map <%s> for editing...") % mapLayer.GetName(),
  745. 0)
  746. self.MapWindow.pdcVector = wx.PseudoDC()
  747. self.digit = self.MapWindow.digit = self.digitClass(mapwindow = self.MapWindow)
  748. self.mapLayer = mapLayer
  749. # open vector map (assume that 'hidden' map layer is temporary vector map)
  750. if self.digit.OpenMap(mapLayer.GetName(), tmp = mapLayer.IsHidden()) is None:
  751. self.mapLayer = None
  752. self.StopEditing()
  753. return False
  754. # check feature type (only for OGR layers)
  755. self.fType = self.digit.GetFeatureType()
  756. self.EnableAll()
  757. self.EnableUndo(False)
  758. self.EnableRedo(False)
  759. if self.fType == 'point':
  760. for tool in (self.addLine, self.addArea, self.moveVertex, self.addVertex,
  761. self.removeVertex, self.editLine):
  762. self.EnableTool(tool, False)
  763. elif self.fType == 'linestring':
  764. for tool in (self.addPoint, self.addArea):
  765. self.EnableTool(tool, False)
  766. elif self.fType == 'polygon':
  767. for tool in (self.addPoint, self.addLine):
  768. self.EnableTool(tool, False)
  769. elif self.fType:
  770. GError(parent = self,
  771. message = _("Unsupported feature type '%(type)s'. Unable to edit "
  772. "OGR layer <%(layer)s>.") % { 'type' : self.fType,
  773. 'layer' : mapLayer.GetName() })
  774. self.digit.CloseMap()
  775. self.mapLayer = None
  776. self.StopEditing()
  777. return False
  778. # update toolbar
  779. if self.combo:
  780. self.combo.SetValue(mapLayer.GetName())
  781. if 'map' in self.parent.toolbars:
  782. self.parent.toolbars['map'].combo.SetValue (_('Vector digitizer'))
  783. # here was dead code to enable vdigit button in toolbar
  784. # with if to ignore iclass
  785. # some signal (DigitizerStarted) can be emitted here
  786. Debug.msg (4, "VDigitToolbar.StartEditing(): layer=%s" % mapLayer.GetName())
  787. # change cursor
  788. if self.MapWindow.mouse['use'] == 'pointer':
  789. self.MapWindow.SetNamedCursor('cross')
  790. if not self.MapWindow.resize:
  791. self.MapWindow.UpdateMap(render = True)
  792. # respect opacity
  793. opacity = mapLayer.GetOpacity()
  794. if opacity < 1.0:
  795. alpha = int(opacity * 255)
  796. self.digit.GetDisplay().UpdateSettings(alpha = alpha)
  797. # emit signal
  798. layerTree = self._giface.GetLayerTree()
  799. if layerTree:
  800. item = layerTree.FindItemByData('maplayer', self.mapLayer)
  801. else:
  802. item = None
  803. self.editingStarted.emit(vectMap = mapLayer.GetName(), digit = self.digit, layerItem = item)
  804. return True
  805. def StopEditing(self):
  806. """Stop editing of selected vector map layer.
  807. :return: True on success
  808. :return: False on failure
  809. """
  810. item = None
  811. if self.combo:
  812. self.combo.SetValue (_('Select vector map'))
  813. # save changes
  814. if self.mapLayer:
  815. Debug.msg (4, "VDigitToolbar.StopEditing(): layer=%s" % self.mapLayer.GetName())
  816. if UserSettings.Get(group = 'vdigit', key = 'saveOnExit', subkey = 'enabled') is False:
  817. if self.digit.GetUndoLevel() > -1:
  818. dlg = wx.MessageDialog(parent = self.parent,
  819. message = _("Do you want to save changes "
  820. "in vector map <%s>?") % self.mapLayer.GetName(),
  821. caption = _("Save changes?"),
  822. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  823. if dlg.ShowModal() == wx.ID_NO:
  824. # revert changes
  825. self.digit.Undo(0)
  826. dlg.Destroy()
  827. self.parent.SetStatusText(_("Please wait, "
  828. "closing and rebuilding topology of "
  829. "vector map <%s>...") % self.mapLayer.GetName(),
  830. 0)
  831. self.digit.CloseMap()
  832. # close open background map if any
  833. bgMap = UserSettings.Get(group = 'vdigit', key = 'bgmap', subkey = 'value',
  834. settings_type='internal')
  835. if bgMap:
  836. self.digit.CloseBackgroundMap()
  837. self.editingBgMap.emit(mapName = bgMap, unset=True)
  838. self._giface.GetProgress().SetValue(0)
  839. self._giface.WriteCmdLog(_("Editing of vector map <%s> successfully finished") % \
  840. self.mapLayer.GetName(),
  841. notification=Notification.HIGHLIGHT)
  842. # re-active layer
  843. layerTree = self._giface.GetLayerTree()
  844. if layerTree:
  845. item = layerTree.FindItemByData('maplayer', self.mapLayer)
  846. if item and layerTree.IsItemChecked(item):
  847. self.Map.ChangeLayerActive(self.mapLayer, True)
  848. # change cursor
  849. self.MapWindow.SetNamedCursor('default')
  850. self.MapWindow.pdcVector = None
  851. # close dialogs
  852. for dialog in ('attributes', 'category'):
  853. if self.parent.dialogs[dialog]:
  854. self.parent.dialogs[dialog].Close()
  855. self.parent.dialogs[dialog] = None
  856. del self.digit
  857. del self.MapWindow.digit
  858. self.editingStopped.emit(layerItem = item)
  859. self.mapLayer = None
  860. self.MapWindow.redrawAll = True
  861. return True
  862. def UpdateListOfLayers (self, updateTool = False):
  863. """Update list of available vector map layers.
  864. This list consists only editable layers (in the current mapset)
  865. :param updateTool: True to update also toolbar
  866. :type updateTool: bool
  867. """
  868. Debug.msg (4, "VDigitToolbar.UpdateListOfLayers(): updateTool=%d" % \
  869. updateTool)
  870. layerNameSelected = None
  871. # name of currently selected layer
  872. if self.mapLayer:
  873. layerNameSelected = self.mapLayer.GetName()
  874. # select vector map layer in the current mapset
  875. layerNameList = []
  876. self.layers = self.Map.GetListOfLayers(ltype = "vector",
  877. mapset = grass.gisenv()['MAPSET'])
  878. for layer in self.layers:
  879. if not layer.name in layerNameList: # do not duplicate layer
  880. layerNameList.append (layer.GetName())
  881. if updateTool: # update toolbar
  882. if not self.mapLayer:
  883. value = _('Select vector map')
  884. else:
  885. value = layerNameSelected
  886. if not self.comboid:
  887. if not self.tools or 'selector' in self.tools:
  888. self.combo = wx.ComboBox(self, id = wx.ID_ANY, value = value,
  889. choices = [_('New vector map'), ] + layerNameList, size = (80, -1),
  890. style = wx.CB_READONLY)
  891. self.comboid = self.InsertControl(0, self.combo)
  892. self.parent.Bind(wx.EVT_COMBOBOX, self.OnSelectMap, self.comboid)
  893. else:
  894. self.combo.SetItems([_('New vector map'), ] + layerNameList)
  895. self.Realize()
  896. return layerNameList
  897. def GetLayer(self):
  898. """Get selected layer for editing -- MapLayer instance"""
  899. return self.mapLayer