goutput.py 41 KB

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