wxdisplay.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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(): line=%d type=%d npoints=%d", robj.fid, robj.type, robj.npoints)
  192. brush = None
  193. if self._isSelected(robj.fid):
  194. pdc = self.dcTmp
  195. if robj.type == TYPE_AREA:
  196. return 1
  197. else:
  198. if self.settings['highlightDupl']['enabled'] and self._isDuplicated(robj.fid):
  199. pen = wx.Pen(self.settings['highlightDupl']['color'], self.settings['lineWidth'], wx.SOLID)
  200. else:
  201. pen = wx.Pen(self.settings['highlight'], self.settings['lineWidth'], wx.SOLID)
  202. dcId = 1
  203. self.topology['highlight'] += 1
  204. if not self._drawSelected:
  205. return
  206. else:
  207. pdc = self.dc
  208. pen, brush = self._definePen(robj.type)
  209. dcId = 0
  210. pdc.SetPen(pen)
  211. if brush:
  212. pdc.SetBrush(brush)
  213. if robj.type & (TYPE_POINT | TYPE_CENTROIDIN | TYPE_CENTROIDOUT | TYPE_CENTROIDDUP |
  214. TYPE_NODEONE | TYPE_NODETWO | TYPE_VERTEX): # -> point
  215. if dcId > 0:
  216. if robj.type == TYPE_VERTEX:
  217. dcId = 3 # first vertex
  218. elif robj.type & (TYPE_NODEONE | TYPE_NODETWO):
  219. if self.firstNode:
  220. dcId = 1
  221. self.firstNode = False
  222. else:
  223. dcId = self.lastNodeId
  224. for i in range(robj.npoints):
  225. p = robj.point[i]
  226. if dcId > 0:
  227. pdc.SetId(dcId)
  228. dcId += 2
  229. self._drawCross(pdc, p)
  230. else:
  231. if dcId > 0 and self._drawSegments:
  232. self.fisrtNode = True
  233. self.lastNodeId = robj.npoints * 2 - 1
  234. dcId = 2 # first segment
  235. i = 0
  236. while i < robj.npoints - 1:
  237. point_beg = wx.Point(robj.point[i].x, robj.point[i].y)
  238. point_end = wx.Point(robj.point[i+1].x, robj.point[i+1].y)
  239. pdc.SetId(dcId) # set unique id & set bbox for each segment
  240. pdc.SetPen(pen)
  241. pdc.SetIdBounds(dcId - 1, wx.Rect(point_beg.x, point_beg.y, 0, 0))
  242. pdc.SetIdBounds(dcId, wx.RectPP(point_beg, point_end))
  243. pdc.DrawLine(point_beg.x, point_beg.y,
  244. point_end.x, point_end.y)
  245. i += 1
  246. dcId += 2
  247. pdc.SetIdBounds(dcId - 1, wx.Rect(robj.point[robj.npoints - 1].x,
  248. robj.point[robj.npoints - 1].y,
  249. 0, 0))
  250. else:
  251. points = list()
  252. for i in range(robj.npoints):
  253. p = robj.point[i]
  254. points.append(wx.Point(p.x, p.y))
  255. if robj.type == TYPE_AREA:
  256. pdc.DrawPolygon(points)
  257. else:
  258. pdc.DrawLines(points)
  259. def _definePen(self, rtype):
  260. """!Define pen/brush based on rendered object)
  261. Updates also self.topology dict
  262. @return pen, brush
  263. """
  264. if rtype == TYPE_POINT:
  265. key = 'point'
  266. elif rtype == TYPE_LINE:
  267. key = 'line'
  268. elif rtype == TYPE_BOUNDARYNO:
  269. key = 'boundaryNo'
  270. elif rtype == TYPE_BOUNDARYTWO:
  271. key = 'boundaryTwo'
  272. elif rtype == TYPE_BOUNDARYONE:
  273. key = 'boundaryOne'
  274. elif rtype == TYPE_CENTROIDIN:
  275. key = 'centroidIn'
  276. elif rtype == TYPE_CENTROIDOUT:
  277. key = 'centroidOut'
  278. elif rtype == TYPE_CENTROIDDUP:
  279. key = 'centroidDup'
  280. elif rtype == TYPE_NODEONE:
  281. key = 'nodeOne'
  282. elif rtype == TYPE_NODETWO:
  283. key = 'nodeTwo'
  284. elif rtype == TYPE_VERTEX:
  285. key = 'vertex'
  286. elif rtype == TYPE_AREA:
  287. key = 'area'
  288. elif rtype == TYPE_ISLE:
  289. key = 'isle'
  290. elif rtype == TYPE_DIRECTION:
  291. key = 'direction'
  292. if key not in ('direction', 'area', 'isle'):
  293. self.topology[key] += 1
  294. if key in ('area', 'isle'):
  295. pen = wx.TRANSPARENT_PEN
  296. if key == 'area':
  297. brush = wx.Brush(self.settings[key]['color'], wx.SOLID)
  298. else:
  299. brush = wx.TRANSPARENT_BRUSH
  300. else:
  301. pen = wx.Pen(self.settings[key]['color'], self.settings['lineWidth'], wx.SOLID)
  302. brush = None
  303. return pen, brush
  304. def _getDrawFlag(self):
  305. """!Get draw flag from the settings
  306. See vedit.h for list of draw flags.
  307. @return draw flag (int)
  308. """
  309. ret = 0
  310. if self.settings['point']['enabled']:
  311. ret |= DRAW_POINT
  312. if self.settings['line']['enabled']:
  313. ret |= DRAW_LINE
  314. if self.settings['boundaryNo']['enabled']:
  315. ret |= DRAW_BOUNDARYNO
  316. if self.settings['boundaryTwo']['enabled']:
  317. ret |= DRAW_BOUNDARYTWO
  318. if self.settings['boundaryOne']['enabled']:
  319. ret |= DRAW_BOUNDARYONE
  320. if self.settings['centroidIn']['enabled']:
  321. ret |= DRAW_CENTROIDIN
  322. if self.settings['centroidOut']['enabled']:
  323. ret |= DRAW_CENTROIDOUT
  324. if self.settings['centroidDup']['enabled']:
  325. ret |= DRAW_CENTROIDDUP
  326. if self.settings['nodeOne']['enabled']:
  327. ret |= DRAW_NODEONE
  328. if self.settings['nodeTwo']['enabled']:
  329. ret |= DRAW_NODETWO
  330. if self.settings['vertex']['enabled']:
  331. ret |= DRAW_VERTEX
  332. if self.settings['area']['enabled']:
  333. ret |= DRAW_AREA
  334. if self.settings['direction']['enabled']:
  335. ret |= DRAW_DIRECTION
  336. return ret
  337. def _isSelected(self, line, force = False):
  338. """!Check if vector object selected?
  339. @param line feature id
  340. @return True if vector object is selected
  341. @return False if vector object is not selected
  342. """
  343. if line in self.selected['ids']:
  344. return True
  345. return False
  346. def _isDuplicated(self, line):
  347. """!Check for already marked duplicates
  348. @param line feature id
  349. @return True line already marked as duplicated
  350. @return False not duplicated
  351. """
  352. return line in self.selected['idsDupl']
  353. def _getRegionBox(self):
  354. """!Get bound_box() from current region
  355. @return bound_box
  356. """
  357. box = bound_box()
  358. box.N = self.region['n']
  359. box.S = self.region['s']
  360. box.E = self.region['e']
  361. box.W = self.region['w']
  362. box.T = PORT_DOUBLE_MAX
  363. box.B = -PORT_DOUBLE_MAX
  364. return box
  365. def DrawMap(self, force = False):
  366. """!Draw content of the vector map to the device
  367. @param force force drawing
  368. @return number of drawn features
  369. @return -1 on error
  370. """
  371. Debug.msg(1, "DisplayDriver.DrawMap(): force=%d", force)
  372. if not self.poMapInfo or not self.dc or not self.dcTmp:
  373. return -1
  374. rlist = Vedit_render_map(self.poMapInfo, byref(self._getRegionBox()), self._getDrawFlag(),
  375. self.region['center_easting'], self.region['center_northing'],
  376. self.mapObj.width, self.mapObj.height,
  377. max(self.region['nsres'], self.region['ewres'])).contents
  378. self._resetTopology()
  379. self.dc.BeginDrawing()
  380. self.dcTmp.BeginDrawing()
  381. # draw objects
  382. for i in range(rlist.nitems):
  383. robj = rlist.item[i].contents
  384. self._drawObject(robj)
  385. self.dc.EndDrawing()
  386. self.dcTmp.EndDrawing()
  387. # reset list of selected features by cat
  388. # list of ids - see IsSelected()
  389. self.selected['field'] = -1
  390. self.selected['cats'] = list()
  391. def _getSelectType(self):
  392. """!Get type(s) to be selected
  393. Used by SelectLinesByBox() and SelectLineByPoint()
  394. """
  395. ftype = 0
  396. for feature in (('point', GV_POINT),
  397. ('line', GV_LINE),
  398. ('centroid', GV_CENTROID),
  399. ('boundary', GV_BOUNDARY)):
  400. if UserSettings.Get(group = 'vdigit', key = 'selectType',
  401. subkey = [feature[0], 'enabled']):
  402. ftype |= feature[1]
  403. return ftype
  404. def _validLine(self, line):
  405. """!Check if feature id is valid
  406. @param line feature id
  407. @return True valid feature id
  408. @return False invalid
  409. """
  410. if line > 0 and line <= Vect_get_num_lines(self.poMapInfo):
  411. return True
  412. return False
  413. def SelectLinesByBox(self, bbox, drawSeg = False, poMapInfo = None):
  414. """!Select vector objects by given bounding box
  415. If line id is already in the list of selected lines, then it will
  416. be excluded from this list.
  417. @param bbox bounding box definition
  418. @param drawSeg True to draw segments of line
  419. @param poMapInfo use external Map_info, None for self.poMapInfo
  420. @return number of selected features
  421. @return None on error
  422. """
  423. thisMapInfo = poMapInfo is None
  424. if not poMapInfo:
  425. poMapInfo = self.poMapInfo
  426. if not poMapInfo:
  427. return None
  428. if thisMapInfo:
  429. self._drawSegments = drawSeg
  430. self._drawSelected = True
  431. # select by ids
  432. self.selected['cats'] = list()
  433. poList = Vect_new_list()
  434. x1, y1 = bbox[0]
  435. x2, y2 = bbox[1]
  436. poBbox = Vect_new_line_struct()
  437. Vect_append_point(poBbox, x1, y1, 0.0)
  438. Vect_append_point(poBbox, x2, y1, 0.0)
  439. Vect_append_point(poBbox, x2, y2, 0.0)
  440. Vect_append_point(poBbox, x1, y2, 0.0)
  441. Vect_append_point(poBbox, x1, y1, 0.0)
  442. Vect_select_lines_by_polygon(poMapInfo, poBbox,
  443. 0, None, # isles
  444. self._getSelectType(), poList)
  445. flist = poList.contents
  446. nlines = flist.n_values
  447. Debug.msg(1, "DisplayDriver.SelectLinesByBox() num = %d", nlines)
  448. for i in range(nlines):
  449. line = flist.value[i]
  450. if UserSettings.Get(group = 'vdigit', key = 'selectInside',
  451. subkey = 'enabled'):
  452. inside = True
  453. if not self._validLine(line):
  454. return None
  455. Vect_read_line(poMapInfo, self.poPoints, None, line)
  456. points = self.poPoints.contents
  457. for p in range(points.n_points):
  458. if not Vect_point_in_poly(points.x[p], points.y[p],
  459. poBbox):
  460. inside = False
  461. break
  462. if not inside:
  463. continue # skip lines just overlapping bbox
  464. if not self._isSelected(line):
  465. self.selected['ids'].append(line)
  466. else:
  467. self.selected['ids'].remove(line)
  468. Vect_destroy_line_struct(poBbox)
  469. Vect_destroy_list(poList)
  470. return nlines
  471. def SelectLineByPoint(self, point, poMapInfo = None):
  472. """!Select vector feature by given point in given
  473. threshold
  474. Only one vector object can be selected. Bounding boxes of
  475. all segments are stores.
  476. @param point points coordinates (x, y)
  477. @param poMapInfo use external Map_info, None for self.poMapInfo
  478. @return dict {'line' : feature id, 'point' : point on line}
  479. """
  480. thisMapInfo = poMapInfo is None
  481. if not poMapInfo:
  482. poMapInfo = self.poMapInfo
  483. if not poMapInfo:
  484. return { 'line' : -1, 'point': None }
  485. if thisMapInfo:
  486. self._drawSelected = True
  487. # select by ids
  488. self.selected['cats'] = list()
  489. poFound = Vect_new_list()
  490. lineNearest = Vect_find_line_list(poMapInfo, point[0], point[1], 0,
  491. self._getSelectType(), self.GetThreshold(), self.is3D,
  492. None, poFound)
  493. Debug.msg(1, "DisplayDriver.SelectLineByPoint() found = %d", lineNearest)
  494. if lineNearest > 0:
  495. if not self._isSelected(lineNearest):
  496. self.selected['ids'].append(lineNearest)
  497. else:
  498. self.selected['ids'].remove(lineNearest)
  499. px = c_double()
  500. py = c_double()
  501. pz = c_double()
  502. if not self._validLine(lineNearest):
  503. return { 'line' : -1, 'point': None }
  504. ftype = Vect_read_line(poMapInfo, self.poPoints, self.poCats, lineNearest)
  505. Vect_line_distance (self.poPoints, point[0], point[1], 0.0, self.is3D,
  506. byref(px), byref(py), byref(pz),
  507. None, None, None)
  508. # check for duplicates
  509. if self.settings['highlightDupl']['enabled']:
  510. found = poFound.contents
  511. for i in range(found.n_values):
  512. line = found.value[i]
  513. if line != lineNearest:
  514. self.selected['ids'].append(line)
  515. self.GetDuplicates()
  516. for i in range(found.n_values):
  517. line = found.value[i]
  518. if line != lineNearest and not self._isDuplicated(line):
  519. self.selected['ids'].remove(line)
  520. Vect_destroy_list(poFound)
  521. if thisMapInfo:
  522. # drawing segments can be very expensive
  523. # only one features selected
  524. self._drawSegments = True
  525. return { 'line' : lineNearest,
  526. 'point' : (px.value, py.value, pz.value) }
  527. def _listToIList(self, plist):
  528. """!Generate from list struct_ilist
  529. """
  530. ilist = Vect_new_list()
  531. for val in plist:
  532. Vect_list_append(ilist, val)
  533. return ilist
  534. def GetSelectedIList(self, ilist = None):
  535. """!Get list of selected objects as struct_ilist
  536. Returned IList must be freed by Vect_destroy_list().
  537. @return struct_ilist
  538. """
  539. if ilist:
  540. return self._listToIList(ilist)
  541. return self._listToIList(self.selected['ids'])
  542. def GetSelected(self, grassId = True):
  543. """!Get ids of selected objects
  544. @param grassId True for feature id, False for PseudoDC id
  545. @return list of ids of selected vector objects
  546. """
  547. if grassId:
  548. return self.selected['ids']
  549. dc_ids = list()
  550. if not self._drawSegments:
  551. dc_ids.append(1)
  552. elif len(self.selected['ids']) > 0:
  553. # only first selected feature
  554. Vect_read_line(self.poMapInfo, self.poPoints, None,
  555. self.selected['ids'][0])
  556. points = self.poPoints.contents
  557. # node - segment - vertex - segment - node
  558. for i in range(1, 2 * points.n_points):
  559. dc_ids.append(i)
  560. return dc_ids
  561. def SetSelected(self, ids, layer = -1):
  562. """!Set selected vector objects
  563. @param list of ids (None to unselect features)
  564. @param layer layer number for features selected based on category number
  565. """
  566. if ids:
  567. self._drawSelected = True
  568. else:
  569. self._drawSelected = False
  570. self.selected['field'] = layer
  571. if layer > 0:
  572. self.selected['cats'] = ids
  573. self.selected['ids'] = list()
  574. ### cidx is not up-to-date
  575. # Vect_cidx_find_all(self.poMapInfo, layer, GV_POINTS | GV_LINES, lid, ilist)
  576. nlines = Vect_get_num_lines(self.poMapInfo)
  577. for line in range(1, nlines + 1):
  578. if not Vect_line_alive(self.poMapInfo, line):
  579. continue
  580. ltype = Vect_read_line (self.poMapInfo, None, self.poCats, line)
  581. if not (ltype & (GV_POINTS | GV_LINES)):
  582. continue
  583. found = False
  584. cats = self.poCats.contents
  585. for i in range(0, cats.n_cats):
  586. for cat in self.selected['cats']:
  587. if cats.cat[i] == cat:
  588. found = True
  589. break
  590. if found:
  591. self.selected['ids'].append(line)
  592. else:
  593. self.selected['ids'] = ids
  594. self.selected['cats'] = []
  595. def GetSelectedVertex(self, pos):
  596. """!Get PseudoDC vertex id of selected line
  597. Set bounding box for vertices of line.
  598. @param pos position
  599. @return id of center, left and right vertex
  600. @return 0 no line found
  601. @return -1 on error
  602. """
  603. returnId = list()
  604. # only one object can be selected
  605. if len(self.selected['ids']) != 1 or not self._drawSegments:
  606. return returnId
  607. startId = 1
  608. line = self.selected['ids'][0]
  609. if not self._validLine(line):
  610. return -1
  611. ftype = Vect_read_line(self.poMapInfo, self.poPoints, self.poCats, line)
  612. minDist = 0.0
  613. Gid = -1
  614. # find the closest vertex (x, y)
  615. DCid = 1
  616. points = self.poPoints.contents
  617. for idx in range(points.n_points):
  618. dist = Vect_points_distance(pos[0], pos[1], 0.0,
  619. points.x[idx], points.y[idx], points.z[idx], 0)
  620. if idx == 0:
  621. minDist = dist
  622. Gid = idx
  623. else:
  624. if minDist > dist:
  625. minDist = dist
  626. Gid = idx
  627. vx, vy = self._cell2Pixel(points.x[idx], points.y[idx], points.z[idx])
  628. rect = wx.Rect(vx, vy, 0, 0)
  629. self.dc.SetIdBounds(DCid, rect)
  630. DCid += 2
  631. if minDist > self.GetThreshold():
  632. return returnId
  633. # translate id
  634. DCid = Gid * 2 + 1
  635. # add selected vertex
  636. returnId.append(DCid)
  637. # left vertex
  638. if DCid == startId:
  639. returnId.append(-1)
  640. else:
  641. returnId.append(DCid - 2)
  642. # right vertex
  643. if DCid == (points.n_points - 1) * 2 + startId:
  644. returnId.append(-1)
  645. else:
  646. returnId.append(DCid + 2)
  647. return returnId
  648. def GetRegionSelected(self):
  649. """!Get minimal region extent of selected features
  650. @return n,s,w,e
  651. """
  652. regionBox = bound_box()
  653. lineBox = bound_box()
  654. setRegion = True
  655. nareas = Vect_get_num_areas(self.poMapInfo)
  656. for line in self.selected['ids']:
  657. area = Vect_get_centroid_area(self.poMapInfo, line)
  658. if area > 0 and area <= nareas:
  659. if not Vect_get_area_box(self.poMapInfo, area, byref(lineBox)):
  660. continue
  661. else:
  662. if not Vect_get_line_box(self.poMapInfo, line, byref(lineBox)):
  663. continue
  664. if setRegion:
  665. Vect_box_copy(byref(regionBox), byref(lineBox))
  666. setRegion = False
  667. else:
  668. Vect_box_extend(byref(regionBox), byref(lineBox))
  669. return regionBox.N, regionBox.S, regionBox.W, regionBox.E
  670. def DrawSelected(self, flag):
  671. """!Draw selected features
  672. @param flag True to draw selected features
  673. """
  674. self._drawSelected = bool(flag)
  675. def CloseMap(self):
  676. """!Close vector map
  677. @return 0 on success
  678. @return non-zero on error
  679. """
  680. ret = 0
  681. if self.poMapInfo:
  682. # rebuild topology
  683. Vect_build_partial(self.poMapInfo, GV_BUILD_NONE)
  684. Vect_build(self.poMapInfo)
  685. # close map and store topo/cidx
  686. ret = Vect_close(self.poMapInfo)
  687. del self.mapInfo
  688. self.poMapInfo = self.mapInfo = None
  689. return ret
  690. def OpenMap(self, name, mapset, update = True):
  691. """!Open vector map by the driver
  692. @param name name of vector map to be open
  693. @param mapset name of mapset where the vector map lives
  694. @return map_info
  695. @return None on error
  696. """
  697. Debug.msg("DisplayDriver.OpenMap(): name=%s mapset=%s updated=%d",
  698. name, mapset, update)
  699. if not self.mapInfo:
  700. self.mapInfo = Map_info()
  701. self.poMapInfo = pointer(self.mapInfo)
  702. # open existing map
  703. if update:
  704. ret = Vect_open_update(self.poMapInfo, name, mapset)
  705. Vect_set_updated(self.poMapInfo, True) # track updated lines
  706. else:
  707. ret = Vect_open_old(self.poMapInfo, name, mapset)
  708. self.is3D = Vect_is_3d(self.poMapInfo)
  709. if ret == -1: # error
  710. del self.mapInfo
  711. self.poMapInfo = self.mapInfo = None
  712. elif ret < 2:
  713. dlg = wx.MessageDialog(parent = self.window,
  714. message = _("Topology for vector map <%s> is not available. "
  715. "Topology is required by digitizer. Do you want to "
  716. "rebuild topology (takes some time) and open the vector map "
  717. "for editing?") % name,
  718. caption=_("Topology missing"),
  719. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  720. ret = dlg.ShowModal()
  721. if ret != wx.ID_YES:
  722. del self.mapInfo
  723. self.poMapInfo = self.mapInfo = None
  724. else:
  725. Vect_build(self.poMapInfo)
  726. return self.poMapInfo
  727. def GetMapBoundingBox(self):
  728. """!Get bounding box of (opened) vector map layer
  729. @return (w,s,b,e,n,t)
  730. """
  731. if not self.poMapInfo:
  732. return None
  733. bbox = bound_box()
  734. Vect_get_map_box(self.poMapInfo, byref(bbox))
  735. return bbox.W, bbox.S, bbox.B, \
  736. bbox.E, bbox.N, bbox.T
  737. def UpdateSettings(self, alpha = 255):
  738. """!Update display driver settings
  739. @todo map units
  740. @alpha color value for aplha channel
  741. """
  742. color = dict()
  743. for key in self.settings.keys():
  744. if key == 'lineWidth':
  745. self.settings[key] = int(UserSettings.Get(group = 'vdigit', key = 'lineWidth',
  746. subkey = 'value'))
  747. continue
  748. color = wx.Color(UserSettings.Get(group = 'vdigit', key = 'symbol',
  749. subkey = [key, 'color'])[0],
  750. UserSettings.Get(group = 'vdigit', key = 'symbol',
  751. subkey = [key, 'color'])[1],
  752. UserSettings.Get(group = 'vdigit', key = 'symbol',
  753. subkey = [key, 'color'])[2],
  754. alpha)
  755. if key == 'highlight':
  756. self.settings[key] = color
  757. continue
  758. if key == 'highlightDupl':
  759. self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'checkForDupl',
  760. subkey = 'enabled'))
  761. else:
  762. self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'symbol',
  763. subkey = [key, 'enabled']))
  764. self.settings[key]['color'] = color
  765. def UpdateRegion(self):
  766. """!Update geographical region used by display driver
  767. """
  768. self.region = self.mapObj.GetCurrentRegion()
  769. def GetThreshold(self, type = 'snapping', value = None, units = None):
  770. """!Return threshold value in map units
  771. @param type snapping mode (node, vertex)
  772. @param value threshold to be set up
  773. @param units units (map, screen)
  774. @return threshold value
  775. """
  776. if value is None:
  777. value = UserSettings.Get(group = 'vdigit', key = type, subkey = 'value')
  778. if units is None:
  779. units = UserSettings.Get(group = 'vdigit', key = type, subkey = 'units')
  780. if value < 0:
  781. value = (self.region['nsres'] + self.region['ewres']) / 2.0
  782. if units == "screen pixels":
  783. # pixel -> cell
  784. res = max(self.region['nsres'], self.region['ewres'])
  785. return value * res
  786. return value
  787. def GetDuplicates(self):
  788. """!Return ids of (selected) duplicated vector features
  789. """
  790. if not self.poMapInfo:
  791. return
  792. ids = dict()
  793. APoints = Vect_new_line_struct()
  794. BPoints = Vect_new_line_struct()
  795. self.selected['idsDupl'] = list()
  796. for i in range(len(self.selected['ids'])):
  797. line1 = self.selected['ids'][i]
  798. if self._isDuplicated(line1):
  799. continue
  800. Vect_read_line(self.poMapInfo, APoints, None, line1)
  801. for line2 in self.selected['ids']:
  802. if line1 == line2 or self._isDuplicated(line2):
  803. continue
  804. Vect_read_line(self.poMapInfo, BPoints, None, line2)
  805. if Vect_line_check_duplicate(APoints, BPoints, WITHOUT_Z):
  806. if i not in ids:
  807. ids[i] = list()
  808. ids[i].append((line1, self._getCatString(line1)))
  809. self.selected['idsDupl'].append(line1)
  810. ids[i].append((line2, self._getCatString(line2)))
  811. self.selected['idsDupl'].append(line2)
  812. Vect_destroy_line_struct(APoints)
  813. Vect_destroy_line_struct(BPoints)
  814. return ids
  815. def _getCatString(self, line):
  816. Vect_read_line(self.poMapInfo, None, self.poCats, line)
  817. cats = self.poCats.contents
  818. catsDict = dict()
  819. for i in range(cats.n_cats):
  820. layer = cats.field[i]
  821. if layer not in catsDict:
  822. catsDict[layer] = list()
  823. catsDict[layer].append(cats.cat[i])
  824. catsStr = ''
  825. for l, c in catsDict.iteritems():
  826. catsStr = '%d: (%s)' % (l, ','.join(map(str, c)))
  827. return catsStr
  828. def UnSelect(self, lines):
  829. """!Unselect vector features
  830. @param lines list of feature id(s)
  831. """
  832. checkForDupl = False
  833. for line in lines:
  834. if self._isSelected(line):
  835. self.selected['ids'].remove(line)
  836. if self.settings['highlightDupl']['enabled'] and self._isDuplicated(line):
  837. checkForDupl = True
  838. if checkForDupl:
  839. self.GetDuplicates()
  840. return len(self.selected['ids'])