goutput.py 44 KB

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