goutput.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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.splitlines():
  181. # fill space
  182. if len(line) < self.lineWidth:
  183. diff = self.lineWidth - len(line)
  184. line += diff * ' '
  185. self.cmd_output.AddTextWrapped(line, wrap=wrap) # adds '\n'
  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] != '\n':
  301. self.history += '\n'
  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. if self.parent.notebook.GetSelection() != self.parent.goutput.pageid:
  323. textP = self.parent.notebook.GetPageText(self.parent.goutput.pageid)
  324. if textP[-1] != ')':
  325. textP += ' (...)'
  326. self.parent.notebook.SetPageText(self.parent.goutput.pageid,
  327. textP)
  328. # message prefix
  329. if type == 'warning':
  330. messege = 'WARNING: ' + message
  331. elif type == 'error':
  332. message = 'ERROR: ' + message
  333. p1 = self.cmd_output.GetEndStyled()
  334. self.cmd_output.GotoPos(p1)
  335. if '\b' in message:
  336. if self.linepos < 0:
  337. self.linepos = p1
  338. last_c = ''
  339. for c in message:
  340. if c == '\b':
  341. self.linepos -= 1
  342. else:
  343. if c == '\r':
  344. pos = self.cmd_output.GetCurLine()[1]
  345. # self.cmd_output.SetCurrentPos(pos)
  346. else:
  347. self.cmd_output.SetCurrentPos(self.linepos)
  348. self.cmd_output.ReplaceSelection(c)
  349. self.linepos = self.cmd_output.GetCurrentPos()
  350. if c != ' ':
  351. last_c = c
  352. if last_c not in ('0123456789'):
  353. self.cmd_output.AddTextWrapped('\n', wrap=None)
  354. self.linepos = -1
  355. else:
  356. self.linepos = -1 # don't force position
  357. if '\n' not in message:
  358. self.cmd_output.AddTextWrapped(message, wrap=60)
  359. else:
  360. self.cmd_output.AddTextWrapped(message, wrap=None)
  361. p2 = self.cmd_output.GetCurrentPos()
  362. if p2 >= p1:
  363. self.cmd_output.StartStyling(p1, 0xff)
  364. if type == 'error':
  365. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleError)
  366. elif type == 'warning':
  367. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleWarning)
  368. elif type == 'message':
  369. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleMessage)
  370. else: # unknown
  371. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleUnknown)
  372. self.cmd_output.EnsureCaretVisible()
  373. def OnCmdProgress(self, event):
  374. """Update progress message info"""
  375. self.console_progressbar.SetValue(event.value)
  376. def OnCmdAbort(self, event):
  377. """Abort running command"""
  378. self.cmdThread.abort()
  379. def OnCmdRun(self, event):
  380. """Run command"""
  381. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  382. def OnCmdDone(self, event):
  383. """Command done (or aborted)"""
  384. if event.aborted:
  385. # Thread aborted (using our convention of None return)
  386. self.WriteLog(_('Please note that the data are left in incosistent stage '
  387. 'and can be corrupted'), self.cmd_output.StyleWarning)
  388. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  389. _('Command aborted'),
  390. (time.time() - event.time)))
  391. # pid=self.cmdThread.requestId)
  392. else:
  393. try:
  394. # Process results here
  395. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  396. _('Command finished'),
  397. (time.time() - event.time)))
  398. # pid=event.pid)
  399. except KeyError:
  400. # stopped deamon
  401. pass
  402. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  403. self.cmd_output_timer.Stop()
  404. # updated command dialog
  405. if hasattr(self.parent.parent, "btn_run"):
  406. dialog = self.parent.parent
  407. if hasattr(self.parent.parent, "btn_abort"):
  408. dialog.btn_abort.Enable(False)
  409. if hasattr(self.parent.parent, "btn_cancel"):
  410. dialog.btn_cancel.Enable(True)
  411. if hasattr(self.parent.parent, "btn_clipboard"):
  412. dialog.btn_clipboard.Enable(True)
  413. if hasattr(self.parent.parent, "btn_help"):
  414. dialog.btn_help.Enable(True)
  415. dialog.btn_run.Enable(True)
  416. if event.returncode == 0 and \
  417. not event.aborted and hasattr(dialog, "addbox") and \
  418. dialog.addbox.IsChecked():
  419. # add new map into layer tree
  420. if dialog.outputType in ('raster', 'vector'):
  421. # add layer into layer tree
  422. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  423. name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True, param='output')
  424. winName = self.parent.parent.parent.GetName()
  425. if winName == 'LayerManager':
  426. mapTree = self.parent.parent.parent.curr_page.maptree
  427. else: # GMConsole
  428. mapTree = self.parent.parent.parent.parent.curr_page.maptree
  429. if dialog.outputType == 'raster':
  430. lcmd = ['d.rast',
  431. 'map=%s' % name]
  432. else:
  433. lcmd = ['d.vect',
  434. 'map=%s' % name]
  435. mapTree.AddLayer(ltype=dialog.outputType,
  436. lcmd=lcmd,
  437. lname=name)
  438. if dialog.get_dcmd is None and \
  439. dialog.closebox.IsChecked():
  440. time.sleep(1)
  441. dialog.Close()
  442. event.Skip()
  443. def OnProcessPendingOutputWindowEvents(self, event):
  444. self.ProcessPendingEvents()
  445. class GMStdout:
  446. """GMConsole standard output
  447. Based on FrameOutErr.py
  448. Name: FrameOutErr.py
  449. Purpose: Redirecting stdout / stderr
  450. Author: Jean-Michel Fauth, Switzerland
  451. Copyright: (c) 2005-2007 Jean-Michel Fauth
  452. Licence: GPL
  453. """
  454. def __init__(self, parent):
  455. self.parent = parent # GMConsole
  456. def write(self, s):
  457. if len(s) == 0 or s == '\n':
  458. return
  459. for line in s.splitlines():
  460. if len(line) == 0:
  461. continue
  462. evt = wxCmdOutput(text=line + '\n',
  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. # remove/replace escape sequences '\b' or '\r' from stream
  483. progressValue = -1
  484. for line in s.splitlines():
  485. if len(line) == 0:
  486. continue
  487. if 'GRASS_INFO_PERCENT' in line:
  488. value = int(line.rsplit(':', 1)[1].strip())
  489. if value >= 0 and value < 100:
  490. progressValue = value
  491. else:
  492. progressValue = 0
  493. elif 'GRASS_INFO_MESSAGE' in line:
  494. self.type = 'message'
  495. self.message = line.split(':', 1)[1].strip()
  496. elif 'GRASS_INFO_WARNING' in line:
  497. self.type = 'warning'
  498. self.message = line.split(':', 1)[1].strip()
  499. elif 'GRASS_INFO_ERROR' in line:
  500. self.type = 'error'
  501. self.message = line.split(':', 1)[1].strip()
  502. elif 'GRASS_INFO_END' in line:
  503. self.printMessage = True
  504. elif self.type == '':
  505. if len(line) == 0:
  506. continue
  507. evt = wxCmdOutput(text=line,
  508. type='')
  509. wx.PostEvent(self.parent.cmd_output, evt)
  510. elif len(line) > 0:
  511. self.message += line.strip() + '\n'
  512. if self.printMessage and len(self.message) > 0:
  513. evt = wxCmdOutput(text=self.message,
  514. type=self.type)
  515. wx.PostEvent(self.parent.cmd_output, evt)
  516. self.type = ''
  517. self.message = ''
  518. self.printMessage = False
  519. # update progress message
  520. if progressValue > -1:
  521. # self.gmgauge.SetValue(progressValue)
  522. evt = wxCmdProgress(value=progressValue)
  523. wx.PostEvent(self.parent.console_progressbar, evt)
  524. class GMStc(wx.stc.StyledTextCtrl):
  525. """Styled GMConsole
  526. Based on FrameOutErr.py
  527. Name: FrameOutErr.py
  528. Purpose: Redirecting stdout / stderr
  529. Author: Jean-Michel Fauth, Switzerland
  530. Copyright: (c) 2005-2007 Jean-Michel Fauth
  531. Licence: GPL
  532. """
  533. def __init__(self, parent, id, margin=False, wrap=None):
  534. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  535. self.parent = parent
  536. #
  537. # styles
  538. #
  539. self.StyleDefault = 0
  540. self.StyleDefaultSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  541. self.StyleCommand = 1
  542. self.StyleCommandSpec = "face:Courier New,size:10,fore:#000000,back:#bcbcbc"
  543. self.StyleOutput = 2
  544. self.StyleOutputSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  545. # fatal error
  546. self.StyleError = 3
  547. self.StyleErrorSpec = "face:Courier New,size:10,fore:#7F0000,back:#FFFFFF"
  548. # warning
  549. self.StyleWarning = 4
  550. self.StyleWarningSpec = "face:Courier New,size:10,fore:#0000FF,back:#FFFFFF"
  551. # message
  552. self.StyleMessage = 5
  553. self.StyleMessageSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  554. # unknown
  555. self.StyleUnknown = 6
  556. self.StyleUnknownSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  557. # default and clear => init
  558. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  559. self.StyleClearAll()
  560. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  561. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  562. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  563. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  564. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  565. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  566. #
  567. # line margins
  568. #
  569. # TODO print number only from cmdlog
  570. self.SetMarginWidth(1, 0)
  571. self.SetMarginWidth(2, 0)
  572. if margin:
  573. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  574. self.SetMarginWidth(0, 30)
  575. else:
  576. self.SetMarginWidth(0, 0)
  577. #
  578. # miscellaneous
  579. #
  580. self.SetViewWhiteSpace(False)
  581. self.SetTabWidth(4)
  582. self.SetUseTabs(False)
  583. self.UsePopUp(True)
  584. self.SetSelBackground(True, "#FFFF00")
  585. self.SetUseHorizontalScrollBar(True)
  586. #
  587. # bindins
  588. #
  589. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  590. def OnDestroy(self, evt):
  591. """The clipboard contents can be preserved after
  592. the app has exited"""
  593. wx.TheClipboard.Flush()
  594. evt.Skip()
  595. def AddTextWrapped(self, txt, wrap=None):
  596. """Add string to text area.
  597. String is wrapped and linesep is also added to the end
  598. of the string"""
  599. if wrap:
  600. txt = textwrap.fill(txt, wrap) + '\n'
  601. else:
  602. if txt[-1] != '\n':
  603. txt += '\n'
  604. if '\r' in txt:
  605. self.parent.linePos = -1
  606. for seg in txt.split('\r'):
  607. if self.parent.linePos > -1:
  608. self.SetCurrentPos(self.parent.linePos)
  609. self.ReplaceSelection(seg)
  610. else:
  611. self.parent.linePos = self.GetCurrentPos()
  612. self.AddText(seg)
  613. else:
  614. self.parent.linePos = self.GetCurrentPos()
  615. try:
  616. self.AddText(txt)
  617. except UnicodeDecodeError:
  618. enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
  619. if enc:
  620. txt = unicode(txt, enc)
  621. elif os.environ.has_key('GRASS_DB_ENCODING'):
  622. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  623. else:
  624. txt = _('Unable to encode text. Please set encoding in GUI preferences.') + '\n'
  625. self.AddText(txt)