mapdisp.py 87 KB

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