mapwindow.py 77 KB

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