mapwindow.py 75 KB

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