mapdisp.py 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025
  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)).
  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.MapWindow = self.MapWindowVDigit
  278. self._mgr.DetachPane(self.MapWindow2D)
  279. self.MapWindow2D.Hide()
  280. self.toolbars['vdigit'] = toolbars.VDigitToolbar(parent = self, mapcontent = self.Map,
  281. layerTree = self.tree,
  282. log = log)
  283. self.MapWindowVDigit.SetToolbar(self.toolbars['vdigit'])
  284. self._mgr.AddPane(self.MapWindowVDigit, wx.aui.AuiPaneInfo().CentrePane().
  285. Dockable(False).BestSize((-1,-1)).
  286. CloseButton(False).DestroyOnClose(True).
  287. Layer(0))
  288. self._mgr.AddPane(self.toolbars['vdigit'],
  289. wx.aui.AuiPaneInfo().
  290. Name("vdigittoolbar").Caption(_("Vector Digitizer Toolbar")).
  291. ToolbarPane().Top().Row(1).
  292. LeftDockable(False).RightDockable(False).
  293. BottomDockable(False).TopDockable(True).
  294. CloseButton(False).Layer(2).
  295. BestSize((self.toolbars['vdigit'].GetBestSize())))
  296. # change mouse to draw digitized line
  297. self.MapWindow.mouse['box'] = "point"
  298. self.MapWindow.zoomtype = 0
  299. self.MapWindow.pen = wx.Pen(colour = 'red', width = 2, style = wx.SOLID)
  300. self.MapWindow.polypen = wx.Pen(colour = 'green', width = 2, style = wx.SOLID)
  301. def _addToolbarNviz(self):
  302. """!Add 3D view mode toolbar
  303. """
  304. import nviz
  305. Debug.msg(5, "MapFrame._addToolbarNviz(): begin")
  306. # check for GLCanvas and OpenGL
  307. if not nviz.haveNviz:
  308. self.toolbars['map'].combo.SetValue(_("2D view"))
  309. gcmd.GError(parent = self,
  310. message = _("Unable to switch to 3D display mode.\nThe Nviz python extension "
  311. "was not found or loaded properly.\n"
  312. "Switching back to 2D display mode.\n\nDetails: %s" % nviz.errorMsg))
  313. return
  314. # add Nviz toolbar and disable 2D display mode tools
  315. self.toolbars['nviz'] = toolbars.NvizToolbar(self, self.Map)
  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. self.statusbar.SetStatusText(_("Please wait, loading data..."), 0)
  328. # create GL window & NVIZ toolbar
  329. if not self.MapWindow3D:
  330. Debug.msg(5, "MapFrame._addToolbarNviz(): GLWindow will be created")
  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.UpdateOverlays()
  337. # add Nviz notebookpage
  338. self._layerManager.AddNviz()
  339. self.MapWindow3D.OnPaint(None) # -> LoadData
  340. self.MapWindow3D.Show()
  341. self.MapWindow3D.UpdateView(None)
  342. else:
  343. self.MapWindow = self.MapWindow3D
  344. self.MapWindow3D.UpdateOverlays()
  345. # add Nviz notebookpage
  346. self._layerManager.AddNviz()
  347. for page in ('view', 'light', 'fringe', 'constant', 'cplane'):
  348. self._layerManager.nviz.UpdatePage(page)
  349. # switch from MapWindow to MapWindowGL
  350. # add nviz toolbar
  351. self._mgr.DetachPane(self.MapWindow2D)
  352. self.MapWindow2D.Hide()
  353. self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
  354. Dockable(False).BestSize((-1,-1)).
  355. CloseButton(False).DestroyOnClose(True).
  356. Layer(0))
  357. self._mgr.AddPane(self.toolbars['nviz'],
  358. wx.aui.AuiPaneInfo().
  359. Name("nviztoolbar").Caption(_("3D View Toolbar")).
  360. ToolbarPane().Top().Row(1).
  361. LeftDockable(False).RightDockable(False).
  362. BottomDockable(False).TopDockable(True).
  363. CloseButton(False).Layer(2).
  364. BestSize((self.toolbars['nviz'].GetBestSize())))
  365. self.SetStatusText("", 0)
  366. Debug.msg(5, "MapFrame._addToolbarNviz(): end")
  367. def AddToolbar(self, name):
  368. """!Add defined toolbar to the window
  369. Currently known toolbars are:
  370. - 'map' - basic map toolbar
  371. - 'vdigit' - vector digitizer
  372. - 'gcpdisp' - GCP Manager Display
  373. - 'georect' - georectifier
  374. - 'nviz' - 3D view mode
  375. """
  376. # default toolbar
  377. if name == "map":
  378. self.toolbars['map'] = toolbars.MapToolbar(self, self.Map)
  379. self._mgr.AddPane(self.toolbars['map'],
  380. wx.aui.AuiPaneInfo().
  381. Name("maptoolbar").Caption(_("Map Toolbar")).
  382. ToolbarPane().Top().
  383. LeftDockable(False).RightDockable(False).
  384. BottomDockable(False).TopDockable(True).
  385. CloseButton(False).Layer(2).
  386. BestSize((self.toolbars['map'].GetBestSize())))
  387. # vector digitizer
  388. elif name == "vdigit":
  389. self._addToolbarVDigit()
  390. # georectifier
  391. elif name == "georect":
  392. self.toolbars['georect'] = toolbars.GRToolbar(self, self.Map)
  393. self._mgr.AddPane(self.toolbars['georect'],
  394. wx.aui.AuiPaneInfo().
  395. Name("georecttoolbar").Caption(_("Georectification Toolbar")).
  396. ToolbarPane().Top().
  397. LeftDockable(False).RightDockable(False).
  398. BottomDockable(False).TopDockable(True).
  399. CloseButton(False).Layer(2).
  400. BestSize((self.toolbars['georect'].GetBestSize())))
  401. # nviz
  402. elif name == "nviz":
  403. self._addToolbarNviz()
  404. self._mgr.Update()
  405. def RemoveToolbar (self, name):
  406. """!Removes defined toolbar from the window
  407. @todo Only hide, activate by calling AddToolbar()
  408. """
  409. # cannot hide main toolbar
  410. if name == "map":
  411. return
  412. self._mgr.DetachPane(self.toolbars[name])
  413. self.toolbars[name].Destroy()
  414. self.toolbars[name] = None
  415. if name == 'vdigit':
  416. self._mgr.DetachPane(self.MapWindowVDigit)
  417. self.MapWindowVDigit.Hide()
  418. self.MapWindow2D.Show()
  419. self._mgr.AddPane(self.MapWindow2D, wx.aui.AuiPaneInfo().CentrePane().
  420. Dockable(False).BestSize((-1,-1)).
  421. CloseButton(False).DestroyOnClose(True).
  422. Layer(0))
  423. self.MapWindow = self.MapWindow2D
  424. elif name == 'nviz':
  425. # unload data
  426. # self.MapWindow3D.Reset()
  427. # switch from MapWindowGL to MapWindow
  428. self._mgr.DetachPane(self.MapWindow3D)
  429. self.MapWindow3D.Hide()
  430. self.MapWindow2D.Show()
  431. self._mgr.AddPane(self.MapWindow2D, wx.aui.AuiPaneInfo().CentrePane().
  432. Dockable(False).BestSize((-1,-1)).
  433. CloseButton(False).DestroyOnClose(True).
  434. Layer(0))
  435. self.MapWindow = self.MapWindow2D
  436. # remove nviz notebook page
  437. self._layerManager.RemoveNviz()
  438. self.MapWindow.UpdateMap()
  439. self.toolbars['map'].combo.SetValue(_("2D view"))
  440. self.toolbars['map'].Enable2D(True)
  441. self.statusbarWin['toggle'].Enable(True)
  442. self._mgr.Update()
  443. def _initDisplay(self):
  444. """!Initialize map display, set dimensions and map region
  445. """
  446. if not grass.find_program('g.region', ['--help']):
  447. sys.exit(_("GRASS module '%s' not found. Unable to start map "
  448. "display window.") % 'g.region')
  449. self.width, self.height = self.GetClientSize()
  450. Debug.msg(2, "MapFrame._initDisplay():")
  451. self.Map.ChangeMapSize(self.GetClientSize())
  452. self.Map.region = self.Map.GetRegion() # g.region -upgc
  453. # self.Map.SetRegion() # adjust region to match display window
  454. def OnUpdateProgress(self, event):
  455. """!Update progress bar info
  456. """
  457. self.statusbarWin['progress'].SetValue(event.value)
  458. event.Skip()
  459. def OnFocus(self, event):
  460. """
  461. Change choicebook page to match display.
  462. Or set display for georectifying
  463. """
  464. if self._layerManager and \
  465. self._layerManager.georectifying:
  466. # in georectifying session; display used to get geographic
  467. # coordinates for GCPs
  468. self.OnPointer(event)
  469. else:
  470. # change bookcontrol page to page associated with display
  471. if self.page:
  472. pgnum = self.layerbook.GetPageIndex(self.page)
  473. if pgnum > -1:
  474. self.layerbook.SetSelection(pgnum)
  475. self._layerManager.curr_page = self.layerbook.GetCurrentPage()
  476. self.layerbook
  477. event.Skip()
  478. def OnDraw(self, event):
  479. """!Re-display current map composition
  480. """
  481. self.MapWindow.UpdateMap(render = False)
  482. def OnRender(self, event):
  483. """!Re-render map composition (each map layer)
  484. """
  485. # delete tmp map layers (queries)
  486. qlayer = self.Map.GetListOfLayers(l_name = globalvar.QUERYLAYER)
  487. for layer in qlayer:
  488. self.Map.DeleteLayer(layer)
  489. # delete tmp lines
  490. if self.MapWindow.mouse["use"] in ("measure",
  491. "profile"):
  492. self.MapWindow.polycoords = []
  493. self.MapWindow.ClearLines()
  494. # deselect features in vdigit
  495. if self.toolbars['vdigit']:
  496. self.MapWindow.digit.GetDisplay().SetSelected([])
  497. self.MapWindow.UpdateMap(render = True, renderVector = True)
  498. else:
  499. self.MapWindow.UpdateMap(render = True)
  500. # update statusbar
  501. self.StatusbarUpdate()
  502. def OnPointer(self, event):
  503. """!Pointer button clicked
  504. """
  505. if self.toolbars['map']:
  506. if event:
  507. self.toolbars['map'].OnTool(event)
  508. self.toolbars['map'].action['desc'] = ''
  509. self.MapWindow.mouse['use'] = "pointer"
  510. self.MapWindow.mouse['box'] = "point"
  511. # change the cursor
  512. if self.toolbars['vdigit']:
  513. # digitization tool activated
  514. self.MapWindow.SetCursor(self.cursors["cross"])
  515. # reset mouse['box'] if needed
  516. if self.toolbars['vdigit'].GetAction() in ['addLine']:
  517. if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
  518. self.MapWindow.mouse['box'] = 'point'
  519. else: # line, boundary
  520. self.MapWindow.mouse['box'] = 'line'
  521. elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
  522. 'editLine', 'displayCats', 'queryMap',
  523. 'copyCats']:
  524. self.MapWindow.mouse['box'] = 'point'
  525. else: # moveLine, deleteLine
  526. self.MapWindow.mouse['box'] = 'box'
  527. elif self._layerManager and self._layerManager.georectifying:
  528. self.MapWindow.SetCursor(self.cursors["cross"])
  529. else:
  530. self.MapWindow.SetCursor(self.cursors["default"])
  531. def OnZoomIn(self, event):
  532. """!Zoom in the map.
  533. Set mouse cursor, zoombox attributes, and zoom direction
  534. """
  535. if self.toolbars['map']:
  536. self.toolbars['map'].OnTool(event)
  537. self.toolbars['map'].action['desc'] = ''
  538. self.MapWindow.mouse['use'] = "zoom"
  539. self.MapWindow.mouse['box'] = "box"
  540. self.MapWindow.zoomtype = 1
  541. self.MapWindow.pen = wx.Pen(colour = 'Red', width = 2, style = wx.SHORT_DASH)
  542. # change the cursor
  543. self.MapWindow.SetCursor(self.cursors["cross"])
  544. def OnZoomOut(self, event):
  545. """!Zoom out the map.
  546. Set mouse cursor, zoombox attributes, and zoom direction
  547. """
  548. if self.toolbars['map']:
  549. self.toolbars['map'].OnTool(event)
  550. self.toolbars['map'].action['desc'] = ''
  551. self.MapWindow.mouse['use'] = "zoom"
  552. self.MapWindow.mouse['box'] = "box"
  553. self.MapWindow.zoomtype = -1
  554. self.MapWindow.pen = wx.Pen(colour = 'Red', width = 2, style = wx.SHORT_DASH)
  555. # change the cursor
  556. self.MapWindow.SetCursor(self.cursors["cross"])
  557. def OnZoomBack(self, event):
  558. """!Zoom last (previously stored position)
  559. """
  560. self.MapWindow.ZoomBack()
  561. def OnPan(self, event):
  562. """!Panning, set mouse to drag
  563. """
  564. if self.toolbars['map']:
  565. self.toolbars['map'].OnTool(event)
  566. self.toolbars['map'].action['desc'] = ''
  567. self.MapWindow.mouse['use'] = "pan"
  568. self.MapWindow.mouse['box'] = "pan"
  569. self.MapWindow.zoomtype = 0
  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' : -1 },
  971. { 'ext' : 'tif', 'type' : wx.BITMAP_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. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, icons["addLegend"].GetLabel())
  1442. AddLegend.SetBitmap(icons["addLegend"].GetBitmap(self.iconsize))
  1443. decmenu.AppendItem(AddLegend)
  1444. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  1445. AddText = wx.MenuItem(decmenu, wx.ID_ANY, icons["addText"].GetLabel())
  1446. AddText.SetBitmap(icons["addText"].GetBitmap(self.iconsize))
  1447. decmenu.AppendItem(AddText)
  1448. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  1449. # temporary
  1450. if self.toolbars['nviz']:
  1451. AddText.Enable(False)
  1452. AddScale.Enable(False)
  1453. AddArrow = wx.MenuItem(decmenu, wx.ID_ANY, _("Add north arrow"))
  1454. AddArrow.SetBitmap(icons["addBarscale"].GetBitmap(self.iconsize))
  1455. decmenu.AppendItem(AddArrow)
  1456. self.Bind(wx.EVT_MENU, self.OnAddArrow, AddArrow)
  1457. # Popup the menu. If an item is selected then its handler
  1458. # will be called before PopupMenu returns.
  1459. self.PopupMenu(decmenu)
  1460. decmenu.Destroy()
  1461. def OnAddBarscale(self, event):
  1462. """!Handler for scale/arrow map decoration menu selection.
  1463. """
  1464. if self.dialogs['barscale']:
  1465. return
  1466. id = 0 # unique index for overlay layer
  1467. # If location is latlon, only display north arrow (scale won't work)
  1468. # proj = self.Map.projinfo['proj']
  1469. # if proj == 'll':
  1470. # barcmd = 'd.barscale -n'
  1471. # else:
  1472. # barcmd = 'd.barscale'
  1473. # decoration overlay control dialog
  1474. self.dialogs['barscale'] = \
  1475. gdialogs.DecorationDialog(parent = self, title = _('Scale and North arrow'),
  1476. size = (350, 200),
  1477. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1478. cmd = ['d.barscale', 'at=0,95'],
  1479. ovlId = id,
  1480. name = 'barscale',
  1481. checktxt = _("Show/hide scale and North arrow"),
  1482. ctrltxt = _("scale object"))
  1483. self.dialogs['barscale'].CentreOnParent()
  1484. ### dialog cannot be show as modal - in the result d.barscale is not selectable
  1485. ### self.dialogs['barscale'].ShowModal()
  1486. self.dialogs['barscale'].Show()
  1487. self.MapWindow.mouse['use'] = 'pointer'
  1488. def OnAddLegend(self, event):
  1489. """!Handler for legend map decoration menu selection.
  1490. """
  1491. if self.dialogs['legend']:
  1492. return
  1493. id = 1 # index for overlay layer in render
  1494. cmd = ['d.legend', 'at=5,50,2,5']
  1495. if self.tree.layer_selected and \
  1496. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1497. cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1498. # Decoration overlay control dialog
  1499. self.dialogs['legend'] = \
  1500. gdialogs.DecorationDialog(parent = self, title = ('Legend'),
  1501. size = (350, 200),
  1502. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1503. cmd = cmd,
  1504. ovlId = id,
  1505. name = 'legend',
  1506. checktxt = _("Show/hide legend"),
  1507. ctrltxt = _("legend object"))
  1508. self.dialogs['legend'].CentreOnParent()
  1509. ### dialog cannot be show as modal - in the result d.legend is not selectable
  1510. ### self.dialogs['legend'].ShowModal()
  1511. self.dialogs['legend'].Show()
  1512. self.MapWindow.mouse['use'] = 'pointer'
  1513. def OnAddText(self, event):
  1514. """!Handler for text decoration menu selection.
  1515. """
  1516. if self.MapWindow.dragid > -1:
  1517. id = self.MapWindow.dragid
  1518. else:
  1519. # index for overlay layer in render
  1520. if len(self.MapWindow.textdict.keys()) > 0:
  1521. id = self.MapWindow.textdict.keys()[-1] + 1
  1522. else:
  1523. id = 101
  1524. self.dialogs['text'] = gdialogs.TextLayerDialog(parent = self, ovlId = id,
  1525. title = _('Add text layer'),
  1526. size = (400, 200))
  1527. self.dialogs['text'].CenterOnParent()
  1528. # If OK button pressed in decoration control dialog
  1529. if self.dialogs['text'].ShowModal() == wx.ID_OK:
  1530. text = self.dialogs['text'].GetValues()['text']
  1531. active = self.dialogs['text'].GetValues()['active']
  1532. coords, w, h = self.MapWindow.TextBounds(self.dialogs['text'].GetValues())
  1533. # delete object if it has no text or is not active
  1534. if text == '' or active == False:
  1535. try:
  1536. self.MapWindow.pdc.ClearId(id)
  1537. self.MapWindow.pdc.RemoveId(id)
  1538. del self.MapWindow.textdict[id]
  1539. except:
  1540. pass
  1541. return
  1542. self.MapWindow.pdc.ClearId(id)
  1543. self.MapWindow.pdc.SetId(id)
  1544. self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
  1545. self.MapWindow.Draw(self.MapWindow.pdcDec, img = self.MapWindow.textdict[id],
  1546. drawid = id, pdctype = 'text', coords = coords)
  1547. self.MapWindow.UpdateMap(render = False, renderVector = False)
  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. def GetOptData(self, dcmd, type, params, propwin):
  1555. """!Callback method for decoration overlay command generated by
  1556. dialog created in menuform.py
  1557. """
  1558. # Reset comand and rendering options in render.Map. Always render decoration.
  1559. # Showing/hiding handled by PseudoDC
  1560. self.Map.ChangeOverlay(ovltype = type, type = 'overlay', name = '', command = dcmd,
  1561. l_active = True, l_render = False)
  1562. self.params[type] = params
  1563. self.propwin[type] = propwin
  1564. def OnZoomToMap(self, event):
  1565. """!Set display extents to match selected raster (including
  1566. NULLs) or vector map.
  1567. """
  1568. self.MapWindow.ZoomToMap()
  1569. def OnZoomToRaster(self, event):
  1570. """!Set display extents to match selected raster map (ignore NULLs)
  1571. """
  1572. self.MapWindow.ZoomToMap(ignoreNulls = True)
  1573. def OnZoomToWind(self, event):
  1574. """!Set display geometry to match computational region
  1575. settings (set with g.region)
  1576. """
  1577. self.MapWindow.ZoomToWind()
  1578. def OnZoomToDefault(self, event):
  1579. """!Set display geometry to match default region settings
  1580. """
  1581. self.MapWindow.ZoomToDefault()
  1582. def OnZoomToSaved(self, event):
  1583. """!Set display geometry to match extents in
  1584. saved region file
  1585. """
  1586. self.MapWindow.ZoomToSaved()
  1587. def OnDisplayToWind(self, event):
  1588. """!Set computational region (WIND file) to match display
  1589. extents
  1590. """
  1591. self.MapWindow.DisplayToWind()
  1592. def SaveDisplayRegion(self, event):
  1593. """!Save display extents to named region file.
  1594. """
  1595. self.MapWindow.SaveDisplayRegion()
  1596. def OnZoomMenu(self, event):
  1597. """!Popup Zoom menu
  1598. """
  1599. point = wx.GetMousePosition()
  1600. zoommenu = wx.Menu()
  1601. # Add items to the menu
  1602. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region'))
  1603. zoommenu.AppendItem(zoomwind)
  1604. self.Bind(wx.EVT_MENU, self.OnZoomToWind, zoomwind)
  1605. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  1606. zoommenu.AppendItem(zoomdefault)
  1607. self.Bind(wx.EVT_MENU, self.OnZoomToDefault, zoomdefault)
  1608. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  1609. zoommenu.AppendItem(zoomsaved)
  1610. self.Bind(wx.EVT_MENU, self.OnZoomToSaved, zoomsaved)
  1611. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display'))
  1612. zoommenu.AppendItem(savewind)
  1613. self.Bind(wx.EVT_MENU, self.OnDisplayToWind, savewind)
  1614. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  1615. zoommenu.AppendItem(savezoom)
  1616. self.Bind(wx.EVT_MENU, self.SaveDisplayRegion, savezoom)
  1617. # Popup the menu. If an item is selected then its handler
  1618. # will be called before PopupMenu returns.
  1619. self.PopupMenu(zoommenu)
  1620. zoommenu.Destroy()
  1621. def SetProperties(self, render = False, mode = 0, showCompExtent = False,
  1622. constrainRes = False, projection = False):
  1623. """!Set properies of map display window"""
  1624. self.statusbarWin['render'].SetValue(render)
  1625. self.statusbarWin['toggle'].SetSelection(mode)
  1626. self.StatusbarUpdate()
  1627. self.statusbarWin['region'].SetValue(showCompExtent)
  1628. self.statusbarWin['resolution'].SetValue(constrainRes)
  1629. self.statusbarWin['projection'].SetValue(projection)
  1630. if showCompExtent:
  1631. self.MapWindow.regionCoords = []
  1632. def IsStandalone(self):
  1633. """!Check if Map display is standalone"""
  1634. if self._layerManager:
  1635. return False
  1636. return True
  1637. def GetLayerManager(self):
  1638. """!Get reference to Layer Manager
  1639. @return window reference
  1640. @return None (if standalone)
  1641. """
  1642. return self._layerManager
  1643. class MapApp(wx.App):
  1644. def OnInit(self):
  1645. wx.InitAllImageHandlers()
  1646. if __name__ == "__main__":
  1647. self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
  1648. Map = render.Map(cmdfile = monFile['cmd'], mapfile = monFile['map'],
  1649. envfile = monFile['env'], monitor = monName)
  1650. else:
  1651. Map = None
  1652. self.mapFrm = MapFrame(parent = None, id = wx.ID_ANY, Map = Map,
  1653. size = monSize)
  1654. # self.SetTopWindow(Map)
  1655. self.mapFrm.Show()
  1656. if __name__ == "__main__":
  1657. self.timer = wx.PyTimer(self.watcher)
  1658. #check each 0.5s
  1659. global mtime
  1660. mtime = 500
  1661. self.timer.Start(mtime)
  1662. return True
  1663. def OnExit(self):
  1664. if __name__ == "__main__":
  1665. # stop the timer
  1666. # self.timer.Stop()
  1667. # terminate thread
  1668. for f in monFile.itervalues():
  1669. grass.try_remove(f)
  1670. def watcher(self):
  1671. """!Redraw, if new layer appears (check's timestamp of
  1672. cmdfile)
  1673. """
  1674. # todo: events
  1675. if os.path.getmtime(monFile['cmd']) > self.cmdTimeStamp:
  1676. self.timer.Stop()
  1677. self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
  1678. self.mapFrm.OnDraw(None)
  1679. self.timer.Start(mtime)
  1680. if __name__ == "__main__":
  1681. # set command variable
  1682. if len(sys.argv) < 5:
  1683. print __doc__
  1684. sys.exit(1)
  1685. monName = sys.argv[1]
  1686. monFile = { 'map' : sys.argv[2],
  1687. 'cmd' : sys.argv[3],
  1688. 'env' : sys.argv[4],
  1689. }
  1690. if len(sys.argv) >= 6:
  1691. try:
  1692. monSize[0] = int(sys.argv[5])
  1693. except ValueError:
  1694. pass
  1695. if len(sys.argv) == 7:
  1696. try:
  1697. monSize[1] = int(sys.argv[6])
  1698. except ValueError:
  1699. pass
  1700. import gettext
  1701. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1702. grass.verbose(_("Starting map display <%s>...") % (monName))
  1703. gcmd.RunCommand('g.gisenv',
  1704. set = 'MONITOR_%s_PID=%d' % (monName, os.getpid()))
  1705. gm_map = MapApp(0)
  1706. # set title
  1707. gm_map.mapFrm.SetTitle(_("GRASS GIS Map Display: " +
  1708. monName +
  1709. " - Location: " + grass.gisenv()["LOCATION_NAME"]))
  1710. gm_map.MainLoop()
  1711. grass.verbose(_("Stopping map display <%s>...") % (monName))
  1712. # clean up GRASS env variables
  1713. env = grass.gisenv()
  1714. env_name = 'MONITOR_%s' % monName
  1715. for key in env.keys():
  1716. if key.find(env_name) == 0:
  1717. gcmd.RunCommand('g.gisenv',
  1718. set = '%s=' % key)
  1719. if key == 'MONITOR' and env[key] == monName:
  1720. gcmd.RunCommand('g.gisenv',
  1721. set = '%s=' % key)
  1722. sys.exit(0)