goutput.py 26 KB

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