mapwindow.py 76 KB

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