mapdisp.py 82 KB

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