toolbars.py 40 KB

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