toolbars.py 38 KB

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