wxdisplay.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. """!
  2. @package vdigit.wxdisplay
  3. @brief wxGUI vector digitizer (display driver)
  4. Code based on wxVdigit C++ component from GRASS 6.4.0
  5. (gui/wxpython/vdigit). Converted to Python in 2010/12-2011/01.
  6. List of classes:
  7. - wxdisplay::DisplayDriver
  8. (C) 2007-2011 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Martin Landa <landa.martin gmail.com>
  12. """
  13. import locale
  14. import wx
  15. from core.debug import Debug
  16. from core.settings import UserSettings
  17. from core.utils import _
  18. try:
  19. from grass.lib.gis import *
  20. from grass.lib.vector import *
  21. from grass.lib.vedit import *
  22. except ImportError:
  23. pass
  24. log = None
  25. progress = None
  26. last_error = ''
  27. def print_error(msg, type):
  28. """!Redirect stderr"""
  29. global log
  30. if log:
  31. log.write(msg + os.linesep)
  32. else:
  33. print msg
  34. global last_error
  35. last_error += ' ' + msg
  36. return 0
  37. def print_progress(value):
  38. """!Redirect progress info"""
  39. global progress
  40. if progress:
  41. progress.SetValue(value)
  42. else:
  43. pass # discard progress info
  44. return 0
  45. def GetLastError():
  46. global last_error
  47. ret = last_error
  48. if ret[-1] != '.':
  49. ret += '.'
  50. last_error = '' # reset
  51. return ret
  52. try:
  53. errtype = CFUNCTYPE(UNCHECKED(c_int), String, c_int)
  54. errfunc = errtype(print_error)
  55. pertype = CFUNCTYPE(UNCHECKED(c_int), c_int)
  56. perfunc = pertype(print_progress)
  57. except NameError:
  58. pass
  59. class DisplayDriver:
  60. def __init__(self, device, deviceTmp, mapObj, window, glog, gprogress):
  61. """!Display driver used by vector digitizer
  62. @param device wx.PseudoDC device where to draw vector objects
  63. @param deviceTmp wx.PseudoDC device where to draw temporary vector objects
  64. @param mapOng Map Object (render.Map)
  65. @param windiow parent window for dialogs
  66. @param glog logging device (None to discard messages)
  67. @param gprogress progress bar device (None to discard message)
  68. """
  69. global errfunc, perfunc, log, progress
  70. log = glog
  71. progress = gprogress
  72. G_gisinit('wxvdigit')
  73. locale.setlocale(locale.LC_NUMERIC, 'C')
  74. G_set_error_routine(errfunc)
  75. G_set_percent_routine(perfunc)
  76. # G_set_fatal_error(FATAL_RETURN)
  77. self.mapInfo = None # open vector map (Map_Info structure)
  78. self.poMapInfo = None # pointer to self.mapInfo
  79. self.is3D = False # is open vector map 3D
  80. self.dc = device # PseudoDC devices
  81. self.dcTmp = deviceTmp
  82. self.mapObj = mapObj
  83. self.region = mapObj.GetCurrentRegion()
  84. self.window = window
  85. self.log = log # log device
  86. self.firstNode = True # track PseudoDC Id of selected features
  87. self.lastNodeId = -1
  88. # GRASS lib
  89. self.poPoints = Vect_new_line_struct()
  90. self.poCats = Vect_new_cats_struct()
  91. # selected objects
  92. self.selected = {
  93. 'field' : -1, # field number
  94. 'cats' : list(), # list of cats
  95. 'ids' : list(), # list of ids
  96. 'idsDupl' : list(), # list of duplicated features
  97. }
  98. # digitizer settings
  99. self.settings = {
  100. 'highlight' : None,
  101. 'highlightDupl' : { 'enabled' : False,
  102. 'color' : None },
  103. 'point' : { 'enabled' : False,
  104. 'color' : None },
  105. 'line' : { 'enabled' : False,
  106. 'color' : None },
  107. 'boundaryNo' : { 'enabled' : False,
  108. 'color' : None },
  109. 'boundaryOne' : { 'enabled' : False,
  110. 'color' : None },
  111. 'boundaryTwo' : { 'enabled' : False,
  112. 'color' : None },
  113. 'centroidIn' : { 'enabled' : False,
  114. 'color' : None },
  115. 'centroidOut' : { 'enabled' : False,
  116. 'color' : None },
  117. 'centroidDup' : { 'enabled' : False,
  118. 'color' : None },
  119. 'nodeOne' : { 'enabled' : False,
  120. 'color' : None },
  121. 'nodeTwo' : { 'enabled' : False,
  122. 'color' : None },
  123. 'vertex' : { 'enabled' : False,
  124. 'color' : None },
  125. 'area' : { 'enabled' : False,
  126. 'color' : None },
  127. 'direction' : { 'enabled' : False,
  128. 'color' : None },
  129. 'lineWidth' : -1, # screen units
  130. }
  131. # topology
  132. self._resetTopology()
  133. self._drawSelected = False
  134. self._drawSegments = False
  135. self.UpdateSettings()
  136. def __del__(self):
  137. """!Close currently open vector map"""
  138. G_unset_error_routine()
  139. G_unset_percent_routine()
  140. if self.poMapInfo:
  141. self.CloseMap()
  142. Vect_destroy_line_struct(self.poPoints)
  143. Vect_destroy_cats_struct(self.poCats)
  144. def _resetTopology(self):
  145. """!Reset topology dict
  146. """
  147. self.topology = {
  148. 'highlight' : 0,
  149. 'point' : 0,
  150. 'line' : 0,
  151. 'boundaryNo' : 0,
  152. 'boundaryOne' : 0,
  153. 'boundaryTwo' : 0,
  154. 'centroidIn' : 0,
  155. 'centroidOut' : 0,
  156. 'centroidDup' : 0,
  157. 'nodeOne' : 0,
  158. 'nodeTwo' : 0,
  159. 'vertex' : 0,
  160. }
  161. def _cell2Pixel(self, east, north, elev):
  162. """!Conversion from geographic coordinates (east, north)
  163. to screen (x, y)
  164. @todo 3D stuff...
  165. @param east, north, elev geographical coordinates
  166. @return x, y screen coordinates (integer)
  167. """
  168. map_res = max(self.region['ewres'], self.region['nsres'])
  169. w = self.region['center_easting'] - (self.mapObj.width / 2) * map_res
  170. n = self.region['center_northing'] + (self.mapObj.height / 2) * map_res
  171. return int((east - w) / map_res), int((n - north) / map_res)
  172. def _drawCross(self, pdc, point, size = 5):
  173. """!Draw cross symbol of given size to device content
  174. Used for points, nodes, vertices
  175. @param[in,out] PseudoDC where to draw
  176. @param point coordinates of center
  177. @param size size of the cross symbol
  178. @return 0 on success
  179. @return -1 on failure
  180. """
  181. if not pdc or not point:
  182. return -1
  183. pdc.DrawLine(point.x - size, point.y, point.x + size, point.y)
  184. pdc.DrawLine(point.x, point.y - size, point.x, point.y + size)
  185. return 0
  186. def _drawObject(self, robj):
  187. """!Draw given object to the device
  188. The object is defined as robject() from vedit.h.
  189. @param robj object to be rendered
  190. @return 1 on success
  191. @return -1 on failure (vector feature marked as dead, etc.)
  192. """
  193. if not self.dc or not self.dcTmp:
  194. return -1
  195. Debug.msg(3, "_drawObject(): line=%d type=%d npoints=%d", robj.fid, robj.type, robj.npoints)
  196. brush = None
  197. if self._isSelected(robj.fid):
  198. pdc = self.dcTmp
  199. if robj.type == TYPE_AREA:
  200. return 1
  201. else:
  202. if self.settings['highlightDupl']['enabled'] and self._isDuplicated(robj.fid):
  203. pen = wx.Pen(self.settings['highlightDupl']['color'], self.settings['lineWidth'], wx.SOLID)
  204. else:
  205. pen = wx.Pen(self.settings['highlight'], self.settings['lineWidth'], wx.SOLID)
  206. dcId = 1
  207. self.topology['highlight'] += 1
  208. if not self._drawSelected:
  209. return
  210. else:
  211. pdc = self.dc
  212. pen, brush = self._definePen(robj.type)
  213. dcId = 0
  214. pdc.SetPen(pen)
  215. if brush:
  216. pdc.SetBrush(brush)
  217. if robj.type & (TYPE_POINT | TYPE_CENTROIDIN | TYPE_CENTROIDOUT | TYPE_CENTROIDDUP |
  218. TYPE_NODEONE | TYPE_NODETWO | TYPE_VERTEX): # -> point
  219. if dcId > 0:
  220. if robj.type == TYPE_VERTEX:
  221. dcId = 3 # first vertex
  222. elif robj.type & (TYPE_NODEONE | TYPE_NODETWO):
  223. if self.firstNode:
  224. dcId = 1
  225. self.firstNode = False
  226. else:
  227. dcId = self.lastNodeId
  228. for i in range(robj.npoints):
  229. p = robj.point[i]
  230. if dcId > 0:
  231. pdc.SetId(dcId)
  232. dcId += 2
  233. self._drawCross(pdc, p)
  234. else:
  235. if dcId > 0 and self._drawSegments:
  236. self.fisrtNode = True
  237. self.lastNodeId = robj.npoints * 2 - 1
  238. dcId = 2 # first segment
  239. i = 0
  240. while i < robj.npoints - 1:
  241. point_beg = wx.Point(robj.point[i].x, robj.point[i].y)
  242. point_end = wx.Point(robj.point[i+1].x, robj.point[i+1].y)
  243. pdc.SetId(dcId) # set unique id & set bbox for each segment
  244. pdc.SetPen(pen)
  245. pdc.SetIdBounds(dcId - 1, wx.Rect(point_beg.x, point_beg.y, 0, 0))
  246. pdc.SetIdBounds(dcId, wx.RectPP(point_beg, point_end))
  247. pdc.DrawLine(point_beg.x, point_beg.y,
  248. point_end.x, point_end.y)
  249. i += 1
  250. dcId += 2
  251. pdc.SetIdBounds(dcId - 1, wx.Rect(robj.point[robj.npoints - 1].x,
  252. robj.point[robj.npoints - 1].y,
  253. 0, 0))
  254. else:
  255. points = list()
  256. for i in range(robj.npoints):
  257. p = robj.point[i]
  258. points.append(wx.Point(p.x, p.y))
  259. if robj.type == TYPE_AREA:
  260. pdc.DrawPolygon(points)
  261. else:
  262. pdc.DrawLines(points)
  263. def _definePen(self, rtype):
  264. """!Define pen/brush based on rendered object)
  265. Updates also self.topology dict
  266. @return pen, brush
  267. """
  268. if rtype == TYPE_POINT:
  269. key = 'point'
  270. elif rtype == TYPE_LINE:
  271. key = 'line'
  272. elif rtype == TYPE_BOUNDARYNO:
  273. key = 'boundaryNo'
  274. elif rtype == TYPE_BOUNDARYTWO:
  275. key = 'boundaryTwo'
  276. elif rtype == TYPE_BOUNDARYONE:
  277. key = 'boundaryOne'
  278. elif rtype == TYPE_CENTROIDIN:
  279. key = 'centroidIn'
  280. elif rtype == TYPE_CENTROIDOUT:
  281. key = 'centroidOut'
  282. elif rtype == TYPE_CENTROIDDUP:
  283. key = 'centroidDup'
  284. elif rtype == TYPE_NODEONE:
  285. key = 'nodeOne'
  286. elif rtype == TYPE_NODETWO:
  287. key = 'nodeTwo'
  288. elif rtype == TYPE_VERTEX:
  289. key = 'vertex'
  290. elif rtype == TYPE_AREA:
  291. key = 'area'
  292. elif rtype == TYPE_ISLE:
  293. key = 'isle'
  294. elif rtype == TYPE_DIRECTION:
  295. key = 'direction'
  296. if key not in ('direction', 'area', 'isle'):
  297. self.topology[key] += 1
  298. if key in ('area', 'isle'):
  299. pen = wx.TRANSPARENT_PEN
  300. if key == 'area':
  301. brush = wx.Brush(self.settings[key]['color'], wx.SOLID)
  302. else:
  303. brush = wx.TRANSPARENT_BRUSH
  304. else:
  305. pen = wx.Pen(self.settings[key]['color'], self.settings['lineWidth'], wx.SOLID)
  306. brush = None
  307. return pen, brush
  308. def _getDrawFlag(self):
  309. """!Get draw flag from the settings
  310. See vedit.h for list of draw flags.
  311. @return draw flag (int)
  312. """
  313. ret = 0
  314. if self.settings['point']['enabled']:
  315. ret |= DRAW_POINT
  316. if self.settings['line']['enabled']:
  317. ret |= DRAW_LINE
  318. if self.settings['boundaryNo']['enabled']:
  319. ret |= DRAW_BOUNDARYNO
  320. if self.settings['boundaryTwo']['enabled']:
  321. ret |= DRAW_BOUNDARYTWO
  322. if self.settings['boundaryOne']['enabled']:
  323. ret |= DRAW_BOUNDARYONE
  324. if self.settings['centroidIn']['enabled']:
  325. ret |= DRAW_CENTROIDIN
  326. if self.settings['centroidOut']['enabled']:
  327. ret |= DRAW_CENTROIDOUT
  328. if self.settings['centroidDup']['enabled']:
  329. ret |= DRAW_CENTROIDDUP
  330. if self.settings['nodeOne']['enabled']:
  331. ret |= DRAW_NODEONE
  332. if self.settings['nodeTwo']['enabled']:
  333. ret |= DRAW_NODETWO
  334. if self.settings['vertex']['enabled']:
  335. ret |= DRAW_VERTEX
  336. if self.settings['area']['enabled']:
  337. ret |= DRAW_AREA
  338. if self.settings['direction']['enabled']:
  339. ret |= DRAW_DIRECTION
  340. return ret
  341. def _isSelected(self, line, force = False):
  342. """!Check if vector object selected?
  343. @param line feature id
  344. @return True if vector object is selected
  345. @return False if vector object is not selected
  346. """
  347. if line in self.selected['ids']:
  348. return True
  349. return False
  350. def _isDuplicated(self, line):
  351. """!Check for already marked duplicates
  352. @param line feature id
  353. @return True line already marked as duplicated
  354. @return False not duplicated
  355. """
  356. return line in self.selected['idsDupl']
  357. def _getRegionBox(self):
  358. """!Get bound_box() from current region
  359. @return bound_box
  360. """
  361. box = bound_box()
  362. box.N = self.region['n']
  363. box.S = self.region['s']
  364. box.E = self.region['e']
  365. box.W = self.region['w']
  366. box.T = PORT_DOUBLE_MAX
  367. box.B = -PORT_DOUBLE_MAX
  368. return box
  369. def DrawMap(self, force = False):
  370. """!Draw content of the vector map to the device
  371. @param force force drawing
  372. @return number of drawn features
  373. @return -1 on error
  374. """
  375. Debug.msg(1, "DisplayDriver.DrawMap(): force=%d", force)
  376. if not self.poMapInfo or not self.dc or not self.dcTmp:
  377. return -1
  378. rlist = Vedit_render_map(self.poMapInfo, byref(self._getRegionBox()), self._getDrawFlag(),
  379. self.region['center_easting'], self.region['center_northing'],
  380. self.mapObj.width, self.mapObj.height,
  381. max(self.region['nsres'], self.region['ewres'])).contents
  382. self._resetTopology()
  383. self.dc.BeginDrawing()
  384. self.dcTmp.BeginDrawing()
  385. # draw objects
  386. for i in range(rlist.nitems):
  387. robj = rlist.item[i].contents
  388. self._drawObject(robj)
  389. self.dc.EndDrawing()
  390. self.dcTmp.EndDrawing()
  391. # reset list of selected features by cat
  392. # list of ids - see IsSelected()
  393. self.selected['field'] = -1
  394. self.selected['cats'] = list()
  395. def _getSelectType(self):
  396. """!Get type(s) to be selected
  397. Used by SelectLinesByBox() and SelectLineByPoint()
  398. """
  399. ftype = 0
  400. for feature in (('point', GV_POINT),
  401. ('line', GV_LINE),
  402. ('centroid', GV_CENTROID),
  403. ('boundary', GV_BOUNDARY)):
  404. if UserSettings.Get(group = 'vdigit', key = 'selectType',
  405. subkey = [feature[0], 'enabled']):
  406. ftype |= feature[1]
  407. return ftype
  408. def _validLine(self, line):
  409. """!Check if feature id is valid
  410. @param line feature id
  411. @return True valid feature id
  412. @return False invalid
  413. """
  414. if line > 0 and line <= Vect_get_num_lines(self.poMapInfo):
  415. return True
  416. return False
  417. def SelectLinesByBox(self, bbox, drawSeg = False, poMapInfo = None):
  418. """!Select vector objects by given bounding box
  419. If line id is already in the list of selected lines, then it will
  420. be excluded from this list.
  421. @param bbox bounding box definition
  422. @param drawSeg True to draw segments of line
  423. @param poMapInfo use external Map_info, None for self.poMapInfo
  424. @return number of selected features
  425. @return None on error
  426. """
  427. thisMapInfo = poMapInfo is None
  428. if not poMapInfo:
  429. poMapInfo = self.poMapInfo
  430. if not poMapInfo:
  431. return None
  432. if thisMapInfo:
  433. self._drawSegments = drawSeg
  434. self._drawSelected = True
  435. # select by ids
  436. self.selected['cats'] = list()
  437. poList = Vect_new_list()
  438. x1, y1 = bbox[0]
  439. x2, y2 = bbox[1]
  440. poBbox = Vect_new_line_struct()
  441. Vect_append_point(poBbox, x1, y1, 0.0)
  442. Vect_append_point(poBbox, x2, y1, 0.0)
  443. Vect_append_point(poBbox, x2, y2, 0.0)
  444. Vect_append_point(poBbox, x1, y2, 0.0)
  445. Vect_append_point(poBbox, x1, y1, 0.0)
  446. Vect_select_lines_by_polygon(poMapInfo, poBbox,
  447. 0, None, # isles
  448. self._getSelectType(), poList)
  449. flist = poList.contents
  450. nlines = flist.n_values
  451. Debug.msg(1, "DisplayDriver.SelectLinesByBox() num = %d", nlines)
  452. for i in range(nlines):
  453. line = flist.value[i]
  454. if UserSettings.Get(group = 'vdigit', key = 'selectInside',
  455. subkey = 'enabled'):
  456. inside = True
  457. if not self._validLine(line):
  458. return None
  459. Vect_read_line(poMapInfo, self.poPoints, None, line)
  460. points = self.poPoints.contents
  461. for p in range(points.n_points):
  462. if not Vect_point_in_poly(points.x[p], points.y[p],
  463. poBbox):
  464. inside = False
  465. break
  466. if not inside:
  467. continue # skip lines just overlapping bbox
  468. if not self._isSelected(line):
  469. self.selected['ids'].append(line)
  470. else:
  471. self.selected['ids'].remove(line)
  472. Vect_destroy_line_struct(poBbox)
  473. Vect_destroy_list(poList)
  474. return nlines
  475. def SelectLineByPoint(self, point, poMapInfo = None):
  476. """!Select vector feature by given point in given
  477. threshold
  478. Only one vector object can be selected. Bounding boxes of
  479. all segments are stores.
  480. @param point points coordinates (x, y)
  481. @param poMapInfo use external Map_info, None for self.poMapInfo
  482. @return dict {'line' : feature id, 'point' : point on line}
  483. """
  484. thisMapInfo = poMapInfo is None
  485. if not poMapInfo:
  486. poMapInfo = self.poMapInfo
  487. if not poMapInfo:
  488. return { 'line' : -1, 'point': None }
  489. if thisMapInfo:
  490. self._drawSelected = True
  491. # select by ids
  492. self.selected['cats'] = list()
  493. poFound = Vect_new_list()
  494. lineNearest = Vect_find_line_list(poMapInfo, point[0], point[1], 0,
  495. self._getSelectType(), self.GetThreshold(), self.is3D,
  496. None, poFound)
  497. Debug.msg(1, "DisplayDriver.SelectLineByPoint() found = %d", lineNearest)
  498. if lineNearest > 0:
  499. if not self._isSelected(lineNearest):
  500. self.selected['ids'].append(lineNearest)
  501. else:
  502. self.selected['ids'].remove(lineNearest)
  503. px = c_double()
  504. py = c_double()
  505. pz = c_double()
  506. if not self._validLine(lineNearest):
  507. return { 'line' : -1, 'point': None }
  508. ftype = Vect_read_line(poMapInfo, self.poPoints, self.poCats, lineNearest)
  509. Vect_line_distance(self.poPoints, point[0], point[1], 0.0, self.is3D,
  510. byref(px), byref(py), byref(pz),
  511. None, None, None)
  512. # check for duplicates
  513. if self.settings['highlightDupl']['enabled']:
  514. found = poFound.contents
  515. for i in range(found.n_values):
  516. line = found.value[i]
  517. if line != lineNearest:
  518. self.selected['ids'].append(line)
  519. self.GetDuplicates()
  520. for i in range(found.n_values):
  521. line = found.value[i]
  522. if line != lineNearest and not self._isDuplicated(line):
  523. self.selected['ids'].remove(line)
  524. Vect_destroy_list(poFound)
  525. if thisMapInfo:
  526. # drawing segments can be very expensive
  527. # only one features selected
  528. self._drawSegments = True
  529. return { 'line' : lineNearest,
  530. 'point' : (px.value, py.value, pz.value) }
  531. def _listToIList(self, plist):
  532. """!Generate from list struct_ilist
  533. """
  534. ilist = Vect_new_list()
  535. for val in plist:
  536. Vect_list_append(ilist, val)
  537. return ilist
  538. def GetSelectedIList(self, ilist = None):
  539. """!Get list of selected objects as struct_ilist
  540. Returned IList must be freed by Vect_destroy_list().
  541. @return struct_ilist
  542. """
  543. if ilist:
  544. return self._listToIList(ilist)
  545. return self._listToIList(self.selected['ids'])
  546. def GetSelected(self, grassId = True):
  547. """!Get ids of selected objects
  548. @param grassId True for feature id, False for PseudoDC id
  549. @return list of ids of selected vector objects
  550. """
  551. if grassId:
  552. return self.selected['ids']
  553. dc_ids = list()
  554. if not self._drawSegments:
  555. dc_ids.append(1)
  556. elif len(self.selected['ids']) > 0:
  557. # only first selected feature
  558. Vect_read_line(self.poMapInfo, self.poPoints, None,
  559. self.selected['ids'][0])
  560. points = self.poPoints.contents
  561. # node - segment - vertex - segment - node
  562. for i in range(1, 2 * points.n_points):
  563. dc_ids.append(i)
  564. return dc_ids
  565. def SetSelected(self, ids, layer = -1):
  566. """!Set selected vector objects
  567. @param list of ids (None to unselect features)
  568. @param layer layer number for features selected based on category number
  569. """
  570. if ids:
  571. self._drawSelected = True
  572. else:
  573. self._drawSelected = False
  574. self.selected['field'] = layer
  575. if layer > 0:
  576. self.selected['cats'] = ids
  577. self.selected['ids'] = list()
  578. ### cidx is not up-to-date
  579. # Vect_cidx_find_all(self.poMapInfo, layer, GV_POINTS | GV_LINES, lid, ilist)
  580. nlines = Vect_get_num_lines(self.poMapInfo)
  581. for line in range(1, nlines + 1):
  582. if not Vect_line_alive(self.poMapInfo, line):
  583. continue
  584. ltype = Vect_read_line (self.poMapInfo, None, self.poCats, line)
  585. if not (ltype & (GV_POINTS | GV_LINES)):
  586. continue
  587. found = False
  588. cats = self.poCats.contents
  589. for i in range(0, cats.n_cats):
  590. for cat in self.selected['cats']:
  591. if cats.cat[i] == cat:
  592. found = True
  593. break
  594. if found:
  595. self.selected['ids'].append(line)
  596. else:
  597. self.selected['ids'] = ids
  598. self.selected['cats'] = []
  599. def GetSelectedVertex(self, pos):
  600. """!Get PseudoDC vertex id of selected line
  601. Set bounding box for vertices of line.
  602. @param pos position
  603. @return id of center, left and right vertex
  604. @return 0 no line found
  605. @return -1 on error
  606. """
  607. returnId = list()
  608. # only one object can be selected
  609. if len(self.selected['ids']) != 1 or not self._drawSegments:
  610. return returnId
  611. startId = 1
  612. line = self.selected['ids'][0]
  613. if not self._validLine(line):
  614. return -1
  615. ftype = Vect_read_line(self.poMapInfo, self.poPoints, self.poCats, line)
  616. minDist = 0.0
  617. Gid = -1
  618. # find the closest vertex (x, y)
  619. DCid = 1
  620. points = self.poPoints.contents
  621. for idx in range(points.n_points):
  622. dist = Vect_points_distance(pos[0], pos[1], 0.0,
  623. points.x[idx], points.y[idx], points.z[idx], 0)
  624. if idx == 0:
  625. minDist = dist
  626. Gid = idx
  627. else:
  628. if minDist > dist:
  629. minDist = dist
  630. Gid = idx
  631. vx, vy = self._cell2Pixel(points.x[idx], points.y[idx], points.z[idx])
  632. rect = wx.Rect(vx, vy, 0, 0)
  633. self.dc.SetIdBounds(DCid, rect)
  634. DCid += 2
  635. if minDist > self.GetThreshold():
  636. return returnId
  637. # translate id
  638. DCid = Gid * 2 + 1
  639. # add selected vertex
  640. returnId.append(DCid)
  641. # left vertex
  642. if DCid == startId:
  643. returnId.append(-1)
  644. else:
  645. returnId.append(DCid - 2)
  646. # right vertex
  647. if DCid == (points.n_points - 1) * 2 + startId:
  648. returnId.append(-1)
  649. else:
  650. returnId.append(DCid + 2)
  651. return returnId
  652. def GetRegionSelected(self):
  653. """!Get minimal region extent of selected features
  654. @return n,s,w,e
  655. """
  656. regionBox = bound_box()
  657. lineBox = bound_box()
  658. setRegion = True
  659. nareas = Vect_get_num_areas(self.poMapInfo)
  660. for line in self.selected['ids']:
  661. area = Vect_get_centroid_area(self.poMapInfo, line)
  662. if area > 0 and area <= nareas:
  663. if not Vect_get_area_box(self.poMapInfo, area, byref(lineBox)):
  664. continue
  665. else:
  666. if not Vect_get_line_box(self.poMapInfo, line, byref(lineBox)):
  667. continue
  668. if setRegion:
  669. Vect_box_copy(byref(regionBox), byref(lineBox))
  670. setRegion = False
  671. else:
  672. Vect_box_extend(byref(regionBox), byref(lineBox))
  673. return regionBox.N, regionBox.S, regionBox.W, regionBox.E
  674. def DrawSelected(self, flag):
  675. """!Draw selected features
  676. @param flag True to draw selected features
  677. """
  678. self._drawSelected = bool(flag)
  679. def CloseMap(self):
  680. """!Close vector map
  681. @return 0 on success
  682. @return non-zero on error
  683. """
  684. ret = 0
  685. if self.poMapInfo:
  686. # rebuild topology
  687. Vect_build_partial(self.poMapInfo, GV_BUILD_NONE)
  688. Vect_build(self.poMapInfo)
  689. # close map and store topo/cidx
  690. ret = Vect_close(self.poMapInfo)
  691. del self.mapInfo
  692. self.poMapInfo = self.mapInfo = None
  693. return ret
  694. def OpenMap(self, name, mapset, update = True, tmp = False):
  695. """!Open vector map by the driver
  696. @param name name of vector map to be open
  697. @param mapset name of mapset where the vector map lives
  698. @param update True to open vector map in update mode
  699. @param tmp True to open temporary vector map
  700. @return map_info
  701. @return None on error
  702. """
  703. Debug.msg("DisplayDriver.OpenMap(): name=%s mapset=%s updated=%d",
  704. name, mapset, update)
  705. if not self.mapInfo:
  706. self.mapInfo = Map_info()
  707. self.poMapInfo = pointer(self.mapInfo)
  708. # open existing map
  709. if update:
  710. if tmp:
  711. open_fn = Vect_open_tmp_update
  712. else:
  713. open_fn = Vect_open_update
  714. else:
  715. if tmp:
  716. open_fn = Vect_open_tmp_old
  717. else:
  718. open_fn = Vect_open_old
  719. ret = open_fn(self.poMapInfo, name, mapset)
  720. if ret == -1:
  721. # fatal error detected
  722. del self.mapInfo
  723. self.poMapInfo = self.mapInfo = None
  724. elif ret < 2:
  725. # map open at level 1, try to build topology
  726. dlg = wx.MessageDialog(parent = self.window,
  727. message = _("Topology for vector map <%s> is not available. "
  728. "Topology is required by digitizer. Do you want to "
  729. "rebuild topology (takes some time) and open the vector map "
  730. "for editing?") % name,
  731. caption=_("Topology missing"),
  732. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  733. ret = dlg.ShowModal()
  734. if ret != wx.ID_YES:
  735. del self.mapInfo
  736. self.poMapInfo = self.mapInfo = None
  737. else:
  738. Vect_build(self.poMapInfo)
  739. if update:
  740. Vect_set_updated(self.poMapInfo, True) # track updated lines at update mode
  741. self.is3D = Vect_is_3d(self.poMapInfo)
  742. return self.poMapInfo
  743. def GetMapBoundingBox(self):
  744. """!Get bounding box of (opened) vector map layer
  745. @return (w,s,b,e,n,t)
  746. """
  747. if not self.poMapInfo:
  748. return None
  749. bbox = bound_box()
  750. Vect_get_map_box(self.poMapInfo, byref(bbox))
  751. return bbox.W, bbox.S, bbox.B, \
  752. bbox.E, bbox.N, bbox.T
  753. def UpdateSettings(self, alpha = 255):
  754. """!Update display driver settings
  755. @todo map units
  756. @param alpha color value for aplha channel
  757. """
  758. color = dict()
  759. for key in self.settings.keys():
  760. if key == 'lineWidth':
  761. self.settings[key] = int(UserSettings.Get(group = 'vdigit', key = 'lineWidth',
  762. subkey = 'value'))
  763. continue
  764. color = wx.Colour(UserSettings.Get(group = 'vdigit', key = 'symbol',
  765. subkey = [key, 'color'])[0],
  766. UserSettings.Get(group = 'vdigit', key = 'symbol',
  767. subkey = [key, 'color'])[1],
  768. UserSettings.Get(group = 'vdigit', key = 'symbol',
  769. subkey = [key, 'color'])[2],
  770. alpha)
  771. if key == 'highlight':
  772. self.settings[key] = color
  773. continue
  774. if key == 'highlightDupl':
  775. self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'checkForDupl',
  776. subkey = 'enabled'))
  777. else:
  778. self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'symbol',
  779. subkey = [key, 'enabled']))
  780. self.settings[key]['color'] = color
  781. def UpdateRegion(self):
  782. """!Update geographical region used by display driver
  783. """
  784. self.region = self.mapObj.GetCurrentRegion()
  785. def GetThreshold(self, type = 'snapping', value = None, units = None):
  786. """!Return threshold value in map units
  787. @param type snapping mode (node, vertex)
  788. @param value threshold to be set up
  789. @param units units (map, screen)
  790. @return threshold value
  791. """
  792. if value is None:
  793. value = UserSettings.Get(group = 'vdigit', key = type, subkey = 'value')
  794. if units is None:
  795. units = UserSettings.Get(group = 'vdigit', key = type, subkey = 'units')
  796. if value < 0:
  797. value = (self.region['nsres'] + self.region['ewres']) / 2.0
  798. if units == "screen pixels":
  799. # pixel -> cell
  800. res = max(self.region['nsres'], self.region['ewres'])
  801. return value * res
  802. return value
  803. def GetDuplicates(self):
  804. """!Return ids of (selected) duplicated vector features
  805. """
  806. if not self.poMapInfo:
  807. return
  808. ids = dict()
  809. APoints = Vect_new_line_struct()
  810. BPoints = Vect_new_line_struct()
  811. self.selected['idsDupl'] = list()
  812. for i in range(len(self.selected['ids'])):
  813. line1 = self.selected['ids'][i]
  814. if self._isDuplicated(line1):
  815. continue
  816. Vect_read_line(self.poMapInfo, APoints, None, line1)
  817. for line2 in self.selected['ids']:
  818. if line1 == line2 or self._isDuplicated(line2):
  819. continue
  820. Vect_read_line(self.poMapInfo, BPoints, None, line2)
  821. if Vect_line_check_duplicate(APoints, BPoints, WITHOUT_Z):
  822. if i not in ids:
  823. ids[i] = list()
  824. ids[i].append((line1, self._getCatString(line1)))
  825. self.selected['idsDupl'].append(line1)
  826. ids[i].append((line2, self._getCatString(line2)))
  827. self.selected['idsDupl'].append(line2)
  828. Vect_destroy_line_struct(APoints)
  829. Vect_destroy_line_struct(BPoints)
  830. return ids
  831. def _getCatString(self, line):
  832. Vect_read_line(self.poMapInfo, None, self.poCats, line)
  833. cats = self.poCats.contents
  834. catsDict = dict()
  835. for i in range(cats.n_cats):
  836. layer = cats.field[i]
  837. if layer not in catsDict:
  838. catsDict[layer] = list()
  839. catsDict[layer].append(cats.cat[i])
  840. catsStr = ''
  841. for l, c in catsDict.iteritems():
  842. catsStr = '%d: (%s)' % (l, ','.join(map(str, c)))
  843. return catsStr
  844. def UnSelect(self, lines):
  845. """!Unselect vector features
  846. @param lines list of feature id(s)
  847. """
  848. checkForDupl = False
  849. for line in lines:
  850. if self._isSelected(line):
  851. self.selected['ids'].remove(line)
  852. if self.settings['highlightDupl']['enabled'] and self._isDuplicated(line):
  853. checkForDupl = True
  854. if checkForDupl:
  855. self.GetDuplicates()
  856. return len(self.selected['ids'])