mapwindow.py 77 KB

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