goutput.py 24 KB

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