mapwindow.py 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169
  1. """!
  2. @package mapdisp.mapwindow
  3. @brief Map display canvas - buffered window.
  4. Classes:
  5. - mapwindow::BufferedWindow
  6. - mapwindow::GraphicsSet
  7. - mapwindow::GraphicsSetItem
  8. (C) 2006-2012 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Martin Landa <landa.martin gmail.com>
  12. @author Michael Barton
  13. @author Jachym Cepicky
  14. @author Vaclav Petras <wenzeslaus gmail.com> (handlers support)
  15. @author Stepan Turek <stepan.turek seznam.cz> (handlers support, GraphicsSet)
  16. """
  17. import os
  18. import time
  19. import math
  20. import sys
  21. from copy import copy
  22. import wx
  23. import grass.script as grass
  24. from gui_core.dialogs import SavedRegion
  25. from core.gcmd import RunCommand, GException, GError, GMessage
  26. from core.debug import Debug
  27. from core.settings import UserSettings
  28. from gui_core.mapwindow import MapWindow
  29. try:
  30. import grass.lib.gis as gislib
  31. haveCtypes = True
  32. except ImportError:
  33. haveCtypes = False
  34. class BufferedWindow(MapWindow, wx.Window):
  35. """!A Buffered window class (2D view mode)
  36. Superclass for VDigitWindow (vector digitizer).
  37. When the drawing needs to change, you app needs to call the
  38. UpdateMap() method. Since the drawing is stored in a bitmap, you
  39. can also save the drawing to file by calling the
  40. SaveToFile() method.
  41. """
  42. def __init__(self, parent, giface, Map, frame,
  43. id = wx.ID_ANY, tree = None, lmgr = None,
  44. style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
  45. MapWindow.__init__(self, parent = parent, giface = giface, Map = Map,
  46. frame = frame, **kwargs)
  47. wx.Window.__init__(self, parent = parent, id = id, style = style, **kwargs)
  48. self.tree = tree
  49. # flags
  50. self.resize = False # indicates whether or not a resize event has taken place
  51. self.dragimg = None # initialize variable for map panning
  52. self.alwaysRender = False # if it always sets render to True in self.UpdateMap()
  53. # variables for drawing on DC
  54. self.pen = None # pen for drawing zoom boxes, etc.
  55. self.polypen = None # pen for drawing polylines (measurements, profiles, etc)
  56. # List of wx.Point tuples defining a polyline (geographical coordinates)
  57. self.polycoords = []
  58. # ID of rubber band line
  59. self.lineid = None
  60. # ID of poly line resulting from cumulative rubber band lines (e.g. measurement)
  61. self.plineid = None
  62. # event bindings
  63. self.Bind(wx.EVT_PAINT, self.OnPaint)
  64. self.Bind(wx.EVT_SIZE, self.OnSize)
  65. self.Bind(wx.EVT_IDLE, self.OnIdle)
  66. self._bindMouseEvents()
  67. self.processMouse = True
  68. # render output objects
  69. self.mapfile = None # image file to be rendered
  70. self.img = None # wx.Image object (self.mapfile)
  71. # decoration overlays
  72. self.overlays = {}
  73. # images and their PseudoDC ID's for painting and dragging
  74. self.imagedict = {}
  75. self.select = {} # selecting/unselecting decorations for dragging
  76. self.textdict = {} # text, font, and color indexed by id
  77. self.currtxtid = None # PseudoDC id for currently selected text
  78. # zoom objects
  79. self.zoomhistory = [] # list of past zoom extents
  80. self.currzoom = 0 # current set of extents in zoom history being used
  81. self.zoomtype = 1 # 1 zoom in, 0 no zoom, -1 zoom out
  82. self.hitradius = 10 # distance for selecting map decorations
  83. self.dialogOffset = 5 # offset for dialog (e.g. DisplayAttributesDialog)
  84. # OnSize called to make sure the buffer is initialized.
  85. # This might result in OnSize getting called twice on some
  86. # platforms at initialization, but little harm done.
  87. ### self.OnSize(None)
  88. self._definePseudoDC()
  89. # redraw all pdc's, pdcTmp layer is redrawn always (speed issue)
  90. self.redrawAll = True
  91. # will store an off screen empty bitmap for saving to file
  92. self._buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  93. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
  94. # vars for handling mouse clicks
  95. self.dragid = -1
  96. self.lastpos = (0, 0)
  97. # list for registration of graphics to draw
  98. self.graphicsSetList = []
  99. def _definePseudoDC(self):
  100. """!Define PseudoDC objects to use
  101. """
  102. # create PseudoDC used for background map, map decorations like scales and legends
  103. self.pdc = wx.PseudoDC()
  104. # used for digitization tool
  105. self.pdcVector = None
  106. # decorations (region box, etc.)
  107. self.pdcDec = wx.PseudoDC()
  108. # pseudoDC for temporal objects (select box, measurement tool, etc.)
  109. self.pdcTmp = wx.PseudoDC()
  110. def _bindMouseEvents(self):
  111. self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
  112. self.Bind(wx.EVT_MOTION, self.OnMotion)
  113. self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)
  114. def OnContextMenu(self, event):
  115. """!Show Map Display context menu"""
  116. if hasattr(self, "digit"):
  117. event.Skip()
  118. return
  119. if not hasattr(self, "popupCopyCoordinates"):
  120. self.popupCopyCoordinates = wx.NewId()
  121. self.Bind(wx.EVT_MENU, self.OnCopyCoordinates, id = self.popupCopyCoordinates)
  122. # generate popup-menu
  123. menu = wx.Menu()
  124. menu.Append(self.popupCopyCoordinates, _("Copy coordinates to clipboard"))
  125. self.PopupMenu(menu)
  126. menu.Destroy()
  127. def Draw(self, pdc, img = None, drawid = None, pdctype = 'image', coords = [0, 0, 0, 0]):
  128. """!Draws map and overlay decorations
  129. """
  130. if drawid == None:
  131. if pdctype == 'image' and img:
  132. drawid = self.imagedict[img]
  133. elif pdctype == 'clear':
  134. drawid = None
  135. else:
  136. drawid = wx.NewId()
  137. if img and pdctype == 'image':
  138. # self.imagedict[img]['coords'] = coords
  139. self.select[self.imagedict[img]['id']] = False # ?
  140. pdc.BeginDrawing()
  141. if drawid != 99:
  142. bg = wx.TRANSPARENT_BRUSH
  143. else:
  144. bg = wx.Brush(self.GetBackgroundColour())
  145. pdc.SetBackground(bg)
  146. Debug.msg (5, "BufferedWindow.Draw(): id=%s, pdctype = %s, coord=%s" % \
  147. (drawid, pdctype, coords))
  148. # set PseudoDC id
  149. if drawid is not None:
  150. pdc.SetId(drawid)
  151. if pdctype == 'clear': # erase the display
  152. bg = wx.WHITE_BRUSH
  153. # bg = wx.Brush(self.GetBackgroundColour())
  154. pdc.SetBackground(bg)
  155. pdc.RemoveAll()
  156. pdc.Clear()
  157. pdc.EndDrawing()
  158. self.Refresh()
  159. return
  160. if pdctype == 'image': # draw selected image
  161. bitmap = wx.BitmapFromImage(img)
  162. w,h = bitmap.GetSize()
  163. pdc.DrawBitmap(bitmap, coords[0], coords[1], True) # draw the composite map
  164. pdc.SetIdBounds(drawid, wx.Rect(coords[0],coords[1], w, h))
  165. elif pdctype == 'box': # draw a box on top of the map
  166. if self.pen:
  167. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  168. pdc.SetPen(self.pen)
  169. x2 = max(coords[0],coords[2])
  170. x1 = min(coords[0],coords[2])
  171. y2 = max(coords[1],coords[3])
  172. y1 = min(coords[1],coords[3])
  173. rwidth = x2-x1
  174. rheight = y2-y1
  175. rect = wx.Rect(x1, y1, rwidth, rheight)
  176. pdc.DrawRectangleRect(rect)
  177. pdc.SetIdBounds(drawid, rect)
  178. elif pdctype == 'line': # draw a line on top of the map
  179. if self.pen:
  180. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  181. pdc.SetPen(self.pen)
  182. pdc.DrawLinePoint(wx.Point(coords[0], coords[1]),wx.Point(coords[2], coords[3]))
  183. pdc.SetIdBounds(drawid, wx.Rect(coords[0], coords[1], coords[2], coords[3]))
  184. elif pdctype == 'polyline': # draw a polyline on top of the map
  185. if self.polypen:
  186. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  187. pdc.SetPen(self.polypen)
  188. if (len(coords) < 2):
  189. return
  190. i = 1
  191. while i < len(coords):
  192. pdc.DrawLinePoint(wx.Point(coords[i-1][0], coords[i-1][1]),
  193. wx.Point(coords[i][0], coords[i][1]))
  194. i += 1
  195. # get bounding rectangle for polyline
  196. xlist = []
  197. ylist = []
  198. if len(coords) > 0:
  199. for point in coords:
  200. x,y = point
  201. xlist.append(x)
  202. ylist.append(y)
  203. x1 = min(xlist)
  204. x2 = max(xlist)
  205. y1 = min(ylist)
  206. y2 = max(ylist)
  207. pdc.SetIdBounds(drawid, wx.Rect(x1,y1,x2,y2))
  208. # self.ovlcoords[drawid] = [x1,y1,x2,y2]
  209. elif pdctype == 'point': # draw point
  210. if self.pen:
  211. pdc.SetPen(self.pen)
  212. pdc.DrawPoint(coords[0], coords[1])
  213. coordsBound = (coords[0] - 5,
  214. coords[1] - 5,
  215. coords[0] + 5,
  216. coords[1] + 5)
  217. pdc.SetIdBounds(drawid, wx.Rect(coordsBound))
  218. elif pdctype == 'text': # draw text on top of map
  219. if not img['active']:
  220. return # only draw active text
  221. if 'rotation' in img:
  222. rotation = float(img['rotation'])
  223. else:
  224. rotation = 0.0
  225. w, h = self.GetFullTextExtent(img['text'])[0:2]
  226. pdc.SetFont(img['font'])
  227. pdc.SetTextForeground(img['color'])
  228. coords, bbox = self.TextBounds(img)
  229. if rotation == 0:
  230. pdc.DrawText(img['text'], coords[0], coords[1])
  231. else:
  232. pdc.DrawRotatedText(img['text'], coords[0], coords[1], rotation)
  233. pdc.SetIdBounds(drawid, bbox)
  234. pdc.EndDrawing()
  235. self.Refresh()
  236. return drawid
  237. def TextBounds(self, textinfo, relcoords = False):
  238. """!Return text boundary data
  239. @param textinfo text metadata (text, font, color, rotation)
  240. @param coords reference point
  241. @return coords of nonrotated text bbox (TL corner)
  242. @return bbox of rotated text bbox (wx.Rect)
  243. @return relCoords are text coord inside bbox
  244. """
  245. if 'rotation' in textinfo:
  246. rotation = float(textinfo['rotation'])
  247. else:
  248. rotation = 0.0
  249. coords = textinfo['coords']
  250. bbox = wx.Rect(coords[0], coords[1], 0, 0)
  251. relCoords = (0, 0)
  252. Debug.msg (4, "BufferedWindow.TextBounds(): text=%s, rotation=%f" % \
  253. (textinfo['text'], rotation))
  254. self.Update()
  255. self.SetFont(textinfo['font'])
  256. w, h = self.GetTextExtent(textinfo['text'])
  257. if rotation == 0:
  258. bbox[2], bbox[3] = w, h
  259. if relcoords:
  260. return coords, bbox, relCoords
  261. else:
  262. return coords, bbox
  263. boxh = math.fabs(math.sin(math.radians(rotation)) * w) + h
  264. boxw = math.fabs(math.cos(math.radians(rotation)) * w) + h
  265. if rotation > 0 and rotation < 90:
  266. bbox[1] -= boxh
  267. relCoords = (0, boxh)
  268. elif rotation >= 90 and rotation < 180:
  269. bbox[0] -= boxw
  270. bbox[1] -= boxh
  271. relCoords = (boxw, boxh)
  272. elif rotation >= 180 and rotation < 270:
  273. bbox[0] -= boxw
  274. relCoords = (boxw, 0)
  275. bbox[2] = boxw
  276. bbox[3] = boxh
  277. bbox.Inflate(h,h)
  278. if relcoords:
  279. return coords, bbox, relCoords
  280. else:
  281. return coords, bbox
  282. def OnPaint(self, event):
  283. """!Draw PseudoDC's to buffered paint DC
  284. If self.redrawAll is False on self.pdcTmp content is re-drawn
  285. """
  286. Debug.msg(4, "BufferedWindow.OnPaint(): redrawAll=%s" % self.redrawAll)
  287. dc = wx.BufferedPaintDC(self, self._buffer)
  288. dc.Clear()
  289. # use PrepareDC to set position correctly
  290. self.PrepareDC(dc)
  291. # create a clipping rect from our position and size
  292. # and update region
  293. rgn = self.GetUpdateRegion().GetBox()
  294. dc.SetClippingRect(rgn)
  295. switchDraw = False
  296. if self.redrawAll is None:
  297. self.redrawAll = True
  298. switchDraw = True
  299. if self.redrawAll: # redraw pdc and pdcVector
  300. # draw to the dc using the calculated clipping rect
  301. self.pdc.DrawToDCClipped(dc, rgn)
  302. # draw vector map layer
  303. if hasattr(self, "digit"):
  304. # decorate with GDDC (transparency)
  305. try:
  306. gcdc = wx.GCDC(dc)
  307. self.pdcVector.DrawToDCClipped(gcdc, rgn)
  308. except NotImplementedError, e:
  309. print >> sys.stderr, e
  310. self.pdcVector.DrawToDCClipped(dc, rgn)
  311. self.bufferLast = None
  312. else: # do not redraw pdc and pdcVector
  313. if self.bufferLast is None:
  314. # draw to the dc
  315. self.pdc.DrawToDC(dc)
  316. if hasattr(self, "digit"):
  317. # decorate with GDDC (transparency)
  318. try:
  319. gcdc = wx.GCDC(dc)
  320. self.pdcVector.DrawToDC(gcdc)
  321. except NotImplementedError, e:
  322. print >> sys.stderr, e
  323. self.pdcVector.DrawToDC(dc)
  324. # store buffered image
  325. # self.bufferLast = wx.BitmapFromImage(self.buffer.ConvertToImage())
  326. self.bufferLast = dc.GetAsBitmap(wx.Rect(0, 0, self.Map.width, self.Map.height))
  327. self.pdc.DrawBitmap(self.bufferLast, 0, 0, False)
  328. self.pdc.DrawToDC(dc)
  329. # draw decorations (e.g. region box)
  330. try:
  331. gcdc = wx.GCDC(dc)
  332. self.pdcDec.DrawToDC(gcdc)
  333. except NotImplementedError, e:
  334. print >> sys.stderr, e
  335. self.pdcDec.DrawToDC(dc)
  336. # draw temporary object on the foreground
  337. ### self.pdcTmp.DrawToDCClipped(dc, rgn)
  338. self.pdcTmp.DrawToDC(dc)
  339. if switchDraw:
  340. self.redrawAll = False
  341. def OnSize(self, event):
  342. """!Scale map image so that it is the same size as the Window
  343. """
  344. # re-render image on idle
  345. self.resize = time.clock()
  346. def OnIdle(self, event):
  347. """!Only re-render a composite map image from GRASS during
  348. idle time instead of multiple times during resizing.
  349. """
  350. # use OnInternalIdle() instead ?
  351. if self.resize and self.resize + 0.2 < time.clock():
  352. Debug.msg(3, "BufferedWindow.OnSize():")
  353. # set size of the input image
  354. self.Map.ChangeMapSize(self.GetClientSize())
  355. # Make new off screen bitmap: this bitmap will always have the
  356. # current drawing in it, so it can be used to save the image to
  357. # a file, or whatever.
  358. self._buffer.Destroy()
  359. self._buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  360. # get the image to be rendered
  361. self.img = self.GetImage()
  362. # update map display
  363. updatemap = True
  364. if self.img and self.Map.width + self.Map.height > 0: # scale image after resize
  365. self.img = self.img.Scale(self.Map.width, self.Map.height)
  366. if len(self.Map.GetListOfLayers()) > 0:
  367. self.UpdateMap()
  368. updatemap = False
  369. # reposition checkbox in statusbar
  370. self.frame.StatusbarReposition()
  371. # update statusbar
  372. self.frame.StatusbarUpdate()
  373. if updatemap:
  374. self.UpdateMap(render = True)
  375. self.resize = False
  376. elif self.resize:
  377. event.RequestMore()
  378. event.Skip()
  379. def SaveToFile(self, FileName, FileType, width, height):
  380. """!This draws the pseudo DC to a buffer that can be saved to
  381. a file.
  382. @param FileName file name
  383. @param FileType type of bitmap
  384. @param width image width
  385. @param height image height
  386. """
  387. busy = wx.BusyInfo(message = _("Please wait, exporting image..."),
  388. parent = self)
  389. wx.Yield()
  390. self.Map.ChangeMapSize((width, height))
  391. ibuffer = wx.EmptyBitmap(max(1, width), max(1, height))
  392. self.Map.Render(force = True, windres = self.frame.GetProperty('resolution'))
  393. img = self.GetImage()
  394. self.pdc.RemoveAll()
  395. self.Draw(self.pdc, img, drawid = 99)
  396. # compute size ratio to move overlay accordingly
  397. cSize = self.GetClientSizeTuple()
  398. ratio = float(width) / cSize[0], float(height) / cSize[1]
  399. # redraw legend, scalebar
  400. for img in self.GetOverlay():
  401. # draw any active and defined overlays
  402. if self.imagedict[img]['layer'].IsActive():
  403. id = self.imagedict[img]['id']
  404. coords = int(ratio[0] * self.overlays[id]['coords'][0]),\
  405. int(ratio[1] * self.overlays[id]['coords'][1])
  406. self.Draw(self.pdc, img = img, drawid = id,
  407. pdctype = self.overlays[id]['pdcType'], coords = coords)
  408. # redraw text labels
  409. for id in self.textdict.keys():
  410. textinfo = self.textdict[id]
  411. oldCoords = textinfo['coords']
  412. textinfo['coords'] = ratio[0] * textinfo['coords'][0],\
  413. ratio[1] * textinfo['coords'][1]
  414. self.Draw(self.pdc, img = self.textdict[id], drawid = id,
  415. pdctype = 'text')
  416. # set back old coordinates
  417. textinfo['coords'] = oldCoords
  418. dc = wx.BufferedDC(None, ibuffer)
  419. dc.Clear()
  420. self.PrepareDC(dc)
  421. self.pdc.DrawToDC(dc)
  422. if self.pdcVector:
  423. self.pdcVector.DrawToDC(dc)
  424. ibuffer.SaveFile(FileName, FileType)
  425. busy.Destroy()
  426. self.UpdateMap(render = True)
  427. self.Refresh()
  428. def GetOverlay(self):
  429. """!Converts rendered overlay files to wx.Image
  430. Updates self.imagedict
  431. @return list of images
  432. """
  433. imgs = []
  434. for overlay in self.Map.GetListOfLayers(l_type = "overlay", l_active = True):
  435. if overlay.mapfile is not None \
  436. and os.path.isfile(overlay.mapfile) and os.path.getsize(overlay.mapfile):
  437. img = wx.Image(overlay.mapfile, wx.BITMAP_TYPE_ANY)
  438. for key in self.imagedict.keys():
  439. if self.imagedict[key]['id'] == overlay.id:
  440. del self.imagedict[key]
  441. self.imagedict[img] = { 'id' : overlay.id,
  442. 'layer' : overlay }
  443. imgs.append(img)
  444. return imgs
  445. def GetImage(self):
  446. """!Converts redered map files to wx.Image
  447. Updates self.imagedict (id=99)
  448. @return wx.Image instance (map composition)
  449. """
  450. imgId = 99
  451. if self.mapfile and self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
  452. os.path.getsize(self.Map.mapfile):
  453. img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
  454. else:
  455. img = None
  456. for key in self.imagedict.keys():
  457. if self.imagedict[key]['id'] == imgId:
  458. del self.imagedict[key]
  459. self.imagedict[img] = { 'id': imgId }
  460. return img
  461. def SetAlwaysRenderEnabled(self, alwaysRender = True):
  462. self.alwaysRender = alwaysRender
  463. def IsAlwaysRenderEnabled(self):
  464. return self.alwaysRender
  465. def UpdateMap(self, render = True, renderVector = True):
  466. """!Updates the canvas anytime there is a change to the
  467. underlaying images or to the geometry of the canvas.
  468. @param render re-render map composition
  469. @param renderVector re-render vector map layer enabled for editing (used for digitizer)
  470. """
  471. start = time.clock()
  472. self.resize = False
  473. # was if self.Map.cmdfile and ...
  474. if self.IsAlwaysRenderEnabled() and self.img is None:
  475. render = True
  476. #
  477. # initialize process bar (only on 'render')
  478. #
  479. if render or renderVector:
  480. self.frame.GetProgressBar().Show()
  481. if self.frame.GetProgressBar().GetRange() > 0:
  482. self.frame.GetProgressBar().SetValue(1)
  483. #
  484. # render background image if needed
  485. #
  486. # update layer dictionary if there has been a change in layers
  487. if self.tree and self.tree.reorder:
  488. self.tree.ReorderLayers()
  489. # reset flag for auto-rendering
  490. if self.tree:
  491. self.tree.rerender = False
  492. try:
  493. if render:
  494. # update display size
  495. self.Map.ChangeMapSize(self.GetClientSize())
  496. if self.frame.GetProperty('resolution'):
  497. # use computation region resolution for rendering
  498. windres = True
  499. else:
  500. windres = False
  501. self.mapfile = self.Map.Render(force = True, mapWindow = self.frame,
  502. windres = windres)
  503. else:
  504. self.mapfile = self.Map.Render(force = False, mapWindow = self.frame)
  505. except GException, e:
  506. GError(message = e.value)
  507. self.mapfile = None
  508. self.img = self.GetImage() # id=99
  509. #
  510. # clear pseudoDcs
  511. #
  512. for pdc in (self.pdc,
  513. self.pdcDec,
  514. self.pdcTmp):
  515. pdc.Clear()
  516. pdc.RemoveAll()
  517. #
  518. # draw background map image to PseudoDC
  519. #
  520. if not self.img:
  521. self.Draw(self.pdc, pdctype = 'clear')
  522. else:
  523. try:
  524. id = self.imagedict[self.img]['id']
  525. except:
  526. return False
  527. self.Draw(self.pdc, self.img, drawid = id)
  528. #
  529. # render vector map layer
  530. #
  531. if renderVector and hasattr(self, "digit"):
  532. self._updateMap()
  533. #
  534. # render overlays
  535. #
  536. for img in self.GetOverlay():
  537. # draw any active and defined overlays
  538. if self.imagedict[img]['layer'].IsActive():
  539. id = self.imagedict[img]['id']
  540. self.Draw(self.pdc, img = img, drawid = id,
  541. pdctype = self.overlays[id]['pdcType'], coords = self.overlays[id]['coords'])
  542. for id in self.textdict.keys():
  543. self.Draw(self.pdc, img = self.textdict[id], drawid = id,
  544. pdctype = 'text', coords = [10, 10, 10, 10])
  545. # optionally draw computational extent box
  546. self.DrawCompRegionExtent()
  547. #
  548. # redraw pdcTmp if needed
  549. #
  550. # draw registered graphics
  551. if len(self.graphicsSetList) > 0:
  552. penOrig = self.pen
  553. polypenOrig = self.polypen
  554. for item in self.graphicsSetList:
  555. try:
  556. item.Draw(self.pdcTmp)
  557. except:
  558. GError(parent = self,
  559. message = _('Unable to draw registered graphics. '
  560. 'The graphics was unregistered.'))
  561. self.UnregisterGraphicsToDraw(item)
  562. self.pen = penOrig
  563. self.polypen = polypenOrig
  564. if len(self.polycoords) > 0:
  565. self.DrawLines(self.pdcTmp)
  566. #
  567. # clear measurement
  568. #
  569. if self.mouse["use"] == "measure":
  570. self.ClearLines(pdc = self.pdcTmp)
  571. self.polycoords = []
  572. self.mouse['use'] = 'pointer'
  573. self.mouse['box'] = 'point'
  574. self.mouse['end'] = [0, 0]
  575. self.SetCursor(self.frame.cursors["default"])
  576. stop = time.clock()
  577. #
  578. # hide process bar
  579. #
  580. self.frame.GetProgressBar().Hide()
  581. #
  582. # update statusbar
  583. #
  584. ### self.Map.SetRegion()
  585. self.frame.StatusbarUpdate()
  586. Debug.msg (1, "BufferedWindow.UpdateMap(): render=%s, renderVector=%s -> time=%g" % \
  587. (render, renderVector, (stop-start)))
  588. return True
  589. def DrawCompRegionExtent(self):
  590. """!Draw computational region extent in the display
  591. Display region is drawn as a blue box inside the computational region,
  592. computational region inside a display region as a red box).
  593. """
  594. if hasattr(self, "regionCoords"):
  595. compReg = self.Map.GetRegion()
  596. dispReg = self.Map.GetCurrentRegion()
  597. reg = None
  598. if self.IsInRegion(dispReg, compReg):
  599. self.polypen = wx.Pen(colour = wx.Colour(0, 0, 255, 128), width = 3, style = wx.SOLID)
  600. reg = dispReg
  601. else:
  602. self.polypen = wx.Pen(colour = wx.Colour(255, 0, 0, 128),
  603. width = 3, style = wx.SOLID)
  604. reg = compReg
  605. self.regionCoords = []
  606. self.regionCoords.append((reg['w'], reg['n']))
  607. self.regionCoords.append((reg['e'], reg['n']))
  608. self.regionCoords.append((reg['e'], reg['s']))
  609. self.regionCoords.append((reg['w'], reg['s']))
  610. self.regionCoords.append((reg['w'], reg['n']))
  611. # draw region extent
  612. self.DrawLines(pdc = self.pdcDec, polycoords = self.regionCoords)
  613. def IsInRegion(self, region, refRegion):
  614. """!
  615. Test if 'region' is inside of 'refRegion'
  616. @param region input region
  617. @param refRegion reference region (e.g. computational region)
  618. @return True if region is inside of refRegion
  619. @return False
  620. """
  621. if region['s'] >= refRegion['s'] and \
  622. region['n'] <= refRegion['n'] and \
  623. region['w'] >= refRegion['w'] and \
  624. region['e'] <= refRegion['e']:
  625. return True
  626. return False
  627. def EraseMap(self):
  628. """!Erase map canvas
  629. """
  630. self.Draw(self.pdc, pdctype = 'clear')
  631. if hasattr(self, "digit"):
  632. self.Draw(self.pdcVector, pdctype = 'clear')
  633. self.Draw(self.pdcDec, pdctype = 'clear')
  634. self.Draw(self.pdcTmp, pdctype = 'clear')
  635. def DragMap(self, moveto):
  636. """!Drag the entire map image for panning.
  637. @param moveto dx,dy
  638. """
  639. dc = wx.BufferedDC(wx.ClientDC(self))
  640. dc.SetBackground(wx.Brush("White"))
  641. dc.Clear()
  642. self.dragimg = wx.DragImage(self._buffer)
  643. self.dragimg.BeginDrag((0, 0), self)
  644. self.dragimg.GetImageRect(moveto)
  645. self.dragimg.Move(moveto)
  646. self.dragimg.DoDrawImage(dc, moveto)
  647. self.dragimg.EndDrag()
  648. def DragItem(self, id, event):
  649. """!Drag an overlay decoration item
  650. """
  651. if id == 99 or id == '' or id == None: return
  652. Debug.msg (5, "BufferedWindow.DragItem(): id=%d" % id)
  653. x, y = self.lastpos
  654. dx = event.GetX() - x
  655. dy = event.GetY() - y
  656. self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
  657. r = self.pdc.GetIdBounds(id)
  658. if type(r) is list:
  659. r = wx.Rect(r[0], r[1], r[2], r[3])
  660. if id > 100: # text dragging
  661. rtop = (r[0],r[1]-r[3],r[2],r[3])
  662. r = r.Union(rtop)
  663. rleft = (r[0]-r[2],r[1],r[2],r[3])
  664. r = r.Union(rleft)
  665. self.pdc.TranslateId(id, dx, dy)
  666. r2 = self.pdc.GetIdBounds(id)
  667. if type(r2) is list:
  668. r2 = wx.Rect(r[0], r[1], r[2], r[3])
  669. if id > 100: # text
  670. self.textdict[id]['bbox'] = r2
  671. self.textdict[id]['coords'][0] += dx
  672. self.textdict[id]['coords'][1] += dy
  673. r = r.Union(r2)
  674. r.Inflate(4,4)
  675. self.RefreshRect(r, False)
  676. self.lastpos = (event.GetX(), event.GetY())
  677. def MouseDraw(self, pdc = None, begin = None, end = None):
  678. """!Mouse box or line from 'begin' to 'end'
  679. If not given from self.mouse['begin'] to self.mouse['end'].
  680. """
  681. if not pdc:
  682. return
  683. if begin is None:
  684. begin = self.mouse['begin']
  685. if end is None:
  686. end = self.mouse['end']
  687. Debug.msg (5, "BufferedWindow.MouseDraw(): use=%s, box=%s, begin=%f,%f, end=%f,%f" % \
  688. (self.mouse['use'], self.mouse['box'],
  689. begin[0], begin[1], end[0], end[1]))
  690. if self.mouse['box'] == "box":
  691. boxid = wx.ID_NEW
  692. mousecoords = [begin[0], begin[1],
  693. end[0], end[1]]
  694. r = pdc.GetIdBounds(boxid)
  695. if type(r) is list:
  696. r = wx.Rect(r[0], r[1], r[2], r[3])
  697. r.Inflate(4, 4)
  698. try:
  699. pdc.ClearId(boxid)
  700. except:
  701. pass
  702. self.RefreshRect(r, False)
  703. pdc.SetId(boxid)
  704. self.Draw(pdc, drawid = boxid, pdctype = 'box', coords = mousecoords)
  705. elif self.mouse['box'] == "line":
  706. self.lineid = wx.ID_NEW
  707. mousecoords = [begin[0], begin[1], \
  708. end[0], end[1]]
  709. x1 = min(begin[0],end[0])
  710. x2 = max(begin[0],end[0])
  711. y1 = min(begin[1],end[1])
  712. y2 = max(begin[1],end[1])
  713. r = wx.Rect(x1,y1,x2-x1,y2-y1)
  714. r.Inflate(4,4)
  715. try:
  716. pdc.ClearId(self.lineid)
  717. except:
  718. pass
  719. self.RefreshRect(r, False)
  720. pdc.SetId(self.lineid)
  721. self.Draw(pdc, drawid = self.lineid, pdctype = 'line', coords = mousecoords)
  722. def DrawLines(self, pdc = None, polycoords = None):
  723. """!Draw polyline in PseudoDC
  724. Set self.pline to wx.NEW_ID + 1
  725. polycoords - list of polyline vertices, geographical coordinates
  726. (if not given, self.polycoords is used)
  727. """
  728. if not pdc:
  729. pdc = self.pdcTmp
  730. if not polycoords:
  731. polycoords = self.polycoords
  732. if len(polycoords) > 0:
  733. self.plineid = wx.ID_NEW + 1
  734. # convert from EN to XY
  735. coords = []
  736. for p in polycoords:
  737. coords.append(self.Cell2Pixel(p))
  738. self.Draw(pdc, drawid = self.plineid, pdctype = 'polyline', coords = coords)
  739. Debug.msg (4, "BufferedWindow.DrawLines(): coords=%s, id=%s" % \
  740. (coords, self.plineid))
  741. return self.plineid
  742. return -1
  743. def DrawCross(self, pdc, coords, size, rotation = 0,
  744. text = None, textAlign = 'lr', textOffset = (5, 5)):
  745. """!Draw cross in PseudoDC
  746. @todo implement rotation
  747. @param pdc PseudoDC
  748. @param coords center coordinates
  749. @param rotation rotate symbol
  750. @param text draw also text (text, font, color, rotation)
  751. @param textAlign alignment (default 'lower-right')
  752. @param textOffset offset for text (from center point)
  753. """
  754. Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" % \
  755. (pdc, coords, size))
  756. coordsCross = ((coords[0] - size, coords[1], coords[0] + size, coords[1]),
  757. (coords[0], coords[1] - size, coords[0], coords[1] + size))
  758. self.lineid = wx.NewId()
  759. for lineCoords in coordsCross:
  760. self.Draw(pdc, drawid = self.lineid, pdctype = 'line', coords = lineCoords)
  761. if not text:
  762. return self.lineid
  763. if textAlign == 'ul':
  764. coord = [coords[0] - textOffset[0], coords[1] - textOffset[1], 0, 0]
  765. elif textAlign == 'ur':
  766. coord = [coords[0] + textOffset[0], coords[1] - textOffset[1], 0, 0]
  767. elif textAlign == 'lr':
  768. coord = [coords[0] + textOffset[0], coords[1] + textOffset[1], 0, 0]
  769. else:
  770. coord = [coords[0] - textOffset[0], coords[1] + textOffset[1], 0, 0]
  771. self.Draw(pdc, img = text,
  772. pdctype = 'text', coords = coord)
  773. return self.lineid
  774. def _computeZoomToPointAndRecenter(self, position, zoomtype):
  775. """!Computes zoom parameters for recenter mode.
  776. Computes begin and end parameters for Zoom() method.
  777. Used for zooming by single click (not box)
  778. and mouse wheel zooming (zoom and recenter mode).
  779. """
  780. if zoomtype > 0:
  781. begin = (position[0] - self.Map.width / 4,
  782. position[1] - self.Map.height / 4)
  783. end = (position[0] + self.Map.width / 4,
  784. position[1] + self.Map.height / 4)
  785. else:
  786. begin = ((self.Map.width - position[0]) / 2,
  787. (self.Map.height - position[1]) / 2)
  788. end = (begin[0] + self.Map.width / 2,
  789. begin[1] + self.Map.height / 2)
  790. return begin, end
  791. def MouseActions(self, event):
  792. """!Mouse motion and button click notifier
  793. """
  794. if not self.processMouse:
  795. return
  796. # zoom with mouse wheel
  797. if event.GetWheelRotation() != 0:
  798. self.OnMouseWheel(event)
  799. # left mouse button pressed
  800. elif event.LeftDown():
  801. self.OnLeftDown(event)
  802. # left mouse button released
  803. elif event.LeftUp():
  804. self.OnLeftUp(event)
  805. # dragging
  806. elif event.Dragging():
  807. self.OnDragging(event)
  808. # double click
  809. elif event.ButtonDClick():
  810. self.OnButtonDClick(event)
  811. # middle mouse button pressed
  812. elif event.MiddleDown():
  813. self.OnMiddleDown(event)
  814. # middle mouse button relesed
  815. elif event.MiddleUp():
  816. self.OnMiddleUp(event)
  817. # right mouse button pressed
  818. elif event.RightDown():
  819. self.OnRightDown(event)
  820. # right mouse button released
  821. elif event.RightUp():
  822. self.OnRightUp(event)
  823. elif event.Entering():
  824. self.OnMouseEnter(event)
  825. elif event.Moving():
  826. self.OnMouseMoving(event)
  827. def OnMouseWheel(self, event):
  828. """!Mouse wheel moved
  829. """
  830. zoomBehaviour = UserSettings.Get(group = 'display',
  831. key = 'mouseWheelZoom',
  832. subkey = 'selection')
  833. if zoomBehaviour == 2:
  834. event.Skip()
  835. return
  836. self.processMouse = False
  837. current = event.GetPositionTuple()[:]
  838. wheel = event.GetWheelRotation()
  839. Debug.msg (5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
  840. if wheel > 0:
  841. zoomtype = 1
  842. else:
  843. zoomtype = -1
  844. if UserSettings.Get(group = 'display',
  845. key = 'scrollDirection',
  846. subkey = 'selection'):
  847. zoomtype *= -1
  848. # zoom 1/2 of the screen (TODO: settings)
  849. if zoomBehaviour == 0: # zoom and recenter
  850. begin, end = self._computeZoomToPointAndRecenter(position = current, zoomtype = zoomtype)
  851. elif zoomBehaviour == 1: # zoom to current cursor position
  852. begin = (current[0]/2, current[1]/2)
  853. end = ((self.Map.width - current[0])/2 + current[0],
  854. (self.Map.height - current[1])/2 + current[1])
  855. # zoom
  856. self.Zoom(begin, end, zoomtype)
  857. # redraw map
  858. self.UpdateMap()
  859. # update statusbar
  860. self.frame.StatusbarUpdate()
  861. self.Refresh()
  862. self.processMouse = True
  863. def OnDragging(self, event):
  864. """!Mouse dragging
  865. """
  866. Debug.msg (5, "BufferedWindow.MouseAction(): Dragging")
  867. current = event.GetPositionTuple()[:]
  868. previous = self.mouse['begin']
  869. move = (current[0] - previous[0],
  870. current[1] - previous[1])
  871. if hasattr(self, "digit"):
  872. digitToolbar = self.toolbar
  873. else:
  874. digitToolbar = None
  875. # dragging or drawing box with left button
  876. if self.mouse['use'] == 'pan' or \
  877. event.MiddleIsDown():
  878. self.DragMap(move)
  879. # dragging decoration overlay item
  880. elif (self.mouse['use'] == 'pointer' and
  881. not digitToolbar and
  882. self.dragid != None):
  883. self.DragItem(self.dragid, event)
  884. # dragging anything else - rubber band box or line
  885. else:
  886. if (self.mouse['use'] == 'pointer' and
  887. not digitToolbar):
  888. return
  889. self.mouse['end'] = event.GetPositionTuple()[:]
  890. if (event.LeftIsDown() and
  891. not (digitToolbar and
  892. digitToolbar.GetAction() in ("moveLine",) and
  893. self.digit.GetDisplay().GetSelected() > 0)):
  894. self.MouseDraw(pdc = self.pdcTmp)
  895. def OnLeftDown(self, event):
  896. """!Left mouse button pressed
  897. """
  898. Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
  899. self.mouse["use"])
  900. self.mouse['begin'] = event.GetPositionTuple()[:]
  901. if self.mouse["use"] in ["measure", "profile"]:
  902. # measure or profile
  903. if len(self.polycoords) == 0:
  904. self.mouse['end'] = self.mouse['begin']
  905. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  906. self.ClearLines(pdc=self.pdcTmp)
  907. else:
  908. self.mouse['begin'] = self.mouse['end']
  909. elif self.mouse['use'] in ('zoom', 'legend'):
  910. pass
  911. # vector digizer
  912. elif self.mouse["use"] == "pointer" and \
  913. hasattr(self, "digit"):
  914. if event.ControlDown():
  915. self.OnLeftDownUndo(event)
  916. else:
  917. self._onLeftDown(event)
  918. elif self.mouse['use'] == 'pointer':
  919. # get decoration or text id
  920. self.idlist = []
  921. self.dragid = ''
  922. self.lastpos = self.mouse['begin']
  923. idlist = self.pdc.FindObjects(self.lastpos[0], self.lastpos[1],
  924. self.hitradius)
  925. if 99 in idlist:
  926. idlist.remove(99)
  927. if idlist != []:
  928. self.dragid = idlist[0] #drag whatever is on top
  929. else:
  930. pass
  931. event.Skip()
  932. def OnLeftUp(self, event):
  933. """!Left mouse button released
  934. """
  935. Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
  936. self.mouse["use"])
  937. self.mouse['end'] = event.GetPositionTuple()[:]
  938. if self.mouse['use'] in ["zoom", "pan"]:
  939. # set region in zoom or pan
  940. begin = self.mouse['begin']
  941. end = self.mouse['end']
  942. if self.mouse['use'] == 'zoom':
  943. # set region for click (zero-width box)
  944. if begin[0] - end[0] == 0 or \
  945. begin[1] - end[1] == 0:
  946. begin, end = self._computeZoomToPointAndRecenter(position = end, zoomtype = self.zoomtype)
  947. self.Zoom(begin, end, self.zoomtype)
  948. # redraw map
  949. self.UpdateMap(render = True)
  950. # update statusbar
  951. self.frame.StatusbarUpdate()
  952. elif self.mouse["use"] == "query":
  953. # querying
  954. if self.frame.IsStandalone():
  955. GMessage(parent = self.frame,
  956. message = _("Querying is not implemented in standalone mode of Map Display"))
  957. return
  958. layers = self.tree.GetSelectedLayer(multi = True, checkedOnly = True)
  959. self.frame.Query(self.mouse['begin'][0],self.mouse['begin'][1], layers)
  960. elif self.mouse["use"] in ["measure", "profile"]:
  961. # measure or profile
  962. if self.mouse["use"] == "measure":
  963. self.frame.MeasureDist(self.mouse['begin'], self.mouse['end'])
  964. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  965. self.ClearLines(pdc = self.pdcTmp)
  966. self.DrawLines(pdc = self.pdcTmp)
  967. elif self.mouse["use"] == "pointer" and \
  968. not self.frame.IsStandalone() and \
  969. self.frame.GetLayerManager().gcpmanagement:
  970. # -> GCP manager
  971. if self.frame.GetToolbar('gcpdisp'):
  972. coord = self.Pixel2Cell(self.mouse['end'])
  973. if self.frame.MapWindow == self.frame.SrcMapWindow:
  974. coordtype = 'source'
  975. else:
  976. coordtype = 'target'
  977. self.frame.GetLayerManager().gcpmanagement.SetGCPData(coordtype, coord, self, confirm = True)
  978. self.UpdateMap(render = False, renderVector = False)
  979. elif self.mouse["use"] == "pointer" and \
  980. hasattr(self, "digit"):
  981. self._onLeftUp(event)
  982. elif (self.mouse['use'] == 'pointer' and
  983. self.dragid >= 0):
  984. # end drag of overlay decoration
  985. if self.dragid < 99 and self.dragid in self.overlays:
  986. self.overlays[self.dragid]['coords'] = self.pdc.GetIdBounds(self.dragid)
  987. elif self.dragid > 100 and self.dragid in self.textdict:
  988. self.textdict[self.dragid]['bbox'] = self.pdc.GetIdBounds(self.dragid)
  989. else:
  990. pass
  991. self.dragid = None
  992. self.currtxtid = None
  993. elif self.mouse['use'] == 'legend':
  994. self.ResizeLegend(self.mouse["begin"], self.mouse["end"])
  995. self.frame.dialogs['legend'].FindWindowByName("resize").SetValue(False)
  996. self.Map.GetOverlay(1).SetActive(True)
  997. self.frame.MapWindow.SetCursor(self.frame.cursors["default"])
  998. self.frame.MapWindow.mouse['use'] = 'pointer'
  999. self.UpdateMap()
  1000. def OnButtonDClick(self, event):
  1001. """!Mouse button double click
  1002. """
  1003. Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
  1004. self.mouse["use"])
  1005. if self.mouse["use"] == "measure":
  1006. # measure
  1007. self.ClearLines(pdc=self.pdcTmp)
  1008. self.polycoords = []
  1009. self.mouse['use'] = 'pointer'
  1010. self.mouse['box'] = 'point'
  1011. self.mouse['end'] = [0, 0]
  1012. self.Refresh()
  1013. self.SetCursor(self.frame.cursors["default"])
  1014. elif self.mouse["use"] != "profile" or \
  1015. (self.mouse['use'] != 'pointer' and \
  1016. hasattr(self, "digit")):
  1017. # select overlay decoration options dialog
  1018. clickposition = event.GetPositionTuple()[:]
  1019. idlist = self.pdc.FindObjects(clickposition[0], clickposition[1], self.hitradius)
  1020. if idlist == []:
  1021. return
  1022. self.dragid = idlist[0]
  1023. # self.ovlcoords[self.dragid] = self.pdc.GetIdBounds(self.dragid)
  1024. if self.dragid > 100:
  1025. self.currtxtid = self.dragid
  1026. self.frame.OnAddText(None)
  1027. elif self.dragid == 0:
  1028. self.frame.OnAddBarscale(None)
  1029. elif self.dragid == 1:
  1030. self.frame.OnAddLegend(None)
  1031. def OnRightDown(self, event):
  1032. """!Right mouse button pressed
  1033. """
  1034. Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
  1035. self.mouse["use"])
  1036. if hasattr(self, "digit"):
  1037. self._onRightDown(event)
  1038. event.Skip()
  1039. def OnRightUp(self, event):
  1040. """!Right mouse button released
  1041. """
  1042. Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
  1043. self.mouse["use"])
  1044. if hasattr(self, "digit"):
  1045. self._onRightUp(event)
  1046. self.redrawAll = True
  1047. self.Refresh()
  1048. event.Skip()
  1049. def OnMiddleDown(self, event):
  1050. """!Middle mouse button pressed
  1051. """
  1052. if not event:
  1053. return
  1054. self.mouse['begin'] = event.GetPositionTuple()[:]
  1055. def OnMiddleUp(self, event):
  1056. """!Middle mouse button released
  1057. """
  1058. self.mouse['end'] = event.GetPositionTuple()[:]
  1059. # set region in zoom or pan
  1060. begin = self.mouse['begin']
  1061. end = self.mouse['end']
  1062. self.Zoom(begin, end, 0) # no zoom
  1063. # redraw map
  1064. self.UpdateMap(render = True)
  1065. # update statusbar
  1066. self.frame.StatusbarUpdate()
  1067. def OnMouseEnter(self, event):
  1068. """!Mouse entered window and no mouse buttons were pressed
  1069. """
  1070. if not self.frame.IsStandalone() and \
  1071. self.frame.GetLayerManager().gcpmanagement:
  1072. if self.frame.GetToolbar('gcpdisp'):
  1073. if not self.frame.MapWindow == self:
  1074. self.frame.MapWindow = self
  1075. self.frame.Map = self.Map
  1076. self.frame.UpdateActive(self)
  1077. # needed for wingrass
  1078. self.SetFocus()
  1079. else:
  1080. event.Skip()
  1081. def OnMouseMoving(self, event):
  1082. """!Motion event and no mouse buttons were pressed
  1083. """
  1084. if self.mouse["use"] == "pointer" and \
  1085. hasattr(self, "digit"):
  1086. self._onMouseMoving(event)
  1087. event.Skip()
  1088. def OnCopyCoordinates(self, event):
  1089. """!Copy coordinates to cliboard"""
  1090. e, n = self.GetLastEN()
  1091. if wx.TheClipboard.Open():
  1092. do = wx.TextDataObject()
  1093. # TODO: put delimiter in settings and apply also for Go to in statusbar
  1094. delim = ';'
  1095. do.SetText(str(e) + delim + str(n))
  1096. wx.TheClipboard.SetData(do)
  1097. wx.TheClipboard.Close()
  1098. def ClearLines(self, pdc = None):
  1099. """!Clears temporary drawn lines from PseudoDC
  1100. """
  1101. if not pdc:
  1102. pdc = self.pdcTmp
  1103. try:
  1104. pdc.ClearId(self.lineid)
  1105. pdc.RemoveId(self.lineid)
  1106. except:
  1107. pass
  1108. try:
  1109. pdc.ClearId(self.plineid)
  1110. pdc.RemoveId(self.plineid)
  1111. except:
  1112. pass
  1113. Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
  1114. (self.lineid, self.plineid))
  1115. return True
  1116. def Pixel2Cell(self, (x, y)):
  1117. """!Convert image coordinates to real word coordinates
  1118. @param x, y image coordinates
  1119. @return easting, northing
  1120. @return None on error
  1121. """
  1122. try:
  1123. x = int(x)
  1124. y = int(y)
  1125. except:
  1126. return None
  1127. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1128. res = self.Map.region["ewres"]
  1129. else:
  1130. res = self.Map.region["nsres"]
  1131. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1132. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1133. east = w + x * res
  1134. north = n - y * res
  1135. return (east, north)
  1136. def Cell2Pixel(self, (east, north)):
  1137. """!Convert real word coordinates to image coordinates
  1138. """
  1139. try:
  1140. east = float(east)
  1141. north = float(north)
  1142. except:
  1143. return None
  1144. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1145. res = self.Map.region["ewres"]
  1146. else:
  1147. res = self.Map.region["nsres"]
  1148. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1149. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1150. x = (east - w) / res
  1151. y = (n - north) / res
  1152. return (x, y)
  1153. def ResizeLegend(self, begin, end):
  1154. w = abs(begin[0] - end[0])
  1155. h = abs(begin[1] - end[1])
  1156. if begin[0] < end[0]:
  1157. x = begin[0]
  1158. else:
  1159. x = end[0]
  1160. if begin[1] < end[1]:
  1161. y = begin[1]
  1162. else:
  1163. y = end[1]
  1164. screenSize = self.GetClientSizeTuple()
  1165. at = [(screenSize[1] - (y + h)) / float(screenSize[1]) * 100,
  1166. (screenSize[1] - y) / float(screenSize[1]) * 100,
  1167. x / float(screenSize[0]) * 100,
  1168. (x + w) / float(screenSize[0]) * 100]
  1169. for i, subcmd in enumerate(self.overlays[1]['cmd']):
  1170. if subcmd.startswith('at='):
  1171. self.overlays[1]['cmd'][i] = "at=%d,%d,%d,%d" % (at[0], at[1], at[2], at[3])
  1172. self.Map.ChangeOverlay(1, True, command = self.overlays[1]['cmd'])
  1173. self.overlays[1]['coords'] = (0,0)
  1174. def Zoom(self, begin, end, zoomtype):
  1175. """!Calculates new region while (un)zoom/pan-ing
  1176. """
  1177. x1, y1 = begin
  1178. x2, y2 = end
  1179. newreg = {}
  1180. # threshold - too small squares do not make sense
  1181. # can only zoom to windows of > 5x5 screen pixels
  1182. if abs(x2-x1) > 5 and abs(y2-y1) > 5 and zoomtype != 0:
  1183. if x1 > x2:
  1184. x1, x2 = x2, x1
  1185. if y1 > y2:
  1186. y1, y2 = y2, y1
  1187. # zoom in
  1188. if zoomtype > 0:
  1189. newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
  1190. newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
  1191. # zoom out
  1192. elif zoomtype < 0:
  1193. newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
  1194. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + 2 * \
  1195. (self.Map.width - x2),
  1196. self.Map.height + 2 * \
  1197. (self.Map.height - y2)))
  1198. # pan
  1199. elif zoomtype == 0:
  1200. dx = x1 - x2
  1201. dy = y1 - y2
  1202. if dx == 0 and dy == 0:
  1203. dx = x1 - self.Map.width / 2
  1204. dy = y1 - self.Map.height / 2
  1205. newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
  1206. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
  1207. self.Map.height + dy))
  1208. # if new region has been calculated, set the values
  1209. if newreg != {}:
  1210. # LL locations
  1211. if self.Map.projinfo['proj'] == 'll':
  1212. self.Map.region['n'] = min(self.Map.region['n'], 90.0)
  1213. self.Map.region['s'] = max(self.Map.region['s'], -90.0)
  1214. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  1215. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  1216. # calculate new center point and display resolution
  1217. self.Map.region['center_easting'] = ce
  1218. self.Map.region['center_northing'] = cn
  1219. self.Map.region['ewres'] = (newreg['e'] - newreg['w']) / self.Map.width
  1220. self.Map.region['nsres'] = (newreg['n'] - newreg['s']) / self.Map.height
  1221. if not self.frame.HasProperty('alignExtent') or \
  1222. self.frame.GetProperty('alignExtent'):
  1223. self.Map.AlignExtentFromDisplay()
  1224. else:
  1225. for k in ('n', 's', 'e', 'w'):
  1226. self.Map.region[k] = newreg[k]
  1227. if hasattr(self, "digit") and \
  1228. hasattr(self, "moveInfo"):
  1229. self._zoom(None)
  1230. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1231. self.Map.region['e'], self.Map.region['w'])
  1232. if self.redrawAll is False:
  1233. self.redrawAll = True
  1234. def ZoomBack(self):
  1235. """!Zoom to previous extents in zoomhistory list
  1236. """
  1237. zoom = list()
  1238. if len(self.zoomhistory) > 1:
  1239. self.zoomhistory.pop()
  1240. zoom = self.zoomhistory[-1]
  1241. # disable tool if stack is empty
  1242. if len(self.zoomhistory) < 2: # disable tool
  1243. toolbar = self.frame.GetMapToolbar()
  1244. toolbar.Enable('zoomBack', enable = False)
  1245. # zoom to selected region
  1246. self.Map.GetRegion(n = zoom[0], s = zoom[1],
  1247. e = zoom[2], w = zoom[3],
  1248. update = True)
  1249. # update map
  1250. self.UpdateMap()
  1251. # update statusbar
  1252. self.frame.StatusbarUpdate()
  1253. def ZoomHistory(self, n, s, e, w):
  1254. """!Manages a list of last 10 zoom extents
  1255. @param n,s,e,w north, south, east, west
  1256. @return removed history item if exists (or None)
  1257. """
  1258. removed = None
  1259. self.zoomhistory.append((n,s,e,w))
  1260. if len(self.zoomhistory) > 10:
  1261. removed = self.zoomhistory.pop(0)
  1262. if removed:
  1263. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
  1264. (self.zoomhistory, removed))
  1265. else:
  1266. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
  1267. (self.zoomhistory))
  1268. # update toolbar
  1269. if len(self.zoomhistory) > 1:
  1270. enable = True
  1271. else:
  1272. enable = False
  1273. toolbar = self.frame.GetMapToolbar()
  1274. toolbar.Enable('zoomBack', enable)
  1275. return removed
  1276. def ResetZoomHistory(self):
  1277. """!Reset zoom history"""
  1278. self.zoomhistory = list()
  1279. def ZoomToMap(self, layers = None, ignoreNulls = False, render = True):
  1280. """!Set display extents to match selected raster
  1281. or vector map(s).
  1282. @param layers list of layers to be zoom to
  1283. @param ignoreNulls True to ignore null-values (valid only for rasters)
  1284. @param render True to re-render display
  1285. """
  1286. if not layers:
  1287. layers = self.tree.GetSelectedLayer(multi = True, checkedOnly = False)
  1288. layers = [self.tree.GetLayerInfo(layer, key = 'maplayer') for layer in layers]
  1289. if not layers:
  1290. return
  1291. rast = []
  1292. vect = []
  1293. updated = False
  1294. for l in layers:
  1295. # only raster/vector layers are currently supported
  1296. if l.type == 'raster':
  1297. rast.append(l.GetName())
  1298. elif l.type == 'vector':
  1299. if hasattr(self, "digit") and \
  1300. self.toolbar.GetLayer() == l:
  1301. w, s, b, e, n, t = self.digit.GetDisplay().GetMapBoundingBox()
  1302. self.Map.GetRegion(n = n, s = s, w = w, e = e,
  1303. update = True)
  1304. updated = True
  1305. else:
  1306. vect.append(l.name)
  1307. elif l.type == 'rgb':
  1308. for rname in l.GetName().splitlines():
  1309. rast.append(rname)
  1310. if not updated:
  1311. self.Map.GetRegion(rast = rast,
  1312. vect = vect,
  1313. zoom = ignoreNulls,
  1314. update = True)
  1315. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1316. self.Map.region['e'], self.Map.region['w'])
  1317. if render:
  1318. self.UpdateMap()
  1319. self.frame.StatusbarUpdate()
  1320. def ZoomToWind(self):
  1321. """!Set display geometry to match computational region
  1322. settings (set with g.region)
  1323. """
  1324. self.Map.region = self.Map.GetRegion()
  1325. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1326. self.Map.region['e'], self.Map.region['w'])
  1327. self.UpdateMap()
  1328. self.frame.StatusbarUpdate()
  1329. def ZoomToDefault(self):
  1330. """!Set display geometry to match default region settings
  1331. """
  1332. self.Map.region = self.Map.GetRegion(default = True)
  1333. self.Map.AdjustRegion() # aling region extent to the display
  1334. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1335. self.Map.region['e'], self.Map.region['w'])
  1336. self.UpdateMap()
  1337. self.frame.StatusbarUpdate()
  1338. def 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. """!Calls UpdateTools to manage connected toolbars"""
  1479. self.frame.UpdateTools(None)
  1480. MapWindow.RegisterMouseEventHandler(self, event, handler, cursor)
  1481. def UnregisterMouseEventHandler(self, event, handler):
  1482. """!Sets pointer and toggles it after unregistration"""
  1483. MapWindow.UnregisterMouseEventHandler(self, event, handler)
  1484. # sets pointer mode
  1485. toolbar = self.frame.toolbars['map']
  1486. toolbar.action['id'] = vars(toolbar)["pointer"]
  1487. toolbar.OnTool(None)
  1488. self.frame.OnPointer(event = None)
  1489. def RegisterGraphicsToDraw(self, graphicsType, setStatusFunc = None, drawFunc = None):
  1490. """! Method allows to register 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) - allows to define 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