wxgui.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  1. """
  2. @package wxgui.py
  3. @brief Main Python app for GRASS wxPython GUI. Main menu, layer management
  4. toolbar, notebook control for display management and access to
  5. command console.
  6. Classes:
  7. - GMFrame
  8. - GMApp
  9. (C) 2006-2009 by the GRASS Development Team
  10. This program is free software under the GNU General Public
  11. License (>=v2). Read the file COPYING that comes with GRASS
  12. for details.
  13. @author Michael Barton (Arizona State University)
  14. @author Jachym Cepicky (Mendel University of Agriculture)
  15. @author Martin Landa <landa.martin gmail.com>
  16. """
  17. import sys
  18. import os
  19. import time
  20. import traceback
  21. import re
  22. import string
  23. import getopt
  24. import platform
  25. import signal
  26. ### XML
  27. try:
  28. import xml.etree.ElementTree as etree
  29. except ImportError:
  30. import elementtree.ElementTree as etree # Python <= 2.4
  31. ### i18N
  32. import gettext
  33. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  34. import gui_modules
  35. gmpath = gui_modules.__path__[0]
  36. sys.path.append(gmpath)
  37. import images
  38. imagepath = images.__path__[0]
  39. sys.path.append(imagepath)
  40. import icons
  41. gmpath = icons.__path__[0]
  42. sys.path.append(gmpath)
  43. import gui_modules.globalvar as globalvar
  44. if not os.getenv("GRASS_WXBUNDLED"):
  45. globalvar.CheckForWx()
  46. import wx
  47. import wx.aui
  48. import wx.combo
  49. import wx.html
  50. import wx.stc
  51. import wx.lib.customtreectrl as CT
  52. import wx.lib.flatnotebook as FN
  53. grassPath = os.path.join(globalvar.ETCDIR, "python")
  54. sys.path.append(grassPath)
  55. from grass.script import core as grass
  56. import gui_modules.utils as utils
  57. import gui_modules.preferences as preferences
  58. import gui_modules.wxgui_utils as wxgui_utils
  59. import gui_modules.mapdisp as mapdisp
  60. import gui_modules.menudata as menudata
  61. import gui_modules.menuform as menuform
  62. import gui_modules.histogram as histogram
  63. import gui_modules.profile as profile
  64. import gui_modules.rules as rules
  65. import gui_modules.mcalc_builder as mapcalculator
  66. import gui_modules.gcmd as gcmd
  67. import gui_modules.georect as georect
  68. import gui_modules.dbm as dbm
  69. import gui_modules.workspace as workspace
  70. import gui_modules.goutput as goutput
  71. import gui_modules.gdialogs as gdialogs
  72. import gui_modules.colorrules as colorrules
  73. import gui_modules.ogc_services as ogc_services
  74. import gui_modules.prompt as prompt
  75. from gui_modules.debug import Debug
  76. from gui_modules.help import MenuTreeWindow
  77. from gui_modules.help import AboutWindow
  78. from icons.icon import Icons
  79. UserSettings = preferences.globalSettings
  80. class GMFrame(wx.Frame):
  81. """
  82. GIS Manager frame with notebook widget for controlling
  83. GRASS GIS. Includes command console page for typing GRASS
  84. (and other) commands, tree widget page for managing GIS map layers.
  85. """
  86. def __init__(self, parent, id=wx.ID_ANY, title=_("GRASS GIS Layer Manager"),
  87. workspace=None):
  88. self.parent = parent
  89. self.baseTitle = title
  90. self.iconsize = (16, 16)
  91. wx.Frame.__init__(self, parent=parent, id=id, size=(550, 450),
  92. style=wx.DEFAULT_FRAME_STYLE)
  93. self.SetTitle(self.baseTitle)
  94. self.SetName("LayerManager")
  95. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  96. self._auimgr = wx.aui.AuiManager(self)
  97. # initialize variables
  98. self.disp_idx = 0 # index value for map displays and layer trees
  99. self.curr_page = '' # currently selected page for layer tree notebook
  100. self.curr_pagenum = '' # currently selected page number for layer tree notebook
  101. self.encoding = 'ISO-8859-1' # default encoding for display fonts
  102. self.workspaceFile = workspace # workspace file
  103. self.menucmd = dict() # menuId / cmd
  104. self.georectifying = None # reference to GCP class or None
  105. # list of open dialogs
  106. self.dialogs = dict()
  107. self.dialogs['preferences'] = None
  108. self.dialogs['atm'] = list()
  109. # creating widgets
  110. # -> self.notebook, self.goutput, self.outpage
  111. self.notebook = self.__createNoteBook()
  112. self.menubar, self.menudata = self.__createMenuBar()
  113. self.statusbar = self.CreateStatusBar(number=1)
  114. self.cmdprompt, self.cmdinput = self.__createCommandPrompt()
  115. self.toolbar = self.__createToolBar()
  116. # bindings
  117. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  118. self.Bind(wx.EVT_KEY_UP, self.OnKey)
  119. # minimal frame size
  120. self.SetMinSize((500, 400))
  121. # AUI stuff
  122. # self._auimgr.AddPane(self.toolbar, wx.aui.AuiPaneInfo().ToolbarPane().
  123. # Top().Dockable(False).CloseButton(False).
  124. # DestroyOnClose(True).Row(0).Layer(0))
  125. self._auimgr.AddPane(self.notebook, wx.aui.AuiPaneInfo().
  126. Left().CentrePane().BestSize((-1,-1)).Dockable(False).
  127. CloseButton(False).DestroyOnClose(True).Row(1).Layer(0))
  128. self._auimgr.AddPane(self.cmdprompt, wx.aui.AuiPaneInfo().
  129. Bottom().BestSize((-1, 65)).Dockable(False).
  130. CloseButton(False).DestroyOnClose(True).
  131. PaneBorder(False).Row(1).Layer(0).Position(0).
  132. CaptionVisible(False))
  133. self._auimgr.Update()
  134. wx.CallAfter(self.notebook.SetSelection, 0)
  135. wx.CallAfter(self.cmdinput.SetFocus)
  136. # use default window layout ?
  137. if UserSettings.Get(group='general', key='defWindowPos', subkey='enabled') is True:
  138. dim = UserSettings.Get(group='general', key='defWindowPos', subkey='dim')
  139. try:
  140. x, y = map(int, dim.split(',')[0:2])
  141. w, h = map(int, dim.split(',')[2:4])
  142. self.SetPosition((x, y))
  143. self.SetSize((w, h))
  144. except:
  145. pass
  146. self.Show()
  147. # load workspace file if requested
  148. if (self.workspaceFile):
  149. # load given workspace file
  150. if self.LoadWorkspaceFile(self.workspaceFile):
  151. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  152. else:
  153. self.workspaceFile = None
  154. else:
  155. # start default initial display
  156. self.NewDisplay(show=False)
  157. # show map display widnow
  158. # -> OnSize() -> UpdateMap()
  159. if self.curr_page and not self.curr_page.maptree.mapdisplay.IsShown():
  160. self.curr_page.maptree.mapdisplay.Show()
  161. # redirect stderr to log area
  162. self.goutput.Redirect()
  163. # start with layer manager on top
  164. self.curr_page.maptree.mapdisplay.Raise()
  165. self.Raise()
  166. def __createCommandPrompt(self):
  167. """!Creates command-line input area"""
  168. p = prompt.GPrompt(self)
  169. return p.GetPanel(), p.GetInput()
  170. def __createMenuBar(self):
  171. """!Creates menubar"""
  172. self.menubar = wx.MenuBar()
  173. self.menudata = menudata.Data()
  174. for eachMenuData in self.menudata.GetMenu():
  175. for eachHeading in eachMenuData:
  176. menuLabel = eachHeading[0]
  177. menuItems = eachHeading[1]
  178. self.menubar.Append(self.__createMenu(menuItems), menuLabel)
  179. self.SetMenuBar(self.menubar)
  180. return (self.menubar, self.menudata)
  181. def __createMenu(self, menuData):
  182. """!Creates menu"""
  183. menu = wx.Menu()
  184. for eachItem in menuData:
  185. if len(eachItem) == 2:
  186. label = eachItem[0]
  187. subMenu = self.__createMenu(eachItem[1])
  188. menu.AppendMenu(wx.ID_ANY, label, subMenu)
  189. else:
  190. self.__createMenuItem(menu, *eachItem)
  191. self.Bind(wx.EVT_MENU_HIGHLIGHT_ALL, self.OnMenuHighlight)
  192. return menu
  193. def __createMenuItem(self, menu, label, help, handler, gcmd, keywords, shortcut = '', kind = wx.ITEM_NORMAL):
  194. """!Creates menu items"""
  195. if not label:
  196. menu.AppendSeparator()
  197. return
  198. if len(gcmd) > 0:
  199. helpString = gcmd + ' -- ' + help
  200. else:
  201. helpString = help
  202. if shortcut:
  203. label += '\t' + shortcut
  204. menuItem = menu.Append(wx.ID_ANY, label, helpString, kind)
  205. self.menucmd[menuItem.GetId()] = gcmd
  206. if len(gcmd) > 0 and \
  207. gcmd.split()[0] not in globalvar.grassCmd['all']:
  208. menuItem.Enable (False)
  209. rhandler = eval(handler)
  210. self.Bind(wx.EVT_MENU, rhandler, menuItem)
  211. def __createNoteBook(self):
  212. """!Creates notebook widgets"""
  213. #create main notebook widget
  214. nbStyle = FN.FNB_FANCY_TABS | \
  215. FN.FNB_BOTTOM | \
  216. FN.FNB_NO_NAV_BUTTONS | \
  217. FN.FNB_NO_X_BUTTON
  218. self.notebook = FN.FlatNotebook(parent=self, id=wx.ID_ANY, style=nbStyle)
  219. #self.notebook = wx.aui.AuiNotebook(parent=self, id=wx.ID_ANY, style=wx.aui.AUI_NB_BOTTOM)
  220. #self.notebook.SetFont(wx.Font(pointSize=11, family=wx.FONTFAMILY_DEFAULT, style=wx.NORMAL, weight=0))
  221. # create displays notebook widget and add it to main notebook page
  222. cbStyle = globalvar.FNPageStyle
  223. self.gm_cb = FN.FlatNotebook(self, id=wx.ID_ANY, style=cbStyle)
  224. self.gm_cb.SetTabAreaColour(globalvar.FNPageColor)
  225. self.notebook.AddPage(self.gm_cb, text=_("Map layers for each display"))
  226. # create command output text area and add it to main notebook page
  227. self.goutput = goutput.GMConsole(self, pageid=1)
  228. self.outpage = self.notebook.AddPage(self.goutput, text=_("Command output"))
  229. # bindings
  230. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnCBPageChanged)
  231. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  232. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnCBPageClosed)
  233. sizer = wx.BoxSizer(wx.VERTICAL)
  234. sizer.Add(item=self.goutput, proportion=1,
  235. flag=wx.EXPAND | wx.ALL, border=1)
  236. self.SetSizer(sizer)
  237. # self.out_sizer.Fit(self.outpage)
  238. self.Layout()
  239. self.Centre()
  240. return self.notebook
  241. def __createToolBar(self):
  242. """!Creates toolbar"""
  243. self.toolbar = self.CreateToolBar()
  244. self.toolbar.SetToolBitmapSize(globalvar.toolbarSize)
  245. for each in self.ToolbarData():
  246. self.AddToolbarButton(self.toolbar, *each)
  247. self.toolbar.Realize()
  248. return self.toolbar
  249. def OnMenuHighlight(self, event):
  250. """
  251. Default menu help handler
  252. """
  253. # Show how to get menu item info from this event handler
  254. id = event.GetMenuId()
  255. item = self.GetMenuBar().FindItemById(id)
  256. if item:
  257. text = item.GetText()
  258. help = item.GetHelp()
  259. # but in this case just call Skip so the default is done
  260. event.Skip()
  261. def OnGeorectify(self, event):
  262. """
  263. Launch georectifier module
  264. """
  265. georect.GeorectWizard(self)
  266. def OnMapsets(self, event):
  267. """
  268. Launch mapset access dialog
  269. """
  270. dlg = preferences.MapsetAccess(parent=self, id=wx.ID_ANY)
  271. dlg.CenterOnScreen()
  272. # if OK is pressed...
  273. if dlg.ShowModal() == wx.ID_OK:
  274. ms = dlg.GetMapsets()
  275. # run g.mapsets with string of accessible mapsets
  276. gcmd.RunCommand('g.mapsets',
  277. parent = self,
  278. mapset = '%s' % ','.join(ms))
  279. def OnRDigit(self, event):
  280. """
  281. Launch raster digitizing module
  282. """
  283. pass
  284. def OnCBPageChanged(self, event):
  285. """!Page in notebook (display) changed"""
  286. old_pgnum = event.GetOldSelection()
  287. new_pgnum = event.GetSelection()
  288. self.curr_page = self.gm_cb.GetCurrentPage()
  289. self.curr_pagenum = self.gm_cb.GetSelection()
  290. try:
  291. self.curr_page.maptree.mapdisplay.SetFocus()
  292. self.curr_page.maptree.mapdisplay.Raise()
  293. except:
  294. pass
  295. event.Skip()
  296. def OnPageChanged(self, event):
  297. """!Page in notebook changed"""
  298. page = event.GetSelection()
  299. if page == self.goutput.pageid:
  300. # remove '(...)'
  301. self.notebook.SetPageText(page, _("Command output"))
  302. event.Skip()
  303. def OnCBPageClosed(self, event):
  304. """
  305. Page of notebook closed
  306. Also close associated map display
  307. """
  308. if UserSettings.Get(group='manager', key='askOnQuit', subkey='enabled'):
  309. maptree = self.curr_page.maptree
  310. if self.workspaceFile:
  311. message = _("Do you want to save changes in the workspace?")
  312. else:
  313. message = _("Do you want to store current settings "
  314. "to workspace file?")
  315. # ask user to save current settings
  316. if maptree.GetCount() > 0:
  317. dlg = wx.MessageDialog(self,
  318. message=message,
  319. caption=_("Close Map Display %d") % (self.curr_pagenum + 1),
  320. style=wx.YES_NO | wx.YES_DEFAULT |
  321. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  322. ret = dlg.ShowModal()
  323. if ret == wx.ID_YES:
  324. if not self.workspaceFile:
  325. self.OnWorkspaceSaveAs()
  326. else:
  327. self.SaveToWorkspaceFile(self.workspaceFile)
  328. elif ret == wx.ID_CANCEL:
  329. event.Veto()
  330. dlg.Destroy()
  331. return
  332. dlg.Destroy()
  333. self.gm_cb.GetPage(event.GetSelection()).maptree.Map.Clean()
  334. self.gm_cb.GetPage(event.GetSelection()).maptree.Close(True)
  335. self.curr_page = None
  336. event.Skip()
  337. def GetLogWindow(self):
  338. """!Get widget for command output"""
  339. return self.goutput
  340. def GetMenuCmd(self, event):
  341. """!Get GRASS command from menu item
  342. Return command as a list"""
  343. layer = None
  344. if event:
  345. cmd = self.menucmd[event.GetId()]
  346. try:
  347. cmdlist = cmd.split(' ')
  348. except: # already list?
  349. cmdlist = cmd
  350. # check list of dummy commands for GUI modules that do not have GRASS
  351. # bin modules or scripts.
  352. if cmd in ['vcolors']:
  353. return cmdlist
  354. try:
  355. layer = self.curr_page.maptree.layer_selected
  356. name = self.curr_page.maptree.GetPyData(layer)[0]['maplayer'].name
  357. type = self.curr_page.maptree.GetPyData(layer)[0]['type']
  358. except:
  359. layer = None
  360. if layer and len(cmdlist) == 1: # only if no paramaters given
  361. if (type == 'raster' and cmdlist[0][0] == 'r' and cmdlist[0][1] != '3') or \
  362. (type == 'vector' and cmdlist[0][0] == 'v'):
  363. input = menuform.GUI().GetCommandInputMapParamKey(cmdlist[0])
  364. if input:
  365. cmdlist.append("%s=%s" % (input, name))
  366. return cmdlist
  367. def RunMenuCmd(self, event, cmd = ''):
  368. """!Run command selected from menu"""
  369. if event:
  370. cmd = self.GetMenuCmd(event)
  371. self.goutput.RunCmd(cmd, switchPage=True)
  372. def OnMenuCmd(self, event, cmd = ''):
  373. """!Parse command selected from menu"""
  374. if event:
  375. cmd = self.GetMenuCmd(event)
  376. menuform.GUI().ParseCommand(cmd, parentframe=self)
  377. def OnRunScript(self, event):
  378. """!Run script"""
  379. # open dialog and choose script file
  380. dlg = wx.FileDialog(parent = self, message = _("Choose script file"),
  381. defaultDir = os.getcwd(), wildcard = _("Bash script (*.sh)|*.sh|Python script (*.py)|*.py"))
  382. filename = None
  383. if dlg.ShowModal() == wx.ID_OK:
  384. filename = dlg.GetPath()
  385. if not filename:
  386. return False
  387. if not os.path.exists(filename):
  388. wx.MessageBox(parent = self,
  389. message = _("Script file '%s' doesn't exist. Operation cancelled.") % filename,
  390. caption = _("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  391. return
  392. self.goutput.WriteCmdLog(_("Launching script '%s'...") % filename)
  393. self.goutput.RunCmd(filename, switchPage = True)
  394. def OnChangeLocation(self, event):
  395. """Change current location"""
  396. dlg = gdialogs.LocationDialog(parent = self)
  397. if dlg.ShowModal() == wx.ID_OK:
  398. location, mapset = dlg.GetValues()
  399. if location and mapset:
  400. ret = gcmd.RunCommand("g.gisenv",
  401. set = "LOCATION_NAME=%s" % location)
  402. ret += gcmd.RunCommand("g.gisenv",
  403. set = "MAPSET=%s" % mapset)
  404. if ret > 0:
  405. wx.MessageBox(parent = self,
  406. message = _("Unable to switch to location <%(loc)s> mapset <%(mapset)s>.") % \
  407. { 'loc' : location, 'mapset' : mapset },
  408. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  409. else:
  410. # close workspace
  411. self.OnWorkspaceClose()
  412. self.OnWorkspaceNew()
  413. wx.MessageBox(parent = self,
  414. message = _("Current location is <%(loc)s>.\n"
  415. "Current mapset is <%(mapset)s>.") % \
  416. { 'loc' : location, 'mapset' : mapset },
  417. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  418. def OnChangeMapset(self, event):
  419. """Change current mapset"""
  420. dlg = gdialogs.MapsetDialog(parent = self)
  421. if dlg.ShowModal() == wx.ID_OK:
  422. mapset = dlg.GetMapset()
  423. if mapset:
  424. if gcmd.RunCommand("g.gisenv",
  425. set = "MAPSET=%s" % mapset) != 0:
  426. wx.MessageBox(parent = self,
  427. message = _("Unable to switch to mapset <%s>.") % mapset,
  428. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  429. else:
  430. wx.MessageBox(parent = self,
  431. message = _("Current mapset is <%s>.") % mapset,
  432. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  433. def OnNewVector(self, event):
  434. """!Create new vector map layer"""
  435. name, add = gdialogs.CreateNewVector(self, log = self.goutput,
  436. cmd = (('v.edit',
  437. { 'tool' : 'create' },
  438. 'map')))
  439. if name and add:
  440. # add layer to map layer tree
  441. self.curr_page.maptree.AddLayer(ltype='vector',
  442. lname=name,
  443. lchecked=True,
  444. lopacity=1.0,
  445. lcmd=['d.vect', 'map=%s' % name])
  446. def OnMenuTree(self, event):
  447. """!Show dialog with menu tree"""
  448. dlg = MenuTreeWindow(self)
  449. dlg.CentreOnScreen()
  450. dlg.Show()
  451. def OnAboutGRASS(self, event):
  452. """!Display 'About GRASS' dialog"""
  453. win = AboutWindow(self)
  454. win.Centre()
  455. win.Show(True)
  456. def OnWorkspace(self, event):
  457. """!Workspace menu (new, load)"""
  458. point = wx.GetMousePosition()
  459. menu = wx.Menu()
  460. # Add items to the menu
  461. new = wx.MenuItem(menu, wx.ID_ANY, Icons["workspaceNew"].GetLabel())
  462. new.SetBitmap(Icons["workspaceNew"].GetBitmap(self.iconsize))
  463. menu.AppendItem(new)
  464. self.Bind(wx.EVT_MENU, self.OnWorkspaceNew, new)
  465. load = wx.MenuItem(menu, wx.ID_ANY, Icons["workspaceLoad"].GetLabel())
  466. load.SetBitmap(Icons["workspaceLoad"].GetBitmap(self.iconsize))
  467. menu.AppendItem(load)
  468. self.Bind(wx.EVT_MENU, self.OnWorkspaceLoad, load)
  469. # create menu
  470. self.PopupMenu(menu)
  471. menu.Destroy()
  472. def OnWorkspaceNew(self, event=None):
  473. """!Create new workspace file
  474. Erase current workspace settings first"""
  475. Debug.msg(4, "GMFrame.OnWorkspaceNew():")
  476. # start new map display if no display is available
  477. if not self.curr_page:
  478. self.NewDisplay()
  479. maptree = self.curr_page.maptree
  480. # ask user to save current settings
  481. if maptree.GetCount() > 0:
  482. dlg = wx.MessageDialog(self, message=_("Current workspace is not empty. "
  483. "Do you want to store current settings "
  484. "to workspace file?"),
  485. caption=_("Create new workspace?"),
  486. style=wx.YES_NO | wx.YES_DEFAULT | \
  487. wx.CANCEL | wx.ICON_QUESTION)
  488. ret = dlg.ShowModal()
  489. if ret == wx.ID_YES:
  490. self.OnWorkspaceSaveAs()
  491. elif ret == wx.ID_CANCEL:
  492. dlg.Destroy()
  493. return
  494. dlg.Destroy()
  495. # delete all items
  496. maptree.DeleteAllItems()
  497. # add new root element
  498. maptree.root = maptree.AddRoot("Map Layers")
  499. self.curr_page.maptree.SetPyData(maptree.root, (None,None))
  500. # no workspace file loaded
  501. self.workspaceFile = None
  502. self.SetTitle(self.baseTitle)
  503. def OnWorkspaceOpen(self, event=None):
  504. """!Open file with workspace definition"""
  505. dlg = wx.FileDialog(parent=self, message=_("Choose workspace file"),
  506. defaultDir=os.getcwd(), wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"))
  507. filename = ''
  508. if dlg.ShowModal() == wx.ID_OK:
  509. filename = dlg.GetPath()
  510. if filename == '':
  511. return
  512. Debug.msg(4, "GMFrame.OnWorkspaceOpen(): filename=%s" % filename)
  513. # delete current layer tree content
  514. self.OnWorkspaceClose()
  515. self.LoadWorkspaceFile(filename)
  516. self.workspaceFile = filename
  517. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  518. def LoadWorkspaceFile(self, filename):
  519. """!Load layer tree definition stored in GRASS Workspace XML file (gxw)
  520. @todo Validate against DTD
  521. @return True on success
  522. @return False on error
  523. """
  524. # dtd
  525. dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxw.dtd")
  526. # parse workspace file
  527. try:
  528. gxwXml = workspace.ProcessWorkspaceFile(etree.parse(filename))
  529. except Exception, err:
  530. raise gcmd.GStdError(_("Reading workspace file <%(file)s> failed.\n"
  531. "Invalid file, unable to parse XML document."
  532. "\n\n%(err)s") % { 'file' : filename, 'err': err},
  533. parent = self)
  534. busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
  535. parent=self)
  536. wx.Yield()
  537. #
  538. # load layer manager window properties
  539. #
  540. if UserSettings.Get(group='workspace', key='posManager', subkey='enabled') is False:
  541. if gxwXml.layerManager['pos']:
  542. self.SetPosition(gxwXml.layerManager['pos'])
  543. if gxwXml.layerManager['size']:
  544. self.SetSize(gxwXml.layerManager['size'])
  545. #
  546. # start map displays first (list of layers can be empty)
  547. #
  548. displayId = 0
  549. mapdisplay = []
  550. for display in gxwXml.displays:
  551. mapdisplay.append(self.NewDisplay(show=False))
  552. maptree = self.gm_cb.GetPage(displayId).maptree
  553. # set windows properties
  554. mapdisplay[-1].SetProperties(render=display['render'],
  555. mode=display['mode'],
  556. showCompExtent=display['showCompExtent'],
  557. constrainRes=display['constrainRes'],
  558. projection=display['projection']['enabled'])
  559. if display['projection']['enabled']:
  560. if display['projection']['epsg']:
  561. UserSettings.Set(group = 'display', key = 'projection', subkey = 'epsg',
  562. value = display['projection']['epsg'])
  563. if display['projection']['proj']:
  564. UserSettings.Set(group = 'display', key = 'projection', subkey = 'proj4',
  565. value = display['projection']['proj'])
  566. # set position and size of map display
  567. if UserSettings.Get(group='workspace', key='posDisplay', subkey='enabled') is False:
  568. if display['pos']:
  569. mapdisplay[-1].SetPosition(display['pos'])
  570. if display['size']:
  571. mapdisplay[-1].SetSize(display['size'])
  572. # set extent if defined
  573. if display['extent']:
  574. w, s, e, n = display['extent']
  575. maptree.Map.region = maptree.Map.GetRegion(w=w, s=s, e=e, n=n)
  576. mapdisplay[-1].Show()
  577. displayId += 1
  578. maptree = None
  579. selected = [] # list of selected layers
  580. #
  581. # load list of map layers
  582. #
  583. for layer in gxwXml.layers:
  584. display = layer['display']
  585. maptree = self.gm_cb.GetPage(display).maptree
  586. newItem = maptree.AddLayer(ltype=layer['type'],
  587. lname=layer['name'],
  588. lchecked=layer['checked'],
  589. lopacity=layer['opacity'],
  590. lcmd=layer['cmd'],
  591. lgroup=layer['group'],
  592. lnviz=layer['nviz'],
  593. lvdigit=layer['vdigit'])
  594. if layer.has_key('selected'):
  595. if layer['selected']:
  596. selected.append((maptree, newItem))
  597. else:
  598. maptree.SelectItem(newItem, select=False)
  599. for maptree, layer in selected:
  600. if not maptree.IsSelected(layer):
  601. maptree.SelectItem(layer, select=True)
  602. maptree.layer_selected = layer
  603. busy.Destroy()
  604. if maptree:
  605. # reverse list of map layers
  606. maptree.Map.ReverseListOfLayers()
  607. for mdisp in mapdisplay:
  608. mdisp.MapWindow2D.UpdateMap()
  609. return True
  610. def OnWorkspaceLoad(self, event=None):
  611. """!Load given map layers into layer tree"""
  612. dialog = gdialogs.LoadMapLayersDialog(parent=self, title=_("Load map layers into layer tree"))
  613. if dialog.ShowModal() == wx.ID_OK:
  614. # start new map display if no display is available
  615. if not self.curr_page:
  616. self.NewDisplay()
  617. maptree = self.curr_page.maptree
  618. busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
  619. parent=self)
  620. wx.Yield()
  621. for layerName in dialog.GetMapLayers():
  622. if dialog.GetLayerType() == 'raster':
  623. cmd = ['d.rast', 'map=%s' % layerName]
  624. elif dialog.GetLayerType() == 'vector':
  625. cmd = ['d.vect', 'map=%s' % layerName]
  626. newItem = maptree.AddLayer(ltype=dialog.GetLayerType(),
  627. lname=layerName,
  628. lchecked=True,
  629. lopacity=1.0,
  630. lcmd=cmd,
  631. lgroup=None)
  632. busy.Destroy()
  633. def OnWorkspaceLoadGrcFile(self, event):
  634. """!Load map layers from GRC file (Tcl/Tk GUI) into map layer tree"""
  635. dlg = wx.FileDialog(parent=self, message=_("Choose GRC file to load"),
  636. defaultDir=os.getcwd(), wildcard=_("Old GRASS Workspace File (*.grc)|*.grc"))
  637. filename = ''
  638. if dlg.ShowModal() == wx.ID_OK:
  639. filename = dlg.GetPath()
  640. if filename == '':
  641. return
  642. Debug.msg(4, "GMFrame.OnWorkspaceLoadGrcFile(): filename=%s" % filename)
  643. # start new map display if no display is available
  644. if not self.curr_page:
  645. self.NewDisplay()
  646. busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
  647. parent=self)
  648. wx.Yield()
  649. maptree = None
  650. for layer in workspace.ProcessGrcFile(filename).read(self):
  651. maptree = self.gm_cb.GetPage(layer['display']).maptree
  652. newItem = maptree.AddLayer(ltype=layer['type'],
  653. lname=layer['name'],
  654. lchecked=layer['checked'],
  655. lopacity=layer['opacity'],
  656. lcmd=layer['cmd'],
  657. lgroup=layer['group'])
  658. busy.Destroy()
  659. if maptree:
  660. # reverse list of map layers
  661. maptree.Map.ReverseListOfLayers()
  662. def OnWorkspaceSaveAs(self, event=None):
  663. """!Save workspace definition to selected file"""
  664. dlg = wx.FileDialog(parent=self, message=_("Choose file to save current workspace"),
  665. defaultDir=os.getcwd(), wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"), style=wx.FD_SAVE)
  666. filename = ''
  667. if dlg.ShowModal() == wx.ID_OK:
  668. filename = dlg.GetPath()
  669. if filename == '':
  670. return False
  671. # check for extension
  672. if filename[-4:] != ".gxw":
  673. filename += ".gxw"
  674. if os.path.exists(filename):
  675. dlg = wx.MessageDialog(self, message=_("Workspace file <%s> already exists. "
  676. "Do you want to overwrite this file?") % filename,
  677. caption=_("Save workspace"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  678. if dlg.ShowModal() != wx.ID_YES:
  679. dlg.Destroy()
  680. return False
  681. Debug.msg(4, "GMFrame.OnWorkspaceSaveAs(): filename=%s" % filename)
  682. self.SaveToWorkspaceFile(filename)
  683. self.workspaceFile = filename
  684. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  685. def OnWorkspaceSave(self, event=None):
  686. """!Save file with workspace definition"""
  687. if self.workspaceFile:
  688. dlg = wx.MessageDialog(self, message=_("Workspace file <%s> already exists. "
  689. "Do you want to overwrite this file?") % \
  690. self.workspaceFile,
  691. caption=_("Save workspace"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  692. if dlg.ShowModal() == wx.ID_NO:
  693. dlg.Destroy()
  694. else:
  695. Debug.msg(4, "GMFrame.OnWorkspaceSave(): filename=%s" % self.workspaceFile)
  696. self.SaveToWorkspaceFile(self.workspaceFile)
  697. else:
  698. self.OnWorkspaceSaveAs()
  699. def SaveToWorkspaceFile(self, filename):
  700. """!Save layer tree layout to workspace file
  701. Return True on success, False on error
  702. """
  703. try:
  704. file = open(filename, "w")
  705. except IOError:
  706. wx.MessageBox(parent=self,
  707. message=_("Unable to open workspace file <%s> for writing.") % filename,
  708. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  709. return False
  710. try:
  711. workspace.WriteWorkspaceFile(lmgr=self, file=file)
  712. except StandardError, e:
  713. file.close()
  714. wx.MessageBox(parent=self,
  715. message=_("Writing current settings to workspace file failed (%s)." % e),
  716. caption=_("Error"),
  717. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  718. return False
  719. file.close()
  720. return True
  721. def OnWorkspaceClose(self, event=None):
  722. """!Close file with workspace definition
  723. If workspace has been modified ask user to save the changes.
  724. """
  725. Debug.msg(4, "GMFrame.OnWorkspaceClose(): file=%s" % self.workspaceFile)
  726. self.workspaceFile = None
  727. self.SetTitle(self.baseTitle)
  728. displays = []
  729. for page in range(0, self.gm_cb.GetPageCount()):
  730. displays.append(self.gm_cb.GetPage(page).maptree.mapdisplay)
  731. for display in displays:
  732. display.OnCloseWindow(event)
  733. self.disp_idx = 0
  734. self.curr_page = None
  735. def RulesCmd(self, event, cmd = ''):
  736. """
  737. Launches dialog for commands that need rules
  738. input and processes rules
  739. """
  740. if event:
  741. cmd = self.GetMenuCmd(event)
  742. if cmd[0] == 'r.colors' or cmd[0] == 'vcolors':
  743. ctable = colorrules.ColorTable(self, cmd=cmd[0])
  744. ctable.Show()
  745. else:
  746. dlg = rules.RulesText(self, cmd=cmd)
  747. dlg.CenterOnScreen()
  748. if dlg.ShowModal() == wx.ID_OK:
  749. gtemp = utils.GetTempfile()
  750. output = open(gtemp, "w")
  751. try:
  752. output.write(dlg.rules)
  753. finally:
  754. output.close()
  755. cmdlist = [cmd[0],
  756. 'input=%s' % dlg.inmap,
  757. 'output=%s' % dlg.outmap,
  758. 'rules=%s' % gtemp]
  759. if dlg.overwrite == True:
  760. cmdlist.append('--o')
  761. dlg.Destroy()
  762. self.goutput.RunCmd(cmdlist)
  763. def OnPreferences(self, event):
  764. """!General GUI preferences/settings"""
  765. if not self.dialogs['preferences']:
  766. dlg = preferences.PreferencesDialog(parent=self)
  767. self.dialogs['preferences'] = dlg
  768. self.dialogs['preferences'].CenterOnScreen()
  769. self.dialogs['preferences'].ShowModal()
  770. def DispHistogram(self, event):
  771. """
  772. Init histogram display canvas and tools
  773. """
  774. self.histogram = histogram.HistFrame(self,
  775. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(400,300),
  776. style=wx.DEFAULT_FRAME_STYLE)
  777. #show new display
  778. self.histogram.Show()
  779. self.histogram.Refresh()
  780. self.histogram.Update()
  781. def DispProfile(self, event):
  782. """
  783. Init profile canvas and tools
  784. """
  785. self.profile = profile.ProfileFrame(self,
  786. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(400,300),
  787. style=wx.DEFAULT_FRAME_STYLE)
  788. self.profile.Show()
  789. self.profile.Refresh()
  790. self.profile.Update()
  791. def DispMapCalculator(self, event):
  792. """
  793. Init map calculator for interactive creation of mapcalc statements
  794. """
  795. self.mapcalculator = mapcalculator.MapCalcFrame(self, wx.ID_ANY, title='',
  796. dimension=2)
  797. def Disp3DMapCalculator(self, event):
  798. """
  799. Init map calculator for interactive creation of mapcalc statements
  800. """
  801. self.mapcalculator = mapcalculator.MapCalcFrame(self, wx.ID_ANY, title='',
  802. dimension=3)
  803. def AddToolbarButton(self, toolbar, label, icon, help, handler):
  804. """!Adds button to the given toolbar"""
  805. if not label:
  806. toolbar.AddSeparator()
  807. return
  808. tool = toolbar.AddLabelTool(id=wx.ID_ANY, label=label, bitmap=icon, shortHelp=help)
  809. self.Bind(wx.EVT_TOOL, handler, tool)
  810. def ToolbarData(self):
  811. return (
  812. ('newdisplay', Icons["newdisplay"].GetBitmap(),
  813. Icons["newdisplay"].GetLabel(), self.OnNewDisplay),
  814. ('', '', '', ''),
  815. ('workspaceLoad', Icons["workspaceLoad"].GetBitmap(),
  816. Icons["workspaceLoad"].GetLabel(), self.OnWorkspace),
  817. ('workspaceOpen', Icons["workspaceOpen"].GetBitmap(),
  818. Icons["workspaceOpen"].GetLabel(), self.OnWorkspaceOpen),
  819. ('workspaceSave', Icons["workspaceSave"].GetBitmap(),
  820. Icons["workspaceSave"].GetLabel(), self.OnWorkspaceSave),
  821. ('', '', '', ''),
  822. ('addrast', Icons["addrast"].GetBitmap(),
  823. Icons["addrast"].GetLabel(), self.OnAddRaster),
  824. ('addshaded', Icons["addshaded"].GetBitmap(),
  825. _("Add various raster-based map layers"), self.OnAddRasterMisc),
  826. ('addvect', Icons["addvect"].GetBitmap(),
  827. Icons["addvect"].GetLabel(), self.OnAddVector),
  828. ('addthematic', Icons["addthematic"].GetBitmap(),
  829. _("Add various vector-based map layer"), self.OnAddVectorMisc),
  830. ('addcmd', Icons["addcmd"].GetBitmap(),
  831. Icons["addcmd"].GetLabel(), self.OnAddCommand),
  832. ('addgrp', Icons["addgrp"].GetBitmap(),
  833. Icons["addgrp"].GetLabel(), self.OnAddGroup),
  834. ('addovl', Icons["addovl"].GetBitmap(),
  835. Icons["addovl"].GetLabel(), self.OnAddOverlay),
  836. ('delcmd', Icons["delcmd"].GetBitmap(),
  837. Icons["delcmd"].GetLabel(), self.OnDeleteLayer),
  838. ('', '', '', ''),
  839. ('attrtable', Icons["attrtable"].GetBitmap(),
  840. Icons["attrtable"].GetLabel(), self.OnShowAttributeTable)
  841. )
  842. def OnImportDxfFile(self, event):
  843. """!Convert multiple DXF layers to GRASS vector map layers"""
  844. dlg = gdialogs.MultiImportDialog(parent=self, type='dxf',
  845. title=_("Import DXF layers"))
  846. dlg.ShowModal()
  847. def OnImportGdalLayers(self, event):
  848. """!Convert multiple GDAL layers to GRASS raster map layers"""
  849. dlg = gdialogs.MultiImportDialog(parent=self, type='gdal',
  850. title=_("Import GDAL layers"))
  851. dlg.ShowModal()
  852. def OnLinkGdalLayers(self, event):
  853. """!Link multiple GDAL layers to GRASS raster map layers"""
  854. dlg = gdialogs.MultiImportDialog(parent=self, type='gdal',
  855. title=_("Link GDAL layers"),
  856. link = True)
  857. dlg.ShowModal()
  858. def OnImportOgrLayers(self, event):
  859. """!Convert multiple OGR layers to GRASS vector map layers"""
  860. dlg = gdialogs.MultiImportDialog(parent=self, type='ogr',
  861. title=_("Import OGR layers"))
  862. dlg.ShowModal()
  863. def OnLinkOgrLayers(self, event):
  864. """!Links multiple OGR layers to GRASS vector map layers"""
  865. dlg = gdialogs.MultiImportDialog(parent=self, type='ogr',
  866. title=_("Link OGR layers"),
  867. link = True)
  868. dlg.ShowModal()
  869. def OnImportWMS(self, event):
  870. """!Import data from OGC WMS server"""
  871. dlg = ogc_services.WMSDialog(parent = self, service = 'wms')
  872. dlg.CenterOnScreen()
  873. if dlg.ShowModal() == wx.ID_OK: # -> import layers
  874. layers = dlg.GetLayers()
  875. if len(layers.keys()) > 0:
  876. for layer in layers.keys():
  877. cmd = ['r.in.wms',
  878. 'mapserver=%s' % dlg.GetSettings()['server'],
  879. 'layers=%s' % layer,
  880. 'output=%s' % layer]
  881. styles = ','.join(layers[layer])
  882. if styles:
  883. cmd.append('styles=%s' % styles)
  884. self.goutput.RunCmd(cmd, switchPage = True)
  885. else:
  886. self.goutput.WriteWarning(_("Nothing to import. No WMS layer selected."))
  887. dlg.Destroy()
  888. def OnShowAttributeTable(self, event):
  889. """
  890. Show attribute table of the given vector map layer
  891. """
  892. if not self.curr_page:
  893. self.MsgNoLayerSelected()
  894. return
  895. layer = self.curr_page.maptree.layer_selected
  896. # no map layer selected
  897. if not layer:
  898. self.MsgNoLayerSelected()
  899. return
  900. # available only for vector map layers
  901. try:
  902. maptype = self.curr_page.maptree.GetPyData(layer)[0]['maplayer'].type
  903. except:
  904. maptype = None
  905. if not maptype or maptype != 'vector':
  906. wx.MessageBox(parent=self,
  907. message=_("Attribute management is available only "
  908. "for vector maps."),
  909. caption=_("Message"),
  910. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  911. return
  912. if not self.curr_page.maptree.GetPyData(layer)[0]:
  913. return
  914. dcmd = self.curr_page.maptree.GetPyData(layer)[0]['cmd']
  915. if not dcmd:
  916. return
  917. busy = wx.BusyInfo(message=_("Please wait, loading attribute data..."),
  918. parent=self)
  919. wx.Yield()
  920. dbmanager = dbm.AttributeManager(parent=self, id=wx.ID_ANY,
  921. size=wx.Size(500, 300),
  922. item=layer, log=self.goutput)
  923. busy.Destroy()
  924. # register ATM dialog
  925. self.dialogs['atm'].append(dbmanager)
  926. # show ATM window
  927. dbmanager.Show()
  928. def OnNewDisplay(self, event=None):
  929. """!Create new layer tree and map display instance"""
  930. self.NewDisplay()
  931. def NewDisplay(self, show=True):
  932. """!Create new layer tree, which will
  933. create an associated map display frame
  934. @param show show map display window if True
  935. @return reference to mapdisplay intance
  936. """
  937. Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.disp_idx)
  938. # make a new page in the bookcontrol for the layer tree (on page 0 of the notebook)
  939. self.pg_panel = wx.Panel(self.gm_cb, id=wx.ID_ANY, style= wx.EXPAND)
  940. self.gm_cb.AddPage(self.pg_panel, text="Display "+ str(self.disp_idx + 1), select = True)
  941. self.curr_page = self.gm_cb.GetCurrentPage()
  942. # create layer tree (tree control for managing GIS layers) and put on new notebook page
  943. self.curr_page.maptree = wxgui_utils.LayerTree(self.curr_page, id=wx.ID_ANY, pos=wx.DefaultPosition,
  944. size=wx.DefaultSize, style=wx.TR_HAS_BUTTONS
  945. |wx.TR_LINES_AT_ROOT|wx.TR_HIDE_ROOT
  946. |wx.TR_DEFAULT_STYLE|wx.NO_BORDER|wx.FULL_REPAINT_ON_RESIZE,
  947. idx=self.disp_idx, lmgr=self, notebook=self.gm_cb,
  948. auimgr=self._auimgr, showMapDisplay=show)
  949. # layout for controls
  950. cb_boxsizer = wx.BoxSizer(wx.VERTICAL)
  951. cb_boxsizer.Add(self.curr_page.maptree, proportion=1, flag=wx.EXPAND, border=1)
  952. self.curr_page.SetSizer(cb_boxsizer)
  953. cb_boxsizer.Fit(self.curr_page.maptree)
  954. self.curr_page.Layout()
  955. self.curr_page.maptree.Layout()
  956. # use default window layout
  957. if UserSettings.Get(group='general', key='defWindowPos', subkey='enabled') is True:
  958. dim = UserSettings.Get(group='general', key='defWindowPos', subkey='dim')
  959. idx = 4 + self.disp_idx * 4
  960. try:
  961. x, y = map(int, dim.split(',')[idx:idx + 2])
  962. w, h = map(int, dim.split(',')[idx + 2:idx + 4])
  963. self.curr_page.maptree.mapdisplay.SetPosition((x, y))
  964. self.curr_page.maptree.mapdisplay.SetSize((w, h))
  965. except:
  966. pass
  967. self.disp_idx += 1
  968. return self.curr_page.maptree.mapdisplay
  969. # toolBar button handlers
  970. def OnAddRaster(self, event):
  971. """!Add raster map layer"""
  972. # start new map display if no display is available
  973. if not self.curr_page:
  974. self.NewDisplay(show=False)
  975. self.AddRaster(event)
  976. def OnAddRasterMisc(self, event):
  977. """!Add raster menu"""
  978. # start new map display if no display is available
  979. if not self.curr_page:
  980. self.NewDisplay(show=False)
  981. point = wx.GetMousePosition()
  982. rastmenu = wx.Menu()
  983. # add items to the menu
  984. if self.curr_page.maptree.mapdisplay.toolbars['nviz']:
  985. addrast3d = wx.MenuItem(rastmenu, -1, Icons ["addrast3d"].GetLabel())
  986. addrast3d.SetBitmap(Icons["addrast3d"].GetBitmap (self.iconsize))
  987. rastmenu.AppendItem(addrast3d)
  988. self.Bind(wx.EVT_MENU, self.AddRaster3d, addrast3d)
  989. addshaded = wx.MenuItem(rastmenu, -1, Icons ["addshaded"].GetLabel())
  990. addshaded.SetBitmap(Icons["addshaded"].GetBitmap (self.iconsize))
  991. rastmenu.AppendItem(addshaded)
  992. self.Bind(wx.EVT_MENU, self.AddShaded, addshaded)
  993. addrgb = wx.MenuItem(rastmenu, -1, Icons["addrgb"].GetLabel())
  994. addrgb.SetBitmap(Icons["addrgb"].GetBitmap(self.iconsize))
  995. rastmenu.AppendItem(addrgb)
  996. self.Bind(wx.EVT_MENU, self.AddRGB, addrgb)
  997. addhis = wx.MenuItem(rastmenu, -1, Icons ["addhis"].GetLabel())
  998. addhis.SetBitmap(Icons["addhis"].GetBitmap (self.iconsize))
  999. rastmenu.AppendItem(addhis)
  1000. self.Bind(wx.EVT_MENU, self.AddHIS, addhis)
  1001. addrastarrow = wx.MenuItem(rastmenu, -1, Icons ["addrarrow"].GetLabel())
  1002. addrastarrow.SetBitmap(Icons["addrarrow"].GetBitmap (self.iconsize))
  1003. rastmenu.AppendItem(addrastarrow)
  1004. self.Bind(wx.EVT_MENU, self.AddRastarrow, addrastarrow)
  1005. addrastnums = wx.MenuItem(rastmenu, -1, Icons ["addrnum"].GetLabel())
  1006. addrastnums.SetBitmap(Icons["addrnum"].GetBitmap (self.iconsize))
  1007. rastmenu.AppendItem(addrastnums)
  1008. self.Bind(wx.EVT_MENU, self.AddRastnum, addrastnums)
  1009. # Popup the menu. If an item is selected then its handler
  1010. # will be called before PopupMenu returns.
  1011. self.PopupMenu(rastmenu)
  1012. rastmenu.Destroy()
  1013. # show map display
  1014. self.curr_page.maptree.mapdisplay.Show()
  1015. def OnAddVector(self, event):
  1016. """!Add vector map layer"""
  1017. # start new map display if no display is available
  1018. if not self.curr_page:
  1019. self.NewDisplay(show=False)
  1020. self.AddVector(event)
  1021. def OnAddVectorMisc(self, event):
  1022. """!Add vector menu"""
  1023. # start new map display if no display is available
  1024. if not self.curr_page:
  1025. self.NewDisplay(show=False)
  1026. point = wx.GetMousePosition()
  1027. vectmenu = wx.Menu()
  1028. addtheme = wx.MenuItem(vectmenu, -1, Icons["addthematic"].GetLabel())
  1029. addtheme.SetBitmap(Icons["addthematic"].GetBitmap(self.iconsize))
  1030. vectmenu.AppendItem(addtheme)
  1031. self.Bind(wx.EVT_MENU, self.AddThemeMap, addtheme)
  1032. addchart = wx.MenuItem(vectmenu, -1, Icons["addchart"].GetLabel())
  1033. addchart.SetBitmap(Icons["addchart"].GetBitmap(self.iconsize))
  1034. vectmenu.AppendItem(addchart)
  1035. self.Bind(wx.EVT_MENU, self.AddThemeChart, addchart)
  1036. # Popup the menu. If an item is selected then its handler
  1037. # will be called before PopupMenu returns.
  1038. self.PopupMenu(vectmenu)
  1039. vectmenu.Destroy()
  1040. # show map display
  1041. self.curr_page.maptree.mapdisplay.Show()
  1042. def OnAddOverlay(self, event):
  1043. """!Add overlay menu"""
  1044. # start new map display if no display is available
  1045. if not self.curr_page:
  1046. self.NewDisplay(show=False)
  1047. point = wx.GetMousePosition()
  1048. ovlmenu = wx.Menu()
  1049. addgrid = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addgrid"].GetLabel())
  1050. addgrid.SetBitmap(Icons["addgrid"].GetBitmap(self.iconsize))
  1051. ovlmenu.AppendItem(addgrid)
  1052. self.Bind(wx.EVT_MENU, self.AddGrid, addgrid)
  1053. addlabels = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addlabels"].GetLabel())
  1054. addlabels.SetBitmap(Icons["addlabels"].GetBitmap(self.iconsize))
  1055. ovlmenu.AppendItem(addlabels)
  1056. self.Bind(wx.EVT_MENU, self.OnAddLabels, addlabels)
  1057. addgeodesic = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addgeodesic"].GetLabel())
  1058. addgeodesic.SetBitmap(Icons["addgeodesic"].GetBitmap(self.iconsize))
  1059. ovlmenu.AppendItem(addgeodesic)
  1060. self.Bind(wx.EVT_MENU, self.AddGeodesic, addgeodesic)
  1061. addrhumb = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addrhumb"].GetLabel())
  1062. addrhumb.SetBitmap(Icons["addrhumb"].GetBitmap(self.iconsize))
  1063. ovlmenu.AppendItem(addrhumb)
  1064. self.Bind(wx.EVT_MENU, self.AddRhumb, addrhumb)
  1065. # Popup the menu. If an item is selected then its handler
  1066. # will be called before PopupMenu returns.
  1067. self.PopupMenu(ovlmenu)
  1068. ovlmenu.Destroy()
  1069. # show map display
  1070. self.curr_page.maptree.mapdisplay.Show()
  1071. def AddRaster(self, event):
  1072. self.notebook.SetSelection(0)
  1073. self.curr_page.maptree.AddLayer('raster')
  1074. def AddRaster3d(self, event):
  1075. self.notebook.SetSelection(0)
  1076. self.curr_page.maptree.AddLayer('3d-raster')
  1077. def AddRGB(self, event):
  1078. """!Add RGB layer"""
  1079. self.notebook.SetSelection(0)
  1080. self.curr_page.maptree.AddLayer('rgb')
  1081. def AddHIS(self, event):
  1082. """!Add HIS layer"""
  1083. self.notebook.SetSelection(0)
  1084. self.curr_page.maptree.AddLayer('his')
  1085. def AddShaded(self, event):
  1086. """!Add shaded relief map layer"""
  1087. self.notebook.SetSelection(0)
  1088. self.curr_page.maptree.AddLayer('shaded')
  1089. def AddRastarrow(self, event):
  1090. """!Add raster flow arrows map"""
  1091. self.notebook.SetSelection(0)
  1092. self.curr_page.maptree.AddLayer('rastarrow')
  1093. def AddRastnum(self, event):
  1094. """!Add raster map with cell numbers"""
  1095. self.notebook.SetSelection(0)
  1096. self.curr_page.maptree.AddLayer('rastnum')
  1097. def AddVector(self, event):
  1098. """!Add vector layer"""
  1099. self.notebook.SetSelection(0)
  1100. self.curr_page.maptree.AddLayer('vector')
  1101. def AddThemeMap(self, event):
  1102. """!Add thematic map layer"""
  1103. self.notebook.SetSelection(0)
  1104. self.curr_page.maptree.AddLayer('thememap')
  1105. def AddThemeChart(self, event):
  1106. """!Add thematic chart layer"""
  1107. self.notebook.SetSelection(0)
  1108. self.curr_page.maptree.AddLayer('themechart')
  1109. def OnAddCommand(self, event):
  1110. """!Add command line layer"""
  1111. # start new map display if no display is available
  1112. if not self.curr_page:
  1113. self.NewDisplay(show=False)
  1114. self.notebook.SetSelection(0)
  1115. self.curr_page.maptree.AddLayer('command')
  1116. # show map display
  1117. self.curr_page.maptree.mapdisplay.Show()
  1118. def OnAddGroup(self, event):
  1119. """!Add layer group"""
  1120. # start new map display if no display is available
  1121. if not self.curr_page:
  1122. self.NewDisplay(show=False)
  1123. self.notebook.SetSelection(0)
  1124. self.curr_page.maptree.AddLayer('group')
  1125. # show map display
  1126. self.curr_page.maptree.mapdisplay.Show()
  1127. def AddGrid(self, event):
  1128. """!Add layer grid"""
  1129. self.notebook.SetSelection(0)
  1130. self.curr_page.maptree.AddLayer('grid')
  1131. def AddGeodesic(self, event):
  1132. """!Add layer geodesic"""
  1133. self.notebook.SetSelection(0)
  1134. self.curr_page.maptree.AddLayer('geodesic')
  1135. def AddRhumb(self, event):
  1136. """!Add layer rhumb"""
  1137. self.notebook.SetSelection(0)
  1138. self.curr_page.maptree.AddLayer('rhumb')
  1139. def OnAddLabels(self, event):
  1140. """!Add layer vector labels"""
  1141. # start new map display if no display is available
  1142. if not self.curr_page:
  1143. self.NewDisplay(show=False)
  1144. self.notebook.SetSelection(0)
  1145. self.curr_page.maptree.AddLayer('labels')
  1146. # show map display
  1147. self.curr_page.maptree.mapdisplay.Show()
  1148. def OnDeleteLayer(self, event):
  1149. """
  1150. Delete selected map display layer in GIS Manager tree widget
  1151. """
  1152. if not self.curr_page or not self.curr_page.maptree.layer_selected:
  1153. self.MsgNoLayerSelected()
  1154. return
  1155. if UserSettings.Get(group='manager', key='askOnRemoveLayer', subkey='enabled'):
  1156. layerName = ''
  1157. for item in self.curr_page.maptree.GetSelections():
  1158. name = str(self.curr_page.maptree.GetItemText(item))
  1159. idx = name.find('(opacity')
  1160. if idx > -1:
  1161. layerName += '<' + name[:idx].strip(' ') + '>,\n'
  1162. else:
  1163. layerName += '<' + name + '>,\n'
  1164. layerName = layerName.rstrip(',\n')
  1165. if len(layerName) > 2: # <>
  1166. message = _("Do you want to remove map layer(s)\n%s\n"
  1167. "from layer tree?") % layerName
  1168. else:
  1169. message = _("Do you want to remove selected map layer(s) "
  1170. "from layer tree?")
  1171. dlg = wx.MessageDialog (parent=self, message=message,
  1172. caption=_("Remove map layer"),
  1173. style=wx.YES_NO | wx.YES_DEFAULT | wx.CANCEL | wx.ICON_QUESTION)
  1174. if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]:
  1175. dlg.Destroy()
  1176. return
  1177. dlg.Destroy()
  1178. for layer in self.curr_page.maptree.GetSelections():
  1179. if self.curr_page.maptree.GetPyData(layer)[0]['type'] == 'group':
  1180. self.curr_page.maptree.DeleteChildren(layer)
  1181. self.curr_page.maptree.Delete(layer)
  1182. def OnKey(self, event):
  1183. """!Check hotkey"""
  1184. kc = event.GetKeyCode()
  1185. if event.ControlDown():
  1186. if kc == wx.WXK_TAB:
  1187. # switch layer list / command output
  1188. if self.notebook.GetSelection() == 0:
  1189. self.notebook.SetSelection(1)
  1190. else:
  1191. self.notebook.SetSelection(0)
  1192. try:
  1193. ckc = chr(kc)
  1194. except ValueError:
  1195. event.Skip()
  1196. return
  1197. if event.AltDown():
  1198. if kc == 'R':
  1199. self.OnAddRaster(None)
  1200. elif kc == 'V':
  1201. self.OnAddVector(None)
  1202. event.Skip()
  1203. def OnQuit(self, event):
  1204. """!Quit GRASS"""
  1205. # quit wxGUI session
  1206. self.OnCloseWindow(event)
  1207. # quit GRASS shell
  1208. try:
  1209. pid = os.environ['GRASS_SHELL_PID']
  1210. except KeyError:
  1211. return
  1212. os.kill(int(pid), signal.SIGQUIT)
  1213. def OnCloseWindow(self, event):
  1214. """!Cleanup when wxGUI is quit"""
  1215. if not self.curr_page:
  1216. self._auimgr.UnInit()
  1217. self.Destroy()
  1218. return
  1219. maptree = self.curr_page.maptree
  1220. if UserSettings.Get(group='manager', key='askOnQuit', subkey='enabled'):
  1221. if self.workspaceFile:
  1222. message = _("Do you want to save changes in the workspace?")
  1223. else:
  1224. message = _("Do you want to store current settings "
  1225. "to workspace file?")
  1226. # ask user to save current settings
  1227. if maptree.GetCount() > 0:
  1228. dlg = wx.MessageDialog(self,
  1229. message=message,
  1230. caption=_("Quit GRASS GUI"),
  1231. style=wx.YES_NO | wx.YES_DEFAULT |
  1232. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  1233. ret = dlg.ShowModal()
  1234. if ret == wx.ID_YES:
  1235. if not self.workspaceFile:
  1236. self.OnWorkspaceSaveAs()
  1237. else:
  1238. self.SaveToWorkspaceFile(self.workspaceFile)
  1239. elif ret == wx.ID_CANCEL:
  1240. event.Veto()
  1241. dlg.Destroy()
  1242. return
  1243. dlg.Destroy()
  1244. # don't ask any more...
  1245. UserSettings.Set(group = 'manager', key = 'askOnQuit', subkey = 'enabled',
  1246. value = False)
  1247. for page in range(self.gm_cb.GetPageCount()):
  1248. self.gm_cb.GetPage(0).maptree.mapdisplay.OnCloseWindow(event)
  1249. self.gm_cb.DeleteAllPages()
  1250. self._auimgr.UnInit()
  1251. self.Destroy()
  1252. def MsgNoLayerSelected(self):
  1253. """!Show dialog message 'No layer selected'"""
  1254. wx.MessageBox(parent=self,
  1255. message=_("No map layer selected. Operation cancelled."),
  1256. caption=_("Message"),
  1257. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1258. class GMApp(wx.App):
  1259. def __init__(self, workspace = None):
  1260. """!Main GUI class.
  1261. @param workspace path to the workspace file
  1262. """
  1263. self.workspaceFile = workspace
  1264. # call parent class initializer
  1265. wx.App.__init__(self, False)
  1266. def OnInit(self):
  1267. """!Initialize all available image handlers
  1268. @return True
  1269. """
  1270. wx.InitAllImageHandlers()
  1271. # create splash screen
  1272. introImagePath = os.path.join(globalvar.ETCWXDIR, "images", "intro.png")
  1273. introImage = wx.Image(introImagePath, wx.BITMAP_TYPE_PNG)
  1274. introBmp = introImage.ConvertToBitmap()
  1275. wx.SplashScreen (bitmap=introBmp, splashStyle=wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
  1276. milliseconds=1500, parent=None, id=wx.ID_ANY)
  1277. wx.Yield()
  1278. # create and show main frame
  1279. mainframe = GMFrame(parent=None, id=wx.ID_ANY,
  1280. workspace = self.workspaceFile)
  1281. mainframe.Show()
  1282. self.SetTopWindow(mainframe)
  1283. return True
  1284. class Usage(Exception):
  1285. def __init__(self, msg):
  1286. self.msg = msg
  1287. def printHelp():
  1288. """!Print program help"""
  1289. print >> sys.stderr, "Usage:"
  1290. print >> sys.stderr, " python wxgui.py [options]"
  1291. print >> sys.stderr, "%sOptions:" % os.linesep
  1292. print >> sys.stderr, " -w\t--workspace file\tWorkspace file to load"
  1293. sys.exit(0)
  1294. def process_opt(opts, args):
  1295. """!Process command-line arguments"""
  1296. workspaceFile = None
  1297. for o, a in opts:
  1298. if o in ("-h", "--help"):
  1299. printHelp()
  1300. if o in ("-w", "--workspace"):
  1301. if a != '':
  1302. workspaceFile = str(a)
  1303. else:
  1304. workspaceFile = args.pop(0)
  1305. return (workspaceFile,)
  1306. def main(argv=None):
  1307. #
  1308. # process command-line arguments
  1309. #
  1310. if argv is None:
  1311. argv = sys.argv
  1312. try:
  1313. try:
  1314. opts, args = getopt.getopt(argv[1:], "hw:",
  1315. ["help", "workspace"])
  1316. except getopt.error, msg:
  1317. raise Usage(msg)
  1318. except Usage, err:
  1319. print >> sys.stderr, err.msg
  1320. print >> sys.stderr, "for help use --help"
  1321. printHelp()
  1322. workspaceFile = process_opt(opts, args)[0]
  1323. #
  1324. # run application
  1325. #
  1326. app = GMApp(workspaceFile)
  1327. # suppress wxPython logs
  1328. q = wx.LogNull()
  1329. app.MainLoop()
  1330. if __name__ == "__main__":
  1331. sys.exit(main())