goutput.py 39 KB

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