mapdisp.py 84 KB

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