mapwindow.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. """
  2. @package vdigit.mapwindow
  3. @brief Map display canvas for wxGUI vector digitizer
  4. Classes:
  5. - mapwindow::VDigitWindow
  6. (C) 2011-2013 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. """
  11. import wx
  12. import tempfile
  13. from grass.pydispatch.signal import Signal
  14. from dbmgr.dialogs import DisplayAttributesDialog
  15. from core.gcmd import RunCommand, GMessage, GError
  16. from core.debug import Debug
  17. from mapwin.buffered import BufferedMapWindow
  18. from core.settings import UserSettings
  19. from core.utils import ListOfCatsToRange, _
  20. from core.globalvar import QUERYLAYER
  21. from vdigit.dialogs import VDigitCategoryDialog, VDigitZBulkDialog, VDigitDuplicatesDialog
  22. from gui_core import gselect
  23. class VDigitWindow(BufferedMapWindow):
  24. """A Buffered window extended for vector digitizer.
  25. """
  26. def __init__(self, parent, giface, Map, properties, tree=None,
  27. id=wx.ID_ANY, lmgr=None,
  28. style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
  29. BufferedMapWindow.__init__(self, parent=parent, giface=giface, Map=Map,
  30. properties=properties,
  31. style=style, **kwargs)
  32. self.lmgr = lmgr
  33. self.tree = tree
  34. self.pdcVector = wx.PseudoDC()
  35. self.toolbar = self.parent.GetToolbar('vdigit')
  36. self.digit = None # wxvdigit.IVDigit
  37. self._digitizingInfo = False # digitizing with info
  38. # Emitted when info about digitizing updated
  39. # Parameter text is a string with information
  40. # currently used only for coordinates of mouse cursor + segmnt and
  41. # total feature length
  42. self.digitizingInfo = Signal('VDigitWindow.digitizingInfo')
  43. # Emitted when some info about digitizing is or will be availbale
  44. self.digitizingInfoAvailable = Signal('VDigitWindow.digitizingInfo')
  45. # Emitted when some info about digitizing is or will be availbale
  46. # digitizingInfo signal is emmited only between digitizingInfoAvailable
  47. # and digitizingInfoUnavailable signals
  48. self.digitizingInfoUnavailable = Signal('VDigitWindow.digitizingInfo')
  49. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
  50. self.mouseMoving.connect(self._mouseMovingToDigitizingInfo)
  51. def GetDisplay(self):
  52. if self.digit:
  53. return self.digit.GetDisplay()
  54. return None
  55. def GetDigit(self):
  56. """Get digit class"""
  57. return self.digit
  58. def SetToolbar(self, toolbar):
  59. """Set up related toolbar
  60. """
  61. self.toolbar = toolbar
  62. def _mouseMovingToDigitizingInfo(self, x, y):
  63. e, n = x, y
  64. precision = int(UserSettings.Get(group='projection', key='format',
  65. subkey='precision'))
  66. if self.toolbar.GetAction() != 'addLine' or \
  67. self.toolbar.GetAction('type') not in ('line', 'boundary') or \
  68. len(self.polycoords) == 0:
  69. # we cannot provide info, so find out if it is something new
  70. if self._digitizingInfo:
  71. self._digitizingInfo = False
  72. self.digitizingInfoUnavailable.emit()
  73. return
  74. # else, we can provide info, so find out if it is first time
  75. if not self._digitizingInfo:
  76. self._digitizingInfo = True
  77. self.digitizingInfoAvailable.emit()
  78. # for linear feature show segment and total length
  79. distance_seg = self.Distance(self.polycoords[-1],
  80. (e, n), screen=False)[0]
  81. distance_tot = distance_seg
  82. for idx in range(1, len(self.polycoords)):
  83. distance_tot += self.Distance(self.polycoords[idx-1],
  84. self.polycoords[idx],
  85. screen=False)[0]
  86. text = "seg: %.*f; tot: %.*f" % (precision, distance_seg,
  87. precision, distance_tot)
  88. self.digitizingInfo.emit(text=text)
  89. def OnKeyDown(self, event):
  90. """Key pressed"""
  91. shift = event.ShiftDown()
  92. kc = event.GetKeyCode()
  93. event = None
  94. if not shift:
  95. if kc == ord('P'):
  96. event = wx.CommandEvent(winid = self.toolbar.addPoint)
  97. tool = self.toolbar.OnAddPoint
  98. elif kc == ord('L'):
  99. event = wx.CommandEvent(winid = self.toolbar.addLine)
  100. tool = self.toolbar.OnAddLine
  101. if event:
  102. self.toolbar.OnTool(event)
  103. tool(event)
  104. def _updateMap(self):
  105. if not self.toolbar or \
  106. not self.toolbar.GetLayer():
  107. return
  108. # set region
  109. self.digit.GetDisplay().UpdateRegion()
  110. # re-calculate threshold for digitization tool
  111. # self.parent.digit.GetDisplay().GetThreshold()
  112. # draw map
  113. # self.pdcVector.Clear()
  114. self.pdcVector.RemoveAll()
  115. item = None
  116. if self.tree:
  117. try:
  118. item = self.tree.FindItemByData('maplayer', self.toolbar.GetLayer())
  119. except TypeError:
  120. pass
  121. if not self.tree or \
  122. (self.tree and item and \
  123. self.tree.IsItemChecked(item)):
  124. self.redrawAll = True
  125. self.digit.GetDisplay().DrawMap()
  126. # translate tmp objects (pointer position)
  127. if self.toolbar.GetAction() == 'moveLine' and \
  128. hasattr(self, "moveInfo"):
  129. if 'beginDiff' in self.moveInfo:
  130. # move line
  131. for id in self.moveInfo['id']:
  132. self.pdcTmp.TranslateId(id,
  133. self.moveInfo['beginDiff'][0],
  134. self.moveInfo['beginDiff'][1])
  135. del self.moveInfo['beginDiff']
  136. def OnLeftDownAddLine(self, event):
  137. """Left mouse button pressed - add new feature
  138. """
  139. try:
  140. mapLayer = self.toolbar.GetLayer().GetName()
  141. except:
  142. return
  143. if self.toolbar.GetAction('type') in ['point', 'centroid']:
  144. # add new point / centroiud
  145. east, north = self.Pixel2Cell(self.mouse['begin'])
  146. nfeat, fids = self.digit.AddFeature(self.toolbar.GetAction('type'), [(east, north)])
  147. if nfeat < 1:
  148. return
  149. self.UpdateMap(render = False) # redraw map
  150. # add new record into atribute table
  151. if UserSettings.Get(group = 'vdigit', key = "addRecord", subkey = 'enabled'):
  152. # select attributes based on layer and category
  153. cats = { fids[0] : {
  154. UserSettings.Get(group = 'vdigit', key = "layer", subkey = 'value') :
  155. (UserSettings.Get(group = 'vdigit', key = "category", subkey = 'value'), )
  156. }}
  157. posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
  158. self.mouse['end'][1] + self.dialogOffset))
  159. addRecordDlg = DisplayAttributesDialog(parent = self, map = mapLayer,
  160. cats = cats,
  161. pos = posWindow,
  162. action = "add", ignoreError = True)
  163. if self.toolbar.GetAction('type') == 'centroid':
  164. for fid in fids:
  165. self._geomAttrb(fid, addRecordDlg, 'area')
  166. self._geomAttrb(fid, addRecordDlg, 'perimeter')
  167. if addRecordDlg.IsFound() and \
  168. addRecordDlg.ShowModal() == wx.ID_OK:
  169. sqlfile = tempfile.NamedTemporaryFile(mode = "w")
  170. for sql in addRecordDlg.GetSQLString():
  171. sqlfile.file.write(sql + ";\n")
  172. sqlfile.file.flush()
  173. RunCommand('db.execute',
  174. parent = self,
  175. quiet = True,
  176. input = sqlfile.name)
  177. if addRecordDlg.mapDBInfo:
  178. self._updateATM()
  179. elif self.toolbar.GetAction('type') in ["line", "boundary", "area"]:
  180. # add new point to the line
  181. self.polycoords.append(self.Pixel2Cell(event.GetPositionTuple()[:]))
  182. self.DrawLines(pdc = self.pdcTmp)
  183. def _geomAttrb(self, fid, dialog, attrb):
  184. """Define geometry attributes
  185. """
  186. mapLayer = self.toolbar.GetLayer()
  187. if self.tree:
  188. item = self.tree.FindItemByData('maplayer', mapLayer)
  189. vdigit = self.tree.GetLayerInfo(item, key = 'vdigit')
  190. else:
  191. item = vdigit = None
  192. if not vdigit or \
  193. 'geomAttr' not in vdigit or \
  194. attrb not in vdigit['geomAttr']:
  195. return
  196. val = -1
  197. if attrb == 'length':
  198. val = self.digit.GetLineLength(fid)
  199. type = attrb
  200. elif attrb == 'area':
  201. val = self.digit.GetAreaSize(fid)
  202. type = attrb
  203. elif attrb == 'perimeter':
  204. val = self.digit.GetAreaPerimeter(fid)
  205. type = 'length'
  206. if val > 0:
  207. layer = int(UserSettings.Get(group = 'vdigit', key = "layer", subkey = 'value'))
  208. column = vdigit['geomAttr'][attrb]['column']
  209. val = UnitsConvertValue(val, type, vdigit['geomAttr'][attrb]['units'])
  210. dialog.SetColumnValue(layer, column, val)
  211. dialog.OnReset()
  212. def _geomAttrbUpdate(self, fids):
  213. """Update geometry atrributes of currently selected features
  214. :param fid: list feature id
  215. """
  216. mapLayer = self.parent.toolbars['vdigit'].GetLayer()
  217. vectorName = mapLayer.GetName()
  218. if self.tree:
  219. item = self.tree.FindItemByData('maplayer', mapLayer)
  220. vdigit = self.tree.GetLayerInfo(item, key = 'vdigit')
  221. else:
  222. item = vdigit = None
  223. if not vdigit or 'geomAttr' not in vdigit:
  224. return
  225. dbInfo = gselect.VectorDBInfo(vectorName)
  226. sqlfile = tempfile.NamedTemporaryFile(mode = "w")
  227. for fid in fids:
  228. for layer, cats in self.digit.GetLineCats(fid).iteritems():
  229. table = dbInfo.GetTable(layer)
  230. for attrb, item in vdigit['geomAttr'].iteritems():
  231. val = -1
  232. if attrb == 'length':
  233. val = self.digit.GetLineLength(fid)
  234. type = attrb
  235. elif attrb == 'area':
  236. val = self.digit.GetAreaSize(fid)
  237. type = attrb
  238. elif attrb == 'perimeter':
  239. val = self.digit.GetAreaPerimeter(fid)
  240. type = 'length'
  241. if val < 0:
  242. continue
  243. val = UnitsConvertValue(val, type, item['units'])
  244. for cat in cats:
  245. sqlfile.write('UPDATE %s SET %s = %f WHERE %s = %d;\n' % \
  246. (table, item['column'], val,
  247. dbInfo.GetKeyColumn(layer), cat))
  248. sqlfile.file.flush()
  249. RunCommand('db.execute',
  250. parent = True,
  251. quiet = True,
  252. input = sqlfile.name)
  253. def _updateATM(self):
  254. """Update open Attribute Table Manager
  255. .. todo::
  256. use AddDataRow() instead
  257. """
  258. if not self.lmgr:
  259. return
  260. # update ATM
  261. digitVector = self.toolbar.GetLayer().GetName()
  262. for atm in self.lmgr.dialogs['atm']:
  263. atmVector = atm.GetVectorName()
  264. if atmVector == digitVector:
  265. layer = UserSettings.Get(group = 'vdigit', key = "layer", subkey = 'value')
  266. # TODO: use AddDataRow instead
  267. atm.LoadData(layer)
  268. def OnLeftDownEditLine(self, event):
  269. """Left mouse button pressed - edit linear feature - add new
  270. vertex.
  271. """
  272. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  273. self.moveInfo['id'].append(wx.NewId())
  274. self.DrawLines(pdc = self.pdcTmp)
  275. def OnLeftDownMoveLine(self, event):
  276. """Left mouse button pressed - vector digitizer move
  277. feature/vertex, edit linear feature
  278. """
  279. self.moveInfo = dict()
  280. # geographic coordinates of initial position (left-down)
  281. self.moveInfo['begin'] = None
  282. # list of ids to modify
  283. self.moveInfo['id'] = list()
  284. # set pen
  285. if self.toolbar.GetAction() in ["moveVertex", "editLine"]:
  286. pcolor = UserSettings.Get(group = 'vdigit', key = "symbol",
  287. subkey = ["highlight", "color"])
  288. self.pen = self.polypen = wx.Pen(colour = pcolor,
  289. width = 2, style = wx.SHORT_DASH)
  290. self.pdcTmp.SetPen(self.polypen)
  291. def OnLeftDownDisplayCA(self, event):
  292. """Left mouse button pressed - vector digitizer display categories
  293. or attributes action
  294. """
  295. try:
  296. mapLayer = self.toolbar.GetLayer().GetName()
  297. except:
  298. return
  299. coords = self.Pixel2Cell(self.mouse['begin'])
  300. # unselect
  301. self.digit.GetDisplay().SetSelected([])
  302. # select feature by point
  303. cats = {}
  304. self.digit.GetDisplay().SelectLineByPoint(coords)
  305. if not self.digit.GetDisplay().GetSelected():
  306. for key in ('attributes', 'category'):
  307. if self.parent.dialogs[key] and \
  308. self.parent.dialogs[key].IsShown():
  309. self.parent.dialogs[key].Hide()
  310. self.UpdateMap(render = False, renderVector = True)
  311. return
  312. if UserSettings.Get(group = 'vdigit', key = 'checkForDupl',
  313. subkey = 'enabled'):
  314. lines = self.digit.GetDisplay().GetSelected()
  315. else:
  316. lines = (self.digit.GetDisplay().GetSelected()[0],) # only first found
  317. for line in lines:
  318. cats[line] = self.digit.GetLineCats(line)
  319. posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
  320. self.mouse['end'][1] + self.dialogOffset))
  321. if self.toolbar.GetAction() == "displayAttrs":
  322. # select attributes based on coordinates (all layers)
  323. if self.parent.dialogs['attributes'] is None:
  324. self.parent.dialogs['attributes'] = \
  325. DisplayAttributesDialog(parent = self, map = mapLayer,
  326. cats = cats,
  327. action = "update")
  328. else:
  329. # upgrade dialog
  330. self.parent.dialogs['attributes'].UpdateDialog(cats = cats)
  331. if self.parent.dialogs['attributes'] and \
  332. self.parent.dialogs['attributes'].mapDBInfo:
  333. if len(cats.keys()) > 0:
  334. # highlight feature & re-draw map
  335. if not self.parent.dialogs['attributes'].IsShown():
  336. self.parent.dialogs['attributes'].Show()
  337. else:
  338. if self.parent.dialogs['attributes'] and \
  339. self.parent.dialogs['attributes'].IsShown():
  340. self.parent.dialogs['attributes'].Hide()
  341. else: # displayCats
  342. if self.parent.dialogs['category'] is None:
  343. # open new dialog
  344. dlg = VDigitCategoryDialog(parent = self,
  345. vectorName = mapLayer,
  346. cats = cats,
  347. pos = posWindow,
  348. title = _("Update categories"))
  349. self.parent.dialogs['category'] = dlg
  350. else:
  351. # update currently open dialog
  352. self.parent.dialogs['category'].UpdateDialog(cats = cats)
  353. if self.parent.dialogs['category']:
  354. if len(cats.keys()) > 0:
  355. # highlight feature & re-draw map
  356. if not self.parent.dialogs['category'].IsShown():
  357. self.parent.dialogs['category'].Show()
  358. else:
  359. if self.parent.dialogs['category'].IsShown():
  360. self.parent.dialogs['category'].Hide()
  361. self.UpdateMap(render = False, renderVector = True)
  362. def OnLeftDownCopyCA(self, event):
  363. """Left mouse button pressed - vector digitizer copy
  364. categories or attributes action
  365. """
  366. if not hasattr(self, "copyCatsList"):
  367. self.copyCatsList = []
  368. else:
  369. self.copyCatsIds = []
  370. self.mouse['box'] = 'box'
  371. def OnLeftDownCopyLine(self, event):
  372. """Left mouse button pressed - vector digitizer copy lines
  373. action
  374. """
  375. if not hasattr(self, "copyIds"):
  376. self.copyIds = []
  377. self.layerTmp = None
  378. def OnLeftDownBulkLine(self, event):
  379. """Left mouse button pressed - vector digitizer label 3D
  380. vector lines
  381. """
  382. if len(self.polycoords) > 1: # start new line
  383. self.polycoords = []
  384. self.ClearLines(pdc = self.pdcTmp)
  385. self.polycoords.append(self.Pixel2Cell(event.GetPositionTuple()[:]))
  386. if len(self.polycoords) == 1:
  387. begin = self.Pixel2Cell(self.polycoords[-1])
  388. end = self.Pixel2Cell(self.mouse['end'])
  389. else:
  390. end = self.Pixel2Cell(self.polycoords[-1])
  391. begin = self.Pixel2Cell(self.mouse['begin'])
  392. self.DrawLines(self.pdcTmp, polycoords = (begin, end))
  393. def OnLeftDownUndo(self, event):
  394. """Left mouse button pressed with control key - vector
  395. digitizer undo functionality
  396. """
  397. if self.mouse["use"] != "pointer" or not self.toolbar:
  398. return
  399. action = self.toolbar.GetAction()
  400. if (action == "addLine" and \
  401. self.toolbar.GetAction('type') in ["line", "boundary", "area"]) or \
  402. action == "editLine":
  403. # add line or boundary -> remove last point from the line
  404. try:
  405. removed = self.polycoords.pop()
  406. Debug.msg(4, "VDigitWindow.OnMiddleDown(): polycoords_poped=%s" %
  407. [removed, ])
  408. # self.mouse['begin'] = self.Cell2Pixel(self.polycoords[-1])
  409. except:
  410. pass
  411. if action == "editLine":
  412. # remove last vertex & line
  413. if len(self.moveInfo['id']) > 1:
  414. self.moveInfo['id'].pop()
  415. self.UpdateMap(render = False, renderVector = False)
  416. elif action in ["deleteLine", "deleteArea", "moveLine", "splitLine",
  417. "addVertex", "removeVertex", "moveVertex",
  418. "copyCats", "flipLine", "mergeLine",
  419. "snapLine", "connectLine", "copyLine",
  420. "queryLine", "breakLine", "typeConv"]:
  421. # various tools -> unselected selected features
  422. self.digit.GetDisplay().SetSelected([])
  423. if action in ["moveLine", "moveVertex", "editLine"] and \
  424. hasattr(self, "moveInfo"):
  425. del self.moveInfo
  426. elif action == "copyCats":
  427. try:
  428. del self.copyCatsList
  429. del self.copyCatsIds
  430. except AttributeError:
  431. pass
  432. elif action == "copyLine":
  433. del self.copyIds
  434. if self.layerTmp:
  435. self.Map.DeleteLayer(self.layerTmp)
  436. self.UpdateMap(render = True, renderVector = False)
  437. del self.layerTmp
  438. self.polycoords = []
  439. self.UpdateMap(render = False) # render vector
  440. elif action == "zbulkLine":
  441. # reset polyline
  442. self.polycoords = []
  443. self.digit.GetDisplay().SetSelected([])
  444. self.UpdateMap(render = False)
  445. self.redrawAll = True
  446. self.UpdateMap(render = False, renderVector = False)
  447. def _onLeftDown(self, event):
  448. """Left mouse button donw - vector digitizer various actions
  449. """
  450. try:
  451. mapLayer = self.toolbar.GetLayer().GetName()
  452. except:
  453. GMessage(parent = self,
  454. message = _("No vector map selected for editing."))
  455. event.Skip()
  456. return
  457. action = self.toolbar.GetAction()
  458. if not action:
  459. GMessage(parent = self,
  460. message = _("Nothing to do. "
  461. "Choose appropriate tool from digitizer toolbar."))
  462. event.Skip()
  463. return
  464. if action not in ("moveVertex",
  465. "addVertex",
  466. "removeVertex",
  467. "editLine"):
  468. # set pen
  469. self.pen = wx.Pen(colour = UserSettings.Get(group = 'vdigit', key = 'symbol',
  470. subkey = ['newSegment', 'color']),
  471. width = 2, style = wx.SHORT_DASH)
  472. self.polypen = wx.Pen(colour = UserSettings.Get(group = 'vdigit', key = 'symbol',
  473. subkey = ['newLine', 'color']),
  474. width = 2, style = wx.SOLID)
  475. if action in ("addVertex",
  476. "removeVertex",
  477. "splitLines"):
  478. # unselect
  479. self.digit.GetDisplay().SetSelected([])
  480. if action == "addLine":
  481. self.OnLeftDownAddLine(event)
  482. elif action == "editLine" and \
  483. hasattr(self, "moveInfo"):
  484. self.OnLeftDownEditLine(event)
  485. elif action in ("moveLine", "moveVertex", "editLine") and \
  486. not hasattr(self, "moveInfo"):
  487. self.OnLeftDownMoveLine(event)
  488. elif action in ("displayAttrs"
  489. "displayCats"):
  490. self.OnLeftDownDisplayCA(event)
  491. elif action in ("copyCats",
  492. "copyAttrs"):
  493. self.OnLeftDownCopyCA(event)
  494. elif action == "copyLine":
  495. self.OnLeftDownCopyLine(event)
  496. elif action == "zbulkLine":
  497. self.OnLeftDownBulkLine(event)
  498. def OnLeftUpVarious(self, event):
  499. """Left mouse button released - vector digitizer various
  500. actions
  501. """
  502. pos1 = self.Pixel2Cell(self.mouse['begin'])
  503. pos2 = self.Pixel2Cell(self.mouse['end'])
  504. nselected = 0
  505. action = self.toolbar.GetAction()
  506. # -> delete line || move line || move vertex
  507. if action in ("moveVertex",
  508. "editLine"):
  509. if len(self.digit.GetDisplay().GetSelected()) == 0:
  510. nselected = int(self.digit.GetDisplay().SelectLineByPoint(pos1)['line'] != -1)
  511. if action == "editLine":
  512. try:
  513. selVertex = self.digit.GetDisplay().GetSelectedVertex(pos1)[0]
  514. except IndexError:
  515. selVertex = None
  516. if selVertex:
  517. # self.UpdateMap(render=False)
  518. ids = self.digit.GetDisplay().GetSelected(grassId = False)
  519. # move this line to tmp layer
  520. self.polycoords = []
  521. for id in ids:
  522. if id % 2: # register only vertices
  523. e, n = self.Pixel2Cell(self.pdcVector.GetIdBounds(id)[0:2])
  524. self.polycoords.append((e, n))
  525. self.digit.GetDisplay().DrawSelected(False)
  526. if selVertex < ids[-1] / 2:
  527. # choose first or last node of line
  528. self.moveInfo['id'].reverse()
  529. self.polycoords.reverse()
  530. else:
  531. # unselect
  532. self.digit.GetDisplay().SetSelected([])
  533. del self.moveInfo
  534. self.UpdateMap(render = False)
  535. elif action in ("copyCats",
  536. "copyAttrs"):
  537. if not hasattr(self, "copyCatsIds"):
  538. # 'from' -> select by point
  539. nselected = int(self.digit.GetDisplay().SelectLineByPoint(pos1)['line'] != -1)
  540. if nselected:
  541. self.copyCatsList = self.digit.GetDisplay().GetSelected()
  542. else:
  543. # -> 'to' -> select by bbox
  544. self.digit.GetDisplay().SetSelected([])
  545. # return number of selected features (by box/point)
  546. nselected = self.digit.GetDisplay().SelectLinesByBox((pos1, pos2))
  547. if nselected == 0:
  548. nselected = int(self.digit.GetDisplay().SelectLineByPoint(pos1)['line'] != -1)
  549. if nselected > 0:
  550. self.copyCatsIds = self.digit.GetDisplay().GetSelected()
  551. elif action == "queryLine":
  552. selected = self.digit.SelectLinesByQuery(bbox = (pos1, pos2))
  553. nselected = len(selected)
  554. if nselected > 0:
  555. self.digit.GetDisplay().SetSelected(selected)
  556. else:
  557. # -> moveLine || deleteLine, etc. (select by point/box)
  558. if action == 'moveLine' and \
  559. len(self.digit.GetDisplay().GetSelected()) > 0:
  560. nselected = 0
  561. else:
  562. if action == 'deleteArea':
  563. nselected = int(self.digit.GetDisplay().SelectAreaByPoint(pos1)['area'] != -1)
  564. else:
  565. if action == 'moveLine':
  566. drawSeg = True
  567. else:
  568. drawSeg = False
  569. nselected = self.digit.GetDisplay().SelectLinesByBox(bbox = (pos1, pos2),
  570. drawSeg = drawSeg)
  571. if nselected == 0:
  572. nselected = int(self.digit.GetDisplay().SelectLineByPoint(pos1)['line'] != -1)
  573. if nselected > 0:
  574. if action in ("moveLine", "moveVertex") and \
  575. hasattr(self, "moveInfo"):
  576. # get pseudoDC id of objects which should be redrawn
  577. if action == "moveLine":
  578. # -> move line
  579. self.moveInfo['id'] = self.digit.GetDisplay().GetSelected(grassId = False)
  580. else: # moveVertex
  581. self.moveInfo['id'] = self.digit.GetDisplay().GetSelectedVertex(pos1)
  582. if len(self.moveInfo['id']) == 0: # no vertex found
  583. self.digit.GetDisplay().SetSelected([])
  584. #
  585. # check for duplicates
  586. #
  587. if UserSettings.Get(group = 'vdigit', key = 'checkForDupl', subkey = 'enabled'):
  588. dupl = self.digit.GetDisplay().GetDuplicates()
  589. self.UpdateMap(render = False)
  590. if dupl:
  591. posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
  592. self.mouse['end'][1] + self.dialogOffset))
  593. dlg = VDigitDuplicatesDialog(parent = self, data = dupl, pos = posWindow)
  594. if dlg.ShowModal() == wx.ID_OK:
  595. self.digit.GetDisplay().UnSelect(dlg.GetUnSelected())
  596. # update selected
  597. self.UpdateMap(render = False)
  598. if action != "editLine":
  599. # -> move line || move vertex
  600. self.UpdateMap(render = False)
  601. else: # no vector object found
  602. if not (action in ("moveLine",
  603. "moveVertex") and \
  604. hasattr(self, "moveInfo") and \
  605. len(self.moveInfo['id']) > 0):
  606. # avoid left-click when features are already selected
  607. self.UpdateMap(render = False, renderVector = False)
  608. def OnLeftUpModifyLine(self, event):
  609. """Left mouse button released - vector digitizer split line,
  610. add/remove vertex action
  611. """
  612. pos1 = self.Pixel2Cell(self.mouse['begin'])
  613. pointOnLine = self.digit.GetDisplay().SelectLineByPoint(pos1)['point']
  614. if not pointOnLine:
  615. return
  616. if self.toolbar.GetAction() in ["splitLine", "addVertex"]:
  617. self.UpdateMap(render = False) # highlight object
  618. self.DrawCross(pdc = self.pdcTmp, coords = self.Cell2Pixel((pointOnLine[0], pointOnLine[1])),
  619. size = 5)
  620. else: # removeVertex
  621. # get only id of vertex
  622. try:
  623. id = self.digit.GetDisplay().GetSelectedVertex(pos1)[0]
  624. except IndexError:
  625. id = None
  626. if id:
  627. x, y = self.pdcVector.GetIdBounds(id)[0:2]
  628. self.pdcVector.RemoveId(id)
  629. self.UpdateMap(render = False) # highlight object
  630. self.DrawCross(pdc = self.pdcTmp, coords = (x, y),
  631. size = 5)
  632. else:
  633. # unselect
  634. self.digit.GetDisplay().SetSelected([])
  635. self.UpdateMap(render = False)
  636. def OnLeftUpCopyLine(self, event):
  637. """Left mouse button released - vector digitizer copy feature
  638. action
  639. """
  640. pos1 = self.Pixel2Cell(self.mouse['begin'])
  641. pos2 = self.Pixel2Cell(self.mouse['end'])
  642. if UserSettings.Get(group = 'vdigit', key = 'bgmap',
  643. subkey='value', settings_type='internal') == '':
  644. # no background map -> copy from current vector map layer
  645. nselected = self.digit.GetDisplay().SelectLinesByBox((pos1, pos2))
  646. if nselected > 0:
  647. # highlight selected features
  648. self.UpdateMap(render = False)
  649. else:
  650. self.UpdateMap(render = False, renderVector = False)
  651. else:
  652. # copy features from background map
  653. self.copyIds = self.digit.SelectLinesFromBackgroundMap(bbox = (pos1, pos2))
  654. if len(self.copyIds) > 0:
  655. color = UserSettings.Get(group = 'vdigit', key = 'symbol',
  656. subkey = ['highlight', 'color'])
  657. colorStr = str(color[0]) + ":" + str(color[1]) + ":" + str(color[2])
  658. dVectTmp = ['d.vect',
  659. 'map=%s' % UserSettings.Get(group = 'vdigit', key = 'bgmap',
  660. subkey='value', settings_type='internal'),
  661. 'cats=%s' % ListOfCatsToRange(self.copyIds),
  662. '-i',
  663. 'color=%s' % colorStr,
  664. 'fill_color=%s' % colorStr,
  665. 'type=point,line,boundary,centroid',
  666. 'width=2']
  667. if not self.layerTmp:
  668. self.layerTmp = self.Map.AddLayer(ltype = 'vector',
  669. name = QUERYLAYER,
  670. command = dVectTmp)
  671. else:
  672. self.layerTmp.SetCmd(dVectTmp)
  673. else:
  674. if self.layerTmp:
  675. self.Map.DeleteLayer(self.layerTmp)
  676. self.layerTmp = None
  677. self.UpdateMap(render = True, renderVector = True)
  678. def OnLeftUpBulkLine(self, event):
  679. """Left mouse button released - vector digitizer z-bulk line
  680. action
  681. """
  682. # select lines to be labeled
  683. pos1 = self.polycoords[0]
  684. pos2 = self.polycoords[1]
  685. nselected = self.digit.GetDisplay().SelectLinesByBox((pos1, pos2))
  686. if nselected > 0:
  687. # highlight selected features
  688. self.UpdateMap(render = False)
  689. self.DrawLines(pdc = self.pdcTmp) # redraw temp line
  690. else:
  691. self.UpdateMap(render = False, renderVector = False)
  692. def OnLeftUpConnectLine(self, event):
  693. """Left mouse button released - vector digitizer connect line
  694. action
  695. """
  696. if len(self.digit.GetDisplay().GetSelected()) > 0:
  697. self.UpdateMap(render = False)
  698. def _onLeftUp(self, event):
  699. """Left mouse button released"""
  700. if event.ControlDown():
  701. return
  702. if hasattr(self, "moveInfo"):
  703. if len(self.digit.GetDisplay().GetSelected()) == 0:
  704. self.moveInfo['begin'] = self.Pixel2Cell(self.mouse['begin']) # left down
  705. # eliminate initial mouse moving efect
  706. self.mouse['begin'] = self.mouse['end']
  707. action = self.toolbar.GetAction()
  708. if action in ("deleteLine",
  709. "deleteArea",
  710. "moveLine",
  711. "moveVertex",
  712. "copyCats",
  713. "copyAttrs",
  714. "editLine",
  715. "flipLine",
  716. "mergeLine",
  717. "snapLine",
  718. "queryLine",
  719. "breakLine",
  720. "typeConv",
  721. "connectLine"):
  722. self.OnLeftUpVarious(event)
  723. elif action in ("splitLine",
  724. "addVertex",
  725. "removeVertex"):
  726. self.OnLeftUpModifyLine(event)
  727. elif action == "copyLine":
  728. self.OnLeftUpCopyLine(event)
  729. elif action == "zbulkLine" and \
  730. len(self.polycoords) == 2:
  731. self.OnLeftUpBulkLine(event)
  732. elif action == "connectLine":
  733. self.OnLeftUpConnectLine(event)
  734. if len(self.digit.GetDisplay().GetSelected()) > 0:
  735. self.redrawAll = None
  736. def _onRightDown(self, event):
  737. # digitization tool (confirm action)
  738. action = self.toolbar.GetAction()
  739. if action in ("moveLine", "moveVertex") and \
  740. hasattr(self, "moveInfo"):
  741. pFrom = self.moveInfo['begin']
  742. pTo = self.Pixel2Cell(event.GetPositionTuple())
  743. move = (pTo[0] - pFrom[0],
  744. pTo[1] - pFrom[1])
  745. if action == "moveLine":
  746. # move line
  747. if self.digit.MoveSelectedLines(move) < 0:
  748. return
  749. elif action == "moveVertex":
  750. # move vertex
  751. fid = self.digit.MoveSelectedVertex(pFrom, move)
  752. if fid < 0:
  753. return
  754. self._geomAttrbUpdate([fid,])
  755. del self.moveInfo
  756. def _onRightUp(self, event):
  757. """Right mouse button released (confirm action)
  758. """
  759. action = self.toolbar.GetAction()
  760. if action == "addLine" and \
  761. self.toolbar.GetAction('type') in ["line", "boundary", "area"]:
  762. # -> add new line / boundary
  763. try:
  764. mapName = self.toolbar.GetLayer().GetName()
  765. except:
  766. mapName = None
  767. GError(parent = self,
  768. message = _("No vector map selected for editing."))
  769. if mapName:
  770. if self.toolbar.GetAction('type') == 'line':
  771. line = True
  772. else:
  773. line = False
  774. if len(self.polycoords) < 2: # ignore 'one-point' lines
  775. return
  776. nfeat, fids = self.digit.AddFeature(self.toolbar.GetAction('type'), self.polycoords)
  777. if nfeat < 0:
  778. return
  779. position = self.Cell2Pixel(self.polycoords[-1])
  780. self.polycoords = []
  781. self.UpdateMap(render = False)
  782. self.redrawAll = True
  783. self.Refresh()
  784. # add new record into atribute table
  785. if self._addRecord() and (line is True or (not line and nfeat > 0)):
  786. posWindow = self.ClientToScreen((position[0] + self.dialogOffset,
  787. position[1] + self.dialogOffset))
  788. # select attributes based on layer and category
  789. cats = { fids[0] : {
  790. UserSettings.Get(group = 'vdigit', key = "layer", subkey = 'value') :
  791. (UserSettings.Get(group = 'vdigit', key = "category", subkey = 'value'), )
  792. }}
  793. addRecordDlg = DisplayAttributesDialog(parent = self, map = mapName,
  794. cats = cats,
  795. pos = posWindow,
  796. action = "add", ignoreError = True)
  797. for fid in fids:
  798. self._geomAttrb(fid, addRecordDlg, 'length')
  799. # auto-placing centroid
  800. self._geomAttrb(fid, addRecordDlg, 'area')
  801. self._geomAttrb(fid, addRecordDlg, 'perimeter')
  802. if addRecordDlg.mapDBInfo and \
  803. addRecordDlg.ShowModal() == wx.ID_OK:
  804. sqlfile = tempfile.NamedTemporaryFile(mode = "w")
  805. for sql in addRecordDlg.GetSQLString():
  806. sqlfile.file.write(sql + ";\n")
  807. sqlfile.file.flush()
  808. RunCommand('db.execute',
  809. parent = True,
  810. quiet = True,
  811. input = sqlfile.name)
  812. if addRecordDlg.mapDBInfo:
  813. self._updateATM()
  814. elif action == "deleteLine":
  815. # -> delete selected vector features
  816. if self.digit.DeleteSelectedLines() < 0:
  817. return
  818. self._updateATM()
  819. elif action == "deleteArea":
  820. # -> delete selected vector areas
  821. if self.digit.DeleteSelectedAreas() < 0:
  822. return
  823. self._updateATM()
  824. elif action == "splitLine":
  825. # split line
  826. if self.digit.SplitLine(self.Pixel2Cell(self.mouse['begin'])) < 0:
  827. return
  828. elif action == "addVertex":
  829. # add vertex
  830. fid = self.digit.AddVertex(self.Pixel2Cell(self.mouse['begin']))
  831. if fid < 0:
  832. return
  833. elif action == "removeVertex":
  834. # remove vertex
  835. fid = self.digit.RemoveVertex(self.Pixel2Cell(self.mouse['begin']))
  836. if fid < 0:
  837. return
  838. self._geomAttrbUpdate([fid,])
  839. elif action in ("copyCats", "copyAttrs"):
  840. if action == 'copyCats':
  841. if self.digit.CopyCats(self.copyCatsList,
  842. self.copyCatsIds, copyAttrb = False) < 0:
  843. return
  844. else:
  845. if self.digit.CopyCats(self.copyCatsList,
  846. self.copyCatsIds, copyAttrb = True) < 0:
  847. return
  848. del self.copyCatsList
  849. del self.copyCatsIds
  850. self._updateATM()
  851. elif action == "editLine" and \
  852. hasattr(self, "moveInfo"):
  853. line = self.digit.GetDisplay().GetSelected()[0]
  854. if self.digit.EditLine(line, self.polycoords) < 0:
  855. return
  856. del self.moveInfo
  857. elif action == "flipLine":
  858. if self.digit.FlipLine() < 0:
  859. return
  860. elif action == "mergeLine":
  861. if self.digit.MergeLine() < 0:
  862. return
  863. elif action == "breakLine":
  864. if self.digit.BreakLine() < 0:
  865. return
  866. elif action == "snapLine":
  867. if self.digit.SnapLine() < 0:
  868. return
  869. elif action == "connectLine":
  870. if len(self.digit.GetDisplay().GetSelected()) > 1:
  871. if self.digit.ConnectLine() < 0:
  872. return
  873. elif action == "copyLine":
  874. if self.digit.CopyLine(self.copyIds) < 0:
  875. return
  876. del self.copyIds
  877. if self.layerTmp:
  878. self.Map.DeleteLayer(self.layerTmp)
  879. self.UpdateMap(render = True, renderVector = False)
  880. del self.layerTmp
  881. elif action == "zbulkLine" and len(self.polycoords) == 2:
  882. pos1 = self.polycoords[0]
  883. pos2 = self.polycoords[1]
  884. selected = self.digit.GetDisplay().GetSelected()
  885. dlg = VDigitZBulkDialog(parent = self, title = _("Z bulk-labeling dialog"),
  886. nselected = len(selected))
  887. if dlg.ShowModal() == wx.ID_OK:
  888. if self.digit.ZBulkLines(pos1, pos2, dlg.value.GetValue(),
  889. dlg.step.GetValue()) < 0:
  890. return
  891. self.UpdateMap(render = False)
  892. elif action == "typeConv":
  893. # -> feature type conversion
  894. # - point <-> centroid
  895. # - line <-> boundary
  896. if self.digit.TypeConvForSelectedLines() < 0:
  897. return
  898. if action != "addLine":
  899. # unselect and re-render
  900. self.digit.GetDisplay().SetSelected([])
  901. self.polycoords = []
  902. self.UpdateMap(render = False)
  903. def _onMouseMoving(self, event):
  904. self.mouse['end'] = event.GetPositionTuple()[:]
  905. Debug.msg(5, "VDigitWindow.OnMouseMoving(): coords=%f,%f" %
  906. (self.mouse['end'][0], self.mouse['end'][1]))
  907. action = self.toolbar.GetAction()
  908. if action == "addLine" and \
  909. self.toolbar.GetAction('type') in ["line", "boundary", "area"]:
  910. if len(self.polycoords) > 0:
  911. self.MouseDraw(pdc = self.pdcTmp, begin = self.Cell2Pixel(self.polycoords[-1]))
  912. elif action in ["moveLine", "moveVertex", "editLine"] \
  913. and hasattr(self, "moveInfo"):
  914. dx = self.mouse['end'][0] - self.mouse['begin'][0]
  915. dy = self.mouse['end'][1] - self.mouse['begin'][1]
  916. # draw lines on new position
  917. if action == "moveLine" and \
  918. len(self.moveInfo['id']) > 0:
  919. # move line
  920. for id in self.moveInfo['id']:
  921. self.pdcTmp.TranslateId(id, dx, dy)
  922. elif action in ["moveVertex", "editLine"]:
  923. # move vertex ->
  924. # (vertex, left vertex, left line,
  925. # right vertex, right line)
  926. # do not draw static lines
  927. if action == "moveVertex" and \
  928. len(self.moveInfo['id']) > 0:
  929. self.polycoords = []
  930. self.pdcTmp.RemoveId(self.moveInfo['id'][0])
  931. if self.moveInfo['id'][1] > 0: # previous vertex
  932. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.moveInfo['id'][1])[0:2])
  933. self.pdcTmp.RemoveId(self.moveInfo['id'][1] + 1)
  934. self.polycoords.append((x, y))
  935. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  936. if self.moveInfo['id'][2] > 0: # next vertex
  937. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.moveInfo['id'][2])[0:2])
  938. self.pdcTmp.RemoveId(self.moveInfo['id'][2]-1)
  939. self.polycoords.append((x, y))
  940. self.ClearLines(pdc = self.pdcTmp)
  941. self.DrawLines(pdc = self.pdcTmp)
  942. if action == "editLine":
  943. self.MouseDraw(pdc = self.pdcTmp,
  944. begin = self.Cell2Pixel(self.polycoords[-1]))
  945. self.Refresh() # TODO: use RefreshRect()
  946. self.mouse['begin'] = self.mouse['end']
  947. elif action == "zbulkLine":
  948. if len(self.polycoords) == 1:
  949. # draw mouse moving
  950. self.MouseDraw(self.pdcTmp)
  951. def _zoom(self, event):
  952. tmp1 = self.mouse['end']
  953. tmp2 = self.Cell2Pixel(self.moveInfo['begin'])
  954. dx = tmp1[0] - tmp2[0]
  955. dy = tmp1[1] - tmp2[1]
  956. self.moveInfo['beginDiff'] = (dx, dy)
  957. for id in self.moveInfo['id']:
  958. self.pdcTmp.RemoveId(id)
  959. def _addRecord(self):
  960. return UserSettings.Get(group = 'vdigit', key = "addRecord", subkey = 'enabled')