toolbars.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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, 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. if not self.parent.IsStandalone():
  300. # disable the toolbar
  301. self.parent.RemoveToolbar("vdigit")
  302. else:
  303. self.parent.Close()
  304. def OnMoveVertex(self, event):
  305. """!Move line vertex"""
  306. Debug.msg(2, "Digittoolbar.OnMoveVertex():")
  307. self.action = { 'desc' : "moveVertex",
  308. 'id' : self.moveVertex }
  309. self.MapWindow.mouse['box'] = 'point'
  310. def OnAddVertex(self, event):
  311. """!Add line vertex"""
  312. Debug.msg(2, "Digittoolbar.OnAddVertex():")
  313. self.action = { 'desc' : "addVertex",
  314. 'id' : self.addVertex }
  315. self.MapWindow.mouse['box'] = 'point'
  316. def OnRemoveVertex(self, event):
  317. """!Remove line vertex"""
  318. Debug.msg(2, "Digittoolbar.OnRemoveVertex():")
  319. self.action = { 'desc' : "removeVertex",
  320. 'id' : self.removeVertex }
  321. self.MapWindow.mouse['box'] = 'point'
  322. def OnEditLine(self, event):
  323. """!Edit line"""
  324. Debug.msg(2, "Digittoolbar.OnEditLine():")
  325. self.action = { 'desc' : "editLine",
  326. 'id' : self.editLine }
  327. self.MapWindow.mouse['box'] = 'line'
  328. def OnMoveLine(self, event):
  329. """!Move line"""
  330. Debug.msg(2, "Digittoolbar.OnMoveLine():")
  331. self.action = { 'desc' : "moveLine",
  332. 'id' : self.moveLine }
  333. self.MapWindow.mouse['box'] = 'box'
  334. def OnDeleteLine(self, event):
  335. """!Delete line"""
  336. Debug.msg(2, "Digittoolbar.OnDeleteLine():")
  337. self.action = { 'desc' : "deleteLine",
  338. 'id' : self.deleteLine }
  339. self.MapWindow.mouse['box'] = 'box'
  340. def OnDeleteArea(self, event):
  341. """!Delete Area"""
  342. Debug.msg(2, "Digittoolbar.OnDeleteArea():")
  343. self.action = { 'desc' : "deleteArea",
  344. 'id' : self.deleteArea }
  345. self.MapWindow.mouse['box'] = 'box'
  346. def OnDisplayCats(self, event):
  347. """!Display/update categories"""
  348. Debug.msg(2, "Digittoolbar.OnDisplayCats():")
  349. self.action = { 'desc' : "displayCats",
  350. 'id' : self.displayCats }
  351. self.MapWindow.mouse['box'] = 'point'
  352. def OnDisplayAttr(self, event):
  353. """!Display/update attributes"""
  354. Debug.msg(2, "Digittoolbar.OnDisplayAttr():")
  355. self.action = { 'desc' : "displayAttrs",
  356. 'id' : self.displayAttr }
  357. self.MapWindow.mouse['box'] = 'point'
  358. def OnUndo(self, event):
  359. """!Undo previous changes"""
  360. self.digit.Undo()
  361. event.Skip()
  362. def OnRedo(self, event):
  363. """!Undo previous changes"""
  364. self.digit.Undo(level = 1)
  365. event.Skip()
  366. def EnableUndo(self, enable = True):
  367. """!Enable 'Undo' in toolbar
  368. @param enable False for disable
  369. """
  370. self._enableTool(self.undo, enable)
  371. def EnableRedo(self, enable = True):
  372. """!Enable 'Redo' in toolbar
  373. @param enable False for disable
  374. """
  375. self._enableTool(self.redo, enable)
  376. def _enableTool(self, tool, enable):
  377. if not self.FindById(tool):
  378. return
  379. if enable:
  380. if self.GetToolEnabled(tool) is False:
  381. self.EnableTool(tool, True)
  382. else:
  383. if self.GetToolEnabled(tool) is True:
  384. self.EnableTool(tool, False)
  385. def OnSettings(self, event):
  386. """!Show settings dialog"""
  387. if self.digit is None:
  388. try:
  389. self.digit = self.MapWindow.digit = self.digitClass(mapwindow = self.MapWindow)
  390. except SystemExit:
  391. self.digit = self.MapWindow.digit = None
  392. if not self.settingsDialog:
  393. self.settingsDialog = VDigitSettingsDialog(parent = self.parent, title = _("Digitization settings"),
  394. style = wx.DEFAULT_DIALOG_STYLE)
  395. self.settingsDialog.Show()
  396. def OnHelp(self, event):
  397. """!Show digitizer help page in web browser"""
  398. try:
  399. log = self.parent.GetLayerManager().GetLogWindow()
  400. except:
  401. log = None
  402. if log:
  403. log.RunCmd(['g.manual',
  404. 'entry = wxGUI.vdigit'])
  405. else:
  406. RunCommand('g.manual',
  407. entry = 'wxGUI.vdigit')
  408. def OnAdditionalToolMenu(self, event):
  409. """!Menu for additional tools"""
  410. point = wx.GetMousePosition()
  411. toolMenu = wx.Menu()
  412. for label, itype, handler, desc in (
  413. (_('Break selected lines/boundaries at intersection'),
  414. wx.ITEM_CHECK, self.OnBreak, "breakLine"),
  415. (_('Connect selected lines/boundaries'),
  416. wx.ITEM_CHECK, self.OnConnect, "connectLine"),
  417. (_('Copy categories'),
  418. wx.ITEM_CHECK, self.OnCopyCats, "copyCats"),
  419. (_('Copy features from (background) vector map'),
  420. wx.ITEM_CHECK, self.OnCopy, "copyLine"),
  421. (_('Copy attributes'),
  422. wx.ITEM_CHECK, self.OnCopyAttrb, "copyAttrs"),
  423. (_('Feature type conversion'),
  424. wx.ITEM_CHECK, self.OnTypeConversion, "typeConv"),
  425. (_('Flip selected lines/boundaries'),
  426. wx.ITEM_CHECK, self.OnFlip, "flipLine"),
  427. (_('Merge selected lines/boundaries'),
  428. wx.ITEM_CHECK, self.OnMerge, "mergeLine"),
  429. (_('Snap selected lines/boundaries (only to nodes)'),
  430. wx.ITEM_CHECK, self.OnSnap, "snapLine"),
  431. (_('Split line/boundary'),
  432. wx.ITEM_CHECK, self.OnSplitLine, "splitLine"),
  433. (_('Query features'),
  434. wx.ITEM_CHECK, self.OnQuery, "queryLine"),
  435. (_('Z bulk-labeling of 3D lines'),
  436. wx.ITEM_CHECK, self.OnZBulk, "zbulkLine")):
  437. # Add items to the menu
  438. item = wx.MenuItem(parentMenu = toolMenu, id = wx.ID_ANY,
  439. text = label,
  440. kind = itype)
  441. toolMenu.AppendItem(item)
  442. self.MapWindow.Bind(wx.EVT_MENU, handler, item)
  443. if self.action['desc'] == desc:
  444. item.Check(True)
  445. # Popup the menu. If an item is selected then its handler
  446. # will be called before PopupMenu returns.
  447. self.MapWindow.PopupMenu(toolMenu)
  448. toolMenu.Destroy()
  449. if self.action['desc'] == 'addPoint':
  450. self.ToggleTool(self.additionalTools, False)
  451. def OnCopy(self, event):
  452. """!Copy selected features from (background) vector map"""
  453. if self.action['desc'] == 'copyLine': # select previous action
  454. self.ToggleTool(self.addPoint, True)
  455. self.ToggleTool(self.additionalTools, False)
  456. self.OnAddPoint(event)
  457. return
  458. Debug.msg(2, "Digittoolbar.OnCopy():")
  459. self.action = { 'desc' : "copyLine",
  460. 'id' : self.additionalTools }
  461. self.MapWindow.mouse['box'] = 'box'
  462. def OnSplitLine(self, event):
  463. """!Split line"""
  464. if self.action['desc'] == 'splitLine': # select previous action
  465. self.ToggleTool(self.addPoint, True)
  466. self.ToggleTool(self.additionalTools, False)
  467. self.OnAddPoint(event)
  468. return
  469. Debug.msg(2, "Digittoolbar.OnSplitLine():")
  470. self.action = { 'desc' : "splitLine",
  471. 'id' : self.additionalTools }
  472. self.MapWindow.mouse['box'] = 'point'
  473. def OnCopyCats(self, event):
  474. """!Copy categories"""
  475. if self.action['desc'] == 'copyCats': # select previous action
  476. self.ToggleTool(self.addPoint, True)
  477. self.ToggleTool(self.copyCats, False)
  478. self.OnAddPoint(event)
  479. return
  480. Debug.msg(2, "Digittoolbar.OnCopyCats():")
  481. self.action = { 'desc' : "copyCats",
  482. 'id' : self.additionalTools }
  483. self.MapWindow.mouse['box'] = 'point'
  484. def OnCopyAttrb(self, event):
  485. """!Copy attributes"""
  486. if self.action['desc'] == 'copyAttrs': # select previous action
  487. self.ToggleTool(self.addPoint, True)
  488. self.ToggleTool(self.copyCats, False)
  489. self.OnAddPoint(event)
  490. return
  491. Debug.msg(2, "Digittoolbar.OnCopyAttrb():")
  492. self.action = { 'desc' : "copyAttrs",
  493. 'id' : self.additionalTools }
  494. self.MapWindow.mouse['box'] = 'point'
  495. def OnFlip(self, event):
  496. """!Flip selected lines/boundaries"""
  497. if self.action['desc'] == 'flipLine': # select previous action
  498. self.ToggleTool(self.addPoint, True)
  499. self.ToggleTool(self.additionalTools, False)
  500. self.OnAddPoint(event)
  501. return
  502. Debug.msg(2, "Digittoolbar.OnFlip():")
  503. self.action = { 'desc' : "flipLine",
  504. 'id' : self.additionalTools }
  505. self.MapWindow.mouse['box'] = 'box'
  506. def OnMerge(self, event):
  507. """!Merge selected lines/boundaries"""
  508. if self.action['desc'] == 'mergeLine': # select previous action
  509. self.ToggleTool(self.addPoint, True)
  510. self.ToggleTool(self.additionalTools, False)
  511. self.OnAddPoint(event)
  512. return
  513. Debug.msg(2, "Digittoolbar.OnMerge():")
  514. self.action = { 'desc' : "mergeLine",
  515. 'id' : self.additionalTools }
  516. self.MapWindow.mouse['box'] = 'box'
  517. def OnBreak(self, event):
  518. """!Break selected lines/boundaries"""
  519. if self.action['desc'] == 'breakLine': # select previous action
  520. self.ToggleTool(self.addPoint, True)
  521. self.ToggleTool(self.additionalTools, False)
  522. self.OnAddPoint(event)
  523. return
  524. Debug.msg(2, "Digittoolbar.OnBreak():")
  525. self.action = { 'desc' : "breakLine",
  526. 'id' : self.additionalTools }
  527. self.MapWindow.mouse['box'] = 'box'
  528. def OnSnap(self, event):
  529. """!Snap selected features"""
  530. if self.action['desc'] == 'snapLine': # select previous action
  531. self.ToggleTool(self.addPoint, True)
  532. self.ToggleTool(self.additionalTools, False)
  533. self.OnAddPoint(event)
  534. return
  535. Debug.msg(2, "Digittoolbar.OnSnap():")
  536. self.action = { 'desc' : "snapLine",
  537. 'id' : self.additionalTools }
  538. self.MapWindow.mouse['box'] = 'box'
  539. def OnConnect(self, event):
  540. """!Connect selected lines/boundaries"""
  541. if self.action['desc'] == 'connectLine': # select previous action
  542. self.ToggleTool(self.addPoint, True)
  543. self.ToggleTool(self.additionalTools, False)
  544. self.OnAddPoint(event)
  545. return
  546. Debug.msg(2, "Digittoolbar.OnConnect():")
  547. self.action = { 'desc' : "connectLine",
  548. 'id' : self.additionalTools }
  549. self.MapWindow.mouse['box'] = 'box'
  550. def OnQuery(self, event):
  551. """!Query selected lines/boundaries"""
  552. if self.action['desc'] == 'queryLine': # select previous action
  553. self.ToggleTool(self.addPoint, True)
  554. self.ToggleTool(self.additionalTools, False)
  555. self.OnAddPoint(event)
  556. return
  557. Debug.msg(2, "Digittoolbar.OnQuery(): %s" % \
  558. UserSettings.Get(group = 'vdigit', key = 'query', subkey = 'selection'))
  559. self.action = { 'desc' : "queryLine",
  560. 'id' : self.additionalTools }
  561. self.MapWindow.mouse['box'] = 'box'
  562. def OnZBulk(self, event):
  563. """!Z bulk-labeling selected lines/boundaries"""
  564. if not self.digit.IsVector3D():
  565. GError(parent = self.parent,
  566. message = _("Vector map is not 3D. Operation canceled."))
  567. return
  568. if self.action['desc'] == 'zbulkLine': # select previous action
  569. self.ToggleTool(self.addPoint, True)
  570. self.ToggleTool(self.additionalTools, False)
  571. self.OnAddPoint(event)
  572. return
  573. Debug.msg(2, "Digittoolbar.OnZBulk():")
  574. self.action = { 'desc' : "zbulkLine",
  575. 'id' : self.additionalTools }
  576. self.MapWindow.mouse['box'] = 'line'
  577. def OnTypeConversion(self, event):
  578. """!Feature type conversion
  579. Supported conversions:
  580. - point <-> centroid
  581. - line <-> boundary
  582. """
  583. if self.action['desc'] == 'typeConv': # 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.OnTypeConversion():")
  589. self.action = { 'desc' : "typeConv",
  590. 'id' : self.additionalTools }
  591. self.MapWindow.mouse['box'] = 'box'
  592. def OnSelectMap (self, event):
  593. """!Select vector map layer for editing
  594. If there is a vector map layer already edited, this action is
  595. firstly terminated. The map layer is closed. After this the
  596. selected map layer activated for editing.
  597. """
  598. if event.GetSelection() == 0: # create new vector map layer
  599. if self.mapLayer:
  600. openVectorMap = self.mapLayer.GetName(fullyQualified = False)['name']
  601. else:
  602. openVectorMap = None
  603. dlg = CreateNewVector(self.parent,
  604. exceptMap = openVectorMap, log = self.log,
  605. cmd = (('v.edit',
  606. { 'tool' : 'create' },
  607. 'map')),
  608. disableAdd = True)
  609. if dlg and dlg.GetName():
  610. # add layer to map layer tree
  611. if self.layerTree:
  612. mapName = dlg.GetName() + '@' + grass.gisenv()['MAPSET']
  613. self.layerTree.AddLayer(ltype = 'vector',
  614. lname = mapName,
  615. lcmd = ['d.vect', 'map=%s' % mapName])
  616. vectLayers = self.UpdateListOfLayers(updateTool = True)
  617. selection = vectLayers.index(mapName)
  618. # create table ?
  619. if dlg.IsChecked('table'):
  620. lmgr = self.parent.GetLayerManager()
  621. if lmgr:
  622. lmgr.OnShowAttributeTable(None, selection = 'table')
  623. dlg.Destroy()
  624. else:
  625. self.combo.SetValue(_('Select vector map'))
  626. if dlg:
  627. dlg.Destroy()
  628. return
  629. else:
  630. selection = event.GetSelection() - 1 # first option is 'New vector map'
  631. # skip currently selected map
  632. if self.layers[selection] == self.mapLayer:
  633. return
  634. if self.mapLayer:
  635. # deactive map layer for editing
  636. self.StopEditing()
  637. # select the given map layer for editing
  638. self.StartEditing(self.layers[selection])
  639. event.Skip()
  640. def StartEditing (self, mapLayer):
  641. """!Start editing selected vector map layer.
  642. @param mapLayer MapLayer to be edited
  643. """
  644. # deactive layer
  645. self.Map.ChangeLayerActive(mapLayer, False)
  646. # clean map canvas
  647. self.MapWindow.EraseMap()
  648. # unset background map if needed
  649. if mapLayer:
  650. if UserSettings.Get(group = 'vdigit', key = 'bgmap',
  651. subkey = 'value', internal = True) == mapLayer.GetName():
  652. UserSettings.Set(group = 'vdigit', key = 'bgmap',
  653. subkey = 'value', value = '', internal = True)
  654. self.parent.SetStatusText(_("Please wait, "
  655. "opening vector map <%s> for editing...") % mapLayer.GetName(),
  656. 0)
  657. self.MapWindow.pdcVector = wx.PseudoDC()
  658. self.digit = self.MapWindow.digit = self.digitClass(mapwindow = self.MapWindow)
  659. self.mapLayer = mapLayer
  660. # open vector map
  661. if self.digit.OpenMap(mapLayer.GetName()) is None:
  662. self.mapLayer = None
  663. self.StopEditing()
  664. return False
  665. # check feature type (only for OGR layers)
  666. fType = self.digit.GetFeatureType()
  667. self.EnableAll()
  668. self.EnableUndo(False)
  669. self.EnableRedo(False)
  670. if fType == 'point':
  671. for tool in (self.addLine, self.addBoundary, self.addCentroid,
  672. self.addArea, self.moveVertex, self.addVertex,
  673. self.removeVertex, self.editLine):
  674. self.EnableTool(tool, False)
  675. elif fType == 'linestring':
  676. for tool in (self.addPoint, self.addBoundary, self.addCentroid,
  677. self.addArea):
  678. self.EnableTool(tool, False)
  679. elif fType == 'polygon':
  680. for tool in (self.addPoint, self.addLine, self.addBoundary, self.addCentroid):
  681. self.EnableTool(tool, False)
  682. elif fType:
  683. GError(parent = self,
  684. message = _("Unsupported feature type '%(type)s'. Unable to edit "
  685. "OGR layer <%(layer)s>.") % { 'type' : fType,
  686. 'layer' : mapLayer.GetName() })
  687. self.digit.CloseMap()
  688. self.mapLayer = None
  689. self.StopEditing()
  690. return False
  691. # update toolbar
  692. if self.combo:
  693. self.combo.SetValue(mapLayer.GetName())
  694. if 'map' in self.parent.toolbars:
  695. self.parent.toolbars['map'].combo.SetValue (_('Digitize'))
  696. if self.digitClass != IClassVDigit:
  697. lmgr = self.parent.GetLayerManager()
  698. if lmgr:
  699. lmgr.toolbars['tools'].Enable('vdigit', enable = False)
  700. Debug.msg (4, "VDigitToolbar.StartEditing(): layer=%s" % mapLayer.GetName())
  701. # change cursor
  702. if self.MapWindow.mouse['use'] == 'pointer':
  703. self.MapWindow.SetCursor(self.parent.cursors["cross"])
  704. if not self.MapWindow.resize:
  705. self.MapWindow.UpdateMap(render = True)
  706. # respect opacity
  707. opacity = mapLayer.GetOpacity(float = True)
  708. if opacity < 1.0:
  709. alpha = int(opacity * 255)
  710. self.digit.GetDisplay().UpdateSettings(alpha = alpha)
  711. return True
  712. def StopEditing(self):
  713. """!Stop editing of selected vector map layer.
  714. @return True on success
  715. @return False on failure
  716. """
  717. if self.combo:
  718. self.combo.SetValue (_('Select vector map'))
  719. # save changes
  720. if self.mapLayer:
  721. Debug.msg (4, "VDigitToolbar.StopEditing(): layer=%s" % self.mapLayer.GetName())
  722. if UserSettings.Get(group = 'vdigit', key = 'saveOnExit', subkey = 'enabled') is False:
  723. if self.digit.GetUndoLevel() > -1:
  724. dlg = wx.MessageDialog(parent = self.parent,
  725. message = _("Do you want to save changes "
  726. "in vector map <%s>?") % self.mapLayer.GetName(),
  727. caption = _("Save changes?"),
  728. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  729. if dlg.ShowModal() == wx.ID_NO:
  730. # revert changes
  731. self.digit.Undo(0)
  732. dlg.Destroy()
  733. self.parent.SetStatusText(_("Please wait, "
  734. "closing and rebuilding topology of "
  735. "vector map <%s>...") % self.mapLayer.GetName(),
  736. 0)
  737. self.digit.CloseMap()
  738. # TODO: replace by giface
  739. lmgr = self.parent.GetLayerManager()
  740. if lmgr:
  741. lmgr.toolbars['tools'].Enable('vdigit', enable = True)
  742. lmgr._giface.GetProgress().SetValue(0)
  743. lmgr.GetLogWindow().WriteCmdLog(_("Editing of vector map <%s> successfully finished") % \
  744. self.mapLayer.GetName())
  745. # re-active layer
  746. if self.parent.tree:
  747. item = self.parent.tree.FindItemByData('maplayer', self.mapLayer)
  748. if item and self.parent.tree.IsItemChecked(item):
  749. self.Map.ChangeLayerActive(self.mapLayer, True)
  750. # change cursor
  751. self.MapWindow.SetCursor(self.parent.cursors["default"])
  752. self.MapWindow.pdcVector = None
  753. # close dialogs
  754. for dialog in ('attributes', 'category'):
  755. if self.parent.dialogs[dialog]:
  756. self.parent.dialogs[dialog].Close()
  757. self.parent.dialogs[dialog] = None
  758. del self.digit
  759. del self.MapWindow.digit
  760. self.mapLayer = None
  761. self.MapWindow.redrawAll = True
  762. return True
  763. def UpdateListOfLayers (self, updateTool = False):
  764. """!Update list of available vector map layers.
  765. This list consists only editable layers (in the current mapset)
  766. @param updateTool True to update also toolbar
  767. """
  768. Debug.msg (4, "VDigitToolbar.UpdateListOfLayers(): updateTool=%d" % \
  769. updateTool)
  770. layerNameSelected = None
  771. # name of currently selected layer
  772. if self.mapLayer:
  773. layerNameSelected = self.mapLayer.GetName()
  774. # select vector map layer in the current mapset
  775. layerNameList = []
  776. self.layers = self.Map.GetListOfLayers(l_type = "vector",
  777. l_mapset = grass.gisenv()['MAPSET'])
  778. for layer in self.layers:
  779. if not layer.name in layerNameList: # do not duplicate layer
  780. layerNameList.append (layer.GetName())
  781. if updateTool: # update toolbar
  782. if not self.mapLayer:
  783. value = _('Select vector map')
  784. else:
  785. value = layerNameSelected
  786. if not self.comboid:
  787. if not self.tools or 'selector' in self.tools:
  788. self.combo = wx.ComboBox(self, id = wx.ID_ANY, value = value,
  789. choices = [_('New vector map'), ] + layerNameList, size = (80, -1),
  790. style = wx.CB_READONLY)
  791. self.comboid = self.InsertControl(0, self.combo)
  792. self.parent.Bind(wx.EVT_COMBOBOX, self.OnSelectMap, self.comboid)
  793. else:
  794. self.combo.SetItems([_('New vector map'), ] + layerNameList)
  795. self.Realize()
  796. return layerNameList
  797. def GetLayer(self):
  798. """!Get selected layer for editing -- MapLayer instance"""
  799. return self.mapLayer