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