mapwindow.py 76 KB

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