goutput.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. """!
  2. @package gui_core.goutput
  3. @brief Command output widgets
  4. Classes:
  5. - goutput::CmdThread
  6. - goutput::GConsole
  7. - goutput::GStdout
  8. - goutput::GStderr
  9. - goutput::GStc
  10. (C) 2007-2012 by the GRASS Development Team
  11. This program is free software under the GNU General Public License
  12. (>=v2). Read the file COPYING that comes with GRASS for details.
  13. @author Michael Barton (Arizona State University)
  14. @author Martin Landa <landa.martin gmail.com>
  15. @author Vaclav Petras <wenzeslaus gmail.com> (copy&paste customization)
  16. """
  17. import os
  18. import sys
  19. import textwrap
  20. import time
  21. import threading
  22. import Queue
  23. import codecs
  24. import locale
  25. import wx
  26. from wx import stc
  27. from wx.lib.newevent import NewEvent
  28. import grass.script as grass
  29. from grass.script import task as gtask
  30. from core import globalvar
  31. from core import utils
  32. from core.gcmd import CommandThread, GMessage, GError, GException, EncodeString
  33. from gui_core.forms import GUI
  34. from gui_core.prompt import GPromptSTC
  35. from core.debug import Debug
  36. from core.settings import UserSettings, GetDisplayVectSettings
  37. from gui_core.ghelp import SearchModuleWindow
  38. wxCmdOutput, EVT_CMD_OUTPUT = NewEvent()
  39. wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
  40. wxCmdRun, EVT_CMD_RUN = NewEvent()
  41. wxCmdDone, EVT_CMD_DONE = NewEvent()
  42. wxCmdAbort, EVT_CMD_ABORT = NewEvent()
  43. wxCmdPrepare, EVT_CMD_PREPARE = NewEvent()
  44. GC_EMPTY = 0
  45. GC_SEARCH = 1
  46. GC_PROMPT = 2
  47. def GrassCmd(cmd, env = None, stdout = None, stderr = None):
  48. """!Return GRASS command thread"""
  49. return CommandThread(cmd, env = env,
  50. stdout = stdout, stderr = stderr)
  51. class CmdThread(threading.Thread):
  52. """!Thread for GRASS commands"""
  53. requestId = 0
  54. def __init__(self, parent, requestQ = None, resultQ = None, **kwds):
  55. threading.Thread.__init__(self, **kwds)
  56. if requestQ is None:
  57. self.requestQ = Queue.Queue()
  58. else:
  59. self.requestQ = requestQ
  60. if resultQ is None:
  61. self.resultQ = Queue.Queue()
  62. else:
  63. self.resultQ = resultQ
  64. self.setDaemon(True)
  65. self.parent = parent # GConsole
  66. self._want_abort_all = False
  67. self.start()
  68. def RunCmd(self, *args, **kwds):
  69. """!Run command in queue
  70. @param args unnamed command arguments
  71. @param kwds named command arguments
  72. @return request id in queue
  73. """
  74. CmdThread.requestId += 1
  75. self.requestCmd = None
  76. self.requestQ.put((CmdThread.requestId, args, kwds))
  77. return CmdThread.requestId
  78. def SetId(self, id):
  79. """!Set starting id"""
  80. CmdThread.requestId = id
  81. def run(self):
  82. os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
  83. while True:
  84. requestId, args, kwds = self.requestQ.get()
  85. for key in ('callable', 'onDone', 'onPrepare', 'userData'):
  86. if key in kwds:
  87. vars()[key] = kwds[key]
  88. del kwds[key]
  89. else:
  90. vars()[key] = None
  91. if not vars()['callable']:
  92. vars()['callable'] = GrassCmd
  93. requestTime = time.time()
  94. # prepare
  95. event = wxCmdPrepare(cmd = args[0],
  96. time = requestTime,
  97. pid = requestId,
  98. onPrepare = vars()['onPrepare'],
  99. userData = vars()['userData'])
  100. wx.PostEvent(self.parent, event)
  101. # run command
  102. event = wxCmdRun(cmd = args[0],
  103. pid = requestId)
  104. wx.PostEvent(self.parent, event)
  105. time.sleep(.1)
  106. self.requestCmd = vars()['callable'](*args, **kwds)
  107. if self._want_abort_all:
  108. self.requestCmd.abort()
  109. if self.requestQ.empty():
  110. self._want_abort_all = False
  111. self.resultQ.put((requestId, self.requestCmd.run()))
  112. try:
  113. returncode = self.requestCmd.module.returncode
  114. except AttributeError:
  115. returncode = 0 # being optimistic
  116. try:
  117. aborted = self.requestCmd.aborted
  118. except AttributeError:
  119. aborted = False
  120. time.sleep(.1)
  121. # set default color table for raster data
  122. if UserSettings.Get(group = 'rasterLayer', key = 'colorTable', subkey = 'enabled') and \
  123. args[0][0][:2] == 'r.':
  124. colorTable = UserSettings.Get(group = 'rasterLayer', key = 'colorTable', subkey = 'selection')
  125. mapName = None
  126. if args[0][0] == 'r.mapcalc':
  127. try:
  128. mapName = args[0][1].split('=', 1)[0].strip()
  129. except KeyError:
  130. pass
  131. else:
  132. moduleInterface = GUI(show = None).ParseCommand(args[0])
  133. outputParam = moduleInterface.get_param(value = 'output', raiseError = False)
  134. if outputParam and outputParam['prompt'] == 'raster':
  135. mapName = outputParam['value']
  136. if mapName:
  137. argsColor = list(args)
  138. argsColor[0] = [ 'r.colors',
  139. 'map=%s' % mapName,
  140. 'color=%s' % colorTable ]
  141. self.requestCmdColor = vars()['callable'](*argsColor, **kwds)
  142. self.resultQ.put((requestId, self.requestCmdColor.run()))
  143. event = wxCmdDone(cmd = args[0],
  144. aborted = aborted,
  145. returncode = returncode,
  146. time = requestTime,
  147. pid = requestId,
  148. onDone = vars()['onDone'],
  149. userData = vars()['userData'])
  150. # send event
  151. wx.PostEvent(self.parent, event)
  152. def abort(self, abortall = True):
  153. """!Abort command(s)"""
  154. if abortall:
  155. self._want_abort_all = True
  156. self.requestCmd.abort()
  157. if self.requestQ.empty():
  158. self._want_abort_all = False
  159. class GConsole(wx.SplitterWindow):
  160. """!Create and manage output console for commands run by GUI.
  161. """
  162. def __init__(self, parent, id = wx.ID_ANY, margin = False,
  163. frame = None, notebook = None,
  164. style = wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  165. gcstyle = GC_EMPTY,
  166. **kwargs):
  167. wx.SplitterWindow.__init__(self, parent, id, style = style, *kwargs)
  168. self.SetName("GConsole")
  169. self.panelOutput = wx.Panel(parent = self, id = wx.ID_ANY)
  170. self.panelPrompt = wx.Panel(parent = self, id = wx.ID_ANY)
  171. # initialize variables
  172. self.parent = parent # GMFrame | CmdPanel | ?
  173. if frame:
  174. self.frame = frame
  175. else:
  176. self.frame = parent
  177. if notebook:
  178. self._notebook = notebook
  179. else:
  180. self._notebook = self.parent.notebook
  181. self._gcstyle = gcstyle
  182. self.lineWidth = 80
  183. # remember position of line begining (used for '\r')
  184. self.linePos = -1
  185. # create queues
  186. self.requestQ = Queue.Queue()
  187. self.resultQ = Queue.Queue()
  188. # progress bar
  189. self.progressbar = wx.Gauge(parent = self.panelOutput, id = wx.ID_ANY,
  190. range = 100, pos = (110, 50), size = (-1, 25),
  191. style = wx.GA_HORIZONTAL)
  192. self.progressbar.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
  193. # text control for command output
  194. self.cmdOutput = GStc(parent = self.panelOutput, id = wx.ID_ANY, margin = margin,
  195. wrap = None)
  196. self.cmdOutputTimer = wx.Timer(self.cmdOutput, id = wx.ID_ANY)
  197. self.cmdOutput.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
  198. self.cmdOutput.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  199. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  200. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  201. self.Bind(EVT_CMD_PREPARE, self.OnCmdPrepare)
  202. # search & command prompt
  203. # move to the if below
  204. # search depends on cmd prompt
  205. self.cmdPrompt = GPromptSTC(parent = self)
  206. if not self._gcstyle & GC_PROMPT:
  207. self.cmdPrompt.Hide()
  208. if self._gcstyle & GC_SEARCH:
  209. self.infoCollapseLabelExp = _("Click here to show search module engine")
  210. self.infoCollapseLabelCol = _("Click here to hide search module engine")
  211. self.searchPane = wx.CollapsiblePane(parent = self.panelOutput,
  212. label = self.infoCollapseLabelExp,
  213. style = wx.CP_DEFAULT_STYLE |
  214. wx.CP_NO_TLW_RESIZE | wx.EXPAND)
  215. self.MakeSearchPaneContent(self.searchPane.GetPane())
  216. self.searchPane.Collapse(True)
  217. self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnSearchPaneChanged, self.searchPane)
  218. self.search.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  219. else:
  220. self.search = None
  221. # stream redirection
  222. self.cmdStdOut = GStdout(self)
  223. self.cmdStdErr = GStderr(self)
  224. # thread
  225. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  226. self.outputBox = wx.StaticBox(parent = self.panelOutput, id = wx.ID_ANY,
  227. label = " %s " % _("Output window"))
  228. if self._gcstyle & GC_PROMPT:
  229. cmdLabel = _("Command prompt")
  230. else:
  231. cmdLabel = _("Command")
  232. self.cmdBox = wx.StaticBox(parent = self.panelOutput, id = wx.ID_ANY,
  233. label = " %s " % cmdLabel)
  234. # buttons
  235. self.btnOutputClear = wx.Button(parent = self.panelOutput, id = wx.ID_CLEAR)
  236. self.btnOutputClear.SetToolTipString(_("Clear output window content"))
  237. self.btnCmdClear = wx.Button(parent = self.panelOutput, id = wx.ID_CLEAR)
  238. self.btnCmdClear.SetToolTipString(_("Clear command prompt content"))
  239. self.btnOutputSave = wx.Button(parent = self.panelOutput, id = wx.ID_SAVE)
  240. self.btnOutputSave.SetToolTipString(_("Save output window content to the file"))
  241. self.btnCmdAbort = wx.Button(parent = self.panelOutput, id = wx.ID_STOP)
  242. self.btnCmdAbort.SetToolTipString(_("Abort running command"))
  243. self.btnCmdAbort.Enable(False)
  244. self.btnCmdProtocol = wx.ToggleButton(parent = self.panelOutput, id = wx.ID_ANY,
  245. label = _("&Protocol"),
  246. size = self.btnCmdClear.GetSize())
  247. self.btnCmdProtocol.SetToolTipString(_("Toggle to save list of executed commands into file; "
  248. "content saved when switching off."))
  249. if not self._gcstyle & GC_PROMPT:
  250. self.btnCmdClear.Hide()
  251. self.btnCmdProtocol.Hide()
  252. self.btnCmdClear.Bind(wx.EVT_BUTTON, self.cmdPrompt.OnCmdErase)
  253. self.btnOutputClear.Bind(wx.EVT_BUTTON, self.OnOutputClear)
  254. self.btnOutputSave.Bind(wx.EVT_BUTTON, self.OnOutputSave)
  255. self.btnCmdAbort.Bind(wx.EVT_BUTTON, self.OnCmdAbort)
  256. self.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  257. self.btnCmdProtocol.Bind(wx.EVT_TOGGLEBUTTON, self.OnCmdProtocol)
  258. self._layout()
  259. def _layout(self):
  260. """!Do layout"""
  261. outputSizer = wx.BoxSizer(wx.VERTICAL)
  262. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  263. outBtnSizer = wx.StaticBoxSizer(self.outputBox, wx.HORIZONTAL)
  264. cmdBtnSizer = wx.StaticBoxSizer(self.cmdBox, wx.HORIZONTAL)
  265. if self._gcstyle & GC_PROMPT:
  266. promptSizer = wx.BoxSizer(wx.VERTICAL)
  267. promptSizer.Add(item = self.cmdPrompt, proportion = 1,
  268. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border = 3)
  269. if self._gcstyle & GC_SEARCH:
  270. outputSizer.Add(item = self.searchPane, proportion = 0,
  271. flag = wx.EXPAND | wx.ALL, border = 3)
  272. outputSizer.Add(item = self.cmdOutput, proportion = 1,
  273. flag = wx.EXPAND | wx.ALL, border = 3)
  274. outputSizer.Add(item = self.progressbar, proportion = 0,
  275. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 3)
  276. outBtnSizer.Add(item = self.btnOutputClear, proportion = 1,
  277. flag = wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT, border = 5)
  278. outBtnSizer.Add(item = self.btnOutputSave, proportion = 1,
  279. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 5)
  280. cmdBtnSizer.Add(item = self.btnCmdProtocol, proportion = 1,
  281. flag = wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border = 5)
  282. cmdBtnSizer.Add(item = self.btnCmdClear, proportion = 1,
  283. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
  284. cmdBtnSizer.Add(item = self.btnCmdAbort, proportion = 1,
  285. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
  286. if self._gcstyle & GC_PROMPT:
  287. proportion = (2, 3)
  288. else:
  289. proportion = (1, 1)
  290. btnSizer.Add(item = outBtnSizer, proportion = proportion[0],
  291. flag = wx.ALL | wx.ALIGN_CENTER, border = 5)
  292. btnSizer.Add(item = cmdBtnSizer, proportion = proportion[1],
  293. flag = wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, border = 5)
  294. outputSizer.Add(item = btnSizer, proportion = 0,
  295. flag = wx.EXPAND)
  296. outputSizer.Fit(self)
  297. outputSizer.SetSizeHints(self)
  298. self.panelOutput.SetSizer(outputSizer)
  299. # eliminate gtk_widget_size_allocate() warnings
  300. outputSizer.SetVirtualSizeHints(self.panelOutput)
  301. if self._gcstyle & GC_PROMPT:
  302. promptSizer.Fit(self)
  303. promptSizer.SetSizeHints(self)
  304. self.panelPrompt.SetSizer(promptSizer)
  305. # split window
  306. if self._gcstyle & GC_PROMPT:
  307. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -50)
  308. else:
  309. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -45)
  310. self.Unsplit()
  311. self.SetMinimumPaneSize(self.btnCmdClear.GetSize()[1] + 25)
  312. self.SetSashGravity(1.0)
  313. # layout
  314. self.SetAutoLayout(True)
  315. self.Layout()
  316. def MakeSearchPaneContent(self, pane):
  317. """!Create search pane"""
  318. border = wx.BoxSizer(wx.VERTICAL)
  319. self.search = SearchModuleWindow(parent = pane, cmdPrompt = self.cmdPrompt)
  320. border.Add(item = self.search, proportion = 0,
  321. flag = wx.EXPAND | wx.ALL, border = 1)
  322. pane.SetSizer(border)
  323. border.Fit(pane)
  324. def OnSearchPaneChanged(self, event):
  325. """!Collapse search module box"""
  326. if self.searchPane.IsExpanded():
  327. self.searchPane.SetLabel(self.infoCollapseLabelCol)
  328. else:
  329. self.searchPane.SetLabel(self.infoCollapseLabelExp)
  330. self.panelOutput.Layout()
  331. self.panelOutput.SendSizeEvent()
  332. def GetPanel(self, prompt = True):
  333. """!Get panel
  334. @param prompt get prompt / output panel
  335. @return wx.Panel reference
  336. """
  337. if prompt:
  338. return self.panelPrompt
  339. return self.panelOutput
  340. def Redirect(self):
  341. """!Redirect stdout/stderr
  342. """
  343. if Debug.GetLevel() == 0 and int(grass.gisenv().get('DEBUG', 0)) == 0:
  344. # don't redirect when debugging is enabled
  345. sys.stdout = self.cmdStdOut
  346. sys.stderr = self.cmdStdErr
  347. else:
  348. enc = locale.getdefaultlocale()[1]
  349. if enc:
  350. sys.stdout = codecs.getwriter(enc)(sys.__stdout__)
  351. sys.stderr = codecs.getwriter(enc)(sys.__stderr__)
  352. else:
  353. sys.stdout = sys.__stdout__
  354. sys.stderr = sys.__stderr__
  355. def WriteLog(self, text, style = None, wrap = None,
  356. switchPage = False):
  357. """!Generic method for writing log message in
  358. given style
  359. @param line text line
  360. @param style text style (see GStc)
  361. @param stdout write to stdout or stderr
  362. """
  363. self.cmdOutput.SetStyle()
  364. if switchPage:
  365. self._notebook.SetSelectionByName('output')
  366. if not style:
  367. style = self.cmdOutput.StyleDefault
  368. # p1 = self.cmdOutput.GetCurrentPos()
  369. p1 = self.cmdOutput.GetEndStyled()
  370. # self.cmdOutput.GotoPos(p1)
  371. self.cmdOutput.DocumentEnd()
  372. for line in text.splitlines():
  373. # fill space
  374. if len(line) < self.lineWidth:
  375. diff = self.lineWidth - len(line)
  376. line += diff * ' '
  377. self.cmdOutput.AddTextWrapped(line, wrap = wrap) # adds '\n'
  378. p2 = self.cmdOutput.GetCurrentPos()
  379. self.cmdOutput.StartStyling(p1, 0xff)
  380. self.cmdOutput.SetStyling(p2 - p1, style)
  381. self.cmdOutput.EnsureCaretVisible()
  382. def WriteCmdLog(self, line, pid = None, switchPage = True):
  383. """!Write message in selected style
  384. @param line message to be printed
  385. @param pid process pid or None
  386. @param switchPage True to switch page
  387. """
  388. if pid:
  389. line = '(' + str(pid) + ') ' + line
  390. self.WriteLog(line, style = self.cmdOutput.StyleCommand, switchPage = switchPage)
  391. def WriteWarning(self, line):
  392. """!Write message in warning style"""
  393. self.WriteLog(line, style = self.cmdOutput.StyleWarning, switchPage = True)
  394. def WriteError(self, line):
  395. """!Write message in error style"""
  396. self.WriteLog(line, style = self.cmdOutput.StyleError, switchPage = True)
  397. def RunCmd(self, command, compReg = True, switchPage = False, skipInterface = False,
  398. onDone = None, onPrepare = None, userData = None):
  399. """!Run command typed into console command prompt (GPrompt).
  400. @todo Display commands (*.d) are captured and processed
  401. separately by mapdisp.py. Display commands are rendered in map
  402. display widget that currently has the focus (as indicted by
  403. mdidx).
  404. @param command command given as a list (produced e.g. by utils.split())
  405. @param compReg True use computation region
  406. @param switchPage switch to output page
  407. @param skipInterface True to do not launch GRASS interface
  408. parser when command has no arguments given
  409. @param onDone function to be called when command is finished
  410. @param onPrepare function to be called before command is launched
  411. @param userData data defined for the command
  412. """
  413. if len(command) == 0:
  414. Debug.msg(2, "GPrompt:RunCmd(): empty command")
  415. return
  416. # update history file
  417. env = grass.gisenv()
  418. try:
  419. filePath = os.path.join(env['GISDBASE'],
  420. env['LOCATION_NAME'],
  421. env['MAPSET'],
  422. '.bash_history')
  423. fileHistory = codecs.open(filePath, encoding = 'utf-8', mode = 'a')
  424. except IOError, e:
  425. GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
  426. {'filePath': filePath, 'error' : e },
  427. parent = self.frame)
  428. fileHistory = None
  429. if fileHistory:
  430. try:
  431. fileHistory.write(' '.join(command) + os.linesep)
  432. finally:
  433. fileHistory.close()
  434. if command[0] in globalvar.grassCmd:
  435. # send GRASS command without arguments to GUI command interface
  436. # except display commands (they are handled differently)
  437. if self.frame.GetName() == "LayerManager" and \
  438. command[0][0:2] == "d." and \
  439. 'help' not in ' '.join(command[1:]):
  440. # display GRASS commands
  441. try:
  442. layertype = {'d.rast' : 'raster',
  443. 'd.rast3d' : '3d-raster',
  444. 'd.rgb' : 'rgb',
  445. 'd.his' : 'his',
  446. 'd.shaded' : 'shaded',
  447. 'd.legend' : 'rastleg',
  448. 'd.rast.arrow' : 'rastarrow',
  449. 'd.rast.num' : 'rastnum',
  450. 'd.rast.leg' : 'maplegend',
  451. 'd.vect' : 'vector',
  452. 'd.thematic.area': 'thememap',
  453. 'd.vect.chart' : 'themechart',
  454. 'd.grid' : 'grid',
  455. 'd.geodesic' : 'geodesic',
  456. 'd.rhumbline' : 'rhumb',
  457. 'd.labels' : 'labels',
  458. 'd.barscale' : 'barscale',
  459. 'd.redraw' : 'redraw'}[command[0]]
  460. except KeyError:
  461. GMessage(parent = self.frame,
  462. message = _("Command '%s' not yet implemented in the WxGUI. "
  463. "Try adding it as a command layer instead.") % command[0])
  464. return
  465. if layertype == 'barscale':
  466. self.frame.GetLayerTree().GetMapDisplay().OnAddBarscale(None)
  467. elif layertype == 'rastleg':
  468. self.frame.GetLayerTree().GetMapDisplay().OnAddLegend(None)
  469. elif layertype == 'redraw':
  470. self.frame.GetLayerTree().GetMapDisplay().OnRender(None)
  471. else:
  472. # add layer into layer tree
  473. lname, found = utils.GetLayerNameFromCmd(command, fullyQualified = True,
  474. layerType = layertype)
  475. if self.frame.GetName() == "LayerManager":
  476. self.frame.GetLayerTree().AddLayer(ltype = layertype,
  477. lname = lname,
  478. lcmd = command)
  479. else:
  480. # other GRASS commands (r|v|g|...)
  481. try:
  482. task = GUI(show = None).ParseCommand(command)
  483. except GException, e:
  484. GError(parent = self,
  485. message = unicode(e),
  486. showTraceback = False)
  487. return
  488. hasParams = False
  489. if task:
  490. options = task.get_options()
  491. hasParams = options['params'] and options['flags']
  492. # check for <input>=-
  493. for p in options['params']:
  494. if p.get('prompt', '') == 'input' and \
  495. p.get('element', '') == 'file' and \
  496. p.get('age', 'new') == 'old' and \
  497. p.get('value', '') == '-':
  498. GError(parent = self,
  499. message = _("Unable to run command:\n%(cmd)s\n\n"
  500. "Option <%(opt)s>: read from standard input is not "
  501. "supported by wxGUI") % { 'cmd': ' '.join(command),
  502. 'opt': p.get('name', '') })
  503. return
  504. if len(command) == 1 and hasParams and \
  505. command[0] != 'v.krige':
  506. # no arguments given
  507. try:
  508. GUI(parent = self, lmgr = self.parent).ParseCommand(command)
  509. except GException, e:
  510. print >> sys.stderr, e
  511. return
  512. # switch to 'Command output' if required
  513. if switchPage:
  514. self._notebook.SetSelectionByName('output')
  515. self.frame.SetFocus()
  516. self.frame.Raise()
  517. # activate computational region (set with g.region)
  518. # for all non-display commands.
  519. if compReg:
  520. tmpreg = os.getenv("GRASS_REGION")
  521. if "GRASS_REGION" in os.environ:
  522. del os.environ["GRASS_REGION"]
  523. # process GRASS command with argument
  524. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  525. onDone = onDone, onPrepare = onPrepare, userData = userData,
  526. env = os.environ.copy())
  527. self.cmdOutputTimer.Start(50)
  528. # deactivate computational region and return to display settings
  529. if compReg and tmpreg:
  530. os.environ["GRASS_REGION"] = tmpreg
  531. else:
  532. # Send any other command to the shell. Send output to
  533. # console output window
  534. if len(command) == 1 and not skipInterface:
  535. try:
  536. task = gtask.parse_interface(command[0])
  537. except:
  538. task = None
  539. else:
  540. task = None
  541. if task:
  542. # process GRASS command without argument
  543. GUI(parent = self, lmgr = self.parent).ParseCommand(command)
  544. else:
  545. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  546. onDone = onDone, onPrepare = onPrepare, userData = userData)
  547. self.cmdOutputTimer.Start(50)
  548. def OnOutputClear(self, event):
  549. """!Clear content of output window"""
  550. self.cmdOutput.SetReadOnly(False)
  551. self.cmdOutput.ClearAll()
  552. self.cmdOutput.SetReadOnly(True)
  553. self.progressbar.SetValue(0)
  554. def GetProgressBar(self):
  555. """!Return progress bar widget"""
  556. return self.progressbar
  557. def GetLog(self, err = False):
  558. """!Get widget used for logging
  559. @param err True to get stderr widget
  560. """
  561. if err:
  562. return self.cmdStdErr
  563. return self.cmdStdOut
  564. def OnOutputSave(self, event):
  565. """!Save (selected) text from output window to the file"""
  566. text = self.cmdOutput.GetSelectedText()
  567. if not text:
  568. text = self.cmdOutput.GetText()
  569. # add newline if needed
  570. if len(text) > 0 and text[-1] != '\n':
  571. text += '\n'
  572. dlg = wx.FileDialog(self, message = _("Save file as..."),
  573. defaultFile = "grass_cmd_output.txt",
  574. wildcard = _("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
  575. {'txt': _("Text files"), 'files': _("Files")},
  576. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  577. # Show the dialog and retrieve the user response. If it is the OK response,
  578. # process the data.
  579. if dlg.ShowModal() == wx.ID_OK:
  580. path = dlg.GetPath()
  581. try:
  582. output = open(path, "w")
  583. output.write(text)
  584. except IOError, e:
  585. GError(_("Unable to write file '%(path)s'.\n\nDetails: %(error)s") % {'path': path, 'error': e})
  586. finally:
  587. output.close()
  588. self.frame.SetStatusText(_("Commands output saved into '%s'") % path)
  589. dlg.Destroy()
  590. def GetCmd(self):
  591. """!Get running command or None"""
  592. return self.requestQ.get()
  593. def SetCopyingOfSelectedText(self, copy):
  594. """!Enable or disable copying of selected text in to clipboard.
  595. Effects prompt and output.
  596. @param copy True for enable, False for disable
  597. """
  598. if copy:
  599. self.cmdPrompt.Bind(stc.EVT_STC_PAINTED, self.cmdPrompt.OnTextSelectionChanged)
  600. self.cmdOutput.Bind(stc.EVT_STC_PAINTED, self.cmdOutput.OnTextSelectionChanged)
  601. else:
  602. self.cmdPrompt.Unbind(stc.EVT_STC_PAINTED)
  603. self.cmdOutput.Unbind(stc.EVT_STC_PAINTED)
  604. def OnUpdateStatusBar(self, event):
  605. """!Update statusbar text"""
  606. if event.GetString():
  607. nItems = len(self.cmdPrompt.GetCommandItems())
  608. self.frame.SetStatusText(_('%d modules match') % nItems, 0)
  609. else:
  610. self.frame.SetStatusText('', 0)
  611. event.Skip()
  612. def OnCmdOutput(self, event):
  613. """!Print command output"""
  614. message = event.text
  615. type = event.type
  616. if self._notebook.GetSelection() != self._notebook.GetPageIndexByName('output'):
  617. page = self._notebook.GetPageIndexByName('output')
  618. textP = self._notebook.GetPageText(page)
  619. if textP[-1] != ')':
  620. textP += ' (...)'
  621. self._notebook.SetPageText(page, textP)
  622. # message prefix
  623. if type == 'warning':
  624. message = 'WARNING: ' + message
  625. elif type == 'error':
  626. message = 'ERROR: ' + message
  627. p1 = self.cmdOutput.GetEndStyled()
  628. self.cmdOutput.GotoPos(p1)
  629. if '\b' in message:
  630. if self.linepos < 0:
  631. self.linepos = p1
  632. last_c = ''
  633. for c in message:
  634. if c == '\b':
  635. self.linepos -= 1
  636. else:
  637. if c == '\r':
  638. pos = self.cmdOutput.GetCurLine()[1]
  639. # self.cmdOutput.SetCurrentPos(pos)
  640. else:
  641. self.cmdOutput.SetCurrentPos(self.linepos)
  642. self.cmdOutput.ReplaceSelection(c)
  643. self.linepos = self.cmdOutput.GetCurrentPos()
  644. if c != ' ':
  645. last_c = c
  646. if last_c not in ('0123456789'):
  647. self.cmdOutput.AddTextWrapped('\n', wrap = None)
  648. self.linepos = -1
  649. else:
  650. self.linepos = -1 # don't force position
  651. if '\n' not in message:
  652. self.cmdOutput.AddTextWrapped(message, wrap = 60)
  653. else:
  654. self.cmdOutput.AddTextWrapped(message, wrap = None)
  655. p2 = self.cmdOutput.GetCurrentPos()
  656. if p2 >= p1:
  657. self.cmdOutput.StartStyling(p1, 0xff)
  658. if type == 'error':
  659. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleError)
  660. elif type == 'warning':
  661. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleWarning)
  662. elif type == 'message':
  663. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleMessage)
  664. else: # unknown
  665. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleUnknown)
  666. self.cmdOutput.EnsureCaretVisible()
  667. def OnCmdProgress(self, event):
  668. """!Update progress message info"""
  669. self.progressbar.SetValue(event.value)
  670. def CmdProtocolSave(self):
  671. """Save commands protocol into the file"""
  672. if not hasattr(self, 'cmdFileProtocol'):
  673. return # it should not happen
  674. try:
  675. output = open(self.cmdFileProtocol, "w")
  676. cmds = self.cmdPrompt.GetCommands()
  677. output.write('\n'.join(cmds))
  678. if len(cmds) > 0:
  679. output.write('\n')
  680. except IOError, e:
  681. GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
  682. {'filePath': self.cmdFileProtocol, 'error': e})
  683. finally:
  684. output.close()
  685. self.frame.SetStatusText(_("Commands protocol saved into '%s'") % self.cmdFileProtocol)
  686. del self.cmdFileProtocol
  687. def OnCmdProtocol(self, event = None):
  688. """!Save commands into file"""
  689. if not event.IsChecked():
  690. # stop capturing commands, save list of commands to the
  691. # protocol file
  692. self.CmdProtocolSave()
  693. else:
  694. # start capturing commands
  695. self.cmdPrompt.ClearCommands()
  696. # ask for the file
  697. dlg = wx.FileDialog(self, message = _("Save file as..."),
  698. defaultFile = "grass_cmd_protocol.txt",
  699. wildcard = _("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
  700. {'txt': _("Text files"), 'files': _("Files")},
  701. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  702. if dlg.ShowModal() == wx.ID_OK:
  703. self.cmdFileProtocol = dlg.GetPath()
  704. else:
  705. wx.CallAfter(self.btnCmdProtocol.SetValue, False)
  706. dlg.Destroy()
  707. event.Skip()
  708. def OnCmdAbort(self, event):
  709. """!Abort running command"""
  710. self.cmdThread.abort()
  711. def OnCmdRun(self, event):
  712. """!Run command"""
  713. if self.frame.GetName() == 'Modeler':
  714. self.frame.OnCmdRun(event)
  715. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  716. self.btnCmdAbort.Enable()
  717. def OnCmdPrepare(self, event):
  718. """!Prepare for running command"""
  719. if self.frame.GetName() == 'Modeler':
  720. self.frame.OnCmdPrepare(event)
  721. event.Skip()
  722. def OnCmdDone(self, event):
  723. """!Command done (or aborted)"""
  724. if self.frame.GetName() == 'Modeler':
  725. self.frame.OnCmdDone(event)
  726. # Process results here
  727. try:
  728. ctime = time.time() - event.time
  729. if ctime < 60:
  730. stime = _("%d sec") % int(ctime)
  731. else:
  732. mtime = int(ctime / 60)
  733. stime = _("%(min)d min %(sec)d sec") % { 'min' : mtime,
  734. 'sec' : int(ctime - (mtime * 60)) }
  735. except KeyError:
  736. # stopped deamon
  737. stime = _("unknown")
  738. if event.aborted:
  739. # Thread aborted (using our convention of None return)
  740. self.WriteLog(_('Please note that the data are left in inconsistent state '
  741. 'and may be corrupted'), self.cmdOutput.StyleWarning)
  742. msg = _('Command aborted')
  743. else:
  744. msg = _('Command finished')
  745. self.WriteCmdLog('(%s) %s (%s)' % (str(time.ctime()), msg, stime))
  746. self.btnCmdAbort.Enable(False)
  747. if event.onDone:
  748. event.onDone(cmd = event.cmd, returncode = event.returncode)
  749. self.progressbar.SetValue(0) # reset progress bar on '0%'
  750. self.cmdOutputTimer.Stop()
  751. if event.cmd[0] == 'g.gisenv':
  752. Debug.SetLevel()
  753. self.Redirect()
  754. if self.frame.GetName() == "LayerManager":
  755. self.btnCmdAbort.Enable(False)
  756. if event.cmd[0] not in globalvar.grassCmd or \
  757. event.cmd[0] == 'r.mapcalc':
  758. return
  759. tree = self.frame.GetLayerTree()
  760. display = None
  761. if tree:
  762. display = tree.GetMapDisplay()
  763. if not display or not display.IsAutoRendered():
  764. return
  765. mapLayers = map(lambda x: x.GetName(),
  766. display.GetMap().GetListOfLayers(l_type = 'raster') +
  767. display.GetMap().GetListOfLayers(l_type = 'vector'))
  768. try:
  769. task = GUI(show = None).ParseCommand(event.cmd)
  770. except GException, e:
  771. print >> sys.stderr, e
  772. task = None
  773. return
  774. for p in task.get_options()['params']:
  775. if p.get('prompt', '') not in ('raster', 'vector'):
  776. continue
  777. mapName = p.get('value', '')
  778. if '@' not in mapName:
  779. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  780. if mapName in mapLayers:
  781. display.GetWindow().UpdateMap(render = True)
  782. return
  783. elif self.frame.GetName() == 'Modeler':
  784. pass
  785. else: # standalone dialogs
  786. dialog = self.frame
  787. if hasattr(dialog, "btn_abort"):
  788. dialog.btn_abort.Enable(False)
  789. if hasattr(dialog, "btn_cancel"):
  790. dialog.btn_cancel.Enable(True)
  791. if hasattr(dialog, "btn_clipboard"):
  792. dialog.btn_clipboard.Enable(True)
  793. if hasattr(dialog, "btn_help"):
  794. dialog.btn_help.Enable(True)
  795. if hasattr(dialog, "btn_run"):
  796. dialog.btn_run.Enable(True)
  797. if event.returncode == 0 and not event.aborted:
  798. try:
  799. winName = self.frame.parent.GetName()
  800. except AttributeError:
  801. winName = ''
  802. if winName == 'LayerManager':
  803. mapTree = self.frame.parent.GetLayerTree()
  804. elif winName == 'LayerTree':
  805. mapTree = self.frame.parent
  806. elif winName: # GConsole
  807. mapTree = self.frame.parent.parent.GetLayerTree()
  808. else:
  809. mapTree = None
  810. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  811. if hasattr(dialog, "addbox") and dialog.addbox.IsChecked():
  812. # add created maps into layer tree
  813. for p in dialog.task.get_options()['params']:
  814. prompt = p.get('prompt', '')
  815. if prompt in ('raster', 'vector', '3d-raster') and \
  816. p.get('age', 'old') == 'new' and \
  817. p.get('value', None):
  818. name, found = utils.GetLayerNameFromCmd(cmd, fullyQualified = True,
  819. param = p.get('name', ''))
  820. if mapTree.GetMap().GetListOfLayers(l_name = name):
  821. display = mapTree.GetMapDisplay()
  822. if display and display.IsAutoRendered():
  823. display.GetWindow().UpdateMap(render = True)
  824. continue
  825. if prompt == 'raster':
  826. lcmd = ['d.rast',
  827. 'map=%s' % name]
  828. elif prompt == '3d-raster':
  829. lcmd = ['d.rast3d',
  830. 'map=%s' % name]
  831. else:
  832. defaultParams = GetDisplayVectSettings()
  833. lcmd = ['d.vect',
  834. 'map=%s' % name] + defaultParams
  835. mapTree.AddLayer(ltype = prompt,
  836. lcmd = lcmd,
  837. lname = name)
  838. if hasattr(dialog, "get_dcmd") and \
  839. dialog.get_dcmd is None and \
  840. hasattr(dialog, "closebox") and \
  841. dialog.closebox.IsChecked() and \
  842. (event.returncode == 0 or event.aborted):
  843. self.cmdOutput.Update()
  844. time.sleep(2)
  845. dialog.Close()
  846. def OnProcessPendingOutputWindowEvents(self, event):
  847. wx.GetApp().ProcessPendingEvents()
  848. def ResetFocus(self):
  849. """!Reset focus"""
  850. self.cmdPrompt.SetFocus()
  851. def GetPrompt(self):
  852. """!Get prompt"""
  853. return self.cmdPrompt
  854. class GStdout:
  855. """!GConsole standard output
  856. Based on FrameOutErr.py
  857. Name: FrameOutErr.py
  858. Purpose: Redirecting stdout / stderr
  859. Author: Jean-Michel Fauth, Switzerland
  860. Copyright: (c) 2005-2007 Jean-Michel Fauth
  861. Licence: GPL
  862. """
  863. def __init__(self, parent):
  864. self.parent = parent # GConsole
  865. def write(self, s):
  866. if len(s) == 0 or s == '\n':
  867. return
  868. for line in s.splitlines():
  869. if len(line) == 0:
  870. continue
  871. evt = wxCmdOutput(text = line + '\n',
  872. type = '')
  873. wx.PostEvent(self.parent.cmdOutput, evt)
  874. class GStderr:
  875. """!GConsole standard error output
  876. Based on FrameOutErr.py
  877. Name: FrameOutErr.py
  878. Purpose: Redirecting stdout / stderr
  879. Author: Jean-Michel Fauth, Switzerland
  880. Copyright: (c) 2005-2007 Jean-Michel Fauth
  881. Licence: GPL
  882. """
  883. def __init__(self, parent):
  884. self.parent = parent # GConsole
  885. self.type = ''
  886. self.message = ''
  887. self.printMessage = False
  888. def flush(self):
  889. pass
  890. def write(self, s):
  891. if "GtkPizza" in s:
  892. return
  893. # remove/replace escape sequences '\b' or '\r' from stream
  894. progressValue = -1
  895. for line in s.splitlines():
  896. if len(line) == 0:
  897. continue
  898. if 'GRASS_INFO_PERCENT' in line:
  899. value = int(line.rsplit(':', 1)[1].strip())
  900. if value >= 0 and value < 100:
  901. progressValue = value
  902. else:
  903. progressValue = 0
  904. elif 'GRASS_INFO_MESSAGE' in line:
  905. self.type = 'message'
  906. self.message += line.split(':', 1)[1].strip() + '\n'
  907. elif 'GRASS_INFO_WARNING' in line:
  908. self.type = 'warning'
  909. self.message += line.split(':', 1)[1].strip() + '\n'
  910. elif 'GRASS_INFO_ERROR' in line:
  911. self.type = 'error'
  912. self.message += line.split(':', 1)[1].strip() + '\n'
  913. elif 'GRASS_INFO_END' in line:
  914. self.printMessage = True
  915. elif self.type == '':
  916. if len(line) == 0:
  917. continue
  918. evt = wxCmdOutput(text = line,
  919. type = '')
  920. wx.PostEvent(self.parent.cmdOutput, evt)
  921. elif len(line) > 0:
  922. self.message += line.strip() + '\n'
  923. if self.printMessage and len(self.message) > 0:
  924. evt = wxCmdOutput(text = self.message,
  925. type = self.type)
  926. wx.PostEvent(self.parent.cmdOutput, evt)
  927. self.type = ''
  928. self.message = ''
  929. self.printMessage = False
  930. # update progress message
  931. if progressValue > -1:
  932. # self.gmgauge.SetValue(progressValue)
  933. evt = wxCmdProgress(value = progressValue)
  934. wx.PostEvent(self.parent.progressbar, evt)
  935. class GStc(stc.StyledTextCtrl):
  936. """!Styled text control for GRASS stdout and stderr.
  937. Based on FrameOutErr.py
  938. Name: FrameOutErr.py
  939. Purpose: Redirecting stdout / stderr
  940. Author: Jean-Michel Fauth, Switzerland
  941. Copyright: (c) 2005-2007 Jean-Michel Fauth
  942. Licence: GPL
  943. """
  944. def __init__(self, parent, id, margin = False, wrap = None):
  945. stc.StyledTextCtrl.__init__(self, parent, id)
  946. self.parent = parent
  947. self.SetUndoCollection(True)
  948. self.SetReadOnly(True)
  949. #
  950. # styles
  951. #
  952. self.SetStyle()
  953. #
  954. # line margins
  955. #
  956. # TODO print number only from cmdlog
  957. self.SetMarginWidth(1, 0)
  958. self.SetMarginWidth(2, 0)
  959. if margin:
  960. self.SetMarginType(0, stc.STC_MARGIN_NUMBER)
  961. self.SetMarginWidth(0, 30)
  962. else:
  963. self.SetMarginWidth(0, 0)
  964. #
  965. # miscellaneous
  966. #
  967. self.SetViewWhiteSpace(False)
  968. self.SetTabWidth(4)
  969. self.SetUseTabs(False)
  970. self.UsePopUp(True)
  971. self.SetSelBackground(True, "#FFFF00")
  972. self.SetUseHorizontalScrollBar(True)
  973. #
  974. # bindings
  975. #
  976. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  977. def OnTextSelectionChanged(self, event):
  978. """!Copy selected text to clipboard and skip event.
  979. The same function is in TextCtrlAutoComplete class (prompt.py).
  980. """
  981. wx.CallAfter(self.Copy)
  982. event.Skip()
  983. def SetStyle(self):
  984. """!Set styles for styled text output windows with type face
  985. and point size selected by user (Courier New 10 is default)"""
  986. typeface = UserSettings.Get(group = 'appearance', key = 'outputfont', subkey = 'type')
  987. if typeface == "":
  988. typeface = "Courier New"
  989. typesize = UserSettings.Get(group = 'appearance', key = 'outputfont', subkey = 'size')
  990. if typesize == None or typesize <= 0:
  991. typesize = 10
  992. typesize = float(typesize)
  993. self.StyleDefault = 0
  994. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  995. self.StyleCommand = 1
  996. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  997. self.StyleOutput = 2
  998. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  999. # fatal error
  1000. self.StyleError = 3
  1001. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  1002. # warning
  1003. self.StyleWarning = 4
  1004. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  1005. # message
  1006. self.StyleMessage = 5
  1007. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  1008. # unknown
  1009. self.StyleUnknown = 6
  1010. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  1011. # default and clear => init
  1012. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  1013. self.StyleClearAll()
  1014. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  1015. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  1016. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  1017. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  1018. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  1019. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  1020. def OnDestroy(self, evt):
  1021. """!The clipboard contents can be preserved after
  1022. the app has exited"""
  1023. wx.TheClipboard.Flush()
  1024. evt.Skip()
  1025. def AddTextWrapped(self, txt, wrap = None):
  1026. """!Add string to text area.
  1027. String is wrapped and linesep is also added to the end
  1028. of the string"""
  1029. # allow writing to output window
  1030. self.SetReadOnly(False)
  1031. if wrap:
  1032. txt = textwrap.fill(txt, wrap) + '\n'
  1033. else:
  1034. if txt[-1] != '\n':
  1035. txt += '\n'
  1036. if '\r' in txt:
  1037. self.parent.linePos = -1
  1038. for seg in txt.split('\r'):
  1039. if self.parent.linePos > -1:
  1040. self.SetCurrentPos(self.parent.linePos)
  1041. self.ReplaceSelection(seg)
  1042. else:
  1043. self.parent.linePos = self.GetCurrentPos()
  1044. self.AddText(seg)
  1045. else:
  1046. self.parent.linePos = self.GetCurrentPos()
  1047. try:
  1048. self.AddText(txt)
  1049. except UnicodeDecodeError:
  1050. enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
  1051. if enc:
  1052. txt = unicode(txt, enc)
  1053. elif 'GRASS_DB_ENCODING' in os.environ:
  1054. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  1055. else:
  1056. txt = EncodeString(txt)
  1057. self.AddText(txt)
  1058. # reset output window to read only
  1059. self.SetReadOnly(True)