mapwindow.py 76 KB

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