goutput.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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. try:
  437. task = GUI(show = None).ParseCommand(command)
  438. except GException, e:
  439. GError(parent = self,
  440. message = unicode(e),
  441. showTraceback = False)
  442. return
  443. hasParams = False
  444. if task:
  445. options = task.get_options()
  446. hasParams = options['params'] and options['flags']
  447. # check for <input>=-
  448. for p in 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. 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. return 1
  459. if len(command) == 1 and hasParams and \
  460. command[0] != 'v.krige':
  461. # no arguments given
  462. try:
  463. GUI(parent = self).ParseCommand(command)
  464. except GException, e:
  465. print >> sys.stderr, e
  466. return 0
  467. # switch to 'Command output' if required
  468. if switchPage:
  469. self._notebook.SetSelectionByName('output')
  470. self.parent.SetFocus()
  471. self.parent.Raise()
  472. # activate computational region (set with g.region)
  473. # for all non-display commands.
  474. if compReg:
  475. tmpreg = os.getenv("GRASS_REGION")
  476. if "GRASS_REGION" in os.environ:
  477. del os.environ["GRASS_REGION"]
  478. # process GRASS command with argument
  479. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  480. onDone = onDone, onPrepare = onPrepare, userData = userData)
  481. self.cmdOutputTimer.Start(50)
  482. # deactivate computational region and return to display settings
  483. if compReg and tmpreg:
  484. os.environ["GRASS_REGION"] = tmpreg
  485. else:
  486. # Send any other command to the shell. Send output to
  487. # console output window
  488. if len(command) == 1:
  489. try:
  490. task = gtask.parse_interface(command[0])
  491. except:
  492. task = None
  493. else:
  494. task = None
  495. if task:
  496. # process GRASS command without argument
  497. GUI(parent = self).ParseCommand(command)
  498. else:
  499. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  500. onDone = onDone, onPrepare = onPrepare, userData = userData)
  501. self.cmdOutputTimer.Start(50)
  502. return 0
  503. def ClearHistory(self, event):
  504. """!Clear history of commands"""
  505. self.cmdOutput.SetReadOnly(False)
  506. self.cmdOutput.ClearAll()
  507. self.cmdOutput.SetReadOnly(True)
  508. self.progressbar.SetValue(0)
  509. def GetProgressBar(self):
  510. """!Return progress bar widget"""
  511. return self.progressbar
  512. def GetLog(self, err = False):
  513. """!Get widget used for logging
  514. @param err True to get stderr widget
  515. """
  516. if err:
  517. return self.cmdStdErr
  518. return self.cmdStdOut
  519. def SaveHistory(self, event):
  520. """!Save history of commands"""
  521. self.history = self.cmdOutput.GetSelectedText()
  522. if self.history == '':
  523. self.history = self.cmdOutput.GetText()
  524. # add newline if needed
  525. if len(self.history) > 0 and self.history[-1] != '\n':
  526. self.history += '\n'
  527. wildcard = "Text file (*.txt)|*.txt"
  528. dlg = wx.FileDialog(self, message = _("Save file as..."), defaultDir = os.getcwd(),
  529. defaultFile = "grass_cmd_history.txt", wildcard = wildcard,
  530. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  531. # Show the dialog and retrieve the user response. If it is the OK response,
  532. # process the data.
  533. if dlg.ShowModal() == wx.ID_OK:
  534. path = dlg.GetPath()
  535. output = open(path, "w")
  536. output.write(self.history)
  537. output.close()
  538. dlg.Destroy()
  539. def GetCmd(self):
  540. """!Get running command or None"""
  541. return self.requestQ.get()
  542. def SetCopyingOfSelectedText(self, copy):
  543. """!Enable or disable copying of selected text in to clipboard.
  544. Effects prompt and output.
  545. @param copy True for enable, False for disable
  546. """
  547. if copy:
  548. self.cmdPrompt.Bind(wx.stc.EVT_STC_PAINTED, self.cmdPrompt.OnTextSelectionChanged)
  549. self.cmdOutput.Bind(wx.stc.EVT_STC_PAINTED, self.cmdOutput.OnTextSelectionChanged)
  550. else:
  551. self.cmdPrompt.Unbind(wx.stc.EVT_STC_PAINTED)
  552. self.cmdOutput.Unbind(wx.stc.EVT_STC_PAINTED)
  553. def OnUpdateStatusBar(self, event):
  554. """!Update statusbar text"""
  555. if event.GetString():
  556. nItems = len(self.cmdPrompt.GetCommandItems())
  557. self.parent.SetStatusText(_('%d modules match') % nItems, 0)
  558. else:
  559. self.parent.SetStatusText('', 0)
  560. event.Skip()
  561. def OnCmdOutput(self, event):
  562. """!Print command output"""
  563. message = event.text
  564. type = event.type
  565. if self._notebook.GetSelection() != self._notebook.GetPageIndexByName('output'):
  566. page = self._notebook.GetPageIndexByName('output')
  567. textP = self._notebook.GetPageText(page)
  568. if textP[-1] != ')':
  569. textP += ' (...)'
  570. self._notebook.SetPageText(page, textP)
  571. # message prefix
  572. if type == 'warning':
  573. messege = 'WARNING: ' + message
  574. elif type == 'error':
  575. message = 'ERROR: ' + message
  576. p1 = self.cmdOutput.GetEndStyled()
  577. self.cmdOutput.GotoPos(p1)
  578. if '\b' in message:
  579. if self.linepos < 0:
  580. self.linepos = p1
  581. last_c = ''
  582. for c in message:
  583. if c == '\b':
  584. self.linepos -= 1
  585. else:
  586. if c == '\r':
  587. pos = self.cmdOutput.GetCurLine()[1]
  588. # self.cmdOutput.SetCurrentPos(pos)
  589. else:
  590. self.cmdOutput.SetCurrentPos(self.linepos)
  591. self.cmdOutput.ReplaceSelection(c)
  592. self.linepos = self.cmdOutput.GetCurrentPos()
  593. if c != ' ':
  594. last_c = c
  595. if last_c not in ('0123456789'):
  596. self.cmdOutput.AddTextWrapped('\n', wrap = None)
  597. self.linepos = -1
  598. else:
  599. self.linepos = -1 # don't force position
  600. if '\n' not in message:
  601. self.cmdOutput.AddTextWrapped(message, wrap = 60)
  602. else:
  603. self.cmdOutput.AddTextWrapped(message, wrap = None)
  604. p2 = self.cmdOutput.GetCurrentPos()
  605. if p2 >= p1:
  606. self.cmdOutput.StartStyling(p1, 0xff)
  607. if type == 'error':
  608. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleError)
  609. elif type == 'warning':
  610. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleWarning)
  611. elif type == 'message':
  612. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleMessage)
  613. else: # unknown
  614. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleUnknown)
  615. self.cmdOutput.EnsureCaretVisible()
  616. def OnCmdProgress(self, event):
  617. """!Update progress message info"""
  618. self.progressbar.SetValue(event.value)
  619. def OnCmdAbort(self, event):
  620. """!Abort running command"""
  621. self.cmdThread.abort()
  622. def OnCmdRun(self, event):
  623. """!Run command"""
  624. if self.parent.GetName() == 'Modeler':
  625. self.parent.OnCmdRun(event)
  626. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  627. self.btnCmdAbort.Enable()
  628. def OnCmdPrepare(self, event):
  629. """!Prepare for running command"""
  630. if self.parent.GetName() == 'Modeler':
  631. self.parent.OnCmdPrepare(event)
  632. event.Skip()
  633. def OnCmdDone(self, event):
  634. """!Command done (or aborted)"""
  635. if self.parent.GetName() == 'Modeler':
  636. self.parent.OnCmdDone(event)
  637. # Process results here
  638. try:
  639. ctime = time.time() - event.time
  640. if ctime < 60:
  641. stime = _("%d sec") % int(ctime)
  642. else:
  643. mtime = int(ctime / 60)
  644. stime = _("%(min)d min %(sec)d sec") % { 'min' : mtime,
  645. 'sec' : int(ctime - (mtime * 60)) }
  646. except KeyError:
  647. # stopped deamon
  648. stime = _("unknown")
  649. if event.aborted:
  650. # Thread aborted (using our convention of None return)
  651. self.WriteLog(_('Please note that the data are left in inconsistent state '
  652. 'and may be corrupted'), self.cmdOutput.StyleWarning)
  653. msg = _('Command aborted')
  654. else:
  655. msg = _('Command finished')
  656. self.WriteCmdLog('(%s) %s (%s)' % (str(time.ctime()), msg, stime))
  657. self.btnCmdAbort.Enable(False)
  658. if event.onDone:
  659. event.onDone(cmd = event.cmd, returncode = event.returncode)
  660. self.progressbar.SetValue(0) # reset progress bar on '0%'
  661. self.cmdOutputTimer.Stop()
  662. if event.cmd[0] == 'g.gisenv':
  663. Debug.SetLevel()
  664. self.Redirect()
  665. if self.parent.GetName() == "LayerManager":
  666. self.btnCmdAbort.Enable(False)
  667. if event.cmd[0] not in globalvar.grassCmd or \
  668. event.cmd[0] == 'r.mapcalc':
  669. return
  670. display = self.parent.GetLayerTree().GetMapDisplay()
  671. if not display or not display.IsAutoRendered():
  672. return
  673. mapLayers = map(lambda x: x.GetName(),
  674. display.GetMap().GetListOfLayers(l_type = 'raster') +
  675. display.GetMap().GetListOfLayers(l_type = 'vector'))
  676. try:
  677. task = GUI(show = None).ParseCommand(event.cmd)
  678. except GException, e:
  679. print >> sys.stderr, e
  680. task = None
  681. return
  682. for p in task.get_options()['params']:
  683. if p.get('prompt', '') not in ('raster', 'vector'):
  684. continue
  685. mapName = p.get('value', '')
  686. if '@' not in mapName:
  687. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  688. if mapName in mapLayers:
  689. display.GetWindow().UpdateMap(render = True)
  690. return
  691. elif self.parent.GetName() == 'Modeler':
  692. pass
  693. else: # standalone dialogs
  694. dialog = self.parent.parent
  695. if hasattr(self.parent.parent, "btn_abort"):
  696. dialog.btn_abort.Enable(False)
  697. if hasattr(self.parent.parent, "btn_cancel"):
  698. dialog.btn_cancel.Enable(True)
  699. if hasattr(self.parent.parent, "btn_clipboard"):
  700. dialog.btn_clipboard.Enable(True)
  701. if hasattr(self.parent.parent, "btn_help"):
  702. dialog.btn_help.Enable(True)
  703. if hasattr(self.parent.parent, "btn_run"):
  704. dialog.btn_run.Enable(True)
  705. if event.returncode == 0 and not event.aborted:
  706. try:
  707. winName = self.parent.parent.parent.GetName()
  708. except AttributeError:
  709. winName = ''
  710. if winName == 'LayerManager':
  711. mapTree = self.parent.parent.parent.GetLayerTree()
  712. elif winName == 'LayerTree':
  713. mapTree = self.parent.parent.parent
  714. elif winName: # GMConsole
  715. mapTree = self.parent.parent.parent.parent.GetLayerTree()
  716. else:
  717. mapTree = None
  718. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  719. if hasattr(dialog, "addbox") and dialog.addbox.IsChecked():
  720. # add created maps into layer tree
  721. for p in dialog.task.get_options()['params']:
  722. prompt = p.get('prompt', '')
  723. if prompt in ('raster', 'vector', '3d-raster') and \
  724. p.get('age', 'old') == 'new' and \
  725. p.get('value', None):
  726. name, found = utils.GetLayerNameFromCmd(cmd, fullyQualified = True,
  727. param = p.get('name', ''))
  728. if mapTree.GetMap().GetListOfLayers(l_name = name):
  729. continue
  730. if prompt == 'raster':
  731. lcmd = ['d.rast',
  732. 'map=%s' % name]
  733. else:
  734. lcmd = ['d.vect',
  735. 'map=%s' % name]
  736. mapTree.AddLayer(ltype = prompt,
  737. lcmd = lcmd,
  738. lname = name)
  739. if hasattr(dialog, "get_dcmd") and \
  740. dialog.get_dcmd is None and \
  741. hasattr(dialog, "closebox") and \
  742. dialog.closebox.IsChecked() and \
  743. (event.returncode == 0 or event.aborted):
  744. self.cmdOutput.Update()
  745. time.sleep(2)
  746. dialog.Close()
  747. def OnProcessPendingOutputWindowEvents(self, event):
  748. self.ProcessPendingEvents()
  749. def ResetFocus(self):
  750. """!Reset focus"""
  751. self.cmdPrompt.SetFocus()
  752. class GMStdout:
  753. """!GMConsole standard output
  754. Based on FrameOutErr.py
  755. Name: FrameOutErr.py
  756. Purpose: Redirecting stdout / stderr
  757. Author: Jean-Michel Fauth, Switzerland
  758. Copyright: (c) 2005-2007 Jean-Michel Fauth
  759. Licence: GPL
  760. """
  761. def __init__(self, parent):
  762. self.parent = parent # GMConsole
  763. def write(self, s):
  764. if len(s) == 0 or s == '\n':
  765. return
  766. for line in s.splitlines():
  767. if len(line) == 0:
  768. continue
  769. evt = wxCmdOutput(text = line + '\n',
  770. type = '')
  771. wx.PostEvent(self.parent.cmdOutput, evt)
  772. class GMStderr:
  773. """!GMConsole standard error output
  774. Based on FrameOutErr.py
  775. Name: FrameOutErr.py
  776. Purpose: Redirecting stdout / stderr
  777. Author: Jean-Michel Fauth, Switzerland
  778. Copyright: (c) 2005-2007 Jean-Michel Fauth
  779. Licence: GPL
  780. """
  781. def __init__(self, parent):
  782. self.parent = parent # GMConsole
  783. self.type = ''
  784. self.message = ''
  785. self.printMessage = False
  786. def flush(self):
  787. pass
  788. def write(self, s):
  789. if "GtkPizza" in s:
  790. return
  791. # remove/replace escape sequences '\b' or '\r' from stream
  792. progressValue = -1
  793. for line in s.splitlines():
  794. if len(line) == 0:
  795. continue
  796. if 'GRASS_INFO_PERCENT' in line:
  797. value = int(line.rsplit(':', 1)[1].strip())
  798. if value >= 0 and value < 100:
  799. progressValue = value
  800. else:
  801. progressValue = 0
  802. elif 'GRASS_INFO_MESSAGE' in line:
  803. self.type = 'message'
  804. self.message += line.split(':', 1)[1].strip() + '\n'
  805. elif 'GRASS_INFO_WARNING' in line:
  806. self.type = 'warning'
  807. self.message += line.split(':', 1)[1].strip() + '\n'
  808. elif 'GRASS_INFO_ERROR' in line:
  809. self.type = 'error'
  810. self.message += line.split(':', 1)[1].strip() + '\n'
  811. elif 'GRASS_INFO_END' in line:
  812. self.printMessage = True
  813. elif self.type == '':
  814. if len(line) == 0:
  815. continue
  816. evt = wxCmdOutput(text = line,
  817. type = '')
  818. wx.PostEvent(self.parent.cmdOutput, evt)
  819. elif len(line) > 0:
  820. self.message += line.strip() + '\n'
  821. if self.printMessage and len(self.message) > 0:
  822. evt = wxCmdOutput(text = self.message,
  823. type = self.type)
  824. wx.PostEvent(self.parent.cmdOutput, evt)
  825. self.type = ''
  826. self.message = ''
  827. self.printMessage = False
  828. # update progress message
  829. if progressValue > -1:
  830. # self.gmgauge.SetValue(progressValue)
  831. evt = wxCmdProgress(value = progressValue)
  832. wx.PostEvent(self.parent.progressbar, evt)
  833. class GMStc(wx.stc.StyledTextCtrl):
  834. """!Styled GMConsole
  835. Based on FrameOutErr.py
  836. Name: FrameOutErr.py
  837. Purpose: Redirecting stdout / stderr
  838. Author: Jean-Michel Fauth, Switzerland
  839. Copyright: (c) 2005-2007 Jean-Michel Fauth
  840. Licence: GPL
  841. """
  842. def __init__(self, parent, id, margin = False, wrap = None):
  843. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  844. self.parent = parent
  845. self.SetUndoCollection(True)
  846. self.SetReadOnly(True)
  847. #
  848. # styles
  849. #
  850. self.SetStyle()
  851. #
  852. # line margins
  853. #
  854. # TODO print number only from cmdlog
  855. self.SetMarginWidth(1, 0)
  856. self.SetMarginWidth(2, 0)
  857. if margin:
  858. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  859. self.SetMarginWidth(0, 30)
  860. else:
  861. self.SetMarginWidth(0, 0)
  862. #
  863. # miscellaneous
  864. #
  865. self.SetViewWhiteSpace(False)
  866. self.SetTabWidth(4)
  867. self.SetUseTabs(False)
  868. self.UsePopUp(True)
  869. self.SetSelBackground(True, "#FFFF00")
  870. self.SetUseHorizontalScrollBar(True)
  871. #
  872. # bindings
  873. #
  874. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  875. def OnTextSelectionChanged(self, event):
  876. """!Copy selected text to clipboard and skip event.
  877. The same function is in TextCtrlAutoComplete class (prompt.py).
  878. """
  879. self.Copy()
  880. event.Skip()
  881. def SetStyle(self):
  882. """!Set styles for styled text output windows with type face
  883. and point size selected by user (Courier New 10 is default)"""
  884. settings = Settings()
  885. typeface = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'type')
  886. if typeface == "":
  887. typeface = "Courier New"
  888. typesize = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'size')
  889. if typesize == None or typesize <= 0:
  890. typesize = 10
  891. typesize = float(typesize)
  892. self.StyleDefault = 0
  893. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  894. self.StyleCommand = 1
  895. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  896. self.StyleOutput = 2
  897. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  898. # fatal error
  899. self.StyleError = 3
  900. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  901. # warning
  902. self.StyleWarning = 4
  903. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  904. # message
  905. self.StyleMessage = 5
  906. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  907. # unknown
  908. self.StyleUnknown = 6
  909. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  910. # default and clear => init
  911. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  912. self.StyleClearAll()
  913. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  914. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  915. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  916. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  917. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  918. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  919. def OnDestroy(self, evt):
  920. """!The clipboard contents can be preserved after
  921. the app has exited"""
  922. wx.TheClipboard.Flush()
  923. evt.Skip()
  924. def AddTextWrapped(self, txt, wrap = None):
  925. """!Add string to text area.
  926. String is wrapped and linesep is also added to the end
  927. of the string"""
  928. # allow writing to output window
  929. self.SetReadOnly(False)
  930. if wrap:
  931. txt = textwrap.fill(txt, wrap) + '\n'
  932. else:
  933. if txt[-1] != '\n':
  934. txt += '\n'
  935. if '\r' in txt:
  936. self.parent.linePos = -1
  937. for seg in txt.split('\r'):
  938. if self.parent.linePos > -1:
  939. self.SetCurrentPos(self.parent.linePos)
  940. self.ReplaceSelection(seg)
  941. else:
  942. self.parent.linePos = self.GetCurrentPos()
  943. self.AddText(seg)
  944. else:
  945. self.parent.linePos = self.GetCurrentPos()
  946. try:
  947. self.AddText(txt)
  948. except UnicodeDecodeError:
  949. enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
  950. if enc:
  951. txt = unicode(txt, enc)
  952. elif 'GRASS_DB_ENCODING' in os.environ:
  953. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  954. else:
  955. txt = EncodeString(txt)
  956. self.AddText(txt)
  957. # reset output window to read only
  958. self.SetReadOnly(True)