goutput.py 25 KB

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