mapdisp.py 85 KB

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