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