mapwindow.py 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119
  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. if wheel > 0:
  802. zoomtype = 1
  803. else:
  804. zoomtype = -1
  805. if UserSettings.Get(group = 'display',
  806. key = 'scrollDirection',
  807. subkey = 'selection'):
  808. zoomtype *= -1
  809. # zoom 1/2 of the screen (TODO: settings)
  810. if zoomBehaviour == 0: # zoom and recenter
  811. if zoomtype > 0:
  812. begin = (current[0] - self.Map.width / 4,
  813. current[1] - self.Map.height / 4)
  814. end = (current[0] + self.Map.width / 4,
  815. current[1] + self.Map.height / 4)
  816. else:
  817. begin = ((self.Map.width - current[0]) / 2,
  818. (self.Map.height - current[1]) / 2)
  819. end = (begin[0] + self.Map.width / 2,
  820. begin[1] + self.Map.height / 2)
  821. elif zoomBehaviour == 1: # zoom to current cursor position
  822. begin = (current[0]/2, current[1]/2)
  823. end = ((self.Map.width - current[0])/2 + current[0],
  824. (self.Map.height - current[1])/2 + current[1])
  825. # zoom
  826. self.Zoom(begin, end, zoomtype)
  827. # redraw map
  828. self.UpdateMap()
  829. # update statusbar
  830. self.parent.StatusbarUpdate()
  831. self.Refresh()
  832. self.processMouse = True
  833. def OnDragging(self, event):
  834. """!Mouse dragging
  835. """
  836. Debug.msg (5, "BufferedWindow.MouseAction(): Dragging")
  837. current = event.GetPositionTuple()[:]
  838. previous = self.mouse['begin']
  839. move = (current[0] - previous[0],
  840. current[1] - previous[1])
  841. if hasattr(self, "digit"):
  842. digitToolbar = self.toolbar
  843. else:
  844. digitToolbar = None
  845. # dragging or drawing box with left button
  846. if self.mouse['use'] == 'pan' or \
  847. event.MiddleIsDown():
  848. self.DragMap(move)
  849. # dragging decoration overlay item
  850. elif (self.mouse['use'] == 'pointer' and
  851. not digitToolbar and
  852. self.dragid != None):
  853. self.DragItem(self.dragid, event)
  854. # dragging anything else - rubber band box or line
  855. else:
  856. if (self.mouse['use'] == 'pointer' and
  857. not digitToolbar):
  858. return
  859. self.mouse['end'] = event.GetPositionTuple()[:]
  860. if (event.LeftIsDown() and
  861. not (digitToolbar and
  862. digitToolbar.GetAction() in ("moveLine",) and
  863. self.digit.GetDisplay().GetSelected() > 0)):
  864. self.MouseDraw(pdc = self.pdcTmp)
  865. def OnLeftDown(self, event):
  866. """!Left mouse button pressed
  867. """
  868. Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
  869. self.mouse["use"])
  870. self.mouse['begin'] = event.GetPositionTuple()[:]
  871. if self.mouse["use"] in ["measure", "profile"]:
  872. # measure or profile
  873. if len(self.polycoords) == 0:
  874. self.mouse['end'] = self.mouse['begin']
  875. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  876. self.ClearLines(pdc=self.pdcTmp)
  877. else:
  878. self.mouse['begin'] = self.mouse['end']
  879. elif self.mouse['use'] in ('zoom', 'legend'):
  880. pass
  881. # vector digizer
  882. elif self.mouse["use"] == "pointer" and \
  883. hasattr(self, "digit"):
  884. if event.ControlDown():
  885. self.OnLeftDownUndo(event)
  886. else:
  887. self._onLeftDown(event)
  888. elif self.mouse['use'] == 'pointer':
  889. # get decoration or text id
  890. self.idlist = []
  891. self.dragid = ''
  892. self.lastpos = self.mouse['begin']
  893. idlist = self.pdc.FindObjects(self.lastpos[0], self.lastpos[1],
  894. self.hitradius)
  895. if 99 in idlist:
  896. idlist.remove(99)
  897. if idlist != []:
  898. self.dragid = idlist[0] #drag whatever is on top
  899. else:
  900. pass
  901. event.Skip()
  902. def OnLeftUp(self, event):
  903. """!Left mouse button released
  904. """
  905. Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
  906. self.mouse["use"])
  907. self.mouse['end'] = event.GetPositionTuple()[:]
  908. if self.mouse['use'] in ["zoom", "pan"]:
  909. # set region in zoom or pan
  910. begin = self.mouse['begin']
  911. end = self.mouse['end']
  912. if self.mouse['use'] == 'zoom':
  913. # set region for click (zero-width box)
  914. if begin[0] - end[0] == 0 or \
  915. begin[1] - end[1] == 0:
  916. # zoom 1/2 of the screen (TODO: settings)
  917. begin = (end[0] - self.Map.width / 4,
  918. end[1] - self.Map.height / 4)
  919. end = (end[0] + self.Map.width / 4,
  920. end[1] + self.Map.height / 4)
  921. self.Zoom(begin, end, self.zoomtype)
  922. # redraw map
  923. self.UpdateMap(render = True)
  924. # update statusbar
  925. self.parent.StatusbarUpdate()
  926. elif self.mouse["use"] == "query":
  927. # querying
  928. layers = self.GetSelectedLayer(multi = True)
  929. isRaster = False
  930. nVectors = 0
  931. for l in layers:
  932. if l.GetType() == 'raster':
  933. isRaster = True
  934. break
  935. if l.GetType() == 'vector':
  936. nVectors += 1
  937. if isRaster or nVectors > 1:
  938. self.parent.QueryMap(self.mouse['begin'][0],self.mouse['begin'][1])
  939. else:
  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"] == "queryVector":
  944. # editable mode for vector map layers
  945. self.parent.QueryVector(self.mouse['begin'][0], self.mouse['begin'][1])
  946. # clear temp canvas
  947. self.UpdateMap(render = False, renderVector = False)
  948. elif self.mouse["use"] in ["measure", "profile"]:
  949. # measure or profile
  950. if self.mouse["use"] == "measure":
  951. self.parent.MeasureDist(self.mouse['begin'], self.mouse['end'])
  952. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  953. self.ClearLines(pdc = self.pdcTmp)
  954. self.DrawLines(pdc = self.pdcTmp)
  955. elif self.mouse["use"] == "pointer" and \
  956. not self.parent.IsStandalone() and \
  957. self.parent.GetLayerManager().gcpmanagement:
  958. # -> GCP manager
  959. if self.parent.GetToolbar('gcpdisp'):
  960. coord = self.Pixel2Cell(self.mouse['end'])
  961. if self.parent.MapWindow == self.parent.SrcMapWindow:
  962. coordtype = 'source'
  963. else:
  964. coordtype = 'target'
  965. self.parent.GetLayerManager().gcpmanagement.SetGCPData(coordtype, coord, self, confirm = True)
  966. self.UpdateMap(render = False, renderVector = False)
  967. elif self.mouse["use"] == "pointer" and \
  968. hasattr(self, "digit"):
  969. self._onLeftUp(event)
  970. elif (self.mouse['use'] == 'pointer' and
  971. self.dragid >= 0):
  972. # end drag of overlay decoration
  973. if self.dragid < 99 and self.dragid in self.overlays:
  974. self.overlays[self.dragid]['coords'] = self.pdc.GetIdBounds(self.dragid)
  975. elif self.dragid > 100 and self.dragid in self.textdict:
  976. self.textdict[self.dragid]['bbox'] = self.pdc.GetIdBounds(self.dragid)
  977. else:
  978. pass
  979. self.dragid = None
  980. self.currtxtid = None
  981. elif self.mouse['use'] == 'legend':
  982. self.ResizeLegend(self.mouse["begin"], self.mouse["end"])
  983. self.parent.dialogs['legend'].FindWindowByName("resize").SetValue(False)
  984. self.Map.GetOverlay(1).SetActive(True)
  985. self.parent.MapWindow.SetCursor(self.parent.cursors["default"])
  986. self.parent.MapWindow.mouse['use'] = 'pointer'
  987. self.UpdateMap()
  988. def OnButtonDClick(self, event):
  989. """!Mouse button double click
  990. """
  991. Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
  992. self.mouse["use"])
  993. if self.mouse["use"] == "measure":
  994. # measure
  995. self.ClearLines(pdc=self.pdcTmp)
  996. self.polycoords = []
  997. self.mouse['use'] = 'pointer'
  998. self.mouse['box'] = 'point'
  999. self.mouse['end'] = [0, 0]
  1000. self.Refresh()
  1001. self.SetCursor(self.parent.cursors["default"])
  1002. elif self.mouse["use"] != "profile" or \
  1003. (self.mouse['use'] != 'pointer' and \
  1004. hasattr(self, "digit")):
  1005. # select overlay decoration options dialog
  1006. clickposition = event.GetPositionTuple()[:]
  1007. idlist = self.pdc.FindObjects(clickposition[0], clickposition[1], self.hitradius)
  1008. if idlist == []:
  1009. return
  1010. self.dragid = idlist[0]
  1011. # self.ovlcoords[self.dragid] = self.pdc.GetIdBounds(self.dragid)
  1012. if self.dragid > 100:
  1013. self.currtxtid = self.dragid
  1014. self.parent.OnAddText(None)
  1015. elif self.dragid == 0:
  1016. self.parent.OnAddBarscale(None)
  1017. elif self.dragid == 1:
  1018. self.parent.OnAddLegend(None)
  1019. def OnRightDown(self, event):
  1020. """!Right mouse button pressed
  1021. """
  1022. Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
  1023. self.mouse["use"])
  1024. if hasattr(self, "digit"):
  1025. self._onRightDown(event)
  1026. event.Skip()
  1027. def OnRightUp(self, event):
  1028. """!Right mouse button released
  1029. """
  1030. Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
  1031. self.mouse["use"])
  1032. if hasattr(self, "digit"):
  1033. self._onRightUp(event)
  1034. self.redrawAll = True
  1035. self.Refresh()
  1036. event.Skip()
  1037. def OnMiddleDown(self, event):
  1038. """!Middle mouse button pressed
  1039. """
  1040. if not event:
  1041. return
  1042. self.mouse['begin'] = event.GetPositionTuple()[:]
  1043. def OnMiddleUp(self, event):
  1044. """!Middle mouse button released
  1045. """
  1046. self.mouse['end'] = event.GetPositionTuple()[:]
  1047. # set region in zoom or pan
  1048. begin = self.mouse['begin']
  1049. end = self.mouse['end']
  1050. self.Zoom(begin, end, 0) # no zoom
  1051. # redraw map
  1052. self.UpdateMap(render = True)
  1053. # update statusbar
  1054. self.parent.StatusbarUpdate()
  1055. def OnMouseEnter(self, event):
  1056. """!Mouse entered window and no mouse buttons were pressed
  1057. """
  1058. if not self.parent.IsStandalone() and \
  1059. self.parent.GetLayerManager().gcpmanagement:
  1060. if self.parent.GetToolbar('gcpdisp'):
  1061. if not self.parent.MapWindow == self:
  1062. self.parent.MapWindow = self
  1063. self.parent.Map = self.Map
  1064. self.parent.UpdateActive(self)
  1065. # needed for wingrass
  1066. self.SetFocus()
  1067. else:
  1068. event.Skip()
  1069. def OnMouseMoving(self, event):
  1070. """!Motion event and no mouse buttons were pressed
  1071. """
  1072. if self.mouse["use"] == "pointer" and \
  1073. hasattr(self, "digit"):
  1074. self._onMouseMoving(event)
  1075. event.Skip()
  1076. def ClearLines(self, pdc = None):
  1077. """!Clears temporary drawn lines from PseudoDC
  1078. """
  1079. if not pdc:
  1080. pdc = self.pdcTmp
  1081. try:
  1082. pdc.ClearId(self.lineid)
  1083. pdc.RemoveId(self.lineid)
  1084. except:
  1085. pass
  1086. try:
  1087. pdc.ClearId(self.plineid)
  1088. pdc.RemoveId(self.plineid)
  1089. except:
  1090. pass
  1091. Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
  1092. (self.lineid, self.plineid))
  1093. return True
  1094. def Pixel2Cell(self, (x, y)):
  1095. """!Convert image coordinates to real word coordinates
  1096. @param x, y image coordinates
  1097. @return easting, northing
  1098. @return None on error
  1099. """
  1100. try:
  1101. x = int(x)
  1102. y = int(y)
  1103. except:
  1104. return None
  1105. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1106. res = self.Map.region["ewres"]
  1107. else:
  1108. res = self.Map.region["nsres"]
  1109. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1110. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1111. east = w + x * res
  1112. north = n - y * res
  1113. return (east, north)
  1114. def Cell2Pixel(self, (east, north)):
  1115. """!Convert real word coordinates to image coordinates
  1116. """
  1117. try:
  1118. east = float(east)
  1119. north = float(north)
  1120. except:
  1121. return None
  1122. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1123. res = self.Map.region["ewres"]
  1124. else:
  1125. res = self.Map.region["nsres"]
  1126. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1127. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1128. x = (east - w) / res
  1129. y = (n - north) / res
  1130. return (x, y)
  1131. def ResizeLegend(self, begin, end):
  1132. w = abs(begin[0] - end[0])
  1133. h = abs(begin[1] - end[1])
  1134. if begin[0] < end[0]:
  1135. x = begin[0]
  1136. else:
  1137. x = end[0]
  1138. if begin[1] < end[1]:
  1139. y = begin[1]
  1140. else:
  1141. y = end[1]
  1142. screenRect = wx.Rect(x, y, w, h)
  1143. screenSize = self.GetClientSizeTuple()
  1144. at = [(screenSize[1] - (y + h)) / float(screenSize[1]) * 100,
  1145. (screenSize[1] - y) / float(screenSize[1]) * 100,
  1146. x / float(screenSize[0]) * 100,
  1147. (x + w) / float(screenSize[0]) * 100]
  1148. for i, subcmd in enumerate(self.overlays[1]['cmd']):
  1149. if subcmd.startswith('at='):
  1150. self.overlays[1]['cmd'][i] = "at=%d,%d,%d,%d" % (at[0], at[1], at[2], at[3])
  1151. self.Map.ChangeOverlay(1, True, command = self.overlays[1]['cmd'])
  1152. self.overlays[1]['coords'] = (0,0)
  1153. def Zoom(self, begin, end, zoomtype):
  1154. """!Calculates new region while (un)zoom/pan-ing
  1155. """
  1156. x1, y1 = begin
  1157. x2, y2 = end
  1158. newreg = {}
  1159. # threshold - too small squares do not make sense
  1160. # can only zoom to windows of > 5x5 screen pixels
  1161. if abs(x2-x1) > 5 and abs(y2-y1) > 5 and zoomtype != 0:
  1162. if x1 > x2:
  1163. x1, x2 = x2, x1
  1164. if y1 > y2:
  1165. y1, y2 = y2, y1
  1166. # zoom in
  1167. if zoomtype > 0:
  1168. newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
  1169. newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
  1170. # zoom out
  1171. elif zoomtype < 0:
  1172. newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
  1173. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + 2 * \
  1174. (self.Map.width - x2),
  1175. self.Map.height + 2 * \
  1176. (self.Map.height - y2)))
  1177. # pan
  1178. elif zoomtype == 0:
  1179. dx = x1 - x2
  1180. dy = y1 - y2
  1181. if dx == 0 and dy == 0:
  1182. dx = x1 - self.Map.width / 2
  1183. dy = y1 - self.Map.height / 2
  1184. newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
  1185. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
  1186. self.Map.height + dy))
  1187. # if new region has been calculated, set the values
  1188. if newreg != {}:
  1189. # LL locations
  1190. if self.Map.projinfo['proj'] == 'll':
  1191. self.Map.region['n'] = min(self.Map.region['n'], 90.0)
  1192. self.Map.region['s'] = max(self.Map.region['s'], -90.0)
  1193. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  1194. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  1195. # calculate new center point and display resolution
  1196. self.Map.region['center_easting'] = ce
  1197. self.Map.region['center_northing'] = cn
  1198. self.Map.region['ewres'] = (newreg['e'] - newreg['w']) / self.Map.width
  1199. self.Map.region['nsres'] = (newreg['n'] - newreg['s']) / self.Map.height
  1200. if not self.parent.HasProperty('alignExtent') or \
  1201. self.parent.GetProperty('alignExtent'):
  1202. self.Map.AlignExtentFromDisplay()
  1203. else:
  1204. for k in ('n', 's', 'e', 'w'):
  1205. self.Map.region[k] = newreg[k]
  1206. if hasattr(self, "digit") and \
  1207. hasattr(self, "moveInfo"):
  1208. self._zoom(None)
  1209. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1210. self.Map.region['e'], self.Map.region['w'])
  1211. if self.redrawAll is False:
  1212. self.redrawAll = True
  1213. def ZoomBack(self):
  1214. """!Zoom to previous extents in zoomhistory list
  1215. """
  1216. zoom = list()
  1217. if len(self.zoomhistory) > 1:
  1218. self.zoomhistory.pop()
  1219. zoom = self.zoomhistory[-1]
  1220. # disable tool if stack is empty
  1221. if len(self.zoomhistory) < 2: # disable tool
  1222. toolbar = self.parent.GetMapToolbar()
  1223. toolbar.Enable('zoomBack', enable = False)
  1224. # zoom to selected region
  1225. self.Map.GetRegion(n = zoom[0], s = zoom[1],
  1226. e = zoom[2], w = zoom[3],
  1227. update = True)
  1228. # update map
  1229. self.UpdateMap()
  1230. # update statusbar
  1231. self.parent.StatusbarUpdate()
  1232. def ZoomHistory(self, n, s, e, w):
  1233. """!Manages a list of last 10 zoom extents
  1234. @param n,s,e,w north, south, east, west
  1235. @return removed history item if exists (or None)
  1236. """
  1237. removed = None
  1238. self.zoomhistory.append((n,s,e,w))
  1239. if len(self.zoomhistory) > 10:
  1240. removed = self.zoomhistory.pop(0)
  1241. if removed:
  1242. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
  1243. (self.zoomhistory, removed))
  1244. else:
  1245. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
  1246. (self.zoomhistory))
  1247. # update toolbar
  1248. if len(self.zoomhistory) > 1:
  1249. enable = True
  1250. else:
  1251. enable = False
  1252. toolbar = self.parent.GetMapToolbar()
  1253. toolbar.Enable('zoomBack', enable)
  1254. return removed
  1255. def ResetZoomHistory(self):
  1256. """!Reset zoom history"""
  1257. self.zoomhistory = list()
  1258. def ZoomToMap(self, layers = None, ignoreNulls = False, render = True):
  1259. """!Set display extents to match selected raster
  1260. or vector map(s).
  1261. @param layers list of layers to be zoom to
  1262. @param ignoreNulls True to ignore null-values (valid only for rasters)
  1263. @param render True to re-render display
  1264. """
  1265. zoomreg = {}
  1266. if not layers:
  1267. layers = self.GetSelectedLayer(multi = True)
  1268. if not layers:
  1269. return
  1270. rast = []
  1271. vect = []
  1272. updated = False
  1273. for l in layers:
  1274. # only raster/vector layers are currently supported
  1275. if l.type == 'raster':
  1276. rast.append(l.GetName())
  1277. elif l.type == 'vector':
  1278. if hasattr(self, "digit") and \
  1279. self.toolbar.GetLayer() == l:
  1280. w, s, b, e, n, t = self.digit.GetDisplay().GetMapBoundingBox()
  1281. self.Map.GetRegion(n = n, s = s, w = w, e = e,
  1282. update = True)
  1283. updated = True
  1284. else:
  1285. vect.append(l.name)
  1286. elif l.type == 'rgb':
  1287. for rname in l.GetName().splitlines():
  1288. rast.append(rname)
  1289. if not updated:
  1290. self.Map.GetRegion(rast = rast,
  1291. vect = vect,
  1292. update = True)
  1293. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1294. self.Map.region['e'], self.Map.region['w'])
  1295. if render:
  1296. self.UpdateMap()
  1297. self.parent.StatusbarUpdate()
  1298. def ZoomToWind(self):
  1299. """!Set display geometry to match computational region
  1300. settings (set with g.region)
  1301. """
  1302. self.Map.region = self.Map.GetRegion()
  1303. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1304. self.Map.region['e'], self.Map.region['w'])
  1305. self.UpdateMap()
  1306. self.parent.StatusbarUpdate()
  1307. def ZoomToDefault(self):
  1308. """!Set display geometry to match default region settings
  1309. """
  1310. self.Map.region = self.Map.GetRegion(default = True)
  1311. self.Map.AdjustRegion() # aling region extent to the display
  1312. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1313. self.Map.region['e'], self.Map.region['w'])
  1314. self.UpdateMap()
  1315. self.parent.StatusbarUpdate()
  1316. def GoTo(self, e, n):
  1317. region = self.Map.GetCurrentRegion()
  1318. region['center_easting'], region['center_northing'] = e, n
  1319. dn = (region['nsres'] * region['rows']) / 2.
  1320. region['n'] = region['center_northing'] + dn
  1321. region['s'] = region['center_northing'] - dn
  1322. de = (region['ewres'] * region['cols']) / 2.
  1323. region['e'] = region['center_easting'] + de
  1324. region['w'] = region['center_easting'] - de
  1325. self.Map.AdjustRegion()
  1326. # add to zoom history
  1327. self.ZoomHistory(region['n'], region['s'],
  1328. region['e'], region['w'])
  1329. self.UpdateMap()
  1330. def DisplayToWind(self):
  1331. """!Set computational region (WIND file) to match display
  1332. extents
  1333. """
  1334. tmpreg = os.getenv("GRASS_REGION")
  1335. if tmpreg:
  1336. del os.environ["GRASS_REGION"]
  1337. # We ONLY want to set extents here. Don't mess with resolution. Leave that
  1338. # for user to set explicitly with g.region
  1339. new = self.Map.AlignResolution()
  1340. RunCommand('g.region',
  1341. parent = self,
  1342. overwrite = True,
  1343. n = new['n'],
  1344. s = new['s'],
  1345. e = new['e'],
  1346. w = new['w'],
  1347. rows = int(new['rows']),
  1348. cols = int(new['cols']))
  1349. if tmpreg:
  1350. os.environ["GRASS_REGION"] = tmpreg
  1351. def ZoomToSaved(self):
  1352. """!Set display geometry to match extents in
  1353. saved region file
  1354. """
  1355. dlg = SavedRegion(parent = self,
  1356. title = _("Zoom to saved region extents"),
  1357. loadsave='load')
  1358. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.wind:
  1359. dlg.Destroy()
  1360. return
  1361. if not grass.find_file(name = dlg.wind, element = 'windows')['name']:
  1362. wx.MessageBox(parent = self,
  1363. message = _("Region <%s> not found. Operation canceled.") % dlg.wind,
  1364. caption = _("Error"), style = wx.ICON_ERROR | wx.OK | wx.CENTRE)
  1365. dlg.Destroy()
  1366. return
  1367. self.Map.GetRegion(regionName = dlg.wind,
  1368. update = True)
  1369. dlg.Destroy()
  1370. self.ZoomHistory(self.Map.region['n'],
  1371. self.Map.region['s'],
  1372. self.Map.region['e'],
  1373. self.Map.region['w'])
  1374. self.UpdateMap()
  1375. def SaveDisplayRegion(self):
  1376. """!Save display extents to named region file.
  1377. """
  1378. dlg = SavedRegion(parent = self,
  1379. title = _("Save display extents to region file"),
  1380. loadsave='save')
  1381. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.wind:
  1382. dlg.Destroy()
  1383. return
  1384. # test to see if it already exists and ask permission to overwrite
  1385. if grass.find_file(name = dlg.wind, element = 'windows')['name']:
  1386. overwrite = wx.MessageBox(parent = self,
  1387. message = _("Region file <%s> already exists. "
  1388. "Do you want to overwrite it?") % (dlg.wind),
  1389. caption = _("Warning"), style = wx.YES_NO | wx.CENTRE)
  1390. if (overwrite == wx.YES):
  1391. self.SaveRegion(dlg.wind)
  1392. else:
  1393. self.SaveRegion(dlg.wind)
  1394. dlg.Destroy()
  1395. def SaveRegion(self, wind):
  1396. """!Save region settings
  1397. @param wind region name
  1398. """
  1399. new = self.Map.GetCurrentRegion()
  1400. tmpreg = os.getenv("GRASS_REGION")
  1401. if tmpreg:
  1402. del os.environ["GRASS_REGION"]
  1403. RunCommand('g.region',
  1404. overwrite = True,
  1405. parent = self,
  1406. flags = 'u',
  1407. n = new['n'],
  1408. s = new['s'],
  1409. e = new['e'],
  1410. w = new['w'],
  1411. rows = int(new['rows']),
  1412. cols = int(new['cols']),
  1413. save = wind)
  1414. if tmpreg:
  1415. os.environ["GRASS_REGION"] = tmpreg
  1416. def Distance(self, beginpt, endpt, screen = True):
  1417. """!Calculates distance
  1418. Ctypes required for LL-locations
  1419. @param beginpt first point
  1420. @param endpt second point
  1421. @param screen True for screen coordinates otherwise EN
  1422. """
  1423. if screen:
  1424. e1, n1 = self.Pixel2Cell(beginpt)
  1425. e2, n2 = self.Pixel2Cell(endpt)
  1426. else:
  1427. e1, n1 = beginpt
  1428. e2, n2 = endpt
  1429. dEast = (e2 - e1)
  1430. dNorth = (n2 - n1)
  1431. if self.parent.Map.projinfo['proj'] == 'll' and haveCtypes:
  1432. dist = gislib.G_distance(e1, n1, e2, n2)
  1433. else:
  1434. dist = math.sqrt(math.pow((dEast), 2) + math.pow((dNorth), 2))
  1435. return (dist, (dEast, dNorth))
  1436. def GetMap(self):
  1437. """!Get render.Map() instance"""
  1438. return self.Map
  1439. def RegisterMouseEventHandler(self, event, handler, cursor = None):
  1440. """!Calls UpdateTools to manage connected toolbars"""
  1441. self.parent.UpdateTools(None)
  1442. MapWindow.RegisterMouseEventHandler(self, event, handler, cursor)
  1443. def UnregisterMouseEventHandler(self, event, handler):
  1444. """!Sets pointer and toggles it after unregistration"""
  1445. MapWindow.UnregisterMouseEventHandler(self, event, handler)
  1446. # sets pointer mode
  1447. toolbar = self.parent.toolbars['map']
  1448. toolbar.action['id'] = vars(toolbar)["pointer"]
  1449. toolbar.OnTool(None)
  1450. self.parent.OnPointer(event = None)
  1451. def RegisterGraphicsToDraw(self, graphicsType, setStatusFunc = None, drawFunc = None):
  1452. """! Method allows to register graphics to draw.
  1453. @param type (string) - graphics type: "point" or "line"
  1454. @param setStatusFunc (function reference) - function called before drawing each item
  1455. Status function should be in this form: setStatusFunc(item, itemOrderNum)
  1456. item - passes instance of GraphicsSetItem which will be drawn
  1457. itemOrderNum - number of item in drawing order (from O)
  1458. Hidden items are also counted in drawing order.
  1459. @param drawFunc (function reference) - allows to define own function for drawing
  1460. If function is not defined DrawCross method is used for type "point"
  1461. or DrawLines method for type "line".
  1462. @return reference to GraphicsSet, which was added.
  1463. """
  1464. item = GraphicsSet(parentMapWin = self,
  1465. graphicsType = graphicsType,
  1466. setStatusFunc = setStatusFunc,
  1467. drawFunc = drawFunc)
  1468. self.graphicsSetList.append(item)
  1469. return item
  1470. def UnregisterGraphicsToDraw(self, item):
  1471. """!Unregisteres GraphicsSet instance
  1472. @param item (GraphicsSetItem) - item to unregister
  1473. @return True - if item was unregistered
  1474. @return False - if item was not found
  1475. """
  1476. if item in self.graphicsSetList:
  1477. self.graphicsSetList.remove(item)
  1478. return True
  1479. return False
  1480. class GraphicsSet:
  1481. def __init__(self, parentMapWin, graphicsType, setStatusFunc = None, drawFunc = None):
  1482. """!Class, which contains instances of GraphicsSetItem and
  1483. draws them For description of parameters look at method
  1484. RegisterGraphicsToDraw in BufferedWindow class.
  1485. """
  1486. self.pens = {
  1487. "default" : wx.Pen(colour = wx.BLACK, width = 2, style = wx.SOLID),
  1488. "selected" : wx.Pen(colour = wx.GREEN, width = 2, style = wx.SOLID),
  1489. "unused" : wx.Pen(colour = wx.LIGHT_GREY, width = 2, style = wx.SOLID),
  1490. "highest" : wx.Pen(colour = wx.RED, width = 2, style = wx.SOLID)
  1491. }
  1492. # list contains instances of GraphicsSetItem
  1493. self.itemsList = []
  1494. self.properties = {}
  1495. self.graphicsType = graphicsType
  1496. self.parentMapWin = parentMapWin
  1497. self.setStatusFunc = setStatusFunc
  1498. if drawFunc:
  1499. self.drawFunc = drawFunc
  1500. elif self.graphicsType == "point":
  1501. self.properties["size"] = 5
  1502. self.properties["text"] = {}
  1503. self.properties["text"]['font'] = wx.Font(pointSize = self.properties["size"],
  1504. family = wx.FONTFAMILY_DEFAULT,
  1505. style = wx.FONTSTYLE_NORMAL,
  1506. weight = wx.FONTWEIGHT_NORMAL)
  1507. self.properties["text"]['active'] = True
  1508. self.drawFunc = self.parentMapWin.DrawCross
  1509. elif self.graphicsType == "line":
  1510. self.drawFunc = self.parentMapWin.DrawLines
  1511. def Draw(self, pdc):
  1512. """!Draws all containing items.
  1513. @param pdc - device context, where items are drawn
  1514. """
  1515. itemOrderNum = 0
  1516. for item in self.itemsList:
  1517. if self.setStatusFunc is not None:
  1518. self.setStatusFunc(item, itemOrderNum)
  1519. if item.GetPropertyVal("hide") == True:
  1520. itemOrderNum += 1
  1521. continue
  1522. if self.graphicsType == "point":
  1523. if item.GetPropertyVal("penName"):
  1524. self.parentMapWin.pen = self.pens[item.GetPropertyVal("penName")]
  1525. else:
  1526. self.parentMapWin.pen = self.pens["default"]
  1527. coords = self.parentMapWin.Cell2Pixel(item.GetCoords())
  1528. size = self.properties["size"]
  1529. self.properties["text"]['coords'] = [coords[0] + size, coords[1] + size, size, size]
  1530. self.properties["text"]['color'] = self.parentMapWin.pen.GetColour()
  1531. self.properties["text"]['text'] = item.GetPropertyVal("label")
  1532. self.drawFunc(pdc = pdc,
  1533. coords = coords,
  1534. text = self.properties["text"],
  1535. size = self.properties["size"])
  1536. elif self.graphicsType == "line":
  1537. if item.GetPropertyVal("pen"):
  1538. self.parentMapWin.polypen = self.pens[item.GetPropertyVal("pen")]
  1539. else:
  1540. self.parentMapWin.polypen = self.pens["default"]
  1541. self.drawFunc(pdc = pdc,
  1542. polycoords = coords)
  1543. itemOrderNum += 1
  1544. def AddItem(self, coords, penName = None, label = None, hide = False):
  1545. """!Append item to the list.
  1546. Added item is put to the last place in drawing order.
  1547. Could be 'point' or 'line' according to graphicsType.
  1548. @param coords - list of east, north coordinates (double) of item
  1549. Example: point: [1023, 122]
  1550. line: [[10, 12],[20,40],[23, 2334]]
  1551. @param penName (string) - the 'default' pen is used if is not defined
  1552. @param label (string) - label, which will be drawn with point. It is relavant just for 'point' type.
  1553. @param hide (bool) - If it is True, the item is not drawn, when self.Draw is called.
  1554. Hidden items are also counted in drawing order.
  1555. @return (GraphicsSetItem) - added item reference
  1556. """
  1557. item = GraphicsSetItem(coords = coords, penName = None, label = None, hide = False)
  1558. self.itemsList.append(item)
  1559. return item
  1560. def DeleteItem(self, item):
  1561. """!Deletes item
  1562. @param item (GraphicsSetItem) - item to remove
  1563. @return True if item was removed
  1564. @return False if item was not found
  1565. """
  1566. try:
  1567. self.itemsList.remove(item)
  1568. except:
  1569. return False
  1570. return True
  1571. def GetAllItems(self):
  1572. """!Returns list of all containing instances of GraphicsSetItem, in order
  1573. as they are drawn. If you want to change order of drawing use: SetItemDrawOrder method.
  1574. """
  1575. # user can edit objects but not order in list, that is reason,
  1576. # why is returned shallow copy of data list it should be used
  1577. # SetItemDrawOrder for changing order
  1578. return copy(self.itemsList)
  1579. def GetItem(self, drawNum):
  1580. """!Get given item from the list.
  1581. @param drawNum (int) - drawing order (index) number of item
  1582. @return instance of GraphicsSetItem which is drawn in drawNum order
  1583. @return False if drawNum was out of range
  1584. """
  1585. if drawNum < len(self.itemsList) and drawNum >= 0:
  1586. return self.itemsList[drawNum]
  1587. else:
  1588. return False
  1589. def SetPropertyVal(self, propName, propVal):
  1590. """!Set property value
  1591. @param propName (string) - property name: "size", "text"
  1592. - both properties are relevant for "point" type
  1593. @param propVal - property value to be set
  1594. @return True - if value was set
  1595. @return False - if propName is not "size" or "text" or type is "line"
  1596. """
  1597. if self.properties.has_key(propName):
  1598. self.properties[propName] = propVal
  1599. return True
  1600. return False
  1601. def GetPropertyVal(self, propName):
  1602. """!Get property value
  1603. Raises KeyError if propName is not "size" or "text" or type is
  1604. "line"
  1605. @param propName (string) - property name: "size", "text"
  1606. - both properties are relevant for "point" type
  1607. @return value of property
  1608. """
  1609. if self.properties.has_key(propName):
  1610. return self.properties[propName]
  1611. raise KeyError(_("Property does not exist: %s") % (propName))
  1612. def AddPen(self, penName, pen):
  1613. """!Add pen
  1614. @param penName (string) - name of added pen
  1615. @param pen (wx.Pen) - added pen
  1616. @return True - if pen was added
  1617. @return False - if pen already exists
  1618. """
  1619. if self.pens.has_key(penName):
  1620. return False
  1621. self.pens[penName] = pen
  1622. return True
  1623. def GetPen(self, penName):
  1624. """!Get existing pen
  1625. @param penName (string) - name of pen
  1626. @return wx.Pen reference if is found
  1627. @return None if penName was not found
  1628. """
  1629. if self.pens.has_key(penName):
  1630. return self.pens[penName]
  1631. return None
  1632. def SetItemDrawOrder(self, item, drawNum):
  1633. """!Set draw order for item
  1634. @param item (GraphicsSetItem)
  1635. @param drawNum (int) - drawing order of item to be set
  1636. @return True - if order was changed
  1637. @return False - if drawNum is out of range or item was not found
  1638. """
  1639. if drawNum < len(self.itemsList) and drawNum >= 0 and \
  1640. item in self.itemsList:
  1641. self.itemsList.insert(drawNum, self.itemsList.pop(self.itemsList.index(item)))
  1642. return True
  1643. return False
  1644. def GetItemDrawOrder(self, item):
  1645. """!Get draw order for given item
  1646. @param item (GraphicsSetItem)
  1647. @return (int) - drawing order of item
  1648. @return None - if item was not found
  1649. """
  1650. try:
  1651. return self.itemsList.index(item)
  1652. except:
  1653. return None
  1654. class GraphicsSetItem:
  1655. def __init__(self, coords, penName = None, label = None, hide = False):
  1656. """!Could be point or line according to graphicsType in
  1657. GraphicsSet class
  1658. @param coords - list of coordinates (double) of item
  1659. Example: point: [1023, 122]
  1660. line: [[10, 12],[20,40],[23, 2334]]
  1661. @param penName (string) - if it is not defined 'default' pen is used
  1662. @param label (string) - label, which will be drawn with point. It is relevant just for 'point' type
  1663. @param hide (bool) - if it is True, item is not drawn
  1664. Hidden items are also counted in drawing order in GraphicsSet class.
  1665. """
  1666. self.coords = coords
  1667. self.properties = { "penName" : penName,
  1668. "hide" : hide,
  1669. "label" : label }
  1670. def SetPropertyVal(self, propName, propVal):
  1671. """!Set property value
  1672. @param propName (string) - property name: "penName", "hide" or "label"
  1673. - property "label" is relevant just for 'point' type
  1674. @param propVal - property value to be set
  1675. @return True - if value was set
  1676. @return False - if propName is not "penName", "hide" or "label"
  1677. """
  1678. if self.properties.has_key(propName):
  1679. self.properties[propName] = propVal
  1680. return True
  1681. return False
  1682. def GetPropertyVal(self, propName):
  1683. """!Get property value
  1684. Raises KeyError if propName is not "penName", "hide" or
  1685. "label".
  1686. @param propName (string) - property name: "penName", "hide" or "label"
  1687. - property "label" is relevant just for 'point' type
  1688. @return value of property
  1689. """
  1690. if self.properties.has_key(propName):
  1691. return self.properties[propName]
  1692. raise KeyError(_("Property does not exist: %s") % (propName))
  1693. def SetCoords(self, coords):
  1694. """!Set coordinates of item
  1695. @param coords - list of east, north coordinates (double) of item
  1696. Example: point: [1023, 122]
  1697. line: [[10, 12],[20,40],[23, 2334]]
  1698. """
  1699. self.coords = coords
  1700. def GetCoords(self):
  1701. """!Get item coordinates
  1702. @returns coordinates
  1703. """
  1704. return self.coords