goutput.py 23 KB

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