goutput.py 49 KB

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