goutput.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  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. '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',
  409. 'd.redraw' : 'redraw'}[command[0]]
  410. except KeyError:
  411. gcmd.GMessage(parent = self.parent,
  412. message = _("Command '%s' not yet implemented in the WxGUI. "
  413. "Try adding it as a command layer instead.") % command[0])
  414. return 1
  415. if layertype == 'barscale':
  416. self.parent.curr_page.maptree.GetMapDisplay().OnAddBarscale(None)
  417. elif layertype == 'rastleg':
  418. self.parent.curr_page.maptree.GetMapDisplay().OnAddLegend(None)
  419. elif layertype == 'redraw':
  420. self.parent.curr_page.maptree.GetMapDisplay().OnRender(None)
  421. else:
  422. # add layer into layer tree
  423. lname, found = utils.GetLayerNameFromCmd(command, fullyQualified = True,
  424. layerType = layertype)
  425. if self.parent.GetName() == "LayerManager":
  426. self.parent.curr_page.maptree.AddLayer(ltype = layertype,
  427. lname = lname,
  428. lcmd = command)
  429. else:
  430. # other GRASS commands (r|v|g|...)
  431. if len(command) == 1 and command[0] != 'v.krige':
  432. # no arguments given
  433. menuform.GUI(parent = self).ParseCommand(command)
  434. return 0
  435. task = menuform.GUI(show = None).ParseCommand(command)
  436. if task:
  437. # check for <input>=-
  438. for p in task.get_options()['params']:
  439. if p.get('prompt', '') == 'input' and \
  440. p.get('element', '') == 'file' and \
  441. p.get('age', 'new') == 'old' and \
  442. p.get('value', '') == '-':
  443. gcmd.GError(parent = self,
  444. message = _("Unable to run command:\n%(cmd)s\n\n"
  445. "Option <%(opt)s>: read from standard input is not "
  446. "supported by wxGUI") % { 'cmd': ' '.join(command),
  447. 'opt': p.get('name', '') }
  448. )
  449. return 1
  450. # switch to 'Command output' if required
  451. if switchPage:
  452. self._notebook.SetSelectionByName('output')
  453. self.parent.SetFocus()
  454. self.parent.Raise()
  455. # activate computational region (set with g.region)
  456. # for all non-display commands.
  457. if compReg:
  458. tmpreg = os.getenv("GRASS_REGION")
  459. if "GRASS_REGION" in os.environ:
  460. del os.environ["GRASS_REGION"]
  461. # process GRASS command with argument
  462. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  463. onDone = onDone)
  464. self.cmdOutputTimer.Start(50)
  465. # deactivate computational region and return to display settings
  466. if compReg and tmpreg:
  467. os.environ["GRASS_REGION"] = tmpreg
  468. else:
  469. # Send any other command to the shell. Send output to
  470. # console output window
  471. if len(command) == 1:
  472. try:
  473. task = gtask.parse_interface(command[0])
  474. except:
  475. task = None
  476. else:
  477. task = None
  478. if task:
  479. # process GRASS command without argument
  480. menuform.GUI(parent = self).ParseCommand(command)
  481. else:
  482. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  483. onDone = onDone)
  484. self.cmdOutputTimer.Start(50)
  485. return 0
  486. def ClearHistory(self, event):
  487. """!Clear history of commands"""
  488. self.cmdOutput.SetReadOnly(False)
  489. self.cmdOutput.ClearAll()
  490. self.cmdOutput.SetReadOnly(True)
  491. self.progressbar.SetValue(0)
  492. def GetProgressBar(self):
  493. """!Return progress bar widget"""
  494. return self.progressbar
  495. def GetLog(self, err = False):
  496. """!Get widget used for logging
  497. @param err True to get stderr widget
  498. """
  499. if err:
  500. return self.cmdStdErr
  501. return self.cmdStdOut
  502. def SaveHistory(self, event):
  503. """!Save history of commands"""
  504. self.history = self.cmdOutput.GetSelectedText()
  505. if self.history == '':
  506. self.history = self.cmdOutput.GetText()
  507. # add newline if needed
  508. if len(self.history) > 0 and self.history[-1] != '\n':
  509. self.history += '\n'
  510. wildcard = "Text file (*.txt)|*.txt"
  511. dlg = wx.FileDialog(self, message = _("Save file as..."), defaultDir = os.getcwd(),
  512. defaultFile = "grass_cmd_history.txt", wildcard = wildcard,
  513. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  514. # Show the dialog and retrieve the user response. If it is the OK response,
  515. # process the data.
  516. if dlg.ShowModal() == wx.ID_OK:
  517. path = dlg.GetPath()
  518. output = open(path, "w")
  519. output.write(self.history)
  520. output.close()
  521. dlg.Destroy()
  522. def GetCmd(self):
  523. """!Get running command or None"""
  524. return self.requestQ.get()
  525. def SetCopyingOfSelectedText(self, copy):
  526. """!Enable or disable copying of selected text in to clipboard.
  527. Effects prompt and output.
  528. @param copy True for enable, False for disable
  529. """
  530. if copy:
  531. self.cmdPrompt.Bind(wx.stc.EVT_STC_PAINTED, self.cmdPrompt.OnTextSelectionChanged)
  532. self.cmdOutput.Bind(wx.stc.EVT_STC_PAINTED, self.cmdOutput.OnTextSelectionChanged)
  533. else:
  534. self.cmdPrompt.Unbind(wx.stc.EVT_STC_PAINTED)
  535. self.cmdOutput.Unbind(wx.stc.EVT_STC_PAINTED)
  536. def OnUpdateStatusBar(self, event):
  537. """!Update statusbar text"""
  538. if event.GetString():
  539. nItems = len(self.cmdPrompt.GetCommandItems())
  540. self.parent.SetStatusText(_('%d modules match') % nItems, 0)
  541. else:
  542. self.parent.SetStatusText('', 0)
  543. event.Skip()
  544. def OnCmdOutput(self, event):
  545. """!Print command output"""
  546. message = event.text
  547. type = event.type
  548. if self._notebook.GetSelection() != self._notebook.GetPageIndexByName('output'):
  549. page = self._notebook.GetPageIndexByName('output')
  550. textP = self._notebook.GetPageText(page)
  551. if textP[-1] != ')':
  552. textP += ' (...)'
  553. self._notebook.SetPageText(page, textP)
  554. # message prefix
  555. if type == 'warning':
  556. messege = 'WARNING: ' + message
  557. elif type == 'error':
  558. message = 'ERROR: ' + message
  559. p1 = self.cmdOutput.GetEndStyled()
  560. self.cmdOutput.GotoPos(p1)
  561. if '\b' in message:
  562. if self.linepos < 0:
  563. self.linepos = p1
  564. last_c = ''
  565. for c in message:
  566. if c == '\b':
  567. self.linepos -= 1
  568. else:
  569. if c == '\r':
  570. pos = self.cmdOutput.GetCurLine()[1]
  571. # self.cmdOutput.SetCurrentPos(pos)
  572. else:
  573. self.cmdOutput.SetCurrentPos(self.linepos)
  574. self.cmdOutput.ReplaceSelection(c)
  575. self.linepos = self.cmdOutput.GetCurrentPos()
  576. if c != ' ':
  577. last_c = c
  578. if last_c not in ('0123456789'):
  579. self.cmdOutput.AddTextWrapped('\n', wrap = None)
  580. self.linepos = -1
  581. else:
  582. self.linepos = -1 # don't force position
  583. if '\n' not in message:
  584. self.cmdOutput.AddTextWrapped(message, wrap = 60)
  585. else:
  586. self.cmdOutput.AddTextWrapped(message, wrap = None)
  587. p2 = self.cmdOutput.GetCurrentPos()
  588. if p2 >= p1:
  589. self.cmdOutput.StartStyling(p1, 0xff)
  590. if type == 'error':
  591. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleError)
  592. elif type == 'warning':
  593. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleWarning)
  594. elif type == 'message':
  595. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleMessage)
  596. else: # unknown
  597. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleUnknown)
  598. self.cmdOutput.EnsureCaretVisible()
  599. def OnCmdProgress(self, event):
  600. """!Update progress message info"""
  601. self.progressbar.SetValue(event.value)
  602. def OnCmdAbort(self, event):
  603. """!Abort running command"""
  604. self.cmdThread.abort()
  605. def OnCmdRun(self, event):
  606. """!Run command"""
  607. if self.parent.GetName() == 'Modeler':
  608. self.parent.OnCmdRun(event)
  609. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  610. self.btnCmdAbort.Enable()
  611. def OnCmdDone(self, event):
  612. """!Command done (or aborted)"""
  613. if self.parent.GetName() == 'Modeler':
  614. self.parent.OnCmdDone(event)
  615. if event.aborted:
  616. # Thread aborted (using our convention of None return)
  617. self.WriteLog(_('Please note that the data are left in inconsistent state '
  618. 'and may be corrupted'), self.cmdOutput.StyleWarning)
  619. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  620. _('Command aborted'),
  621. (time.time() - event.time)))
  622. # pid=self.cmdThread.requestId)
  623. self.btnCmdAbort.Enable(False)
  624. else:
  625. try:
  626. # Process results here
  627. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  628. _('Command finished'),
  629. (time.time() - event.time)))
  630. except KeyError:
  631. # stopped deamon
  632. pass
  633. self.btnCmdAbort.Enable(False)
  634. if event.onDone:
  635. event.onDone(cmd = event.cmd, returncode = event.returncode)
  636. self.progressbar.SetValue(0) # reset progress bar on '0%'
  637. self.cmdOutputTimer.Stop()
  638. if event.cmd[0] == 'g.gisenv':
  639. Debug.SetLevel()
  640. self.Redirect()
  641. if self.parent.GetName() == "LayerManager":
  642. self.btnCmdAbort.Enable(False)
  643. if event.cmd[0] not in globalvar.grassCmd['all'] or \
  644. event.cmd[0] == 'r.mapcalc':
  645. return
  646. display = self.parent.GetLayerTree().GetMapDisplay()
  647. if not display or not display.IsAutoRendered():
  648. return
  649. mapLayers = map(lambda x: x.GetName(),
  650. display.GetMap().GetListOfLayers(l_type = 'raster') +
  651. display.GetMap().GetListOfLayers(l_type = 'vector'))
  652. try:
  653. task = menuform.GUI(show = None).ParseCommand(event.cmd)
  654. except gcmd.GException:
  655. task = None
  656. return
  657. for p in task.get_options()['params']:
  658. if p.get('prompt', '') not in ('raster', 'vector'):
  659. continue
  660. mapName = p.get('value', '')
  661. if '@' not in mapName:
  662. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  663. if mapName in mapLayers:
  664. display.GetWindow().UpdateMap(render = True)
  665. return
  666. elif self.parent.GetName() == 'Modeler':
  667. pass
  668. else: # standalone dialogs
  669. dialog = self.parent.parent
  670. if hasattr(self.parent.parent, "btn_abort"):
  671. dialog.btn_abort.Enable(False)
  672. if hasattr(self.parent.parent, "btn_cancel"):
  673. dialog.btn_cancel.Enable(True)
  674. if hasattr(self.parent.parent, "btn_clipboard"):
  675. dialog.btn_clipboard.Enable(True)
  676. if hasattr(self.parent.parent, "btn_help"):
  677. dialog.btn_help.Enable(True)
  678. if hasattr(self.parent.parent, "btn_run"):
  679. dialog.btn_run.Enable(True)
  680. if event.returncode == 0 and not event.aborted:
  681. try:
  682. winName = self.parent.parent.parent.GetName()
  683. except AttributeError:
  684. winName = ''
  685. if winName == 'LayerManager':
  686. mapTree = self.parent.parent.parent.GetLayerTree()
  687. elif winName == 'LayerTree':
  688. mapTree = self.parent.parent.parent
  689. elif winName: # GMConsole
  690. mapTree = self.parent.parent.parent.parent.GetLayerTree()
  691. else:
  692. mapTree = None
  693. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  694. if hasattr(dialog, "addbox") and dialog.addbox.IsChecked():
  695. # add created maps into layer tree
  696. for p in dialog.task.get_options()['params']:
  697. prompt = p.get('prompt', '')
  698. if prompt in ('raster', 'vector', '3d-raster') and \
  699. p.get('age', 'old') == 'new' and \
  700. p.get('value', None):
  701. name, found = utils.GetLayerNameFromCmd(cmd, fullyQualified = True,
  702. param = p.get('name', ''))
  703. if mapTree.GetMap().GetListOfLayers(l_name = name):
  704. continue
  705. if prompt == 'raster':
  706. lcmd = ['d.rast',
  707. 'map=%s' % name]
  708. else:
  709. lcmd = ['d.vect',
  710. 'map=%s' % name]
  711. mapTree.AddLayer(ltype = prompt,
  712. lcmd = lcmd,
  713. lname = name)
  714. if hasattr(dialog, "get_dcmd") and \
  715. dialog.get_dcmd is None and \
  716. hasattr(dialog, "closebox") and \
  717. dialog.closebox.IsChecked() and \
  718. (event.returncode == 0 or event.aborted):
  719. self.cmdOutput.Update()
  720. time.sleep(2)
  721. dialog.Close()
  722. def OnProcessPendingOutputWindowEvents(self, event):
  723. self.ProcessPendingEvents()
  724. def ResetFocus(self):
  725. """!Reset focus"""
  726. self.cmdPrompt.SetFocus()
  727. class GMStdout:
  728. """!GMConsole standard output
  729. Based on FrameOutErr.py
  730. Name: FrameOutErr.py
  731. Purpose: Redirecting stdout / stderr
  732. Author: Jean-Michel Fauth, Switzerland
  733. Copyright: (c) 2005-2007 Jean-Michel Fauth
  734. Licence: GPL
  735. """
  736. def __init__(self, parent):
  737. self.parent = parent # GMConsole
  738. def write(self, s):
  739. if len(s) == 0 or s == '\n':
  740. return
  741. for line in s.splitlines():
  742. if len(line) == 0:
  743. continue
  744. evt = wxCmdOutput(text = line + '\n',
  745. type = '')
  746. wx.PostEvent(self.parent.cmdOutput, evt)
  747. class GMStderr:
  748. """!GMConsole standard error output
  749. Based on FrameOutErr.py
  750. Name: FrameOutErr.py
  751. Purpose: Redirecting stdout / stderr
  752. Author: Jean-Michel Fauth, Switzerland
  753. Copyright: (c) 2005-2007 Jean-Michel Fauth
  754. Licence: GPL
  755. """
  756. def __init__(self, parent):
  757. self.parent = parent # GMConsole
  758. self.type = ''
  759. self.message = ''
  760. self.printMessage = False
  761. def flush(self):
  762. pass
  763. def write(self, s):
  764. if "GtkPizza" in s:
  765. return
  766. # remove/replace escape sequences '\b' or '\r' from stream
  767. progressValue = -1
  768. for line in s.splitlines():
  769. if len(line) == 0:
  770. continue
  771. if 'GRASS_INFO_PERCENT' in line:
  772. value = int(line.rsplit(':', 1)[1].strip())
  773. if value >= 0 and value < 100:
  774. progressValue = value
  775. else:
  776. progressValue = 0
  777. elif 'GRASS_INFO_MESSAGE' in line:
  778. self.type = 'message'
  779. self.message += line.split(':', 1)[1].strip() + '\n'
  780. elif 'GRASS_INFO_WARNING' in line:
  781. self.type = 'warning'
  782. self.message += line.split(':', 1)[1].strip() + '\n'
  783. elif 'GRASS_INFO_ERROR' in line:
  784. self.type = 'error'
  785. self.message += line.split(':', 1)[1].strip() + '\n'
  786. elif 'GRASS_INFO_END' in line:
  787. self.printMessage = True
  788. elif self.type == '':
  789. if len(line) == 0:
  790. continue
  791. evt = wxCmdOutput(text = line,
  792. type = '')
  793. wx.PostEvent(self.parent.cmdOutput, evt)
  794. elif len(line) > 0:
  795. self.message += line.strip() + '\n'
  796. if self.printMessage and len(self.message) > 0:
  797. evt = wxCmdOutput(text = self.message,
  798. type = self.type)
  799. wx.PostEvent(self.parent.cmdOutput, evt)
  800. self.type = ''
  801. self.message = ''
  802. self.printMessage = False
  803. # update progress message
  804. if progressValue > -1:
  805. # self.gmgauge.SetValue(progressValue)
  806. evt = wxCmdProgress(value = progressValue)
  807. wx.PostEvent(self.parent.progressbar, evt)
  808. class GMStc(wx.stc.StyledTextCtrl):
  809. """!Styled GMConsole
  810. Based on FrameOutErr.py
  811. Name: FrameOutErr.py
  812. Purpose: Redirecting stdout / stderr
  813. Author: Jean-Michel Fauth, Switzerland
  814. Copyright: (c) 2005-2007 Jean-Michel Fauth
  815. Licence: GPL
  816. """
  817. def __init__(self, parent, id, margin = False, wrap = None):
  818. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  819. self.parent = parent
  820. self.SetUndoCollection(True)
  821. self.SetReadOnly(True)
  822. #
  823. # styles
  824. #
  825. self.SetStyle()
  826. #
  827. # line margins
  828. #
  829. # TODO print number only from cmdlog
  830. self.SetMarginWidth(1, 0)
  831. self.SetMarginWidth(2, 0)
  832. if margin:
  833. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  834. self.SetMarginWidth(0, 30)
  835. else:
  836. self.SetMarginWidth(0, 0)
  837. #
  838. # miscellaneous
  839. #
  840. self.SetViewWhiteSpace(False)
  841. self.SetTabWidth(4)
  842. self.SetUseTabs(False)
  843. self.UsePopUp(True)
  844. self.SetSelBackground(True, "#FFFF00")
  845. self.SetUseHorizontalScrollBar(True)
  846. #
  847. # bindings
  848. #
  849. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  850. def OnTextSelectionChanged(self, event):
  851. """!Copy selected text to clipboard and skip event.
  852. The same function is in TextCtrlAutoComplete class (prompt.py).
  853. """
  854. self.Copy()
  855. event.Skip()
  856. def SetStyle(self):
  857. """!Set styles for styled text output windows with type face
  858. and point size selected by user (Courier New 10 is default)"""
  859. settings = preferences.Settings()
  860. typeface = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'type')
  861. if typeface == "":
  862. typeface = "Courier New"
  863. typesize = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'size')
  864. if typesize == None or typesize <= 0:
  865. typesize = 10
  866. typesize = float(typesize)
  867. self.StyleDefault = 0
  868. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  869. self.StyleCommand = 1
  870. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  871. self.StyleOutput = 2
  872. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  873. # fatal error
  874. self.StyleError = 3
  875. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  876. # warning
  877. self.StyleWarning = 4
  878. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  879. # message
  880. self.StyleMessage = 5
  881. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  882. # unknown
  883. self.StyleUnknown = 6
  884. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  885. # default and clear => init
  886. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  887. self.StyleClearAll()
  888. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  889. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  890. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  891. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  892. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  893. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  894. def OnDestroy(self, evt):
  895. """!The clipboard contents can be preserved after
  896. the app has exited"""
  897. wx.TheClipboard.Flush()
  898. evt.Skip()
  899. def AddTextWrapped(self, txt, wrap = None):
  900. """!Add string to text area.
  901. String is wrapped and linesep is also added to the end
  902. of the string"""
  903. # allow writing to output window
  904. self.SetReadOnly(False)
  905. if wrap:
  906. txt = textwrap.fill(txt, wrap) + '\n'
  907. else:
  908. if txt[-1] != '\n':
  909. txt += '\n'
  910. if '\r' in txt:
  911. self.parent.linePos = -1
  912. for seg in txt.split('\r'):
  913. if self.parent.linePos > -1:
  914. self.SetCurrentPos(self.parent.linePos)
  915. self.ReplaceSelection(seg)
  916. else:
  917. self.parent.linePos = self.GetCurrentPos()
  918. self.AddText(seg)
  919. else:
  920. self.parent.linePos = self.GetCurrentPos()
  921. try:
  922. self.AddText(txt)
  923. except UnicodeDecodeError:
  924. enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
  925. if enc:
  926. txt = unicode(txt, enc)
  927. elif 'GRASS_DB_ENCODING' in os.environ:
  928. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  929. else:
  930. txt = utils.EncodeString(txt)
  931. self.AddText(txt)
  932. # reset output window to read only
  933. self.SetReadOnly(True)