mapwindow.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087
  1. """!
  2. @package mapdisp.mapwindow
  3. @brief Map display canvas - buffered window.
  4. Classes:
  5. - mapwindow::BufferedWindow
  6. - mapwindow::GraphicsSet
  7. - mapwindow::GraphicsSetItem
  8. (C) 2006-2013 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. @author Michael Barton
  13. @author Jachym Cepicky
  14. @author Stepan Turek <stepan.turek seznam.cz> (handlers support, GraphicsSet)
  15. @author Anna Petrasova <kratochanna gmail.com> (refactoring)
  16. @author Vaclav Petras <wenzeslaus gmail.com> (refactoring)
  17. """
  18. import os
  19. import time
  20. import math
  21. import sys
  22. from copy import copy
  23. import wx
  24. from grass.pydispatch.signal import Signal
  25. import grass.script as grass
  26. from gui_core.dialogs import SavedRegion
  27. from core.gcmd import RunCommand, GException, GError, GMessage
  28. from core.debug import Debug
  29. from core.settings import UserSettings
  30. from gui_core.mapwindow import MapWindow
  31. from core.utils import GetGEventAttribsForHandler, _
  32. import core.utils as utils
  33. try:
  34. import grass.lib.gis as gislib
  35. haveCtypes = True
  36. except ImportError:
  37. haveCtypes = False
  38. class BufferedWindow(MapWindow, wx.Window):
  39. """!A Buffered window class (2D view mode)
  40. Superclass for VDigitWindow (vector digitizer).
  41. When the drawing needs to change, you app needs to call the
  42. UpdateMap() method. Since the drawing is stored in a bitmap, you
  43. can also save the drawing to file by calling the
  44. SaveToFile() method.
  45. """
  46. def __init__(self, parent, giface, Map, properties,
  47. id=wx.ID_ANY, overlays=None,
  48. style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
  49. """!
  50. @param parent parent window
  51. @param giface grass interface instance
  52. @param Map map instance
  53. @param properties instance of MapWindowProperties
  54. @param id wx window id
  55. @param style wx window style
  56. @param kwargs keyword arguments passed to MapWindow and wx.Window
  57. """
  58. MapWindow.__init__(self, parent=parent, giface=giface, Map=Map)
  59. wx.Window.__init__(self, parent=parent, id=id, style=style, **kwargs)
  60. self._properties = properties
  61. # flags
  62. self.resize = False # indicates whether or not a resize event has taken place
  63. self.dragimg = None # initialize variable for map panning
  64. self.alwaysRender = False # if it always sets render to True in self.UpdateMap()
  65. # variables for drawing on DC
  66. self.pen = None # pen for drawing zoom boxes, etc.
  67. self.polypen = None # pen for drawing polylines (measurements, profiles, etc)
  68. # List of wx.Point tuples defining a polyline (geographical coordinates)
  69. self.polycoords = []
  70. # ID of rubber band line
  71. self.lineid = None
  72. # ID of poly line resulting from cumulative rubber band lines (e.g. measurement)
  73. self.plineid = None
  74. # Emitted when zoom of a window is changed
  75. self.zoomChanged = Signal('BufferedWindow.zoomChanged')
  76. # Emitted when map was queried, parameters x, y are mouse coordinates
  77. # TODO: change pixel coordinates to map coordinates (using Pixel2Cell)
  78. self.mapQueried = Signal('BufferedWindow.mapQueried')
  79. # Emitted when the zoom history stack is emptied
  80. self.zoomHistoryUnavailable = Signal('BufferedWindow.zoomHistoryUnavailable')
  81. # Emitted when the zoom history stack is not empty
  82. self.zoomHistoryAvailable = Signal('BufferedWindow.zoomHistoryAvailable')
  83. # Emitted when map enters the window
  84. self.mouseEntered = Signal('BufferedWindow.mouseEntered')
  85. # Emitted when left mouse button is released and mouse use is 'pointer'
  86. # Parameters are x and y of the mouse click in map (cell) units
  87. # new and experimental, if the concept would be used widely,
  88. # it could replace register and unregister mechanism
  89. # and partially maybe also internal mouse use dictionary
  90. self.mouseLeftUpPointer = Signal('BufferedWindow.mouseLeftUpPointer')
  91. # Emitted when left mouse button is released
  92. self.mouseLeftUp = Signal('BufferedWindow.mouseLeftUp')
  93. # Emitted when left mouse button was pressed
  94. self.mouseLeftDown = Signal('BufferedWindow.mouseLeftDown')
  95. # Emitted after double-click
  96. self.mouseDClick = Signal('BufferedWindow.mouseDClick')
  97. # Emitted when mouse us moving (mouse motion event)
  98. # Parametres are x and y of the mouse position in map (cell) units
  99. self.mouseMoving = Signal('BufferedWindow.mouseMoving')
  100. # event bindings
  101. self.Bind(wx.EVT_PAINT, self.OnPaint)
  102. self.Bind(wx.EVT_SIZE, self.OnSize)
  103. self.Bind(wx.EVT_IDLE, self.OnIdle)
  104. self._bindMouseEvents()
  105. self.processMouse = True
  106. # render output objects
  107. self.mapfile = None # image file to be rendered
  108. self.img = None # wx.Image object (self.mapfile)
  109. # decoration overlays
  110. self.overlays = overlays
  111. # images and their PseudoDC ID's for painting and dragging
  112. self.imagedict = {}
  113. self.select = {} # selecting/unselecting decorations for dragging
  114. self.textdict = {} # text, font, and color indexed by id
  115. # zoom objects
  116. self.zoomhistory = [] # list of past zoom extents
  117. self.currzoom = 0 # current set of extents in zoom history being used
  118. self.zoomtype = 1 # 1 zoom in, 0 no zoom, -1 zoom out
  119. self.hitradius = 10 # distance for selecting map decorations
  120. self.dialogOffset = 5 # offset for dialog (e.g. DisplayAttributesDialog)
  121. # OnSize called to make sure the buffer is initialized.
  122. # This might result in OnSize getting called twice on some
  123. # platforms at initialization, but little harm done.
  124. ### self.OnSize(None)
  125. self._definePseudoDC()
  126. # redraw all pdc's, pdcTmp layer is redrawn always (speed issue)
  127. self.redrawAll = True
  128. # will store an off screen empty bitmap for saving to file
  129. self._buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  130. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
  131. # rerender when Map reports change
  132. self.Map.layerChanged.connect(lambda: self.UpdateMap())
  133. # vars for handling mouse clicks
  134. self.dragid = -1
  135. self.lastpos = (0, 0)
  136. # list for registration of graphics to draw
  137. self.graphicsSetList = []
  138. def _definePseudoDC(self):
  139. """!Define PseudoDC objects to use
  140. """
  141. # create PseudoDC used for background map, map decorations like scales and legends
  142. self.pdc = wx.PseudoDC()
  143. # used for digitization tool
  144. self.pdcVector = None
  145. # decorations (region box, etc.)
  146. self.pdcDec = wx.PseudoDC()
  147. # pseudoDC for temporal objects (select box, measurement tool, etc.)
  148. self.pdcTmp = wx.PseudoDC()
  149. def _bindMouseEvents(self):
  150. self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
  151. self.Bind(wx.EVT_MOTION, self.OnMotion)
  152. self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)
  153. def OnContextMenu(self, event):
  154. """!Show Map Display context menu"""
  155. if hasattr(self, "digit"):
  156. event.Skip()
  157. return
  158. if not hasattr(self, "popupCopyCoordinates"):
  159. self.popupCopyCoordinates = wx.NewId()
  160. self.Bind(wx.EVT_MENU, self.OnCopyCoordinates, id = self.popupCopyCoordinates)
  161. # generate popup-menu
  162. menu = wx.Menu()
  163. menu.Append(self.popupCopyCoordinates, _("Copy coordinates to clipboard"))
  164. self.PopupMenu(menu)
  165. menu.Destroy()
  166. def Draw(self, pdc, img = None, drawid = None, pdctype = 'image', coords = [0, 0, 0, 0], pen = None):
  167. """!Draws map and overlay decorations
  168. """
  169. if drawid == None:
  170. if pdctype == 'image' and img:
  171. drawid = self.imagedict[img]
  172. elif pdctype == 'clear':
  173. drawid = None
  174. else:
  175. drawid = wx.NewId()
  176. # TODO: find better solution
  177. if not pen:
  178. if pdctype == 'polyline':
  179. pen = self.polypen
  180. else:
  181. pen = self.pen
  182. if img and pdctype == 'image':
  183. # self.imagedict[img]['coords'] = coords
  184. self.select[self.imagedict[img]['id']] = False # ?
  185. pdc.BeginDrawing()
  186. if drawid != 99:
  187. bg = wx.TRANSPARENT_BRUSH
  188. else:
  189. bg = wx.Brush(self.GetBackgroundColour())
  190. pdc.SetBackground(bg)
  191. Debug.msg (5, "BufferedWindow.Draw(): id=%s, pdctype = %s, coord=%s" % \
  192. (drawid, pdctype, coords))
  193. # set PseudoDC id
  194. if drawid is not None:
  195. pdc.SetId(drawid)
  196. if pdctype == 'clear': # erase the display
  197. bg = wx.WHITE_BRUSH
  198. # bg = wx.Brush(self.GetBackgroundColour())
  199. pdc.SetBackground(bg)
  200. pdc.RemoveAll()
  201. pdc.Clear()
  202. pdc.EndDrawing()
  203. self.Refresh()
  204. return
  205. if pdctype == 'image': # draw selected image
  206. bitmap = wx.BitmapFromImage(img)
  207. w,h = bitmap.GetSize()
  208. pdc.DrawBitmap(bitmap, coords[0], coords[1], True) # draw the composite map
  209. pdc.SetIdBounds(drawid, wx.Rect(coords[0],coords[1], w, h))
  210. elif pdctype == 'box': # draw a box on top of the map
  211. if pen:
  212. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  213. pdc.SetPen(pen)
  214. x2 = max(coords[0],coords[2])
  215. x1 = min(coords[0],coords[2])
  216. y2 = max(coords[1],coords[3])
  217. y1 = min(coords[1],coords[3])
  218. rwidth = x2-x1
  219. rheight = y2-y1
  220. rect = wx.Rect(x1, y1, rwidth, rheight)
  221. pdc.DrawRectangleRect(rect)
  222. pdc.SetIdBounds(drawid, rect)
  223. elif pdctype == 'line': # draw a line on top of the map
  224. if pen:
  225. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  226. pdc.SetPen(pen)
  227. pdc.DrawLinePoint(wx.Point(coords[0], coords[1]),wx.Point(coords[2], coords[3]))
  228. pdc.SetIdBounds(drawid, wx.Rect(coords[0], coords[1], coords[2], coords[3]))
  229. elif pdctype == 'polyline': # draw a polyline on top of the map
  230. if pen:
  231. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  232. pdc.SetPen(pen)
  233. if (len(coords) < 2):
  234. return
  235. i = 1
  236. while i < len(coords):
  237. pdc.DrawLinePoint(wx.Point(coords[i-1][0], coords[i-1][1]),
  238. wx.Point(coords[i][0], coords[i][1]))
  239. i += 1
  240. # get bounding rectangle for polyline
  241. xlist = []
  242. ylist = []
  243. if len(coords) > 0:
  244. for point in coords:
  245. x,y = point
  246. xlist.append(x)
  247. ylist.append(y)
  248. x1 = min(xlist)
  249. x2 = max(xlist)
  250. y1 = min(ylist)
  251. y2 = max(ylist)
  252. pdc.SetIdBounds(drawid, wx.Rect(x1,y1,x2,y2))
  253. # self.ovlcoords[drawid] = [x1,y1,x2,y2]
  254. elif pdctype == 'point': # draw point
  255. if pen:
  256. pdc.SetPen(pen)
  257. pdc.DrawPoint(coords[0], coords[1])
  258. coordsBound = (coords[0] - 5,
  259. coords[1] - 5,
  260. coords[0] + 5,
  261. coords[1] + 5)
  262. pdc.SetIdBounds(drawid, wx.Rect(coordsBound))
  263. elif pdctype == 'text': # draw text on top of map
  264. if not img['active']:
  265. return # only draw active text
  266. if 'rotation' in img:
  267. rotation = float(img['rotation'])
  268. else:
  269. rotation = 0.0
  270. w, h = self.GetFullTextExtent(img['text'])[0:2]
  271. pdc.SetFont(img['font'])
  272. pdc.SetTextForeground(img['color'])
  273. coords, bbox = self.TextBounds(img)
  274. if rotation == 0:
  275. pdc.DrawText(img['text'], coords[0], coords[1])
  276. else:
  277. pdc.DrawRotatedText(img['text'], coords[0], coords[1], rotation)
  278. pdc.SetIdBounds(drawid, bbox)
  279. pdc.EndDrawing()
  280. self.Refresh()
  281. return drawid
  282. def TextBounds(self, textinfo, relcoords = False):
  283. """!Return text boundary data
  284. @param textinfo text metadata (text, font, color, rotation)
  285. @param coords reference point
  286. @return coords of nonrotated text bbox (TL corner)
  287. @return bbox of rotated text bbox (wx.Rect)
  288. @return relCoords are text coord inside bbox
  289. """
  290. if 'rotation' in textinfo:
  291. rotation = float(textinfo['rotation'])
  292. else:
  293. rotation = 0.0
  294. coords = textinfo['coords']
  295. bbox = wx.Rect(coords[0], coords[1], 0, 0)
  296. relCoords = (0, 0)
  297. Debug.msg (4, "BufferedWindow.TextBounds(): text=%s, rotation=%f" % \
  298. (textinfo['text'], rotation))
  299. self.Update()
  300. self.SetFont(textinfo['font'])
  301. w, h = self.GetTextExtent(textinfo['text'])
  302. if rotation == 0:
  303. bbox[2], bbox[3] = w, h
  304. if relcoords:
  305. return coords, bbox, relCoords
  306. else:
  307. return coords, bbox
  308. boxh = math.fabs(math.sin(math.radians(rotation)) * w) + h
  309. boxw = math.fabs(math.cos(math.radians(rotation)) * w) + h
  310. if rotation > 0 and rotation < 90:
  311. bbox[1] -= boxh
  312. relCoords = (0, boxh)
  313. elif rotation >= 90 and rotation < 180:
  314. bbox[0] -= boxw
  315. bbox[1] -= boxh
  316. relCoords = (boxw, boxh)
  317. elif rotation >= 180 and rotation < 270:
  318. bbox[0] -= boxw
  319. relCoords = (boxw, 0)
  320. bbox[2] = boxw
  321. bbox[3] = boxh
  322. bbox.Inflate(h,h)
  323. if relcoords:
  324. return coords, bbox, relCoords
  325. else:
  326. return coords, bbox
  327. def OnPaint(self, event):
  328. """!Draw PseudoDC's to buffered paint DC
  329. If self.redrawAll is False on self.pdcTmp content is re-drawn
  330. """
  331. Debug.msg(4, "BufferedWindow.OnPaint(): redrawAll=%s" % self.redrawAll)
  332. dc = wx.BufferedPaintDC(self, self._buffer)
  333. dc.Clear()
  334. # use PrepareDC to set position correctly
  335. # probably does nothing, removed from wxPython 2.9
  336. # self.PrepareDC(dc)
  337. # create a clipping rect from our position and size
  338. # and update region
  339. rgn = self.GetUpdateRegion().GetBox()
  340. dc.SetClippingRect(rgn)
  341. switchDraw = False
  342. if self.redrawAll is None:
  343. self.redrawAll = True
  344. switchDraw = True
  345. if self.redrawAll: # redraw pdc and pdcVector
  346. # draw to the dc using the calculated clipping rect
  347. self.pdc.DrawToDCClipped(dc, rgn)
  348. # draw vector map layer
  349. if hasattr(self, "digit"):
  350. # decorate with GDDC (transparency)
  351. try:
  352. gcdc = wx.GCDC(dc)
  353. self.pdcVector.DrawToDCClipped(gcdc, rgn)
  354. except NotImplementedError, e:
  355. print >> sys.stderr, e
  356. self.pdcVector.DrawToDCClipped(dc, rgn)
  357. self.bufferLast = None
  358. else: # do not redraw pdc and pdcVector
  359. if self.bufferLast is None:
  360. # draw to the dc
  361. self.pdc.DrawToDC(dc)
  362. if hasattr(self, "digit"):
  363. # decorate with GDDC (transparency)
  364. try:
  365. gcdc = wx.GCDC(dc)
  366. self.pdcVector.DrawToDC(gcdc)
  367. except NotImplementedError, e:
  368. print >> sys.stderr, e
  369. self.pdcVector.DrawToDC(dc)
  370. # store buffered image
  371. # self.bufferLast = wx.BitmapFromImage(self.buffer.ConvertToImage())
  372. self.bufferLast = dc.GetAsBitmap(wx.Rect(0, 0, self.Map.width, self.Map.height))
  373. self.pdc.DrawBitmap(self.bufferLast, 0, 0, False)
  374. self.pdc.DrawToDC(dc)
  375. # draw decorations (e.g. region box)
  376. try:
  377. gcdc = wx.GCDC(dc)
  378. self.pdcDec.DrawToDC(gcdc)
  379. except NotImplementedError, e:
  380. print >> sys.stderr, e
  381. self.pdcDec.DrawToDC(dc)
  382. # draw temporary object on the foreground
  383. ### self.pdcTmp.DrawToDCClipped(dc, rgn)
  384. self.pdcTmp.DrawToDC(dc)
  385. if switchDraw:
  386. self.redrawAll = False
  387. def OnSize(self, event):
  388. """!Scale map image so that it is the same size as the Window
  389. """
  390. # re-render image on idle
  391. self.resize = time.clock()
  392. def OnIdle(self, event):
  393. """!Only re-render a composite map image from GRASS during
  394. idle time instead of multiple times during resizing.
  395. """
  396. # use OnInternalIdle() instead ?
  397. if self.resize and self.resize + 0.2 < time.clock():
  398. Debug.msg(3, "BufferedWindow.OnSize():")
  399. # set size of the input image
  400. self.Map.ChangeMapSize(self.GetClientSize())
  401. # Make new off screen bitmap: this bitmap will always have the
  402. # current drawing in it, so it can be used to save the image to
  403. # a file, or whatever.
  404. self._buffer.Destroy()
  405. self._buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  406. # get the image to be rendered
  407. self.img = self.GetImage()
  408. # update map display
  409. updatemap = True
  410. if self.img and self.Map.width + self.Map.height > 0: # scale image after resize
  411. self.img = self.img.Scale(self.Map.width, self.Map.height)
  412. if len(self.Map.GetListOfLayers()) > 0:
  413. self.UpdateMap()
  414. updatemap = False
  415. if updatemap:
  416. self.UpdateMap(render = True)
  417. self.resize = False
  418. elif self.resize:
  419. event.RequestMore()
  420. event.Skip()
  421. def SaveToFile(self, FileName, FileType, width, height):
  422. """!This draws the pseudo DC to a buffer that can be saved to
  423. a file.
  424. @param FileName file name
  425. @param FileType type of bitmap
  426. @param width image width
  427. @param height image height
  428. """
  429. busy = wx.BusyInfo(message = _("Please wait, exporting image..."),
  430. parent = self)
  431. wx.Yield()
  432. self.Map.ChangeMapSize((width, height))
  433. ibuffer = wx.EmptyBitmap(max(1, width), max(1, height))
  434. self.Map.Render(force = True, windres = self._properties.resolution)
  435. img = self.GetImage()
  436. self.pdc.RemoveAll()
  437. self.Draw(self.pdc, img, drawid = 99)
  438. # compute size ratio to move overlay accordingly
  439. cSize = self.GetClientSizeTuple()
  440. ratio = float(width) / cSize[0], float(height) / cSize[1]
  441. # redraw legend, scalebar
  442. for img in self.GetOverlay():
  443. # draw any active and defined overlays
  444. if self.imagedict[img]['layer'].IsActive():
  445. id = self.imagedict[img]['id']
  446. coords = int(ratio[0] * self.overlays[id].coords[0]),\
  447. int(ratio[1] * self.overlays[id].coords[1])
  448. self.Draw(self.pdc, img = img, drawid = id,
  449. pdctype = self.overlays[id].pdcType, coords = coords)
  450. # redraw text labels
  451. for id in self.textdict.keys():
  452. textinfo = self.textdict[id]
  453. oldCoords = textinfo['coords']
  454. textinfo['coords'] = ratio[0] * textinfo['coords'][0],\
  455. ratio[1] * textinfo['coords'][1]
  456. self.Draw(self.pdc, img = self.textdict[id], drawid = id,
  457. pdctype = 'text')
  458. # set back old coordinates
  459. textinfo['coords'] = oldCoords
  460. dc = wx.BufferedDC(None, ibuffer)
  461. dc.Clear()
  462. # probably does nothing, removed from wxPython 2.9
  463. # self.PrepareDC(dc)
  464. self.pdc.DrawToDC(dc)
  465. if self.pdcVector:
  466. self.pdcVector.DrawToDC(dc)
  467. ibuffer.SaveFile(FileName, FileType)
  468. busy.Destroy()
  469. self.UpdateMap(render = True)
  470. self.Refresh()
  471. def GetOverlay(self):
  472. """!Converts rendered overlay files to wx.Image
  473. Updates self.imagedict
  474. @return list of images
  475. """
  476. imgs = []
  477. for overlay in self.Map.GetListOfLayers(ltype = "overlay", active = True):
  478. if overlay.mapfile is not None \
  479. and os.path.isfile(overlay.mapfile) and os.path.getsize(overlay.mapfile):
  480. img = wx.Image(overlay.mapfile, wx.BITMAP_TYPE_ANY)
  481. for key in self.imagedict.keys():
  482. if self.imagedict[key]['id'] == overlay.id:
  483. del self.imagedict[key]
  484. self.imagedict[img] = { 'id' : overlay.id,
  485. 'layer' : overlay }
  486. imgs.append(img)
  487. return imgs
  488. def GetImage(self):
  489. """!Converts redered map files to wx.Image
  490. Updates self.imagedict (id=99)
  491. @return wx.Image instance (map composition)
  492. """
  493. imgId = 99
  494. if self.mapfile and self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
  495. os.path.getsize(self.Map.mapfile):
  496. img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
  497. else:
  498. img = None
  499. for key in self.imagedict.keys():
  500. if self.imagedict[key]['id'] == imgId:
  501. del self.imagedict[key]
  502. self.imagedict[img] = { 'id': imgId }
  503. return img
  504. def SetAlwaysRenderEnabled(self, alwaysRender = True):
  505. self.alwaysRender = alwaysRender
  506. def IsAlwaysRenderEnabled(self):
  507. return self.alwaysRender
  508. def UpdateMap(self, render = True, renderVector = True):
  509. """!Updates the canvas anytime there is a change to the
  510. underlaying images or to the geometry of the canvas.
  511. This method should not be called directly.
  512. @todo change direct calling of UpdateMap method to emittig grass
  513. interface updateMap signal
  514. @param render re-render map composition
  515. @param renderVector re-render vector map layer enabled for editing (used for digitizer)
  516. """
  517. start = time.clock()
  518. self.resize = False
  519. # was if self.Map.cmdfile and ...
  520. if self.IsAlwaysRenderEnabled() and self.img is None:
  521. render = True
  522. #
  523. # render background image if needed
  524. #
  525. # here was the change of the layertree rerender variable
  526. # but it is fully the problem of layertree
  527. # and so it is handled there
  528. # remove this comment when it is old enough
  529. try:
  530. if render:
  531. # update display size
  532. self.Map.ChangeMapSize(self.GetClientSize())
  533. if self._properties.resolution:
  534. # use computation region resolution for rendering
  535. windres = True
  536. else:
  537. windres = False
  538. self.mapfile = self.Map.Render(force = True,
  539. windres = windres)
  540. else:
  541. self.mapfile = self.Map.Render(force = False)
  542. except GException, e:
  543. GError(message = e.value)
  544. self.mapfile = None
  545. self.img = self.GetImage() # id=99
  546. #
  547. # clear pseudoDcs
  548. #
  549. for pdc in (self.pdc,
  550. self.pdcDec,
  551. self.pdcTmp):
  552. pdc.Clear()
  553. pdc.RemoveAll()
  554. #
  555. # draw background map image to PseudoDC
  556. #
  557. if not self.img:
  558. self.Draw(self.pdc, pdctype = 'clear')
  559. else:
  560. try:
  561. id = self.imagedict[self.img]['id']
  562. except:
  563. return False
  564. self.Draw(self.pdc, self.img, drawid = id)
  565. #
  566. # render vector map layer
  567. #
  568. if renderVector and hasattr(self, "digit"):
  569. self._updateMap()
  570. #
  571. # render overlays
  572. #
  573. for img in self.GetOverlay():
  574. # draw any active and defined overlays
  575. if self.imagedict[img]['layer'].IsActive():
  576. id = self.imagedict[img]['id']
  577. self.Draw(self.pdc, img = img, drawid = id,
  578. pdctype = self.overlays[id].pdcType, coords = self.overlays[id].coords)
  579. for id in self.textdict.keys():
  580. self.Draw(self.pdc, img = self.textdict[id], drawid = id,
  581. pdctype = 'text', coords = [10, 10, 10, 10])
  582. # optionally draw computational extent box
  583. self.DrawCompRegionExtent()
  584. #
  585. # redraw pdcTmp if needed
  586. #
  587. # draw registered graphics
  588. if len(self.graphicsSetList) > 0:
  589. penOrig = self.pen
  590. polypenOrig = self.polypen
  591. for item in self.graphicsSetList:
  592. try:
  593. item.Draw(self.pdcTmp)
  594. except:
  595. GError(parent = self,
  596. message = _('Unable to draw registered graphics. '
  597. 'The graphics was unregistered.'))
  598. self.UnregisterGraphicsToDraw(item)
  599. self.pen = penOrig
  600. self.polypen = polypenOrig
  601. if len(self.polycoords) > 0:
  602. self.DrawLines(self.pdcTmp)
  603. stop = time.clock()
  604. Debug.msg (1, "BufferedWindow.UpdateMap(): render=%s, renderVector=%s -> time=%g" % \
  605. (render, renderVector, (stop-start)))
  606. return True
  607. def DrawCompRegionExtent(self):
  608. """!Draw computational region extent in the display
  609. Display region is drawn as a blue box inside the computational region,
  610. computational region inside a display region as a red box).
  611. """
  612. if self._properties.showRegion:
  613. compReg = self.Map.GetRegion()
  614. dispReg = self.Map.GetCurrentRegion()
  615. reg = None
  616. if utils.isInRegion(dispReg, compReg):
  617. self.polypen = wx.Pen(colour = wx.Colour(0, 0, 255, 128), width = 3, style = wx.SOLID)
  618. reg = dispReg
  619. else:
  620. self.polypen = wx.Pen(colour = wx.Colour(255, 0, 0, 128),
  621. width = 3, style = wx.SOLID)
  622. reg = compReg
  623. regionCoords = []
  624. regionCoords.append((reg['w'], reg['n']))
  625. regionCoords.append((reg['e'], reg['n']))
  626. regionCoords.append((reg['e'], reg['s']))
  627. regionCoords.append((reg['w'], reg['s']))
  628. regionCoords.append((reg['w'], reg['n']))
  629. # draw region extent
  630. self.DrawLines(pdc=self.pdcDec, polycoords=regionCoords)
  631. def EraseMap(self):
  632. """!Erase map canvas
  633. """
  634. self.Draw(self.pdc, pdctype = 'clear')
  635. if hasattr(self, "digit"):
  636. self.Draw(self.pdcVector, pdctype = 'clear')
  637. self.Draw(self.pdcDec, pdctype = 'clear')
  638. self.Draw(self.pdcTmp, pdctype = 'clear')
  639. self.Map.AbortAllThreads()
  640. def DragMap(self, moveto):
  641. """!Drag the entire map image for panning.
  642. @param moveto dx,dy
  643. """
  644. dc = wx.BufferedDC(wx.ClientDC(self))
  645. dc.SetBackground(wx.Brush("White"))
  646. dc.Clear()
  647. self.dragimg = wx.DragImage(self._buffer)
  648. self.dragimg.BeginDrag((0, 0), self)
  649. self.dragimg.GetImageRect(moveto)
  650. self.dragimg.Move(moveto)
  651. self.dragimg.DoDrawImage(dc, moveto)
  652. self.dragimg.EndDrag()
  653. def DragItem(self, id, coords):
  654. """!Drag an overlay decoration item
  655. """
  656. if id == 99 or id == '' or id == None: return
  657. Debug.msg (5, "BufferedWindow.DragItem(): id=%d" % id)
  658. x, y = self.lastpos
  659. dx = coords[0] - x
  660. dy = coords[1] - y
  661. self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
  662. r = self.pdc.GetIdBounds(id)
  663. if type(r) is list:
  664. r = wx.Rect(r[0], r[1], r[2], r[3])
  665. if id > 100: # text dragging
  666. rtop = (r[0],r[1]-r[3],r[2],r[3])
  667. r = r.Union(rtop)
  668. rleft = (r[0]-r[2],r[1],r[2],r[3])
  669. r = r.Union(rleft)
  670. self.pdc.TranslateId(id, dx, dy)
  671. r2 = self.pdc.GetIdBounds(id)
  672. if type(r2) is list:
  673. r2 = wx.Rect(r[0], r[1], r[2], r[3])
  674. if id > 100: # text
  675. self.textdict[id]['bbox'] = r2
  676. self.textdict[id]['coords'][0] += dx
  677. self.textdict[id]['coords'][1] += dy
  678. r = r.Union(r2)
  679. r.Inflate(4,4)
  680. self.RefreshRect(r, False)
  681. self.lastpos = (coords[0], coords[1])
  682. def MouseDraw(self, pdc = None, begin = None, end = None):
  683. """!Mouse box or line from 'begin' to 'end'
  684. If not given from self.mouse['begin'] to self.mouse['end'].
  685. """
  686. if not pdc:
  687. return
  688. if begin is None:
  689. begin = self.mouse['begin']
  690. if end is None:
  691. end = self.mouse['end']
  692. Debug.msg (5, "BufferedWindow.MouseDraw(): use=%s, box=%s, begin=%f,%f, end=%f,%f" % \
  693. (self.mouse['use'], self.mouse['box'],
  694. begin[0], begin[1], end[0], end[1]))
  695. if self.mouse['box'] == "box":
  696. boxid = wx.ID_NEW
  697. mousecoords = [begin[0], begin[1],
  698. end[0], end[1]]
  699. r = pdc.GetIdBounds(boxid)
  700. if type(r) is list:
  701. r = wx.Rect(r[0], r[1], r[2], r[3])
  702. r.Inflate(4, 4)
  703. try:
  704. pdc.ClearId(boxid)
  705. except:
  706. pass
  707. self.RefreshRect(r, False)
  708. pdc.SetId(boxid)
  709. self.Draw(pdc, drawid = boxid, pdctype = 'box', coords = mousecoords)
  710. elif self.mouse['box'] == "line":
  711. self.lineid = wx.ID_NEW
  712. mousecoords = [begin[0], begin[1], \
  713. end[0], end[1]]
  714. x1 = min(begin[0],end[0])
  715. x2 = max(begin[0],end[0])
  716. y1 = min(begin[1],end[1])
  717. y2 = max(begin[1],end[1])
  718. r = wx.Rect(x1,y1,x2-x1,y2-y1)
  719. r.Inflate(4,4)
  720. try:
  721. pdc.ClearId(self.lineid)
  722. except:
  723. pass
  724. self.RefreshRect(r, False)
  725. pdc.SetId(self.lineid)
  726. self.Draw(pdc, drawid = self.lineid, pdctype = 'line', coords = mousecoords)
  727. def DrawLines(self, pdc = None, polycoords = None):
  728. """!Draw polyline in PseudoDC
  729. Set self.pline to wx.NEW_ID + 1
  730. polycoords - list of polyline vertices, geographical coordinates
  731. (if not given, self.polycoords is used)
  732. """
  733. if not pdc:
  734. pdc = self.pdcTmp
  735. if not polycoords:
  736. polycoords = self.polycoords
  737. if len(polycoords) > 0:
  738. self.plineid = wx.ID_NEW + 1
  739. # convert from EN to XY
  740. coords = []
  741. for p in polycoords:
  742. coords.append(self.Cell2Pixel(p))
  743. self.Draw(pdc, drawid = self.plineid, pdctype = 'polyline', coords = coords)
  744. Debug.msg (4, "BufferedWindow.DrawLines(): coords=%s, id=%s" % \
  745. (coords, self.plineid))
  746. return self.plineid
  747. return -1
  748. def DrawCross(self, pdc, coords, size, rotation = 0, pen = None,
  749. text = None, textAlign = 'lr', textOffset = (5, 5)):
  750. """!Draw cross in PseudoDC
  751. @todo implement rotation
  752. @param pdc PseudoDC
  753. @param coords center coordinates
  754. @param rotation rotate symbol
  755. @param text draw also text (text, font, color, rotation)
  756. @param textAlign alignment (default 'lower-right')
  757. @param textOffset offset for text (from center point)
  758. """
  759. Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" % \
  760. (pdc, coords, size))
  761. coordsCross = ((coords[0] - size, coords[1], coords[0] + size, coords[1]),
  762. (coords[0], coords[1] - size, coords[0], coords[1] + size))
  763. self.lineid = wx.NewId()
  764. for lineCoords in coordsCross:
  765. self.Draw(pdc, drawid = self.lineid, pdctype = 'line', coords = lineCoords, pen = pen)
  766. if not text:
  767. return self.lineid
  768. if textAlign == 'ul':
  769. coord = [coords[0] - textOffset[0], coords[1] - textOffset[1], 0, 0]
  770. elif textAlign == 'ur':
  771. coord = [coords[0] + textOffset[0], coords[1] - textOffset[1], 0, 0]
  772. elif textAlign == 'lr':
  773. coord = [coords[0] + textOffset[0], coords[1] + textOffset[1], 0, 0]
  774. else:
  775. coord = [coords[0] - textOffset[0], coords[1] + textOffset[1], 0, 0]
  776. self.Draw(pdc, img = text,
  777. pdctype = 'text', coords = coord, pen = pen)
  778. return self.lineid
  779. def _computeZoomToPointAndRecenter(self, position, zoomtype):
  780. """!Computes zoom parameters for recenter mode.
  781. Computes begin and end parameters for Zoom() method.
  782. Used for zooming by single click (not box)
  783. and mouse wheel zooming (zoom and recenter mode).
  784. """
  785. if zoomtype > 0:
  786. begin = (position[0] - self.Map.width / 4,
  787. position[1] - self.Map.height / 4)
  788. end = (position[0] + self.Map.width / 4,
  789. position[1] + self.Map.height / 4)
  790. else:
  791. begin = ((self.Map.width - position[0]) / 2,
  792. (self.Map.height - position[1]) / 2)
  793. end = (begin[0] + self.Map.width / 2,
  794. begin[1] + self.Map.height / 2)
  795. return begin, end
  796. def MouseActions(self, event):
  797. """!Mouse motion and button click notifier
  798. """
  799. if not self.processMouse:
  800. return
  801. # zoom with mouse wheel
  802. if event.GetWheelRotation() != 0:
  803. self.OnMouseWheel(event)
  804. # left mouse button pressed
  805. elif event.LeftDown():
  806. self.OnLeftDown(event)
  807. # left mouse button released
  808. elif event.LeftUp():
  809. self.OnLeftUp(event)
  810. # dragging
  811. elif event.Dragging():
  812. self.OnDragging(event)
  813. # double click
  814. elif event.ButtonDClick():
  815. self.OnButtonDClick(event)
  816. # middle mouse button pressed
  817. elif event.MiddleDown():
  818. self.OnMiddleDown(event)
  819. # middle mouse button relesed
  820. elif event.MiddleUp():
  821. self.OnMiddleUp(event)
  822. # right mouse button pressed
  823. elif event.RightDown():
  824. self.OnRightDown(event)
  825. # right mouse button released
  826. elif event.RightUp():
  827. self.OnRightUp(event)
  828. elif event.Entering():
  829. self.OnMouseEnter(event)
  830. elif event.Moving():
  831. pixelCoordinates = event.GetPositionTuple()[:]
  832. coordinates = self.Pixel2Cell(pixelCoordinates)
  833. self.mouseMoving.emit(x=coordinates[0], y=coordinates[1])
  834. self.OnMouseMoving(event)
  835. def OnMouseWheel(self, event):
  836. """!Mouse wheel moved
  837. """
  838. zoomBehaviour = UserSettings.Get(group = 'display',
  839. key = 'mouseWheelZoom',
  840. subkey = 'selection')
  841. if zoomBehaviour == 2:
  842. event.Skip()
  843. return
  844. self.processMouse = False
  845. current = event.GetPositionTuple()[:]
  846. wheel = event.GetWheelRotation()
  847. Debug.msg (5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
  848. if wheel > 0:
  849. zoomtype = 1
  850. else:
  851. zoomtype = -1
  852. if UserSettings.Get(group = 'display',
  853. key = 'scrollDirection',
  854. subkey = 'selection'):
  855. zoomtype *= -1
  856. # zoom 1/2 of the screen (TODO: settings)
  857. if zoomBehaviour == 0: # zoom and recenter
  858. begin, end = self._computeZoomToPointAndRecenter(position = current, zoomtype = zoomtype)
  859. elif zoomBehaviour == 1: # zoom to current cursor position
  860. begin = (current[0]/2, current[1]/2)
  861. end = ((self.Map.width - current[0])/2 + current[0],
  862. (self.Map.height - current[1])/2 + current[1])
  863. # zoom
  864. self.Zoom(begin, end, zoomtype)
  865. # redraw map
  866. self.UpdateMap()
  867. self.Refresh()
  868. self.processMouse = True
  869. def OnDragging(self, event):
  870. """!Mouse dragging
  871. """
  872. Debug.msg (5, "BufferedWindow.MouseAction(): Dragging")
  873. current = event.GetPositionTuple()[:]
  874. previous = self.mouse['begin']
  875. move = (current[0] - previous[0],
  876. current[1] - previous[1])
  877. if hasattr(self, "digit"):
  878. digitToolbar = self.toolbar
  879. else:
  880. digitToolbar = None
  881. # dragging or drawing box with left button
  882. if self.mouse['use'] == 'pan' or \
  883. event.MiddleIsDown():
  884. self.DragMap(move)
  885. # dragging decoration overlay item
  886. elif (self.mouse['use'] == 'pointer' and
  887. not digitToolbar and
  888. self.dragid != None):
  889. coords = event.GetPositionTuple()
  890. self.DragItem(self.dragid, coords)
  891. # dragging anything else - rubber band box or line
  892. else:
  893. if (self.mouse['use'] == 'pointer' and
  894. not digitToolbar):
  895. return
  896. self.mouse['end'] = event.GetPositionTuple()[:]
  897. if (event.LeftIsDown() and
  898. not (digitToolbar and
  899. digitToolbar.GetAction() in ("moveLine",) and
  900. self.digit.GetDisplay().GetSelected() > 0)):
  901. self.MouseDraw(pdc = self.pdcTmp)
  902. def OnLeftDown(self, event):
  903. """!Left mouse button pressed
  904. """
  905. Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
  906. self.mouse["use"])
  907. self.mouse['begin'] = event.GetPositionTuple()[:]
  908. # vector digizer
  909. if self.mouse["use"] == "pointer" and \
  910. hasattr(self, "digit"):
  911. if event.ControlDown():
  912. self.OnLeftDownUndo(event)
  913. else:
  914. self._onLeftDown(event)
  915. elif self.mouse['use'] == 'pointer':
  916. # get decoration or text id
  917. idlist = []
  918. self.dragid = ''
  919. self.lastpos = self.mouse['begin']
  920. idlist = self.pdc.FindObjects(self.lastpos[0], self.lastpos[1],
  921. self.hitradius)
  922. if 99 in idlist:
  923. idlist.remove(99)
  924. if idlist != []:
  925. self.dragid = idlist[0] #drag whatever is on top
  926. else:
  927. pass
  928. coords = self.Pixel2Cell(self.mouse['begin'])
  929. self.mouseLeftDown.emit(x=coords[0], y=coords[1])
  930. event.Skip()
  931. def OnLeftUp(self, event):
  932. """!Left mouse button released
  933. Emits mapQueried signal when mouse use is 'query'.
  934. """
  935. Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
  936. self.mouse["use"])
  937. self.mouse['end'] = event.GetPositionTuple()[:]
  938. coordinates = self.Pixel2Cell(self.mouse['end'])
  939. if self.mouse['use'] in ["zoom", "pan"]:
  940. # set region in zoom or pan
  941. begin = self.mouse['begin']
  942. end = self.mouse['end']
  943. if self.mouse['use'] == 'zoom':
  944. # set region for click (zero-width box)
  945. if begin[0] - end[0] == 0 or \
  946. begin[1] - end[1] == 0:
  947. begin, end = self._computeZoomToPointAndRecenter(position = end, zoomtype = self.zoomtype)
  948. self.Zoom(begin, end, self.zoomtype)
  949. # redraw map
  950. self.UpdateMap(render = True)
  951. elif self.mouse["use"] == "query":
  952. self.mapQueried.emit(x=self.mouse['end'][0], y=self.mouse['end'][1])
  953. elif self.mouse["use"] == "pointer" and \
  954. hasattr(self, "digit"):
  955. self._onLeftUp(event)
  956. elif (self.mouse['use'] == 'pointer' and
  957. self.dragid >= 0):
  958. # end drag of overlay decoration
  959. if self.dragid < 99 and self.dragid in self.overlays:
  960. self.overlays[self.dragid].coords = self.pdc.GetIdBounds(self.dragid)
  961. elif self.dragid > 100 and self.dragid in self.textdict:
  962. self.textdict[self.dragid]['bbox'] = self.pdc.GetIdBounds(self.dragid)
  963. else:
  964. pass
  965. self.dragid = None
  966. self.mouseLeftUpPointer.emit(x=coordinates[0], y=coordinates[1])
  967. # TODO: decide which coordinates to send (e, n, mouse['begin'], mouse['end'])
  968. self.mouseLeftUp.emit(x=coordinates[0], y=coordinates[1])
  969. def OnButtonDClick(self, event):
  970. """!Mouse button double click
  971. """
  972. Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
  973. self.mouse["use"])
  974. screenCoords = event.GetPosition()
  975. if self.mouse['use'] == 'pointer':
  976. # select overlay decoration options dialog
  977. idlist = self.pdc.FindObjects(screenCoords[0], screenCoords[1], self.hitradius)
  978. if idlist:
  979. self.dragid = idlist[0]
  980. self.overlayActivated.emit(overlayId=self.dragid)
  981. coords = self.Pixel2Cell(screenCoords)
  982. self.mouseDClick.emit(x=coords[0], y=coords[1])
  983. def OnRightDown(self, event):
  984. """!Right mouse button pressed
  985. """
  986. Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
  987. self.mouse["use"])
  988. if hasattr(self, "digit"):
  989. self._onRightDown(event)
  990. event.Skip()
  991. def OnRightUp(self, event):
  992. """!Right mouse button released
  993. """
  994. Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
  995. self.mouse["use"])
  996. if hasattr(self, "digit"):
  997. self._onRightUp(event)
  998. self.redrawAll = True
  999. self.Refresh()
  1000. event.Skip()
  1001. def OnMiddleDown(self, event):
  1002. """!Middle mouse button pressed
  1003. """
  1004. if not event:
  1005. return
  1006. self.mouse['begin'] = event.GetPositionTuple()[:]
  1007. def OnMiddleUp(self, event):
  1008. """!Middle mouse button released
  1009. """
  1010. self.mouse['end'] = event.GetPositionTuple()[:]
  1011. # set region in zoom or pan
  1012. begin = self.mouse['begin']
  1013. end = self.mouse['end']
  1014. self.Zoom(begin, end, 0) # no zoom
  1015. # redraw map
  1016. self.UpdateMap(render = True)
  1017. def OnMouseEnter(self, event):
  1018. """!Mouse entered window and no mouse buttons were pressed
  1019. Emits the mouseEntered signal.
  1020. """
  1021. self.mouseEntered.emit()
  1022. event.Skip()
  1023. def OnMouseMoving(self, event):
  1024. """!Motion event and no mouse buttons were pressed
  1025. """
  1026. if self.mouse["use"] == "pointer" and \
  1027. hasattr(self, "digit"):
  1028. self._onMouseMoving(event)
  1029. event.Skip()
  1030. def OnCopyCoordinates(self, event):
  1031. """!Copy coordinates to cliboard"""
  1032. e, n = self.GetLastEN()
  1033. if wx.TheClipboard.Open():
  1034. do = wx.TextDataObject()
  1035. # TODO: put delimiter in settings and apply also for Go to in statusbar
  1036. delim = ';'
  1037. do.SetText(str(e) + delim + str(n))
  1038. wx.TheClipboard.SetData(do)
  1039. wx.TheClipboard.Close()
  1040. def ClearLines(self, pdc = None):
  1041. """!Clears temporary drawn lines from PseudoDC
  1042. """
  1043. if not pdc:
  1044. pdc = self.pdcTmp
  1045. try:
  1046. pdc.ClearId(self.lineid)
  1047. pdc.RemoveId(self.lineid)
  1048. except:
  1049. pass
  1050. try:
  1051. pdc.ClearId(self.plineid)
  1052. pdc.RemoveId(self.plineid)
  1053. except:
  1054. pass
  1055. Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
  1056. (self.lineid, self.plineid))
  1057. return True
  1058. def Pixel2Cell(self, xyCoords):
  1059. """!Convert image coordinates to real word coordinates
  1060. @param x, y image coordinates
  1061. @return easting, northing
  1062. @return None on error
  1063. """
  1064. try:
  1065. x = int(xyCoords[0])
  1066. y = int(xyCoords[1])
  1067. except:
  1068. return None
  1069. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1070. res = self.Map.region["ewres"]
  1071. else:
  1072. res = self.Map.region["nsres"]
  1073. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1074. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1075. east = w + x * res
  1076. north = n - y * res
  1077. return (east, north)
  1078. def Cell2Pixel(self, enCoords):
  1079. """!Convert real word coordinates to image coordinates
  1080. """
  1081. try:
  1082. east = float(enCoords[0])
  1083. north = float(enCoords[1])
  1084. except:
  1085. return None
  1086. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1087. res = self.Map.region["ewres"]
  1088. else:
  1089. res = self.Map.region["nsres"]
  1090. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1091. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1092. x = (east - w) / res
  1093. y = (n - north) / res
  1094. return (x, y)
  1095. def Zoom(self, begin, end, zoomtype):
  1096. """!Calculates new region while (un)zoom/pan-ing
  1097. """
  1098. x1, y1 = begin
  1099. x2, y2 = end
  1100. newreg = {}
  1101. # threshold - too small squares do not make sense
  1102. # can only zoom to windows of > 5x5 screen pixels
  1103. if abs(x2-x1) > 5 and abs(y2-y1) > 5 and zoomtype != 0:
  1104. if x1 > x2:
  1105. x1, x2 = x2, x1
  1106. if y1 > y2:
  1107. y1, y2 = y2, y1
  1108. # zoom in
  1109. if zoomtype > 0:
  1110. newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
  1111. newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
  1112. # zoom out
  1113. elif zoomtype < 0:
  1114. newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
  1115. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + 2 * \
  1116. (self.Map.width - x2),
  1117. self.Map.height + 2 * \
  1118. (self.Map.height - y2)))
  1119. # pan
  1120. elif zoomtype == 0:
  1121. dx = x1 - x2
  1122. dy = y1 - y2
  1123. if dx == 0 and dy == 0:
  1124. dx = x1 - self.Map.width / 2
  1125. dy = y1 - self.Map.height / 2
  1126. newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
  1127. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
  1128. self.Map.height + dy))
  1129. # if new region has been calculated, set the values
  1130. if newreg != {}:
  1131. # LL locations
  1132. if self.Map.projinfo['proj'] == 'll':
  1133. self.Map.region['n'] = min(self.Map.region['n'], 90.0)
  1134. self.Map.region['s'] = max(self.Map.region['s'], -90.0)
  1135. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  1136. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  1137. # calculate new center point and display resolution
  1138. self.Map.region['center_easting'] = ce
  1139. self.Map.region['center_northing'] = cn
  1140. self.Map.region['ewres'] = (newreg['e'] - newreg['w']) / self.Map.width
  1141. self.Map.region['nsres'] = (newreg['n'] - newreg['s']) / self.Map.height
  1142. if self._properties.alignExtent:
  1143. self.Map.AlignExtentFromDisplay()
  1144. else:
  1145. for k in ('n', 's', 'e', 'w'):
  1146. self.Map.region[k] = newreg[k]
  1147. if hasattr(self, "digit") and \
  1148. hasattr(self, "moveInfo"):
  1149. self._zoom(None)
  1150. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1151. self.Map.region['e'], self.Map.region['w'])
  1152. if self.redrawAll is False:
  1153. self.redrawAll = True
  1154. def ZoomBack(self):
  1155. """!Zoom to previous extents in zoomhistory list
  1156. Emits zoomChanged signal.
  1157. Emits zoomHistoryUnavailable signal when stack is empty.
  1158. """
  1159. Debug.msg(4, "BufferedWindow.ZoomBack(): hist)=%s" % self.zoomhistory)
  1160. zoom = list()
  1161. if len(self.zoomhistory) > 1:
  1162. self.zoomhistory.pop()
  1163. zoom = self.zoomhistory[-1]
  1164. if len(self.zoomhistory) < 2:
  1165. self.zoomHistoryUnavailable.emit()
  1166. # zoom to selected region
  1167. self.Map.GetRegion(n = zoom[0], s = zoom[1],
  1168. e = zoom[2], w = zoom[3],
  1169. update = True)
  1170. # update map
  1171. self.UpdateMap()
  1172. self.zoomChanged.emit()
  1173. def ZoomHistory(self, n, s, e, w):
  1174. """!Manages a list of last 10 zoom extents
  1175. Emits zoomChanged signal.
  1176. Emits zoomHistoryAvailable signal when stack is not empty.
  1177. Emits zoomHistoryUnavailable signal when stack is empty.
  1178. All methods which are changing zoom should call this method
  1179. to make a record in the history. The signal zoomChanged will be
  1180. then emitted automatically.
  1181. @param n,s,e,w north, south, east, west
  1182. @return removed history item if exists (or None)
  1183. """
  1184. removed = None
  1185. self.zoomhistory.append((n,s,e,w))
  1186. if len(self.zoomhistory) > 10:
  1187. removed = self.zoomhistory.pop(0)
  1188. if removed:
  1189. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
  1190. (self.zoomhistory, removed))
  1191. else:
  1192. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
  1193. (self.zoomhistory))
  1194. # update toolbar
  1195. if len(self.zoomhistory) > 1:
  1196. self.zoomHistoryAvailable.emit()
  1197. else:
  1198. self.zoomHistoryUnavailable.emit()
  1199. self.zoomChanged.emit()
  1200. return removed
  1201. def InitZoomHistory(self):
  1202. """Initializes zoom history.
  1203. @todo First item is handled in some special way. Improve the
  1204. documentation or fix the code.
  1205. It does not emits any signals.
  1206. This method can be possibly removed when the history will solve the
  1207. fist item in different way or when GCP manager (and possibly others)
  1208. will handle Map variable in the way that it will be prepared for
  1209. MapWindow/BufferedWindow and thus usable to initialize history.
  1210. """
  1211. self.zoomhistory.append((self.Map.region['n'],
  1212. self.Map.region['s'],
  1213. self.Map.region['e'],
  1214. self.Map.region['w']))
  1215. Debug.msg(4, "BufferedWindow.InitZoomHistory(): hist=%s" %
  1216. (self.zoomhistory))
  1217. def ResetZoomHistory(self):
  1218. """!Reset zoom history"""
  1219. self.zoomhistory = list()
  1220. def ZoomToMap(self, layers = None, ignoreNulls = False, render = True):
  1221. """!Set display extents to match selected raster
  1222. or vector map(s).
  1223. @param layers list of layers to be zoom to
  1224. @param ignoreNulls True to ignore null-values (valid only for rasters)
  1225. @param render True to re-render display
  1226. """
  1227. if not layers:
  1228. layers = self._giface.GetLayerList().GetSelectedLayers(checkedOnly=False)
  1229. layers = [layer.maplayer for layer in layers]
  1230. if not layers:
  1231. return
  1232. rast = []
  1233. vect = []
  1234. updated = False
  1235. for l in layers:
  1236. # only raster/vector layers are currently supported
  1237. if l.type == 'raster':
  1238. rast.append(l.GetName())
  1239. elif l.type == 'vector':
  1240. if hasattr(self, "digit") and \
  1241. self.toolbar.GetLayer() == l:
  1242. w, s, b, e, n, t = self.digit.GetDisplay().GetMapBoundingBox()
  1243. self.Map.GetRegion(n = n, s = s, w = w, e = e,
  1244. update = True)
  1245. updated = True
  1246. else:
  1247. vect.append(l.name)
  1248. elif l.type == 'rgb':
  1249. for rname in l.GetName().splitlines():
  1250. rast.append(rname)
  1251. if not updated:
  1252. self.Map.GetRegion(rast = rast,
  1253. vect = vect,
  1254. zoom = ignoreNulls,
  1255. update = True)
  1256. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1257. self.Map.region['e'], self.Map.region['w'])
  1258. if render:
  1259. self.UpdateMap()
  1260. def ZoomToWind(self):
  1261. """!Set display geometry to match computational region
  1262. settings (set with g.region)
  1263. """
  1264. self.Map.region = self.Map.GetRegion()
  1265. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1266. self.Map.region['e'], self.Map.region['w'])
  1267. self.UpdateMap()
  1268. def ZoomToDefault(self):
  1269. """!Set display geometry to match default region settings
  1270. """
  1271. self.Map.region = self.Map.GetRegion(default = True)
  1272. self.Map.AdjustRegion() # aling region extent to the display
  1273. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1274. self.Map.region['e'], self.Map.region['w'])
  1275. self.UpdateMap()
  1276. def GoTo(self, e, n):
  1277. region = self.Map.GetCurrentRegion()
  1278. region['center_easting'], region['center_northing'] = e, n
  1279. dn = (region['nsres'] * region['rows']) / 2.
  1280. region['n'] = region['center_northing'] + dn
  1281. region['s'] = region['center_northing'] - dn
  1282. de = (region['ewres'] * region['cols']) / 2.
  1283. region['e'] = region['center_easting'] + de
  1284. region['w'] = region['center_easting'] - de
  1285. self.Map.AdjustRegion()
  1286. # add to zoom history
  1287. self.ZoomHistory(region['n'], region['s'],
  1288. region['e'], region['w'])
  1289. self.UpdateMap()
  1290. def DisplayToWind(self):
  1291. """!Set computational region (WIND file) to match display
  1292. extents
  1293. """
  1294. tmpreg = os.getenv("GRASS_REGION")
  1295. if tmpreg:
  1296. del os.environ["GRASS_REGION"]
  1297. # We ONLY want to set extents here. Don't mess with resolution. Leave that
  1298. # for user to set explicitly with g.region
  1299. new = self.Map.AlignResolution()
  1300. RunCommand('g.region',
  1301. parent = self,
  1302. overwrite = True,
  1303. n = new['n'],
  1304. s = new['s'],
  1305. e = new['e'],
  1306. w = new['w'],
  1307. rows = int(new['rows']),
  1308. cols = int(new['cols']))
  1309. if tmpreg:
  1310. os.environ["GRASS_REGION"] = tmpreg
  1311. def ZoomToSaved(self):
  1312. """!Set display geometry to match extents in
  1313. saved region file
  1314. """
  1315. dlg = SavedRegion(parent = self,
  1316. title = _("Zoom to saved region extents"),
  1317. loadsave = 'load')
  1318. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.GetName():
  1319. dlg.Destroy()
  1320. return
  1321. if not grass.find_file(name = dlg.GetName(), element = 'windows')['name']:
  1322. wx.MessageBox(parent = self,
  1323. message = _("Region <%s> not found. Operation canceled.") % dlg.GetName(),
  1324. caption = _("Error"), style = wx.ICON_ERROR | wx.OK | wx.CENTRE)
  1325. dlg.Destroy()
  1326. return
  1327. self.Map.GetRegion(regionName = dlg.GetName(),
  1328. update = True)
  1329. dlg.Destroy()
  1330. self.ZoomHistory(self.Map.region['n'],
  1331. self.Map.region['s'],
  1332. self.Map.region['e'],
  1333. self.Map.region['w'])
  1334. self.UpdateMap()
  1335. def SaveRegion(self, display = True):
  1336. """!Save display extents/compulational region to named region
  1337. file.
  1338. @param display True for display extends otherwise computational region
  1339. """
  1340. if display:
  1341. title = _("Save display extents to region file")
  1342. else:
  1343. title = _("Save computational region to region file")
  1344. dlg = SavedRegion(parent = self, title = title, loadsave = 'save')
  1345. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.GetName():
  1346. dlg.Destroy()
  1347. return
  1348. # test to see if it already exists and ask permission to overwrite
  1349. if grass.find_file(name = dlg.GetName(), element = 'windows')['name']:
  1350. overwrite = wx.MessageBox(parent = self,
  1351. message = _("Region file <%s> already exists. "
  1352. "Do you want to overwrite it?") % (dlg.GetName()),
  1353. caption = _("Warning"), style = wx.YES_NO | wx.CENTRE)
  1354. if overwrite != wx.YES:
  1355. dlg.Destroy()
  1356. return
  1357. if display:
  1358. self._saveDisplayRegion(dlg.GetName())
  1359. else:
  1360. self._saveCompRegion(dlg.GetName())
  1361. dlg.Destroy()
  1362. def _saveCompRegion(self, name):
  1363. """!Save region settings to region file
  1364. @param name region name
  1365. """
  1366. RunCommand('g.region',
  1367. overwrite = True,
  1368. parent = self,
  1369. flags = 'u',
  1370. save = name)
  1371. def _saveDisplayRegion(self, name):
  1372. """!Save display extents to region file
  1373. @param name region name
  1374. """
  1375. new = self.Map.GetCurrentRegion()
  1376. tmpreg = os.getenv("GRASS_REGION")
  1377. if tmpreg:
  1378. del os.environ["GRASS_REGION"]
  1379. RunCommand('g.region',
  1380. overwrite = True,
  1381. parent = self,
  1382. flags = 'u',
  1383. n = new['n'],
  1384. s = new['s'],
  1385. e = new['e'],
  1386. w = new['w'],
  1387. rows = int(new['rows']),
  1388. cols = int(new['cols']),
  1389. save = name)
  1390. if tmpreg:
  1391. os.environ["GRASS_REGION"] = tmpreg
  1392. def Distance(self, beginpt, endpt, screen = True):
  1393. """!Calculates distance
  1394. Ctypes required for LL-locations
  1395. @param beginpt first point
  1396. @param endpt second point
  1397. @param screen True for screen coordinates otherwise EN
  1398. """
  1399. if screen:
  1400. e1, n1 = self.Pixel2Cell(beginpt)
  1401. e2, n2 = self.Pixel2Cell(endpt)
  1402. else:
  1403. e1, n1 = beginpt
  1404. e2, n2 = endpt
  1405. dEast = (e2 - e1)
  1406. dNorth = (n2 - n1)
  1407. if self.Map.projinfo['proj'] == 'll' and haveCtypes:
  1408. dist = gislib.G_distance(e1, n1, e2, n2)
  1409. else:
  1410. dist = math.sqrt(math.pow((dEast), 2) + math.pow((dNorth), 2))
  1411. return (dist, (dEast, dNorth))
  1412. def GetMap(self):
  1413. """!Get render.Map() instance"""
  1414. return self.Map
  1415. def RegisterGraphicsToDraw(self, graphicsType, setStatusFunc = None, drawFunc = None):
  1416. """! This method registers graphics to draw.
  1417. @param type (string) - graphics type: "point" or "line"
  1418. @param setStatusFunc (function reference) - function called before drawing each item
  1419. Status function should be in this form: setStatusFunc(item, itemOrderNum)
  1420. item - passes instance of GraphicsSetItem which will be drawn
  1421. itemOrderNum - number of item in drawing order (from O)
  1422. Hidden items are also counted in drawing order.
  1423. @param drawFunc (function reference) - defines own function for drawing
  1424. If function is not defined DrawCross method is used for type "point"
  1425. or DrawLines method for type "line".
  1426. @return reference to GraphicsSet, which was added.
  1427. """
  1428. item = GraphicsSet(parentMapWin = self,
  1429. graphicsType = graphicsType,
  1430. setStatusFunc = setStatusFunc,
  1431. drawFunc = drawFunc)
  1432. self.graphicsSetList.append(item)
  1433. return item
  1434. def UnregisterGraphicsToDraw(self, item):
  1435. """!Unregisteres GraphicsSet instance
  1436. @param item (GraphicsSetItem) - item to unregister
  1437. @return True - if item was unregistered
  1438. @return False - if item was not found
  1439. """
  1440. if item in self.graphicsSetList:
  1441. self.graphicsSetList.remove(item)
  1442. return True
  1443. return False
  1444. class GraphicsSet:
  1445. def __init__(self, parentMapWin, graphicsType, setStatusFunc = None, drawFunc = None):
  1446. """!Class, which contains instances of GraphicsSetItem and
  1447. draws them For description of parameters look at method
  1448. RegisterGraphicsToDraw in BufferedWindow class.
  1449. """
  1450. self.pens = {
  1451. "default" : wx.Pen(colour = wx.BLACK, width = 2, style = wx.SOLID),
  1452. "selected" : wx.Pen(colour = wx.GREEN, width = 2, style = wx.SOLID),
  1453. "unused" : wx.Pen(colour = wx.LIGHT_GREY, width = 2, style = wx.SOLID),
  1454. "highest" : wx.Pen(colour = wx.RED, width = 2, style = wx.SOLID)
  1455. }
  1456. # list contains instances of GraphicsSetItem
  1457. self.itemsList = []
  1458. self.properties = {}
  1459. self.graphicsType = graphicsType
  1460. self.parentMapWin = parentMapWin
  1461. self.setStatusFunc = setStatusFunc
  1462. if drawFunc:
  1463. self.drawFunc = drawFunc
  1464. elif self.graphicsType == "point":
  1465. self.properties["size"] = 5
  1466. self.properties["text"] = {}
  1467. self.properties["text"]['font'] = wx.Font(pointSize = self.properties["size"],
  1468. family = wx.FONTFAMILY_DEFAULT,
  1469. style = wx.FONTSTYLE_NORMAL,
  1470. weight = wx.FONTWEIGHT_NORMAL)
  1471. self.properties["text"]['active'] = True
  1472. self.drawFunc = self.parentMapWin.DrawCross
  1473. elif self.graphicsType == "line":
  1474. self.drawFunc = self.parentMapWin.DrawLines
  1475. def Draw(self, pdc):
  1476. """!Draws all containing items.
  1477. @param pdc - device context, where items are drawn
  1478. """
  1479. itemOrderNum = 0
  1480. for item in self.itemsList:
  1481. if self.setStatusFunc is not None:
  1482. self.setStatusFunc(item, itemOrderNum)
  1483. if item.GetPropertyVal("hide") == True:
  1484. itemOrderNum += 1
  1485. continue
  1486. if self.graphicsType == "point":
  1487. if item.GetPropertyVal("penName"):
  1488. self.parentMapWin.pen = self.pens[item.GetPropertyVal("penName")]
  1489. else:
  1490. self.parentMapWin.pen = self.pens["default"]
  1491. coords = self.parentMapWin.Cell2Pixel(item.GetCoords())
  1492. size = self.properties["size"]
  1493. self.properties["text"]['coords'] = [coords[0] + size, coords[1] + size, size, size]
  1494. self.properties["text"]['color'] = self.parentMapWin.pen.GetColour()
  1495. self.properties["text"]['text'] = item.GetPropertyVal("label")
  1496. self.drawFunc(pdc = pdc,
  1497. coords = coords,
  1498. text = self.properties["text"],
  1499. size = self.properties["size"])
  1500. elif self.graphicsType == "line":
  1501. if item.GetPropertyVal("penName"):
  1502. self.parentMapWin.polypen = self.pens[item.GetPropertyVal("penName")]
  1503. else:
  1504. self.parentMapWin.polypen = self.pens["default"]
  1505. coords = item.GetCoords()
  1506. self.drawFunc(pdc = pdc,
  1507. polycoords = coords)
  1508. itemOrderNum += 1
  1509. def AddItem(self, coords, penName = None, label = None, hide = False):
  1510. """!Append item to the list.
  1511. Added item is put to the last place in drawing order.
  1512. Could be 'point' or 'line' according to graphicsType.
  1513. @param coords - list of east, north coordinates (double) of item
  1514. Example: point: [1023, 122]
  1515. line: [[10, 12],[20,40],[23, 2334]]
  1516. @param penName (string) - the 'default' pen is used if is not defined
  1517. @param label (string) - label, which will be drawn with point. It is relavant just for 'point' type.
  1518. @param hide (bool) - If it is True, the item is not drawn, when self.Draw is called.
  1519. Hidden items are also counted in drawing order.
  1520. @return (GraphicsSetItem) - added item reference
  1521. """
  1522. item = GraphicsSetItem(coords = coords, penName = penName, label = label, hide = hide)
  1523. self.itemsList.append(item)
  1524. return item
  1525. def DeleteItem(self, item):
  1526. """!Deletes item
  1527. @param item (GraphicsSetItem) - item to remove
  1528. @return True if item was removed
  1529. @return False if item was not found
  1530. """
  1531. try:
  1532. self.itemsList.remove(item)
  1533. except ValueError:
  1534. return False
  1535. return True
  1536. def GetAllItems(self):
  1537. """!Returns list of all containing instances of GraphicsSetItem, in order
  1538. as they are drawn. If you want to change order of drawing use: SetItemDrawOrder method.
  1539. """
  1540. # user can edit objects but not order in list, that is reason,
  1541. # why is returned shallow copy of data list it should be used
  1542. # SetItemDrawOrder for changing order
  1543. return copy(self.itemsList)
  1544. def GetItem(self, drawNum):
  1545. """!Get given item from the list.
  1546. @param drawNum (int) - drawing order (index) number of item
  1547. @return instance of GraphicsSetItem which is drawn in drawNum order
  1548. @return False if drawNum was out of range
  1549. """
  1550. if drawNum < len(self.itemsList) and drawNum >= 0:
  1551. return self.itemsList[drawNum]
  1552. else:
  1553. return False
  1554. def SetPropertyVal(self, propName, propVal):
  1555. """!Set property value
  1556. @param propName (string) - property name: "size", "text"
  1557. - both properties are relevant for "point" type
  1558. @param propVal - property value to be set
  1559. @return True - if value was set
  1560. @return False - if propName is not "size" or "text" or type is "line"
  1561. """
  1562. if self.properties.has_key(propName):
  1563. self.properties[propName] = propVal
  1564. return True
  1565. return False
  1566. def GetPropertyVal(self, propName):
  1567. """!Get property value
  1568. Raises KeyError if propName is not "size" or "text" or type is
  1569. "line"
  1570. @param propName (string) - property name: "size", "text"
  1571. - both properties are relevant for "point" type
  1572. @return value of property
  1573. """
  1574. if self.properties.has_key(propName):
  1575. return self.properties[propName]
  1576. raise KeyError(_("Property does not exist: %s") % (propName))
  1577. def AddPen(self, penName, pen):
  1578. """!Add pen
  1579. @param penName (string) - name of added pen
  1580. @param pen (wx.Pen) - added pen
  1581. @return True - if pen was added
  1582. @return False - if pen already exists
  1583. """
  1584. if self.pens.has_key(penName):
  1585. return False
  1586. self.pens[penName] = pen
  1587. return True
  1588. def GetPen(self, penName):
  1589. """!Get existing pen
  1590. @param penName (string) - name of pen
  1591. @return wx.Pen reference if is found
  1592. @return None if penName was not found
  1593. """
  1594. if self.pens.has_key(penName):
  1595. return self.pens[penName]
  1596. return None
  1597. def SetItemDrawOrder(self, item, drawNum):
  1598. """!Set draw order for item
  1599. @param item (GraphicsSetItem)
  1600. @param drawNum (int) - drawing order of item to be set
  1601. @return True - if order was changed
  1602. @return False - if drawNum is out of range or item was not found
  1603. """
  1604. if drawNum < len(self.itemsList) and drawNum >= 0 and \
  1605. item in self.itemsList:
  1606. self.itemsList.insert(drawNum, self.itemsList.pop(self.itemsList.index(item)))
  1607. return True
  1608. return False
  1609. def GetItemDrawOrder(self, item):
  1610. """!Get draw order for given item
  1611. @param item (GraphicsSetItem)
  1612. @return (int) - drawing order of item
  1613. @return None - if item was not found
  1614. """
  1615. try:
  1616. return self.itemsList.index(item)
  1617. except ValueError:
  1618. return None
  1619. class GraphicsSetItem:
  1620. def __init__(self, coords, penName = None, label = None, hide = False):
  1621. """!Could be point or line according to graphicsType in
  1622. GraphicsSet class
  1623. @param coords - list of coordinates (double) of item
  1624. Example: point: [1023, 122]
  1625. line: [[10, 12],[20,40],[23, 2334]]
  1626. @param penName (string) - if it is not defined 'default' pen is used
  1627. @param label (string) - label, which will be drawn with point. It is relevant just for 'point' type
  1628. @param hide (bool) - if it is True, item is not drawn
  1629. Hidden items are also counted in drawing order in GraphicsSet class.
  1630. """
  1631. self.coords = coords
  1632. self.properties = { "penName" : penName,
  1633. "hide" : hide,
  1634. "label" : label }
  1635. def SetPropertyVal(self, propName, propVal):
  1636. """!Set property value
  1637. @param propName (string) - property name: "penName", "hide" or "label"
  1638. - property "label" is relevant just for 'point' type
  1639. @param propVal - property value to be set
  1640. @return True - if value was set
  1641. @return False - if propName is not "penName", "hide" or "label"
  1642. """
  1643. if self.properties.has_key(propName):
  1644. self.properties[propName] = propVal
  1645. return True
  1646. return False
  1647. def GetPropertyVal(self, propName):
  1648. """!Get property value
  1649. Raises KeyError if propName is not "penName", "hide" or
  1650. "label".
  1651. @param propName (string) - property name: "penName", "hide" or "label"
  1652. - property "label" is relevant just for 'point' type
  1653. @return value of property
  1654. """
  1655. if self.properties.has_key(propName):
  1656. return self.properties[propName]
  1657. raise KeyError(_("Property does not exist: %s") % (propName))
  1658. def SetCoords(self, coords):
  1659. """!Set coordinates of item
  1660. @param coords - list of east, north coordinates (double) of item
  1661. Example: point: [1023, 122]
  1662. line: [[10, 12],[20,40],[23, 2334]]
  1663. """
  1664. self.coords = coords
  1665. def GetCoords(self):
  1666. """!Get item coordinates
  1667. @returns coordinates
  1668. """
  1669. return self.coords