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