goutput.py 26 KB

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