goutput.py 27 KB

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