goutput.py 49 KB

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