goutput.py 41 KB

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