mapdisp_vdigit.py 44 KB

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