wxdisplay.py 33 KB

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