mapdisp.py 82 KB

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