goutput.py 44 KB

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