goutput.py 31 KB

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