mapwindow.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. """!
  2. @package vdigit.mapwindow
  3. @brief Map display canvas for wxGUI vector digitizer
  4. Classes:
  5. - mapwindow::VDigitWindow
  6. (C) 2011 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. from dbmgr.dialogs import DisplayAttributesDialog
  13. from core.gcmd import RunCommand, GMessage, GError
  14. from core.debug import Debug
  15. from mapdisp.mapwindow import BufferedWindow
  16. from core.settings import UserSettings
  17. from core.utils import ListOfCatsToRange
  18. from core.globalvar import QUERYLAYER
  19. from vdigit.dialogs import VDigitCategoryDialog, VDigitZBulkDialog, VDigitDuplicatesDialog
  20. class VDigitWindow(BufferedWindow):
  21. """!A Buffered window extended for vector digitizer.
  22. """
  23. def __init__(self, parent, id = wx.ID_ANY,
  24. Map = None, tree = None, lmgr = None,
  25. style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
  26. BufferedWindow.__init__(self, parent, id, Map, tree, lmgr,
  27. style, **kwargs)
  28. self.pdcVector = wx.PseudoDC()
  29. self.toolbar = self.parent.GetToolbar('vdigit')
  30. self.digit = None # wxvdigit.IVDigit
  31. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
  32. def GetDisplay(self):
  33. if self.digit:
  34. return self.digit.GetDisplay()
  35. return None
  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 = 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. 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. 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. 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", "deleteArea", "moveLine", "splitLine",
  388. "addVertex", "removeVertex", "moveVertex",
  389. "copyCats", "flipLine", "mergeLine",
  390. "snapLine", "connectLine", "copyLine",
  391. "queryLine", "breakLine", "typeConv"]:
  392. # various 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. 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. "deleteArea",
  670. "moveLine",
  671. "moveVertex",
  672. "copyCats",
  673. "copyAttrs",
  674. "editLine",
  675. "flipLine",
  676. "mergeLine",
  677. "snapLine",
  678. "queryLine",
  679. "breakLine",
  680. "typeConv",
  681. "connectLine"):
  682. self.OnLeftUpVarious(event)
  683. elif action in ("splitLine",
  684. "addVertex",
  685. "removeVertex"):
  686. self.OnLeftUpModifyLine(event)
  687. elif action == "copyLine":
  688. self.OnLeftUpCopyLine(event)
  689. elif action == "zbulkLine" and \
  690. len(self.polycoords) == 2:
  691. self.OnLeftUpBulkLine(event)
  692. elif action == "connectLine":
  693. self.OnLeftUpConnectLine(event)
  694. if len(self.digit.GetDisplay().GetSelected()) > 0:
  695. self.redrawAll = None
  696. def _onRightDown(self, event):
  697. # digitization tool (confirm action)
  698. action = self.toolbar.GetAction()
  699. if action in ("moveLine", "moveVertex") and \
  700. hasattr(self, "moveInfo"):
  701. pFrom = self.moveInfo['begin']
  702. pTo = self.Pixel2Cell(event.GetPositionTuple())
  703. move = (pTo[0] - pFrom[0],
  704. pTo[1] - pFrom[1])
  705. if action == "moveLine":
  706. # move line
  707. if self.digit.MoveSelectedLines(move) < 0:
  708. return
  709. elif action == "moveVertex":
  710. # move vertex
  711. fid = self.digit.MoveSelectedVertex(pFrom, move)
  712. if fid < 0:
  713. return
  714. self._geomAttrbUpdate([fid,])
  715. del self.moveInfo
  716. def _onRightUp(self, event):
  717. """!Right mouse button released (confirm action)
  718. """
  719. action = self.toolbar.GetAction()
  720. if action == "addLine" and \
  721. self.toolbar.GetAction('type') in ["line", "boundary", "area"]:
  722. # -> add new line / boundary
  723. try:
  724. mapName = self.toolbar.GetLayer().GetName()
  725. except:
  726. mapName = None
  727. GError(parent = self,
  728. message = _("No vector map selected for editing."))
  729. if mapName:
  730. if self.toolbar.GetAction('type') == 'line':
  731. line = True
  732. else:
  733. line = False
  734. if len(self.polycoords) < 2: # ignore 'one-point' lines
  735. return
  736. nfeat, fids = self.digit.AddFeature(self.toolbar.GetAction('type'), self.polycoords)
  737. if nfeat < 0:
  738. return
  739. position = self.Cell2Pixel(self.polycoords[-1])
  740. self.polycoords = []
  741. self.UpdateMap(render = False)
  742. self.redrawAll = True
  743. self.Refresh()
  744. # add new record into atribute table
  745. if self._addRecord() and (line is True or (not line and nfeat > 0)):
  746. posWindow = self.ClientToScreen((position[0] + self.dialogOffset,
  747. position[1] + self.dialogOffset))
  748. # select attributes based on layer and category
  749. cats = { fids[0] : {
  750. UserSettings.Get(group = 'vdigit', key = "layer", subkey = 'value') :
  751. (UserSettings.Get(group = 'vdigit', key = "category", subkey = 'value'), )
  752. }}
  753. addRecordDlg = DisplayAttributesDialog(parent = self, map = mapName,
  754. cats = cats,
  755. pos = posWindow,
  756. action = "add", ignoreError = True)
  757. for fid in fids:
  758. self._geomAttrb(fid, addRecordDlg, 'length')
  759. # auto-placing centroid
  760. self._geomAttrb(fid, addRecordDlg, 'area')
  761. self._geomAttrb(fid, addRecordDlg, 'perimeter')
  762. if addRecordDlg.mapDBInfo and \
  763. addRecordDlg.ShowModal() == wx.ID_OK:
  764. sqlfile = tempfile.NamedTemporaryFile(mode = "w")
  765. for sql in addRecordDlg.GetSQLString():
  766. sqlfile.file.write(sql + ";\n")
  767. sqlfile.file.flush()
  768. RunCommand('db.execute',
  769. parent = True,
  770. quiet = True,
  771. input = sqlfile.name)
  772. if addRecordDlg.mapDBInfo:
  773. self._updateATM()
  774. elif action == "deleteLine":
  775. # -> delete selected vector features
  776. if self.digit.DeleteSelectedLines() < 0:
  777. return
  778. self._updateATM()
  779. elif action == "deleteArea":
  780. # -> delete selected vector areas
  781. if self.digit.DeleteSelectedAreas() < 0:
  782. return
  783. self._updateATM()
  784. elif action == "splitLine":
  785. # split line
  786. if self.digit.SplitLine(self.Pixel2Cell(self.mouse['begin'])) < 0:
  787. return
  788. elif action == "addVertex":
  789. # add vertex
  790. fid = self.digit.AddVertex(self.Pixel2Cell(self.mouse['begin']))
  791. if fid < 0:
  792. return
  793. elif action == "removeVertex":
  794. # remove vertex
  795. fid = self.digit.RemoveVertex(self.Pixel2Cell(self.mouse['begin']))
  796. if fid < 0:
  797. return
  798. self._geomAttrbUpdate([fid,])
  799. elif action in ("copyCats", "copyAttrs"):
  800. if action == 'copyCats':
  801. if self.digit.CopyCats(self.copyCatsList,
  802. self.copyCatsIds, copyAttrb = False) < 0:
  803. return
  804. else:
  805. if self.digit.CopyCats(self.copyCatsList,
  806. self.copyCatsIds, copyAttrb = True) < 0:
  807. return
  808. del self.copyCatsList
  809. del self.copyCatsIds
  810. self._updateATM()
  811. elif action == "editLine" and \
  812. hasattr(self, "moveInfo"):
  813. line = self.digit.GetDisplay().GetSelected()[0]
  814. if self.digit.EditLine(line, self.polycoords) < 0:
  815. return
  816. del self.moveInfo
  817. elif action == "flipLine":
  818. if self.digit.FlipLine() < 0:
  819. return
  820. elif action == "mergeLine":
  821. if self.digit.MergeLine() < 0:
  822. return
  823. elif action == "breakLine":
  824. if self.digit.BreakLine() < 0:
  825. return
  826. elif action == "snapLine":
  827. if self.digit.SnapLine() < 0:
  828. return
  829. elif action == "connectLine":
  830. if len(self.digit.GetDisplay().GetSelected()) > 1:
  831. if self.digit.ConnectLine() < 0:
  832. return
  833. elif action == "copyLine":
  834. if self.digit.CopyLine(self.copyIds) < 0:
  835. return
  836. del self.copyIds
  837. if self.layerTmp:
  838. self.Map.DeleteLayer(self.layerTmp)
  839. self.UpdateMap(render = True, renderVector = False)
  840. del self.layerTmp
  841. elif action == "zbulkLine" and len(self.polycoords) == 2:
  842. pos1 = self.polycoords[0]
  843. pos2 = self.polycoords[1]
  844. selected = self.digit.GetDisplay().GetSelected()
  845. dlg = VDigitZBulkDialog(parent = self, title = _("Z bulk-labeling dialog"),
  846. nselected = len(selected))
  847. if dlg.ShowModal() == wx.ID_OK:
  848. if self.digit.ZBulkLines(pos1, pos2, dlg.value.GetValue(),
  849. dlg.step.GetValue()) < 0:
  850. return
  851. self.UpdateMap(render = False)
  852. elif action == "typeConv":
  853. # -> feature type conversion
  854. # - point <-> centroid
  855. # - line <-> boundary
  856. if self.digit.TypeConvForSelectedLines() < 0:
  857. return
  858. if action != "addLine":
  859. # unselect and re-render
  860. self.digit.GetDisplay().SetSelected([])
  861. self.polycoords = []
  862. self.UpdateMap(render = False)
  863. def _onMouseMoving(self, event):
  864. self.mouse['end'] = event.GetPositionTuple()[:]
  865. Debug.msg (5, "BufferedWindow.OnMouseMoving(): coords=%f,%f" % \
  866. (self.mouse['end'][0], self.mouse['end'][1]))
  867. action = self.toolbar.GetAction()
  868. if action == "addLine" and \
  869. self.toolbar.GetAction('type') in ["line", "boundary", "area"]:
  870. if len(self.polycoords) > 0:
  871. self.MouseDraw(pdc = self.pdcTmp, begin = self.Cell2Pixel(self.polycoords[-1]))
  872. elif action in ["moveLine", "moveVertex", "editLine"] \
  873. and hasattr(self, "moveInfo"):
  874. dx = self.mouse['end'][0] - self.mouse['begin'][0]
  875. dy = self.mouse['end'][1] - self.mouse['begin'][1]
  876. # draw lines on new position
  877. if action == "moveLine" and \
  878. len(self.moveInfo['id']) > 0:
  879. # move line
  880. for id in self.moveInfo['id']:
  881. self.pdcTmp.TranslateId(id, dx, dy)
  882. elif action in ["moveVertex", "editLine"]:
  883. # move vertex ->
  884. # (vertex, left vertex, left line,
  885. # right vertex, right line)
  886. # do not draw static lines
  887. if action == "moveVertex" and \
  888. len(self.moveInfo['id']) > 0:
  889. self.polycoords = []
  890. self.pdcTmp.RemoveId(self.moveInfo['id'][0])
  891. if self.moveInfo['id'][1] > 0: # previous vertex
  892. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.moveInfo['id'][1])[0:2])
  893. self.pdcTmp.RemoveId(self.moveInfo['id'][1] + 1)
  894. self.polycoords.append((x, y))
  895. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  896. if self.moveInfo['id'][2] > 0: # next vertex
  897. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.moveInfo['id'][2])[0:2])
  898. self.pdcTmp.RemoveId(self.moveInfo['id'][2]-1)
  899. self.polycoords.append((x, y))
  900. self.ClearLines(pdc = self.pdcTmp)
  901. self.DrawLines(pdc = self.pdcTmp)
  902. if action == "editLine":
  903. self.MouseDraw(pdc = self.pdcTmp,
  904. begin = self.Cell2Pixel(self.polycoords[-1]))
  905. self.Refresh() # TODO: use RefreshRect()
  906. self.mouse['begin'] = self.mouse['end']
  907. elif action == "zbulkLine":
  908. if len(self.polycoords) == 1:
  909. # draw mouse moving
  910. self.MouseDraw(self.pdcTmp)
  911. def _zoom(self, event):
  912. tmp1 = self.mouse['end']
  913. tmp2 = self.Cell2Pixel(self.moveInfo['begin'])
  914. dx = tmp1[0] - tmp2[0]
  915. dy = tmp1[1] - tmp2[1]
  916. self.moveInfo['beginDiff'] = (dx, dy)
  917. for id in self.moveInfo['id']:
  918. self.pdcTmp.RemoveId(id)
  919. def _addRecord(self):
  920. return UserSettings.Get(group = 'vdigit', key = "addRecord", subkey = 'enabled')