goutput.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. """!
  2. @package gui_core.goutput
  3. @brief Command output widgets
  4. Classes:
  5. - CmdThread
  6. - GMConsole
  7. - GMStc
  8. - GMStdout
  9. - GMStderr
  10. (C) 2007-2011 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Michael Barton (Arizona State University)
  15. @author Martin Landa <landa.martin gmail.com>
  16. @author Vaclav Petras <wenzeslaus gmail.com> (copy&paste customization)
  17. """
  18. import os
  19. import sys
  20. import textwrap
  21. import time
  22. import threading
  23. import Queue
  24. import codecs
  25. import locale
  26. import wx
  27. import wx.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 gui_core.forms import GUI
  35. from gui_core.prompt import GPromptSTC
  36. from core.debug import Debug
  37. from core.settings import UserSettings, Settings
  38. from gui_core.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 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 = 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 = 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.panelOutput, id = wx.ID_ANY,
  205. label = " %s " % _("Output window"))
  206. self.cmdBox = wx.StaticBox(parent = self.panelOutput, id = wx.ID_ANY,
  207. label = " %s " % _("Command prompt"))
  208. # buttons
  209. self.btnOutputClear = wx.Button(parent = self.panelOutput, id = wx.ID_CLEAR)
  210. self.btnOutputClear.SetToolTipString(_("Clear output window content"))
  211. self.btnCmdClear = wx.Button(parent = self.panelOutput, 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.panelOutput, id = wx.ID_SAVE)
  216. self.btnOutputSave.SetToolTipString(_("Save output window content to the file"))
  217. # abort
  218. self.btnCmdAbort = wx.Button(parent = self.panelOutput, 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. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  231. outBtnSizer = wx.StaticBoxSizer(self.outputBox, wx.HORIZONTAL)
  232. cmdBtnSizer = wx.StaticBoxSizer(self.cmdBox, wx.HORIZONTAL)
  233. if self.cmdPrompt.IsShown():
  234. promptSizer = wx.BoxSizer(wx.VERTICAL)
  235. promptSizer.Add(item = self.cmdPrompt, proportion = 1,
  236. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border = 3)
  237. if self.search and self.search.IsShown():
  238. outputSizer.Add(item = self.searchPane, proportion = 0,
  239. flag = wx.EXPAND | wx.ALL, border = 3)
  240. outputSizer.Add(item = self.cmdOutput, proportion = 1,
  241. flag = wx.EXPAND | wx.ALL, border = 3)
  242. outputSizer.Add(item = self.progressbar, proportion = 0,
  243. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 3)
  244. outBtnSizer.Add(item = self.btnOutputClear, proportion = 1,
  245. flag = wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT, border = 5)
  246. outBtnSizer.Add(item = self.btnOutputSave, proportion = 1,
  247. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 5)
  248. cmdBtnSizer.Add(item = self.btnCmdClear, proportion = 1,
  249. flag = wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT, border = 5)
  250. cmdBtnSizer.Add(item = self.btnCmdAbort, proportion = 1,
  251. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
  252. btnSizer.Add(item = outBtnSizer, proportion = 1,
  253. flag = wx.ALL | wx.ALIGN_CENTER, border = 5)
  254. btnSizer.Add(item = cmdBtnSizer, proportion = 1,
  255. flag = wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, border = 5)
  256. outputSizer.Add(item = btnSizer, proportion = 0,
  257. flag = wx.EXPAND)
  258. outputSizer.Fit(self)
  259. outputSizer.SetSizeHints(self)
  260. self.panelOutput.SetSizer(outputSizer)
  261. if self.cmdPrompt.IsShown():
  262. promptSizer.Fit(self)
  263. promptSizer.SetSizeHints(self)
  264. self.panelPrompt.SetSizer(promptSizer)
  265. # split window
  266. if self.cmdPrompt.IsShown():
  267. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -50)
  268. else:
  269. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -45)
  270. self.Unsplit()
  271. self.SetMinimumPaneSize(self.btnCmdClear.GetSize()[1] + 25)
  272. self.SetSashGravity(1.0)
  273. # layout
  274. self.SetAutoLayout(True)
  275. self.Layout()
  276. def MakeSearchPaneContent(self, pane):
  277. """!Create search pane"""
  278. border = wx.BoxSizer(wx.VERTICAL)
  279. self.search = SearchModuleWindow(parent = pane, cmdPrompt = self.cmdPrompt)
  280. border.Add(item = self.search, proportion = 0,
  281. flag = wx.EXPAND | wx.ALL, border = 1)
  282. pane.SetSizer(border)
  283. border.Fit(pane)
  284. def OnSearchPaneChanged(self, event):
  285. """!Collapse search module box"""
  286. if self.searchPane.IsExpanded():
  287. self.searchPane.SetLabel(self.infoCollapseLabelCol)
  288. else:
  289. self.searchPane.SetLabel(self.infoCollapseLabelExp)
  290. self.panelOutput.Layout()
  291. self.panelOutput.SendSizeEvent()
  292. def GetPanel(self, prompt = True):
  293. """!Get panel
  294. @param prompt get prompt / output panel
  295. @return wx.Panel reference
  296. """
  297. if prompt:
  298. return self.panelPrompt
  299. return self.panelOutput
  300. def Redirect(self):
  301. """!Redirect stdout/stderr
  302. """
  303. if Debug.GetLevel() == 0 and int(grass.gisenv().get('DEBUG', 0)) == 0:
  304. # don't redirect when debugging is enabled
  305. sys.stdout = self.cmdStdOut
  306. sys.stderr = self.cmdStdErr
  307. else:
  308. enc = locale.getdefaultlocale()[1]
  309. if enc:
  310. sys.stdout = codecs.getwriter(enc)(sys.__stdout__)
  311. sys.stderr = codecs.getwriter(enc)(sys.__stderr__)
  312. else:
  313. sys.stdout = sys.__stdout__
  314. sys.stderr = sys.__stderr__
  315. def WriteLog(self, text, style = None, wrap = None,
  316. switchPage = False):
  317. """!Generic method for writing log message in
  318. given style
  319. @param line text line
  320. @param style text style (see GMStc)
  321. @param stdout write to stdout or stderr
  322. """
  323. self.cmdOutput.SetStyle()
  324. if switchPage:
  325. self._notebook.SetSelectionByName('output')
  326. if not style:
  327. style = self.cmdOutput.StyleDefault
  328. # p1 = self.cmdOutput.GetCurrentPos()
  329. p1 = self.cmdOutput.GetEndStyled()
  330. # self.cmdOutput.GotoPos(p1)
  331. self.cmdOutput.DocumentEnd()
  332. for line in text.splitlines():
  333. # fill space
  334. if len(line) < self.lineWidth:
  335. diff = self.lineWidth - len(line)
  336. line += diff * ' '
  337. self.cmdOutput.AddTextWrapped(line, wrap = wrap) # adds '\n'
  338. p2 = self.cmdOutput.GetCurrentPos()
  339. self.cmdOutput.StartStyling(p1, 0xff)
  340. self.cmdOutput.SetStyling(p2 - p1, style)
  341. self.cmdOutput.EnsureCaretVisible()
  342. def WriteCmdLog(self, line, pid = None, switchPage = True):
  343. """!Write message in selected style
  344. @param line message to be printed
  345. @param pid process pid or None
  346. @param switchPage True to switch page
  347. """
  348. if pid:
  349. line = '(' + str(pid) + ') ' + line
  350. self.WriteLog(line, style = self.cmdOutput.StyleCommand, switchPage = switchPage)
  351. def WriteWarning(self, line):
  352. """!Write message in warning style"""
  353. self.WriteLog(line, style = self.cmdOutput.StyleWarning, switchPage = True)
  354. def WriteError(self, line):
  355. """!Write message in error style"""
  356. self.WriteLog(line, style = self.cmdOutput.StyleError, switchPage = True)
  357. def RunCmd(self, command, compReg = True, switchPage = False,
  358. onDone = None, onPrepare = None, userData = None):
  359. """!Run command typed into console command prompt (GPrompt).
  360. @todo Display commands (*.d) are captured and processed
  361. separately by mapdisp.py. Display commands are rendered in map
  362. display widget that currently has the focus (as indicted by
  363. mdidx).
  364. @param command command given as a list (produced e.g. by utils.split())
  365. @param compReg True use computation region
  366. @param switchPage switch to output page
  367. @param onDone function to be called when command is finished
  368. @param onPrepare function to be called before command is launched
  369. @param userData data defined for the command
  370. """
  371. if len(command) == 0:
  372. Debug.msg(2, "GPrompt:RunCmd(): empty command")
  373. return 0
  374. # update history file
  375. env = grass.gisenv()
  376. try:
  377. fileHistory = codecs.open(os.path.join(env['GISDBASE'],
  378. env['LOCATION_NAME'],
  379. env['MAPSET'],
  380. '.bash_history'),
  381. encoding = 'utf-8', mode = 'a')
  382. except IOError, e:
  383. self.WriteError(e)
  384. fileHistory = None
  385. if fileHistory:
  386. try:
  387. fileHistory.write(' '.join(command) + os.linesep)
  388. finally:
  389. fileHistory.close()
  390. # update history items
  391. if self.parent.GetName() == 'LayerManager':
  392. try:
  393. self.parent.cmdinput.SetHistoryItems()
  394. except AttributeError:
  395. pass
  396. if command[0] in globalvar.grassCmd['all']:
  397. # send GRASS command without arguments to GUI command interface
  398. # except display commands (they are handled differently)
  399. if self.parent.GetName() == "LayerManager" and \
  400. command[0][0:2] == "d." and \
  401. 'help' not in ' '.join(command[1:]):
  402. # display GRASS commands
  403. try:
  404. layertype = {'d.rast' : 'raster',
  405. 'd.rast3d' : '3d-raster',
  406. 'd.rgb' : 'rgb',
  407. 'd.his' : 'his',
  408. 'd.shaded' : 'shaded',
  409. 'd.legend' : 'rastleg',
  410. 'd.rast.arrow' : 'rastarrow',
  411. 'd.rast.num' : 'rastnum',
  412. 'd.rast.leg' : 'maplegend',
  413. 'd.vect' : 'vector',
  414. 'd.thematic.area': 'thememap',
  415. 'd.vect.chart' : 'themechart',
  416. 'd.grid' : 'grid',
  417. 'd.geodesic' : 'geodesic',
  418. 'd.rhumbline' : 'rhumb',
  419. 'd.labels' : 'labels',
  420. 'd.barscale' : 'barscale',
  421. 'd.redraw' : 'redraw'}[command[0]]
  422. except KeyError:
  423. GMessage(parent = self.parent,
  424. message = _("Command '%s' not yet implemented in the WxGUI. "
  425. "Try adding it as a command layer instead.") % command[0])
  426. return 1
  427. if layertype == 'barscale':
  428. self.parent.curr_page.maptree.GetMapDisplay().OnAddBarscale(None)
  429. elif layertype == 'rastleg':
  430. self.parent.curr_page.maptree.GetMapDisplay().OnAddLegend(None)
  431. elif layertype == 'redraw':
  432. self.parent.curr_page.maptree.GetMapDisplay().OnRender(None)
  433. else:
  434. # add layer into layer tree
  435. lname, found = utils.GetLayerNameFromCmd(command, fullyQualified = True,
  436. layerType = layertype)
  437. if self.parent.GetName() == "LayerManager":
  438. self.parent.curr_page.maptree.AddLayer(ltype = layertype,
  439. lname = lname,
  440. lcmd = command)
  441. else:
  442. # other GRASS commands (r|v|g|...)
  443. if len(command) == 1 and command[0] != 'v.krige':
  444. # no arguments given
  445. GUI(parent = self).ParseCommand(command)
  446. return 0
  447. task = GUI(show = None).ParseCommand(command)
  448. if task:
  449. # check for <input>=-
  450. for p in task.get_options()['params']:
  451. if p.get('prompt', '') == 'input' and \
  452. p.get('element', '') == 'file' and \
  453. p.get('age', 'new') == 'old' and \
  454. p.get('value', '') == '-':
  455. GError(parent = self,
  456. message = _("Unable to run command:\n%(cmd)s\n\n"
  457. "Option <%(opt)s>: read from standard input is not "
  458. "supported by wxGUI") % { 'cmd': ' '.join(command),
  459. 'opt': p.get('name', '') })
  460. return 1
  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:
  678. task = None
  679. return
  680. for p in task.get_options()['params']:
  681. if p.get('prompt', '') not in ('raster', 'vector'):
  682. continue
  683. mapName = p.get('value', '')
  684. if '@' not in mapName:
  685. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  686. if mapName in mapLayers:
  687. display.GetWindow().UpdateMap(render = True)
  688. return
  689. elif self.parent.GetName() == 'Modeler':
  690. pass
  691. else: # standalone dialogs
  692. dialog = self.parent.parent
  693. if hasattr(self.parent.parent, "btn_abort"):
  694. dialog.btn_abort.Enable(False)
  695. if hasattr(self.parent.parent, "btn_cancel"):
  696. dialog.btn_cancel.Enable(True)
  697. if hasattr(self.parent.parent, "btn_clipboard"):
  698. dialog.btn_clipboard.Enable(True)
  699. if hasattr(self.parent.parent, "btn_help"):
  700. dialog.btn_help.Enable(True)
  701. if hasattr(self.parent.parent, "btn_run"):
  702. dialog.btn_run.Enable(True)
  703. if event.returncode == 0 and not event.aborted:
  704. try:
  705. winName = self.parent.parent.parent.GetName()
  706. except AttributeError:
  707. winName = ''
  708. if winName == 'LayerManager':
  709. mapTree = self.parent.parent.parent.GetLayerTree()
  710. elif winName == 'LayerTree':
  711. mapTree = self.parent.parent.parent
  712. elif winName: # GMConsole
  713. mapTree = self.parent.parent.parent.parent.GetLayerTree()
  714. else:
  715. mapTree = None
  716. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  717. if hasattr(dialog, "addbox") and dialog.addbox.IsChecked():
  718. # add created maps into layer tree
  719. for p in dialog.task.get_options()['params']:
  720. prompt = p.get('prompt', '')
  721. if prompt in ('raster', 'vector', '3d-raster') and \
  722. p.get('age', 'old') == 'new' and \
  723. p.get('value', None):
  724. name, found = utils.GetLayerNameFromCmd(cmd, fullyQualified = True,
  725. param = p.get('name', ''))
  726. if mapTree.GetMap().GetListOfLayers(l_name = name):
  727. continue
  728. if prompt == 'raster':
  729. lcmd = ['d.rast',
  730. 'map=%s' % name]
  731. else:
  732. lcmd = ['d.vect',
  733. 'map=%s' % name]
  734. mapTree.AddLayer(ltype = prompt,
  735. lcmd = lcmd,
  736. lname = name)
  737. if hasattr(dialog, "get_dcmd") and \
  738. dialog.get_dcmd is None and \
  739. hasattr(dialog, "closebox") and \
  740. dialog.closebox.IsChecked() and \
  741. (event.returncode == 0 or event.aborted):
  742. self.cmdOutput.Update()
  743. time.sleep(2)
  744. dialog.Close()
  745. def OnProcessPendingOutputWindowEvents(self, event):
  746. self.ProcessPendingEvents()
  747. def ResetFocus(self):
  748. """!Reset focus"""
  749. self.cmdPrompt.SetFocus()
  750. class GMStdout:
  751. """!GMConsole standard output
  752. Based on FrameOutErr.py
  753. Name: FrameOutErr.py
  754. Purpose: Redirecting stdout / stderr
  755. Author: Jean-Michel Fauth, Switzerland
  756. Copyright: (c) 2005-2007 Jean-Michel Fauth
  757. Licence: GPL
  758. """
  759. def __init__(self, parent):
  760. self.parent = parent # GMConsole
  761. def write(self, s):
  762. if len(s) == 0 or s == '\n':
  763. return
  764. for line in s.splitlines():
  765. if len(line) == 0:
  766. continue
  767. evt = wxCmdOutput(text = line + '\n',
  768. type = '')
  769. wx.PostEvent(self.parent.cmdOutput, evt)
  770. class GMStderr:
  771. """!GMConsole standard error output
  772. Based on FrameOutErr.py
  773. Name: FrameOutErr.py
  774. Purpose: Redirecting stdout / stderr
  775. Author: Jean-Michel Fauth, Switzerland
  776. Copyright: (c) 2005-2007 Jean-Michel Fauth
  777. Licence: GPL
  778. """
  779. def __init__(self, parent):
  780. self.parent = parent # GMConsole
  781. self.type = ''
  782. self.message = ''
  783. self.printMessage = False
  784. def flush(self):
  785. pass
  786. def write(self, s):
  787. if "GtkPizza" in s:
  788. return
  789. # remove/replace escape sequences '\b' or '\r' from stream
  790. progressValue = -1
  791. for line in s.splitlines():
  792. if len(line) == 0:
  793. continue
  794. if 'GRASS_INFO_PERCENT' in line:
  795. value = int(line.rsplit(':', 1)[1].strip())
  796. if value >= 0 and value < 100:
  797. progressValue = value
  798. else:
  799. progressValue = 0
  800. elif 'GRASS_INFO_MESSAGE' in line:
  801. self.type = 'message'
  802. self.message += line.split(':', 1)[1].strip() + '\n'
  803. elif 'GRASS_INFO_WARNING' in line:
  804. self.type = 'warning'
  805. self.message += line.split(':', 1)[1].strip() + '\n'
  806. elif 'GRASS_INFO_ERROR' in line:
  807. self.type = 'error'
  808. self.message += line.split(':', 1)[1].strip() + '\n'
  809. elif 'GRASS_INFO_END' in line:
  810. self.printMessage = True
  811. elif self.type == '':
  812. if len(line) == 0:
  813. continue
  814. evt = wxCmdOutput(text = line,
  815. type = '')
  816. wx.PostEvent(self.parent.cmdOutput, evt)
  817. elif len(line) > 0:
  818. self.message += line.strip() + '\n'
  819. if self.printMessage and len(self.message) > 0:
  820. evt = wxCmdOutput(text = self.message,
  821. type = self.type)
  822. wx.PostEvent(self.parent.cmdOutput, evt)
  823. self.type = ''
  824. self.message = ''
  825. self.printMessage = False
  826. # update progress message
  827. if progressValue > -1:
  828. # self.gmgauge.SetValue(progressValue)
  829. evt = wxCmdProgress(value = progressValue)
  830. wx.PostEvent(self.parent.progressbar, evt)
  831. class GMStc(wx.stc.StyledTextCtrl):
  832. """!Styled GMConsole
  833. Based on FrameOutErr.py
  834. Name: FrameOutErr.py
  835. Purpose: Redirecting stdout / stderr
  836. Author: Jean-Michel Fauth, Switzerland
  837. Copyright: (c) 2005-2007 Jean-Michel Fauth
  838. Licence: GPL
  839. """
  840. def __init__(self, parent, id, margin = False, wrap = None):
  841. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  842. self.parent = parent
  843. self.SetUndoCollection(True)
  844. self.SetReadOnly(True)
  845. #
  846. # styles
  847. #
  848. self.SetStyle()
  849. #
  850. # line margins
  851. #
  852. # TODO print number only from cmdlog
  853. self.SetMarginWidth(1, 0)
  854. self.SetMarginWidth(2, 0)
  855. if margin:
  856. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  857. self.SetMarginWidth(0, 30)
  858. else:
  859. self.SetMarginWidth(0, 0)
  860. #
  861. # miscellaneous
  862. #
  863. self.SetViewWhiteSpace(False)
  864. self.SetTabWidth(4)
  865. self.SetUseTabs(False)
  866. self.UsePopUp(True)
  867. self.SetSelBackground(True, "#FFFF00")
  868. self.SetUseHorizontalScrollBar(True)
  869. #
  870. # bindings
  871. #
  872. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  873. def OnTextSelectionChanged(self, event):
  874. """!Copy selected text to clipboard and skip event.
  875. The same function is in TextCtrlAutoComplete class (prompt.py).
  876. """
  877. self.Copy()
  878. event.Skip()
  879. def SetStyle(self):
  880. """!Set styles for styled text output windows with type face
  881. and point size selected by user (Courier New 10 is default)"""
  882. settings = Settings()
  883. typeface = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'type')
  884. if typeface == "":
  885. typeface = "Courier New"
  886. typesize = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'size')
  887. if typesize == None or typesize <= 0:
  888. typesize = 10
  889. typesize = float(typesize)
  890. self.StyleDefault = 0
  891. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  892. self.StyleCommand = 1
  893. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  894. self.StyleOutput = 2
  895. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  896. # fatal error
  897. self.StyleError = 3
  898. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  899. # warning
  900. self.StyleWarning = 4
  901. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  902. # message
  903. self.StyleMessage = 5
  904. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  905. # unknown
  906. self.StyleUnknown = 6
  907. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  908. # default and clear => init
  909. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  910. self.StyleClearAll()
  911. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  912. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  913. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  914. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  915. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  916. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  917. def OnDestroy(self, evt):
  918. """!The clipboard contents can be preserved after
  919. the app has exited"""
  920. wx.TheClipboard.Flush()
  921. evt.Skip()
  922. def AddTextWrapped(self, txt, wrap = None):
  923. """!Add string to text area.
  924. String is wrapped and linesep is also added to the end
  925. of the string"""
  926. # allow writing to output window
  927. self.SetReadOnly(False)
  928. if wrap:
  929. txt = textwrap.fill(txt, wrap) + '\n'
  930. else:
  931. if txt[-1] != '\n':
  932. txt += '\n'
  933. if '\r' in txt:
  934. self.parent.linePos = -1
  935. for seg in txt.split('\r'):
  936. if self.parent.linePos > -1:
  937. self.SetCurrentPos(self.parent.linePos)
  938. self.ReplaceSelection(seg)
  939. else:
  940. self.parent.linePos = self.GetCurrentPos()
  941. self.AddText(seg)
  942. else:
  943. self.parent.linePos = self.GetCurrentPos()
  944. try:
  945. self.AddText(txt)
  946. except UnicodeDecodeError:
  947. enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
  948. if enc:
  949. txt = unicode(txt, enc)
  950. elif 'GRASS_DB_ENCODING' in os.environ:
  951. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  952. else:
  953. txt = EncodeString(txt)
  954. self.AddText(txt)
  955. # reset output window to read only
  956. self.SetReadOnly(True)