goutput.py 42 KB

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