goutput.py 44 KB

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