toolbars.py 40 KB

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