mapdisp_vdigit.py 43 KB

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