goutput.py 44 KB

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