wxvdriver.py 33 KB

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