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