mapwindow.py 75 KB

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