mapdisp.py 85 KB

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