goutput.py 40 KB

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