mapwindow.py 77 KB

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