goutput.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  1. """!
  2. @package goutput
  3. @brief Command output log widget
  4. Classes:
  5. - GMConsole
  6. - GMStc
  7. - GMStdout
  8. - GMStderr
  9. (C) 2007-2010 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 Martin Landa <landa.martin gmail.com>
  15. """
  16. import os
  17. import sys
  18. import textwrap
  19. import time
  20. import threading
  21. import Queue
  22. import codecs
  23. import wx
  24. import wx.stc
  25. from wx.lib.newevent import NewEvent
  26. import grass.script as grass
  27. import globalvar
  28. import gcmd
  29. import utils
  30. import preferences
  31. import menuform
  32. import prompt
  33. from debug import Debug
  34. from preferences import globalSettings as UserSettings
  35. from ghelp import SearchModuleWindow
  36. wxCmdOutput, EVT_CMD_OUTPUT = NewEvent()
  37. wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
  38. wxCmdRun, EVT_CMD_RUN = NewEvent()
  39. wxCmdDone, EVT_CMD_DONE = NewEvent()
  40. wxCmdAbort, EVT_CMD_ABORT = NewEvent()
  41. def GrassCmd(cmd, stdout = None, stderr = None):
  42. """!Return GRASS command thread"""
  43. return gcmd.CommandThread(cmd,
  44. stdout = stdout, stderr = stderr)
  45. class CmdThread(threading.Thread):
  46. """!Thread for GRASS commands"""
  47. requestId = 0
  48. def __init__(self, parent, requestQ, resultQ, **kwds):
  49. threading.Thread.__init__(self, **kwds)
  50. self.setDaemon(True)
  51. self.parent = parent # GMConsole
  52. self._want_abort_all = False
  53. self.requestQ = requestQ
  54. self.resultQ = resultQ
  55. self.start()
  56. def RunCmd(self, *args, **kwds):
  57. CmdThread.requestId += 1
  58. self.requestCmd = None
  59. self.requestQ.put((CmdThread.requestId, args, kwds))
  60. return CmdThread.requestId
  61. def SetId(self, id):
  62. """!Set starting id"""
  63. CmdThread.requestId = id
  64. def run(self):
  65. os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
  66. while True:
  67. requestId, args, kwds = self.requestQ.get()
  68. for key in ('callable', 'onDone', 'userData'):
  69. if key in kwds:
  70. vars()[key] = kwds[key]
  71. del kwds[key]
  72. else:
  73. vars()[key] = None
  74. if not vars()['callable']:
  75. vars()['callable'] = GrassCmd
  76. requestTime = time.time()
  77. event = wxCmdRun(cmd = args[0],
  78. pid = requestId)
  79. wx.PostEvent(self.parent, event)
  80. time.sleep(.1)
  81. self.requestCmd = vars()['callable'](*args, **kwds)
  82. if self._want_abort_all:
  83. self.requestCmd.abort()
  84. if self.requestQ.empty():
  85. self._want_abort_all = False
  86. self.resultQ.put((requestId, self.requestCmd.run()))
  87. try:
  88. returncode = self.requestCmd.module.returncode
  89. except AttributeError:
  90. returncode = 0 # being optimistic
  91. try:
  92. aborted = self.requestCmd.aborted
  93. except AttributeError:
  94. aborted = False
  95. time.sleep(.1)
  96. # set default color table for raster data
  97. if UserSettings.Get(group='cmd', key='rasterColorTable', subkey='enabled') and \
  98. args[0][0][:2] == 'r.':
  99. colorTable = UserSettings.Get(group='cmd', key='rasterColorTable', subkey='selection')
  100. mapName = None
  101. if args[0][0] == 'r.mapcalc':
  102. try:
  103. mapName = args[0][1].split('=', 1)[0].strip()
  104. except KeyError:
  105. pass
  106. else:
  107. moduleInterface = menuform.GUI(show = None).ParseCommand(args[0])
  108. outputParam = moduleInterface.get_param(value = 'output', raiseError = False)
  109. if outputParam and outputParam['prompt'] == 'raster':
  110. mapName = outputParam['value']
  111. if mapName:
  112. argsColor = list(args)
  113. argsColor[0] = [ 'r.colors',
  114. 'map=%s' % mapName,
  115. 'color=%s' % colorTable ]
  116. self.requestCmdColor = vars()['callable'](*argsColor, **kwds)
  117. self.resultQ.put((requestId, self.requestCmdColor.run()))
  118. event = wxCmdDone(cmd = args[0],
  119. aborted = aborted,
  120. returncode = returncode,
  121. time = requestTime,
  122. pid = requestId,
  123. onDone = vars()['onDone'],
  124. userData = vars()['userData'])
  125. # send event
  126. wx.PostEvent(self.parent, event)
  127. def abort(self, abortall = True):
  128. """!Abort command(s)"""
  129. if abortall:
  130. self._want_abort_all = True
  131. self.requestCmd.abort()
  132. if self.requestQ.empty():
  133. self._want_abort_all = False
  134. class GMConsole(wx.SplitterWindow):
  135. """!Create and manage output console for commands run by GUI.
  136. """
  137. def __init__(self, parent, id=wx.ID_ANY, margin=False, pageid=0,
  138. notebook = None,
  139. style=wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  140. **kwargs):
  141. wx.SplitterWindow.__init__(self, parent, id, style = style, *kwargs)
  142. self.SetName("GMConsole")
  143. self.panelOutput = wx.Panel(parent = self, id = wx.ID_ANY)
  144. self.panelPrompt = wx.Panel(parent = self, id = wx.ID_ANY)
  145. # initialize variables
  146. self.parent = parent # GMFrame | CmdPanel | ?
  147. if notebook:
  148. self._notebook = notebook
  149. else:
  150. self._notebook = self.parent.notebook
  151. self.lineWidth = 80
  152. self.pageid = pageid
  153. # remember position of line begining (used for '\r')
  154. self.linePos = -1
  155. #
  156. # create queues
  157. #
  158. self.requestQ = Queue.Queue()
  159. self.resultQ = Queue.Queue()
  160. #
  161. # progress bar
  162. #
  163. self.console_progressbar = wx.Gauge(parent=self.panelOutput, id=wx.ID_ANY,
  164. range=100, pos=(110, 50), size=(-1, 25),
  165. style=wx.GA_HORIZONTAL)
  166. self.console_progressbar.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
  167. #
  168. # text control for command output
  169. #
  170. self.cmd_output = GMStc(parent=self.panelOutput, id=wx.ID_ANY, margin=margin,
  171. wrap=None)
  172. self.cmd_output_timer = wx.Timer(self.cmd_output, id=wx.ID_ANY)
  173. self.cmd_output.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
  174. self.cmd_output.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  175. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  176. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  177. # search & command prompt
  178. self.cmd_prompt = prompt.GPromptSTC(parent = self)
  179. if self.parent.GetName() != 'LayerManager':
  180. self.search = None
  181. self.cmd_prompt.Hide()
  182. else:
  183. self.infoCollapseLabelExp = _("Click here to show search module engine")
  184. self.infoCollapseLabelCol = _("Click here to hide search module engine")
  185. self.searchPane = wx.CollapsiblePane(parent = self.panelOutput,
  186. label = self.infoCollapseLabelExp,
  187. style = wx.CP_DEFAULT_STYLE |
  188. wx.CP_NO_TLW_RESIZE | wx.EXPAND)
  189. self.MakeSearchPaneContent(self.searchPane.GetPane())
  190. self.searchPane.Collapse(True)
  191. self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnSearchPaneChanged, self.searchPane)
  192. self.search.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  193. #
  194. # stream redirection
  195. #
  196. self.cmd_stdout = GMStdout(self)
  197. self.cmd_stderr = GMStderr(self)
  198. #
  199. # thread
  200. #
  201. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  202. #
  203. # buttons
  204. #
  205. self.btn_console_clear = wx.Button(parent = self.panelPrompt, id = wx.ID_ANY,
  206. label = _("&Clear output"), size=(125,-1))
  207. self.btn_cmd_clear = wx.Button(parent = self.panelPrompt, id = wx.ID_ANY,
  208. label = _("C&lear command"), size=(125,-1))
  209. if self.parent.GetName() != 'LayerManager':
  210. self.btn_cmd_clear.Hide()
  211. self.btn_console_save = wx.Button(parent = self.panelPrompt, id = wx.ID_ANY,
  212. label = _("&Save output"), size=(125,-1))
  213. # abort
  214. self.btn_abort = wx.Button(parent = self.panelPrompt, id = wx.ID_ANY, label = _("&Abort command"),
  215. size=(125,-1))
  216. self.btn_abort.SetToolTipString(_("Abort the running command"))
  217. self.btn_abort.Enable(False)
  218. self.btn_cmd_clear.Bind(wx.EVT_BUTTON, self.cmd_prompt.OnCmdErase)
  219. self.btn_console_clear.Bind(wx.EVT_BUTTON, self.ClearHistory)
  220. self.btn_console_save.Bind(wx.EVT_BUTTON, self.SaveHistory)
  221. self.btn_abort.Bind(wx.EVT_BUTTON, self.OnCmdAbort)
  222. self.btn_abort.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  223. self.__layout()
  224. def __layout(self):
  225. """!Do layout"""
  226. OutputSizer = wx.BoxSizer(wx.VERTICAL)
  227. PromptSizer = wx.BoxSizer(wx.VERTICAL)
  228. ButtonSizer = wx.BoxSizer(wx.HORIZONTAL)
  229. if self.search and self.search.IsShown():
  230. OutputSizer.Add(item=self.searchPane, proportion=0,
  231. flag=wx.EXPAND | wx.ALL, border=3)
  232. OutputSizer.Add(item=self.cmd_output, proportion=1,
  233. flag=wx.EXPAND | wx.ALL, border=3)
  234. OutputSizer.Add(item=self.console_progressbar, proportion=0,
  235. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=3)
  236. PromptSizer.Add(item=self.cmd_prompt, proportion=1,
  237. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=3)
  238. ButtonSizer.Add(item=self.btn_console_clear, proportion=0,
  239. flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE | wx.ALL, border=5)
  240. ButtonSizer.Add(item=self.btn_console_save, proportion=0,
  241. flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE | wx.ALL, border=5)
  242. ButtonSizer.Add(item=self.btn_cmd_clear, proportion=0,
  243. flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE | wx.ALL, border=5)
  244. ButtonSizer.Add(item=self.btn_abort, proportion=0,
  245. flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE | wx.ALL, border=5)
  246. PromptSizer.Add(item=ButtonSizer, proportion=0,
  247. flag=wx.ALIGN_CENTER)
  248. OutputSizer.Fit(self)
  249. OutputSizer.SetSizeHints(self)
  250. PromptSizer.Fit(self)
  251. PromptSizer.SetSizeHints(self)
  252. self.panelOutput.SetSizer(OutputSizer)
  253. self.panelPrompt.SetSizer(PromptSizer)
  254. # split window
  255. if self.parent.GetName() == 'LayerManager':
  256. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -50)
  257. self.SetMinimumPaneSize(self.btn_cmd_clear.GetSize()[1] + 50)
  258. else:
  259. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -45)
  260. self.SetMinimumPaneSize(self.btn_cmd_clear.GetSize()[1] + 10)
  261. self.SetSashGravity(1.0)
  262. # layout
  263. self.SetAutoLayout(True)
  264. self.Layout()
  265. def MakeSearchPaneContent(self, pane):
  266. """!Create search pane"""
  267. border = wx.BoxSizer(wx.VERTICAL)
  268. self.search = SearchModuleWindow(parent = pane, cmdPrompt = self.cmd_prompt)
  269. border.Add(item = self.search, proportion = 0,
  270. flag = wx.EXPAND | wx.ALL, border = 1)
  271. pane.SetSizer(border)
  272. border.Fit(pane)
  273. def OnSearchPaneChanged(self, event):
  274. """!Collapse search module box"""
  275. if self.searchPane.IsExpanded():
  276. self.searchPane.SetLabel(self.infoCollapseLabelCol)
  277. else:
  278. self.searchPane.SetLabel(self.infoCollapseLabelExp)
  279. self.panelOutput.Layout()
  280. self.panelOutput.SendSizeEvent()
  281. def GetPanel(self, prompt = True):
  282. """!Get panel
  283. @param prompt get prompt / output panel
  284. @return wx.Panel reference
  285. """
  286. if prompt:
  287. return self.panelPrompt
  288. return self.panelOutput
  289. def Redirect(self):
  290. """!Redirect stdout/stderr
  291. @return True redirected
  292. @return False failed
  293. """
  294. if Debug.GetLevel() == 0 and int(grass.gisenv().get('DEBUG', 0)) == 0:
  295. # don't redirect when debugging is enabled
  296. sys.stdout = self.cmd_stdout
  297. sys.stderr = self.cmd_stderr
  298. return True
  299. else:
  300. sys.stdout = sys.__stdout__
  301. sys.stderr = sys.__stderr__
  302. return False
  303. def WriteLog(self, text, style = None, wrap = None,
  304. switchPage = False):
  305. """!Generic method for writing log message in
  306. given style
  307. @param line text line
  308. @param style text style (see GMStc)
  309. @param stdout write to stdout or stderr
  310. """
  311. self.cmd_output.SetStyle()
  312. if switchPage and \
  313. self._notebook.GetSelection() != self.parent.goutput.pageid:
  314. self._notebook.SetSelection(self.parent.goutput.pageid)
  315. if not style:
  316. style = self.cmd_output.StyleDefault
  317. # p1 = self.cmd_output.GetCurrentPos()
  318. p1 = self.cmd_output.GetEndStyled()
  319. # self.cmd_output.GotoPos(p1)
  320. self.cmd_output.DocumentEnd()
  321. for line in text.splitlines():
  322. # fill space
  323. if len(line) < self.lineWidth:
  324. diff = self.lineWidth - len(line)
  325. line += diff * ' '
  326. self.cmd_output.AddTextWrapped(line, wrap=wrap) # adds '\n'
  327. p2 = self.cmd_output.GetCurrentPos()
  328. self.cmd_output.StartStyling(p1, 0xff)
  329. self.cmd_output.SetStyling(p2 - p1, style)
  330. self.cmd_output.EnsureCaretVisible()
  331. def WriteCmdLog(self, line, pid=None):
  332. """!Write message in selected style"""
  333. if pid:
  334. line = '(' + str(pid) + ') ' + line
  335. self.WriteLog(line, style=self.cmd_output.StyleCommand, switchPage = True)
  336. def WriteWarning(self, line):
  337. """!Write message in warning style"""
  338. self.WriteLog(line, style=self.cmd_output.StyleWarning, switchPage = True)
  339. def WriteError(self, line):
  340. """!Write message in error style"""
  341. self.WriteLog(line, style = self.cmd_output.StyleError, switchPage = True)
  342. def RunCmd(self, command, compReg = True, switchPage = False,
  343. onDone = None):
  344. """!Run command typed into console command prompt (GPrompt).
  345. @todo Display commands (*.d) are captured and processed
  346. separately by mapdisp.py. Display commands are rendered in map
  347. display widget that currently has the focus (as indicted by
  348. mdidx).
  349. @param command command given as a list (produced e.g. by utils.split())
  350. @param compReg True use computation region
  351. @param switchPage switch to output page
  352. @param onDone function to be called when command is finished
  353. """
  354. if len(command) == 0:
  355. Debug.msg(2, "GPrompt:RunCmd(): empty command")
  356. return
  357. # update history file
  358. env = grass.gisenv()
  359. try:
  360. fileHistory = codecs.open(os.path.join(env['GISDBASE'],
  361. env['LOCATION_NAME'],
  362. env['MAPSET'],
  363. '.bash_history'),
  364. encoding = 'utf-8', mode = 'a')
  365. except IOError, e:
  366. self.WriteError(e)
  367. fileHistory = None
  368. if fileHistory:
  369. try:
  370. fileHistory.write(' '.join(command) + os.linesep)
  371. finally:
  372. fileHistory.close()
  373. # update history items
  374. if self.parent.GetName() == 'LayerManager':
  375. try:
  376. self.parent.cmdinput.SetHistoryItems()
  377. except AttributeError:
  378. pass
  379. if command[0] in globalvar.grassCmd['all']:
  380. # send GRASS command without arguments to GUI command interface
  381. # except display commands (they are handled differently)
  382. if self.parent.GetName() == "LayerManager" and \
  383. command[0][0:2] == "d.":
  384. # display GRASS commands
  385. try:
  386. layertype = {'d.rast' : 'raster',
  387. 'd.rast3d' : '3d-raster',
  388. 'd.rgb' : 'rgb',
  389. 'd.his' : 'his',
  390. 'd.shaded' : 'shaded',
  391. 'd.legend' : 'rastleg',
  392. 'd.rast.arrow' : 'rastarrow',
  393. 'd.rast.num' : 'rastnum',
  394. 'd.vect' : 'vector',
  395. 'd.thematic.area': 'thememap',
  396. 'd.vect.chart' : 'themechart',
  397. 'd.grid' : 'grid',
  398. 'd.geodesic' : 'geodesic',
  399. 'd.rhumbline' : 'rhumb',
  400. 'd.labels' : 'labels',
  401. 'd.barscale' : 'barscale'}[command[0]]
  402. except KeyError:
  403. gcmd.GMessage(parent = self.parent,
  404. message = _("Command '%s' not yet implemented in the WxGUI. "
  405. "Try adding it as a command layer instead.") % command[0])
  406. return None
  407. if layertype == 'barscale':
  408. self.parent.curr_page.maptree.GetMapDisplay().OnAddBarscale(None)
  409. elif layertype == 'rastleg':
  410. self.parent.curr_page.maptree.GetMapDisplay().OnAddLegend(None)
  411. else:
  412. # add layer into layer tree
  413. lname, found = utils.GetLayerNameFromCmd(command, fullyQualified = True,
  414. layerType = layertype)
  415. if self.parent.GetName() == "LayerManager":
  416. self.parent.curr_page.maptree.AddLayer(ltype = layertype,
  417. lname = lname,
  418. lcmd = command)
  419. else:
  420. # other GRASS commands (r|v|g|...)
  421. # switch to 'Command output' if required
  422. if switchPage:
  423. if self._notebook.GetSelection() != self.parent.goutput.pageid:
  424. self._notebook.SetSelection(self.parent.goutput.pageid)
  425. self.parent.SetFocus()
  426. self.parent.Raise()
  427. # activate computational region (set with g.region)
  428. # for all non-display commands.
  429. if compReg:
  430. tmpreg = os.getenv("GRASS_REGION")
  431. if "GRASS_REGION" in os.environ:
  432. del os.environ["GRASS_REGION"]
  433. if len(command) == 1:
  434. import menuform
  435. task = menuform.GUI().ParseInterface(command)
  436. # if not task.has_required():
  437. # task = None # run command
  438. else:
  439. task = None
  440. if task and command[0] not in ('v.krige'):
  441. # process GRASS command without argument
  442. menuform.GUI(parent = self).ParseCommand(command)
  443. else:
  444. # process GRASS command with argument
  445. self.cmdThread.RunCmd(command, stdout = self.cmd_stdout, stderr = self.cmd_stderr,
  446. onDone = onDone)
  447. self.cmd_output_timer.Start(50)
  448. return None
  449. # deactivate computational region and return to display settings
  450. if compReg and tmpreg:
  451. os.environ["GRASS_REGION"] = tmpreg
  452. else:
  453. # Send any other command to the shell. Send output to
  454. # console output window
  455. if len(command) == 1:
  456. import menuform
  457. try:
  458. task = menuform.GUI().ParseInterface(command)
  459. except:
  460. task = None
  461. else:
  462. task = None
  463. if task:
  464. # process GRASS command without argument
  465. menuform.GUI(parent = self).ParseCommand(command)
  466. else:
  467. self.cmdThread.RunCmd(command, stdout = self.cmd_stdout, stderr = self.cmd_stderr,
  468. onDone = onDone)
  469. self.cmd_output_timer.Start(50)
  470. return None
  471. def ClearHistory(self, event):
  472. """!Clear history of commands"""
  473. self.cmd_output.SetReadOnly(False)
  474. self.cmd_output.ClearAll()
  475. self.cmd_output.SetReadOnly(True)
  476. self.console_progressbar.SetValue(0)
  477. def GetProgressBar(self):
  478. """!Return progress bar widget"""
  479. return self.console_progressbar
  480. def GetLog(self, err = False):
  481. """!Get widget used for logging
  482. @param err True to get stderr widget
  483. """
  484. if err:
  485. return self.cmd_stderr
  486. return self.cmd_stdout
  487. def SaveHistory(self, event):
  488. """!Save history of commands"""
  489. self.history = self.cmd_output.GetSelectedText()
  490. if self.history == '':
  491. self.history = self.cmd_output.GetText()
  492. # add newline if needed
  493. if len(self.history) > 0 and self.history[-1] != '\n':
  494. self.history += '\n'
  495. wildcard = "Text file (*.txt)|*.txt"
  496. dlg = wx.FileDialog(
  497. self, message=_("Save file as..."), defaultDir=os.getcwd(),
  498. defaultFile="grass_cmd_history.txt", wildcard=wildcard,
  499. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  500. # Show the dialog and retrieve the user response. If it is the OK response,
  501. # process the data.
  502. if dlg.ShowModal() == wx.ID_OK:
  503. path = dlg.GetPath()
  504. output = open(path, "w")
  505. output.write(self.history)
  506. output.close()
  507. dlg.Destroy()
  508. def GetCmd(self):
  509. """!Get running command or None"""
  510. return self.requestQ.get()
  511. def OnUpdateStatusBar(self, event):
  512. """!Update statusbar text"""
  513. if event.GetString():
  514. nItems = len(self.cmd_prompt.GetCommandItems())
  515. self.parent.SetStatusText(_('%d modules match') % nItems, 0)
  516. else:
  517. self.parent.SetStatusText('', 0)
  518. event.Skip()
  519. def OnCmdOutput(self, event):
  520. """!Print command output"""
  521. message = event.text
  522. type = event.type
  523. if self._notebook.GetSelection() != self.parent.goutput.pageid:
  524. textP = self._notebook.GetPageText(self.parent.goutput.pageid)
  525. if textP[-1] != ')':
  526. textP += ' (...)'
  527. self._notebook.SetPageText(self.parent.goutput.pageid,
  528. textP)
  529. # message prefix
  530. if type == 'warning':
  531. messege = 'WARNING: ' + message
  532. elif type == 'error':
  533. message = 'ERROR: ' + message
  534. p1 = self.cmd_output.GetEndStyled()
  535. self.cmd_output.GotoPos(p1)
  536. if '\b' in message:
  537. if self.linepos < 0:
  538. self.linepos = p1
  539. last_c = ''
  540. for c in message:
  541. if c == '\b':
  542. self.linepos -= 1
  543. else:
  544. if c == '\r':
  545. pos = self.cmd_output.GetCurLine()[1]
  546. # self.cmd_output.SetCurrentPos(pos)
  547. else:
  548. self.cmd_output.SetCurrentPos(self.linepos)
  549. self.cmd_output.ReplaceSelection(c)
  550. self.linepos = self.cmd_output.GetCurrentPos()
  551. if c != ' ':
  552. last_c = c
  553. if last_c not in ('0123456789'):
  554. self.cmd_output.AddTextWrapped('\n', wrap=None)
  555. self.linepos = -1
  556. else:
  557. self.linepos = -1 # don't force position
  558. if '\n' not in message:
  559. self.cmd_output.AddTextWrapped(message, wrap=60)
  560. else:
  561. self.cmd_output.AddTextWrapped(message, wrap=None)
  562. p2 = self.cmd_output.GetCurrentPos()
  563. if p2 >= p1:
  564. self.cmd_output.StartStyling(p1, 0xff)
  565. if type == 'error':
  566. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleError)
  567. elif type == 'warning':
  568. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleWarning)
  569. elif type == 'message':
  570. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleMessage)
  571. else: # unknown
  572. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleUnknown)
  573. self.cmd_output.EnsureCaretVisible()
  574. def OnCmdProgress(self, event):
  575. """!Update progress message info"""
  576. self.console_progressbar.SetValue(event.value)
  577. def OnCmdAbort(self, event):
  578. """!Abort running command"""
  579. self.cmdThread.abort()
  580. def OnCmdRun(self, event):
  581. """!Run command"""
  582. if self.parent.GetName() == 'Modeler':
  583. self.parent.OnCmdRun(event)
  584. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  585. self.btn_abort.Enable()
  586. def OnCmdDone(self, event):
  587. """!Command done (or aborted)"""
  588. if self.parent.GetName() == 'Modeler':
  589. self.parent.OnCmdDone(event)
  590. if event.aborted:
  591. # Thread aborted (using our convention of None return)
  592. self.WriteLog(_('Please note that the data are left in inconsistent state '
  593. 'and may be corrupted'), self.cmd_output.StyleWarning)
  594. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  595. _('Command aborted'),
  596. (time.time() - event.time)))
  597. # pid=self.cmdThread.requestId)
  598. self.btn_abort.Enable(False)
  599. else:
  600. try:
  601. # Process results here
  602. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  603. _('Command finished'),
  604. (time.time() - event.time)))
  605. except KeyError:
  606. # stopped deamon
  607. pass
  608. self.btn_abort.Enable(False)
  609. if event.onDone:
  610. event.onDone(cmd = event.cmd, returncode = event.returncode)
  611. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  612. self.cmd_output_timer.Stop()
  613. if event.cmd[0] == 'g.gisenv':
  614. Debug.SetLevel()
  615. self.Redirect()
  616. if self.parent.GetName() == "LayerManager":
  617. self.btn_abort.Enable(False)
  618. if event.cmd[0] not in globalvar.grassCmd['all'] or \
  619. event.cmd[0] == 'r.mapcalc':
  620. return
  621. display = self.parent.GetLayerTree().GetMapDisplay()
  622. if not display or not display.IsAutoRendered():
  623. return
  624. mapLayers = map(lambda x: x.GetName(),
  625. display.GetRender().GetListOfLayers(l_type = 'raster') +
  626. display.GetRender().GetListOfLayers(l_type = 'vector'))
  627. try:
  628. task = menuform.GUI(show = None).ParseCommand(event.cmd)
  629. except gcmd.GException:
  630. task = None
  631. return
  632. for p in task.get_options()['params']:
  633. if p.get('prompt', '') not in ('raster', 'vector'):
  634. continue
  635. mapName = p.get('value', '')
  636. if '@' not in mapName:
  637. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  638. if mapName in mapLayers:
  639. display.GetWindow().UpdateMap(render = True)
  640. return
  641. elif self.parent.GetName() == 'Modeler':
  642. pass
  643. else: # standalone dialogs
  644. dialog = self.parent.parent
  645. if hasattr(self.parent.parent, "btn_abort"):
  646. dialog.btn_abort.Enable(False)
  647. if hasattr(self.parent.parent, "btn_cancel"):
  648. dialog.btn_cancel.Enable(True)
  649. if hasattr(self.parent.parent, "btn_clipboard"):
  650. dialog.btn_clipboard.Enable(True)
  651. if hasattr(self.parent.parent, "btn_help"):
  652. dialog.btn_help.Enable(True)
  653. if hasattr(self.parent.parent, "btn_run"):
  654. dialog.btn_run.Enable(True)
  655. if event.returncode == 0 and not event.aborted:
  656. try:
  657. winName = self.parent.parent.parent.GetName()
  658. except AttributeError:
  659. winName = ''
  660. if winName == 'LayerManager':
  661. mapTree = self.parent.parent.parent.GetLayerTree()
  662. elif winName == 'LayerTree':
  663. mapTree = self.parent.parent.parent
  664. elif winName: # GMConsole
  665. mapTree = self.parent.parent.parent.parent.GetLayerTree()
  666. else:
  667. mapTree = None
  668. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  669. if hasattr(dialog, "addbox") and dialog.addbox.IsChecked():
  670. # add created maps into layer tree
  671. for p in dialog.task.get_options()['params']:
  672. prompt = p.get('prompt', '')
  673. if prompt in ('raster', 'vector', '3d-raster') and \
  674. p.get('age', 'old') == 'new' and \
  675. p.get('value', None):
  676. name, found = utils.GetLayerNameFromCmd(cmd, fullyQualified = True,
  677. param = p.get('name', ''))
  678. if mapTree.GetMap().GetListOfLayers(l_name = name):
  679. continue
  680. if prompt == 'raster':
  681. lcmd = ['d.rast',
  682. 'map=%s' % name]
  683. else:
  684. lcmd = ['d.vect',
  685. 'map=%s' % name]
  686. mapTree.AddLayer(ltype = prompt,
  687. lcmd = lcmd,
  688. lname = name)
  689. if hasattr(dialog, "get_dcmd") and \
  690. dialog.get_dcmd is None and \
  691. hasattr(dialog, "closebox") and \
  692. dialog.closebox.IsChecked() and \
  693. (event.returncode == 0 or event.aborted):
  694. self.cmd_output.Update()
  695. time.sleep(2)
  696. dialog.Close()
  697. def OnProcessPendingOutputWindowEvents(self, event):
  698. self.ProcessPendingEvents()
  699. class GMStdout:
  700. """!GMConsole standard output
  701. Based on FrameOutErr.py
  702. Name: FrameOutErr.py
  703. Purpose: Redirecting stdout / stderr
  704. Author: Jean-Michel Fauth, Switzerland
  705. Copyright: (c) 2005-2007 Jean-Michel Fauth
  706. Licence: GPL
  707. """
  708. def __init__(self, parent):
  709. self.parent = parent # GMConsole
  710. def write(self, s):
  711. if len(s) == 0 or s == '\n':
  712. return
  713. for line in s.splitlines():
  714. if len(line) == 0:
  715. continue
  716. evt = wxCmdOutput(text=line + '\n',
  717. type='')
  718. wx.PostEvent(self.parent.cmd_output, evt)
  719. class GMStderr:
  720. """!GMConsole standard error output
  721. Based on FrameOutErr.py
  722. Name: FrameOutErr.py
  723. Purpose: Redirecting stdout / stderr
  724. Author: Jean-Michel Fauth, Switzerland
  725. Copyright: (c) 2005-2007 Jean-Michel Fauth
  726. Licence: GPL
  727. """
  728. def __init__(self, parent):
  729. self.parent = parent # GMConsole
  730. self.type = ''
  731. self.message = ''
  732. self.printMessage = False
  733. def flush(self):
  734. pass
  735. def write(self, s):
  736. if "GtkPizza" in s:
  737. return
  738. # remove/replace escape sequences '\b' or '\r' from stream
  739. progressValue = -1
  740. for line in s.splitlines():
  741. if len(line) == 0:
  742. continue
  743. if 'GRASS_INFO_PERCENT' in line:
  744. value = int(line.rsplit(':', 1)[1].strip())
  745. if value >= 0 and value < 100:
  746. progressValue = value
  747. else:
  748. progressValue = 0
  749. elif 'GRASS_INFO_MESSAGE' in line:
  750. self.type = 'message'
  751. self.message += line.split(':', 1)[1].strip() + '\n'
  752. elif 'GRASS_INFO_WARNING' in line:
  753. self.type = 'warning'
  754. self.message += line.split(':', 1)[1].strip() + '\n'
  755. elif 'GRASS_INFO_ERROR' in line:
  756. self.type = 'error'
  757. self.message += line.split(':', 1)[1].strip() + '\n'
  758. elif 'GRASS_INFO_END' in line:
  759. self.printMessage = True
  760. elif self.type == '':
  761. if len(line) == 0:
  762. continue
  763. evt = wxCmdOutput(text=line,
  764. type='')
  765. wx.PostEvent(self.parent.cmd_output, evt)
  766. elif len(line) > 0:
  767. self.message += line.strip() + '\n'
  768. if self.printMessage and len(self.message) > 0:
  769. evt = wxCmdOutput(text=self.message,
  770. type=self.type)
  771. wx.PostEvent(self.parent.cmd_output, evt)
  772. self.type = ''
  773. self.message = ''
  774. self.printMessage = False
  775. # update progress message
  776. if progressValue > -1:
  777. # self.gmgauge.SetValue(progressValue)
  778. evt = wxCmdProgress(value=progressValue)
  779. wx.PostEvent(self.parent.console_progressbar, evt)
  780. class GMStc(wx.stc.StyledTextCtrl):
  781. """!Styled GMConsole
  782. Based on FrameOutErr.py
  783. Name: FrameOutErr.py
  784. Purpose: Redirecting stdout / stderr
  785. Author: Jean-Michel Fauth, Switzerland
  786. Copyright: (c) 2005-2007 Jean-Michel Fauth
  787. Licence: GPL
  788. """
  789. def __init__(self, parent, id, margin=False, wrap=None):
  790. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  791. self.parent = parent
  792. self.SetUndoCollection(True)
  793. self.SetReadOnly(True)
  794. #
  795. # styles
  796. #
  797. self.SetStyle()
  798. #
  799. # line margins
  800. #
  801. # TODO print number only from cmdlog
  802. self.SetMarginWidth(1, 0)
  803. self.SetMarginWidth(2, 0)
  804. if margin:
  805. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  806. self.SetMarginWidth(0, 30)
  807. else:
  808. self.SetMarginWidth(0, 0)
  809. #
  810. # miscellaneous
  811. #
  812. self.SetViewWhiteSpace(False)
  813. self.SetTabWidth(4)
  814. self.SetUseTabs(False)
  815. self.UsePopUp(True)
  816. self.SetSelBackground(True, "#FFFF00")
  817. self.SetUseHorizontalScrollBar(True)
  818. #
  819. # bindings
  820. #
  821. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  822. def SetStyle(self):
  823. """!Set styles for styled text output windows with type face
  824. and point size selected by user (Courier New 10 is default)"""
  825. settings = preferences.Settings()
  826. typeface = settings.Get(group='display', key='outputfont', subkey='type')
  827. if typeface == "": typeface = "Courier New"
  828. typesize = settings.Get(group='display', key='outputfont', subkey='size')
  829. if typesize == None or typesize <= 0: typesize = 10
  830. typesize = float(typesize)
  831. self.StyleDefault = 0
  832. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  833. self.StyleCommand = 1
  834. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  835. self.StyleOutput = 2
  836. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  837. # fatal error
  838. self.StyleError = 3
  839. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  840. # warning
  841. self.StyleWarning = 4
  842. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  843. # message
  844. self.StyleMessage = 5
  845. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  846. # unknown
  847. self.StyleUnknown = 6
  848. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  849. # default and clear => init
  850. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  851. self.StyleClearAll()
  852. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  853. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  854. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  855. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  856. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  857. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  858. def OnDestroy(self, evt):
  859. """!The clipboard contents can be preserved after
  860. the app has exited"""
  861. wx.TheClipboard.Flush()
  862. evt.Skip()
  863. def AddTextWrapped(self, txt, wrap=None):
  864. """!Add string to text area.
  865. String is wrapped and linesep is also added to the end
  866. of the string"""
  867. # allow writing to output window
  868. self.SetReadOnly(False)
  869. if wrap:
  870. txt = textwrap.fill(txt, wrap) + '\n'
  871. else:
  872. if txt[-1] != '\n':
  873. txt += '\n'
  874. if '\r' in txt:
  875. self.parent.linePos = -1
  876. for seg in txt.split('\r'):
  877. if self.parent.linePos > -1:
  878. self.SetCurrentPos(self.parent.linePos)
  879. self.ReplaceSelection(seg)
  880. else:
  881. self.parent.linePos = self.GetCurrentPos()
  882. self.AddText(seg)
  883. else:
  884. self.parent.linePos = self.GetCurrentPos()
  885. try:
  886. self.AddText(txt)
  887. except UnicodeDecodeError:
  888. enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
  889. if enc:
  890. txt = unicode(txt, enc)
  891. elif 'GRASS_DB_ENCODING' in os.environ:
  892. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  893. else:
  894. txt = utils.EncodeString(txt)
  895. self.AddText(txt)
  896. # reset output window to read only
  897. self.SetReadOnly(True)