goutput.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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, compReg=True):
  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. @param command command (list)
  201. @param compReg if true use computation region
  202. """
  203. # map display window available ?
  204. try:
  205. curr_disp = self.parent.curr_page.maptree.mapdisplay
  206. self.Map = curr_disp.GetRender()
  207. except:
  208. curr_disp = None
  209. # command given as a string ?
  210. try:
  211. cmdlist = command.strip().split(' ')
  212. except:
  213. cmdlist = command
  214. if cmdlist[0] in globalvar.grassCmd['all']:
  215. # send GRASS command without arguments to GUI command interface
  216. # except display commands (they are handled differently)
  217. if cmdlist[0][0:2] == "d.":
  218. #
  219. # display GRASS commands
  220. #
  221. try:
  222. layertype = {'d.rast' : 'raster',
  223. 'd.rgb' : 'rgb',
  224. 'd.his' : 'his',
  225. 'd.shaded' : 'shaded',
  226. 'd.legend' : 'rastleg',
  227. 'd.rast.arrow' : 'rastarrow',
  228. 'd.rast.num' : 'rastnum',
  229. 'd.vect' : 'vector',
  230. 'd.vect.thematic': 'thememap',
  231. 'd.vect.chart' : 'themechart',
  232. 'd.grid' : 'grid',
  233. 'd.geodesic' : 'geodesic',
  234. 'd.rhumbline' : 'rhumb',
  235. 'd.labels' : 'labels'}[cmdlist[0]]
  236. except KeyError:
  237. wx.MessageBox(message=_("Command '%s' not yet implemented.") % cmdlist[0])
  238. return None
  239. # add layer into layer tree
  240. self.parent.curr_page.maptree.AddLayer(ltype=layertype,
  241. lcmd=cmdlist)
  242. else:
  243. #
  244. # other GRASS commands (r|v|g|...)
  245. #
  246. # activate computational region (set with g.region)
  247. # for all non-display commands.
  248. if compReg:
  249. tmpreg = os.getenv("GRASS_REGION")
  250. if os.environ.has_key("GRASS_REGION"):
  251. del os.environ["GRASS_REGION"]
  252. if len(cmdlist) == 1:
  253. import menuform
  254. # process GRASS command without argument
  255. menuform.GUI().ParseCommand(cmdlist, parentframe=self)
  256. else:
  257. # process GRASS command with argument
  258. self.cmdThread.RunCmd(GrassCmd,
  259. cmdlist,
  260. self.cmd_stdout, self.cmd_stderr)
  261. self.cmd_output_timer.Start(50)
  262. return None
  263. # deactivate computational region and return to display settings
  264. if compReg and tmpreg:
  265. os.environ["GRASS_REGION"] = tmpreg
  266. else:
  267. # Send any other command to the shell. Send output to
  268. # console output window
  269. # if command is not a GRASS command, treat it like a shell command
  270. try:
  271. generalCmd = gcmd.Command(cmdlist,
  272. stdout=self.cmd_stdout,
  273. stderr=self.cmd_stderr)
  274. except gcmd.CmdError, e:
  275. print >> sys.stderr, e
  276. return None
  277. def ClearHistory(self, event):
  278. """Clear history of commands"""
  279. self.cmd_output.ClearAll()
  280. self.console_progressbar.SetValue(0)
  281. def SaveHistory(self, event):
  282. """Save history of commands"""
  283. self.history = self.cmd_output.GetSelectedText()
  284. if self.history == '':
  285. self.history = self.cmd_output.GetText()
  286. # add newline if needed
  287. if len(self.history) > 0 and self.history[-1] != os.linesep:
  288. self.history += os.linesep
  289. wildcard = "Text file (*.txt)|*.txt"
  290. dlg = wx.FileDialog(
  291. self, message=_("Save file as..."), defaultDir=os.getcwd(),
  292. defaultFile="grass_cmd_history.txt", wildcard=wildcard,
  293. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  294. # Show the dialog and retrieve the user response. If it is the OK response,
  295. # process the data.
  296. if dlg.ShowModal() == wx.ID_OK:
  297. path = dlg.GetPath()
  298. output = open(path, "w")
  299. output.write(self.history)
  300. output.close()
  301. dlg.Destroy()
  302. def GetCmd(self):
  303. """Get running command or None"""
  304. return self.requestQ.get()
  305. def OnCmdOutput(self, event):
  306. """Print command output"""
  307. message = event.text
  308. type = event.type
  309. # switch to 'Command output'
  310. if self.parent.notebook.GetSelection() != self.parent.goutput.pageid:
  311. self.parent.notebook.SetSelection(self.parent.goutput.pageid)
  312. # message prefix
  313. if type == 'warning':
  314. messege = 'WARNING: ' + message
  315. elif type == 'error':
  316. message = 'ERROR: ' + message
  317. p1 = self.cmd_output.GetEndStyled()
  318. self.cmd_output.GotoPos(p1)
  319. if '\b' in message:
  320. if self.linepos < 0:
  321. self.linepos = p1
  322. last_c = ''
  323. for c in message:
  324. if c == '\b':
  325. self.linepos -= 1
  326. else:
  327. if c == '\r':
  328. pos = self.cmd_output.GetCurLine()[1]
  329. # self.cmd_output.SetCurrentPos(pos)
  330. else:
  331. self.cmd_output.SetCurrentPos(self.linepos)
  332. self.cmd_output.ReplaceSelection(c)
  333. self.linepos = self.cmd_output.GetCurrentPos()
  334. if c != ' ':
  335. last_c = c
  336. if last_c not in ('0123456789'):
  337. self.cmd_output.AddTextWrapped('\n', wrap=None)
  338. self.linepos = -1
  339. else:
  340. self.linepos = -1 # don't force position
  341. if os.linesep not in message:
  342. self.cmd_output.AddTextWrapped(message, wrap=60)
  343. else:
  344. self.cmd_output.AddTextWrapped(message, wrap=None)
  345. p2 = self.cmd_output.GetCurrentPos()
  346. if p2 >= p1:
  347. self.cmd_output.StartStyling(p1, 0xff)
  348. if type == 'error':
  349. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleError)
  350. elif type == 'warning':
  351. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleWarning)
  352. elif type == 'message':
  353. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleMessage)
  354. else: # unknown
  355. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleUnknown)
  356. self.cmd_output.EnsureCaretVisible()
  357. def OnCmdProgress(self, event):
  358. """Update progress message info"""
  359. self.console_progressbar.SetValue(event.value)
  360. def OnCmdAbort(self, event):
  361. """Abort running command"""
  362. self.cmdThread.abort()
  363. def OnCmdRun(self, event):
  364. """Run command"""
  365. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  366. def OnCmdDone(self, event):
  367. """Command done (or aborted)"""
  368. if event.aborted:
  369. # Thread aborted (using our convention of None return)
  370. self.WriteLog(_('Please note that the data are left in incosistent stage '
  371. 'and can be corrupted'), self.cmd_output.StyleWarning)
  372. self.WriteCmdLog('(%s) %s' % (str(time.ctime()),
  373. _('Command aborted')))
  374. # pid=self.cmdThread.requestId)
  375. else:
  376. try:
  377. # Process results here
  378. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  379. _('Command finished'),
  380. (time.time() - event.time)))
  381. # pid=event.pid)
  382. except KeyError:
  383. # stopped deamon
  384. pass
  385. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  386. self.cmd_output_timer.Stop()
  387. # updated command dialog
  388. if hasattr(self.parent.parent, "btn_run"):
  389. dialog = self.parent.parent
  390. if hasattr(self.parent.parent, "btn_abort"):
  391. dialog.btn_abort.Enable(False)
  392. if hasattr(self.parent.parent, "btn_cancel"):
  393. dialog.btn_cancel.Enable(True)
  394. if hasattr(self.parent.parent, "btn_clipboard"):
  395. dialog.btn_clipboard.Enable(True)
  396. if hasattr(self.parent.parent, "btn_help"):
  397. dialog.btn_help.Enable(True)
  398. dialog.btn_run.Enable(True)
  399. if not event.aborted and hasattr(dialog, "addbox") and \
  400. dialog.addbox.IsChecked():
  401. # add new map into layer tree
  402. if dialog.outputType in ('raster', 'vector'):
  403. # add layer into layer tree
  404. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  405. name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True, param='output')
  406. mapTree = self.parent.parent.parent.curr_page.maptree
  407. if dialog.outputType == 'raster':
  408. lcmd = ['d.rast',
  409. 'map=%s' % name]
  410. else:
  411. lcmd = ['d.vect',
  412. 'map=%s' % name]
  413. mapTree.AddLayer(ltype=dialog.outputType,
  414. lcmd=lcmd,
  415. lname=name)
  416. if dialog.get_dcmd is None and \
  417. dialog.closebox.IsChecked():
  418. time.sleep(1)
  419. dialog.Close()
  420. event.Skip()
  421. def OnProcessPendingOutputWindowEvents(self, event):
  422. self.ProcessPendingEvents()
  423. class GMStdout:
  424. """GMConsole standard output
  425. Based on FrameOutErr.py
  426. Name: FrameOutErr.py
  427. Purpose: Redirecting stdout / stderr
  428. Author: Jean-Michel Fauth, Switzerland
  429. Copyright: (c) 2005-2007 Jean-Michel Fauth
  430. Licence: GPL
  431. """
  432. def __init__(self, parent):
  433. self.parent = parent # GMConsole
  434. def write(self, s):
  435. if len(s) == 0 or s == '\n':
  436. return
  437. s = s.replace('\n', os.linesep)
  438. for line in s.split(os.linesep):
  439. if len(line) == 0:
  440. continue
  441. evt = wxCmdOutput(text=line + os.linesep,
  442. type='')
  443. wx.PostEvent(self.parent.cmd_output, evt)
  444. class GMStderr:
  445. """GMConsole standard error output
  446. Based on FrameOutErr.py
  447. Name: FrameOutErr.py
  448. Purpose: Redirecting stdout / stderr
  449. Author: Jean-Michel Fauth, Switzerland
  450. Copyright: (c) 2005-2007 Jean-Michel Fauth
  451. Licence: GPL
  452. """
  453. def __init__(self, parent):
  454. self.parent = parent # GMConsole
  455. self.type = ''
  456. self.message = ''
  457. self.printMessage = False
  458. def write(self, s):
  459. s = s.replace('\n', os.linesep)
  460. # remove/replace escape sequences '\b' or '\r' from stream
  461. progressValue = -1
  462. for line in s.split(os.linesep):
  463. if len(line) == 0:
  464. continue
  465. if 'GRASS_INFO_PERCENT' in line:
  466. value = int(line.rsplit(':', 1)[1].strip())
  467. if value >= 0 and value < 100:
  468. progressValue = value
  469. else:
  470. progressValue = 0
  471. elif 'GRASS_INFO_MESSAGE' in line:
  472. self.type = 'message'
  473. self.message = line.split(':', 1)[1].strip()
  474. elif 'GRASS_INFO_WARNING' in line:
  475. self.type = 'warning'
  476. self.message = line.split(':', 1)[1].strip()
  477. elif 'GRASS_INFO_ERROR' in line:
  478. self.type = 'error'
  479. self.message = line.split(':', 1)[1].strip()
  480. elif 'GRASS_INFO_END' in line:
  481. self.printMessage = True
  482. elif self.type == '':
  483. if len(line) == 0:
  484. continue
  485. evt = wxCmdOutput(text=line,
  486. type='')
  487. wx.PostEvent(self.parent.cmd_output, evt)
  488. elif len(line) > 0:
  489. self.message += line.strip() + os.linesep
  490. if self.printMessage and len(self.message) > 0:
  491. evt = wxCmdOutput(text=self.message,
  492. type=self.type)
  493. wx.PostEvent(self.parent.cmd_output, evt)
  494. self.type = ''
  495. self.message = ''
  496. self.printMessage = False
  497. # update progress message
  498. if progressValue > -1:
  499. # self.gmgauge.SetValue(progressValue)
  500. evt = wxCmdProgress(value=progressValue)
  501. wx.PostEvent(self.parent.console_progressbar, evt)
  502. class GMStc(wx.stc.StyledTextCtrl):
  503. """Styled GMConsole
  504. Based on FrameOutErr.py
  505. Name: FrameOutErr.py
  506. Purpose: Redirecting stdout / stderr
  507. Author: Jean-Michel Fauth, Switzerland
  508. Copyright: (c) 2005-2007 Jean-Michel Fauth
  509. Licence: GPL
  510. """
  511. def __init__(self, parent, id, margin=False, wrap=None):
  512. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  513. self.parent = parent
  514. #
  515. # styles
  516. #
  517. self.StyleDefault = 0
  518. self.StyleDefaultSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  519. self.StyleCommand = 1
  520. self.StyleCommandSpec = "face:Courier New,size:10,fore:#000000,back:#bcbcbc"
  521. self.StyleOutput = 2
  522. self.StyleOutputSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  523. # fatal error
  524. self.StyleError = 3
  525. self.StyleErrorSpec = "face:Courier New,size:10,fore:#7F0000,back:#FFFFFF"
  526. # warning
  527. self.StyleWarning = 4
  528. self.StyleWarningSpec = "face:Courier New,size:10,fore:#0000FF,back:#FFFFFF"
  529. # message
  530. self.StyleMessage = 5
  531. self.StyleMessageSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  532. # unknown
  533. self.StyleUnknown = 6
  534. self.StyleUnknownSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  535. # default and clear => init
  536. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  537. self.StyleClearAll()
  538. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  539. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  540. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  541. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  542. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  543. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  544. #
  545. # line margins
  546. #
  547. # TODO print number only from cmdlog
  548. self.SetMarginWidth(1, 0)
  549. self.SetMarginWidth(2, 0)
  550. if margin:
  551. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  552. self.SetMarginWidth(0, 30)
  553. else:
  554. self.SetMarginWidth(0, 0)
  555. #
  556. # miscellaneous
  557. #
  558. self.SetViewWhiteSpace(False)
  559. self.SetTabWidth(4)
  560. self.SetUseTabs(False)
  561. self.UsePopUp(True)
  562. self.SetSelBackground(True, "#FFFF00")
  563. self.SetUseHorizontalScrollBar(True)
  564. #
  565. # bindins
  566. #
  567. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  568. def OnDestroy(self, evt):
  569. """The clipboard contents can be preserved after
  570. the app has exited"""
  571. wx.TheClipboard.Flush()
  572. evt.Skip()
  573. def AddTextWrapped(self, txt, wrap=None):
  574. """Add string to text area.
  575. String is wrapped and linesep is also added to the end
  576. of the string"""
  577. if wrap:
  578. txt = textwrap.fill(txt, wrap) + os.linesep
  579. else:
  580. if txt[-1] != os.linesep:
  581. txt += os.linesep
  582. if '\r' in txt:
  583. self.parent.linePos = -1
  584. for seg in txt.split('\r'):
  585. if self.parent.linePos > -1:
  586. self.SetCurrentPos(self.parent.linePos)
  587. self.ReplaceSelection(seg)
  588. else:
  589. self.parent.linePos = self.GetCurrentPos()
  590. self.AddText(seg)
  591. else:
  592. self.parent.linePos = self.GetCurrentPos()
  593. self.AddText(txt)