goutput.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  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 locale
  25. import wx
  26. import wx.stc
  27. from wx.lib.newevent import NewEvent
  28. import grass.script as grass
  29. from grass.script import task as gtask
  30. import globalvar
  31. import gcmd
  32. import utils
  33. import preferences
  34. import menuform
  35. import prompt
  36. from debug import Debug
  37. from preferences import globalSettings as UserSettings
  38. from ghelp import SearchModuleWindow
  39. wxCmdOutput, EVT_CMD_OUTPUT = NewEvent()
  40. wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
  41. wxCmdRun, EVT_CMD_RUN = NewEvent()
  42. wxCmdDone, EVT_CMD_DONE = NewEvent()
  43. wxCmdAbort, EVT_CMD_ABORT = NewEvent()
  44. def GrassCmd(cmd, stdout = None, stderr = None):
  45. """!Return GRASS command thread"""
  46. return gcmd.CommandThread(cmd,
  47. stdout = stdout, stderr = stderr)
  48. class CmdThread(threading.Thread):
  49. """!Thread for GRASS commands"""
  50. requestId = 0
  51. def __init__(self, parent, requestQ, resultQ, **kwds):
  52. threading.Thread.__init__(self, **kwds)
  53. self.setDaemon(True)
  54. self.parent = parent # GMConsole
  55. self._want_abort_all = False
  56. self.requestQ = requestQ
  57. self.resultQ = resultQ
  58. self.start()
  59. def RunCmd(self, *args, **kwds):
  60. CmdThread.requestId += 1
  61. self.requestCmd = None
  62. self.requestQ.put((CmdThread.requestId, args, kwds))
  63. return CmdThread.requestId
  64. def SetId(self, id):
  65. """!Set starting id"""
  66. CmdThread.requestId = id
  67. def run(self):
  68. os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
  69. while True:
  70. requestId, args, kwds = self.requestQ.get()
  71. for key in ('callable', 'onDone', 'userData'):
  72. if key in kwds:
  73. vars()[key] = kwds[key]
  74. del kwds[key]
  75. else:
  76. vars()[key] = None
  77. if not vars()['callable']:
  78. vars()['callable'] = GrassCmd
  79. requestTime = time.time()
  80. event = wxCmdRun(cmd = args[0],
  81. pid = requestId)
  82. wx.PostEvent(self.parent, event)
  83. time.sleep(.1)
  84. self.requestCmd = vars()['callable'](*args, **kwds)
  85. if self._want_abort_all:
  86. self.requestCmd.abort()
  87. if self.requestQ.empty():
  88. self._want_abort_all = False
  89. self.resultQ.put((requestId, self.requestCmd.run()))
  90. try:
  91. returncode = self.requestCmd.module.returncode
  92. except AttributeError:
  93. returncode = 0 # being optimistic
  94. try:
  95. aborted = self.requestCmd.aborted
  96. except AttributeError:
  97. aborted = False
  98. time.sleep(.1)
  99. # set default color table for raster data
  100. if UserSettings.Get(group = 'cmd', key = 'rasterColorTable', subkey = 'enabled') and \
  101. args[0][0][:2] == 'r.':
  102. colorTable = UserSettings.Get(group = 'cmd', key = 'rasterColorTable', subkey = 'selection')
  103. mapName = None
  104. if args[0][0] == 'r.mapcalc':
  105. try:
  106. mapName = args[0][1].split('=', 1)[0].strip()
  107. except KeyError:
  108. pass
  109. else:
  110. moduleInterface = menuform.GUI(show = None).ParseCommand(args[0])
  111. outputParam = moduleInterface.get_param(value = 'output', raiseError = False)
  112. if outputParam and outputParam['prompt'] == 'raster':
  113. mapName = outputParam['value']
  114. if mapName:
  115. argsColor = list(args)
  116. argsColor[0] = [ 'r.colors',
  117. 'map=%s' % mapName,
  118. 'color=%s' % colorTable ]
  119. self.requestCmdColor = vars()['callable'](*argsColor, **kwds)
  120. self.resultQ.put((requestId, self.requestCmdColor.run()))
  121. event = wxCmdDone(cmd = args[0],
  122. aborted = aborted,
  123. returncode = returncode,
  124. time = requestTime,
  125. pid = requestId,
  126. onDone = vars()['onDone'],
  127. userData = vars()['userData'])
  128. # send event
  129. wx.PostEvent(self.parent, event)
  130. def abort(self, abortall = True):
  131. """!Abort command(s)"""
  132. if abortall:
  133. self._want_abort_all = True
  134. self.requestCmd.abort()
  135. if self.requestQ.empty():
  136. self._want_abort_all = False
  137. class GMConsole(wx.SplitterWindow):
  138. """!Create and manage output console for commands run by GUI.
  139. """
  140. def __init__(self, parent, id = wx.ID_ANY, margin = False,
  141. notebook = None,
  142. style = wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  143. **kwargs):
  144. wx.SplitterWindow.__init__(self, parent, id, style = style, *kwargs)
  145. self.SetName("GMConsole")
  146. self.panelOutput = wx.Panel(parent = self, id = wx.ID_ANY)
  147. self.panelPrompt = wx.Panel(parent = self, id = wx.ID_ANY)
  148. # initialize variables
  149. self.parent = parent # GMFrame | CmdPanel | ?
  150. if notebook:
  151. self._notebook = notebook
  152. else:
  153. self._notebook = self.parent.notebook
  154. self.lineWidth = 80
  155. # remember position of line begining (used for '\r')
  156. self.linePos = -1
  157. # create queues
  158. self.requestQ = Queue.Queue()
  159. self.resultQ = Queue.Queue()
  160. # progress bar
  161. self.progressbar = wx.Gauge(parent = self.panelOutput, id = wx.ID_ANY,
  162. range = 100, pos = (110, 50), size = (-1, 25),
  163. style = wx.GA_HORIZONTAL)
  164. self.progressbar.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
  165. # text control for command output
  166. self.cmdOutput = GMStc(parent = self.panelOutput, id = wx.ID_ANY, margin = margin,
  167. wrap = None)
  168. self.cmdOutputTimer = wx.Timer(self.cmdOutput, id = wx.ID_ANY)
  169. self.cmdOutput.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
  170. self.cmdOutput.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  171. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  172. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  173. # search & command prompt
  174. self.cmdPrompt = prompt.GPromptSTC(parent = self)
  175. if self.parent.GetName() != 'LayerManager':
  176. self.search = None
  177. self.cmdPrompt.Hide()
  178. else:
  179. self.infoCollapseLabelExp = _("Click here to show search module engine")
  180. self.infoCollapseLabelCol = _("Click here to hide search module engine")
  181. self.searchPane = wx.CollapsiblePane(parent = self.panelOutput,
  182. label = self.infoCollapseLabelExp,
  183. style = wx.CP_DEFAULT_STYLE |
  184. wx.CP_NO_TLW_RESIZE | wx.EXPAND)
  185. self.MakeSearchPaneContent(self.searchPane.GetPane())
  186. self.searchPane.Collapse(True)
  187. self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnSearchPaneChanged, self.searchPane)
  188. self.search.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  189. # stream redirection
  190. self.cmdStdOut = GMStdout(self)
  191. self.cmdStrErr = GMStderr(self)
  192. # thread
  193. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  194. self.outputBox = wx.StaticBox(parent = self.panelPrompt, id = wx.ID_ANY,
  195. label = " %s " % _("Output window"))
  196. self.cmdBox = wx.StaticBox(parent = self.panelPrompt, id = wx.ID_ANY,
  197. label = " %s " % _("Command prompt"))
  198. # buttons
  199. self.btnOutputClear = wx.Button(parent = self.panelPrompt, id = wx.ID_CLEAR)
  200. self.btnOutputClear.SetToolTipString(_("Clear output window content"))
  201. self.btnCmdClear = wx.Button(parent = self.panelPrompt, id = wx.ID_CLEAR)
  202. self.btnCmdClear.SetToolTipString(_("Clear command prompt content"))
  203. if self.parent.GetName() != 'LayerManager':
  204. self.btnCmdClear.Hide()
  205. self.btnOutputSave = wx.Button(parent = self.panelPrompt, id = wx.ID_SAVE)
  206. self.btnOutputSave.SetToolTipString(_("Save output window content to the file"))
  207. # abort
  208. self.btnCmdAbort = wx.Button(parent = self.panelPrompt, id = wx.ID_ANY, label = _("&Abort"))
  209. self.btnCmdAbort.SetToolTipString(_("Abort running command"))
  210. self.btnCmdAbort.Enable(False)
  211. self.btnCmdClear.Bind(wx.EVT_BUTTON, self.cmdPrompt.OnCmdErase)
  212. self.btnOutputClear.Bind(wx.EVT_BUTTON, self.ClearHistory)
  213. self.btnOutputSave.Bind(wx.EVT_BUTTON, self.SaveHistory)
  214. self.btnCmdAbort.Bind(wx.EVT_BUTTON, self.OnCmdAbort)
  215. self.btnCmdAbort.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  216. self._layout()
  217. def _layout(self):
  218. """!Do layout"""
  219. outputSizer = wx.BoxSizer(wx.VERTICAL)
  220. promptSizer = wx.BoxSizer(wx.VERTICAL)
  221. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  222. outBtnSizer = wx.StaticBoxSizer(self.outputBox, wx.HORIZONTAL)
  223. cmdBtnSizer = wx.StaticBoxSizer(self.cmdBox, wx.HORIZONTAL)
  224. if self.search and self.search.IsShown():
  225. outputSizer.Add(item = self.searchPane, proportion = 0,
  226. flag = wx.EXPAND | wx.ALL, border = 3)
  227. outputSizer.Add(item = self.cmdOutput, proportion = 1,
  228. flag = wx.EXPAND | wx.ALL, border = 3)
  229. outputSizer.Add(item = self.progressbar, proportion = 0,
  230. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 3)
  231. promptSizer.Add(item = self.cmdPrompt, proportion = 1,
  232. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border = 3)
  233. outBtnSizer.Add(item = self.btnOutputClear, proportion = 1,
  234. flag = wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT, border = 5)
  235. outBtnSizer.Add(item = self.btnOutputSave, proportion = 1,
  236. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 5)
  237. cmdBtnSizer.Add(item = self.btnCmdClear, proportion = 1,
  238. flag = wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT, border = 5)
  239. cmdBtnSizer.Add(item = self.btnCmdAbort, proportion = 1,
  240. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
  241. btnSizer.Add(item = outBtnSizer, proportion = 1,
  242. flag = wx.ALL | wx.ALIGN_CENTER, border = 5)
  243. btnSizer.Add(item = cmdBtnSizer, proportion = 1,
  244. flag = wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, border = 5)
  245. promptSizer.Add(item = btnSizer, proportion = 1,
  246. flag = wx.EXPAND)
  247. outputSizer.Fit(self)
  248. outputSizer.SetSizeHints(self)
  249. promptSizer.Fit(self)
  250. promptSizer.SetSizeHints(self)
  251. self.panelOutput.SetSizer(outputSizer)
  252. self.panelPrompt.SetSizer(promptSizer)
  253. # split window
  254. if self.parent.GetName() == 'LayerManager':
  255. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -50)
  256. self.SetMinimumPaneSize(self.btnCmdClear.GetSize()[1] + 85)
  257. else:
  258. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -45)
  259. self.SetMinimumPaneSize(self.btnCmdClear.GetSize()[1] +25)
  260. self.SetSashGravity(1.0)
  261. # layout
  262. self.SetAutoLayout(True)
  263. self.Layout()
  264. def MakeSearchPaneContent(self, pane):
  265. """!Create search pane"""
  266. border = wx.BoxSizer(wx.VERTICAL)
  267. self.search = SearchModuleWindow(parent = pane, cmdPrompt = self.cmdPrompt)
  268. border.Add(item = self.search, proportion = 0,
  269. flag = wx.EXPAND | wx.ALL, border = 1)
  270. pane.SetSizer(border)
  271. border.Fit(pane)
  272. def OnSearchPaneChanged(self, event):
  273. """!Collapse search module box"""
  274. if self.searchPane.IsExpanded():
  275. self.searchPane.SetLabel(self.infoCollapseLabelCol)
  276. else:
  277. self.searchPane.SetLabel(self.infoCollapseLabelExp)
  278. self.panelOutput.Layout()
  279. self.panelOutput.SendSizeEvent()
  280. def GetPanel(self, prompt = True):
  281. """!Get panel
  282. @param prompt get prompt / output panel
  283. @return wx.Panel reference
  284. """
  285. if prompt:
  286. return self.panelPrompt
  287. return self.panelOutput
  288. def Redirect(self):
  289. """!Redirect stdout/stderr
  290. """
  291. if Debug.GetLevel() == 0 and int(grass.gisenv().get('DEBUG', 0)) == 0:
  292. # don't redirect when debugging is enabled
  293. sys.stdout = self.cmdStdOut
  294. sys.stderr = self.cmdStrErr
  295. else:
  296. enc = locale.getdefaultlocale()[1]
  297. if enc:
  298. sys.stdout = codecs.getwriter(enc)(sys.__stdout__)
  299. sys.stderr = codecs.getwriter(enc)(sys.__stderr__)
  300. else:
  301. sys.stdout = sys.__stdout__
  302. sys.stderr = sys.__stderr__
  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.cmdOutput.SetStyle()
  312. if switchPage:
  313. self._notebook.SetSelectionByName('output')
  314. if not style:
  315. style = self.cmdOutput.StyleDefault
  316. # p1 = self.cmdOutput.GetCurrentPos()
  317. p1 = self.cmdOutput.GetEndStyled()
  318. # self.cmdOutput.GotoPos(p1)
  319. self.cmdOutput.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.cmdOutput.AddTextWrapped(line, wrap = wrap) # adds '\n'
  326. p2 = self.cmdOutput.GetCurrentPos()
  327. self.cmdOutput.StartStyling(p1, 0xff)
  328. self.cmdOutput.SetStyling(p2 - p1, style)
  329. self.cmdOutput.EnsureCaretVisible()
  330. def WriteCmdLog(self, line, pid = None, switchPage = True):
  331. """!Write message in selected style
  332. @param line message to be printed
  333. @param pid process pid or None
  334. @param switchPage True to switch page
  335. """
  336. if pid:
  337. line = '(' + str(pid) + ') ' + line
  338. self.WriteLog(line, style = self.cmdOutput.StyleCommand, switchPage = switchPage)
  339. def WriteWarning(self, line):
  340. """!Write message in warning style"""
  341. self.WriteLog(line, style = self.cmdOutput.StyleWarning, switchPage = True)
  342. def WriteError(self, line):
  343. """!Write message in error style"""
  344. self.WriteLog(line, style = self.cmdOutput.StyleError, switchPage = True)
  345. def RunCmd(self, command, compReg = True, switchPage = False,
  346. onDone = None):
  347. """!Run command typed into console command prompt (GPrompt).
  348. @todo Display commands (*.d) are captured and processed
  349. separately by mapdisp.py. Display commands are rendered in map
  350. display widget that currently has the focus (as indicted by
  351. mdidx).
  352. @param command command given as a list (produced e.g. by utils.split())
  353. @param compReg True use computation region
  354. @param switchPage switch to output page
  355. @param onDone function to be called when command is finished
  356. """
  357. if len(command) == 0:
  358. Debug.msg(2, "GPrompt:RunCmd(): empty command")
  359. return
  360. # update history file
  361. env = grass.gisenv()
  362. try:
  363. fileHistory = codecs.open(os.path.join(env['GISDBASE'],
  364. env['LOCATION_NAME'],
  365. env['MAPSET'],
  366. '.bash_history'),
  367. encoding = 'utf-8', mode = 'a')
  368. except IOError, e:
  369. self.WriteError(e)
  370. fileHistory = None
  371. if fileHistory:
  372. try:
  373. fileHistory.write(' '.join(command) + os.linesep)
  374. finally:
  375. fileHistory.close()
  376. # update history items
  377. if self.parent.GetName() == 'LayerManager':
  378. try:
  379. self.parent.cmdinput.SetHistoryItems()
  380. except AttributeError:
  381. pass
  382. if command[0] in globalvar.grassCmd['all']:
  383. # send GRASS command without arguments to GUI command interface
  384. # except display commands (they are handled differently)
  385. if self.parent.GetName() == "LayerManager" and \
  386. command[0][0:2] == "d." and \
  387. (len(command) > 1 and 'help' not in ' '.join(command[1:])):
  388. # display GRASS commands
  389. try:
  390. layertype = {'d.rast' : 'raster',
  391. 'd.rast3d' : '3d-raster',
  392. 'd.rgb' : 'rgb',
  393. 'd.his' : 'his',
  394. 'd.shaded' : 'shaded',
  395. 'd.legend' : 'rastleg',
  396. 'd.rast.arrow' : 'rastarrow',
  397. 'd.rast.num' : 'rastnum',
  398. 'd.rast.leg' : 'maplegend',
  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.cmdStdOut, stderr = self.cmdStrErr,
  450. onDone = onDone)
  451. self.cmdOutputTimer.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.cmdStdOut, stderr = self.cmdStrErr,
  472. onDone = onDone)
  473. self.cmdOutputTimer.Start(50)
  474. return None
  475. def ClearHistory(self, event):
  476. """!Clear history of commands"""
  477. self.cmdOutput.SetReadOnly(False)
  478. self.cmdOutput.ClearAll()
  479. self.cmdOutput.SetReadOnly(True)
  480. self.progressbar.SetValue(0)
  481. def GetProgressBar(self):
  482. """!Return progress bar widget"""
  483. return self.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.cmdStrErr
  490. return self.cmdStdOut
  491. def SaveHistory(self, event):
  492. """!Save history of commands"""
  493. self.history = self.cmdOutput.GetSelectedText()
  494. if self.history == '':
  495. self.history = self.cmdOutput.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.cmdPrompt.Bind(wx.stc.EVT_STC_PAINTED, self.cmdPrompt.OnTextSelectionChanged)
  521. self.cmdOutput.Bind(wx.stc.EVT_STC_PAINTED, self.cmdOutput.OnTextSelectionChanged)
  522. else:
  523. self.cmdPrompt.Unbind(wx.stc.EVT_STC_PAINTED)
  524. self.cmdOutput.Unbind(wx.stc.EVT_STC_PAINTED)
  525. def OnUpdateStatusBar(self, event):
  526. """!Update statusbar text"""
  527. if event.GetString():
  528. nItems = len(self.cmdPrompt.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.cmdOutput.GetEndStyled()
  549. self.cmdOutput.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.cmdOutput.GetCurLine()[1]
  560. # self.cmdOutput.SetCurrentPos(pos)
  561. else:
  562. self.cmdOutput.SetCurrentPos(self.linepos)
  563. self.cmdOutput.ReplaceSelection(c)
  564. self.linepos = self.cmdOutput.GetCurrentPos()
  565. if c != ' ':
  566. last_c = c
  567. if last_c not in ('0123456789'):
  568. self.cmdOutput.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.cmdOutput.AddTextWrapped(message, wrap = 60)
  574. else:
  575. self.cmdOutput.AddTextWrapped(message, wrap = None)
  576. p2 = self.cmdOutput.GetCurrentPos()
  577. if p2 >= p1:
  578. self.cmdOutput.StartStyling(p1, 0xff)
  579. if type == 'error':
  580. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleError)
  581. elif type == 'warning':
  582. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleWarning)
  583. elif type == 'message':
  584. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleMessage)
  585. else: # unknown
  586. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleUnknown)
  587. self.cmdOutput.EnsureCaretVisible()
  588. def OnCmdProgress(self, event):
  589. """!Update progress message info"""
  590. self.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.btnCmdAbort.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.cmdOutput.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.btnCmdAbort.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.btnCmdAbort.Enable(False)
  623. if event.onDone:
  624. event.onDone(cmd = event.cmd, returncode = event.returncode)
  625. self.progressbar.SetValue(0) # reset progress bar on '0%'
  626. self.cmdOutputTimer.Stop()
  627. if event.cmd[0] == 'g.gisenv':
  628. Debug.SetLevel()
  629. self.Redirect()
  630. if self.parent.GetName() == "LayerManager":
  631. self.btnCmdAbort.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.cmdOutput.Update()
  709. time.sleep(2)
  710. dialog.Close()
  711. def OnProcessPendingOutputWindowEvents(self, event):
  712. self.ProcessPendingEvents()
  713. def ResetFocus(self):
  714. """!Reset focus"""
  715. self.cmdPrompt.SetFocus()
  716. class GMStdout:
  717. """!GMConsole standard output
  718. Based on FrameOutErr.py
  719. Name: FrameOutErr.py
  720. Purpose: Redirecting stdout / stderr
  721. Author: Jean-Michel Fauth, Switzerland
  722. Copyright: (c) 2005-2007 Jean-Michel Fauth
  723. Licence: GPL
  724. """
  725. def __init__(self, parent):
  726. self.parent = parent # GMConsole
  727. def write(self, s):
  728. if len(s) == 0 or s == '\n':
  729. return
  730. for line in s.splitlines():
  731. if len(line) == 0:
  732. continue
  733. evt = wxCmdOutput(text = line + '\n',
  734. type = '')
  735. wx.PostEvent(self.parent.cmdOutput, evt)
  736. class GMStderr:
  737. """!GMConsole standard error output
  738. Based on FrameOutErr.py
  739. Name: FrameOutErr.py
  740. Purpose: Redirecting stdout / stderr
  741. Author: Jean-Michel Fauth, Switzerland
  742. Copyright: (c) 2005-2007 Jean-Michel Fauth
  743. Licence: GPL
  744. """
  745. def __init__(self, parent):
  746. self.parent = parent # GMConsole
  747. self.type = ''
  748. self.message = ''
  749. self.printMessage = False
  750. def flush(self):
  751. pass
  752. def write(self, s):
  753. if "GtkPizza" in s:
  754. return
  755. # remove/replace escape sequences '\b' or '\r' from stream
  756. progressValue = -1
  757. for line in s.splitlines():
  758. if len(line) == 0:
  759. continue
  760. if 'GRASS_INFO_PERCENT' in line:
  761. value = int(line.rsplit(':', 1)[1].strip())
  762. if value >= 0 and value < 100:
  763. progressValue = value
  764. else:
  765. progressValue = 0
  766. elif 'GRASS_INFO_MESSAGE' in line:
  767. self.type = 'message'
  768. self.message += line.split(':', 1)[1].strip() + '\n'
  769. elif 'GRASS_INFO_WARNING' in line:
  770. self.type = 'warning'
  771. self.message += line.split(':', 1)[1].strip() + '\n'
  772. elif 'GRASS_INFO_ERROR' in line:
  773. self.type = 'error'
  774. self.message += line.split(':', 1)[1].strip() + '\n'
  775. elif 'GRASS_INFO_END' in line:
  776. self.printMessage = True
  777. elif self.type == '':
  778. if len(line) == 0:
  779. continue
  780. evt = wxCmdOutput(text = line,
  781. type = '')
  782. wx.PostEvent(self.parent.cmdOutput, evt)
  783. elif len(line) > 0:
  784. self.message += line.strip() + '\n'
  785. if self.printMessage and len(self.message) > 0:
  786. evt = wxCmdOutput(text = self.message,
  787. type = self.type)
  788. wx.PostEvent(self.parent.cmdOutput, evt)
  789. self.type = ''
  790. self.message = ''
  791. self.printMessage = False
  792. # update progress message
  793. if progressValue > -1:
  794. # self.gmgauge.SetValue(progressValue)
  795. evt = wxCmdProgress(value = progressValue)
  796. wx.PostEvent(self.parent.progressbar, evt)
  797. class GMStc(wx.stc.StyledTextCtrl):
  798. """!Styled GMConsole
  799. Based on FrameOutErr.py
  800. Name: FrameOutErr.py
  801. Purpose: Redirecting stdout / stderr
  802. Author: Jean-Michel Fauth, Switzerland
  803. Copyright: (c) 2005-2007 Jean-Michel Fauth
  804. Licence: GPL
  805. """
  806. def __init__(self, parent, id, margin = False, wrap = None):
  807. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  808. self.parent = parent
  809. self.SetUndoCollection(True)
  810. self.SetReadOnly(True)
  811. #
  812. # styles
  813. #
  814. self.SetStyle()
  815. #
  816. # line margins
  817. #
  818. # TODO print number only from cmdlog
  819. self.SetMarginWidth(1, 0)
  820. self.SetMarginWidth(2, 0)
  821. if margin:
  822. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  823. self.SetMarginWidth(0, 30)
  824. else:
  825. self.SetMarginWidth(0, 0)
  826. #
  827. # miscellaneous
  828. #
  829. self.SetViewWhiteSpace(False)
  830. self.SetTabWidth(4)
  831. self.SetUseTabs(False)
  832. self.UsePopUp(True)
  833. self.SetSelBackground(True, "#FFFF00")
  834. self.SetUseHorizontalScrollBar(True)
  835. #
  836. # bindings
  837. #
  838. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  839. def OnTextSelectionChanged(self, event):
  840. """!Copy selected text to clipboard and skip event.
  841. The same function is in TextCtrlAutoComplete class (prompt.py).
  842. """
  843. self.Copy()
  844. event.Skip()
  845. def SetStyle(self):
  846. """!Set styles for styled text output windows with type face
  847. and point size selected by user (Courier New 10 is default)"""
  848. settings = preferences.Settings()
  849. typeface = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'type')
  850. if typeface == "":
  851. typeface = "Courier New"
  852. typesize = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'size')
  853. if typesize == None or typesize <= 0:
  854. typesize = 10
  855. typesize = float(typesize)
  856. self.StyleDefault = 0
  857. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  858. self.StyleCommand = 1
  859. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  860. self.StyleOutput = 2
  861. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  862. # fatal error
  863. self.StyleError = 3
  864. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  865. # warning
  866. self.StyleWarning = 4
  867. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  868. # message
  869. self.StyleMessage = 5
  870. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  871. # unknown
  872. self.StyleUnknown = 6
  873. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  874. # default and clear => init
  875. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  876. self.StyleClearAll()
  877. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  878. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  879. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  880. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  881. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  882. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  883. def OnDestroy(self, evt):
  884. """!The clipboard contents can be preserved after
  885. the app has exited"""
  886. wx.TheClipboard.Flush()
  887. evt.Skip()
  888. def AddTextWrapped(self, txt, wrap = None):
  889. """!Add string to text area.
  890. String is wrapped and linesep is also added to the end
  891. of the string"""
  892. # allow writing to output window
  893. self.SetReadOnly(False)
  894. if wrap:
  895. txt = textwrap.fill(txt, wrap) + '\n'
  896. else:
  897. if txt[-1] != '\n':
  898. txt += '\n'
  899. if '\r' in txt:
  900. self.parent.linePos = -1
  901. for seg in txt.split('\r'):
  902. if self.parent.linePos > -1:
  903. self.SetCurrentPos(self.parent.linePos)
  904. self.ReplaceSelection(seg)
  905. else:
  906. self.parent.linePos = self.GetCurrentPos()
  907. self.AddText(seg)
  908. else:
  909. self.parent.linePos = self.GetCurrentPos()
  910. try:
  911. self.AddText(txt)
  912. except UnicodeDecodeError:
  913. enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
  914. if enc:
  915. txt = unicode(txt, enc)
  916. elif 'GRASS_DB_ENCODING' in os.environ:
  917. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  918. else:
  919. txt = utils.EncodeString(txt)
  920. self.AddText(txt)
  921. # reset output window to read only
  922. self.SetReadOnly(True)