goutput.py 40 KB

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