goutput.py 44 KB

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