buffered.py 68 KB

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