toolbars.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. """!
  2. @package vdigit.toolbars
  3. @brief wxGUI vector digitizer toolbars
  4. List of classes:
  5. - toolbars::VDigitToolbar
  6. (C) 2007-2012 by the GRASS Development Team
  7. This program is free software under the GNU General Public License
  8. (>=v2). Read the file COPYING that comes with GRASS for details.
  9. @author Martin Landa <landa.martin gmail.com>
  10. @author Stepan Turek <stepan.turek seznam.cz> (handlers support)
  11. """
  12. import wx
  13. from grass.script import core as grass
  14. from gui_core.toolbars import BaseToolbar, BaseIcons
  15. from gui_core.dialogs import CreateNewVector
  16. from vdigit.preferences import VDigitSettingsDialog
  17. from core.debug import Debug
  18. from core.settings import UserSettings
  19. from core.gcmd import GError, RunCommand
  20. from 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, toolSwitcher, MapWindow, digitClass, giface,
  27. tools=[], layerTree=None):
  28. self.MapWindow = MapWindow
  29. self.Map = MapWindow.GetMap() # Map class instance
  30. self.layerTree = layerTree # reference to layer tree associated to map display
  31. self.tools = tools
  32. self.digitClass = digitClass
  33. BaseToolbar.__init__(self, parent, toolSwitcher)
  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._default = -1
  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. for tool in ('addPoint', 'addLine', 'addBoundary', 'addCentroid', 'addArea',
  55. 'addVertex', 'deleteLine', 'deleteArea', 'displayAttr', 'displayCats',
  56. 'editLine', 'moveLine', 'moveVertex', 'removeVertex', 'additionalTools'):
  57. if hasattr(self, tool):
  58. tool = getattr(self, tool)
  59. self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
  60. # realize toolbar
  61. self.Realize()
  62. # workaround for Mac bug. May be fixed by 2.8.8, but not before then.
  63. if self.combo:
  64. self.combo.Hide()
  65. self.combo.Show()
  66. # disable undo/redo
  67. if self.undo > 0:
  68. self.EnableTool(self.undo, False)
  69. if self.redo > 0:
  70. self.EnableTool(self.redo, False)
  71. self.FixSize(width = 105)
  72. def _toolbarData(self):
  73. """!Toolbar data
  74. """
  75. data = []
  76. icons = {
  77. 'addPoint' : MetaIcon(img = 'point-create',
  78. label = _('Digitize new point'),
  79. desc = _('Left: new point')),
  80. 'addLine' : MetaIcon(img = 'line-create',
  81. label = _('Digitize new line'),
  82. desc = _('Left: new point; Ctrl+Left: undo last point; Right: close line')),
  83. 'addBoundary' : MetaIcon(img = 'boundary-create',
  84. label = _('Digitize new boundary'),
  85. desc = _('Left: new point; Ctrl+Left: undo last point; Right: close line')),
  86. 'addCentroid' : MetaIcon(img = 'centroid-create',
  87. label = _('Digitize new centroid'),
  88. desc = _('Left: new point')),
  89. 'addArea' : MetaIcon(img = 'polygon-create',
  90. label = _('Digitize new area (composition of boundaries without category and one centroid with category)'),
  91. desc = _('Left: new point')),
  92. 'addVertex' : MetaIcon(img = 'vertex-create',
  93. label = _('Add new vertex'),
  94. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  95. 'deleteLine' : MetaIcon(img = 'line-delete',
  96. label = _('Delete feature(s)'),
  97. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  98. 'deleteArea' : MetaIcon(img = 'polygon-delete',
  99. label = _('Delete area(s)'),
  100. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  101. 'displayAttr' : MetaIcon(img = 'attributes-display',
  102. label = _('Display/update attributes'),
  103. desc = _('Left: Select')),
  104. 'displayCats' : MetaIcon(img = 'cats-display',
  105. label = _('Display/update categories'),
  106. desc = _('Left: Select')),
  107. 'editLine' : MetaIcon(img = 'line-edit',
  108. label = _('Edit line/boundary'),
  109. desc = _('Left: new point; Ctrl+Left: undo last point; Right: close line')),
  110. 'moveLine' : MetaIcon(img = 'line-move',
  111. label = _('Move feature(s)'),
  112. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  113. 'moveVertex' : MetaIcon(img = 'vertex-move',
  114. label = _('Move vertex'),
  115. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  116. 'removeVertex' : MetaIcon(img = 'vertex-delete',
  117. label = _('Remove vertex'),
  118. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  119. 'settings' : BaseIcons['settings'].SetLabel(_('Digitization settings')),
  120. 'quit' : BaseIcons['quit'].SetLabel(label = _('Quit digitizer'),
  121. desc = _('Quit digitizer and save changes')),
  122. 'help' : BaseIcons['help'].SetLabel(label = _('Vector Digitizer manual'),
  123. desc = _('Show Vector Digitizer manual')),
  124. 'additionalTools' : MetaIcon(img = 'tools',
  125. label = _('Additional tools '
  126. '(copy, flip, connect, etc.)'),
  127. desc = _('Left: Select; Ctrl+Left: Unselect; Right: Confirm')),
  128. 'undo' : MetaIcon(img = 'undo',
  129. label = _('Undo'),
  130. desc = _('Undo previous changes')),
  131. 'redo' : MetaIcon(img = 'redo',
  132. label = _('Redo'),
  133. desc = _('Redo previous changes')),
  134. }
  135. if not self.tools or 'selector' in self.tools:
  136. data.append((None, ))
  137. if not self.tools or 'addPoint' in self.tools:
  138. data.append(("addPoint", icons["addPoint"],
  139. self.OnAddPoint,
  140. wx.ITEM_CHECK))
  141. if not self.tools or 'addLine' in self.tools:
  142. data.append(("addLine", icons["addLine"],
  143. self.OnAddLine,
  144. wx.ITEM_CHECK))
  145. if not self.tools or 'addBoundary' in self.tools:
  146. data.append(("addBoundary", icons["addBoundary"],
  147. self.OnAddBoundary,
  148. wx.ITEM_CHECK))
  149. if not self.tools or 'addCentroid' in self.tools:
  150. data.append(("addCentroid", icons["addCentroid"],
  151. self.OnAddCentroid,
  152. wx.ITEM_CHECK))
  153. if not self.tools or 'addArea' in self.tools:
  154. data.append(("addArea", icons["addArea"],
  155. self.OnAddArea,
  156. wx.ITEM_CHECK))
  157. if not self.tools or 'moveVertex' in self.tools:
  158. data.append(("moveVertex", icons["moveVertex"],
  159. self.OnMoveVertex,
  160. wx.ITEM_CHECK))
  161. if not self.tools or 'addVertex' in self.tools:
  162. data.append(("addVertex", icons["addVertex"],
  163. self.OnAddVertex,
  164. wx.ITEM_CHECK))
  165. if not self.tools or 'removeVertex' in self.tools:
  166. data.append(("removeVertex", icons["removeVertex"],
  167. self.OnRemoveVertex,
  168. wx.ITEM_CHECK))
  169. if not self.tools or 'editLine' in self.tools:
  170. data.append(("editLine", icons["editLine"],
  171. self.OnEditLine,
  172. wx.ITEM_CHECK))
  173. if not self.tools or 'moveLine' in self.tools:
  174. data.append(("moveLine", icons["moveLine"],
  175. self.OnMoveLine,
  176. wx.ITEM_CHECK))
  177. if not self.tools or 'deleteLine' in self.tools:
  178. data.append(("deleteLine", icons["deleteLine"],
  179. self.OnDeleteLine,
  180. wx.ITEM_CHECK))
  181. if not self.tools or 'deleteArea' in self.tools:
  182. data.append(("deleteArea", icons["deleteArea"],
  183. self.OnDeleteArea,
  184. wx.ITEM_CHECK))
  185. if not self.tools or 'displayCats' in self.tools:
  186. data.append(("displayCats", icons["displayCats"],
  187. self.OnDisplayCats,
  188. wx.ITEM_CHECK))
  189. if not self.tools or 'displayAttr' in self.tools:
  190. data.append(("displayAttr", icons["displayAttr"],
  191. self.OnDisplayAttr,
  192. wx.ITEM_CHECK))
  193. if not self.tools or 'additionalSelf.Tools' in self.tools:
  194. data.append(("additionalTools", icons["additionalTools"],
  195. self.OnAdditionalToolMenu,
  196. wx.ITEM_CHECK))
  197. if not self.tools or 'undo' in self.tools or \
  198. 'redo' in self.tools:
  199. data.append((None, ))
  200. if not self.tools or 'undo' in self.tools:
  201. data.append(("undo", icons["undo"],
  202. self.OnUndo))
  203. if not self.tools or 'redo' in self.tools:
  204. data.append(("redo", icons["redo"],
  205. self.OnRedo))
  206. if not self.tools or 'settings' in self.tools or \
  207. 'help' in self.tools or \
  208. 'quit' in self.tools:
  209. data.append((None, ))
  210. if not self.tools or 'settings' in self.tools:
  211. data.append(("settings", icons["settings"],
  212. self.OnSettings))
  213. if not self.tools or 'help' in self.tools:
  214. data.append(("help", icons["help"],
  215. self.OnHelp))
  216. if not self.tools or 'quit' in self.tools:
  217. data.append(("quit", icons["quit"],
  218. self.OnExit))
  219. return self._getToolbarData(data)
  220. def OnTool(self, event):
  221. """!Tool selected -> untoggles previusly selected tool in
  222. toolbar"""
  223. Debug.msg(3, "VDigitToolbar.OnTool(): id = %s" % event.GetId())
  224. # set cursor
  225. self.MapWindow.SetNamedCursor('cross')
  226. self.MapWindow.mouse['box'] = 'point'
  227. self.MapWindow.mouse['use'] = 'pointer'
  228. aId = self.action.get('id', -1)
  229. BaseToolbar.OnTool(self, event)
  230. # clear tmp canvas
  231. if self.action['id'] != aId or aId == -1:
  232. self.MapWindow.polycoords = []
  233. self.MapWindow.ClearLines(pdc = self.MapWindow.pdcTmp)
  234. if self.digit and \
  235. len(self.MapWindow.digit.GetDisplay().GetSelected()) > 0:
  236. # cancel action
  237. self.MapWindow.OnMiddleDown(None)
  238. # set no action
  239. if self.action['id'] == -1:
  240. self.action = { 'desc' : '',
  241. 'type' : '',
  242. 'id' : -1 }
  243. # set focus
  244. self.MapWindow.SetFocus()
  245. def OnAddPoint(self, event):
  246. """!Add point to the vector map Laier"""
  247. Debug.msg (2, "VDigitToolbar.OnAddPoint()")
  248. self.action = { 'desc' : "addLine",
  249. 'type' : "point",
  250. 'id' : self.addPoint }
  251. self.MapWindow.mouse['box'] = 'point'
  252. def OnAddLine(self, event):
  253. """!Add line to the vector map layer"""
  254. Debug.msg (2, "VDigitToolbar.OnAddLine()")
  255. self.action = { 'desc' : "addLine",
  256. 'type' : "line",
  257. 'id' : self.addLine }
  258. self.MapWindow.mouse['box'] = 'line'
  259. ### self.MapWindow.polycoords = [] # reset temp line
  260. def OnAddBoundary(self, event):
  261. """!Add boundary to the vector map layer"""
  262. Debug.msg (2, "VDigitToolbar.OnAddBoundary()")
  263. if self.action['desc'] != 'addLine' or \
  264. self.action['type'] != 'boundary':
  265. self.MapWindow.polycoords = [] # reset temp line
  266. self.action = { 'desc' : "addLine",
  267. 'type' : "boundary",
  268. 'id' : self.addBoundary }
  269. self.MapWindow.mouse['box'] = 'line'
  270. def OnAddCentroid(self, event):
  271. """!Add centroid to the vector map layer"""
  272. Debug.msg (2, "VDigitToolbar.OnAddCentroid()")
  273. self.action = { 'desc' : "addLine",
  274. 'type' : "centroid",
  275. 'id' : self.addCentroid }
  276. self.MapWindow.mouse['box'] = 'point'
  277. def OnAddArea(self, event):
  278. """!Add area to the vector map layer"""
  279. Debug.msg (2, "VDigitToolbar.OnAddArea()")
  280. self.action = { 'desc' : "addLine",
  281. 'type' : "area",
  282. 'id' : self.addArea }
  283. self.MapWindow.mouse['box'] = 'line'
  284. def OnExit (self, event = None):
  285. """!Quit digitization tool"""
  286. # stop editing of the currently selected map layer
  287. if self.mapLayer:
  288. self.StopEditing()
  289. # close dialogs if still open
  290. if self.settingsDialog:
  291. self.settingsDialog.OnCancel(None)
  292. # set default mouse settings
  293. self.parent.GetMapToolbar().SelectDefault()
  294. self.MapWindow.polycoords = []
  295. # TODO: replace this by binding wx event in parent (or use signals...)
  296. if not self.parent.IsStandalone():
  297. # disable the toolbar
  298. self.parent.RemoveToolbar("vdigit")
  299. else:
  300. self.parent.Close()
  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 GetAction(self, type = 'desc'):
  383. """!Get current action info"""
  384. return self.action.get(type, '')
  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, giface = self._giface)
  394. self.settingsDialog.Show()
  395. def OnHelp(self, event):
  396. """!Show digitizer help page in web browser"""
  397. self._giface.Help('wxGUI.vdigit')
  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, giface=self._giface,
  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._giface.GetLayerList().AddLayer(ltype='vector',
  604. name=mapName,
  605. cmd=['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. # TODO: replace this by signal
  611. # also note that starting of tools such as atm, iclass,
  612. # plots etc. should be handled in some better way
  613. # than starting randomly from mapdisp and lmgr
  614. lmgr = self.parent.GetLayerManager()
  615. if lmgr:
  616. lmgr.OnShowAttributeTable(None, selection = 'table')
  617. dlg.Destroy()
  618. else:
  619. self.combo.SetValue(_('Select vector map'))
  620. if dlg:
  621. dlg.Destroy()
  622. return
  623. else:
  624. selection = event.GetSelection() - 1 # first option is 'New vector map'
  625. # skip currently selected map
  626. if self.layers[selection] == self.mapLayer:
  627. return
  628. if self.mapLayer:
  629. # deactive map layer for editing
  630. self.StopEditing()
  631. # select the given map layer for editing
  632. self.StartEditing(self.layers[selection])
  633. event.Skip()
  634. def StartEditing (self, mapLayer):
  635. """!Start editing selected vector map layer.
  636. @param mapLayer MapLayer to be edited
  637. """
  638. # deactive layer
  639. self.Map.ChangeLayerActive(mapLayer, False)
  640. # clean map canvas
  641. self.MapWindow.EraseMap()
  642. # unset background map if needed
  643. if mapLayer:
  644. if UserSettings.Get(group = 'vdigit', key = 'bgmap',
  645. subkey = 'value', internal = True) == mapLayer.GetName():
  646. UserSettings.Set(group = 'vdigit', key = 'bgmap',
  647. subkey = 'value', value = '', internal = True)
  648. self.parent.SetStatusText(_("Please wait, "
  649. "opening vector map <%s> for editing...") % mapLayer.GetName(),
  650. 0)
  651. self.MapWindow.pdcVector = wx.PseudoDC()
  652. self.digit = self.MapWindow.digit = self.digitClass(mapwindow = self.MapWindow)
  653. self.mapLayer = mapLayer
  654. # open vector map (assume that 'hidden' map layer is temporary vector map)
  655. if self.digit.OpenMap(mapLayer.GetName(), tmp = mapLayer.IsHidden()) is None:
  656. self.mapLayer = None
  657. self.StopEditing()
  658. return False
  659. # check feature type (only for OGR layers)
  660. fType = self.digit.GetFeatureType()
  661. self.EnableAll()
  662. self.EnableUndo(False)
  663. self.EnableRedo(False)
  664. if fType == 'point':
  665. for tool in (self.addLine, self.addBoundary, self.addCentroid,
  666. self.addArea, self.moveVertex, self.addVertex,
  667. self.removeVertex, self.editLine):
  668. self.EnableTool(tool, False)
  669. elif fType == 'linestring':
  670. for tool in (self.addPoint, self.addBoundary, self.addCentroid,
  671. self.addArea):
  672. self.EnableTool(tool, False)
  673. elif fType == 'polygon':
  674. for tool in (self.addPoint, self.addLine, self.addBoundary, self.addCentroid):
  675. self.EnableTool(tool, False)
  676. elif fType:
  677. GError(parent = self,
  678. message = _("Unsupported feature type '%(type)s'. Unable to edit "
  679. "OGR layer <%(layer)s>.") % { 'type' : fType,
  680. 'layer' : mapLayer.GetName() })
  681. self.digit.CloseMap()
  682. self.mapLayer = None
  683. self.StopEditing()
  684. return False
  685. # update toolbar
  686. if self.combo:
  687. self.combo.SetValue(mapLayer.GetName())
  688. if 'map' in self.parent.toolbars:
  689. self.parent.toolbars['map'].combo.SetValue (_('Digitize'))
  690. # here was dead code to enable vdigit button in toolbar
  691. # with if to ignore iclass
  692. # some signal (DigitizerStarted) can be emitted here
  693. Debug.msg (4, "VDigitToolbar.StartEditing(): layer=%s" % mapLayer.GetName())
  694. # change cursor
  695. if self.MapWindow.mouse['use'] == 'pointer':
  696. self.MapWindow.SetNamedCursor('cross')
  697. if not self.MapWindow.resize:
  698. self.MapWindow.UpdateMap(render = True)
  699. # respect opacity
  700. opacity = mapLayer.GetOpacity(float = True)
  701. if opacity < 1.0:
  702. alpha = int(opacity * 255)
  703. self.digit.GetDisplay().UpdateSettings(alpha = alpha)
  704. return True
  705. def StopEditing(self):
  706. """!Stop editing of selected vector map layer.
  707. @return True on success
  708. @return False on failure
  709. """
  710. if self.combo:
  711. self.combo.SetValue (_('Select vector map'))
  712. # save changes
  713. if self.mapLayer:
  714. Debug.msg (4, "VDigitToolbar.StopEditing(): layer=%s" % self.mapLayer.GetName())
  715. if UserSettings.Get(group = 'vdigit', key = 'saveOnExit', subkey = 'enabled') is False:
  716. if self.digit.GetUndoLevel() > -1:
  717. dlg = wx.MessageDialog(parent = self.parent,
  718. message = _("Do you want to save changes "
  719. "in vector map <%s>?") % self.mapLayer.GetName(),
  720. caption = _("Save changes?"),
  721. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  722. if dlg.ShowModal() == wx.ID_NO:
  723. # revert changes
  724. self.digit.Undo(0)
  725. dlg.Destroy()
  726. self.parent.SetStatusText(_("Please wait, "
  727. "closing and rebuilding topology of "
  728. "vector map <%s>...") % self.mapLayer.GetName(),
  729. 0)
  730. self.digit.CloseMap()
  731. # TODO: replace by giface
  732. lmgr = self.parent.GetLayerManager()
  733. if lmgr:
  734. # here was dead code to enable vdigit button in toolbar
  735. # some signal (DigitizerEnded) can be emitted here
  736. lmgr._giface.GetProgress().SetValue(0)
  737. lmgr.GetLogWindow().WriteCmdLog(_("Editing of vector map <%s> successfully finished") % \
  738. self.mapLayer.GetName())
  739. # re-active layer
  740. if self.parent.tree:
  741. item = self.parent.tree.FindItemByData('maplayer', self.mapLayer)
  742. if item and self.parent.tree.IsItemChecked(item):
  743. self.Map.ChangeLayerActive(self.mapLayer, True)
  744. # change cursor
  745. self.MapWindow.SetNamedCursor('default')
  746. self.MapWindow.pdcVector = None
  747. # close dialogs
  748. for dialog in ('attributes', 'category'):
  749. if self.parent.dialogs[dialog]:
  750. self.parent.dialogs[dialog].Close()
  751. self.parent.dialogs[dialog] = None
  752. del self.digit
  753. del self.MapWindow.digit
  754. self.mapLayer = None
  755. self.MapWindow.redrawAll = True
  756. return True
  757. def UpdateListOfLayers (self, updateTool = False):
  758. """!Update list of available vector map layers.
  759. This list consists only editable layers (in the current mapset)
  760. @param updateTool True to update also toolbar
  761. """
  762. Debug.msg (4, "VDigitToolbar.UpdateListOfLayers(): updateTool=%d" % \
  763. updateTool)
  764. layerNameSelected = None
  765. # name of currently selected layer
  766. if self.mapLayer:
  767. layerNameSelected = self.mapLayer.GetName()
  768. # select vector map layer in the current mapset
  769. layerNameList = []
  770. self.layers = self.Map.GetListOfLayers(ltype = "vector",
  771. mapset = grass.gisenv()['MAPSET'])
  772. for layer in self.layers:
  773. if not layer.name in layerNameList: # do not duplicate layer
  774. layerNameList.append (layer.GetName())
  775. if updateTool: # update toolbar
  776. if not self.mapLayer:
  777. value = _('Select vector map')
  778. else:
  779. value = layerNameSelected
  780. if not self.comboid:
  781. if not self.tools or 'selector' in self.tools:
  782. self.combo = wx.ComboBox(self, id = wx.ID_ANY, value = value,
  783. choices = [_('New vector map'), ] + layerNameList, size = (80, -1),
  784. style = wx.CB_READONLY)
  785. self.comboid = self.InsertControl(0, self.combo)
  786. self.parent.Bind(wx.EVT_COMBOBOX, self.OnSelectMap, self.comboid)
  787. else:
  788. self.combo.SetItems([_('New vector map'), ] + layerNameList)
  789. self.Realize()
  790. return layerNameList
  791. def GetLayer(self):
  792. """!Get selected layer for editing -- MapLayer instance"""
  793. return self.mapLayer