goutput.py 41 KB

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