mapwindow.py 77 KB

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