goutput.py 43 KB

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