mapdisp.py 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040
  1. """!
  2. @package mapdisp.py
  3. @brief GIS map display canvas, with toolbar for various display
  4. management functions, and additional toolbars (vector digitizer, 3d
  5. view).
  6. Can be used either from Layer Manager or as p.mon backend.
  7. Classes:
  8. - MapFrame
  9. - MapApp
  10. Usage:
  11. python mapdisp.py monitor-identifier /path/to/command/file
  12. (C) 2006-2010 by the GRASS Development Team
  13. This program is free software under the GNU General Public
  14. License (>=v2). Read the file COPYING that comes with GRASS
  15. for details.
  16. @author Michael Barton
  17. @author Jachym Cepicky
  18. @author Martin Landa <landa.martin gmail.com>
  19. """
  20. import os
  21. import sys
  22. import glob
  23. import math
  24. import tempfile
  25. import copy
  26. import globalvar
  27. if not os.getenv("GRASS_WXBUNDLED"):
  28. globalvar.CheckForWx()
  29. import wx
  30. import wx.aui
  31. try:
  32. import subprocess
  33. except:
  34. CompatPath = os.path.join(globalvar.ETCWXDIR)
  35. sys.path.append(CompatPath)
  36. from compat import subprocess
  37. gmpath = os.path.join(globalvar.ETCWXDIR, "icons")
  38. sys.path.append(gmpath)
  39. grassPath = os.path.join(globalvar.ETCDIR, "python")
  40. sys.path.append(grassPath)
  41. import render
  42. import toolbars
  43. import menuform
  44. import gselect
  45. import disp_print
  46. import gcmd
  47. import dbm
  48. import dbm_dialogs
  49. import histogram
  50. import profile
  51. import globalvar
  52. import utils
  53. import gdialogs
  54. from grass.script import core as grass
  55. from debug import Debug
  56. from icon import Icons
  57. from preferences import globalSettings as UserSettings
  58. from mapdisp_command import Command
  59. from mapdisp_window import BufferedWindow
  60. import images
  61. imagepath = images.__path__[0]
  62. sys.path.append(imagepath)
  63. ###
  64. ### global variables
  65. ###
  66. # for standalone app
  67. cmdfilename = None
  68. class MapFrame(wx.Frame):
  69. """!Main frame for map display window. Drawing takes place in
  70. child double buffered drawing window.
  71. """
  72. def __init__(self, parent=None, id=wx.ID_ANY, title=_("GRASS GIS - Map display"),
  73. style=wx.DEFAULT_FRAME_STYLE, toolbars=["map"],
  74. tree=None, notebook=None, lmgr=None, page=None,
  75. Map=None, auimgr=None, **kwargs):
  76. """!Main map display window with toolbars, statusbar and
  77. DrawWindow
  78. @param toolbars array of activated toolbars, e.g. ['map', 'digit']
  79. @param tree reference to layer tree
  80. @param notebook control book ID in Layer Manager
  81. @param lmgr Layer Manager
  82. @param page notebook page with layer tree
  83. @param Map instance of render.Map
  84. @param auimgs AUI manager
  85. @param kwargs wx.Frame attribures
  86. """
  87. self._layerManager = lmgr # Layer Manager object
  88. self.Map = Map # instance of render.Map
  89. self.tree = tree # Layer Manager layer tree object
  90. self.page = page # Notebook page holding the layer tree
  91. self.layerbook = notebook # Layer Manager layer tree notebook
  92. self.parent = parent
  93. if not kwargs.has_key('name'):
  94. kwargs['name'] = 'MapWindow'
  95. wx.Frame.__init__(self, parent, id, title, style = style, **kwargs)
  96. # available cursors
  97. self.cursors = {
  98. # default: cross
  99. # "default" : wx.StockCursor(wx.CURSOR_DEFAULT),
  100. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  101. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  102. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  103. "pencil" : wx.StockCursor(wx.CURSOR_PENCIL),
  104. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  105. }
  106. #
  107. # set the size & system icon
  108. #
  109. self.SetClientSize(self.GetSize())
  110. self.iconsize = (16, 16)
  111. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  112. #
  113. # Fancy gui
  114. #
  115. # self._mgr = auimgr
  116. self._mgr = wx.aui.AuiManager(self)
  117. #
  118. # Add toolbars
  119. #
  120. self.toolbars = { 'map' : None,
  121. 'vdigit' : None,
  122. 'georect' : None,
  123. 'gcpdisp' : None,
  124. 'nviz' : None }
  125. for toolb in toolbars:
  126. self.AddToolbar(toolb)
  127. #
  128. # Add statusbar
  129. #
  130. self.statusbar = self.CreateStatusBar(number=4, style=0)
  131. self.statusbar.SetStatusWidths([-5, -2, -1, -1])
  132. self.statusbarWin = dict()
  133. self.statusbarWin['toggle'] = wx.Choice(self.statusbar, wx.ID_ANY,
  134. choices = globalvar.MAP_DISPLAY_STATUSBAR_MODE)
  135. self.statusbarWin['toggle'].SetSelection(UserSettings.Get(group='display',
  136. key='statusbarMode',
  137. subkey='selection'))
  138. self.statusbar.Bind(wx.EVT_CHOICE, self.OnToggleStatus, self.statusbarWin['toggle'])
  139. # auto-rendering checkbox
  140. self.statusbarWin['render'] = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  141. label=_("Render"))
  142. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleRender, self.statusbarWin['render'])
  143. self.statusbarWin['render'].SetValue(UserSettings.Get(group='display',
  144. key='autoRendering',
  145. subkey='enabled'))
  146. self.statusbarWin['render'].SetToolTip(wx.ToolTip (_("Enable/disable auto-rendering")))
  147. # show region
  148. self.statusbarWin['region'] = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  149. label=_("Show computational extent"))
  150. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleShowRegion, self.statusbarWin['region'])
  151. self.statusbarWin['region'].SetValue(False)
  152. self.statusbarWin['region'].Hide()
  153. self.statusbarWin['region'].SetToolTip(wx.ToolTip (_("Show/hide computational "
  154. "region extent (set with g.region). "
  155. "Display region drawn as a blue box inside the "
  156. "computational region, "
  157. "computational region inside a display region "
  158. "as a red box).")))
  159. # set resolution
  160. self.statusbarWin['resolution'] = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  161. label=_("Constrain display resolution to computational settings"))
  162. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleResolution, self.statusbarWin['resolution'])
  163. self.statusbarWin['resolution'].SetValue(UserSettings.Get(group='display', key='compResolution', subkey='enabled'))
  164. self.statusbarWin['resolution'].Hide()
  165. self.statusbarWin['resolution'].SetToolTip(wx.ToolTip (_("Constrain display resolution "
  166. "to computational region settings. "
  167. "Default value for new map displays can "
  168. "be set up in 'User GUI settings' dialog.")))
  169. # map scale
  170. self.statusbarWin['mapscale'] = wx.ComboBox(parent = self.statusbar, id = wx.ID_ANY,
  171. style = wx.TE_PROCESS_ENTER,
  172. size=(150, -1))
  173. self.statusbarWin['mapscale'].SetItems(['1:1000',
  174. '1:5000',
  175. '1:10000',
  176. '1:25000',
  177. '1:50000',
  178. '1:100000',
  179. '1:1000000'])
  180. self.statusbarWin['mapscale'].Hide()
  181. self.statusbar.Bind(wx.EVT_TEXT_ENTER, self.OnChangeMapScale, self.statusbarWin['mapscale'])
  182. self.statusbar.Bind(wx.EVT_COMBOBOX, self.OnChangeMapScale, self.statusbarWin['mapscale'])
  183. # go to
  184. self.statusbarWin['goto'] = wx.TextCtrl(parent=self.statusbar, id=wx.ID_ANY,
  185. value="", style=wx.TE_PROCESS_ENTER,
  186. size=(300, -1))
  187. self.statusbarWin['goto'].Hide()
  188. self.statusbar.Bind(wx.EVT_TEXT_ENTER, self.OnGoTo, self.statusbarWin['goto'])
  189. # projection
  190. self.statusbarWin['projection'] = wx.CheckBox(parent=self.statusbar, id=wx.ID_ANY,
  191. label=_("Use defined projection"))
  192. self.statusbarWin['projection'].SetValue(False)
  193. size = self.statusbarWin['projection'].GetSize()
  194. self.statusbarWin['projection'].SetMinSize((size[0] + 150, size[1]))
  195. self.statusbarWin['projection'].SetToolTip(wx.ToolTip (_("Reproject coordinates displayed "
  196. "in the statusbar. Projection can be "
  197. "defined in GUI preferences dialog "
  198. "(tab 'Display')")))
  199. self.statusbarWin['projection'].Hide()
  200. # mask
  201. self.statusbarWin['mask'] = wx.StaticText(parent = self.statusbar, id = wx.ID_ANY,
  202. label = '')
  203. self.statusbarWin['mask'].SetForegroundColour(wx.Colour(255, 0, 0))
  204. # on-render gauge
  205. self.statusbarWin['progress'] = wx.Gauge(parent=self.statusbar, id=wx.ID_ANY,
  206. range=0, style=wx.GA_HORIZONTAL)
  207. self.statusbarWin['progress'].Hide()
  208. self.StatusbarReposition() # reposition statusbar
  209. #
  210. # Init map display (buffered DC & set default cursor)
  211. #
  212. self.MapWindow2D = BufferedWindow(self, id=wx.ID_ANY,
  213. Map=self.Map, tree=self.tree, lmgr=self._layerManager)
  214. # default is 2D display mode
  215. self.MapWindow = self.MapWindow2D
  216. self.MapWindow.SetCursor(self.cursors["default"])
  217. # used by Nviz (3D display mode)
  218. self.MapWindow3D = None
  219. #
  220. # initialize region values
  221. #
  222. self.__InitDisplay()
  223. #
  224. # Bind various events
  225. #
  226. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  227. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  228. self.Bind(render.EVT_UPDATE_PRGBAR, self.OnUpdateProgress)
  229. #
  230. # Update fancy gui style
  231. #
  232. self._mgr.AddPane(self.MapWindow, wx.aui.AuiPaneInfo().CentrePane().
  233. Dockable(False).BestSize((-1,-1)).
  234. CloseButton(False).DestroyOnClose(True).
  235. Layer(0))
  236. self._mgr.Update()
  237. #
  238. # Init print module and classes
  239. #
  240. self.printopt = disp_print.PrintOptions(self, self.MapWindow)
  241. #
  242. # Initialization of digitization tool
  243. #
  244. self.digit = None
  245. #
  246. # Init zoom history
  247. #
  248. self.MapWindow.ZoomHistory(self.Map.region['n'],
  249. self.Map.region['s'],
  250. self.Map.region['e'],
  251. self.Map.region['w'])
  252. #
  253. # Re-use dialogs
  254. #
  255. self.dialogs = {}
  256. self.dialogs['attributes'] = None
  257. self.dialogs['category'] = None
  258. self.dialogs['barscale'] = None
  259. self.dialogs['legend'] = None
  260. self.decorationDialog = None # decoration/overlays
  261. def AddToolbar(self, name):
  262. """!Add defined toolbar to the window
  263. Currently known toolbars are:
  264. - 'map' - basic map toolbar
  265. - 'vdigit' - vector digitizer
  266. - 'gcpdisp' - GCP Manager Display
  267. - 'georect' - georectifier
  268. - 'nviz' - 3D view mode
  269. """
  270. # default toolbar
  271. if name == "map":
  272. self.toolbars['map'] = toolbars.MapToolbar(self, self.Map)
  273. self._mgr.AddPane(self.toolbars['map'],
  274. wx.aui.AuiPaneInfo().
  275. Name("maptoolbar").Caption(_("Map Toolbar")).
  276. ToolbarPane().Top().
  277. LeftDockable(False).RightDockable(False).
  278. BottomDockable(False).TopDockable(True).
  279. CloseButton(False).Layer(2).
  280. BestSize((self.toolbars['map'].GetSize())))
  281. # vector digitizer
  282. elif name == "vdigit":
  283. from vdigit import haveVDigit
  284. if not haveVDigit:
  285. from vdigit import errorMsg
  286. msg = _("Unable to start wxGUI vector digitizer.\nDo you want to start "
  287. "TCL/TK digitizer (v.digit) instead?\n\n"
  288. "Details: %s" % errorMsg)
  289. self.mapdisplay.toolbars['map'].combo.SetValue (_("2D view"))
  290. dlg = wx.MessageDialog(parent = self.mapdisplay,
  291. message = msg,
  292. caption=_("Vector digitizer failed"),
  293. style = wx.YES_NO | wx.CENTRE)
  294. if dlg.ShowModal() == wx.ID_YES:
  295. self.lmgr.goutput.RunCmd(['v.digit', 'map=%s' % maplayer.GetName()],
  296. switchPage=False)
  297. dlg.Destroy()
  298. self.toolbars['map'].combo.SetValue (_("2D view"))
  299. return
  300. if self._layerManager:
  301. log = self._layerManager.goutput
  302. else:
  303. log = None
  304. self.toolbars['vdigit'] = toolbars.VDigitToolbar(parent=self, mapcontent=self.Map,
  305. layerTree=self.tree,
  306. log=log)
  307. self._mgr.AddPane(self.toolbars['vdigit'],
  308. wx.aui.AuiPaneInfo().
  309. Name("vdigittoolbar").Caption(_("Vector digitizer toolbar")).
  310. ToolbarPane().Top().Row(1).
  311. LeftDockable(False).RightDockable(False).
  312. BottomDockable(False).TopDockable(True).
  313. CloseButton(False).Layer(2).
  314. BestSize((self.toolbars['vdigit'].GetSize())))
  315. # change mouse to draw digitized line
  316. self.MapWindow.mouse['box'] = "point"
  317. self.MapWindow.zoomtype = 0
  318. self.MapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SOLID)
  319. self.MapWindow.polypen = wx.Pen(colour='green', width=2, style=wx.SOLID)
  320. # georectifier
  321. elif name == "georect":
  322. self.toolbars['georect'] = toolbars.GRToolbar(self, self.Map)
  323. self._mgr.AddPane(self.toolbars['georect'],
  324. wx.aui.AuiPaneInfo().
  325. Name("georecttoolbar").Caption(_("Georectification toolbar")).
  326. ToolbarPane().Top().
  327. LeftDockable(False).RightDockable(False).
  328. BottomDockable(False).TopDockable(True).
  329. CloseButton(False).Layer(2))
  330. # nviz
  331. elif name == "nviz":
  332. import nviz
  333. # check for GLCanvas and OpenGL
  334. if not nviz.haveNviz:
  335. self.toolbars['map'].combo.SetValue (_("2D view"))
  336. wx.MessageBox(parent = self,
  337. message = _("Unable to switch to 3D display mode.\nThe Nviz python extension "
  338. "was not found or loaded properly.\n"
  339. "Switching back to 2D display mode.\n\nDetails: %s" % nviz.errorMsg),
  340. caption = _("Error"),
  341. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  342. return
  343. # add Nviz toolbar and disable 2D display mode tools
  344. self.toolbars['nviz'] = toolbars.NvizToolbar(self, self.Map)
  345. self.toolbars['map'].Enable2D(False)
  346. # update layer tree (-> enable 3d-rasters)
  347. if self.tree:
  348. self.tree.EnableItemType(type='3d-raster', enable=True)
  349. # update status bar
  350. self.statusbarWin['toggle'].Enable(False)
  351. # erase map window
  352. self.MapWindow.EraseMap()
  353. self.statusbar.SetStatusText(_("Please wait, loading data..."), 0)
  354. # create GL window & NVIZ toolbar
  355. if not self.MapWindow3D:
  356. self.MapWindow3D = nviz.GLWindow(self, id=wx.ID_ANY,
  357. Map=self.Map, tree=self.tree, lmgr=self._layerManager)
  358. self.MapWindow = self.MapWindow3D
  359. self.MapWindow.SetCursor(self.cursors["default"])
  360. # add Nviz notebookpage
  361. self._layerManager.AddNviz()
  362. self.MapWindow3D.OnPaint(None) # -> LoadData
  363. self.MapWindow3D.Show()
  364. self.MapWindow3D.UpdateView(None)
  365. else:
  366. self.MapWindow = self.MapWindow3D
  367. # add Nviz notebookpage
  368. self._layerManager.AddNviz()
  369. # switch from MapWindow to MapWindowGL
  370. # add nviz toolbar
  371. self._mgr.DetachPane(self.MapWindow2D)
  372. self.MapWindow2D.Hide()
  373. self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
  374. Dockable(False).BestSize((-1,-1)).
  375. CloseButton(False).DestroyOnClose(True).
  376. Layer(0))
  377. self._mgr.AddPane(self.toolbars['nviz'],
  378. wx.aui.AuiPaneInfo().
  379. Name("nviztoolbar").Caption(_("Nviz toolbar")).
  380. ToolbarPane().Top().Row(1).
  381. LeftDockable(False).RightDockable(False).
  382. BottomDockable(False).TopDockable(True).
  383. CloseButton(False).Layer(2))
  384. self.SetStatusText("", 0)
  385. self._mgr.Update()
  386. def RemoveToolbar (self, name):
  387. """!Removes toolbar from the window
  388. @todo Only hide, activate by calling AddToolbar()
  389. """
  390. # cannot hide main toolbar
  391. if name == "map":
  392. return
  393. elif name == "vdigit":
  394. # TODO: not destroy only hide
  395. self._mgr.DetachPane(self.toolbars['vdigit'])
  396. self.toolbars['vdigit'].Destroy()
  397. else:
  398. self._mgr.DetachPane (self.toolbars[name])
  399. self.toolbars[name].Destroy()
  400. self.toolbars[name] = None
  401. if name == 'nviz':
  402. # unload data
  403. # self.MapWindow3D.Reset()
  404. # switch from MapWindowGL to MapWindow
  405. self._mgr.DetachPane(self.MapWindow3D)
  406. self.MapWindow3D.Hide()
  407. self.MapWindow2D.Show()
  408. self._mgr.AddPane(self.MapWindow2D, wx.aui.AuiPaneInfo().CentrePane().
  409. Dockable(False).BestSize((-1,-1)).
  410. CloseButton(False).DestroyOnClose(True).
  411. Layer(0))
  412. self.MapWindow = self.MapWindow2D
  413. # remove nviz notebook page
  414. self._layerManager.RemoveNviz()
  415. # update layer tree (-> disable 3d-rasters)
  416. if self.tree:
  417. self.tree.EnableItemType(type='3d-raster', enable=False)
  418. self.MapWindow.UpdateMap()
  419. self.toolbars['map'].combo.SetValue (_("2D view"))
  420. self.toolbars['map'].Enable2D(True)
  421. self.statusbarWin['toggle'].Enable(True)
  422. self._mgr.Update()
  423. def __InitDisplay(self):
  424. """
  425. Initialize map display, set dimensions and map region
  426. """
  427. self.width, self.height = self.GetClientSize()
  428. Debug.msg(2, "MapFrame.__InitDisplay():")
  429. self.Map.ChangeMapSize(self.GetClientSize())
  430. self.Map.region = self.Map.GetRegion() # g.region -upgc
  431. # self.Map.SetRegion() # adjust region to match display window
  432. def OnUpdateProgress(self, event):
  433. """
  434. Update progress bar info
  435. """
  436. self.statusbarWin['progress'].SetValue(event.value)
  437. event.Skip()
  438. def OnFocus(self, event):
  439. """
  440. Change choicebook page to match display.
  441. Or set display for georectifying
  442. """
  443. if self._layerManager and \
  444. self._layerManager.georectifying:
  445. # in georectifying session; display used to get geographic
  446. # coordinates for GCPs
  447. self.OnPointer(event)
  448. else:
  449. # change bookcontrol page to page associated with display
  450. if self.page:
  451. pgnum = self.layerbook.GetPageIndex(self.page)
  452. if pgnum > -1:
  453. self.layerbook.SetSelection(pgnum)
  454. event.Skip()
  455. def OnDraw(self, event):
  456. """!Re-display current map composition
  457. """
  458. self.MapWindow.UpdateMap(render = False)
  459. def OnRender(self, event):
  460. """!Re-render map composition (each map layer)
  461. """
  462. # delete tmp map layers (queries)
  463. qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)
  464. for layer in qlayer:
  465. self.Map.DeleteLayer(layer)
  466. # delete tmp lines
  467. if self.MapWindow.mouse["use"] in ("measure",
  468. "profile"):
  469. self.MapWindow.polycoords = []
  470. self.MapWindow.ClearLines()
  471. # deselect features in vdigit
  472. if self.toolbars['vdigit'] and self.digit:
  473. self.digit.driver.SetSelected([])
  474. self.MapWindow.UpdateMap(render=True, renderVector=True)
  475. else:
  476. self.MapWindow.UpdateMap(render=True)
  477. # update statusbar
  478. self.StatusbarUpdate()
  479. def OnPointer(self, event):
  480. """!Pointer button clicked
  481. """
  482. if self.toolbars['map']:
  483. if event:
  484. self.toolbars['map'].OnTool(event)
  485. self.toolbars['map'].action['desc'] = ''
  486. self.MapWindow.mouse['use'] = "pointer"
  487. self.MapWindow.mouse['box'] = "point"
  488. # change the cursor
  489. if self.toolbars['vdigit']:
  490. # digitization tool activated
  491. self.MapWindow.SetCursor(self.cursors["cross"])
  492. # reset mouse['box'] if needed
  493. if self.toolbars['vdigit'].GetAction() in ['addLine']:
  494. if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
  495. self.MapWindow.mouse['box'] = 'point'
  496. else: # line, boundary
  497. self.MapWindow.mouse['box'] = 'line'
  498. elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
  499. 'editLine', 'displayCats', 'displayAttrs',
  500. 'copyCats']:
  501. self.MapWindow.mouse['box'] = 'point'
  502. else: # moveLine, deleteLine
  503. self.MapWindow.mouse['box'] = 'box'
  504. elif self._layerManager and self._layerManager.georectifying:
  505. self.MapWindow.SetCursor(self.cursors["cross"])
  506. else:
  507. self.MapWindow.SetCursor(self.cursors["default"])
  508. def OnZoomIn(self, event):
  509. """
  510. Zoom in the map.
  511. Set mouse cursor, zoombox attributes, and zoom direction
  512. """
  513. if self.toolbars['map']:
  514. self.toolbars['map'].OnTool(event)
  515. self.toolbars['map'].action['desc'] = ''
  516. self.MapWindow.mouse['use'] = "zoom"
  517. self.MapWindow.mouse['box'] = "box"
  518. self.MapWindow.zoomtype = 1
  519. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  520. # change the cursor
  521. self.MapWindow.SetCursor(self.cursors["cross"])
  522. def OnZoomOut(self, event):
  523. """
  524. Zoom out the map.
  525. Set mouse cursor, zoombox attributes, and zoom direction
  526. """
  527. if self.toolbars['map']:
  528. self.toolbars['map'].OnTool(event)
  529. self.toolbars['map'].action['desc'] = ''
  530. self.MapWindow.mouse['use'] = "zoom"
  531. self.MapWindow.mouse['box'] = "box"
  532. self.MapWindow.zoomtype = -1
  533. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  534. # change the cursor
  535. self.MapWindow.SetCursor(self.cursors["cross"])
  536. def OnZoomBack(self, event):
  537. """
  538. Zoom last (previously stored position)
  539. """
  540. self.MapWindow.ZoomBack()
  541. def OnPan(self, event):
  542. """
  543. Panning, set mouse to drag
  544. """
  545. if self.toolbars['map']:
  546. self.toolbars['map'].OnTool(event)
  547. self.toolbars['map'].action['desc'] = ''
  548. self.MapWindow.mouse['use'] = "pan"
  549. self.MapWindow.mouse['box'] = "pan"
  550. self.MapWindow.zoomtype = 0
  551. # change the cursor
  552. self.MapWindow.SetCursor(self.cursors["hand"])
  553. def OnErase(self, event):
  554. """
  555. Erase the canvas
  556. """
  557. self.MapWindow.EraseMap()
  558. def OnZoomRegion(self, event):
  559. """
  560. Zoom to region
  561. """
  562. self.Map.getRegion()
  563. self.Map.getResolution()
  564. self.UpdateMap()
  565. # event.Skip()
  566. def OnAlignRegion(self, event):
  567. """
  568. Align region
  569. """
  570. if not self.Map.alignRegion:
  571. self.Map.alignRegion = True
  572. else:
  573. self.Map.alignRegion = False
  574. # event.Skip()
  575. def OnToggleRender(self, event):
  576. """
  577. Enable/disable auto-rendering
  578. """
  579. if self.statusbarWin['render'].GetValue():
  580. self.OnRender(None)
  581. def OnToggleShowRegion(self, event):
  582. """
  583. Show/Hide extent in map canvas
  584. """
  585. if self.statusbarWin['region'].GetValue():
  586. # show extent
  587. self.MapWindow.regionCoords = []
  588. else:
  589. del self.MapWindow.regionCoords
  590. # redraw map if auto-rendering is enabled
  591. if self.statusbarWin['render'].GetValue():
  592. self.OnRender(None)
  593. def OnToggleResolution(self, event):
  594. """
  595. Use resolution of computation region settings
  596. for redering image instead of display resolution
  597. """
  598. # redraw map if auto-rendering is enabled
  599. if self.statusbarWin['render'].GetValue():
  600. self.OnRender(None)
  601. def OnToggleStatus(self, event):
  602. """
  603. Toggle status text
  604. """
  605. self.StatusbarUpdate()
  606. def OnChangeMapScale(self, event):
  607. """
  608. Map scale changed by user
  609. """
  610. scale = event.GetString()
  611. try:
  612. if scale[:2] != '1:':
  613. raise ValueError
  614. value = int(scale[2:])
  615. except ValueError:
  616. self.statusbarWin['mapscale'].SetValue('1:%ld' % int(self.mapScaleValue))
  617. return
  618. dEW = value * (self.Map.region['cols'] / self.ppm[0])
  619. dNS = value * (self.Map.region['rows'] / self.ppm[1])
  620. self.Map.region['n'] = self.Map.region['center_northing'] + dNS / 2.
  621. self.Map.region['s'] = self.Map.region['center_northing'] - dNS / 2.
  622. self.Map.region['w'] = self.Map.region['center_easting'] - dEW / 2.
  623. self.Map.region['e'] = self.Map.region['center_easting'] + dEW / 2.
  624. # add to zoom history
  625. self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  626. self.Map.region['e'], self.Map.region['w'])
  627. # redraw a map
  628. self.MapWindow.UpdateMap()
  629. self.statusbarWin['mapscale'].SetFocus()
  630. def OnGoTo(self, event):
  631. """
  632. Go to position
  633. """
  634. try:
  635. if self.statusbarWin['projection'].IsChecked():
  636. if not UserSettings.Get(group='projection', key='statusbar', subkey='proj4'):
  637. self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
  638. else:
  639. # reproject values
  640. projIn = UserSettings.Get(group='projection',
  641. key='statusbar',
  642. subkey='proj4')
  643. projOut = gcmd.RunCommand('g.proj',
  644. flags = 'jf',
  645. read = True)
  646. proj = projIn.split(' ')[0].split('=')[1]
  647. if proj in ('ll', 'latlong', 'longlat'):
  648. e, n = self.statusbarWin['goto'].GetValue().split(';')
  649. e, n = utils.DMS2Deg(e, n)
  650. proj, coord1 = utils.ReprojectCoordinates(coord = (e, n),
  651. projIn = projIn,
  652. projOut = projOut, flags = 'd')
  653. e, n = coord1
  654. else:
  655. e, n = map(float, self.statusbarWin['goto'].GetValue().split(';'))
  656. proj, coord1 = utils.ReprojectCoordinates(coord = (e, n),
  657. projIn = projIn,
  658. projOut = projOut, flags = 'd')
  659. e, n = coord1
  660. else:
  661. if self.Map.projinfo['proj'] == 'll':
  662. e, n = self.statusbarWin['goto'].GetValue().split(';')
  663. else:
  664. e, n = map(float, self.statusbarWin['goto'].GetValue().split(';'))
  665. region = self.Map.GetCurrentRegion()
  666. if self.statusbarWin['projection'].IsChecked():
  667. if not UserSettings.Get(group='projection', key='statusbar', subkey='proj4'):
  668. self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
  669. else:
  670. region['center_easting'], region['center_northing'] = e, n
  671. else:
  672. if self.Map.projinfo['proj'] == 'll':
  673. region['center_easting'], region['center_northing'] = utils.DMS2Deg(e, n)
  674. else:
  675. region['center_easting'], region['center_northing'] = e, n
  676. except ValueError:
  677. region = self.Map.GetCurrentRegion()
  678. precision = int(UserSettings.Get(group = 'projection', key = 'format',
  679. subkey = 'precision'))
  680. format = UserSettings.Get(group = 'projection', key = 'format',
  681. subkey = 'll')
  682. if self.Map.projinfo['proj'] == 'll' and format == 'DMS':
  683. self.statusbarWin['goto'].SetValue("%s" % utils.Deg2DMS(region['center_easting'],
  684. region['center_northing'],
  685. precision = precision))
  686. else:
  687. self.statusbarWin['goto'].SetValue("%.*f; %.*f" % \
  688. (precision, region['center_easting'],
  689. precision, region['center_northing']))
  690. return
  691. dn = (region['nsres'] * region['rows']) / 2.
  692. region['n'] = region['center_northing'] + dn
  693. region['s'] = region['center_northing'] - dn
  694. de = (region['ewres'] * region['cols']) / 2.
  695. region['e'] = region['center_easting'] + de
  696. region['w'] = region['center_easting'] - de
  697. self.Map.AdjustRegion()
  698. # add to zoom history
  699. self.MapWindow.ZoomHistory(region['n'], region['s'],
  700. region['e'], region['w'])
  701. # redraw a map
  702. self.MapWindow.UpdateMap()
  703. self.statusbarWin['goto'].SetFocus()
  704. def StatusbarUpdate(self):
  705. """!Update statusbar content"""
  706. self.statusbarWin['region'].Hide()
  707. self.statusbarWin['resolution'].Hide()
  708. self.statusbarWin['mapscale'].Hide()
  709. self.statusbarWin['goto'].Hide()
  710. self.statusbarWin['projection'].Hide()
  711. self.mapScaleValue = self.ppm = None
  712. if self.statusbarWin['toggle'].GetSelection() == 0: # Coordinates
  713. self.statusbar.SetStatusText("", 0)
  714. # enable long help
  715. self.StatusbarEnableLongHelp()
  716. elif self.statusbarWin['toggle'].GetSelection() in (1, 2): # Extent
  717. sel = self.statusbarWin['toggle'].GetSelection()
  718. if sel == 1:
  719. region = self.Map.region
  720. else:
  721. region = self.Map.GetRegion() # computation region
  722. precision = int(UserSettings.Get(group = 'projection', key = 'format',
  723. subkey = 'precision'))
  724. format = UserSettings.Get(group = 'projection', key = 'format',
  725. subkey = 'll')
  726. if self.statusbarWin['projection'].IsChecked():
  727. if not UserSettings.Get(group='projection', key='statusbar', subkey='proj4'):
  728. self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
  729. else:
  730. projOut = UserSettings.Get(group='projection',
  731. key='statusbar',
  732. subkey='proj4')
  733. proj, coord1 = utils.ReprojectCoordinates(coord = (region["w"], region["s"]),
  734. projOut = projOut, flags = 'd')
  735. proj, coord2 = utils.ReprojectCoordinates(coord = (region["e"], region["n"]),
  736. projOut = projOut, flags = 'd')
  737. if sel == 2:
  738. proj, coord3 = utils.ReprojectCoordinates(coord = (0.0, 0.0),
  739. projOut = projOut, flags = 'd')
  740. proj, coord4 = utils.ReprojectCoordinates(coord = (region["ewres"], region["nsres"]),
  741. projOut = projOut, flags = 'd')
  742. if coord1 and coord2:
  743. if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
  744. w, s = utils.Deg2DMS(coord1[0], coord1[1], string = False,
  745. precision = precision)
  746. e, n = utils.Deg2DMS(coord2[0], coord2[1], string = False,
  747. precision = precision)
  748. if sel == 1:
  749. self.statusbar.SetStatusText("%s - %s, %s - %s" %
  750. (w, e, s, n), 0)
  751. else:
  752. ewres, nsres = utils.Deg2DMS(abs(coord3[0]) - abs(coord4[0]),
  753. abs(coord3[1]) - abs(coord4[1]),
  754. string = False, hemisphere = False,
  755. precision = precision)
  756. self.statusbar.SetStatusText("%s - %s, %s - %s (%s, %s)" %
  757. (w, e, s, n, ewres, nsres), 0)
  758. else:
  759. w, s = coord1
  760. e, n = coord2
  761. if sel == 1:
  762. self.statusbar.SetStatusText("%.*f - %.*f, %.*f - %.*f" %
  763. (precision, w, precision, e,
  764. precision, s, precision, n), 0)
  765. else:
  766. ewres, nsres = coord3
  767. self.statusbar.SetStatusText("%.*f - %.*f, %.*f - %.*f (%.*f, %.*f)" %
  768. (precision, w, precision, e,
  769. precision, s, precision, n,
  770. precision, ewres, precision, nsres), 0)
  771. else:
  772. self.statusbar.SetStatusText(_("Error in projection (check the settings)"), 0)
  773. else:
  774. if self.Map.projinfo['proj'] == 'll' and format == 'DMS':
  775. w, s = utils.Deg2DMS(region["w"], region["s"],
  776. string = False, precision = precision)
  777. e, n = utils.Deg2DMS(region["e"], region["n"],
  778. string = False, precision = precision)
  779. if sel == 1:
  780. self.statusbar.SetStatusText("%s - %s, %s - %s" %
  781. (w, e, s, n), 0)
  782. else:
  783. ewres, nsres = utils.Deg2DMS(region['ewres'], region['nsres'],
  784. string = False, precision = precision)
  785. self.statusbar.SetStatusText("%s - %s, %s - %s (%s, %s)" %
  786. (w, e, s, n, ewres, nsres), 0)
  787. else:
  788. w, s = region["w"], region["s"]
  789. e, n = region["e"], region["n"]
  790. if sel == 1:
  791. self.statusbar.SetStatusText("%.*f - %.*f, %.*f - %.*f" %
  792. (precision, w, precision, e,
  793. precision, s, precision, n), 0)
  794. else:
  795. ewres, nsres = region['ewres'], region['nsres']
  796. self.statusbar.SetStatusText("%.*f - %.*f, %.*f - %.*f (%.*f, %.*f)" %
  797. (precision, w, precision, e,
  798. precision, s, precision, n,
  799. precision, ewres, precision, nsres), 0)
  800. # enable long help
  801. self.StatusbarEnableLongHelp()
  802. elif self.statusbarWin['toggle'].GetSelection() == 3: # Show comp. extent
  803. self.statusbar.SetStatusText("", 0)
  804. self.statusbarWin['region'].Show()
  805. # disable long help
  806. self.StatusbarEnableLongHelp(False)
  807. elif self.statusbarWin['toggle'].GetSelection() == 4: # Display mode
  808. self.statusbar.SetStatusText("", 0)
  809. self.statusbarWin['resolution'].Show()
  810. # disable long help
  811. self.StatusbarEnableLongHelp(False)
  812. elif self.statusbarWin['toggle'].GetSelection() == 5: # Display geometry
  813. self.statusbar.SetStatusText("rows=%d; cols=%d; nsres=%.2f; ewres=%.2f" %
  814. (self.Map.region["rows"], self.Map.region["cols"],
  815. self.Map.region["nsres"], self.Map.region["ewres"]), 0)
  816. # enable long help
  817. self.StatusbarEnableLongHelp()
  818. elif self.statusbarWin['toggle'].GetSelection() == 6: # Map scale
  819. # TODO: need to be fixed...
  820. ### screen X region problem
  821. ### user should specify ppm
  822. dc = wx.ScreenDC()
  823. dpSizePx = wx.DisplaySize() # display size in pixels
  824. dpSizeMM = wx.DisplaySizeMM() # display size in mm (system)
  825. dpSizeIn = (dpSizeMM[0] / 25.4, dpSizeMM[1] / 25.4) # inches
  826. sysPpi = dc.GetPPI()
  827. comPpi = (dpSizePx[0] / dpSizeIn[0],
  828. dpSizePx[1] / dpSizeIn[1])
  829. ppi = comPpi # pixel per inch
  830. self.ppm = ((ppi[0] / 2.54) * 100, # pixel per meter
  831. (ppi[1] / 2.54) * 100)
  832. Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): size: px=%d,%d mm=%f,%f "
  833. "in=%f,%f ppi: sys=%d,%d com=%d,%d; ppm=%f,%f" % \
  834. (dpSizePx[0], dpSizePx[1], dpSizeMM[0], dpSizeMM[1],
  835. dpSizeIn[0], dpSizeIn[1],
  836. sysPpi[0], sysPpi[1], comPpi[0], comPpi[1],
  837. self.ppm[0], self.ppm[1]))
  838. region = self.Map.region
  839. heightCm = region['rows'] / self.ppm[1] * 100
  840. widthCm = region['cols'] / self.ppm[0] * 100
  841. Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): width_cm=%f, height_cm=%f" %
  842. (widthCm, heightCm))
  843. xscale = (region['e'] - region['w']) / (region['cols'] / self.ppm[0])
  844. yscale = (region['n'] - region['s']) / (region['rows'] / self.ppm[1])
  845. scale = (xscale + yscale) / 2.
  846. Debug.msg(3, "MapFrame.StatusbarUpdate(mapscale): xscale=%f, yscale=%f -> scale=%f" % \
  847. (xscale, yscale, scale))
  848. self.statusbar.SetStatusText("")
  849. try:
  850. self.statusbarWin['mapscale'].SetValue("1:%ld" % (scale + 0.5))
  851. except TypeError:
  852. pass
  853. self.mapScaleValue = scale
  854. self.statusbarWin['mapscale'].Show()
  855. # disable long help
  856. self.StatusbarEnableLongHelp(False)
  857. elif self.statusbarWin['toggle'].GetSelection() == 7: # go to
  858. self.statusbar.SetStatusText("")
  859. region = self.Map.GetCurrentRegion()
  860. precision = int(UserSettings.Get(group = 'projection', key = 'format',
  861. subkey = 'precision'))
  862. format = UserSettings.Get(group = 'projection', key = 'format',
  863. subkey = 'll')
  864. if self.statusbarWin['projection'].IsChecked():
  865. if not UserSettings.Get(group='projection', key='statusbar', subkey='proj4'):
  866. self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
  867. else:
  868. proj, coord = utils.ReprojectCoordinates(coord = (region['center_easting'],
  869. region['center_northing']),
  870. projOut = UserSettings.Get(group='projection',
  871. key='statusbar',
  872. subkey='proj4'),
  873. flags = 'd')
  874. if coord:
  875. if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
  876. self.statusbarWin['goto'].SetValue("%s" % utils.Deg2DMS(coord[0],
  877. coord[1],
  878. precision = precision))
  879. else:
  880. self.statusbarWin['goto'].SetValue("%.*f; %.*f" % (precision, coord[0],
  881. precision, coord[1]))
  882. else:
  883. self.statusbar.SetStatusText(_("Error in projection (check the settings)"), 0)
  884. else:
  885. if self.Map.projinfo['proj'] == 'll' and format == 'DMS':
  886. self.statusbarWin['goto'].SetValue("%s" % utils.Deg2DMS(region['center_easting'],
  887. region['center_northing'],
  888. precision = precision))
  889. else:
  890. self.statusbarWin['goto'].SetValue("%.*f; %.*f" % (precision, region['center_easting'],
  891. precision, region['center_northing']))
  892. self.statusbarWin['goto'].Show()
  893. # disable long help
  894. self.StatusbarEnableLongHelp(False)
  895. elif self.statusbarWin['toggle'].GetSelection() == 8: # projection
  896. self.statusbar.SetStatusText("")
  897. epsg = UserSettings.Get(group='projection', key='statusbar', subkey='epsg')
  898. if epsg:
  899. label = '%s (EPSG: %s)' % (_("Use defined projection"), epsg)
  900. self.statusbarWin['projection'].SetLabel(label)
  901. else:
  902. self.statusbarWin['projection'].SetLabel(_("Use defined projection"))
  903. self.statusbarWin['projection'].Show()
  904. # disable long help
  905. self.StatusbarEnableLongHelp(False)
  906. else:
  907. self.statusbar.SetStatusText("", 1)
  908. def StatusbarEnableLongHelp(self, enable=True):
  909. """!Enable/disable toolbars long help"""
  910. for toolbar in self.toolbars.itervalues():
  911. if toolbar:
  912. toolbar.EnableLongHelp(enable)
  913. def StatusbarReposition(self):
  914. """!Reposition checkbox in statusbar"""
  915. # reposition checkbox
  916. widgets = [(0, self.statusbarWin['region']),
  917. (0, self.statusbarWin['resolution']),
  918. (0, self.statusbarWin['mapscale']),
  919. (0, self.statusbarWin['progress']),
  920. (0, self.statusbarWin['projection']),
  921. (1, self.statusbarWin['toggle']),
  922. (2, self.statusbarWin['mask']),
  923. (3, self.statusbarWin['render'])]
  924. for idx, win in widgets:
  925. rect = self.statusbar.GetFieldRect(idx)
  926. if idx == 0: # show region / mapscale / process bar
  927. # -> size
  928. wWin, hWin = win.GetBestSize()
  929. if win == self.statusbarWin['progress']:
  930. wWin = rect.width - 6
  931. # -> position
  932. # if win == self.statusbarWin['region']:
  933. # x, y = rect.x + rect.width - wWin, rect.y - 1
  934. # align left
  935. # else:
  936. x, y = rect.x + 3, rect.y - 1
  937. w, h = wWin, rect.height + 2
  938. else: # choice || auto-rendering
  939. x, y = rect.x, rect.y - 1
  940. w, h = rect.width, rect.height + 2
  941. if idx == 2: # mask
  942. x += 5
  943. y += 4
  944. elif idx == 3: # render
  945. x += 5
  946. win.SetPosition((x, y))
  947. win.SetSize((w, h))
  948. def SaveToFile(self, event):
  949. """!Save map to image
  950. """
  951. if self.toolbars['nviz']:
  952. filetype = "PPM file (*.ppm)|*.ppm|TIF file (*.tif)|*.tif"
  953. ltype = [{ 'ext' : 'ppm', 'type' : -1 },
  954. { 'ext' : 'tif', 'type' : wx.BITMAP_TYPE_TIF }]
  955. else:
  956. img = self.MapWindow.img
  957. if not img:
  958. gcmd.GMessage(parent = self,
  959. message = _("Nothing to render (empty map). Operation canceled."))
  960. return
  961. filetype, ltype = gdialogs.GetImageHandlers(img)
  962. # get size
  963. dlg = gdialogs.ImageSizeDialog(self)
  964. dlg.CentreOnParent()
  965. if dlg.ShowModal() != wx.ID_OK:
  966. dlg.Destroy()
  967. return
  968. width, height = dlg.GetValues()
  969. dlg.Destroy()
  970. # get filename
  971. dlg = wx.FileDialog(parent = self,
  972. message = _("Choose a file name to save the image "
  973. "(no need to add extension)"),
  974. wildcard = filetype,
  975. style=wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  976. if dlg.ShowModal() == wx.ID_OK:
  977. path = dlg.GetPath()
  978. if not path:
  979. dlg.Destroy()
  980. return
  981. base, ext = os.path.splitext(path)
  982. fileType = ltype[dlg.GetFilterIndex()]['type']
  983. extType = ltype[dlg.GetFilterIndex()]['ext']
  984. if ext != extType:
  985. path = base + '.' + extType
  986. self.MapWindow.SaveToFile(path, fileType,
  987. width, height)
  988. dlg.Destroy()
  989. def PrintMenu(self, event):
  990. """
  991. Print options and output menu for map display
  992. """
  993. point = wx.GetMousePosition()
  994. printmenu = wx.Menu()
  995. # Add items to the menu
  996. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  997. printmenu.AppendItem(setup)
  998. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  999. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  1000. printmenu.AppendItem(preview)
  1001. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  1002. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  1003. printmenu.AppendItem(doprint)
  1004. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  1005. # Popup the menu. If an item is selected then its handler
  1006. # will be called before PopupMenu returns.
  1007. self.PopupMenu(printmenu)
  1008. printmenu.Destroy()
  1009. def OnCloseWindow(self, event):
  1010. """!Window closed.
  1011. Also close associated layer tree page
  1012. """
  1013. pgnum = None
  1014. self.Map.Clean()
  1015. # close edited map and 3D tools properly
  1016. if self.toolbars['vdigit']:
  1017. maplayer = self.toolbars['vdigit'].GetLayer()
  1018. if maplayer:
  1019. self.toolbars['vdigit'].OnExit()
  1020. self.imgVectorMap = None
  1021. if self.toolbars['nviz']:
  1022. self.toolbars['nviz'].OnExit()
  1023. if not self._layerManager:
  1024. self.Destroy()
  1025. elif self.page:
  1026. pgnum = self.layerbook.GetPageIndex(self.page)
  1027. if pgnum > -1:
  1028. self.layerbook.DeletePage(pgnum)
  1029. def GetRender(self):
  1030. """!Returns current instance of render.Map()
  1031. """
  1032. return self.Map
  1033. def GetWindow(self):
  1034. """!Get map window"""
  1035. return self.MapWindow
  1036. def OnQueryDisplay(self, event):
  1037. """!Query currrent raster/vector map layers (display mode)
  1038. """
  1039. if self.toolbars['map'].GetAction() == 'displayAttrb': # select previous action
  1040. self.toolbars['map'].SelectDefault(event)
  1041. return
  1042. self.toolbars['map'].action['desc'] = 'displayAttrb'
  1043. # switch GIS Manager to output console to show query results
  1044. self._layerManager.notebook.SetSelection(1)
  1045. self.MapWindow.mouse['use'] = "query"
  1046. self.MapWindow.mouse['box'] = "point"
  1047. self.MapWindow.zoomtype = 0
  1048. # change the cursor
  1049. self.MapWindow.SetCursor(self.cursors["cross"])
  1050. def OnQueryModify(self, event):
  1051. """
  1052. Query vector map layer (edit mode)
  1053. """
  1054. if self.toolbars['map'].GetAction() == 'modifyAttrb': # select previous action
  1055. self.toolbars['map'].SelectDefault(event)
  1056. return
  1057. self.toolbars['map'].action['desc'] = 'modifyAttrb'
  1058. self.MapWindow.mouse['use'] = "queryVector"
  1059. self.MapWindow.mouse['box'] = "point"
  1060. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  1061. self.MapWindow.zoomtype = 0
  1062. # change the cursor
  1063. self.MapWindow.SetCursor(self.cursors["cross"])
  1064. def QueryMap(self, x, y):
  1065. """!Query map layer features
  1066. Currently only raster and vector map layers are supported.
  1067. @param x,y coordinates
  1068. """
  1069. #set query snap distance for v.what at mapunit equivalent of 10 pixels
  1070. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  1071. east, north = self.MapWindow.Pixel2Cell((x, y))
  1072. num = 0
  1073. for layer in self.tree.GetSelections():
  1074. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  1075. if type in ('raster', 'rgb', 'his',
  1076. 'vector', 'thememap', 'themechart'):
  1077. num += 1
  1078. if num < 1:
  1079. dlg = wx.MessageDialog(parent = self,
  1080. message = _('No raster or vector map layer selected for querying.'),
  1081. caption = _('No map layer selected'),
  1082. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1083. dlg.ShowModal()
  1084. dlg.Destroy()
  1085. return
  1086. mapname = None
  1087. raststr = ''
  1088. vectstr = ''
  1089. rcmd = ['r.what', '--v']
  1090. vcmd = ['v.what', '--v']
  1091. for layer in self.tree.GetSelections():
  1092. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  1093. dcmd = self.tree.GetPyData(layer)[0]['cmd']
  1094. name = utils.GetLayerNameFromCmd(dcmd)
  1095. if name == '':
  1096. continue
  1097. if type in ('raster', 'rgb', 'his'):
  1098. raststr += "%s," % name
  1099. elif type in ('vector', 'thememap', 'themechart'):
  1100. vectstr += "%s," % name
  1101. # use display region settings instead of computation region settings
  1102. self.tmpreg = os.getenv("GRASS_REGION")
  1103. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres=False)
  1104. # build query commands for any selected rasters and vectors
  1105. if raststr != '':
  1106. rcmd.append('-f')
  1107. rcmd.append('input=%s' % raststr.rstrip(','))
  1108. rcmd.append('east_north=%f,%f' % (float(east), float(north)))
  1109. if vectstr != '':
  1110. # check for vector maps open to be edited
  1111. digitToolbar = self.toolbars['vdigit']
  1112. if digitToolbar:
  1113. map = digitToolbar.GetLayer().GetName()
  1114. vect = []
  1115. for vector in vectstr.split(','):
  1116. if map == vector:
  1117. self._layerManager.goutput.WriteWarning("Vector map <%s> "
  1118. "opened for editing - skipped." % map)
  1119. continue
  1120. vect.append(vector)
  1121. vectstr = ','.join(vect)
  1122. if len(vectstr) <= 1:
  1123. self._layerManager.goutput.WriteCmdLog("Nothing to query.")
  1124. return
  1125. vcmd.append('-a')
  1126. vcmd.append('map=%s' % vectstr.rstrip(','))
  1127. vcmd.append('east_north=%f,%f' % (float(east), float(north)))
  1128. vcmd.append('distance=%f' % float(qdist))
  1129. # parse query command(s)
  1130. if self._layerManager:
  1131. if raststr:
  1132. self._layerManager.goutput.RunCmd(rcmd,
  1133. compReg=False,
  1134. onDone = self._QueryMapDone)
  1135. if vectstr:
  1136. self._layerManager.goutput.RunCmd(vcmd,
  1137. onDone = self._QueryMapDone)
  1138. else:
  1139. if raststr:
  1140. gcmd.RunCommand(rcmd)
  1141. if vectstr:
  1142. gcmd.RunCommand(vcmd)
  1143. def _QueryMapDone(self, returncode):
  1144. """!Restore settings after querying (restore GRASS_REGION)
  1145. @param returncode command return code
  1146. """
  1147. if hasattr(self, "tmpreg"):
  1148. if self.tmpreg:
  1149. os.environ["GRASS_REGION"] = self.tmpreg
  1150. elif os.environ.has_key('GRASS_REGION'):
  1151. del os.environ["GRASS_REGION"]
  1152. elif os.environ.has_key('GRASS_REGION'):
  1153. del os.environ["GRASS_REGION"]
  1154. if hasattr(self, "tmpreg"):
  1155. del self.tmpreg
  1156. def QueryVector(self, x, y):
  1157. """!Query vector map layer features
  1158. Attribute data of selected vector object are displayed in GUI dialog.
  1159. Data can be modified (On Submit)
  1160. """
  1161. if not self.tree.layer_selected or \
  1162. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] != 'vector':
  1163. wx.MessageBox(parent=self,
  1164. message=_("No vector map selected for querying."),
  1165. caption=_("Vector querying"),
  1166. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1167. return
  1168. if self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetMapset() != \
  1169. grass.gisenv()['MAPSET']:
  1170. wx.MessageBox(parent=self,
  1171. message=_("Only vector map from the current mapset can be modified."),
  1172. caption=_("Vector querying"),
  1173. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1174. return
  1175. posWindow = self.ClientToScreen((x + self.MapWindow.dialogOffset,
  1176. y + self.MapWindow.dialogOffset))
  1177. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) /
  1178. self.Map.width)
  1179. east, north = self.MapWindow.Pixel2Cell((x, y))
  1180. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name
  1181. if self.dialogs['attributes'] is None:
  1182. self.dialogs['attributes'] = \
  1183. dbm_dialogs.DisplayAttributesDialog(parent=self.MapWindow,
  1184. map=mapName,
  1185. query=((east, north), qdist),
  1186. pos=posWindow,
  1187. action="update")
  1188. else:
  1189. # selection changed?
  1190. if not self.dialogs['attributes'].mapDBInfo or \
  1191. self.dialogs['attributes'].mapDBInfo.map != mapName:
  1192. self.dialogs['attributes'].UpdateDialog(map=mapName, query=((east, north), qdist))
  1193. else:
  1194. self.dialogs['attributes'].UpdateDialog(query=((east, north), qdist))
  1195. cats = self.dialogs['attributes'].GetCats()
  1196. try:
  1197. qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)[0]
  1198. except IndexError:
  1199. qlayer = None
  1200. if self.dialogs['attributes'].mapDBInfo and cats:
  1201. # highlight feature & re-draw map
  1202. if qlayer:
  1203. qlayer.SetCmd(self.AddTmpVectorMapLayer(mapName, cats,
  1204. useId=False,
  1205. addLayer=False))
  1206. else:
  1207. qlayer = self.AddTmpVectorMapLayer(mapName, cats, useId=False)
  1208. # set opacity based on queried layer
  1209. opacity = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetOpacity(float=True)
  1210. qlayer.SetOpacity(opacity)
  1211. self.MapWindow.UpdateMap(render=False, renderVector=False)
  1212. if not self.dialogs['attributes'].IsShown():
  1213. self.dialogs['attributes'].Show()
  1214. else:
  1215. if qlayer:
  1216. self.Map.DeleteLayer(qlayer)
  1217. self.MapWindow.UpdateMap(render=False, renderVector=False)
  1218. if self.dialogs['attributes'].IsShown():
  1219. self.dialogs['attributes'].Hide()
  1220. def OnQuery(self, event):
  1221. """!Query tools menu"""
  1222. if self.toolbars['map']:
  1223. self.toolbars['map'].OnTool(event)
  1224. action = self.toolbars['map'].GetAction()
  1225. point = wx.GetMousePosition()
  1226. toolsmenu = wx.Menu()
  1227. # add items to the menu
  1228. if self.toolbars['nviz']:
  1229. raster = wx.MenuItem(parentMenu = toolsmenu, id = wx.ID_ANY,
  1230. text = _("Query surface (raster map)"),
  1231. kind = wx.ITEM_CHECK)
  1232. toolsmenu.AppendItem(raster)
  1233. self.Bind(wx.EVT_MENU, self.OnQueryDisplay, raster)
  1234. if action == "displayAttrb":
  1235. display.Check(True)
  1236. vector = wx.MenuItem(parentMenu = toolsmenu, id = wx.ID_ANY,
  1237. text = _("Query vector map"),
  1238. kind = wx.ITEM_CHECK)
  1239. toolsmenu.AppendItem(vector)
  1240. self.Bind(wx.EVT_MENU, self.OnQueryDisplay, vector)
  1241. else:
  1242. display = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
  1243. text=_("Query raster/vector map(s) (display mode)"),
  1244. kind=wx.ITEM_CHECK)
  1245. toolsmenu.AppendItem(display)
  1246. self.Bind(wx.EVT_MENU, self.OnQueryDisplay, display)
  1247. numLayers = 0
  1248. for layer in self.tree.GetSelections():
  1249. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  1250. if type in ('raster', 'rgb', 'his',
  1251. 'vector', 'thememap', 'themechart'):
  1252. numLayers += 1
  1253. if numLayers < 1:
  1254. display.Enable(False)
  1255. if action == "displayAttrb":
  1256. display.Check(True)
  1257. modify = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
  1258. text=_("Query vector map (edit mode)"),
  1259. kind=wx.ITEM_CHECK)
  1260. toolsmenu.AppendItem(modify)
  1261. self.Bind(wx.EVT_MENU, self.OnQueryModify, modify)
  1262. modify.Enable(False)
  1263. digitToolbar = self.toolbars['vdigit']
  1264. if self.tree.layer_selected:
  1265. layer_selected = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer']
  1266. if layer_selected.GetType() != 'vector' or \
  1267. (digitToolbar and \
  1268. digitToolbar.GetLayer() == layer_selected):
  1269. modify.Enable(False)
  1270. else:
  1271. if action == "modifyAttrb":
  1272. modify.Check(True)
  1273. self.PopupMenu(toolsmenu)
  1274. toolsmenu.Destroy()
  1275. def AddTmpVectorMapLayer(self, name, cats, useId=False, addLayer=True):
  1276. """
  1277. Add temporal vector map layer to map composition
  1278. @param name name of map layer
  1279. @param useId use feature id instead of category
  1280. """
  1281. # color settings from ATM
  1282. color = UserSettings.Get(group='atm', key='highlight', subkey='color')
  1283. colorStr = str(color[0]) + ":" + \
  1284. str(color[1]) + ":" + \
  1285. str(color[2])
  1286. # icon used in vector display and its size
  1287. icon = ''
  1288. size = 0
  1289. vparam = self.tree.GetPyData(self.tree.layer_selected)[0]['cmd']
  1290. for p in vparam:
  1291. if '=' in p:
  1292. parg,pval = p.split('=')
  1293. if parg == 'icon': icon = pval
  1294. elif parg == 'size': size = int(pval)
  1295. pattern = ["d.vect",
  1296. "map=%s" % name,
  1297. "color=%s" % colorStr,
  1298. "fcolor=%s" % colorStr,
  1299. "width=%d" % UserSettings.Get(group='atm', key='highlight', subkey='width')]
  1300. if icon != '':
  1301. pattern.append('icon=%s' % icon)
  1302. if size > 0:
  1303. pattern.append('size=%i' % size)
  1304. if useId:
  1305. cmd = pattern
  1306. cmd.append('-i')
  1307. cmd.append('cats=%s' % str(cats))
  1308. else:
  1309. cmd = []
  1310. for layer in cats.keys():
  1311. cmd.append(copy.copy(pattern))
  1312. lcats = cats[layer]
  1313. cmd[-1].append("layer=%d" % layer)
  1314. cmd[-1].append("cats=%s" % utils.ListOfCatsToRange(lcats))
  1315. # if self.icon:
  1316. # cmd.append("icon=%s" % (self.icon))
  1317. # if self.pointsize:
  1318. # cmd.append("size=%s" % (self.pointsize))
  1319. if addLayer:
  1320. if useId:
  1321. return self.Map.AddLayer(type='vector', name=globalvar.QUERYLAYER, command=cmd,
  1322. l_active=True, l_hidden=True, l_opacity=1.0)
  1323. else:
  1324. return self.Map.AddLayer(type='command', name=globalvar.QUERYLAYER, command=cmd,
  1325. l_active=True, l_hidden=True, l_opacity=1.0)
  1326. else:
  1327. return cmd
  1328. def OnAnalyze(self, event):
  1329. """
  1330. Analysis tools menu
  1331. """
  1332. point = wx.GetMousePosition()
  1333. toolsmenu = wx.Menu()
  1334. # Add items to the menu
  1335. measure = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["measure"].GetLabel())
  1336. measure.SetBitmap(Icons["measure"].GetBitmap(self.iconsize))
  1337. toolsmenu.AppendItem(measure)
  1338. self.Bind(wx.EVT_MENU, self.OnMeasure, measure)
  1339. profile = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["profile"].GetLabel())
  1340. profile.SetBitmap(Icons["profile"].GetBitmap(self.iconsize))
  1341. toolsmenu.AppendItem(profile)
  1342. self.Bind(wx.EVT_MENU, self.Profile, profile)
  1343. histogram = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["histogram"].GetLabel())
  1344. histogram.SetBitmap(Icons["histogram"].GetBitmap(self.iconsize))
  1345. toolsmenu.AppendItem(histogram)
  1346. self.Bind(wx.EVT_MENU, self.Histogram, histogram)
  1347. # Popup the menu. If an item is selected then its handler
  1348. # will be called before PopupMenu returns.
  1349. self.PopupMenu(toolsmenu)
  1350. toolsmenu.Destroy()
  1351. def OnMeasure(self, event):
  1352. """
  1353. Init measurement routine that calculates
  1354. map distance along transect drawn on
  1355. map display
  1356. """
  1357. self.totaldist = 0.0 # total measured distance
  1358. # switch GIS Manager to output console to show measure results
  1359. self._layerManager.notebook.SetSelection(1)
  1360. # change mouse to draw line for measurement
  1361. self.MapWindow.mouse['use'] = "measure"
  1362. self.MapWindow.mouse['box'] = "line"
  1363. self.MapWindow.zoomtype = 0
  1364. self.MapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SHORT_DASH)
  1365. self.MapWindow.polypen = wx.Pen(colour='green', width=2, style=wx.SHORT_DASH)
  1366. # change the cursor
  1367. self.MapWindow.SetCursor(self.cursors["pencil"])
  1368. # initiating output
  1369. style = self._layerManager.goutput.cmd_output.StyleWarning
  1370. self._layerManager.goutput.WriteLog(_('Click and drag with left mouse button '
  1371. 'to measure.%s'
  1372. 'Double click with left button to clear.') % \
  1373. (os.linesep), style)
  1374. if self.Map.projinfo['proj'] != 'xy':
  1375. units = self.Map.projinfo['units']
  1376. style = self._layerManager.goutput.cmd_output.StyleCommand
  1377. self._layerManager.goutput.WriteLog(_('Measuring distance') + ' ('
  1378. + units + '):',
  1379. style)
  1380. else:
  1381. self._layerManager.goutput.WriteLog(_('Measuring distance:'),
  1382. style)
  1383. def MeasureDist(self, beginpt, endpt):
  1384. """!Calculate map distance from screen distance
  1385. and print to output window
  1386. """
  1387. if self._layerManager.notebook.GetSelection() != 1:
  1388. self._layerManager.notebook.SetSelection(1)
  1389. dist, (north, east) = self.MapWindow.Distance(beginpt, endpt)
  1390. dist = round(dist, 3)
  1391. d, dunits = self.FormatDist(dist)
  1392. self.totaldist += dist
  1393. td, tdunits = self.FormatDist(self.totaldist)
  1394. strdist = str(d)
  1395. strtotdist = str(td)
  1396. if self.Map.projinfo['proj'] == 'xy' or 'degree' not in self.Map.projinfo['unit']:
  1397. angle = int(math.degrees(math.atan2(north,east)) + 0.5)
  1398. angle = 180 - angle
  1399. if angle < 0:
  1400. angle = 360+angle
  1401. mstring = 'segment = %s %s\ttotal distance = %s %s\tbearing = %d deg' \
  1402. % (strdist,dunits,strtotdist,tdunits,angle)
  1403. else:
  1404. mstring = 'segment = %s %s\ttotal distance = %s %s' \
  1405. % (strdist,dunits,strtotdist,tdunits)
  1406. self._layerManager.goutput.WriteLog(mstring)
  1407. return dist
  1408. def Profile(self, event):
  1409. """
  1410. Init profile canvas and tools
  1411. """
  1412. raster = []
  1413. if self.tree.layer_selected and \
  1414. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1415. raster.append(self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1416. self.profile = profile.ProfileFrame(self,
  1417. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(700,300),
  1418. style=wx.DEFAULT_FRAME_STYLE, rasterList=raster)
  1419. self.profile.Show()
  1420. # Open raster select dialog to make sure that a raster (and the desired raster)
  1421. # is selected to be profiled
  1422. self.profile.OnSelectRaster(None)
  1423. def FormatDist(self, dist):
  1424. """!Format length numbers and units in a nice way,
  1425. as a function of length. From code by Hamish Bowman
  1426. Grass Development Team 2006"""
  1427. mapunits = self.Map.projinfo['units']
  1428. if mapunits == 'metres': mapunits = 'meters'
  1429. outunits = mapunits
  1430. dist = float(dist)
  1431. divisor = 1.0
  1432. # figure out which units to use
  1433. if mapunits == 'meters':
  1434. if dist > 2500.0:
  1435. outunits = 'km'
  1436. divisor = 1000.0
  1437. else: outunits = 'm'
  1438. elif mapunits == 'feet':
  1439. # nano-bug: we match any "feet", but US Survey feet is really
  1440. # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
  1441. # miles the tick markers are rounded to the nearest 10th of a
  1442. # mile (528'), the difference in foot flavours is ignored.
  1443. if dist > 5280.0:
  1444. outunits = 'miles'
  1445. divisor = 5280.0
  1446. else:
  1447. outunits = 'ft'
  1448. elif 'degree' in mapunits:
  1449. if dist < 1:
  1450. outunits = 'min'
  1451. divisor = (1/60.0)
  1452. else:
  1453. outunits = 'deg'
  1454. # format numbers in a nice way
  1455. if (dist/divisor) >= 2500.0:
  1456. outdist = round(dist/divisor)
  1457. elif (dist/divisor) >= 1000.0:
  1458. outdist = round(dist/divisor,1)
  1459. elif (dist/divisor) > 0.0:
  1460. outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
  1461. else:
  1462. outdist = float(dist/divisor)
  1463. return (outdist, outunits)
  1464. def Histogram(self, event):
  1465. """
  1466. Init histogram display canvas and tools
  1467. """
  1468. self.histogram = histogram.HistFrame(self,
  1469. id=wx.ID_ANY, size=globalvar.HIST_WINDOW_SIZE,
  1470. style=wx.DEFAULT_FRAME_STYLE)
  1471. #show new display
  1472. self.histogram.Show()
  1473. self.histogram.Refresh()
  1474. self.histogram.Update()
  1475. def OnDecoration(self, event):
  1476. """
  1477. Decorations overlay menu
  1478. """
  1479. point = wx.GetMousePosition()
  1480. decmenu = wx.Menu()
  1481. # Add items to the menu
  1482. AddScale = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addbarscale"].GetLabel())
  1483. AddScale.SetBitmap(Icons["addbarscale"].GetBitmap(self.iconsize))
  1484. decmenu.AppendItem(AddScale)
  1485. self.Bind(wx.EVT_MENU, self.OnAddBarscale, AddScale)
  1486. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addlegend"].GetLabel())
  1487. AddLegend.SetBitmap(Icons["addlegend"].GetBitmap(self.iconsize))
  1488. decmenu.AppendItem(AddLegend)
  1489. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  1490. AddText = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addtext"].GetLabel())
  1491. AddText.SetBitmap(Icons["addtext"].GetBitmap(self.iconsize))
  1492. decmenu.AppendItem(AddText)
  1493. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  1494. # Popup the menu. If an item is selected then its handler
  1495. # will be called before PopupMenu returns.
  1496. self.PopupMenu(decmenu)
  1497. decmenu.Destroy()
  1498. def OnAddBarscale(self, event):
  1499. """
  1500. Handler for scale/arrow map decoration menu selection.
  1501. """
  1502. if self.dialogs['barscale']:
  1503. return
  1504. id = 0 # unique index for overlay layer
  1505. # If location is latlon, only display north arrow (scale won't work)
  1506. # proj = self.Map.projinfo['proj']
  1507. # if proj == 'll':
  1508. # barcmd = 'd.barscale -n'
  1509. # else:
  1510. # barcmd = 'd.barscale'
  1511. # decoration overlay control dialog
  1512. self.dialogs['barscale'] = \
  1513. gdialogs.DecorationDialog(parent=self, title=_('Scale and North arrow'),
  1514. size=(350, 200),
  1515. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1516. cmd=['d.barscale', 'at=0,5'],
  1517. ovlId=id,
  1518. name='barscale',
  1519. checktxt = _("Show/hide scale and North arrow"),
  1520. ctrltxt = _("scale object"))
  1521. self.dialogs['barscale'].CentreOnParent()
  1522. ### dialog cannot be show as modal - in the result d.barscale is not selectable
  1523. ### self.dialogs['barscale'].ShowModal()
  1524. self.dialogs['barscale'].Show()
  1525. self.MapWindow.mouse['use'] = 'pointer'
  1526. def OnAddLegend(self, event):
  1527. """
  1528. Handler for legend map decoration menu selection.
  1529. """
  1530. if self.dialogs['legend']:
  1531. return
  1532. id = 1 # index for overlay layer in render
  1533. cmd = ['d.legend', 'at=5,50,2,5']
  1534. if self.tree.layer_selected and \
  1535. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1536. cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1537. # Decoration overlay control dialog
  1538. self.dialogs['legend'] = \
  1539. gdialogs.DecorationDialog(parent=self, title=('Legend'),
  1540. size=(350, 200),
  1541. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1542. cmd=cmd,
  1543. ovlId=id,
  1544. name='legend',
  1545. checktxt = _("Show/hide legend"),
  1546. ctrltxt = _("legend object"))
  1547. self.dialogs['legend'].CentreOnParent()
  1548. ### dialog cannot be show as modal - in the result d.legend is not selectable
  1549. ### self.dialogs['legend'].ShowModal()
  1550. self.dialogs['legend'].Show()
  1551. self.MapWindow.mouse['use'] = 'pointer'
  1552. def OnAddText(self, event):
  1553. """
  1554. Handler for text decoration menu selection.
  1555. """
  1556. if self.MapWindow.dragid > -1:
  1557. id = self.MapWindow.dragid
  1558. else:
  1559. # index for overlay layer in render
  1560. if len(self.MapWindow.textdict.keys()) > 0:
  1561. id = self.MapWindow.textdict.keys()[-1] + 1
  1562. else:
  1563. id = 101
  1564. self.dialogs['text'] = gdialogs.TextLayerDialog(parent=self, ovlId=id,
  1565. title=_('Add text layer'),
  1566. size=(400, 200))
  1567. self.dialogs['text'].CenterOnParent()
  1568. # If OK button pressed in decoration control dialog
  1569. if self.dialogs['text'].ShowModal() == wx.ID_OK:
  1570. text = self.dialogs['text'].GetValues()['text']
  1571. active = self.dialogs['text'].GetValues()['active']
  1572. coords, w, h = self.MapWindow.TextBounds(self.dialogs['text'].GetValues())
  1573. # delete object if it has no text or is not active
  1574. if text == '' or active == False:
  1575. try:
  1576. self.MapWindow.pdc.ClearId(id)
  1577. self.MapWindow.pdc.RemoveId(id)
  1578. del self.MapWindow.textdict[id]
  1579. except:
  1580. pass
  1581. return
  1582. self.MapWindow.pdc.ClearId(id)
  1583. self.MapWindow.pdc.SetId(id)
  1584. self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
  1585. self.MapWindow.Draw(self.MapWindow.pdcDec, img=self.MapWindow.textdict[id],
  1586. drawid=id, pdctype='text', coords=coords)
  1587. self.MapWindow.UpdateMap(render=False, renderVector=False)
  1588. self.MapWindow.mouse['use'] = 'pointer'
  1589. def GetOptData(self, dcmd, type, params, propwin):
  1590. """
  1591. Callback method for decoration overlay command generated by
  1592. dialog created in menuform.py
  1593. """
  1594. # Reset comand and rendering options in render.Map. Always render decoration.
  1595. # Showing/hiding handled by PseudoDC
  1596. self.Map.ChangeOverlay(ovltype=type, type='overlay', name='', command=dcmd,
  1597. l_active=True, l_render=False)
  1598. self.params[type] = params
  1599. self.propwin[type] = propwin
  1600. def OnZoomToMap(self, event):
  1601. """!
  1602. Set display extents to match selected raster (including NULLs)
  1603. or vector map.
  1604. """
  1605. self.MapWindow.ZoomToMap()
  1606. def OnZoomToRaster(self, event):
  1607. """!
  1608. Set display extents to match selected raster map (ignore NULLs)
  1609. """
  1610. self.MapWindow.ZoomToMap(ignoreNulls = True)
  1611. def OnZoomToWind(self, event):
  1612. """!Set display geometry to match computational region
  1613. settings (set with g.region)
  1614. """
  1615. self.MapWindow.ZoomToWind()
  1616. def OnZoomToDefault(self, event):
  1617. """!Set display geometry to match default region settings
  1618. """
  1619. self.MapWindow.ZoomToDefault()
  1620. def OnZoomToSaved(self, event):
  1621. """!Set display geometry to match extents in
  1622. saved region file
  1623. """
  1624. self.MapWindow.ZoomToSaved()
  1625. def OnDisplayToWind(self, event):
  1626. """!Set computational region (WIND file) to match display
  1627. extents
  1628. """
  1629. self.MapWindow.DisplayToWind()
  1630. def SaveDisplayRegion(self, event):
  1631. """!Save display extents to named region file.
  1632. """
  1633. self.MapWindow.SaveDisplayRegion()
  1634. def OnZoomMenu(self, event):
  1635. """!Popup Zoom menu
  1636. """
  1637. point = wx.GetMousePosition()
  1638. zoommenu = wx.Menu()
  1639. # Add items to the menu
  1640. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region (set with g.region)'))
  1641. zoommenu.AppendItem(zoomwind)
  1642. self.Bind(wx.EVT_MENU, self.OnZoomToWind, zoomwind)
  1643. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  1644. zoommenu.AppendItem(zoomdefault)
  1645. self.Bind(wx.EVT_MENU, self.OnZoomToDefault, zoomdefault)
  1646. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  1647. zoommenu.AppendItem(zoomsaved)
  1648. self.Bind(wx.EVT_MENU, self.OnZoomToSaved, zoomsaved)
  1649. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display'))
  1650. zoommenu.AppendItem(savewind)
  1651. self.Bind(wx.EVT_MENU, self.OnDisplayToWind, savewind)
  1652. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  1653. zoommenu.AppendItem(savezoom)
  1654. self.Bind(wx.EVT_MENU, self.SaveDisplayRegion, savezoom)
  1655. # Popup the menu. If an item is selected then its handler
  1656. # will be called before PopupMenu returns.
  1657. self.PopupMenu(zoommenu)
  1658. zoommenu.Destroy()
  1659. def SetProperties(self, render=False, mode=0, showCompExtent=False,
  1660. constrainRes=False, projection=False):
  1661. """!Set properies of map display window"""
  1662. self.statusbarWin['render'].SetValue(render)
  1663. self.statusbarWin['toggle'].SetSelection(mode)
  1664. self.StatusbarUpdate()
  1665. self.statusbarWin['region'].SetValue(showCompExtent)
  1666. self.statusbarWin['resolution'].SetValue(constrainRes)
  1667. self.statusbarWin['projection'].SetValue(projection)
  1668. if showCompExtent:
  1669. self.MapWindow.regionCoords = []
  1670. def IsStandalone(self):
  1671. """!Check if Map display is standalone"""
  1672. if self._layerManager:
  1673. return False
  1674. return True
  1675. def GetLayerManager(self):
  1676. """!Get reference to Layer Manager
  1677. @return window reference
  1678. @return None (if standalone)
  1679. """
  1680. return self._layerManager
  1681. # end of class MapFrame
  1682. class MapApp(wx.App):
  1683. """
  1684. MapApp class
  1685. """
  1686. def OnInit(self):
  1687. wx.InitAllImageHandlers()
  1688. if __name__ == "__main__":
  1689. Map = render.Map() # instance of Map class to render GRASS display output to PPM file
  1690. else:
  1691. Map = None
  1692. self.mapFrm = MapFrame(parent=None, id=wx.ID_ANY, Map=Map,
  1693. size=globalvar.MAP_WINDOW_SIZE)
  1694. #self.SetTopWindow(Map)
  1695. self.mapFrm.Show()
  1696. if __name__ == "__main__":
  1697. # redraw map, if new command appears
  1698. self.redraw = False
  1699. status = Command(self, Map, cmdfilename)
  1700. status.start()
  1701. self.timer = wx.PyTimer(self.watcher)
  1702. # check each 0.1s
  1703. self.timer.Start(100)
  1704. return 1
  1705. def OnExit(self):
  1706. if __name__ == "__main__":
  1707. # stop the timer
  1708. self.timer.Stop()
  1709. # terminate thread (a bit ugly)
  1710. os.system("""!echo "quit" >> %s""" % (cmdfilename))
  1711. def watcher(self):
  1712. """!Redraw, if new layer appears"""
  1713. if self.redraw:
  1714. self.mapFrm.OnDraw(None)
  1715. self.redraw = False
  1716. return
  1717. # end of class MapApp
  1718. if __name__ == "__main__":
  1719. ###### SET command variable
  1720. if len(sys.argv) != 3:
  1721. print __doc__
  1722. sys.exit()
  1723. title = sys.argv[1]
  1724. cmdfilename = sys.argv[2]
  1725. import gettext
  1726. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  1727. print >> sys.stderr, "\nStarting monitor <%s>...\n" % (title)
  1728. gm_map = MapApp(0)
  1729. # set title
  1730. gm_map.mapFrm.SetTitle(_("GRASS GIS Map Display: " +
  1731. title +
  1732. " - Location: " + grass.gisenv()["LOCATION_NAME"]))
  1733. gm_map.MainLoop()
  1734. os.remove(cmdfilename)
  1735. os.system("""!g.gisenv set="GRASS_PYCMDFILE" """)
  1736. print >> sys.stderr, "\nStopping monitor <%s>...\n" % (title)
  1737. sys.exit(0)