mapdisp_vdigit.py 44 KB

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