goutput.py 24 KB

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