toolbars.py 38 KB

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