goutput.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. """
  2. @package goutput
  3. @brief Command output log widget
  4. Classes:
  5. - GMConsole
  6. - GMStc
  7. - GMStdout
  8. - GMStderr
  9. (C) 2007-2008 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 menuform
  30. from debug import Debug as Debug
  31. from preferences import globalSettings as UserSettings
  32. wxCmdOutput, EVT_CMD_OUTPUT = NewEvent()
  33. wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
  34. wxCmdRun, EVT_CMD_RUN = NewEvent()
  35. wxCmdDone, EVT_CMD_DONE = NewEvent()
  36. wxCmdAbort, EVT_CMD_ABORT = NewEvent()
  37. def GrassCmd(cmd, stdout, stderr):
  38. """!Return GRASS command thread"""
  39. return gcmd.CommandThread(cmd,
  40. stdout=stdout, stderr=stderr)
  41. class CmdThread(threading.Thread):
  42. """!Thread for GRASS commands"""
  43. requestId = 0
  44. def __init__(self, parent, requestQ, resultQ, **kwds):
  45. threading.Thread.__init__(self, **kwds)
  46. self.setDaemon(True)
  47. self.parent = parent # GMConsole
  48. self.requestQ = requestQ
  49. self.resultQ = resultQ
  50. self.start()
  51. def RunCmd(self, callable, onDone, *args, **kwds):
  52. CmdThread.requestId += 1
  53. self.requestCmd = None
  54. self.requestQ.put((CmdThread.requestId, callable, onDone, args, kwds))
  55. return CmdThread.requestId
  56. def run(self):
  57. while True:
  58. requestId, callable, onDone, args, kwds = self.requestQ.get()
  59. requestTime = time.time()
  60. event = wxCmdRun(cmd=args[0],
  61. pid=requestId)
  62. wx.PostEvent(self.parent, event)
  63. time.sleep(.1)
  64. self.requestCmd = callable(*args, **kwds)
  65. self.resultQ.put((requestId, self.requestCmd.run()))
  66. try:
  67. returncode = self.requestCmd.module.returncode
  68. except AttributeError:
  69. returncode = 0 # being optimistic
  70. try:
  71. aborted = self.requestCmd.aborted
  72. except AttributeError:
  73. aborted = False
  74. time.sleep(.1)
  75. # set default color table for raster data
  76. if UserSettings.Get(group='cmd', key='rasterColorTable', subkey='enabled') and \
  77. args[0][0][:2] == 'r.':
  78. moduleInterface = menuform.GUI().ParseCommand(args[0], show = None)
  79. outputParam = moduleInterface.get_param(value = 'output', raiseError = False)
  80. colorTable = UserSettings.Get(group='cmd', key='rasterColorTable', subkey='selection')
  81. if outputParam and outputParam['prompt'] == 'raster':
  82. argsColor = list(args)
  83. argsColor[0] = [ 'r.colors',
  84. 'map=%s' % outputParam['value'],
  85. 'color=%s' % colorTable]
  86. self.requestCmdColor = callable(*argsColor, **kwds)
  87. self.resultQ.put((requestId, self.requestCmdColor.run()))
  88. event = wxCmdDone(aborted = aborted,
  89. returncode = returncode,
  90. time = requestTime,
  91. pid = requestId,
  92. onDone = onDone)
  93. # send event
  94. wx.PostEvent(self.parent, event)
  95. def abort(self):
  96. self.requestCmd.abort()
  97. class GMConsole(wx.Panel):
  98. """!Create and manage output console for commands run by GUI.
  99. """
  100. def __init__(self, parent, id=wx.ID_ANY, margin=False, pageid=0,
  101. notebook = None,
  102. style=wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  103. **kwargs):
  104. wx.Panel.__init__(self, parent, id, style = style, *kwargs)
  105. self.SetName("GMConsole")
  106. # initialize variables
  107. self.Map = None
  108. self.parent = parent # GMFrame | CmdPanel | ?
  109. if notebook:
  110. self._notebook = notebook
  111. else:
  112. self._notebook = self.parent.notebook
  113. self.lineWidth = 80
  114. self.pageid = pageid
  115. # remember position of line begining (used for '\r')
  116. self.linePos = -1
  117. #
  118. # create queues
  119. #
  120. self.requestQ = Queue.Queue()
  121. self.resultQ = Queue.Queue()
  122. #
  123. # progress bar
  124. #
  125. self.console_progressbar = wx.Gauge(parent=self, id=wx.ID_ANY,
  126. range=100, pos=(110, 50), size=(-1, 25),
  127. style=wx.GA_HORIZONTAL)
  128. self.console_progressbar.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
  129. # abort
  130. self.btn_abort = wx.Button(parent=self, id=wx.ID_STOP)
  131. self.btn_abort.SetToolTipString(_("Abort the running command"))
  132. self.btn_abort.Bind(wx.EVT_BUTTON, self.OnCmdAbort)
  133. self.btn_abort.Enable(False)
  134. #
  135. # text control for command output
  136. #
  137. self.cmd_output = GMStc(parent=self, id=wx.ID_ANY, margin=margin,
  138. wrap=None)
  139. self.cmd_output_timer = wx.Timer(self.cmd_output, id=wx.ID_ANY)
  140. self.cmd_output.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
  141. self.cmd_output.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  142. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  143. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  144. #
  145. # stream redirection
  146. #
  147. self.cmd_stdout = GMStdout(self)
  148. self.cmd_stderr = GMStderr(self)
  149. #
  150. # thread
  151. #
  152. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  153. #
  154. # buttons
  155. #
  156. self.console_clear = wx.Button(parent=self, id=wx.ID_CLEAR)
  157. self.console_save = wx.Button(parent=self, id=wx.ID_SAVE)
  158. self.Bind(wx.EVT_BUTTON, self.ClearHistory, self.console_clear)
  159. self.Bind(wx.EVT_BUTTON, self.SaveHistory, self.console_save)
  160. self.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  161. self.__layout()
  162. def __layout(self):
  163. """!Do layout"""
  164. boxsizer1 = wx.BoxSizer(wx.VERTICAL)
  165. gridsizer1 = wx.GridSizer(rows=1, cols=2, vgap=0, hgap=0)
  166. boxsizer1.Add(item=self.cmd_output, proportion=1,
  167. flag=wx.EXPAND | wx.ADJUST_MINSIZE, border=0)
  168. gridsizer1.Add(item=self.console_clear, proportion=0,
  169. flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ADJUST_MINSIZE, border=0)
  170. gridsizer1.Add(item=self.console_save, proportion=0,
  171. flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ADJUST_MINSIZE, border=0)
  172. boxsizer1.Add(item=gridsizer1, proportion=0,
  173. flag=wx.EXPAND | wx.ALIGN_CENTRE_VERTICAL | wx.TOP | wx.BOTTOM,
  174. border=5)
  175. boxsizer2 = wx.BoxSizer(wx.HORIZONTAL)
  176. boxsizer2.Add(item=self.console_progressbar, proportion=1,
  177. flag=wx.EXPAND | wx.ALIGN_CENTRE_VERTICAL)
  178. boxsizer2.Add(item=self.btn_abort, proportion=0,
  179. flag=wx.ALIGN_CENTRE_VERTICAL | wx.LEFT,
  180. border = 5)
  181. boxsizer1.Add(item=boxsizer2, proportion=0,
  182. flag=wx.EXPAND | wx.ALIGN_CENTRE_VERTICAL | wx.ALL,
  183. border=5)
  184. boxsizer1.Fit(self)
  185. boxsizer1.SetSizeHints(self)
  186. # layout
  187. self.SetAutoLayout(True)
  188. self.SetSizer(boxsizer1)
  189. def Redirect(self):
  190. """!Redirect stderr
  191. @return True redirected
  192. @return False failed
  193. """
  194. if Debug.get_level() == 0:
  195. # don't redirect when debugging is enabled
  196. sys.stdout = self.cmd_stdout
  197. sys.stderr = self.cmd_stderr
  198. return True
  199. return False
  200. def WriteLog(self, text, style = None, wrap = None,
  201. switchPage = False):
  202. """!Generic method for writing log message in
  203. given style
  204. @param line text line
  205. @param style text style (see GMStc)
  206. @param stdout write to stdout or stderr
  207. """
  208. if switchPage and \
  209. self._notebook.GetSelection() != self.parent.goutput.pageid:
  210. self._notebook.SetSelection(self.parent.goutput.pageid)
  211. if not style:
  212. style = self.cmd_output.StyleDefault
  213. # p1 = self.cmd_output.GetCurrentPos()
  214. p1 = self.cmd_output.GetEndStyled()
  215. self.cmd_output.GotoPos(p1)
  216. for line in text.splitlines():
  217. # fill space
  218. if len(line) < self.lineWidth:
  219. diff = self.lineWidth - len(line)
  220. line += diff * ' '
  221. self.cmd_output.AddTextWrapped(line, wrap=wrap) # adds '\n'
  222. p2 = self.cmd_output.GetCurrentPos()
  223. self.cmd_output.StartStyling(p1, 0xff)
  224. self.cmd_output.SetStyling(p2 - p1, style)
  225. self.cmd_output.EnsureCaretVisible()
  226. def WriteCmdLog(self, line, pid=None):
  227. """!Write message in selected style"""
  228. if pid:
  229. line = '(' + str(pid) + ') ' + line
  230. self.WriteLog(line, style=self.cmd_output.StyleCommand, switchPage = True)
  231. def WriteWarning(self, line):
  232. """!Write message in warning style"""
  233. self.WriteLog(line, style=self.cmd_output.StyleWarning, switchPage = True)
  234. def WriteError(self, line):
  235. """!Write message in error style"""
  236. self.WriteLog(line, style=self.cmd_output.StyleError, switchPage = True)
  237. def RunCmd(self, command, compReg=True, switchPage=False,
  238. onDone = None):
  239. """
  240. Run in GUI GRASS (or other) commands typed into
  241. console command text widget, and send stdout output to output
  242. text widget.
  243. Command is transformed into a list for processing.
  244. TODO: Display commands (*.d) are captured and
  245. processed separately by mapdisp.py. Display commands are
  246. rendered in map display widget that currently has
  247. the focus (as indicted by mdidx).
  248. @param command command (list)
  249. @param compReg if true use computation region
  250. @param switchPage switch to output page
  251. @param onDone function to be called when command is finished
  252. """
  253. # map display window available ?
  254. try:
  255. curr_disp = self.parent.curr_page.maptree.mapdisplay
  256. self.Map = curr_disp.GetRender()
  257. except:
  258. curr_disp = None
  259. # command given as a string ?
  260. try:
  261. cmdlist = command.strip().split(' ')
  262. except:
  263. cmdlist = command
  264. # update history file
  265. env = grass.gisenv()
  266. fileHistory = open(os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'],
  267. '.bash_history'), 'a')
  268. cmdString = ' '.join(cmdlist)
  269. try:
  270. fileHistory.write(cmdString + '\n')
  271. finally:
  272. fileHistory.close()
  273. # update history items
  274. if self.parent.GetName() == 'LayerManager':
  275. try:
  276. self.parent.cmdinput.SetHistoryItems()
  277. except AttributeError:
  278. pass
  279. if cmdlist[0] in globalvar.grassCmd['all']:
  280. # send GRASS command without arguments to GUI command interface
  281. # except display commands (they are handled differently)
  282. if cmdlist[0][0:2] == "d.":
  283. #
  284. # display GRASS commands
  285. #
  286. try:
  287. layertype = {'d.rast' : 'raster',
  288. 'd.rgb' : 'rgb',
  289. 'd.his' : 'his',
  290. 'd.shaded' : 'shaded',
  291. 'd.legend' : 'rastleg',
  292. 'd.rast.arrow' : 'rastarrow',
  293. 'd.rast.num' : 'rastnum',
  294. 'd.vect' : 'vector',
  295. 'd.vect.thematic': 'thememap',
  296. 'd.vect.chart' : 'themechart',
  297. 'd.grid' : 'grid',
  298. 'd.geodesic' : 'geodesic',
  299. 'd.rhumbline' : 'rhumb',
  300. 'd.labels' : 'labels'}[cmdlist[0]]
  301. except KeyError:
  302. wx.MessageBox(message=_("Command '%s' not yet implemented.") % cmdlist[0])
  303. return None
  304. # add layer into layer tree
  305. if cmdlist[0] == 'd.rast':
  306. lname = utils.GetLayerNameFromCmd(cmdlist, fullyQualified = True,
  307. layerType = 'raster')
  308. elif cmdlist[0] == 'd.vect':
  309. lname = utils.GetLayerNameFromCmd(cmdlist, fullyQualified = True,
  310. layerType = 'vector')
  311. else:
  312. lname = None
  313. self.parent.curr_page.maptree.AddLayer(ltype=layertype,
  314. lname=lname,
  315. lcmd=cmdlist)
  316. else:
  317. #
  318. # other GRASS commands (r|v|g|...)
  319. #
  320. # switch to 'Command output'
  321. if switchPage:
  322. if self._notebook.GetSelection() != self.parent.goutput.pageid:
  323. self._notebook.SetSelection(self.parent.goutput.pageid)
  324. self.parent.SetFocus() # -> set focus
  325. self.parent.Raise()
  326. # activate computational region (set with g.region)
  327. # for all non-display commands.
  328. if compReg:
  329. tmpreg = os.getenv("GRASS_REGION")
  330. if os.environ.has_key("GRASS_REGION"):
  331. del os.environ["GRASS_REGION"]
  332. if len(cmdlist) == 1:
  333. import menuform
  334. # process GRASS command without argument
  335. menuform.GUI().ParseCommand(cmdlist, parentframe=self)
  336. else:
  337. # process GRASS command with argument
  338. self.cmdThread.RunCmd(GrassCmd,
  339. onDone,
  340. cmdlist,
  341. self.cmd_stdout, self.cmd_stderr)
  342. self.btn_abort.Enable()
  343. self.cmd_output_timer.Start(50)
  344. return None
  345. # deactivate computational region and return to display settings
  346. if compReg and tmpreg:
  347. os.environ["GRASS_REGION"] = tmpreg
  348. else:
  349. # Send any other command to the shell. Send output to
  350. # console output window
  351. self.cmdThread.RunCmd(GrassCmd,
  352. onDone,
  353. cmdlist,
  354. self.cmd_stdout, self.cmd_stderr)
  355. self.btn_abort.Enable()
  356. self.cmd_output_timer.Start(50)
  357. return None
  358. def ClearHistory(self, event):
  359. """!Clear history of commands"""
  360. self.cmd_output.ClearAll()
  361. self.console_progressbar.SetValue(0)
  362. def SaveHistory(self, event):
  363. """!Save history of commands"""
  364. self.history = self.cmd_output.GetSelectedText()
  365. if self.history == '':
  366. self.history = self.cmd_output.GetText()
  367. # add newline if needed
  368. if len(self.history) > 0 and self.history[-1] != '\n':
  369. self.history += '\n'
  370. wildcard = "Text file (*.txt)|*.txt"
  371. dlg = wx.FileDialog(
  372. self, message=_("Save file as..."), defaultDir=os.getcwd(),
  373. defaultFile="grass_cmd_history.txt", wildcard=wildcard,
  374. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  375. # Show the dialog and retrieve the user response. If it is the OK response,
  376. # process the data.
  377. if dlg.ShowModal() == wx.ID_OK:
  378. path = dlg.GetPath()
  379. output = open(path, "w")
  380. output.write(self.history)
  381. output.close()
  382. dlg.Destroy()
  383. def GetCmd(self):
  384. """!Get running command or None"""
  385. return self.requestQ.get()
  386. def OnCmdOutput(self, event):
  387. """!Print command output"""
  388. message = event.text
  389. type = event.type
  390. if self._notebook.GetSelection() != self.parent.goutput.pageid:
  391. textP = self._notebook.GetPageText(self.parent.goutput.pageid)
  392. if textP[-1] != ')':
  393. textP += ' (...)'
  394. self._notebook.SetPageText(self.parent.goutput.pageid,
  395. textP)
  396. # message prefix
  397. if type == 'warning':
  398. messege = 'WARNING: ' + message
  399. elif type == 'error':
  400. message = 'ERROR: ' + message
  401. p1 = self.cmd_output.GetEndStyled()
  402. self.cmd_output.GotoPos(p1)
  403. if '\b' in message:
  404. if self.linepos < 0:
  405. self.linepos = p1
  406. last_c = ''
  407. for c in message:
  408. if c == '\b':
  409. self.linepos -= 1
  410. else:
  411. if c == '\r':
  412. pos = self.cmd_output.GetCurLine()[1]
  413. # self.cmd_output.SetCurrentPos(pos)
  414. else:
  415. self.cmd_output.SetCurrentPos(self.linepos)
  416. self.cmd_output.ReplaceSelection(c)
  417. self.linepos = self.cmd_output.GetCurrentPos()
  418. if c != ' ':
  419. last_c = c
  420. if last_c not in ('0123456789'):
  421. self.cmd_output.AddTextWrapped('\n', wrap=None)
  422. self.linepos = -1
  423. else:
  424. self.linepos = -1 # don't force position
  425. if '\n' not in message:
  426. self.cmd_output.AddTextWrapped(message, wrap=60)
  427. else:
  428. self.cmd_output.AddTextWrapped(message, wrap=None)
  429. p2 = self.cmd_output.GetCurrentPos()
  430. if p2 >= p1:
  431. self.cmd_output.StartStyling(p1, 0xff)
  432. if type == 'error':
  433. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleError)
  434. elif type == 'warning':
  435. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleWarning)
  436. elif type == 'message':
  437. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleMessage)
  438. else: # unknown
  439. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleUnknown)
  440. self.cmd_output.EnsureCaretVisible()
  441. def OnCmdProgress(self, event):
  442. """!Update progress message info"""
  443. self.console_progressbar.SetValue(event.value)
  444. def OnCmdAbort(self, event):
  445. """!Abort running command"""
  446. self.cmdThread.abort()
  447. def OnCmdRun(self, event):
  448. """!Run command"""
  449. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  450. def OnCmdDone(self, event):
  451. """!Command done (or aborted)"""
  452. if event.aborted:
  453. # Thread aborted (using our convention of None return)
  454. self.WriteLog(_('Please note that the data are left in incosistent stage '
  455. 'and can be corrupted'), self.cmd_output.StyleWarning)
  456. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  457. _('Command aborted'),
  458. (time.time() - event.time)))
  459. # pid=self.cmdThread.requestId)
  460. self.btn_abort.Enable(False)
  461. else:
  462. try:
  463. # Process results here
  464. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  465. _('Command finished'),
  466. (time.time() - event.time)))
  467. except KeyError:
  468. # stopped deamon
  469. pass
  470. self.btn_abort.Enable(False)
  471. if event.onDone:
  472. event.onDone(returncode = event.returncode)
  473. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  474. self.cmd_output_timer.Stop()
  475. # set focus on prompt
  476. if self.parent.GetName() == "LayerManager":
  477. self.parent.cmdinput.SetFocus()
  478. self.btn_abort.Enable(False)
  479. else:
  480. # updated command dialog
  481. dialog = self.parent.parent
  482. if hasattr(self.parent.parent, "btn_abort"):
  483. dialog.btn_abort.Enable(False)
  484. if hasattr(self.parent.parent, "btn_cancel"):
  485. dialog.btn_cancel.Enable(True)
  486. if hasattr(self.parent.parent, "btn_clipboard"):
  487. dialog.btn_clipboard.Enable(True)
  488. if hasattr(self.parent.parent, "btn_help"):
  489. dialog.btn_help.Enable(True)
  490. if hasattr(self.parent.parent, "btn_run"):
  491. dialog.btn_run.Enable(True)
  492. if event.returncode == 0 and \
  493. not event.aborted and hasattr(dialog, "addbox") and \
  494. dialog.addbox.IsChecked():
  495. # add new map into layer tree
  496. if dialog.outputType in ('raster', 'vector'):
  497. # add layer into layer tree
  498. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  499. name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True, param='output')
  500. winName = self.parent.parent.parent.GetName()
  501. if winName == 'LayerManager':
  502. mapTree = self.parent.parent.parent.curr_page.maptree
  503. else: # GMConsole
  504. mapTree = self.parent.parent.parent.parent.curr_page.maptree
  505. if dialog.outputType == 'raster':
  506. lcmd = ['d.rast',
  507. 'map=%s' % name]
  508. else:
  509. lcmd = ['d.vect',
  510. 'map=%s' % name]
  511. mapTree.AddLayer(ltype=dialog.outputType,
  512. lcmd=lcmd,
  513. lname=name)
  514. if hasattr(dialog, "get_dcmd") and \
  515. dialog.get_dcmd is None and \
  516. dialog.closebox.IsChecked():
  517. time.sleep(1)
  518. dialog.Close()
  519. event.Skip()
  520. def OnProcessPendingOutputWindowEvents(self, event):
  521. self.ProcessPendingEvents()
  522. class GMStdout:
  523. """!GMConsole standard output
  524. Based on FrameOutErr.py
  525. Name: FrameOutErr.py
  526. Purpose: Redirecting stdout / stderr
  527. Author: Jean-Michel Fauth, Switzerland
  528. Copyright: (c) 2005-2007 Jean-Michel Fauth
  529. Licence: GPL
  530. """
  531. def __init__(self, parent):
  532. self.parent = parent # GMConsole
  533. def write(self, s):
  534. if len(s) == 0 or s == '\n':
  535. return
  536. for line in s.splitlines():
  537. if len(line) == 0:
  538. continue
  539. evt = wxCmdOutput(text=line + '\n',
  540. type='')
  541. wx.PostEvent(self.parent.cmd_output, evt)
  542. class GMStderr:
  543. """!GMConsole standard error output
  544. Based on FrameOutErr.py
  545. Name: FrameOutErr.py
  546. Purpose: Redirecting stdout / stderr
  547. Author: Jean-Michel Fauth, Switzerland
  548. Copyright: (c) 2005-2007 Jean-Michel Fauth
  549. Licence: GPL
  550. """
  551. def __init__(self, parent):
  552. self.parent = parent # GMConsole
  553. self.type = ''
  554. self.message = ''
  555. self.printMessage = False
  556. def write(self, s):
  557. if "GtkPizza" in s:
  558. return
  559. # remove/replace escape sequences '\b' or '\r' from stream
  560. progressValue = -1
  561. for line in s.splitlines():
  562. if len(line) == 0:
  563. continue
  564. if 'GRASS_INFO_PERCENT' in line:
  565. value = int(line.rsplit(':', 1)[1].strip())
  566. if value >= 0 and value < 100:
  567. progressValue = value
  568. else:
  569. progressValue = 0
  570. elif 'GRASS_INFO_MESSAGE' in line:
  571. self.type = 'message'
  572. self.message += line.split(':', 1)[1].strip() + '\n'
  573. elif 'GRASS_INFO_WARNING' in line:
  574. self.type = 'warning'
  575. self.message += line.split(':', 1)[1].strip() + '\n'
  576. elif 'GRASS_INFO_ERROR' in line:
  577. self.type = 'error'
  578. self.message += line.split(':', 1)[1].strip() + '\n'
  579. elif 'GRASS_INFO_END' in line:
  580. self.printMessage = True
  581. elif self.type == '':
  582. if len(line) == 0:
  583. continue
  584. evt = wxCmdOutput(text=line,
  585. type='')
  586. wx.PostEvent(self.parent.cmd_output, evt)
  587. elif len(line) > 0:
  588. self.message += line.strip() + '\n'
  589. if self.printMessage and len(self.message) > 0:
  590. evt = wxCmdOutput(text=self.message,
  591. type=self.type)
  592. wx.PostEvent(self.parent.cmd_output, evt)
  593. self.type = ''
  594. self.message = ''
  595. self.printMessage = False
  596. # update progress message
  597. if progressValue > -1:
  598. # self.gmgauge.SetValue(progressValue)
  599. evt = wxCmdProgress(value=progressValue)
  600. wx.PostEvent(self.parent.console_progressbar, evt)
  601. class GMStc(wx.stc.StyledTextCtrl):
  602. """!Styled GMConsole
  603. Based on FrameOutErr.py
  604. Name: FrameOutErr.py
  605. Purpose: Redirecting stdout / stderr
  606. Author: Jean-Michel Fauth, Switzerland
  607. Copyright: (c) 2005-2007 Jean-Michel Fauth
  608. Licence: GPL
  609. """
  610. def __init__(self, parent, id, margin=False, wrap=None):
  611. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  612. self.parent = parent
  613. #
  614. # styles
  615. #
  616. self.StyleDefault = 0
  617. self.StyleDefaultSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  618. self.StyleCommand = 1
  619. self.StyleCommandSpec = "face:Courier New,size:10,fore:#000000,back:#bcbcbc"
  620. self.StyleOutput = 2
  621. self.StyleOutputSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  622. # fatal error
  623. self.StyleError = 3
  624. self.StyleErrorSpec = "face:Courier New,size:10,fore:#7F0000,back:#FFFFFF"
  625. # warning
  626. self.StyleWarning = 4
  627. self.StyleWarningSpec = "face:Courier New,size:10,fore:#0000FF,back:#FFFFFF"
  628. # message
  629. self.StyleMessage = 5
  630. self.StyleMessageSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  631. # unknown
  632. self.StyleUnknown = 6
  633. self.StyleUnknownSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  634. # default and clear => init
  635. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  636. self.StyleClearAll()
  637. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  638. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  639. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  640. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  641. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  642. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  643. #
  644. # line margins
  645. #
  646. # TODO print number only from cmdlog
  647. self.SetMarginWidth(1, 0)
  648. self.SetMarginWidth(2, 0)
  649. if margin:
  650. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  651. self.SetMarginWidth(0, 30)
  652. else:
  653. self.SetMarginWidth(0, 0)
  654. #
  655. # miscellaneous
  656. #
  657. self.SetViewWhiteSpace(False)
  658. self.SetTabWidth(4)
  659. self.SetUseTabs(False)
  660. self.UsePopUp(True)
  661. self.SetSelBackground(True, "#FFFF00")
  662. self.SetUseHorizontalScrollBar(True)
  663. #
  664. # bindins
  665. #
  666. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  667. def OnDestroy(self, evt):
  668. """!The clipboard contents can be preserved after
  669. the app has exited"""
  670. wx.TheClipboard.Flush()
  671. evt.Skip()
  672. def AddTextWrapped(self, txt, wrap=None):
  673. """!Add string to text area.
  674. String is wrapped and linesep is also added to the end
  675. of the string"""
  676. if wrap:
  677. txt = textwrap.fill(txt, wrap) + '\n'
  678. else:
  679. if txt[-1] != '\n':
  680. txt += '\n'
  681. if '\r' in txt:
  682. self.parent.linePos = -1
  683. for seg in txt.split('\r'):
  684. if self.parent.linePos > -1:
  685. self.SetCurrentPos(self.parent.linePos)
  686. self.ReplaceSelection(seg)
  687. else:
  688. self.parent.linePos = self.GetCurrentPos()
  689. self.AddText(seg)
  690. else:
  691. self.parent.linePos = self.GetCurrentPos()
  692. try:
  693. self.AddText(txt)
  694. except UnicodeDecodeError:
  695. enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
  696. if enc:
  697. txt = unicode(txt, enc)
  698. elif os.environ.has_key('GRASS_DB_ENCODING'):
  699. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  700. else:
  701. txt = _('Unable to encode text. Please set encoding in GUI preferences.') + '\n'
  702. self.AddText(txt)