mapwindow.py 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157
  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. # render background image if needed
  479. #
  480. # update layer dictionary if there has been a change in layers
  481. if self.tree and self.tree.reorder:
  482. self.tree.ReorderLayers()
  483. # reset flag for auto-rendering
  484. if self.tree:
  485. self.tree.rerender = False
  486. try:
  487. if render:
  488. # update display size
  489. self.Map.ChangeMapSize(self.GetClientSize())
  490. if self.frame.GetProperty('resolution'):
  491. # use computation region resolution for rendering
  492. windres = True
  493. else:
  494. windres = False
  495. self.mapfile = self.Map.Render(force = True, mapWindow = self.frame,
  496. windres = windres)
  497. else:
  498. self.mapfile = self.Map.Render(force = False, mapWindow = self.frame)
  499. except GException, e:
  500. GError(message = e.value)
  501. self.mapfile = None
  502. self.img = self.GetImage() # id=99
  503. #
  504. # clear pseudoDcs
  505. #
  506. for pdc in (self.pdc,
  507. self.pdcDec,
  508. self.pdcTmp):
  509. pdc.Clear()
  510. pdc.RemoveAll()
  511. #
  512. # draw background map image to PseudoDC
  513. #
  514. if not self.img:
  515. self.Draw(self.pdc, pdctype = 'clear')
  516. else:
  517. try:
  518. id = self.imagedict[self.img]['id']
  519. except:
  520. return False
  521. self.Draw(self.pdc, self.img, drawid = id)
  522. #
  523. # render vector map layer
  524. #
  525. if renderVector and hasattr(self, "digit"):
  526. self._updateMap()
  527. #
  528. # render overlays
  529. #
  530. for img in self.GetOverlay():
  531. # draw any active and defined overlays
  532. if self.imagedict[img]['layer'].IsActive():
  533. id = self.imagedict[img]['id']
  534. self.Draw(self.pdc, img = img, drawid = id,
  535. pdctype = self.overlays[id]['pdcType'], coords = self.overlays[id]['coords'])
  536. for id in self.textdict.keys():
  537. self.Draw(self.pdc, img = self.textdict[id], drawid = id,
  538. pdctype = 'text', coords = [10, 10, 10, 10])
  539. # optionally draw computational extent box
  540. self.DrawCompRegionExtent()
  541. #
  542. # redraw pdcTmp if needed
  543. #
  544. # draw registered graphics
  545. if len(self.graphicsSetList) > 0:
  546. penOrig = self.pen
  547. polypenOrig = self.polypen
  548. for item in self.graphicsSetList:
  549. try:
  550. item.Draw(self.pdcTmp)
  551. except:
  552. GError(parent = self,
  553. message = _('Unable to draw registered graphics. '
  554. 'The graphics was unregistered.'))
  555. self.UnregisterGraphicsToDraw(item)
  556. self.pen = penOrig
  557. self.polypen = polypenOrig
  558. if len(self.polycoords) > 0:
  559. self.DrawLines(self.pdcTmp)
  560. #
  561. # clear measurement
  562. #
  563. if self.mouse["use"] == "measure":
  564. self.ClearLines(pdc = self.pdcTmp)
  565. self.polycoords = []
  566. self.mouse['use'] = 'pointer'
  567. self.mouse['box'] = 'point'
  568. self.mouse['end'] = [0, 0]
  569. self.SetCursor(self.frame.cursors["default"])
  570. stop = time.clock()
  571. Debug.msg (1, "BufferedWindow.UpdateMap(): render=%s, renderVector=%s -> time=%g" % \
  572. (render, renderVector, (stop-start)))
  573. return True
  574. def DrawCompRegionExtent(self):
  575. """!Draw computational region extent in the display
  576. Display region is drawn as a blue box inside the computational region,
  577. computational region inside a display region as a red box).
  578. """
  579. if hasattr(self, "regionCoords"):
  580. compReg = self.Map.GetRegion()
  581. dispReg = self.Map.GetCurrentRegion()
  582. reg = None
  583. if self.IsInRegion(dispReg, compReg):
  584. self.polypen = wx.Pen(colour = wx.Colour(0, 0, 255, 128), width = 3, style = wx.SOLID)
  585. reg = dispReg
  586. else:
  587. self.polypen = wx.Pen(colour = wx.Colour(255, 0, 0, 128),
  588. width = 3, style = wx.SOLID)
  589. reg = compReg
  590. self.regionCoords = []
  591. self.regionCoords.append((reg['w'], reg['n']))
  592. self.regionCoords.append((reg['e'], reg['n']))
  593. self.regionCoords.append((reg['e'], reg['s']))
  594. self.regionCoords.append((reg['w'], reg['s']))
  595. self.regionCoords.append((reg['w'], reg['n']))
  596. # draw region extent
  597. self.DrawLines(pdc = self.pdcDec, polycoords = self.regionCoords)
  598. def IsInRegion(self, region, refRegion):
  599. """!
  600. Test if 'region' is inside of 'refRegion'
  601. @param region input region
  602. @param refRegion reference region (e.g. computational region)
  603. @return True if region is inside of refRegion
  604. @return False
  605. """
  606. if region['s'] >= refRegion['s'] and \
  607. region['n'] <= refRegion['n'] and \
  608. region['w'] >= refRegion['w'] and \
  609. region['e'] <= refRegion['e']:
  610. return True
  611. return False
  612. def EraseMap(self):
  613. """!Erase map canvas
  614. """
  615. self.Draw(self.pdc, pdctype = 'clear')
  616. if hasattr(self, "digit"):
  617. self.Draw(self.pdcVector, pdctype = 'clear')
  618. self.Draw(self.pdcDec, pdctype = 'clear')
  619. self.Draw(self.pdcTmp, pdctype = 'clear')
  620. for layer in self.Map.GetListOfLayers(l_active = True):
  621. layer.AbortDownload()
  622. def DragMap(self, moveto):
  623. """!Drag the entire map image for panning.
  624. @param moveto dx,dy
  625. """
  626. dc = wx.BufferedDC(wx.ClientDC(self))
  627. dc.SetBackground(wx.Brush("White"))
  628. dc.Clear()
  629. self.dragimg = wx.DragImage(self._buffer)
  630. self.dragimg.BeginDrag((0, 0), self)
  631. self.dragimg.GetImageRect(moveto)
  632. self.dragimg.Move(moveto)
  633. self.dragimg.DoDrawImage(dc, moveto)
  634. self.dragimg.EndDrag()
  635. def DragItem(self, id, coords):
  636. """!Drag an overlay decoration item
  637. """
  638. if id == 99 or id == '' or id == None: return
  639. Debug.msg (5, "BufferedWindow.DragItem(): id=%d" % id)
  640. x, y = self.lastpos
  641. dx = coords[0] - x
  642. dy = coords[1] - y
  643. self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
  644. r = self.pdc.GetIdBounds(id)
  645. if type(r) is list:
  646. r = wx.Rect(r[0], r[1], r[2], r[3])
  647. if id > 100: # text dragging
  648. rtop = (r[0],r[1]-r[3],r[2],r[3])
  649. r = r.Union(rtop)
  650. rleft = (r[0]-r[2],r[1],r[2],r[3])
  651. r = r.Union(rleft)
  652. self.pdc.TranslateId(id, dx, dy)
  653. r2 = self.pdc.GetIdBounds(id)
  654. if type(r2) is list:
  655. r2 = wx.Rect(r[0], r[1], r[2], r[3])
  656. if id > 100: # text
  657. self.textdict[id]['bbox'] = r2
  658. self.textdict[id]['coords'][0] += dx
  659. self.textdict[id]['coords'][1] += dy
  660. r = r.Union(r2)
  661. r.Inflate(4,4)
  662. self.RefreshRect(r, False)
  663. self.lastpos = (coords[0], coords[1])
  664. def MouseDraw(self, pdc = None, begin = None, end = None):
  665. """!Mouse box or line from 'begin' to 'end'
  666. If not given from self.mouse['begin'] to self.mouse['end'].
  667. """
  668. if not pdc:
  669. return
  670. if begin is None:
  671. begin = self.mouse['begin']
  672. if end is None:
  673. end = self.mouse['end']
  674. Debug.msg (5, "BufferedWindow.MouseDraw(): use=%s, box=%s, begin=%f,%f, end=%f,%f" % \
  675. (self.mouse['use'], self.mouse['box'],
  676. begin[0], begin[1], end[0], end[1]))
  677. if self.mouse['box'] == "box":
  678. boxid = wx.ID_NEW
  679. mousecoords = [begin[0], begin[1],
  680. end[0], end[1]]
  681. r = pdc.GetIdBounds(boxid)
  682. if type(r) is list:
  683. r = wx.Rect(r[0], r[1], r[2], r[3])
  684. r.Inflate(4, 4)
  685. try:
  686. pdc.ClearId(boxid)
  687. except:
  688. pass
  689. self.RefreshRect(r, False)
  690. pdc.SetId(boxid)
  691. self.Draw(pdc, drawid = boxid, pdctype = 'box', coords = mousecoords)
  692. elif self.mouse['box'] == "line":
  693. self.lineid = wx.ID_NEW
  694. mousecoords = [begin[0], begin[1], \
  695. end[0], end[1]]
  696. x1 = min(begin[0],end[0])
  697. x2 = max(begin[0],end[0])
  698. y1 = min(begin[1],end[1])
  699. y2 = max(begin[1],end[1])
  700. r = wx.Rect(x1,y1,x2-x1,y2-y1)
  701. r.Inflate(4,4)
  702. try:
  703. pdc.ClearId(self.lineid)
  704. except:
  705. pass
  706. self.RefreshRect(r, False)
  707. pdc.SetId(self.lineid)
  708. self.Draw(pdc, drawid = self.lineid, pdctype = 'line', coords = mousecoords)
  709. def DrawLines(self, pdc = None, polycoords = None):
  710. """!Draw polyline in PseudoDC
  711. Set self.pline to wx.NEW_ID + 1
  712. polycoords - list of polyline vertices, geographical coordinates
  713. (if not given, self.polycoords is used)
  714. """
  715. if not pdc:
  716. pdc = self.pdcTmp
  717. if not polycoords:
  718. polycoords = self.polycoords
  719. if len(polycoords) > 0:
  720. self.plineid = wx.ID_NEW + 1
  721. # convert from EN to XY
  722. coords = []
  723. for p in polycoords:
  724. coords.append(self.Cell2Pixel(p))
  725. self.Draw(pdc, drawid = self.plineid, pdctype = 'polyline', coords = coords)
  726. Debug.msg (4, "BufferedWindow.DrawLines(): coords=%s, id=%s" % \
  727. (coords, self.plineid))
  728. return self.plineid
  729. return -1
  730. def DrawCross(self, pdc, coords, size, rotation = 0,
  731. text = None, textAlign = 'lr', textOffset = (5, 5)):
  732. """!Draw cross in PseudoDC
  733. @todo implement rotation
  734. @param pdc PseudoDC
  735. @param coords center coordinates
  736. @param rotation rotate symbol
  737. @param text draw also text (text, font, color, rotation)
  738. @param textAlign alignment (default 'lower-right')
  739. @param textOffset offset for text (from center point)
  740. """
  741. Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" % \
  742. (pdc, coords, size))
  743. coordsCross = ((coords[0] - size, coords[1], coords[0] + size, coords[1]),
  744. (coords[0], coords[1] - size, coords[0], coords[1] + size))
  745. self.lineid = wx.NewId()
  746. for lineCoords in coordsCross:
  747. self.Draw(pdc, drawid = self.lineid, pdctype = 'line', coords = lineCoords)
  748. if not text:
  749. return self.lineid
  750. if textAlign == 'ul':
  751. coord = [coords[0] - textOffset[0], coords[1] - textOffset[1], 0, 0]
  752. elif textAlign == 'ur':
  753. coord = [coords[0] + textOffset[0], coords[1] - textOffset[1], 0, 0]
  754. elif textAlign == 'lr':
  755. coord = [coords[0] + textOffset[0], coords[1] + textOffset[1], 0, 0]
  756. else:
  757. coord = [coords[0] - textOffset[0], coords[1] + textOffset[1], 0, 0]
  758. self.Draw(pdc, img = text,
  759. pdctype = 'text', coords = coord)
  760. return self.lineid
  761. def _computeZoomToPointAndRecenter(self, position, zoomtype):
  762. """!Computes zoom parameters for recenter mode.
  763. Computes begin and end parameters for Zoom() method.
  764. Used for zooming by single click (not box)
  765. and mouse wheel zooming (zoom and recenter mode).
  766. """
  767. if zoomtype > 0:
  768. begin = (position[0] - self.Map.width / 4,
  769. position[1] - self.Map.height / 4)
  770. end = (position[0] + self.Map.width / 4,
  771. position[1] + self.Map.height / 4)
  772. else:
  773. begin = ((self.Map.width - position[0]) / 2,
  774. (self.Map.height - position[1]) / 2)
  775. end = (begin[0] + self.Map.width / 2,
  776. begin[1] + self.Map.height / 2)
  777. return begin, end
  778. def MouseActions(self, event):
  779. """!Mouse motion and button click notifier
  780. """
  781. if not self.processMouse:
  782. return
  783. # zoom with mouse wheel
  784. if event.GetWheelRotation() != 0:
  785. self.OnMouseWheel(event)
  786. # left mouse button pressed
  787. elif event.LeftDown():
  788. self.OnLeftDown(event)
  789. # left mouse button released
  790. elif event.LeftUp():
  791. self.OnLeftUp(event)
  792. # dragging
  793. elif event.Dragging():
  794. self.OnDragging(event)
  795. # double click
  796. elif event.ButtonDClick():
  797. self.OnButtonDClick(event)
  798. # middle mouse button pressed
  799. elif event.MiddleDown():
  800. self.OnMiddleDown(event)
  801. # middle mouse button relesed
  802. elif event.MiddleUp():
  803. self.OnMiddleUp(event)
  804. # right mouse button pressed
  805. elif event.RightDown():
  806. self.OnRightDown(event)
  807. # right mouse button released
  808. elif event.RightUp():
  809. self.OnRightUp(event)
  810. elif event.Entering():
  811. self.OnMouseEnter(event)
  812. elif event.Moving():
  813. self.OnMouseMoving(event)
  814. def OnMouseWheel(self, event):
  815. """!Mouse wheel moved
  816. """
  817. zoomBehaviour = UserSettings.Get(group = 'display',
  818. key = 'mouseWheelZoom',
  819. subkey = 'selection')
  820. if zoomBehaviour == 2:
  821. event.Skip()
  822. return
  823. self.processMouse = False
  824. current = event.GetPositionTuple()[:]
  825. wheel = event.GetWheelRotation()
  826. Debug.msg (5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
  827. if wheel > 0:
  828. zoomtype = 1
  829. else:
  830. zoomtype = -1
  831. if UserSettings.Get(group = 'display',
  832. key = 'scrollDirection',
  833. subkey = 'selection'):
  834. zoomtype *= -1
  835. # zoom 1/2 of the screen (TODO: settings)
  836. if zoomBehaviour == 0: # zoom and recenter
  837. begin, end = self._computeZoomToPointAndRecenter(position = current, zoomtype = zoomtype)
  838. elif zoomBehaviour == 1: # zoom to current cursor position
  839. begin = (current[0]/2, current[1]/2)
  840. end = ((self.Map.width - current[0])/2 + current[0],
  841. (self.Map.height - current[1])/2 + current[1])
  842. # zoom
  843. self.Zoom(begin, end, zoomtype)
  844. # redraw map
  845. self.UpdateMap()
  846. # update statusbar
  847. self.frame.StatusbarUpdate()
  848. self.Refresh()
  849. self.processMouse = True
  850. def OnDragging(self, event):
  851. """!Mouse dragging
  852. """
  853. Debug.msg (5, "BufferedWindow.MouseAction(): Dragging")
  854. current = event.GetPositionTuple()[:]
  855. previous = self.mouse['begin']
  856. move = (current[0] - previous[0],
  857. current[1] - previous[1])
  858. if hasattr(self, "digit"):
  859. digitToolbar = self.toolbar
  860. else:
  861. digitToolbar = None
  862. # dragging or drawing box with left button
  863. if self.mouse['use'] == 'pan' or \
  864. event.MiddleIsDown():
  865. self.DragMap(move)
  866. # dragging decoration overlay item
  867. elif (self.mouse['use'] == 'pointer' and
  868. not digitToolbar and
  869. self.dragid != None):
  870. coords = event.GetPositionTuple()
  871. self.DragItem(self.dragid, coords)
  872. # dragging anything else - rubber band box or line
  873. else:
  874. if (self.mouse['use'] == 'pointer' and
  875. not digitToolbar):
  876. return
  877. self.mouse['end'] = event.GetPositionTuple()[:]
  878. if (event.LeftIsDown() and
  879. not (digitToolbar and
  880. digitToolbar.GetAction() in ("moveLine",) and
  881. self.digit.GetDisplay().GetSelected() > 0)):
  882. self.MouseDraw(pdc = self.pdcTmp)
  883. def OnLeftDown(self, event):
  884. """!Left mouse button pressed
  885. """
  886. Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
  887. self.mouse["use"])
  888. self.mouse['begin'] = event.GetPositionTuple()[:]
  889. if self.mouse["use"] in ["measure", "profile"]:
  890. # measure or profile
  891. if len(self.polycoords) == 0:
  892. self.mouse['end'] = self.mouse['begin']
  893. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  894. self.ClearLines(pdc=self.pdcTmp)
  895. else:
  896. self.mouse['begin'] = self.mouse['end']
  897. elif self.mouse['use'] in ('zoom', 'legend'):
  898. pass
  899. # vector digizer
  900. elif self.mouse["use"] == "pointer" and \
  901. hasattr(self, "digit"):
  902. if event.ControlDown():
  903. self.OnLeftDownUndo(event)
  904. else:
  905. self._onLeftDown(event)
  906. elif self.mouse['use'] == 'pointer':
  907. # get decoration or text id
  908. idlist = []
  909. self.dragid = ''
  910. self.lastpos = self.mouse['begin']
  911. idlist = self.pdc.FindObjects(self.lastpos[0], self.lastpos[1],
  912. self.hitradius)
  913. if 99 in idlist:
  914. idlist.remove(99)
  915. if idlist != []:
  916. self.dragid = idlist[0] #drag whatever is on top
  917. else:
  918. pass
  919. event.Skip()
  920. def OnLeftUp(self, event):
  921. """!Left mouse button released
  922. """
  923. Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
  924. self.mouse["use"])
  925. self.mouse['end'] = event.GetPositionTuple()[:]
  926. if self.mouse['use'] in ["zoom", "pan"]:
  927. # set region in zoom or pan
  928. begin = self.mouse['begin']
  929. end = self.mouse['end']
  930. if self.mouse['use'] == 'zoom':
  931. # set region for click (zero-width box)
  932. if begin[0] - end[0] == 0 or \
  933. begin[1] - end[1] == 0:
  934. begin, end = self._computeZoomToPointAndRecenter(position = end, zoomtype = self.zoomtype)
  935. self.Zoom(begin, end, self.zoomtype)
  936. # redraw map
  937. self.UpdateMap(render = True)
  938. # update statusbar
  939. self.frame.StatusbarUpdate()
  940. elif self.mouse["use"] == "query":
  941. # querying
  942. if self.frame.IsStandalone():
  943. GMessage(parent = self.frame,
  944. message = _("Querying is not implemented in standalone mode of Map Display"))
  945. return
  946. layers = self.tree.GetSelectedLayer(multi = True, checkedOnly = True)
  947. self.frame.Query(self.mouse['begin'][0],self.mouse['begin'][1], layers)
  948. elif self.mouse["use"] in ["measure", "profile"]:
  949. # measure or profile
  950. if self.mouse["use"] == "measure":
  951. self.frame.MeasureDist(self.mouse['begin'], self.mouse['end'])
  952. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  953. self.ClearLines(pdc = self.pdcTmp)
  954. self.DrawLines(pdc = self.pdcTmp)
  955. elif self.mouse["use"] == "pointer" and \
  956. not self.frame.IsStandalone() and \
  957. self.frame.GetLayerManager().gcpmanagement:
  958. # -> GCP manager
  959. if self.frame.GetToolbar('gcpdisp'):
  960. coord = self.Pixel2Cell(self.mouse['end'])
  961. if self.frame.MapWindow == self.frame.SrcMapWindow:
  962. coordtype = 'source'
  963. else:
  964. coordtype = 'target'
  965. self.frame.GetLayerManager().gcpmanagement.SetGCPData(coordtype, coord, self, confirm = True)
  966. self.UpdateMap(render = False, renderVector = False)
  967. elif self.mouse["use"] == "pointer" and \
  968. hasattr(self, "digit"):
  969. self._onLeftUp(event)
  970. elif (self.mouse['use'] == 'pointer' and
  971. self.dragid >= 0):
  972. # end drag of overlay decoration
  973. if self.dragid < 99 and self.dragid in self.overlays:
  974. self.overlays[self.dragid]['coords'] = self.pdc.GetIdBounds(self.dragid)
  975. elif self.dragid > 100 and self.dragid in self.textdict:
  976. self.textdict[self.dragid]['bbox'] = self.pdc.GetIdBounds(self.dragid)
  977. else:
  978. pass
  979. self.dragid = None
  980. self.currtxtid = None
  981. elif self.mouse['use'] == 'legend':
  982. self.ResizeLegend(self.mouse["begin"], self.mouse["end"])
  983. self.frame.dialogs['legend'].FindWindowByName("resize").SetValue(False)
  984. self.Map.GetOverlay(1).SetActive(True)
  985. self.frame.MapWindow.SetCursor(self.frame.cursors["default"])
  986. self.frame.MapWindow.mouse['use'] = 'pointer'
  987. self.UpdateMap()
  988. def OnButtonDClick(self, event):
  989. """!Mouse button double click
  990. """
  991. Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
  992. self.mouse["use"])
  993. if self.mouse["use"] == "measure":
  994. # measure
  995. self.ClearLines(pdc=self.pdcTmp)
  996. self.polycoords = []
  997. self.mouse['use'] = 'pointer'
  998. self.mouse['box'] = 'point'
  999. self.mouse['end'] = [0, 0]
  1000. self.Refresh()
  1001. self.SetCursor(self.frame.cursors["default"])
  1002. elif self.mouse["use"] != "profile" or \
  1003. (self.mouse['use'] != 'pointer' and \
  1004. hasattr(self, "digit")):
  1005. # select overlay decoration options dialog
  1006. clickposition = event.GetPositionTuple()[:]
  1007. idlist = self.pdc.FindObjects(clickposition[0], clickposition[1], self.hitradius)
  1008. if idlist == []:
  1009. return
  1010. self.dragid = idlist[0]
  1011. # self.ovlcoords[self.dragid] = self.pdc.GetIdBounds(self.dragid)
  1012. if self.dragid > 100:
  1013. self.currtxtid = self.dragid
  1014. self.frame.OnAddText(None)
  1015. elif self.dragid == 0:
  1016. self.frame.OnAddBarscale(None)
  1017. elif self.dragid == 1:
  1018. self.frame.OnAddLegend(None)
  1019. def OnRightDown(self, event):
  1020. """!Right mouse button pressed
  1021. """
  1022. Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
  1023. self.mouse["use"])
  1024. if hasattr(self, "digit"):
  1025. self._onRightDown(event)
  1026. event.Skip()
  1027. def OnRightUp(self, event):
  1028. """!Right mouse button released
  1029. """
  1030. Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
  1031. self.mouse["use"])
  1032. if hasattr(self, "digit"):
  1033. self._onRightUp(event)
  1034. self.redrawAll = True
  1035. self.Refresh()
  1036. event.Skip()
  1037. def OnMiddleDown(self, event):
  1038. """!Middle mouse button pressed
  1039. """
  1040. if not event:
  1041. return
  1042. self.mouse['begin'] = event.GetPositionTuple()[:]
  1043. def OnMiddleUp(self, event):
  1044. """!Middle mouse button released
  1045. """
  1046. self.mouse['end'] = event.GetPositionTuple()[:]
  1047. # set region in zoom or pan
  1048. begin = self.mouse['begin']
  1049. end = self.mouse['end']
  1050. self.Zoom(begin, end, 0) # no zoom
  1051. # redraw map
  1052. self.UpdateMap(render = True)
  1053. # update statusbar
  1054. self.frame.StatusbarUpdate()
  1055. def OnMouseEnter(self, event):
  1056. """!Mouse entered window and no mouse buttons were pressed
  1057. """
  1058. if not self.frame.IsStandalone() and \
  1059. self.frame.GetLayerManager().gcpmanagement:
  1060. if self.frame.GetToolbar('gcpdisp'):
  1061. if not self.frame.MapWindow == self:
  1062. self.frame.MapWindow = self
  1063. self.frame.Map = self.Map
  1064. self.frame.UpdateActive(self)
  1065. # needed for wingrass
  1066. self.SetFocus()
  1067. else:
  1068. event.Skip()
  1069. def OnMouseMoving(self, event):
  1070. """!Motion event and no mouse buttons were pressed
  1071. """
  1072. if self.mouse["use"] == "pointer" and \
  1073. hasattr(self, "digit"):
  1074. self._onMouseMoving(event)
  1075. event.Skip()
  1076. def OnCopyCoordinates(self, event):
  1077. """!Copy coordinates to cliboard"""
  1078. e, n = self.GetLastEN()
  1079. if wx.TheClipboard.Open():
  1080. do = wx.TextDataObject()
  1081. # TODO: put delimiter in settings and apply also for Go to in statusbar
  1082. delim = ';'
  1083. do.SetText(str(e) + delim + str(n))
  1084. wx.TheClipboard.SetData(do)
  1085. wx.TheClipboard.Close()
  1086. def ClearLines(self, pdc = None):
  1087. """!Clears temporary drawn lines from PseudoDC
  1088. """
  1089. if not pdc:
  1090. pdc = self.pdcTmp
  1091. try:
  1092. pdc.ClearId(self.lineid)
  1093. pdc.RemoveId(self.lineid)
  1094. except:
  1095. pass
  1096. try:
  1097. pdc.ClearId(self.plineid)
  1098. pdc.RemoveId(self.plineid)
  1099. except:
  1100. pass
  1101. Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
  1102. (self.lineid, self.plineid))
  1103. return True
  1104. def Pixel2Cell(self, (x, y)):
  1105. """!Convert image coordinates to real word coordinates
  1106. @param x, y image coordinates
  1107. @return easting, northing
  1108. @return None on error
  1109. """
  1110. try:
  1111. x = int(x)
  1112. y = int(y)
  1113. except:
  1114. return None
  1115. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1116. res = self.Map.region["ewres"]
  1117. else:
  1118. res = self.Map.region["nsres"]
  1119. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1120. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1121. east = w + x * res
  1122. north = n - y * res
  1123. return (east, north)
  1124. def Cell2Pixel(self, (east, north)):
  1125. """!Convert real word coordinates to image coordinates
  1126. """
  1127. try:
  1128. east = float(east)
  1129. north = float(north)
  1130. except:
  1131. return None
  1132. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1133. res = self.Map.region["ewres"]
  1134. else:
  1135. res = self.Map.region["nsres"]
  1136. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1137. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1138. x = (east - w) / res
  1139. y = (n - north) / res
  1140. return (x, y)
  1141. def ResizeLegend(self, begin, end):
  1142. w = abs(begin[0] - end[0])
  1143. h = abs(begin[1] - end[1])
  1144. if begin[0] < end[0]:
  1145. x = begin[0]
  1146. else:
  1147. x = end[0]
  1148. if begin[1] < end[1]:
  1149. y = begin[1]
  1150. else:
  1151. y = end[1]
  1152. screenSize = self.GetClientSizeTuple()
  1153. at = [(screenSize[1] - (y + h)) / float(screenSize[1]) * 100,
  1154. (screenSize[1] - y) / float(screenSize[1]) * 100,
  1155. x / float(screenSize[0]) * 100,
  1156. (x + w) / float(screenSize[0]) * 100]
  1157. for i, subcmd in enumerate(self.overlays[1]['cmd']):
  1158. if subcmd.startswith('at='):
  1159. self.overlays[1]['cmd'][i] = "at=%d,%d,%d,%d" % (at[0], at[1], at[2], at[3])
  1160. self.Map.ChangeOverlay(1, True, command = self.overlays[1]['cmd'])
  1161. self.overlays[1]['coords'] = (0,0)
  1162. def Zoom(self, begin, end, zoomtype):
  1163. """!Calculates new region while (un)zoom/pan-ing
  1164. """
  1165. x1, y1 = begin
  1166. x2, y2 = end
  1167. newreg = {}
  1168. # threshold - too small squares do not make sense
  1169. # can only zoom to windows of > 5x5 screen pixels
  1170. if abs(x2-x1) > 5 and abs(y2-y1) > 5 and zoomtype != 0:
  1171. if x1 > x2:
  1172. x1, x2 = x2, x1
  1173. if y1 > y2:
  1174. y1, y2 = y2, y1
  1175. # zoom in
  1176. if zoomtype > 0:
  1177. newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
  1178. newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
  1179. # zoom out
  1180. elif zoomtype < 0:
  1181. newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
  1182. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + 2 * \
  1183. (self.Map.width - x2),
  1184. self.Map.height + 2 * \
  1185. (self.Map.height - y2)))
  1186. # pan
  1187. elif zoomtype == 0:
  1188. dx = x1 - x2
  1189. dy = y1 - y2
  1190. if dx == 0 and dy == 0:
  1191. dx = x1 - self.Map.width / 2
  1192. dy = y1 - self.Map.height / 2
  1193. newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
  1194. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
  1195. self.Map.height + dy))
  1196. # if new region has been calculated, set the values
  1197. if newreg != {}:
  1198. # LL locations
  1199. if self.Map.projinfo['proj'] == 'll':
  1200. self.Map.region['n'] = min(self.Map.region['n'], 90.0)
  1201. self.Map.region['s'] = max(self.Map.region['s'], -90.0)
  1202. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  1203. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  1204. # calculate new center point and display resolution
  1205. self.Map.region['center_easting'] = ce
  1206. self.Map.region['center_northing'] = cn
  1207. self.Map.region['ewres'] = (newreg['e'] - newreg['w']) / self.Map.width
  1208. self.Map.region['nsres'] = (newreg['n'] - newreg['s']) / self.Map.height
  1209. if not self.frame.HasProperty('alignExtent') or \
  1210. self.frame.GetProperty('alignExtent'):
  1211. self.Map.AlignExtentFromDisplay()
  1212. else:
  1213. for k in ('n', 's', 'e', 'w'):
  1214. self.Map.region[k] = newreg[k]
  1215. if hasattr(self, "digit") and \
  1216. hasattr(self, "moveInfo"):
  1217. self._zoom(None)
  1218. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1219. self.Map.region['e'], self.Map.region['w'])
  1220. if self.redrawAll is False:
  1221. self.redrawAll = True
  1222. def ZoomBack(self):
  1223. """!Zoom to previous extents in zoomhistory list
  1224. """
  1225. zoom = list()
  1226. if len(self.zoomhistory) > 1:
  1227. self.zoomhistory.pop()
  1228. zoom = self.zoomhistory[-1]
  1229. # disable tool if stack is empty
  1230. if len(self.zoomhistory) < 2: # disable tool
  1231. toolbar = self.frame.GetMapToolbar()
  1232. toolbar.Enable('zoomBack', enable = False)
  1233. # zoom to selected region
  1234. self.Map.GetRegion(n = zoom[0], s = zoom[1],
  1235. e = zoom[2], w = zoom[3],
  1236. update = True)
  1237. # update map
  1238. self.UpdateMap()
  1239. # update statusbar
  1240. self.frame.StatusbarUpdate()
  1241. wx.PostEvent(self, gZoomChanged())
  1242. def ZoomHistory(self, n, s, e, w):
  1243. """!Manages a list of last 10 zoom extents
  1244. @param n,s,e,w north, south, east, west
  1245. @return removed history item if exists (or None)
  1246. """
  1247. removed = None
  1248. self.zoomhistory.append((n,s,e,w))
  1249. if len(self.zoomhistory) > 10:
  1250. removed = self.zoomhistory.pop(0)
  1251. if removed:
  1252. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
  1253. (self.zoomhistory, removed))
  1254. else:
  1255. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
  1256. (self.zoomhistory))
  1257. # update toolbar
  1258. if len(self.zoomhistory) > 1:
  1259. enable = True
  1260. else:
  1261. enable = False
  1262. toolbar = self.frame.GetMapToolbar()
  1263. toolbar.Enable('zoomBack', enable)
  1264. wx.PostEvent(self, gZoomChanged())
  1265. return removed
  1266. def ResetZoomHistory(self):
  1267. """!Reset zoom history"""
  1268. self.zoomhistory = list()
  1269. def ZoomToMap(self, layers = None, ignoreNulls = False, render = True):
  1270. """!Set display extents to match selected raster
  1271. or vector map(s).
  1272. @param layers list of layers to be zoom to
  1273. @param ignoreNulls True to ignore null-values (valid only for rasters)
  1274. @param render True to re-render display
  1275. """
  1276. if not layers:
  1277. layers = self.tree.GetSelectedLayer(multi = True, checkedOnly = False)
  1278. layers = [self.tree.GetLayerInfo(layer, key = 'maplayer') for layer in layers]
  1279. if not layers:
  1280. return
  1281. rast = []
  1282. vect = []
  1283. updated = False
  1284. for l in layers:
  1285. # only raster/vector layers are currently supported
  1286. if l.type == 'raster':
  1287. rast.append(l.GetName())
  1288. elif l.type == 'vector':
  1289. if hasattr(self, "digit") and \
  1290. self.toolbar.GetLayer() == l:
  1291. w, s, b, e, n, t = self.digit.GetDisplay().GetMapBoundingBox()
  1292. self.Map.GetRegion(n = n, s = s, w = w, e = e,
  1293. update = True)
  1294. updated = True
  1295. else:
  1296. vect.append(l.name)
  1297. elif l.type == 'rgb':
  1298. for rname in l.GetName().splitlines():
  1299. rast.append(rname)
  1300. if not updated:
  1301. self.Map.GetRegion(rast = rast,
  1302. vect = vect,
  1303. zoom = ignoreNulls,
  1304. update = True)
  1305. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1306. self.Map.region['e'], self.Map.region['w'])
  1307. if render:
  1308. self.UpdateMap()
  1309. self.frame.StatusbarUpdate()
  1310. def ZoomToWind(self):
  1311. """!Set display geometry to match computational region
  1312. settings (set with g.region)
  1313. """
  1314. self.Map.region = self.Map.GetRegion()
  1315. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1316. self.Map.region['e'], self.Map.region['w'])
  1317. self.UpdateMap()
  1318. self.frame.StatusbarUpdate()
  1319. def ZoomToDefault(self):
  1320. """!Set display geometry to match default region settings
  1321. """
  1322. self.Map.region = self.Map.GetRegion(default = True)
  1323. self.Map.AdjustRegion() # aling region extent to the display
  1324. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1325. self.Map.region['e'], self.Map.region['w'])
  1326. self.UpdateMap()
  1327. self.frame.StatusbarUpdate()
  1328. def GoTo(self, e, n):
  1329. region = self.Map.GetCurrentRegion()
  1330. region['center_easting'], region['center_northing'] = e, n
  1331. dn = (region['nsres'] * region['rows']) / 2.
  1332. region['n'] = region['center_northing'] + dn
  1333. region['s'] = region['center_northing'] - dn
  1334. de = (region['ewres'] * region['cols']) / 2.
  1335. region['e'] = region['center_easting'] + de
  1336. region['w'] = region['center_easting'] - de
  1337. self.Map.AdjustRegion()
  1338. # add to zoom history
  1339. self.ZoomHistory(region['n'], region['s'],
  1340. region['e'], region['w'])
  1341. self.UpdateMap()
  1342. def DisplayToWind(self):
  1343. """!Set computational region (WIND file) to match display
  1344. extents
  1345. """
  1346. tmpreg = os.getenv("GRASS_REGION")
  1347. if tmpreg:
  1348. del os.environ["GRASS_REGION"]
  1349. # We ONLY want to set extents here. Don't mess with resolution. Leave that
  1350. # for user to set explicitly with g.region
  1351. new = self.Map.AlignResolution()
  1352. RunCommand('g.region',
  1353. parent = self,
  1354. overwrite = True,
  1355. n = new['n'],
  1356. s = new['s'],
  1357. e = new['e'],
  1358. w = new['w'],
  1359. rows = int(new['rows']),
  1360. cols = int(new['cols']))
  1361. if tmpreg:
  1362. os.environ["GRASS_REGION"] = tmpreg
  1363. def ZoomToSaved(self):
  1364. """!Set display geometry to match extents in
  1365. saved region file
  1366. """
  1367. dlg = SavedRegion(parent = self,
  1368. title = _("Zoom to saved region extents"),
  1369. loadsave = 'load')
  1370. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.GetName():
  1371. dlg.Destroy()
  1372. return
  1373. if not grass.find_file(name = dlg.GetName(), element = 'windows')['name']:
  1374. wx.MessageBox(parent = self,
  1375. message = _("Region <%s> not found. Operation canceled.") % dlg.GetName(),
  1376. caption = _("Error"), style = wx.ICON_ERROR | wx.OK | wx.CENTRE)
  1377. dlg.Destroy()
  1378. return
  1379. self.Map.GetRegion(regionName = dlg.GetName(),
  1380. update = True)
  1381. dlg.Destroy()
  1382. self.ZoomHistory(self.Map.region['n'],
  1383. self.Map.region['s'],
  1384. self.Map.region['e'],
  1385. self.Map.region['w'])
  1386. self.UpdateMap()
  1387. def SaveRegion(self, display = True):
  1388. """!Save display extents/compulational region to named region
  1389. file.
  1390. @param display True for display extends otherwise computational region
  1391. """
  1392. if display:
  1393. title = _("Save display extents to region file")
  1394. else:
  1395. title = _("Save computational region to region file")
  1396. dlg = SavedRegion(parent = self, title = title, loadsave = 'save')
  1397. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.GetName():
  1398. dlg.Destroy()
  1399. return
  1400. # test to see if it already exists and ask permission to overwrite
  1401. if grass.find_file(name = dlg.GetName(), element = 'windows')['name']:
  1402. overwrite = wx.MessageBox(parent = self,
  1403. message = _("Region file <%s> already exists. "
  1404. "Do you want to overwrite it?") % (dlg.GetName()),
  1405. caption = _("Warning"), style = wx.YES_NO | wx.CENTRE)
  1406. if overwrite != wx.YES:
  1407. dlg.Destroy()
  1408. return
  1409. if display:
  1410. self._saveDisplayRegion(dlg.GetName())
  1411. else:
  1412. self._saveCompRegion(dlg.GetName())
  1413. dlg.Destroy()
  1414. def _saveCompRegion(self, name):
  1415. """!Save region settings to region file
  1416. @param name region name
  1417. """
  1418. RunCommand('g.region',
  1419. overwrite = True,
  1420. parent = self,
  1421. flags = 'u',
  1422. save = name)
  1423. def _saveDisplayRegion(self, name):
  1424. """!Save display extents to region file
  1425. @param name region name
  1426. """
  1427. new = self.Map.GetCurrentRegion()
  1428. tmpreg = os.getenv("GRASS_REGION")
  1429. if tmpreg:
  1430. del os.environ["GRASS_REGION"]
  1431. RunCommand('g.region',
  1432. overwrite = True,
  1433. parent = self,
  1434. flags = 'u',
  1435. n = new['n'],
  1436. s = new['s'],
  1437. e = new['e'],
  1438. w = new['w'],
  1439. rows = int(new['rows']),
  1440. cols = int(new['cols']),
  1441. save = name)
  1442. if tmpreg:
  1443. os.environ["GRASS_REGION"] = tmpreg
  1444. def Distance(self, beginpt, endpt, screen = True):
  1445. """!Calculates distance
  1446. Ctypes required for LL-locations
  1447. @param beginpt first point
  1448. @param endpt second point
  1449. @param screen True for screen coordinates otherwise EN
  1450. """
  1451. if screen:
  1452. e1, n1 = self.Pixel2Cell(beginpt)
  1453. e2, n2 = self.Pixel2Cell(endpt)
  1454. else:
  1455. e1, n1 = beginpt
  1456. e2, n2 = endpt
  1457. dEast = (e2 - e1)
  1458. dNorth = (n2 - n1)
  1459. if self.frame.Map.projinfo['proj'] == 'll' and haveCtypes:
  1460. dist = gislib.G_distance(e1, n1, e2, n2)
  1461. else:
  1462. dist = math.sqrt(math.pow((dEast), 2) + math.pow((dNorth), 2))
  1463. return (dist, (dEast, dNorth))
  1464. def GetMap(self):
  1465. """!Get render.Map() instance"""
  1466. return self.Map
  1467. def RegisterMouseEventHandler(self, event, handler, cursor = None):
  1468. """!Calls UpdateTools to manage connected toolbars"""
  1469. self.frame.UpdateTools(None)
  1470. MapWindow.RegisterMouseEventHandler(self, event, handler, cursor)
  1471. def UnregisterMouseEventHandler(self, event, handler):
  1472. """!Sets pointer and toggles it after unregistration"""
  1473. MapWindow.UnregisterMouseEventHandler(self, event, handler)
  1474. # sets pointer mode
  1475. toolbar = self.frame.toolbars['map']
  1476. toolbar.action['id'] = vars(toolbar)["pointer"]
  1477. toolbar.OnTool(None)
  1478. self.frame.OnPointer(event = None)
  1479. def RegisterGraphicsToDraw(self, graphicsType, setStatusFunc = None, drawFunc = None):
  1480. """! Method allows to register graphics to draw.
  1481. @param type (string) - graphics type: "point" or "line"
  1482. @param setStatusFunc (function reference) - function called before drawing each item
  1483. Status function should be in this form: setStatusFunc(item, itemOrderNum)
  1484. item - passes instance of GraphicsSetItem which will be drawn
  1485. itemOrderNum - number of item in drawing order (from O)
  1486. Hidden items are also counted in drawing order.
  1487. @param drawFunc (function reference) - allows to define own function for drawing
  1488. If function is not defined DrawCross method is used for type "point"
  1489. or DrawLines method for type "line".
  1490. @return reference to GraphicsSet, which was added.
  1491. """
  1492. item = GraphicsSet(parentMapWin = self,
  1493. graphicsType = graphicsType,
  1494. setStatusFunc = setStatusFunc,
  1495. drawFunc = drawFunc)
  1496. self.graphicsSetList.append(item)
  1497. return item
  1498. def UnregisterGraphicsToDraw(self, item):
  1499. """!Unregisteres GraphicsSet instance
  1500. @param item (GraphicsSetItem) - item to unregister
  1501. @return True - if item was unregistered
  1502. @return False - if item was not found
  1503. """
  1504. if item in self.graphicsSetList:
  1505. self.graphicsSetList.remove(item)
  1506. return True
  1507. return False
  1508. class GraphicsSet:
  1509. def __init__(self, parentMapWin, graphicsType, setStatusFunc = None, drawFunc = None):
  1510. """!Class, which contains instances of GraphicsSetItem and
  1511. draws them For description of parameters look at method
  1512. RegisterGraphicsToDraw in BufferedWindow class.
  1513. """
  1514. self.pens = {
  1515. "default" : wx.Pen(colour = wx.BLACK, width = 2, style = wx.SOLID),
  1516. "selected" : wx.Pen(colour = wx.GREEN, width = 2, style = wx.SOLID),
  1517. "unused" : wx.Pen(colour = wx.LIGHT_GREY, width = 2, style = wx.SOLID),
  1518. "highest" : wx.Pen(colour = wx.RED, width = 2, style = wx.SOLID)
  1519. }
  1520. # list contains instances of GraphicsSetItem
  1521. self.itemsList = []
  1522. self.properties = {}
  1523. self.graphicsType = graphicsType
  1524. self.parentMapWin = parentMapWin
  1525. self.setStatusFunc = setStatusFunc
  1526. if drawFunc:
  1527. self.drawFunc = drawFunc
  1528. elif self.graphicsType == "point":
  1529. self.properties["size"] = 5
  1530. self.properties["text"] = {}
  1531. self.properties["text"]['font'] = wx.Font(pointSize = self.properties["size"],
  1532. family = wx.FONTFAMILY_DEFAULT,
  1533. style = wx.FONTSTYLE_NORMAL,
  1534. weight = wx.FONTWEIGHT_NORMAL)
  1535. self.properties["text"]['active'] = True
  1536. self.drawFunc = self.parentMapWin.DrawCross
  1537. elif self.graphicsType == "line":
  1538. self.drawFunc = self.parentMapWin.DrawLines
  1539. def Draw(self, pdc):
  1540. """!Draws all containing items.
  1541. @param pdc - device context, where items are drawn
  1542. """
  1543. itemOrderNum = 0
  1544. for item in self.itemsList:
  1545. if self.setStatusFunc is not None:
  1546. self.setStatusFunc(item, itemOrderNum)
  1547. if item.GetPropertyVal("hide") == True:
  1548. itemOrderNum += 1
  1549. continue
  1550. if self.graphicsType == "point":
  1551. if item.GetPropertyVal("penName"):
  1552. self.parentMapWin.pen = self.pens[item.GetPropertyVal("penName")]
  1553. else:
  1554. self.parentMapWin.pen = self.pens["default"]
  1555. coords = self.parentMapWin.Cell2Pixel(item.GetCoords())
  1556. size = self.properties["size"]
  1557. self.properties["text"]['coords'] = [coords[0] + size, coords[1] + size, size, size]
  1558. self.properties["text"]['color'] = self.parentMapWin.pen.GetColour()
  1559. self.properties["text"]['text'] = item.GetPropertyVal("label")
  1560. self.drawFunc(pdc = pdc,
  1561. coords = coords,
  1562. text = self.properties["text"],
  1563. size = self.properties["size"])
  1564. elif self.graphicsType == "line":
  1565. if item.GetPropertyVal("pen"):
  1566. self.parentMapWin.polypen = self.pens[item.GetPropertyVal("pen")]
  1567. else:
  1568. self.parentMapWin.polypen = self.pens["default"]
  1569. self.drawFunc(pdc = pdc,
  1570. polycoords = coords)
  1571. itemOrderNum += 1
  1572. def AddItem(self, coords, penName = None, label = None, hide = False):
  1573. """!Append item to the list.
  1574. Added item is put to the last place in drawing order.
  1575. Could be 'point' or 'line' according to graphicsType.
  1576. @param coords - list of east, north coordinates (double) of item
  1577. Example: point: [1023, 122]
  1578. line: [[10, 12],[20,40],[23, 2334]]
  1579. @param penName (string) - the 'default' pen is used if is not defined
  1580. @param label (string) - label, which will be drawn with point. It is relavant just for 'point' type.
  1581. @param hide (bool) - If it is True, the item is not drawn, when self.Draw is called.
  1582. Hidden items are also counted in drawing order.
  1583. @return (GraphicsSetItem) - added item reference
  1584. """
  1585. item = GraphicsSetItem(coords = coords, penName = penName, label = label, hide = hide)
  1586. self.itemsList.append(item)
  1587. return item
  1588. def DeleteItem(self, item):
  1589. """!Deletes item
  1590. @param item (GraphicsSetItem) - item to remove
  1591. @return True if item was removed
  1592. @return False if item was not found
  1593. """
  1594. try:
  1595. self.itemsList.remove(item)
  1596. except ValueError:
  1597. return False
  1598. return True
  1599. def GetAllItems(self):
  1600. """!Returns list of all containing instances of GraphicsSetItem, in order
  1601. as they are drawn. If you want to change order of drawing use: SetItemDrawOrder method.
  1602. """
  1603. # user can edit objects but not order in list, that is reason,
  1604. # why is returned shallow copy of data list it should be used
  1605. # SetItemDrawOrder for changing order
  1606. return copy(self.itemsList)
  1607. def GetItem(self, drawNum):
  1608. """!Get given item from the list.
  1609. @param drawNum (int) - drawing order (index) number of item
  1610. @return instance of GraphicsSetItem which is drawn in drawNum order
  1611. @return False if drawNum was out of range
  1612. """
  1613. if drawNum < len(self.itemsList) and drawNum >= 0:
  1614. return self.itemsList[drawNum]
  1615. else:
  1616. return False
  1617. def SetPropertyVal(self, propName, propVal):
  1618. """!Set property value
  1619. @param propName (string) - property name: "size", "text"
  1620. - both properties are relevant for "point" type
  1621. @param propVal - property value to be set
  1622. @return True - if value was set
  1623. @return False - if propName is not "size" or "text" or type is "line"
  1624. """
  1625. if self.properties.has_key(propName):
  1626. self.properties[propName] = propVal
  1627. return True
  1628. return False
  1629. def GetPropertyVal(self, propName):
  1630. """!Get property value
  1631. Raises KeyError if propName is not "size" or "text" or type is
  1632. "line"
  1633. @param propName (string) - property name: "size", "text"
  1634. - both properties are relevant for "point" type
  1635. @return value of property
  1636. """
  1637. if self.properties.has_key(propName):
  1638. return self.properties[propName]
  1639. raise KeyError(_("Property does not exist: %s") % (propName))
  1640. def AddPen(self, penName, pen):
  1641. """!Add pen
  1642. @param penName (string) - name of added pen
  1643. @param pen (wx.Pen) - added pen
  1644. @return True - if pen was added
  1645. @return False - if pen already exists
  1646. """
  1647. if self.pens.has_key(penName):
  1648. return False
  1649. self.pens[penName] = pen
  1650. return True
  1651. def GetPen(self, penName):
  1652. """!Get existing pen
  1653. @param penName (string) - name of pen
  1654. @return wx.Pen reference if is found
  1655. @return None if penName was not found
  1656. """
  1657. if self.pens.has_key(penName):
  1658. return self.pens[penName]
  1659. return None
  1660. def SetItemDrawOrder(self, item, drawNum):
  1661. """!Set draw order for item
  1662. @param item (GraphicsSetItem)
  1663. @param drawNum (int) - drawing order of item to be set
  1664. @return True - if order was changed
  1665. @return False - if drawNum is out of range or item was not found
  1666. """
  1667. if drawNum < len(self.itemsList) and drawNum >= 0 and \
  1668. item in self.itemsList:
  1669. self.itemsList.insert(drawNum, self.itemsList.pop(self.itemsList.index(item)))
  1670. return True
  1671. return False
  1672. def GetItemDrawOrder(self, item):
  1673. """!Get draw order for given item
  1674. @param item (GraphicsSetItem)
  1675. @return (int) - drawing order of item
  1676. @return None - if item was not found
  1677. """
  1678. try:
  1679. return self.itemsList.index(item)
  1680. except ValueError:
  1681. return None
  1682. class GraphicsSetItem:
  1683. def __init__(self, coords, penName = None, label = None, hide = False):
  1684. """!Could be point or line according to graphicsType in
  1685. GraphicsSet class
  1686. @param coords - list of coordinates (double) of item
  1687. Example: point: [1023, 122]
  1688. line: [[10, 12],[20,40],[23, 2334]]
  1689. @param penName (string) - if it is not defined 'default' pen is used
  1690. @param label (string) - label, which will be drawn with point. It is relevant just for 'point' type
  1691. @param hide (bool) - if it is True, item is not drawn
  1692. Hidden items are also counted in drawing order in GraphicsSet class.
  1693. """
  1694. self.coords = coords
  1695. self.properties = { "penName" : penName,
  1696. "hide" : hide,
  1697. "label" : label }
  1698. def SetPropertyVal(self, propName, propVal):
  1699. """!Set property value
  1700. @param propName (string) - property name: "penName", "hide" or "label"
  1701. - property "label" is relevant just for 'point' type
  1702. @param propVal - property value to be set
  1703. @return True - if value was set
  1704. @return False - if propName is not "penName", "hide" or "label"
  1705. """
  1706. if self.properties.has_key(propName):
  1707. self.properties[propName] = propVal
  1708. return True
  1709. return False
  1710. def GetPropertyVal(self, propName):
  1711. """!Get property value
  1712. Raises KeyError if propName is not "penName", "hide" or
  1713. "label".
  1714. @param propName (string) - property name: "penName", "hide" or "label"
  1715. - property "label" is relevant just for 'point' type
  1716. @return value of property
  1717. """
  1718. if self.properties.has_key(propName):
  1719. return self.properties[propName]
  1720. raise KeyError(_("Property does not exist: %s") % (propName))
  1721. def SetCoords(self, coords):
  1722. """!Set coordinates of item
  1723. @param coords - list of east, north coordinates (double) of item
  1724. Example: point: [1023, 122]
  1725. line: [[10, 12],[20,40],[23, 2334]]
  1726. """
  1727. self.coords = coords
  1728. def GetCoords(self):
  1729. """!Get item coordinates
  1730. @returns coordinates
  1731. """
  1732. return self.coords