goutput.py 27 KB

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