mapwindow.py 77 KB

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