toolbars.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  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,
  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)
  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. self.MapWindow.SetNamedCursor('cross')
  230. # pointer
  231. self.parent.OnPointer(None)
  232. aId = self.action.get('id', -1)
  233. BaseToolbar.OnTool(self, event)
  234. # clear tmp canvas
  235. if self.action['id'] != aId or aId == -1:
  236. self.MapWindow.polycoords = []
  237. self.MapWindow.ClearLines(pdc = self.MapWindow.pdcTmp)
  238. if self.digit and \
  239. len(self.MapWindow.digit.GetDisplay().GetSelected()) > 0:
  240. # cancel action
  241. self.MapWindow.OnMiddleDown(None)
  242. # set no action
  243. if self.action['id'] == -1:
  244. self.action = { 'desc' : '',
  245. 'type' : '',
  246. 'id' : -1 }
  247. # set focus
  248. self.MapWindow.SetFocus()
  249. def OnAddPoint(self, event):
  250. """!Add point to the vector map Laier"""
  251. Debug.msg (2, "VDigitToolbar.OnAddPoint()")
  252. self.action = { 'desc' : "addLine",
  253. 'type' : "point",
  254. 'id' : self.addPoint }
  255. self.MapWindow.mouse['box'] = 'point'
  256. def OnAddLine(self, event):
  257. """!Add line to the vector map layer"""
  258. Debug.msg (2, "VDigitToolbar.OnAddLine()")
  259. self.action = { 'desc' : "addLine",
  260. 'type' : "line",
  261. 'id' : self.addLine }
  262. self.MapWindow.mouse['box'] = 'line'
  263. ### self.MapWindow.polycoords = [] # reset temp line
  264. def OnAddBoundary(self, event):
  265. """!Add boundary to the vector map layer"""
  266. Debug.msg (2, "VDigitToolbar.OnAddBoundary()")
  267. if self.action['desc'] != 'addLine' or \
  268. self.action['type'] != 'boundary':
  269. self.MapWindow.polycoords = [] # reset temp line
  270. self.action = { 'desc' : "addLine",
  271. 'type' : "boundary",
  272. 'id' : self.addBoundary }
  273. self.MapWindow.mouse['box'] = 'line'
  274. def OnAddCentroid(self, event):
  275. """!Add centroid to the vector map layer"""
  276. Debug.msg (2, "VDigitToolbar.OnAddCentroid()")
  277. self.action = { 'desc' : "addLine",
  278. 'type' : "centroid",
  279. 'id' : self.addCentroid }
  280. self.MapWindow.mouse['box'] = 'point'
  281. def OnAddArea(self, event):
  282. """!Add area to the vector map layer"""
  283. Debug.msg (2, "VDigitToolbar.OnAddCentroid()")
  284. self.action = { 'desc' : "addLine",
  285. 'type' : "area",
  286. 'id' : self.addArea }
  287. self.MapWindow.mouse['box'] = 'line'
  288. def OnExit (self, event = None):
  289. """!Quit digitization tool"""
  290. # stop editing of the currently selected map layer
  291. if self.mapLayer:
  292. self.StopEditing()
  293. # close dialogs if still open
  294. if self.settingsDialog:
  295. self.settingsDialog.OnCancel(None)
  296. # set default mouse settings
  297. self.MapWindow.mouse['use'] = "pointer"
  298. self.MapWindow.mouse['box'] = "point"
  299. self.MapWindow.polycoords = []
  300. # TODO: replace this by binding wx event in parent (or use signals...)
  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, giface=self._giface,
  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. # TODO: replace this by signal
  613. # also note that starting of tools such as atm, iclass,
  614. # plots etc. should be handled in some better way
  615. # than starting randomly from mapdisp and lmgr
  616. lmgr = self.parent.GetLayerManager()
  617. if lmgr:
  618. lmgr.OnShowAttributeTable(None, selection = 'table')
  619. dlg.Destroy()
  620. else:
  621. self.combo.SetValue(_('Select vector map'))
  622. if dlg:
  623. dlg.Destroy()
  624. return
  625. else:
  626. selection = event.GetSelection() - 1 # first option is 'New vector map'
  627. # skip currently selected map
  628. if self.layers[selection] == self.mapLayer:
  629. return
  630. if self.mapLayer:
  631. # deactive map layer for editing
  632. self.StopEditing()
  633. # select the given map layer for editing
  634. self.StartEditing(self.layers[selection])
  635. event.Skip()
  636. def StartEditing (self, mapLayer):
  637. """!Start editing selected vector map layer.
  638. @param mapLayer MapLayer to be edited
  639. """
  640. # deactive layer
  641. self.Map.ChangeLayerActive(mapLayer, False)
  642. # clean map canvas
  643. self.MapWindow.EraseMap()
  644. # unset background map if needed
  645. if mapLayer:
  646. if UserSettings.Get(group = 'vdigit', key = 'bgmap',
  647. subkey = 'value', internal = True) == mapLayer.GetName():
  648. UserSettings.Set(group = 'vdigit', key = 'bgmap',
  649. subkey = 'value', value = '', internal = True)
  650. self.parent.SetStatusText(_("Please wait, "
  651. "opening vector map <%s> for editing...") % mapLayer.GetName(),
  652. 0)
  653. self.MapWindow.pdcVector = wx.PseudoDC()
  654. self.digit = self.MapWindow.digit = self.digitClass(mapwindow = self.MapWindow)
  655. self.mapLayer = mapLayer
  656. # open vector map
  657. if self.digit.OpenMap(mapLayer.GetName()) is None:
  658. self.mapLayer = None
  659. self.StopEditing()
  660. return False
  661. # check feature type (only for OGR layers)
  662. fType = self.digit.GetFeatureType()
  663. self.EnableAll()
  664. self.EnableUndo(False)
  665. self.EnableRedo(False)
  666. if fType == 'point':
  667. for tool in (self.addLine, self.addBoundary, self.addCentroid,
  668. self.addArea, self.moveVertex, self.addVertex,
  669. self.removeVertex, self.editLine):
  670. self.EnableTool(tool, False)
  671. elif fType == 'linestring':
  672. for tool in (self.addPoint, self.addBoundary, self.addCentroid,
  673. self.addArea):
  674. self.EnableTool(tool, False)
  675. elif fType == 'polygon':
  676. for tool in (self.addPoint, self.addLine, self.addBoundary, self.addCentroid):
  677. self.EnableTool(tool, False)
  678. elif fType:
  679. GError(parent = self,
  680. message = _("Unsupported feature type '%(type)s'. Unable to edit "
  681. "OGR layer <%(layer)s>.") % { 'type' : fType,
  682. 'layer' : mapLayer.GetName() })
  683. self.digit.CloseMap()
  684. self.mapLayer = None
  685. self.StopEditing()
  686. return False
  687. # update toolbar
  688. if self.combo:
  689. self.combo.SetValue(mapLayer.GetName())
  690. if 'map' in self.parent.toolbars:
  691. self.parent.toolbars['map'].combo.SetValue (_('Digitize'))
  692. # here was dead code to enable vdigit button in toolbar
  693. # with if to ignore iclass
  694. # some signal (DigitizerStarted) can be emitted here
  695. Debug.msg (4, "VDigitToolbar.StartEditing(): layer=%s" % mapLayer.GetName())
  696. # change cursor
  697. if self.MapWindow.mouse['use'] == 'pointer':
  698. self.MapWindow.SetNamedCursor('cross')
  699. if not self.MapWindow.resize:
  700. self.MapWindow.UpdateMap(render = True)
  701. # respect opacity
  702. opacity = mapLayer.GetOpacity(float = True)
  703. if opacity < 1.0:
  704. alpha = int(opacity * 255)
  705. self.digit.GetDisplay().UpdateSettings(alpha = alpha)
  706. return True
  707. def StopEditing(self):
  708. """!Stop editing of selected vector map layer.
  709. @return True on success
  710. @return False on failure
  711. """
  712. if self.combo:
  713. self.combo.SetValue (_('Select vector map'))
  714. # save changes
  715. if self.mapLayer:
  716. Debug.msg (4, "VDigitToolbar.StopEditing(): layer=%s" % self.mapLayer.GetName())
  717. if UserSettings.Get(group = 'vdigit', key = 'saveOnExit', subkey = 'enabled') is False:
  718. if self.digit.GetUndoLevel() > -1:
  719. dlg = wx.MessageDialog(parent = self.parent,
  720. message = _("Do you want to save changes "
  721. "in vector map <%s>?") % self.mapLayer.GetName(),
  722. caption = _("Save changes?"),
  723. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  724. if dlg.ShowModal() == wx.ID_NO:
  725. # revert changes
  726. self.digit.Undo(0)
  727. dlg.Destroy()
  728. self.parent.SetStatusText(_("Please wait, "
  729. "closing and rebuilding topology of "
  730. "vector map <%s>...") % self.mapLayer.GetName(),
  731. 0)
  732. self.digit.CloseMap()
  733. # TODO: replace by giface
  734. lmgr = self.parent.GetLayerManager()
  735. if lmgr:
  736. # here was dead code to enable vdigit button in toolbar
  737. # some signal (DigitizerEnded) can be emitted here
  738. lmgr._giface.GetProgress().SetValue(0)
  739. lmgr.GetLogWindow().WriteCmdLog(_("Editing of vector map <%s> successfully finished") % \
  740. self.mapLayer.GetName())
  741. # re-active layer
  742. if self.parent.tree:
  743. item = self.parent.tree.FindItemByData('maplayer', self.mapLayer)
  744. if item and self.parent.tree.IsItemChecked(item):
  745. self.Map.ChangeLayerActive(self.mapLayer, True)
  746. # change cursor
  747. self.MapWindow.SetNamedCursor('default')
  748. self.MapWindow.pdcVector = None
  749. # close dialogs
  750. for dialog in ('attributes', 'category'):
  751. if self.parent.dialogs[dialog]:
  752. self.parent.dialogs[dialog].Close()
  753. self.parent.dialogs[dialog] = None
  754. del self.digit
  755. del self.MapWindow.digit
  756. self.mapLayer = None
  757. self.MapWindow.redrawAll = True
  758. return True
  759. def UpdateListOfLayers (self, updateTool = False):
  760. """!Update list of available vector map layers.
  761. This list consists only editable layers (in the current mapset)
  762. @param updateTool True to update also toolbar
  763. """
  764. Debug.msg (4, "VDigitToolbar.UpdateListOfLayers(): updateTool=%d" % \
  765. updateTool)
  766. layerNameSelected = None
  767. # name of currently selected layer
  768. if self.mapLayer:
  769. layerNameSelected = self.mapLayer.GetName()
  770. # select vector map layer in the current mapset
  771. layerNameList = []
  772. self.layers = self.Map.GetListOfLayers(ltype = "vector",
  773. mapset = grass.gisenv()['MAPSET'])
  774. for layer in self.layers:
  775. if not layer.name in layerNameList: # do not duplicate layer
  776. layerNameList.append (layer.GetName())
  777. if updateTool: # update toolbar
  778. if not self.mapLayer:
  779. value = _('Select vector map')
  780. else:
  781. value = layerNameSelected
  782. if not self.comboid:
  783. if not self.tools or 'selector' in self.tools:
  784. self.combo = wx.ComboBox(self, id = wx.ID_ANY, value = value,
  785. choices = [_('New vector map'), ] + layerNameList, size = (80, -1),
  786. style = wx.CB_READONLY)
  787. self.comboid = self.InsertControl(0, self.combo)
  788. self.parent.Bind(wx.EVT_COMBOBOX, self.OnSelectMap, self.comboid)
  789. else:
  790. self.combo.SetItems([_('New vector map'), ] + layerNameList)
  791. self.Realize()
  792. return layerNameList
  793. def GetLayer(self):
  794. """!Get selected layer for editing -- MapLayer instance"""
  795. return self.mapLayer