mapwindow.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  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. GMessage(parent = self,
  431. message = _("Nothing to do. "
  432. "Choose appropriate tool from digitizer toolbar."))
  433. event.Skip()
  434. return
  435. if action not in ("moveVertex",
  436. "addVertex",
  437. "removeVertex",
  438. "editLine"):
  439. # set pen
  440. self.pen = wx.Pen(colour = 'Red', width = 2, style = wx.SHORT_DASH)
  441. self.polypen = wx.Pen(colour = 'dark green', width = 2, style = wx.SOLID)
  442. if action in ("addVertex",
  443. "removeVertex",
  444. "splitLines"):
  445. # unselect
  446. self.digit.GetDisplay().SetSelected([])
  447. if action == "addLine":
  448. self.OnLeftDownAddLine(event)
  449. elif action == "editLine" and \
  450. hasattr(self, "moveInfo"):
  451. self.OnLeftDownEditLine(event)
  452. elif action in ("moveLine", "moveVertex", "editLine") and \
  453. not hasattr(self, "moveInfo"):
  454. self.OnLeftDownMoveLine(event)
  455. elif action in ("displayAttrs"
  456. "displayCats"):
  457. self.OnLeftDownDisplayCA(event)
  458. elif action in ("copyCats",
  459. "copyAttrs"):
  460. self.OnLeftDownCopyCA(event)
  461. elif action == "copyLine":
  462. self.OnLeftDownCopyLine(event)
  463. elif action == "zbulkLine":
  464. self.OnLeftDownBulkLine(event)
  465. def OnLeftUpVarious(self, event):
  466. """!Left mouse button released - vector digitizer various
  467. actions
  468. """
  469. pos1 = self.Pixel2Cell(self.mouse['begin'])
  470. pos2 = self.Pixel2Cell(self.mouse['end'])
  471. nselected = 0
  472. action = self.toolbar.GetAction()
  473. # -> delete line || move line || move vertex
  474. if action in ("moveVertex",
  475. "editLine"):
  476. if len(self.digit.GetDisplay().GetSelected()) == 0:
  477. nselected = self.digit.GetDisplay().SelectLineByPoint(pos1)['point']
  478. if action == "editLine":
  479. try:
  480. selVertex = self.digit.GetDisplay().GetSelectedVertex(pos1)[0]
  481. except IndexError:
  482. selVertex = None
  483. if selVertex:
  484. # self.UpdateMap(render=False)
  485. ids = self.digit.GetDisplay().GetSelected(grassId = False)
  486. # move this line to tmp layer
  487. self.polycoords = []
  488. for id in ids:
  489. if id % 2: # register only vertices
  490. e, n = self.Pixel2Cell(self.pdcVector.GetIdBounds(id)[0:2])
  491. self.polycoords.append((e, n))
  492. self.digit.GetDisplay().DrawSelected(False)
  493. if selVertex < ids[-1] / 2:
  494. # choose first or last node of line
  495. self.moveInfo['id'].reverse()
  496. self.polycoords.reverse()
  497. else:
  498. # unselect
  499. self.digit.GetDisplay().SetSelected([])
  500. del self.moveInfo
  501. self.UpdateMap(render = False)
  502. elif action in ("copyCats",
  503. "copyAttrs"):
  504. if not hasattr(self, "copyCatsIds"):
  505. # 'from' -> select by point
  506. nselected = self.digit.GetDisplay().SelectLineByPoint(pos1)['point']
  507. if nselected:
  508. self.copyCatsList = self.digit.GetDisplay().GetSelected()
  509. else:
  510. # -> 'to' -> select by bbox
  511. self.digit.GetDisplay().SetSelected([])
  512. # return number of selected features (by box/point)
  513. nselected = self.digit.GetDisplay().SelectLinesByBox((pos1, pos2))
  514. if nselected == 0:
  515. if self.digit.GetDisplay().SelectLineByPoint(pos1) is not None:
  516. nselected = 1
  517. if nselected > 0:
  518. self.copyCatsIds = self.digit.GetDisplay().GetSelected()
  519. elif action == "queryLine":
  520. selected = self.digit.SelectLinesByQuery(bbox = (pos1, pos2))
  521. nselected = len(selected)
  522. if nselected > 0:
  523. self.digit.GetDisplay().SetSelected(selected)
  524. else:
  525. # -> moveLine || deleteLine, etc. (select by point/box)
  526. if action == 'moveLine' and \
  527. len(self.digit.GetDisplay().GetSelected()) > 0:
  528. nselected = 0
  529. else:
  530. if action == 'moveLine':
  531. drawSeg = True
  532. else:
  533. drawSeg = False
  534. nselected = self.digit.GetDisplay().SelectLinesByBox(bbox = (pos1, pos2),
  535. drawSeg = drawSeg)
  536. if nselected == 0:
  537. if self.digit.GetDisplay().SelectLineByPoint(pos1) is not None:
  538. nselected = 1
  539. if nselected > 0:
  540. if action in ("moveLine", "moveVertex") and \
  541. hasattr(self, "moveInfo"):
  542. # get pseudoDC id of objects which should be redrawn
  543. if action == "moveLine":
  544. # -> move line
  545. self.moveInfo['id'] = self.digit.GetDisplay().GetSelected(grassId = False)
  546. else: # moveVertex
  547. self.moveInfo['id'] = self.digit.GetDisplay().GetSelectedVertex(pos1)
  548. if len(self.moveInfo['id']) == 0: # no vertex found
  549. self.digit.GetDisplay().SetSelected([])
  550. #
  551. # check for duplicates
  552. #
  553. if UserSettings.Get(group = 'vdigit', key = 'checkForDupl', subkey = 'enabled'):
  554. dupl = self.digit.GetDisplay().GetDuplicates()
  555. self.UpdateMap(render = False)
  556. if dupl:
  557. posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
  558. self.mouse['end'][1] + self.dialogOffset))
  559. dlg = VDigitDuplicatesDialog(parent = self, data = dupl, pos = posWindow)
  560. if dlg.ShowModal() == wx.ID_OK:
  561. self.digit.GetDisplay().UnSelect(dlg.GetUnSelected())
  562. # update selected
  563. self.UpdateMap(render = False)
  564. if action != "editLine":
  565. # -> move line || move vertex
  566. self.UpdateMap(render = False)
  567. else: # no vector object found
  568. if not (action in ("moveLine",
  569. "moveVertex") and \
  570. hasattr(self, "moveInfo") and \
  571. len(self.moveInfo['id']) > 0):
  572. # avoid left-click when features are already selected
  573. self.UpdateMap(render = False, renderVector = False)
  574. def OnLeftUpModifyLine(self, event):
  575. """!Left mouse button released - vector digitizer split line,
  576. add/remove vertex action
  577. """
  578. pos1 = self.Pixel2Cell(self.mouse['begin'])
  579. pointOnLine = self.digit.GetDisplay().SelectLineByPoint(pos1)['point']
  580. if not pointOnLine:
  581. return
  582. if self.toolbar.GetAction() in ["splitLine", "addVertex"]:
  583. self.UpdateMap(render = False) # highlight object
  584. self.DrawCross(pdc = self.pdcTmp, coords = self.Cell2Pixel((pointOnLine[0], pointOnLine[1])),
  585. size = 5)
  586. else: # removeVertex
  587. # get only id of vertex
  588. try:
  589. id = self.digit.GetDisplay().GetSelectedVertex(pos1)[0]
  590. except IndexError:
  591. id = None
  592. if id:
  593. x, y = self.pdcVector.GetIdBounds(id)[0:2]
  594. self.pdcVector.RemoveId(id)
  595. self.UpdateMap(render = False) # highlight object
  596. self.DrawCross(pdc = self.pdcTmp, coords = (x, y),
  597. size = 5)
  598. else:
  599. # unselect
  600. self.digit.GetDisplay().SetSelected([])
  601. self.UpdateMap(render = False)
  602. def OnLeftUpCopyLine(self, event):
  603. """!Left mouse button released - vector digitizer copy feature
  604. action
  605. """
  606. pos1 = self.Pixel2Cell(self.mouse['begin'])
  607. pos2 = self.Pixel2Cell(self.mouse['end'])
  608. if UserSettings.Get(group = 'vdigit', key = 'bgmap',
  609. subkey = 'value', internal = True) == '':
  610. # no background map -> copy from current vector map layer
  611. nselected = self.bdigit.GetDisplay().SelectLinesByBox((pos1, pos2))
  612. if nselected > 0:
  613. # highlight selected features
  614. self.UpdateMap(render = False)
  615. else:
  616. self.UpdateMap(render = False, renderVector = False)
  617. else:
  618. # copy features from background map
  619. self.copyIds = self.digit.SelectLinesFromBackgroundMap(bbox = (pos1, pos2))
  620. if len(self.copyIds) > 0:
  621. color = UserSettings.Get(group = 'vdigit', key = 'symbol',
  622. subkey = ['highlight', 'color'])
  623. colorStr = str(color[0]) + ":" + str(color[1]) + ":" + str(color[2])
  624. dVectTmp = ['d.vect',
  625. 'map=%s' % UserSettings.Get(group = 'vdigit', key = 'bgmap',
  626. subkey = 'value', internal = True),
  627. 'cats=%s' % ListOfCatsToRange(self.copyIds),
  628. '-i',
  629. 'color=%s' % colorStr,
  630. 'fcolor=%s' % colorStr,
  631. 'type=point,line,boundary,centroid',
  632. 'width=2']
  633. if not self.layerTmp:
  634. self.layerTmp = self.Map.AddLayer(type = 'vector',
  635. name = QUERYLAYER,
  636. command = dVectTmp)
  637. else:
  638. self.layerTmp.SetCmd(dVectTmp)
  639. else:
  640. if self.layerTmp:
  641. self.Map.DeleteLayer(self.layerTmp)
  642. self.layerTmp = None
  643. self.UpdateMap(render = True, renderVector = True)
  644. def OnLeftUpBulkLine(self, event):
  645. """!Left mouse button released - vector digitizer z-bulk line
  646. action
  647. """
  648. # select lines to be labeled
  649. pos1 = self.polycoords[0]
  650. pos2 = self.polycoords[1]
  651. nselected = self.digit.GetDisplay().SelectLinesByBox((pos1, pos2))
  652. if nselected > 0:
  653. # highlight selected features
  654. self.UpdateMap(render = False)
  655. self.DrawLines(pdc = self.pdcTmp) # redraw temp line
  656. else:
  657. self.UpdateMap(render = False, renderVector = False)
  658. def OnLeftUpConnectLine(self, event):
  659. """!Left mouse button released - vector digitizer connect line
  660. action
  661. """
  662. if len(self.digit.GetDisplay().GetSelected()) > 0:
  663. self.UpdateMap(render = False)
  664. def _onLeftUp(self, event):
  665. """!Left mouse button released"""
  666. if hasattr(self, "moveInfo"):
  667. if len(self.digit.GetDisplay().GetSelected()) == 0:
  668. self.moveInfo['begin'] = self.Pixel2Cell(self.mouse['begin']) # left down
  669. # eliminate initial mouse moving efect
  670. self.mouse['begin'] = self.mouse['end']
  671. action = self.toolbar.GetAction()
  672. if action in ("deleteLine",
  673. "deleteArea",
  674. "moveLine",
  675. "moveVertex",
  676. "copyCats",
  677. "copyAttrs",
  678. "editLine",
  679. "flipLine",
  680. "mergeLine",
  681. "snapLine",
  682. "queryLine",
  683. "breakLine",
  684. "typeConv",
  685. "connectLine"):
  686. self.OnLeftUpVarious(event)
  687. elif action in ("splitLine",
  688. "addVertex",
  689. "removeVertex"):
  690. self.OnLeftUpModifyLine(event)
  691. elif action == "copyLine":
  692. self.OnLeftUpCopyLine(event)
  693. elif action == "zbulkLine" and \
  694. len(self.polycoords) == 2:
  695. self.OnLeftUpBulkLine(event)
  696. elif action == "connectLine":
  697. self.OnLeftUpConnectLine(event)
  698. if len(self.digit.GetDisplay().GetSelected()) > 0:
  699. self.redrawAll = None
  700. def _onRightDown(self, event):
  701. # digitization tool (confirm action)
  702. action = self.toolbar.GetAction()
  703. if action in ("moveLine", "moveVertex") and \
  704. hasattr(self, "moveInfo"):
  705. pFrom = self.moveInfo['begin']
  706. pTo = self.Pixel2Cell(event.GetPositionTuple())
  707. move = (pTo[0] - pFrom[0],
  708. pTo[1] - pFrom[1])
  709. if action == "moveLine":
  710. # move line
  711. if self.digit.MoveSelectedLines(move) < 0:
  712. return
  713. elif action == "moveVertex":
  714. # move vertex
  715. fid = self.digit.MoveSelectedVertex(pFrom, move)
  716. if fid < 0:
  717. return
  718. self._geomAttrbUpdate([fid,])
  719. del self.moveInfo
  720. def _onRightUp(self, event):
  721. """!Right mouse button released (confirm action)
  722. """
  723. action = self.toolbar.GetAction()
  724. if action == "addLine" and \
  725. self.toolbar.GetAction('type') in ["line", "boundary", "area"]:
  726. # -> add new line / boundary
  727. try:
  728. mapName = self.toolbar.GetLayer().GetName()
  729. except:
  730. mapName = None
  731. GError(parent = self,
  732. message = _("No vector map selected for editing."))
  733. if mapName:
  734. if self.toolbar.GetAction('type') == 'line':
  735. line = True
  736. else:
  737. line = False
  738. if len(self.polycoords) < 2: # ignore 'one-point' lines
  739. return
  740. nfeat, fids = self.digit.AddFeature(self.toolbar.GetAction('type'), self.polycoords)
  741. if nfeat < 0:
  742. return
  743. position = self.Cell2Pixel(self.polycoords[-1])
  744. self.polycoords = []
  745. self.UpdateMap(render = False)
  746. self.redrawAll = True
  747. self.Refresh()
  748. # add new record into atribute table
  749. if self._addRecord() and (line is True or (not line and nfeat > 0)):
  750. posWindow = self.ClientToScreen((position[0] + self.dialogOffset,
  751. position[1] + self.dialogOffset))
  752. # select attributes based on layer and category
  753. cats = { fids[0] : {
  754. UserSettings.Get(group = 'vdigit', key = "layer", subkey = 'value') :
  755. (UserSettings.Get(group = 'vdigit', key = "category", subkey = 'value'), )
  756. }}
  757. addRecordDlg = DisplayAttributesDialog(parent = self, map = mapName,
  758. cats = cats,
  759. pos = posWindow,
  760. action = "add", ignoreError = True)
  761. for fid in fids:
  762. self._geomAttrb(fid, addRecordDlg, 'length')
  763. # auto-placing centroid
  764. self._geomAttrb(fid, addRecordDlg, 'area')
  765. self._geomAttrb(fid, addRecordDlg, 'perimeter')
  766. if addRecordDlg.mapDBInfo and \
  767. addRecordDlg.ShowModal() == wx.ID_OK:
  768. sqlfile = tempfile.NamedTemporaryFile(mode = "w")
  769. for sql in addRecordDlg.GetSQLString():
  770. sqlfile.file.write(sql + ";\n")
  771. sqlfile.file.flush()
  772. RunCommand('db.execute',
  773. parent = True,
  774. quiet = True,
  775. input = sqlfile.name)
  776. if addRecordDlg.mapDBInfo:
  777. self._updateATM()
  778. elif action == "deleteLine":
  779. # -> delete selected vector features
  780. if self.digit.DeleteSelectedLines() < 0:
  781. return
  782. self._updateATM()
  783. elif action == "deleteArea":
  784. # -> delete selected vector areas
  785. if self.digit.DeleteSelectedAreas() < 0:
  786. return
  787. self._updateATM()
  788. elif action == "splitLine":
  789. # split line
  790. if self.digit.SplitLine(self.Pixel2Cell(self.mouse['begin'])) < 0:
  791. return
  792. elif action == "addVertex":
  793. # add vertex
  794. fid = self.digit.AddVertex(self.Pixel2Cell(self.mouse['begin']))
  795. if fid < 0:
  796. return
  797. elif action == "removeVertex":
  798. # remove vertex
  799. fid = self.digit.RemoveVertex(self.Pixel2Cell(self.mouse['begin']))
  800. if fid < 0:
  801. return
  802. self._geomAttrbUpdate([fid,])
  803. elif action in ("copyCats", "copyAttrs"):
  804. if action == 'copyCats':
  805. if self.digit.CopyCats(self.copyCatsList,
  806. self.copyCatsIds, copyAttrb = False) < 0:
  807. return
  808. else:
  809. if self.digit.CopyCats(self.copyCatsList,
  810. self.copyCatsIds, copyAttrb = True) < 0:
  811. return
  812. del self.copyCatsList
  813. del self.copyCatsIds
  814. self._updateATM()
  815. elif action == "editLine" and \
  816. hasattr(self, "moveInfo"):
  817. line = self.digit.GetDisplay().GetSelected()[0]
  818. if self.digit.EditLine(line, self.polycoords) < 0:
  819. return
  820. del self.moveInfo
  821. elif action == "flipLine":
  822. if self.digit.FlipLine() < 0:
  823. return
  824. elif action == "mergeLine":
  825. if self.digit.MergeLine() < 0:
  826. return
  827. elif action == "breakLine":
  828. if self.digit.BreakLine() < 0:
  829. return
  830. elif action == "snapLine":
  831. if self.digit.SnapLine() < 0:
  832. return
  833. elif action == "connectLine":
  834. if len(self.digit.GetDisplay().GetSelected()) > 1:
  835. if self.digit.ConnectLine() < 0:
  836. return
  837. elif action == "copyLine":
  838. if self.digit.CopyLine(self.copyIds) < 0:
  839. return
  840. del self.copyIds
  841. if self.layerTmp:
  842. self.Map.DeleteLayer(self.layerTmp)
  843. self.UpdateMap(render = True, renderVector = False)
  844. del self.layerTmp
  845. elif action == "zbulkLine" and len(self.polycoords) == 2:
  846. pos1 = self.polycoords[0]
  847. pos2 = self.polycoords[1]
  848. selected = self.digit.GetDisplay().GetSelected()
  849. dlg = VDigitZBulkDialog(parent = self, title = _("Z bulk-labeling dialog"),
  850. nselected = len(selected))
  851. if dlg.ShowModal() == wx.ID_OK:
  852. if self.digit.ZBulkLines(pos1, pos2, dlg.value.GetValue(),
  853. dlg.step.GetValue()) < 0:
  854. return
  855. self.UpdateMap(render = False)
  856. elif action == "typeConv":
  857. # -> feature type conversion
  858. # - point <-> centroid
  859. # - line <-> boundary
  860. if self.digit.TypeConvForSelectedLines() < 0:
  861. return
  862. if action != "addLine":
  863. # unselect and re-render
  864. self.digit.GetDisplay().SetSelected([])
  865. self.polycoords = []
  866. self.UpdateMap(render = False)
  867. def _onMouseMoving(self, event):
  868. self.mouse['end'] = event.GetPositionTuple()[:]
  869. Debug.msg (5, "BufferedWindow.OnMouseMoving(): coords=%f,%f" % \
  870. (self.mouse['end'][0], self.mouse['end'][1]))
  871. action = self.toolbar.GetAction()
  872. if action == "addLine" and \
  873. self.toolbar.GetAction('type') in ["line", "boundary", "area"]:
  874. if len(self.polycoords) > 0:
  875. self.MouseDraw(pdc = self.pdcTmp, begin = self.Cell2Pixel(self.polycoords[-1]))
  876. elif action in ["moveLine", "moveVertex", "editLine"] \
  877. and hasattr(self, "moveInfo"):
  878. dx = self.mouse['end'][0] - self.mouse['begin'][0]
  879. dy = self.mouse['end'][1] - self.mouse['begin'][1]
  880. # draw lines on new position
  881. if action == "moveLine" and \
  882. len(self.moveInfo['id']) > 0:
  883. # move line
  884. for id in self.moveInfo['id']:
  885. self.pdcTmp.TranslateId(id, dx, dy)
  886. elif action in ["moveVertex", "editLine"]:
  887. # move vertex ->
  888. # (vertex, left vertex, left line,
  889. # right vertex, right line)
  890. # do not draw static lines
  891. if action == "moveVertex" and \
  892. len(self.moveInfo['id']) > 0:
  893. self.polycoords = []
  894. self.pdcTmp.RemoveId(self.moveInfo['id'][0])
  895. if self.moveInfo['id'][1] > 0: # previous vertex
  896. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.moveInfo['id'][1])[0:2])
  897. self.pdcTmp.RemoveId(self.moveInfo['id'][1] + 1)
  898. self.polycoords.append((x, y))
  899. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  900. if self.moveInfo['id'][2] > 0: # next vertex
  901. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.moveInfo['id'][2])[0:2])
  902. self.pdcTmp.RemoveId(self.moveInfo['id'][2]-1)
  903. self.polycoords.append((x, y))
  904. self.ClearLines(pdc = self.pdcTmp)
  905. self.DrawLines(pdc = self.pdcTmp)
  906. if action == "editLine":
  907. self.MouseDraw(pdc = self.pdcTmp,
  908. begin = self.Cell2Pixel(self.polycoords[-1]))
  909. self.Refresh() # TODO: use RefreshRect()
  910. self.mouse['begin'] = self.mouse['end']
  911. elif action == "zbulkLine":
  912. if len(self.polycoords) == 1:
  913. # draw mouse moving
  914. self.MouseDraw(self.pdcTmp)
  915. def _zoom(self, event):
  916. tmp1 = self.mouse['end']
  917. tmp2 = self.Cell2Pixel(self.moveInfo['begin'])
  918. dx = tmp1[0] - tmp2[0]
  919. dy = tmp1[1] - tmp2[1]
  920. self.moveInfo['beginDiff'] = (dx, dy)
  921. for id in self.moveInfo['id']:
  922. self.pdcTmp.RemoveId(id)
  923. def _addRecord(self):
  924. return UserSettings.Get(group = 'vdigit', key = "addRecord", subkey = 'enabled')