wxvdriver.py 32 KB

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