toolbars.py 38 KB

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