goutput.py 26 KB

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