wxvdriver.py 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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. rlist = Vedit_render_map(self.poMapInfo, byref(self._getRegionBox()), self._getDrawFlag(),
  371. self.region['center_easting'], self.region['center_northing'],
  372. self.mapObj.width, self.mapObj.height,
  373. max(self.region['nsres'], self.region['ewres'])).contents
  374. self._resetTopology()
  375. self.dc.BeginDrawing()
  376. self.dcTmp.BeginDrawing()
  377. # draw objects
  378. for i in range(rlist.nitems):
  379. robj = rlist.item[i].contents
  380. self._drawObject(robj)
  381. self.dc.EndDrawing()
  382. self.dcTmp.EndDrawing()
  383. # reset list of selected features by cat
  384. # list of ids - see IsSelected()
  385. self.selected['field'] = -1
  386. self.selected['cats'] = list()
  387. def _getSelectType(self):
  388. """!Get type(s) to be selected
  389. Used by SelectLinesByBox() and SelectLineByPoint()
  390. """
  391. ftype = 0
  392. for feature in (('point', GV_POINT),
  393. ('line', GV_LINE),
  394. ('centroid', GV_CENTROID),
  395. ('boundary', GV_BOUNDARY)):
  396. if UserSettings.Get(group = 'vdigit', key = 'selectType',
  397. subkey = [feature[0], 'enabled']):
  398. ftype |= feature[1]
  399. return ftype
  400. def _validLine(self, line):
  401. """!Check if feature id is valid
  402. @param line feature id
  403. @return True valid feature id
  404. @return False invalid
  405. """
  406. if line > 0 and line <= Vect_get_num_lines(self.poMapInfo):
  407. return True
  408. return False
  409. def SelectLinesByBox(self, bbox, drawSeg = False, poMapInfo = None):
  410. """!Select vector objects by given bounding box
  411. If line id is already in the list of selected lines, then it will
  412. be excluded from this list.
  413. @param bbox bounding box definition
  414. @param drawSeg True to draw segments of line
  415. @param poMapInfo use external Map_info, None for self.poMapInfo
  416. @return number of selected features
  417. @return None on error
  418. """
  419. thisMapInfo = poMapInfo is None
  420. if not poMapInfo:
  421. poMapInfo = self.poMapInfo
  422. if not poMapInfo:
  423. return None
  424. if thisMapInfo:
  425. self._drawSegments = drawSeg
  426. self._drawSelected = True
  427. # select by ids
  428. self.selected['cats'] = list()
  429. if thisMapInfo:
  430. selected = self.selected['ids']
  431. else:
  432. selected = list()
  433. poList = Vect_new_list()
  434. x1, y1 = bbox[0]
  435. x2, y2 = bbox[1]
  436. poBbox = Vect_new_line_struct()
  437. Vect_append_point(poBbox, x1, y1, 0.0)
  438. Vect_append_point(poBbox, x2, y1, 0.0)
  439. Vect_append_point(poBbox, x2, y2, 0.0)
  440. Vect_append_point(poBbox, x1, y2, 0.0)
  441. Vect_append_point(poBbox, x1, y1, 0.0)
  442. Vect_select_lines_by_polygon(poMapInfo, poBbox,
  443. 0, None, # isles
  444. self._getSelectType(), poList)
  445. flist = poList.contents
  446. nlines = flist.n_values
  447. Debug.msg(1, "DisplayDriver.SelectLinesByBox() num = %d", nlines)
  448. for i in range(nlines):
  449. line = flist.value[i]
  450. if UserSettings.Get(group = 'vdigit', key = 'selectInside',
  451. subkey = 'enabled'):
  452. inside = True
  453. if not self._validLine(line):
  454. return None
  455. Vect_read_line(poMapInfo, self.poPoints, None, line)
  456. points = self.poPoints.contents
  457. for p in range(points.n_points):
  458. if not Vect_point_in_poly(points.x[p], points.y[p],
  459. poBbox):
  460. inside = False
  461. break
  462. if not inside:
  463. continue # skip lines just overlapping bbox
  464. if not self._isSelected(line):
  465. selected.append(line)
  466. else:
  467. selected.remove(line)
  468. Vect_destroy_line_struct(poBbox)
  469. Vect_destroy_list(poList)
  470. return nlines
  471. def SelectLineByPoint(self, point, poMapInfo = None):
  472. """!Select vector feature by given point in given
  473. threshold
  474. Only one vector object can be selected. Bounding boxes of
  475. all segments are stores.
  476. @param point points coordinates (x, y)
  477. @param poMapInfo use external Map_info, None for self.poMapInfo
  478. @return dict {'line' : feature id, 'point' : point on line}
  479. """
  480. thisMapInfo = poMapInfo is None
  481. if not poMapInfo:
  482. poMapInfo = self.poMapInfo
  483. if not poMapInfo:
  484. return { 'line' : -1, 'point': None }
  485. if thisMapInfo:
  486. self._drawSelected = True
  487. # select by ids
  488. self.selected['cats'] = list()
  489. if thisMapInfo:
  490. selected = self.selected['ids']
  491. else:
  492. selected = 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. selected.append(lineNearest)
  501. else:
  502. selected.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. selected.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. selected.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. if layer > 0:
  575. selected.field = layer
  576. self.selected['cats'] = ids
  577. else:
  578. field = -1
  579. self.selected['ids'] = ids
  580. def GetSelectedVertex(self, pos):
  581. """!Get PseudoDC vertex id of selected line
  582. Set bounding box for vertices of line.
  583. @param pos position
  584. @return id of center, left and right vertex
  585. @return 0 no line found
  586. @return -1 on error
  587. """
  588. returnId = list()
  589. # only one object can be selected
  590. if len(self.selected['ids']) != 1 or not self._drawSegments:
  591. return returnId
  592. startId = 1
  593. line = self.selected['ids'][0]
  594. if not self._validLine(line):
  595. return -1
  596. ftype = Vect_read_line(self.poMapInfo, self.poPoints, self.poCats, line)
  597. minDist = 0.0
  598. Gid = -1
  599. # find the closest vertex (x, y)
  600. DCid = 1
  601. points = self.poPoints.contents
  602. for idx in range(points.n_points):
  603. dist = Vect_points_distance(pos[0], pos[1], 0.0,
  604. points.x[idx], points.y[idx], points.z[idx], 0)
  605. if idx == 0:
  606. minDist = dist
  607. Gid = idx
  608. else:
  609. if minDist > dist:
  610. minDist = dist
  611. Gid = idx
  612. vx, vy = self._cell2Pixel(points.x[idx], points.y[idx], points.z[idx])
  613. rect = wx.Rect(vx, vy, 0, 0)
  614. self.dc.SetIdBounds(DCid, rect)
  615. DCid += 2
  616. if minDist > self.GetThreshold():
  617. return returnId
  618. # translate id
  619. DCid = Gid * 2 + 1
  620. # add selected vertex
  621. returnId.append(DCid)
  622. # left vertex
  623. if DCid == startId:
  624. returnId.append(-1)
  625. else:
  626. returnId.append(DCid - 2)
  627. # right vertex
  628. if DCid == (points.n_points - 1) * 2 + startId:
  629. returnId.append(-1)
  630. else:
  631. returnId.append(DCid + 2)
  632. return returnId
  633. def DrawSelected(self, flag):
  634. """!Draw selected features
  635. @param flag True to draw selected features
  636. """
  637. self._drawSelected = bool(flag)
  638. def CloseMap(self):
  639. """!Close vector map
  640. @return 0 on success
  641. @return non-zero on error
  642. """
  643. ret = 0
  644. if self.poMapInfo:
  645. # rebuild topology
  646. Vect_build_partial(self.poMapInfo, GV_BUILD_NONE)
  647. Vect_build(self.poMapInfo)
  648. # close map and store topo/cidx
  649. ret = Vect_close(self.poMapInfo)
  650. del self.mapInfo
  651. self.poMapInfo = self.mapInfo = None
  652. return ret
  653. def OpenMap(self, name, mapset, update = True):
  654. """!Open vector map by the driver
  655. @param name name of vector map to be open
  656. @param mapset name of mapset where the vector map lives
  657. @return map_info
  658. @return None on error
  659. """
  660. Debug.msg("DisplayDriver.OpenMap(): name=%s mapset=%s updated=%d",
  661. name, mapset, update)
  662. if not self.mapInfo:
  663. self.mapInfo = Map_info()
  664. self.poMapInfo = pointer(self.mapInfo)
  665. # open existing map
  666. if update:
  667. ret = Vect_open_update(self.poMapInfo, name, mapset)
  668. else:
  669. ret = Vect_open_old(self.poMapInfo, name, mapset)
  670. self.is3D = Vect_is_3d(self.poMapInfo)
  671. if ret == -1: # error
  672. del self.mapInfo
  673. self.poMapInfo = self.mapInfo = None
  674. elif ret < 2:
  675. dlg = wx.MessageDialog(parent = self.window,
  676. message = _("Topology for vector map <%s> is not available. "
  677. "Topology is required by digitizer. Do you want to "
  678. "rebuild topology (takes some time) and open the vector map "
  679. "for editing?") % name,
  680. caption=_("Topology missing"),
  681. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  682. ret = dlg.ShowModal()
  683. if ret != wx.ID_YES:
  684. del self.mapInfo
  685. self.poMapInfo = self.mapInfo = None
  686. else:
  687. Vect_build(self.poMapInfo)
  688. return self.poMapInfo
  689. def GetMapBoundingBox(self):
  690. """!Get bounding box of (opened) vector map layer
  691. @return (w,s,b,e,n,t)
  692. """
  693. if not self.poMapInfo:
  694. return None
  695. bbox = bound_box()
  696. Vect_get_map_box(self.poMapInfo, byref(bbox))
  697. return bbox.W, bbox.S, bbox.B, \
  698. bbox.E, bbox.N, bbox.T
  699. def UpdateSettings(self, alpha = 255):
  700. """!Update display driver settings
  701. @todo map units
  702. @alpha color value for aplha channel
  703. """
  704. color = dict()
  705. for key in self.settings.keys():
  706. if key == 'lineWidth':
  707. self.settings[key] = int(UserSettings.Get(group = 'vdigit', key = 'lineWidth',
  708. subkey = 'value'))
  709. continue
  710. color = wx.Color(UserSettings.Get(group = 'vdigit', key = 'symbol',
  711. subkey = [key, 'color'])[0],
  712. UserSettings.Get(group = 'vdigit', key = 'symbol',
  713. subkey = [key, 'color'])[1],
  714. UserSettings.Get(group = 'vdigit', key = 'symbol',
  715. subkey = [key, 'color'])[2],
  716. alpha)
  717. if key == 'highlight':
  718. self.settings[key] = color
  719. continue
  720. if key == 'highlightDupl':
  721. self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'checkForDupl',
  722. subkey = 'enabled'))
  723. else:
  724. self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'symbol',
  725. subkey = [key, 'enabled']))
  726. self.settings[key]['color'] = color
  727. def UpdateRegion(self):
  728. """!Update geographical region used by display driver
  729. """
  730. self.region = self.mapObj.GetCurrentRegion()
  731. def GetThreshold(self, type = 'snapping', value = None, units = None):
  732. """!Return threshold value in map units
  733. @param type snapping mode (node, vertex)
  734. @param value threshold to be set up
  735. @param units units (map, screen)
  736. @return threshold value
  737. """
  738. if value is None:
  739. value = UserSettings.Get(group = 'vdigit', key = type, subkey = 'value')
  740. if units is None:
  741. units = UserSettings.Get(group = 'vdigit', key = type, subkey = 'units')
  742. if value < 0:
  743. value = (self.region['nsres'] + self.region['ewres']) / 2.0
  744. if units == "screen pixels":
  745. # pixel -> cell
  746. res = max(self.region['nsres'], self.region['ewres'])
  747. return value * res
  748. return value
  749. def GetDuplicates(self):
  750. """!Return ids of (selected) duplicated vector features
  751. """
  752. if not self.poMapInfo:
  753. return
  754. ids = dict()
  755. APoints = Vect_new_line_struct()
  756. BPoints = Vect_new_line_struct()
  757. self.selected['idsDupl'] = list()
  758. for i in range(len(self.selected['ids'])):
  759. line1 = self.selected['ids'][i]
  760. if self._isDuplicated(line1):
  761. continue
  762. Vect_read_line(self.poMapInfo, APoints, None, line1)
  763. for line2 in self.selected['ids']:
  764. if line1 == line2 or self._isDuplicated(line2):
  765. continue
  766. Vect_read_line(self.poMapInfo, BPoints, None, line2)
  767. if Vect_line_check_duplicate(APoints, BPoints, WITHOUT_Z):
  768. if i not in ids:
  769. ids[i] = list()
  770. ids[i].append((line1, self._getCatString(line1)))
  771. self.selected['idsDupl'].append(line1)
  772. ids[i].append((line2, self._getCatString(line2)))
  773. self.selected['idsDupl'].append(line2)
  774. Vect_destroy_line_struct(APoints)
  775. Vect_destroy_line_struct(BPoints)
  776. return ids
  777. def _getCatString(self, line):
  778. Vect_read_line(self.poMapInfo, None, self.poCats, line)
  779. cats = self.poCats.contents
  780. catsDict = dict()
  781. for i in range(cats.n_cats):
  782. layer = cats.field[i]
  783. if layer not in catsDict:
  784. catsDict[layer] = list()
  785. catsDict[layer].append(cats.cat[i])
  786. catsStr = ''
  787. for l, c in catsDict.iteritems():
  788. catsStr = '%d: (%s)' % (l, ','.join(map(str, c)))
  789. return catsStr
  790. def UnSelect(self, lines):
  791. """!Unselect vector features
  792. @param lines list of feature id(s)
  793. """
  794. checkForDupl = False
  795. for line in lines:
  796. if self._isSelected(line):
  797. self.selected['ids'].remove(line)
  798. if self.settings['highlightDupl']['enabled'] and self._isDuplicated(line):
  799. checkForDupl = True
  800. if checkForDupl:
  801. self.GetDuplicates()
  802. return len(self.selected['ids'])