goutput.py 43 KB

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