mapdisp.py 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088
  1. """!
  2. @package mapdisp.py
  3. @brief GIS map display canvas, with toolbar for various display
  4. management functions, and additional toolbars (vector digitizer, 3d
  5. view).
  6. Can be used either from Layer Manager or as p.mon backend.
  7. Classes:
  8. - MapFrame
  9. - MapApp
  10. Usage:
  11. python mapdisp.py monitor-identifier /path/to/command/file
  12. (C) 2006-2010 by the GRASS Development Team
  13. This program is free software under the GNU General Public
  14. License (>=v2). Read the file COPYING that comes with GRASS
  15. for details.
  16. @author Michael Barton
  17. @author Jachym Cepicky
  18. @author Martin Landa <landa.martin gmail.com>
  19. """
  20. import os
  21. import sys
  22. import glob
  23. import math
  24. import tempfile
  25. import copy
  26. import globalvar
  27. if not os.getenv("GRASS_WXBUNDLED"):
  28. globalvar.CheckForWx()
  29. import wx
  30. import wx.aui
  31. try:
  32. import subprocess
  33. except:
  34. CompatPath = os.path.join(globalvar.ETCWXDIR)
  35. sys.path.append(CompatPath)
  36. from compat import subprocess
  37. gmpath = os.path.join(globalvar.ETCWXDIR, "icons")
  38. sys.path.append(gmpath)
  39. grassPath = os.path.join(globalvar.ETCDIR, "python")
  40. sys.path.append(grassPath)
  41. import render
  42. import toolbars
  43. import menuform
  44. import gselect
  45. import disp_print
  46. import gcmd
  47. import dbm
  48. import dbm_dialogs
  49. import histogram
  50. import profile
  51. import globalvar
  52. import utils
  53. import gdialogs
  54. from grass.script import core as grass
  55. from debug import Debug
  56. from icon import Icons
  57. from preferences import globalSettings as UserSettings
  58. from mapdisp_command import Command
  59. from mapdisp_window import BufferedWindow
  60. # for standalone app
  61. cmdfilename = None
  62. haveCtypes = False
  63. class MapFrame(wx.Frame):
  64. """!Main frame for map display window. Drawing takes place in
  65. child double buffered drawing window.
  66. """
  67. def __init__(self, parent = None, id = wx.ID_ANY, title = _("GRASS GIS - Map display"),
  68. style = wx.DEFAULT_FRAME_STYLE, toolbars = ["map"],
  69. tree = None, notebook = None, lmgr = None, page = None,
  70. Map = None, auimgr = None, **kwargs):
  71. """!Main map display window with toolbars, statusbar and
  72. DrawWindow
  73. @param toolbars array of activated toolbars, e.g. ['map', 'digit']
  74. @param tree reference to layer tree
  75. @param notebook control book ID in Layer Manager
  76. @param lmgr Layer Manager
  77. @param page notebook page with layer tree
  78. @param Map instance of render.Map
  79. @param auimgs AUI manager
  80. @param kwargs wx.Frame attribures
  81. """
  82. self._layerManager = lmgr # Layer Manager object
  83. self.Map = Map # instance of render.Map
  84. self.tree = tree # Layer Manager layer tree object
  85. self.page = page # Notebook page holding the layer tree
  86. self.layerbook = notebook # Layer Manager layer tree notebook
  87. self.parent = parent
  88. if 'name' not in kwargs:
  89. kwargs['name'] = 'MapWindow'
  90. wx.Frame.__init__(self, parent, id, title, style = style, **kwargs)
  91. # available cursors
  92. self.cursors = {
  93. # default: cross
  94. # "default" : wx.StockCursor(wx.CURSOR_DEFAULT),
  95. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  96. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  97. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  98. "pencil" : wx.StockCursor(wx.CURSOR_PENCIL),
  99. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  100. }
  101. #
  102. # set the size & system icon
  103. #
  104. self.SetClientSize(self.GetSize())
  105. self.iconsize = (16, 16)
  106. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  107. #
  108. # Fancy gui
  109. #
  110. # self._mgr = auimgr
  111. self._mgr = wx.aui.AuiManager(self)
  112. #
  113. # Add toolbars
  114. #
  115. self.toolbars = { 'map' : None,
  116. 'vdigit' : None,
  117. 'georect' : None,
  118. 'gcpdisp' : None,
  119. 'nviz' : None }
  120. for toolb in toolbars:
  121. self.AddToolbar(toolb)
  122. #
  123. # Add statusbar
  124. #
  125. self.statusbar = self.CreateStatusBar(number = 4, style = 0)
  126. self.statusbar.SetStatusWidths([-5, -2, -1, -1])
  127. self.statusbarWin = dict()
  128. self.statusbarWin['toggle'] = wx.Choice(self.statusbar, wx.ID_ANY,
  129. choices = globalvar.MAP_DISPLAY_STATUSBAR_MODE)
  130. self.statusbarWin['toggle'].SetSelection(UserSettings.Get(group = 'display',
  131. key = 'statusbarMode',
  132. subkey = 'selection'))
  133. self.statusbar.Bind(wx.EVT_CHOICE, self.OnToggleStatus, self.statusbarWin['toggle'])
  134. # auto-rendering checkbox
  135. self.statusbarWin['render'] = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
  136. label = _("Render"))
  137. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleRender, self.statusbarWin['render'])
  138. self.statusbarWin['render'].SetValue(UserSettings.Get(group = 'display',
  139. key = 'autoRendering',
  140. subkey = 'enabled'))
  141. self.statusbarWin['render'].SetToolTip(wx.ToolTip (_("Enable/disable auto-rendering")))
  142. # show region
  143. self.statusbarWin['region'] = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
  144. label = _("Show computational extent"))
  145. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleShowRegion, self.statusbarWin['region'])
  146. self.statusbarWin['region'].SetValue(False)
  147. self.statusbarWin['region'].Hide()
  148. self.statusbarWin['region'].SetToolTip(wx.ToolTip (_("Show/hide computational "
  149. "region extent (set with g.region). "
  150. "Display region drawn as a blue box inside the "
  151. "computational region, "
  152. "computational region inside a display region "
  153. "as a red box).")))
  154. # set resolution
  155. self.statusbarWin['resolution'] = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
  156. label = _("Constrain display resolution to computational settings"))
  157. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleResolution, self.statusbarWin['resolution'])
  158. self.statusbarWin['resolution'].SetValue(UserSettings.Get(group = 'display', key = 'compResolution', subkey = 'enabled'))
  159. self.statusbarWin['resolution'].Hide()
  160. self.statusbarWin['resolution'].SetToolTip(wx.ToolTip (_("Constrain display resolution "
  161. "to computational region settings. "
  162. "Default value for new map displays can "
  163. "be set up in 'User GUI settings' dialog.")))
  164. # map scale
  165. self.statusbarWin['mapscale'] = wx.ComboBox(parent = self.statusbar, id = wx.ID_ANY,
  166. style = wx.TE_PROCESS_ENTER,
  167. size = (150, -1))
  168. self.statusbarWin['mapscale'].SetItems(['1:1000',
  169. '1:5000',
  170. '1:10000',
  171. '1:25000',
  172. '1:50000',
  173. '1:100000',
  174. '1:1000000'])
  175. self.statusbarWin['mapscale'].Hide()
  176. self.statusbar.Bind(wx.EVT_TEXT_ENTER, self.OnChangeMapScale, self.statusbarWin['mapscale'])
  177. self.statusbar.Bind(wx.EVT_COMBOBOX, self.OnChangeMapScale, self.statusbarWin['mapscale'])
  178. # go to
  179. self.statusbarWin['goto'] = wx.TextCtrl(parent = self.statusbar, id = wx.ID_ANY,
  180. value = "", style = wx.TE_PROCESS_ENTER,
  181. size = (300, -1))
  182. self.statusbarWin['goto'].Hide()
  183. self.statusbar.Bind(wx.EVT_TEXT_ENTER, self.OnGoTo, self.statusbarWin['goto'])
  184. # projection
  185. self.statusbarWin['projection'] = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
  186. label = _("Use defined projection"))
  187. self.statusbarWin['projection'].SetValue(False)
  188. size = self.statusbarWin['projection'].GetSize()
  189. self.statusbarWin['projection'].SetMinSize((size[0] + 150, size[1]))
  190. self.statusbarWin['projection'].SetToolTip(wx.ToolTip (_("Reproject coordinates displayed "
  191. "in the statusbar. Projection can be "
  192. "defined in GUI preferences dialog "
  193. "(tab 'Display')")))
  194. self.statusbarWin['projection'].Hide()
  195. # mask
  196. self.statusbarWin['mask'] = wx.StaticText(parent = self.statusbar, id = wx.ID_ANY,
  197. label = '')
  198. self.statusbarWin['mask'].SetForegroundColour(wx.Colour(255, 0, 0))
  199. # on-render gauge
  200. self.statusbarWin['progress'] = wx.Gauge(parent = self.statusbar, id = wx.ID_ANY,
  201. range = 0, style = wx.GA_HORIZONTAL)
  202. self.statusbarWin['progress'].Hide()
  203. self.StatusbarReposition() # reposition statusbar
  204. #
  205. # Init map display (buffered DC & set default cursor)
  206. #
  207. self.MapWindow2D = BufferedWindow(self, id = wx.ID_ANY,
  208. Map = self.Map, tree = self.tree, lmgr = self._layerManager)
  209. # default is 2D display mode
  210. self.MapWindow = self.MapWindow2D
  211. self.MapWindow.SetCursor(self.cursors["default"])
  212. # used by vector digitizer
  213. self.MapWindowVDigit = None
  214. # used by Nviz (3D display mode)
  215. self.MapWindow3D = None
  216. #
  217. # initialize region values
  218. #
  219. self._initDisplay()
  220. #
  221. # Bind various events
  222. #
  223. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  224. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  225. self.Bind(render.EVT_UPDATE_PRGBAR, self.OnUpdateProgress)
  226. #
  227. # Update fancy gui style
  228. #
  229. self._mgr.AddPane(self.MapWindow, wx.aui.AuiPaneInfo().CentrePane().
  230. Dockable(False).BestSize((-1,-1)).
  231. CloseButton(False).DestroyOnClose(True).
  232. Layer(0))
  233. self._mgr.Update()
  234. #
  235. # Init print module and classes
  236. #
  237. self.printopt = disp_print.PrintOptions(self, self.MapWindow)
  238. #
  239. # Init zoom history
  240. #
  241. self.MapWindow.ZoomHistory(self.Map.region['n'],
  242. self.Map.region['s'],
  243. self.Map.region['e'],
  244. self.Map.region['w'])
  245. #
  246. # Re-use dialogs
  247. #
  248. self.dialogs = {}
  249. self.dialogs['attributes'] = None
  250. self.dialogs['category'] = None
  251. self.dialogs['barscale'] = None
  252. self.dialogs['legend'] = None
  253. self.decorationDialog = None # decoration/overlays
  254. def _addToolbarVDigit(self):
  255. """!Add vector digitizer toolbar
  256. """
  257. from vdigit import haveVDigit
  258. if not haveVDigit:
  259. from vdigit import errorMsg
  260. msg = _("Unable to start wxGUI vector digitizer.\nDo you want to start "
  261. "TCL/TK digitizer (v.digit) instead?\n\n"
  262. "Details: %s" % errorMsg)
  263. self.toolbars['map'].combo.SetValue(_("2D view"))
  264. dlg = wx.MessageDialog(parent = self,
  265. message = msg,
  266. caption=_("Vector digitizer failed"),
  267. style = wx.YES_NO | wx.CENTRE)
  268. if dlg.ShowModal() == wx.ID_YES:
  269. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetName()
  270. self._layerManager.goutput.RunCmd(['v.digit', 'map=%s' % mapName],
  271. switchPage = False)
  272. dlg.Destroy()
  273. self.toolbars['map'].combo.SetValue(_("2D view"))
  274. return
  275. if self._layerManager:
  276. log = self._layerManager.goutput
  277. else:
  278. log = None
  279. if not self.MapWindowVDigit:
  280. from mapdisp_vdigit import VDigitWindow
  281. self.MapWindowVDigit = VDigitWindow(self, id = wx.ID_ANY,
  282. Map = self.Map, tree = self.tree,
  283. lmgr = self._layerManager)
  284. self.MapWindowVDigit.Show()
  285. self.MapWindow = self.MapWindowVDigit
  286. self._mgr.DetachPane(self.MapWindow2D)
  287. self.MapWindow2D.Hide()
  288. self.toolbars['vdigit'] = toolbars.VDigitToolbar(parent = self, mapcontent = self.Map,
  289. layerTree = self.tree,
  290. log = log)
  291. self.MapWindowVDigit.SetToolbar(self.toolbars['vdigit'])
  292. self._mgr.AddPane(self.MapWindowVDigit, wx.aui.AuiPaneInfo().CentrePane().
  293. Dockable(False).BestSize((-1,-1)).
  294. CloseButton(False).DestroyOnClose(True).
  295. Layer(0))
  296. self._mgr.AddPane(self.toolbars['vdigit'],
  297. wx.aui.AuiPaneInfo().
  298. Name("vdigittoolbar").Caption(_("Vector digitizer toolbar")).
  299. ToolbarPane().Top().Row(1).
  300. LeftDockable(False).RightDockable(False).
  301. BottomDockable(False).TopDockable(True).
  302. CloseButton(False).Layer(2).
  303. BestSize((self.toolbars['vdigit'].GetSize())))
  304. # change mouse to draw digitized line
  305. self.MapWindow.mouse['box'] = "point"
  306. self.MapWindow.zoomtype = 0
  307. self.MapWindow.pen = wx.Pen(colour = 'red', width = 2, style = wx.SOLID)
  308. self.MapWindow.polypen = wx.Pen(colour = 'green', width = 2, style = wx.SOLID)
  309. def _addToolbarNviz(self):
  310. """!Add 3D view mode toolbar
  311. """
  312. import nviz
  313. # check for GLCanvas and OpenGL
  314. if not nviz.haveNviz:
  315. self.toolbars['map'].combo.SetValue (_("2D view"))
  316. wx.MessageBox(parent = self,
  317. message = _("Unable to switch to 3D display mode.\nThe Nviz python extension "
  318. "was not found or loaded properly.\n"
  319. "Switching back to 2D display mode.\n\nDetails: %s" % nviz.errorMsg),
  320. caption = _("Error"),
  321. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  322. return
  323. # add Nviz toolbar and disable 2D display mode tools
  324. self.toolbars['nviz'] = toolbars.NvizToolbar(self, self.Map)
  325. self.toolbars['map'].Enable2D(False)
  326. # update status bar
  327. self.statusbarWin['toggle'].Enable(False)
  328. # erase map window
  329. self.MapWindow.EraseMap()
  330. self._layerManager.goutput.WriteCmdLog(_("Starting 3D view mode..."))
  331. self.statusbar.SetStatusText(_("Please wait, loading data..."), 0)
  332. # create GL window & NVIZ toolbar
  333. if not self.MapWindow3D:
  334. self.MapWindow3D = nviz.GLWindow(self, id = wx.ID_ANY,
  335. Map = self.Map, tree = self.tree, lmgr = self._layerManager)
  336. self.MapWindow = self.MapWindow3D
  337. self.MapWindow.SetCursor(self.cursors["default"])
  338. # add Nviz notebookpage
  339. self._layerManager.AddNviz()
  340. self.MapWindow3D.OnPaint(None) # -> LoadData
  341. self.MapWindow3D.Show()
  342. self.MapWindow3D.UpdateView(None)
  343. else:
  344. self.MapWindow = self.MapWindow3D
  345. # add Nviz notebookpage
  346. self._layerManager.AddNviz()
  347. # switch from MapWindow to MapWindowGL
  348. # add nviz toolbar
  349. self._mgr.DetachPane(self.MapWindow2D)
  350. self.MapWindow2D.Hide()
  351. self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
  352. Dockable(False).BestSize((-1,-1)).
  353. CloseButton(False).DestroyOnClose(True).
  354. Layer(0))
  355. self._mgr.AddPane(self.toolbars['nviz'],
  356. wx.aui.AuiPaneInfo().
  357. Name("nviztoolbar").Caption(_("3D view toolbar")).
  358. ToolbarPane().Top().Row(1).
  359. LeftDockable(False).RightDockable(False).
  360. BottomDockable(False).TopDockable(True).
  361. CloseButton(False).Layer(2))
  362. self.SetStatusText("", 0)
  363. def AddToolbar(self, name):
  364. """!Add defined toolbar to the window
  365. Currently known toolbars are:
  366. - 'map' - basic map toolbar
  367. - 'vdigit' - vector digitizer
  368. - 'gcpdisp' - GCP Manager Display
  369. - 'georect' - georectifier
  370. - 'nviz' - 3D view mode
  371. """
  372. # default toolbar
  373. if name == "map":
  374. self.toolbars['map'] = toolbars.MapToolbar(self, self.Map)
  375. self._mgr.AddPane(self.toolbars['map'],
  376. wx.aui.AuiPaneInfo().
  377. Name("maptoolbar").Caption(_("Map toolbar")).
  378. ToolbarPane().Top().
  379. LeftDockable(False).RightDockable(False).
  380. BottomDockable(False).TopDockable(True).
  381. CloseButton(False).Layer(2).
  382. BestSize((self.toolbars['map'].GetSize())))
  383. # vector digitizer
  384. elif name == "vdigit":
  385. self._addToolbarVDigit()
  386. # georectifier
  387. elif name == "georect":
  388. self.toolbars['georect'] = toolbars.GRToolbar(self, self.Map)
  389. self._mgr.AddPane(self.toolbars['georect'],
  390. wx.aui.AuiPaneInfo().
  391. Name("georecttoolbar").Caption(_("Georectification toolbar")).
  392. ToolbarPane().Top().
  393. LeftDockable(False).RightDockable(False).
  394. BottomDockable(False).TopDockable(True).
  395. CloseButton(False).Layer(2))
  396. # nviz
  397. elif name == "nviz":
  398. self._addToolbarNviz()
  399. self._mgr.Update()
  400. def RemoveToolbar (self, name):
  401. """!Removes defined toolbar from the window
  402. @todo Only hide, activate by calling AddToolbar()
  403. """
  404. # cannot hide main toolbar
  405. if name == "map":
  406. return
  407. self._mgr.DetachPane(self.toolbars[name])
  408. self.toolbars[name].Destroy()
  409. self.toolbars[name] = None
  410. if name == 'vdigit':
  411. self._mgr.DetachPane(self.MapWindowVDigit)
  412. self.MapWindowVDigit.Hide()
  413. self.MapWindow2D.Show()
  414. self._mgr.AddPane(self.MapWindow2D, wx.aui.AuiPaneInfo().CentrePane().
  415. Dockable(False).BestSize((-1,-1)).
  416. CloseButton(False).DestroyOnClose(True).
  417. Layer(0))
  418. self.MapWindow = self.MapWindow2D
  419. elif name == 'nviz':
  420. # unload data
  421. # self.MapWindow3D.Reset()
  422. # switch from MapWindowGL to MapWindow
  423. self._mgr.DetachPane(self.MapWindow3D)
  424. self.MapWindow3D.Hide()
  425. self.MapWindow2D.Show()
  426. self._mgr.AddPane(self.MapWindow2D, wx.aui.AuiPaneInfo().CentrePane().
  427. Dockable(False).BestSize((-1,-1)).
  428. CloseButton(False).DestroyOnClose(True).
  429. Layer(0))
  430. self.MapWindow = self.MapWindow2D
  431. # remove nviz notebook page
  432. self._layerManager.RemoveNviz()
  433. self.MapWindow.UpdateMap()
  434. self.toolbars['map'].combo.SetValue(_("2D view"))
  435. self.toolbars['map'].Enable2D(True)
  436. self.statusbarWin['toggle'].Enable(True)
  437. self._mgr.Update()
  438. def _initDisplay(self):
  439. """!Initialize map display, set dimensions and map region
  440. """
  441. if not grass.find_program('g.region', ['--help']):
  442. sys.exit(_("GRASS module '%s' not found. Unable to start map "
  443. "display window.") % 'g.region')
  444. self.width, self.height = self.GetClientSize()
  445. Debug.msg(2, "MapFrame._initDisplay():")
  446. self.Map.ChangeMapSize(self.GetClientSize())
  447. self.Map.region = self.Map.GetRegion() # g.region -upgc
  448. # self.Map.SetRegion() # adjust region to match display window
  449. def OnUpdateProgress(self, event):
  450. """!Update progress bar info
  451. """
  452. self.statusbarWin['progress'].SetValue(event.value)
  453. event.Skip()
  454. def OnFocus(self, event):
  455. """
  456. Change choicebook page to match display.
  457. Or set display for georectifying
  458. """
  459. if self._layerManager and \
  460. self._layerManager.georectifying:
  461. # in georectifying session; display used to get geographic
  462. # coordinates for GCPs
  463. self.OnPointer(event)
  464. else:
  465. # change bookcontrol page to page associated with display
  466. if self.page:
  467. pgnum = self.layerbook.GetPageIndex(self.page)
  468. if pgnum > -1:
  469. self.layerbook.SetSelection(pgnum)
  470. event.Skip()
  471. def OnDraw(self, event):
  472. """!Re-display current map composition
  473. """
  474. self.MapWindow.UpdateMap(render = False)
  475. def OnRender(self, event):
  476. """!Re-render map composition (each map layer)
  477. """
  478. # delete tmp map layers (queries)
  479. qlayer = self.Map.GetListOfLayers(l_name = globalvar.QUERYLAYER)
  480. for layer in qlayer:
  481. self.Map.DeleteLayer(layer)
  482. # delete tmp lines
  483. if self.MapWindow.mouse["use"] in ("measure",
  484. "profile"):
  485. self.MapWindow.polycoords = []
  486. self.MapWindow.ClearLines()
  487. # deselect features in vdigit
  488. if self.toolbars['vdigit']:
  489. self.MapWindow.display.SetSelected([])
  490. self.MapWindow.UpdateMap(render = True, renderVector = True)
  491. else:
  492. self.MapWindow.UpdateMap(render = True)
  493. # update statusbar
  494. self.StatusbarUpdate()
  495. def OnPointer(self, event):
  496. """!Pointer button clicked
  497. """
  498. if self.toolbars['map']:
  499. if event:
  500. self.toolbars['map'].OnTool(event)
  501. self.toolbars['map'].action['desc'] = ''
  502. self.MapWindow.mouse['use'] = "pointer"
  503. self.MapWindow.mouse['box'] = "point"
  504. # change the cursor
  505. if self.toolbars['vdigit']:
  506. # digitization tool activated
  507. self.MapWindow.SetCursor(self.cursors["cross"])
  508. # reset mouse['box'] if needed
  509. if self.toolbars['vdigit'].GetAction() in ['addLine']:
  510. if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
  511. self.MapWindow.mouse['box'] = 'point'
  512. else: # line, boundary
  513. self.MapWindow.mouse['box'] = 'line'
  514. elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
  515. 'editLine', 'displayCats', 'displayAttrs',
  516. 'copyCats']:
  517. self.MapWindow.mouse['box'] = 'point'
  518. else: # moveLine, deleteLine
  519. self.MapWindow.mouse['box'] = 'box'
  520. elif self._layerManager and self._layerManager.georectifying:
  521. self.MapWindow.SetCursor(self.cursors["cross"])
  522. else:
  523. self.MapWindow.SetCursor(self.cursors["default"])
  524. def OnZoomIn(self, event):
  525. """
  526. Zoom in the map.
  527. Set mouse cursor, zoombox attributes, and zoom direction
  528. """
  529. if self.toolbars['map']:
  530. self.toolbars['map'].OnTool(event)
  531. self.toolbars['map'].action['desc'] = ''
  532. self.MapWindow.mouse['use'] = "zoom"
  533. self.MapWindow.mouse['box'] = "box"
  534. self.MapWindow.zoomtype = 1
  535. self.MapWindow.pen = wx.Pen(colour = 'Red', width = 2, style = wx.SHORT_DASH)
  536. # change the cursor
  537. self.MapWindow.SetCursor(self.cursors["cross"])
  538. def OnZoomOut(self, event):
  539. """
  540. Zoom out the map.
  541. Set mouse cursor, zoombox attributes, and zoom direction
  542. """
  543. if self.toolbars['map']:
  544. self.toolbars['map'].OnTool(event)
  545. self.toolbars['map'].action['desc'] = ''
  546. self.MapWindow.mouse['use'] = "zoom"
  547. self.MapWindow.mouse['box'] = "box"
  548. self.MapWindow.zoomtype = -1
  549. self.MapWindow.pen = wx.Pen(colour = 'Red', width = 2, style = wx.SHORT_DASH)
  550. # change the cursor
  551. self.MapWindow.SetCursor(self.cursors["cross"])
  552. def OnZoomBack(self, event):
  553. """
  554. Zoom last (previously stored position)
  555. """
  556. self.MapWindow.ZoomBack()
  557. def OnPan(self, event):
  558. """
  559. Panning, set mouse to drag
  560. """
  561. if self.toolbars['map']:
  562. self.toolbars['map'].OnTool(event)
  563. self.toolbars['map'].action['desc'] = ''
  564. self.MapWindow.mouse['use'] = "pan"
  565. self.MapWindow.mouse['box'] = "pan"
  566. self.MapWindow.zoomtype = 0
  567. # change the cursor
  568. self.MapWindow.SetCursor(self.cursors["hand"])
  569. def OnErase(self, event):
  570. """
  571. Erase the canvas
  572. """
  573. self.MapWindow.EraseMap()
  574. def OnZoomRegion(self, event):
  575. """
  576. Zoom to region
  577. """
  578. self.Map.getRegion()
  579. self.Map.getResolution()
  580. self.UpdateMap()
  581. # event.Skip()
  582. def OnAlignRegion(self, event):
  583. """
  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 _OnQuery(self):
  1053. """!Internal method used by OnQuery*() methods"""
  1054. if self.toolbars['map'].GetAction() == 'displayAttrb':
  1055. # switch to output console to show query results
  1056. self._layerManager.notebook.SetSelection(1)
  1057. self.MapWindow.mouse['box'] = "point"
  1058. self.MapWindow.zoomtype = 0
  1059. # change the cursor
  1060. self.MapWindow.SetCursor(self.cursors["cross"])
  1061. def OnQueryDisplay(self, event):
  1062. """!Query currrent raster/vector map layers (display mode) -
  1063. 2D view mode
  1064. """
  1065. if self.toolbars['map'].GetAction() == 'displayAttrb': # select previous action
  1066. self.toolbars['map'].SelectDefault(event)
  1067. return
  1068. self.toolbars['map'].action['desc'] = 'displayAttrb'
  1069. self.MapWindow.mouse['use'] = "query"
  1070. self._OnQuery()
  1071. def OnQueryModify(self, event):
  1072. """!Query vector map layer (edit mode) - 2D view mode
  1073. """
  1074. if self.toolbars['map'].GetAction() == 'modifyAttrb': # select previous action
  1075. self.toolbars['map'].SelectDefault(event)
  1076. return
  1077. self.toolbars['map'].action['desc'] = 'modifyAttrb'
  1078. self.MapWindow.mouse['use'] = "queryVector"
  1079. self.MapWindow.pen = wx.Pen(colour = 'Red', width = 2, style = wx.SHORT_DASH)
  1080. self._OnQuery()
  1081. def OnNvizQuerySurface(self, event):
  1082. """!Query current surface in 3D view mode"""
  1083. if self.toolbars['map'].GetAction() == 'nvizQuerySurface':
  1084. self.toolbars['map'].SelectDefault(event)
  1085. return
  1086. self.toolbars['map'].action['desc'] = 'nvizQuerySurface'
  1087. self.MapWindow.mouse['use'] = "nvizQuerySurface"
  1088. self._OnQuery()
  1089. def OnNvizQueryVector(self, event):
  1090. """!Query current vector in 3D view mode"""
  1091. if self.toolbars['map'].GetAction() == 'nvizQueryVector':
  1092. self.toolbars['map'].SelectDefault(event)
  1093. return
  1094. self.toolbars['map'].action['desc'] = 'nvizQueryVector'
  1095. self.MapWindow.mouse['use'] = "nvizQueryVector"
  1096. self._OnQuery()
  1097. def QueryMap(self, x, y):
  1098. """!Query map layer features
  1099. Currently only raster and vector map layers are supported.
  1100. @param x,y coordinates
  1101. """
  1102. #set query snap distance for v.what at mapunit equivalent of 10 pixels
  1103. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  1104. east, north = self.MapWindow.Pixel2Cell((x, y))
  1105. num = 0
  1106. for layer in self.tree.GetSelections():
  1107. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  1108. if type in ('raster', 'rgb', 'his',
  1109. 'vector', 'thememap', 'themechart'):
  1110. num += 1
  1111. if num < 1:
  1112. dlg = wx.MessageDialog(parent = self,
  1113. message = _('No raster or vector map layer selected for querying.'),
  1114. caption = _('No map layer selected'),
  1115. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1116. dlg.ShowModal()
  1117. dlg.Destroy()
  1118. return
  1119. mapname = None
  1120. raststr = ''
  1121. vectstr = ''
  1122. rcmd = ['r.what', '--v']
  1123. vcmd = ['v.what', '--v']
  1124. for layer in self.tree.GetSelections():
  1125. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  1126. dcmd = self.tree.GetPyData(layer)[0]['cmd']
  1127. name, found = utils.GetLayerNameFromCmd(dcmd)
  1128. if not found:
  1129. continue
  1130. if type in ('raster', 'rgb', 'his'):
  1131. raststr += "%s," % name
  1132. elif type in ('vector', 'thememap', 'themechart'):
  1133. vectstr += "%s," % name
  1134. # use display region settings instead of computation region settings
  1135. self.tmpreg = os.getenv("GRASS_REGION")
  1136. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres = False)
  1137. # build query commands for any selected rasters and vectors
  1138. if raststr != '':
  1139. rcmd.append('-f')
  1140. rcmd.append('input=%s' % raststr.rstrip(','))
  1141. rcmd.append('east_north=%f,%f' % (float(east), float(north)))
  1142. if vectstr != '':
  1143. # check for vector maps open to be edited
  1144. digitToolbar = self.toolbars['vdigit']
  1145. if digitToolbar:
  1146. map = digitToolbar.GetLayer().GetName()
  1147. vect = []
  1148. for vector in vectstr.split(','):
  1149. if map == vector:
  1150. self._layerManager.goutput.WriteWarning("Vector map <%s> "
  1151. "opened for editing - skipped." % map)
  1152. continue
  1153. vect.append(vector)
  1154. vectstr = ','.join(vect)
  1155. if len(vectstr) <= 1:
  1156. self._layerManager.goutput.WriteCmdLog("Nothing to query.")
  1157. return
  1158. vcmd.append('-a')
  1159. vcmd.append('map=%s' % vectstr.rstrip(','))
  1160. vcmd.append('east_north=%f,%f' % (float(east), float(north)))
  1161. vcmd.append('distance=%f' % float(qdist))
  1162. # parse query command(s)
  1163. if self._layerManager:
  1164. if raststr:
  1165. self._layerManager.goutput.RunCmd(rcmd,
  1166. compReg = False,
  1167. onDone = self._QueryMapDone)
  1168. if vectstr:
  1169. self._layerManager.goutput.RunCmd(vcmd,
  1170. onDone = self._QueryMapDone)
  1171. else:
  1172. if raststr:
  1173. gcmd.RunCommand(rcmd)
  1174. if vectstr:
  1175. gcmd.RunCommand(vcmd)
  1176. def _QueryMapDone(self, cmd, returncode):
  1177. """!Restore settings after querying (restore GRASS_REGION)
  1178. @param returncode command return code
  1179. """
  1180. if hasattr(self, "tmpreg"):
  1181. if self.tmpreg:
  1182. os.environ["GRASS_REGION"] = self.tmpreg
  1183. elif 'GRASS_REGION' in os.environ:
  1184. del os.environ["GRASS_REGION"]
  1185. elif 'GRASS_REGION' in os.environ:
  1186. del os.environ["GRASS_REGION"]
  1187. if hasattr(self, "tmpreg"):
  1188. del self.tmpreg
  1189. def QueryVector(self, x, y):
  1190. """!Query vector map layer features
  1191. Attribute data of selected vector object are displayed in GUI dialog.
  1192. Data can be modified (On Submit)
  1193. """
  1194. if not self.tree.layer_selected or \
  1195. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] != 'vector':
  1196. wx.MessageBox(parent = self,
  1197. message = _("No vector map selected for querying."),
  1198. caption = _("Vector querying"),
  1199. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1200. return
  1201. if self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetMapset() != \
  1202. grass.gisenv()['MAPSET']:
  1203. wx.MessageBox(parent = self,
  1204. message = _("Only vector map from the current mapset can be modified."),
  1205. caption = _("Vector querying"),
  1206. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1207. return
  1208. posWindow = self.ClientToScreen((x + self.MapWindow.dialogOffset,
  1209. y + self.MapWindow.dialogOffset))
  1210. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) /
  1211. self.Map.width)
  1212. east, north = self.MapWindow.Pixel2Cell((x, y))
  1213. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name
  1214. if self.dialogs['attributes'] is None:
  1215. self.dialogs['attributes'] = \
  1216. dbm_dialogs.DisplayAttributesDialog(parent = self.MapWindow,
  1217. map = mapName,
  1218. query = ((east, north), qdist),
  1219. pos = posWindow,
  1220. action = "update")
  1221. else:
  1222. # selection changed?
  1223. if not self.dialogs['attributes'].mapDBInfo or \
  1224. self.dialogs['attributes'].mapDBInfo.map != mapName:
  1225. self.dialogs['attributes'].UpdateDialog(map = mapName, query = ((east, north), qdist))
  1226. else:
  1227. self.dialogs['attributes'].UpdateDialog(query = ((east, north), qdist))
  1228. cats = self.dialogs['attributes'].GetCats()
  1229. try:
  1230. qlayer = self.Map.GetListOfLayers(l_name = globalvar.QUERYLAYER)[0]
  1231. except IndexError:
  1232. qlayer = None
  1233. if self.dialogs['attributes'].mapDBInfo and cats:
  1234. # highlight feature & re-draw map
  1235. if qlayer:
  1236. qlayer.SetCmd(self.AddTmpVectorMapLayer(mapName, cats,
  1237. useId = False,
  1238. addLayer = False))
  1239. else:
  1240. qlayer = self.AddTmpVectorMapLayer(mapName, cats, useId = False)
  1241. # set opacity based on queried layer
  1242. opacity = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetOpacity(float = True)
  1243. qlayer.SetOpacity(opacity)
  1244. self.MapWindow.UpdateMap(render = False, renderVector = False)
  1245. if not self.dialogs['attributes'].IsShown():
  1246. self.dialogs['attributes'].Show()
  1247. else:
  1248. if qlayer:
  1249. self.Map.DeleteLayer(qlayer)
  1250. self.MapWindow.UpdateMap(render = False, renderVector = False)
  1251. if self.dialogs['attributes'].IsShown():
  1252. self.dialogs['attributes'].Hide()
  1253. def OnQuery(self, event):
  1254. """!Query tools menu"""
  1255. if self.toolbars['map']:
  1256. self.toolbars['map'].OnTool(event)
  1257. action = self.toolbars['map'].GetAction()
  1258. point = wx.GetMousePosition()
  1259. toolsmenu = wx.Menu()
  1260. # add items to the menu
  1261. if self.toolbars['nviz']:
  1262. raster = wx.MenuItem(parentMenu = toolsmenu, id = wx.ID_ANY,
  1263. text = _("Query surface (raster map)"),
  1264. kind = wx.ITEM_CHECK)
  1265. toolsmenu.AppendItem(raster)
  1266. self.Bind(wx.EVT_MENU, self.OnNvizQuerySurface, raster)
  1267. if action == "nvizQuerySurface":
  1268. raster.Check(True)
  1269. vector = wx.MenuItem(parentMenu = toolsmenu, id = wx.ID_ANY,
  1270. text = _("Query vector map"),
  1271. kind = wx.ITEM_CHECK)
  1272. toolsmenu.AppendItem(vector)
  1273. self.Bind(wx.EVT_MENU, self.OnNvizQueryVector, vector)
  1274. if action == "nvizQueryVector":
  1275. vector.Check(True)
  1276. else:
  1277. display = wx.MenuItem(parentMenu = toolsmenu, id = wx.ID_ANY,
  1278. text = _("Query raster/vector map(s) (display mode)"),
  1279. kind = wx.ITEM_CHECK)
  1280. toolsmenu.AppendItem(display)
  1281. self.Bind(wx.EVT_MENU, self.OnQueryDisplay, display)
  1282. numLayers = 0
  1283. for layer in self.tree.GetSelections():
  1284. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  1285. if type in ('raster', 'rgb', 'his',
  1286. 'vector', 'thememap', 'themechart'):
  1287. numLayers += 1
  1288. if numLayers < 1:
  1289. display.Enable(False)
  1290. if action == "displayAttrb":
  1291. display.Check(True)
  1292. modify = wx.MenuItem(parentMenu = toolsmenu, id = wx.ID_ANY,
  1293. text = _("Query vector map (edit mode)"),
  1294. kind = wx.ITEM_CHECK)
  1295. toolsmenu.AppendItem(modify)
  1296. self.Bind(wx.EVT_MENU, self.OnQueryModify, modify)
  1297. modify.Enable(False)
  1298. if action == "modifyAttrb":
  1299. modify.Check(True)
  1300. digitToolbar = self.toolbars['vdigit']
  1301. if self.tree.layer_selected:
  1302. mapLayer = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer']
  1303. if mapLayer.GetType() == 'vector' and \
  1304. mapLayer.GetMapset() == grass.gisenv()['MAPSET'] and \
  1305. (not digitToolbar or (digitToolbar and \
  1306. digitToolbar.GetLayer() != mapLayer)):
  1307. modify.Enable(True)
  1308. else:
  1309. if action == "modifyAttrb":
  1310. modify.Check(True)
  1311. self.PopupMenu(toolsmenu)
  1312. toolsmenu.Destroy()
  1313. def AddTmpVectorMapLayer(self, name, cats, useId = False, addLayer = True):
  1314. """!Add temporal vector map layer to map composition
  1315. @param name name of map layer
  1316. @param useId use feature id instead of category
  1317. """
  1318. # color settings from ATM
  1319. color = UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'color')
  1320. colorStr = str(color[0]) + ":" + \
  1321. str(color[1]) + ":" + \
  1322. str(color[2])
  1323. # icon used in vector display and its size
  1324. icon = ''
  1325. size = 0
  1326. vparam = self.tree.GetPyData(self.tree.layer_selected)[0]['cmd']
  1327. for p in vparam:
  1328. if '=' in p:
  1329. parg,pval = p.split('=')
  1330. if parg == 'icon': icon = pval
  1331. elif parg == 'size': size = int(pval)
  1332. pattern = ["d.vect",
  1333. "map=%s" % name,
  1334. "color=%s" % colorStr,
  1335. "fcolor=%s" % colorStr,
  1336. "width=%d" % UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'width')]
  1337. if icon != '':
  1338. pattern.append('icon=%s' % icon)
  1339. if size > 0:
  1340. pattern.append('size=%i' % size)
  1341. if useId:
  1342. cmd = pattern
  1343. cmd.append('-i')
  1344. cmd.append('cats=%s' % str(cats))
  1345. else:
  1346. cmd = []
  1347. for layer in cats.keys():
  1348. cmd.append(copy.copy(pattern))
  1349. lcats = cats[layer]
  1350. cmd[-1].append("layer=%d" % layer)
  1351. cmd[-1].append("cats=%s" % utils.ListOfCatsToRange(lcats))
  1352. if addLayer:
  1353. if useId:
  1354. return self.Map.AddLayer(type = 'vector', name = globalvar.QUERYLAYER, command = cmd,
  1355. l_active = True, l_hidden = True, l_opacity = 1.0)
  1356. else:
  1357. return self.Map.AddLayer(type = 'command', name = globalvar.QUERYLAYER, command = cmd,
  1358. l_active = True, l_hidden = True, l_opacity = 1.0)
  1359. else:
  1360. return cmd
  1361. def OnAnalyze(self, event):
  1362. """!Analysis tools menu
  1363. """
  1364. point = wx.GetMousePosition()
  1365. toolsmenu = wx.Menu()
  1366. icons = Icons['displayWindow']
  1367. # Add items to the menu
  1368. measure = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["measure"].GetLabel())
  1369. measure.SetBitmap(icons["measure"].GetBitmap(self.iconsize))
  1370. toolsmenu.AppendItem(measure)
  1371. self.Bind(wx.EVT_MENU, self.OnMeasure, measure)
  1372. profile = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["profile"].GetLabel())
  1373. profile.SetBitmap(icons["profile"].GetBitmap(self.iconsize))
  1374. toolsmenu.AppendItem(profile)
  1375. self.Bind(wx.EVT_MENU, self.Profile, profile)
  1376. histogram = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["histogram"].GetLabel())
  1377. histogram.SetBitmap(icons["histogram"].GetBitmap(self.iconsize))
  1378. toolsmenu.AppendItem(histogram)
  1379. self.Bind(wx.EVT_MENU, self.Histogram, histogram)
  1380. # Popup the menu. If an item is selected then its handler
  1381. # will be called before PopupMenu returns.
  1382. self.PopupMenu(toolsmenu)
  1383. toolsmenu.Destroy()
  1384. def OnMeasure(self, event):
  1385. """!Init measurement routine that calculates map distance
  1386. along transect drawn on map display
  1387. """
  1388. self.totaldist = 0.0 # total measured distance
  1389. # switch Layer Manager to output console to show measure results
  1390. self._layerManager.notebook.SetSelection(1)
  1391. # change mouse to draw line for measurement
  1392. self.MapWindow.mouse['use'] = "measure"
  1393. self.MapWindow.mouse['box'] = "line"
  1394. self.MapWindow.zoomtype = 0
  1395. self.MapWindow.pen = wx.Pen(colour = 'red', width = 2, style = wx.SHORT_DASH)
  1396. self.MapWindow.polypen = wx.Pen(colour = 'green', width = 2, style = wx.SHORT_DASH)
  1397. # change the cursor
  1398. self.MapWindow.SetCursor(self.cursors["pencil"])
  1399. # initiating output
  1400. style = self._layerManager.goutput.cmd_output.StyleWarning
  1401. self._layerManager.goutput.WriteLog(_('Click and drag with left mouse button '
  1402. 'to measure.%s'
  1403. 'Double click with left button to clear.') % \
  1404. (os.linesep), style)
  1405. if self.Map.projinfo['proj'] != 'xy':
  1406. units = self.Map.projinfo['units']
  1407. self._layerManager.goutput.WriteCmdLog(_('Measuring distance') + ' ('
  1408. + units + '):')
  1409. else:
  1410. self._layerManager.goutput.WriteCmdLog(_('Measuring distance:'))
  1411. if self.Map.projinfo['proj'] == 'll':
  1412. try:
  1413. import grass.lib.gis as gislib
  1414. global haveCtypes
  1415. haveCtypes = True
  1416. gislib.G_begin_distance_calculations()
  1417. except ImportError, e:
  1418. self._layerManager.goutput.WriteWarning(_('Geodesic distance is not yet '
  1419. 'supported by this tool.\n'
  1420. 'Reason: %s' % e))
  1421. def MeasureDist(self, beginpt, endpt):
  1422. """!Calculate map distance from screen distance
  1423. and print to output window
  1424. """
  1425. if self._layerManager.notebook.GetSelection() != 1:
  1426. self._layerManager.notebook.SetSelection(1)
  1427. dist, (north, east) = self.MapWindow.Distance(beginpt, endpt)
  1428. dist = round(dist, 3)
  1429. d, dunits = self.FormatDist(dist)
  1430. self.totaldist += dist
  1431. td, tdunits = self.FormatDist(self.totaldist)
  1432. strdist = str(d)
  1433. strtotdist = str(td)
  1434. if self.Map.projinfo['proj'] == 'xy' or 'degree' not in self.Map.projinfo['unit']:
  1435. angle = int(math.degrees(math.atan2(north,east)) + 0.5)
  1436. angle = 180 - angle
  1437. if angle < 0:
  1438. angle = 360 + angle
  1439. mstring = '%s = %s %s\n%s = %s %s\n%s = %d %s\n%s' \
  1440. % (_('segment'), strdist, dunits,
  1441. _('total distance'), strtotdist, tdunits,
  1442. _('bearing'), angle, _('deg'),
  1443. '-' * 60)
  1444. else:
  1445. mstring = '%s = %s %s\n%s = %s %s\n%s' \
  1446. % (_('segment'), strdist, dunits,
  1447. _('total distance'), strtotdist, tdunits,
  1448. '-' * 60)
  1449. self._layerManager.goutput.WriteLog(mstring)
  1450. return dist
  1451. def Profile(self, event):
  1452. """!Init profile canvas and tools
  1453. """
  1454. raster = []
  1455. if self.tree.layer_selected and \
  1456. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1457. raster.append(self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1458. self.profile = profile.ProfileFrame(self,
  1459. id = wx.ID_ANY, pos = wx.DefaultPosition, size = (700,300),
  1460. style = wx.DEFAULT_FRAME_STYLE, rasterList = raster)
  1461. self.profile.Show()
  1462. # Open raster select dialog to make sure that a raster (and the desired raster)
  1463. # is selected to be profiled
  1464. self.profile.OnSelectRaster(None)
  1465. def FormatDist(self, dist):
  1466. """!Format length numbers and units in a nice way,
  1467. as a function of length. From code by Hamish Bowman
  1468. Grass Development Team 2006"""
  1469. mapunits = self.Map.projinfo['units']
  1470. if mapunits == 'metres':
  1471. mapunits = 'meters'
  1472. outunits = mapunits
  1473. dist = float(dist)
  1474. divisor = 1.0
  1475. # figure out which units to use
  1476. if mapunits == 'meters':
  1477. if dist > 2500.0:
  1478. outunits = 'km'
  1479. divisor = 1000.0
  1480. else: outunits = 'm'
  1481. elif mapunits == 'feet':
  1482. # nano-bug: we match any "feet", but US Survey feet is really
  1483. # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
  1484. # miles the tick markers are rounded to the nearest 10th of a
  1485. # mile (528'), the difference in foot flavours is ignored.
  1486. if dist > 5280.0:
  1487. outunits = 'miles'
  1488. divisor = 5280.0
  1489. else:
  1490. outunits = 'ft'
  1491. elif 'degree' in mapunits and \
  1492. not haveCtypes:
  1493. if dist < 1:
  1494. outunits = 'min'
  1495. divisor = (1/60.0)
  1496. else:
  1497. outunits = 'deg'
  1498. else:
  1499. outunits = 'meters'
  1500. # format numbers in a nice way
  1501. if (dist/divisor) >= 2500.0:
  1502. outdist = round(dist/divisor)
  1503. elif (dist/divisor) >= 1000.0:
  1504. outdist = round(dist/divisor,1)
  1505. elif (dist/divisor) > 0.0:
  1506. outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
  1507. else:
  1508. outdist = float(dist/divisor)
  1509. return (outdist, outunits)
  1510. def Histogram(self, event):
  1511. """!Init histogram display canvas and tools
  1512. """
  1513. self.histogram = histogram.HistFrame(self,
  1514. id = wx.ID_ANY, size = globalvar.HIST_WINDOW_SIZE,
  1515. style = wx.DEFAULT_FRAME_STYLE)
  1516. #show new display
  1517. self.histogram.Show()
  1518. self.histogram.Refresh()
  1519. self.histogram.Update()
  1520. def OnDecoration(self, event):
  1521. """!Decorations overlay menu
  1522. """
  1523. point = wx.GetMousePosition()
  1524. decmenu = wx.Menu()
  1525. icons = Icons['displayWindow']
  1526. # Add items to the menu
  1527. AddScale = wx.MenuItem(decmenu, wx.ID_ANY, icons["addBarscale"].GetLabel())
  1528. AddScale.SetBitmap(icons["addBarscale"].GetBitmap(self.iconsize))
  1529. decmenu.AppendItem(AddScale)
  1530. self.Bind(wx.EVT_MENU, self.OnAddBarscale, AddScale)
  1531. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, icons["addLegend"].GetLabel())
  1532. AddLegend.SetBitmap(icons["addLegend"].GetBitmap(self.iconsize))
  1533. decmenu.AppendItem(AddLegend)
  1534. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  1535. AddText = wx.MenuItem(decmenu, wx.ID_ANY, icons["addText"].GetLabel())
  1536. AddText.SetBitmap(icons["addText"].GetBitmap(self.iconsize))
  1537. decmenu.AppendItem(AddText)
  1538. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  1539. # Popup the menu. If an item is selected then its handler
  1540. # will be called before PopupMenu returns.
  1541. self.PopupMenu(decmenu)
  1542. decmenu.Destroy()
  1543. def OnAddBarscale(self, event):
  1544. """!Handler for scale/arrow map decoration menu selection.
  1545. """
  1546. if self.dialogs['barscale']:
  1547. return
  1548. id = 0 # unique index for overlay layer
  1549. # If location is latlon, only display north arrow (scale won't work)
  1550. # proj = self.Map.projinfo['proj']
  1551. # if proj == 'll':
  1552. # barcmd = 'd.barscale -n'
  1553. # else:
  1554. # barcmd = 'd.barscale'
  1555. # decoration overlay control dialog
  1556. self.dialogs['barscale'] = \
  1557. gdialogs.DecorationDialog(parent = self, title = _('Scale and North arrow'),
  1558. size = (350, 200),
  1559. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1560. cmd = ['d.barscale', 'at=0,95'],
  1561. ovlId = id,
  1562. name = 'barscale',
  1563. checktxt = _("Show/hide scale and North arrow"),
  1564. ctrltxt = _("scale object"))
  1565. self.dialogs['barscale'].CentreOnParent()
  1566. ### dialog cannot be show as modal - in the result d.barscale is not selectable
  1567. ### self.dialogs['barscale'].ShowModal()
  1568. self.dialogs['barscale'].Show()
  1569. self.MapWindow.mouse['use'] = 'pointer'
  1570. def OnAddLegend(self, event):
  1571. """!Handler for legend map decoration menu selection.
  1572. """
  1573. if self.dialogs['legend']:
  1574. return
  1575. id = 1 # index for overlay layer in render
  1576. cmd = ['d.legend', 'at=5,50,2,5']
  1577. if self.tree.layer_selected and \
  1578. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1579. cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1580. # Decoration overlay control dialog
  1581. self.dialogs['legend'] = \
  1582. gdialogs.DecorationDialog(parent = self, title = ('Legend'),
  1583. size = (350, 200),
  1584. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1585. cmd = cmd,
  1586. ovlId = id,
  1587. name = 'legend',
  1588. checktxt = _("Show/hide legend"),
  1589. ctrltxt = _("legend object"))
  1590. self.dialogs['legend'].CentreOnParent()
  1591. ### dialog cannot be show as modal - in the result d.legend is not selectable
  1592. ### self.dialogs['legend'].ShowModal()
  1593. self.dialogs['legend'].Show()
  1594. self.MapWindow.mouse['use'] = 'pointer'
  1595. def OnAddText(self, event):
  1596. """!Handler for text decoration menu selection.
  1597. """
  1598. if self.MapWindow.dragid > -1:
  1599. id = self.MapWindow.dragid
  1600. else:
  1601. # index for overlay layer in render
  1602. if len(self.MapWindow.textdict.keys()) > 0:
  1603. id = self.MapWindow.textdict.keys()[-1] + 1
  1604. else:
  1605. id = 101
  1606. self.dialogs['text'] = gdialogs.TextLayerDialog(parent = self, ovlId = id,
  1607. title = _('Add text layer'),
  1608. size = (400, 200))
  1609. self.dialogs['text'].CenterOnParent()
  1610. # If OK button pressed in decoration control dialog
  1611. if self.dialogs['text'].ShowModal() == wx.ID_OK:
  1612. text = self.dialogs['text'].GetValues()['text']
  1613. active = self.dialogs['text'].GetValues()['active']
  1614. coords, w, h = self.MapWindow.TextBounds(self.dialogs['text'].GetValues())
  1615. # delete object if it has no text or is not active
  1616. if text == '' or active == False:
  1617. try:
  1618. self.MapWindow.pdc.ClearId(id)
  1619. self.MapWindow.pdc.RemoveId(id)
  1620. del self.MapWindow.textdict[id]
  1621. except:
  1622. pass
  1623. return
  1624. self.MapWindow.pdc.ClearId(id)
  1625. self.MapWindow.pdc.SetId(id)
  1626. self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
  1627. self.MapWindow.Draw(self.MapWindow.pdcDec, img = self.MapWindow.textdict[id],
  1628. drawid = id, pdctype = 'text', coords = coords)
  1629. self.MapWindow.UpdateMap(render = False, renderVector = False)
  1630. self.MapWindow.mouse['use'] = 'pointer'
  1631. def GetOptData(self, dcmd, type, params, propwin):
  1632. """!Callback method for decoration overlay command generated by
  1633. dialog created in menuform.py
  1634. """
  1635. # Reset comand and rendering options in render.Map. Always render decoration.
  1636. # Showing/hiding handled by PseudoDC
  1637. self.Map.ChangeOverlay(ovltype = type, type = 'overlay', name = '', command = dcmd,
  1638. l_active = True, l_render = False)
  1639. self.params[type] = params
  1640. self.propwin[type] = propwin
  1641. def OnZoomToMap(self, event):
  1642. """!Set display extents to match selected raster (including
  1643. NULLs) or vector map.
  1644. """
  1645. self.MapWindow.ZoomToMap()
  1646. def OnZoomToRaster(self, event):
  1647. """!Set display extents to match selected raster map (ignore NULLs)
  1648. """
  1649. self.MapWindow.ZoomToMap(ignoreNulls = True)
  1650. def OnZoomToWind(self, event):
  1651. """!Set display geometry to match computational region
  1652. settings (set with g.region)
  1653. """
  1654. self.MapWindow.ZoomToWind()
  1655. def OnZoomToDefault(self, event):
  1656. """!Set display geometry to match default region settings
  1657. """
  1658. self.MapWindow.ZoomToDefault()
  1659. def OnZoomToSaved(self, event):
  1660. """!Set display geometry to match extents in
  1661. saved region file
  1662. """
  1663. self.MapWindow.ZoomToSaved()
  1664. def OnDisplayToWind(self, event):
  1665. """!Set computational region (WIND file) to match display
  1666. extents
  1667. """
  1668. self.MapWindow.DisplayToWind()
  1669. def SaveDisplayRegion(self, event):
  1670. """!Save display extents to named region file.
  1671. """
  1672. self.MapWindow.SaveDisplayRegion()
  1673. def OnZoomMenu(self, event):
  1674. """!Popup Zoom menu
  1675. """
  1676. point = wx.GetMousePosition()
  1677. zoommenu = wx.Menu()
  1678. # Add items to the menu
  1679. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region'))
  1680. zoommenu.AppendItem(zoomwind)
  1681. self.Bind(wx.EVT_MENU, self.OnZoomToWind, zoomwind)
  1682. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  1683. zoommenu.AppendItem(zoomdefault)
  1684. self.Bind(wx.EVT_MENU, self.OnZoomToDefault, zoomdefault)
  1685. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  1686. zoommenu.AppendItem(zoomsaved)
  1687. self.Bind(wx.EVT_MENU, self.OnZoomToSaved, zoomsaved)
  1688. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display'))
  1689. zoommenu.AppendItem(savewind)
  1690. self.Bind(wx.EVT_MENU, self.OnDisplayToWind, savewind)
  1691. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  1692. zoommenu.AppendItem(savezoom)
  1693. self.Bind(wx.EVT_MENU, self.SaveDisplayRegion, savezoom)
  1694. # Popup the menu. If an item is selected then its handler
  1695. # will be called before PopupMenu returns.
  1696. self.PopupMenu(zoommenu)
  1697. zoommenu.Destroy()
  1698. def SetProperties(self, render = False, mode = 0, showCompExtent = False,
  1699. constrainRes = False, projection = False):
  1700. """!Set properies of map display window"""
  1701. self.statusbarWin['render'].SetValue(render)
  1702. self.statusbarWin['toggle'].SetSelection(mode)
  1703. self.StatusbarUpdate()
  1704. self.statusbarWin['region'].SetValue(showCompExtent)
  1705. self.statusbarWin['resolution'].SetValue(constrainRes)
  1706. self.statusbarWin['projection'].SetValue(projection)
  1707. if showCompExtent:
  1708. self.MapWindow.regionCoords = []
  1709. def IsStandalone(self):
  1710. """!Check if Map display is standalone"""
  1711. if self._layerManager:
  1712. return False
  1713. return True
  1714. def GetLayerManager(self):
  1715. """!Get reference to Layer Manager
  1716. @return window reference
  1717. @return None (if standalone)
  1718. """
  1719. return self._layerManager
  1720. # end of class MapFrame
  1721. class MapApp(wx.App):
  1722. def OnInit(self):
  1723. wx.InitAllImageHandlers()
  1724. if __name__ == "__main__":
  1725. Map = render.Map() # instance of Map class to render GRASS display output to PPM file
  1726. else:
  1727. Map = None
  1728. self.mapFrm = MapFrame(parent = None, id = wx.ID_ANY, Map = Map,
  1729. size = globalvar.MAP_WINDOW_SIZE)
  1730. #self.SetTopWindow(Map)
  1731. self.mapFrm.Show()
  1732. if __name__ == "__main__":
  1733. # redraw map, if new command appears
  1734. self.redraw = False
  1735. status = Command(self, Map, cmdfilename)
  1736. status.start()
  1737. self.timer = wx.PyTimer(self.watcher)
  1738. # check each 0.1s
  1739. self.timer.Start(100)
  1740. return 1
  1741. def OnExit(self):
  1742. if __name__ == "__main__":
  1743. # stop the timer
  1744. self.timer.Stop()
  1745. # terminate thread (a bit ugly)
  1746. os.system("""!echo "quit" >> %s""" % (cmdfilename))
  1747. def watcher(self):
  1748. """!Redraw, if new layer appears"""
  1749. if self.redraw:
  1750. self.mapFrm.OnDraw(None)
  1751. self.redraw = False
  1752. return
  1753. # end of class MapApp
  1754. if __name__ == "__main__":
  1755. ###### SET command variable
  1756. if len(sys.argv) != 3:
  1757. print __doc__
  1758. sys.exit()
  1759. title = sys.argv[1]
  1760. cmdfilename = sys.argv[2]
  1761. import gettext
  1762. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1763. print >> sys.stderr, "\nStarting monitor <%s>...\n" % (title)
  1764. gm_map = MapApp(0)
  1765. # set title
  1766. gm_map.mapFrm.SetTitle(_("GRASS GIS Map Display: " +
  1767. title +
  1768. " - Location: " + grass.gisenv()["LOCATION_NAME"]))
  1769. gm_map.MainLoop()
  1770. os.remove(cmdfilename)
  1771. os.system("""!g.gisenv set="GRASS_PYCMDFILE" """)
  1772. print >> sys.stderr, "\nStopping monitor <%s>...\n" % (title)
  1773. sys.exit(0)