wxdisplay.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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. Vect_read_line(self.poMapInfo, None, self.poCats, line)
  347. cats = self.poCats.contents
  348. for i in range(cats.n_cats):
  349. if cats.field[i] == self.selected['field'] and \
  350. cats.cat[i] in self.selected['cats']:
  351. # remember id
  352. # -> after drawing all features selected.cats is reseted */
  353. self.selected['ids'].append(line)
  354. return True
  355. return False
  356. def _isDuplicated(self, line):
  357. """!Check for already marked duplicates
  358. @param line feature id
  359. @return True line already marked as duplicated
  360. @return False not duplicated
  361. """
  362. return line in self.selected['idsDupl']
  363. def _getRegionBox(self):
  364. """!Get bound_box() from current region
  365. @return bound_box
  366. """
  367. box = bound_box()
  368. box.N = self.region['n']
  369. box.S = self.region['s']
  370. box.E = self.region['e']
  371. box.W = self.region['w']
  372. box.T = PORT_DOUBLE_MAX
  373. box.B = -PORT_DOUBLE_MAX
  374. return box
  375. def DrawMap(self, force = False):
  376. """!Draw content of the vector map to the device
  377. @param force force drawing
  378. @return number of drawn features
  379. @return -1 on error
  380. """
  381. Debug.msg(1, "DisplayDriver.DrawMap(): force=%d", force)
  382. if not self.poMapInfo or not self.dc or not self.dcTmp:
  383. return -1
  384. try:
  385. rlist = Vedit_render_map(self.poMapInfo, byref(self._getRegionBox()), self._getDrawFlag(),
  386. self.region['center_easting'], self.region['center_northing'],
  387. self.mapObj.width, self.mapObj.height,
  388. max(self.region['nsres'], self.region['ewres'])).contents
  389. except SystemExit:
  390. pass
  391. self._resetTopology()
  392. self.dc.BeginDrawing()
  393. self.dcTmp.BeginDrawing()
  394. # draw objects
  395. for i in range(rlist.nitems):
  396. robj = rlist.item[i].contents
  397. self._drawObject(robj)
  398. self.dc.EndDrawing()
  399. self.dcTmp.EndDrawing()
  400. # reset list of selected features by cat
  401. # list of ids - see IsSelected()
  402. self.selected['field'] = -1
  403. self.selected['cats'] = list()
  404. def _getSelectType(self):
  405. """!Get type(s) to be selected
  406. Used by SelectLinesByBox() and SelectLineByPoint()
  407. """
  408. ftype = 0
  409. for feature in (('point', GV_POINT),
  410. ('line', GV_LINE),
  411. ('centroid', GV_CENTROID),
  412. ('boundary', GV_BOUNDARY)):
  413. if UserSettings.Get(group = 'vdigit', key = 'selectType',
  414. subkey = [feature[0], 'enabled']):
  415. ftype |= feature[1]
  416. return ftype
  417. def _validLine(self, line):
  418. """!Check if feature id is valid
  419. @param line feature id
  420. @return True valid feature id
  421. @return False invalid
  422. """
  423. if line > 0 and line <= Vect_get_num_lines(self.poMapInfo):
  424. return True
  425. return False
  426. def SelectLinesByBox(self, bbox, drawSeg = False, poMapInfo = None):
  427. """!Select vector objects by given bounding box
  428. If line id is already in the list of selected lines, then it will
  429. be excluded from this list.
  430. @param bbox bounding box definition
  431. @param drawSeg True to draw segments of line
  432. @param poMapInfo use external Map_info, None for self.poMapInfo
  433. @return number of selected features
  434. @return None on error
  435. """
  436. thisMapInfo = poMapInfo is None
  437. if not poMapInfo:
  438. poMapInfo = self.poMapInfo
  439. if not poMapInfo:
  440. return None
  441. if thisMapInfo:
  442. self._drawSegments = drawSeg
  443. self._drawSelected = True
  444. # select by ids
  445. self.selected['cats'] = list()
  446. poList = Vect_new_list()
  447. x1, y1 = bbox[0]
  448. x2, y2 = bbox[1]
  449. poBbox = Vect_new_line_struct()
  450. Vect_append_point(poBbox, x1, y1, 0.0)
  451. Vect_append_point(poBbox, x2, y1, 0.0)
  452. Vect_append_point(poBbox, x2, y2, 0.0)
  453. Vect_append_point(poBbox, x1, y2, 0.0)
  454. Vect_append_point(poBbox, x1, y1, 0.0)
  455. Vect_select_lines_by_polygon(poMapInfo, poBbox,
  456. 0, None, # isles
  457. self._getSelectType(), poList)
  458. flist = poList.contents
  459. nlines = flist.n_values
  460. Debug.msg(1, "DisplayDriver.SelectLinesByBox() num = %d", nlines)
  461. for i in range(nlines):
  462. line = flist.value[i]
  463. if UserSettings.Get(group = 'vdigit', key = 'selectInside',
  464. subkey = 'enabled'):
  465. inside = True
  466. if not self._validLine(line):
  467. return None
  468. Vect_read_line(poMapInfo, self.poPoints, None, line)
  469. points = self.poPoints.contents
  470. for p in range(points.n_points):
  471. if not Vect_point_in_poly(points.x[p], points.y[p],
  472. poBbox):
  473. inside = False
  474. break
  475. if not inside:
  476. continue # skip lines just overlapping bbox
  477. if not self._isSelected(line):
  478. self.selected['ids'].append(line)
  479. else:
  480. self.selected['ids'].remove(line)
  481. Vect_destroy_line_struct(poBbox)
  482. Vect_destroy_list(poList)
  483. return nlines
  484. def SelectLineByPoint(self, point, poMapInfo = None):
  485. """!Select vector feature by given point in given
  486. threshold
  487. Only one vector object can be selected. Bounding boxes of
  488. all segments are stores.
  489. @param point points coordinates (x, y)
  490. @param poMapInfo use external Map_info, None for self.poMapInfo
  491. @return dict {'line' : feature id, 'point' : point on line}
  492. """
  493. thisMapInfo = poMapInfo is None
  494. if not poMapInfo:
  495. poMapInfo = self.poMapInfo
  496. if not poMapInfo:
  497. return { 'line' : -1, 'point': None }
  498. if thisMapInfo:
  499. self._drawSelected = True
  500. # select by ids
  501. self.selected['cats'] = list()
  502. poFound = Vect_new_list()
  503. lineNearest = Vect_find_line_list(poMapInfo, point[0], point[1], 0,
  504. self._getSelectType(), self.GetThreshold(), self.is3D,
  505. None, poFound)
  506. Debug.msg(1, "DisplayDriver.SelectLineByPoint() found = %d", lineNearest)
  507. if lineNearest > 0:
  508. if not self._isSelected(lineNearest):
  509. self.selected['ids'].append(lineNearest)
  510. else:
  511. self.selected['ids'].remove(lineNearest)
  512. px = c_double()
  513. py = c_double()
  514. pz = c_double()
  515. if not self._validLine(lineNearest):
  516. return { 'line' : -1, 'point': None }
  517. ftype = Vect_read_line(poMapInfo, self.poPoints, self.poCats, lineNearest)
  518. Vect_line_distance (self.poPoints, point[0], point[1], 0.0, self.is3D,
  519. byref(px), byref(py), byref(pz),
  520. None, None, None)
  521. # check for duplicates
  522. if self.settings['highlightDupl']['enabled']:
  523. found = poFound.contents
  524. for i in range(found.n_values):
  525. line = found.value[i]
  526. if line != lineNearest:
  527. self.selected['ids'].append(line)
  528. self.GetDuplicates()
  529. for i in range(found.n_values):
  530. line = found.value[i]
  531. if line != lineNearest and not self._isDuplicated(line):
  532. self.selected['ids'].remove(line)
  533. Vect_destroy_list(poFound)
  534. if thisMapInfo:
  535. # drawing segments can be very expensive
  536. # only one features selected
  537. self._drawSegments = True
  538. return { 'line' : lineNearest,
  539. 'point' : (px.value, py.value, pz.value) }
  540. def _listToIList(self, plist):
  541. """!Generate from list struct_ilist
  542. """
  543. ilist = Vect_new_list()
  544. for val in plist:
  545. Vect_list_append(ilist, val)
  546. return ilist
  547. def GetSelectedIList(self, ilist = None):
  548. """!Get list of selected objects as struct_ilist
  549. Returned IList must be freed by Vect_destroy_list().
  550. @return struct_ilist
  551. """
  552. if ilist:
  553. return self._listToIList(ilist)
  554. return self._listToIList(self.selected['ids'])
  555. def GetSelected(self, grassId = True):
  556. """!Get ids of selected objects
  557. @param grassId True for feature id, False for PseudoDC id
  558. @return list of ids of selected vector objects
  559. """
  560. if grassId:
  561. return self.selected['ids']
  562. dc_ids = list()
  563. if not self._drawSegments:
  564. dc_ids.append(1)
  565. elif len(self.selected['ids']) > 0:
  566. # only first selected feature
  567. Vect_read_line(self.poMapInfo, self.poPoints, None,
  568. self.selected['ids'][0])
  569. points = self.poPoints.contents
  570. # node - segment - vertex - segment - node
  571. for i in range(1, 2 * points.n_points):
  572. dc_ids.append(i)
  573. return dc_ids
  574. def SetSelected(self, ids, layer = -1):
  575. """!Set selected vector objects
  576. @param list of ids (None to unselect features)
  577. @param layer layer number for features selected based on category number
  578. """
  579. if ids:
  580. self._drawSelected = True
  581. else:
  582. self._drawSelected = False
  583. self.selected['field'] = layer
  584. if layer > 0:
  585. self.selected['cats'] = ids
  586. self.selected['ids'] = list()
  587. ### cidx is not up-to-date
  588. # Vect_cidx_find_all(self.poMapInfo, layer, GV_POINTS | GV_LINES, lid, ilist)
  589. nlines = Vect_get_num_lines(self.poMapInfo)
  590. for line in range(1, nlines + 1):
  591. if not Vect_line_alive(self.poMapInfo, line):
  592. continue
  593. ltype = Vect_read_line (self.poMapInfo, None, self.poCats, line)
  594. if not (ltype & (GV_POINTS | GV_LINES)):
  595. continue
  596. found = False
  597. cats = self.poCats.contents
  598. for i in range(0, cats.n_cats):
  599. for cat in self.selected['cats']:
  600. if cats.cat[i] == cat:
  601. found = True
  602. break
  603. if found:
  604. self.selected['ids'].append(line)
  605. else:
  606. self.selected['ids'] = ids
  607. self.selected['cats'] = []
  608. def GetSelectedVertex(self, pos):
  609. """!Get PseudoDC vertex id of selected line
  610. Set bounding box for vertices of line.
  611. @param pos position
  612. @return id of center, left and right vertex
  613. @return 0 no line found
  614. @return -1 on error
  615. """
  616. returnId = list()
  617. # only one object can be selected
  618. if len(self.selected['ids']) != 1 or not self._drawSegments:
  619. return returnId
  620. startId = 1
  621. line = self.selected['ids'][0]
  622. if not self._validLine(line):
  623. return -1
  624. ftype = Vect_read_line(self.poMapInfo, self.poPoints, self.poCats, line)
  625. minDist = 0.0
  626. Gid = -1
  627. # find the closest vertex (x, y)
  628. DCid = 1
  629. points = self.poPoints.contents
  630. for idx in range(points.n_points):
  631. dist = Vect_points_distance(pos[0], pos[1], 0.0,
  632. points.x[idx], points.y[idx], points.z[idx], 0)
  633. if idx == 0:
  634. minDist = dist
  635. Gid = idx
  636. else:
  637. if minDist > dist:
  638. minDist = dist
  639. Gid = idx
  640. vx, vy = self._cell2Pixel(points.x[idx], points.y[idx], points.z[idx])
  641. rect = wx.Rect(vx, vy, 0, 0)
  642. self.dc.SetIdBounds(DCid, rect)
  643. DCid += 2
  644. if minDist > self.GetThreshold():
  645. return returnId
  646. # translate id
  647. DCid = Gid * 2 + 1
  648. # add selected vertex
  649. returnId.append(DCid)
  650. # left vertex
  651. if DCid == startId:
  652. returnId.append(-1)
  653. else:
  654. returnId.append(DCid - 2)
  655. # right vertex
  656. if DCid == (points.n_points - 1) * 2 + startId:
  657. returnId.append(-1)
  658. else:
  659. returnId.append(DCid + 2)
  660. return returnId
  661. def GetRegionSelected(self):
  662. """!Get minimal region extent of selected features
  663. @return n,s,w,e
  664. """
  665. regionBox = bound_box()
  666. lineBox = bound_box()
  667. setRegion = True
  668. nareas = Vect_get_num_areas(self.poMapInfo)
  669. for line in self.selected['ids']:
  670. area = Vect_get_centroid_area(self.poMapInfo, line)
  671. if area > 0 and area <= nareas:
  672. if not Vect_get_area_box(self.poMapInfo, area, byref(lineBox)):
  673. continue
  674. else:
  675. if not Vect_get_line_box(self.poMapInfo, line, byref(lineBox)):
  676. continue
  677. if setRegion:
  678. Vect_box_copy(byref(regionBox), byref(lineBox))
  679. setRegion = False
  680. else:
  681. Vect_box_extend(byref(regionBox), byref(lineBox))
  682. return regionBox.N, regionBox.S, regionBox.W, regionBox.E
  683. def DrawSelected(self, flag):
  684. """!Draw selected features
  685. @param flag True to draw selected features
  686. """
  687. self._drawSelected = bool(flag)
  688. def CloseMap(self):
  689. """!Close vector map
  690. @return 0 on success
  691. @return non-zero on error
  692. """
  693. ret = 0
  694. if self.poMapInfo:
  695. # rebuild topology
  696. Vect_build_partial(self.poMapInfo, GV_BUILD_NONE)
  697. Vect_build(self.poMapInfo)
  698. # close map and store topo/cidx
  699. ret = Vect_close(self.poMapInfo)
  700. del self.mapInfo
  701. self.poMapInfo = self.mapInfo = None
  702. return ret
  703. def OpenMap(self, name, mapset, update = True):
  704. """!Open vector map by the driver
  705. @param name name of vector map to be open
  706. @param mapset name of mapset where the vector map lives
  707. @return map_info
  708. @return None on error
  709. """
  710. Debug.msg("DisplayDriver.OpenMap(): name=%s mapset=%s updated=%d",
  711. name, mapset, update)
  712. if not self.mapInfo:
  713. self.mapInfo = Map_info()
  714. self.poMapInfo = pointer(self.mapInfo)
  715. # open existing map
  716. if update:
  717. ret = Vect_open_update(self.poMapInfo, name, mapset)
  718. else:
  719. ret = Vect_open_old(self.poMapInfo, name, mapset)
  720. self.is3D = Vect_is_3d(self.poMapInfo)
  721. if ret == -1: # error
  722. del self.mapInfo
  723. self.poMapInfo = self.mapInfo = None
  724. elif ret < 2:
  725. dlg = wx.MessageDialog(parent = self.window,
  726. message = _("Topology for vector map <%s> is not available. "
  727. "Topology is required by digitizer. Do you want to "
  728. "rebuild topology (takes some time) and open the vector map "
  729. "for editing?") % name,
  730. caption=_("Topology missing"),
  731. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  732. ret = dlg.ShowModal()
  733. if ret != wx.ID_YES:
  734. del self.mapInfo
  735. self.poMapInfo = self.mapInfo = None
  736. else:
  737. Vect_build(self.poMapInfo)
  738. return self.poMapInfo
  739. def GetMapBoundingBox(self):
  740. """!Get bounding box of (opened) vector map layer
  741. @return (w,s,b,e,n,t)
  742. """
  743. if not self.poMapInfo:
  744. return None
  745. bbox = bound_box()
  746. Vect_get_map_box(self.poMapInfo, byref(bbox))
  747. return bbox.W, bbox.S, bbox.B, \
  748. bbox.E, bbox.N, bbox.T
  749. def UpdateSettings(self, alpha = 255):
  750. """!Update display driver settings
  751. @todo map units
  752. @alpha color value for aplha channel
  753. """
  754. color = dict()
  755. for key in self.settings.keys():
  756. if key == 'lineWidth':
  757. self.settings[key] = int(UserSettings.Get(group = 'vdigit', key = 'lineWidth',
  758. subkey = 'value'))
  759. continue
  760. color = wx.Color(UserSettings.Get(group = 'vdigit', key = 'symbol',
  761. subkey = [key, 'color'])[0],
  762. UserSettings.Get(group = 'vdigit', key = 'symbol',
  763. subkey = [key, 'color'])[1],
  764. UserSettings.Get(group = 'vdigit', key = 'symbol',
  765. subkey = [key, 'color'])[2],
  766. alpha)
  767. if key == 'highlight':
  768. self.settings[key] = color
  769. continue
  770. if key == 'highlightDupl':
  771. self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'checkForDupl',
  772. subkey = 'enabled'))
  773. else:
  774. self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'symbol',
  775. subkey = [key, 'enabled']))
  776. self.settings[key]['color'] = color
  777. def UpdateRegion(self):
  778. """!Update geographical region used by display driver
  779. """
  780. self.region = self.mapObj.GetCurrentRegion()
  781. def GetThreshold(self, type = 'snapping', value = None, units = None):
  782. """!Return threshold value in map units
  783. @param type snapping mode (node, vertex)
  784. @param value threshold to be set up
  785. @param units units (map, screen)
  786. @return threshold value
  787. """
  788. if value is None:
  789. value = UserSettings.Get(group = 'vdigit', key = type, subkey = 'value')
  790. if units is None:
  791. units = UserSettings.Get(group = 'vdigit', key = type, subkey = 'units')
  792. if value < 0:
  793. value = (self.region['nsres'] + self.region['ewres']) / 2.0
  794. if units == "screen pixels":
  795. # pixel -> cell
  796. res = max(self.region['nsres'], self.region['ewres'])
  797. return value * res
  798. return value
  799. def GetDuplicates(self):
  800. """!Return ids of (selected) duplicated vector features
  801. """
  802. if not self.poMapInfo:
  803. return
  804. ids = dict()
  805. APoints = Vect_new_line_struct()
  806. BPoints = Vect_new_line_struct()
  807. self.selected['idsDupl'] = list()
  808. for i in range(len(self.selected['ids'])):
  809. line1 = self.selected['ids'][i]
  810. if self._isDuplicated(line1):
  811. continue
  812. Vect_read_line(self.poMapInfo, APoints, None, line1)
  813. for line2 in self.selected['ids']:
  814. if line1 == line2 or self._isDuplicated(line2):
  815. continue
  816. Vect_read_line(self.poMapInfo, BPoints, None, line2)
  817. if Vect_line_check_duplicate(APoints, BPoints, WITHOUT_Z):
  818. if i not in ids:
  819. ids[i] = list()
  820. ids[i].append((line1, self._getCatString(line1)))
  821. self.selected['idsDupl'].append(line1)
  822. ids[i].append((line2, self._getCatString(line2)))
  823. self.selected['idsDupl'].append(line2)
  824. Vect_destroy_line_struct(APoints)
  825. Vect_destroy_line_struct(BPoints)
  826. return ids
  827. def _getCatString(self, line):
  828. Vect_read_line(self.poMapInfo, None, self.poCats, line)
  829. cats = self.poCats.contents
  830. catsDict = dict()
  831. for i in range(cats.n_cats):
  832. layer = cats.field[i]
  833. if layer not in catsDict:
  834. catsDict[layer] = list()
  835. catsDict[layer].append(cats.cat[i])
  836. catsStr = ''
  837. for l, c in catsDict.iteritems():
  838. catsStr = '%d: (%s)' % (l, ','.join(map(str, c)))
  839. return catsStr
  840. def UnSelect(self, lines):
  841. """!Unselect vector features
  842. @param lines list of feature id(s)
  843. """
  844. checkForDupl = False
  845. for line in lines:
  846. if self._isSelected(line):
  847. self.selected['ids'].remove(line)
  848. if self.settings['highlightDupl']['enabled'] and self._isDuplicated(line):
  849. checkForDupl = True
  850. if checkForDupl:
  851. self.GetDuplicates()
  852. return len(self.selected['ids'])