toolbars.py 41 KB

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