mapwindow.py 77 KB

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