goutput.py 42 KB

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