mapwindow.py 76 KB

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