goutput.py 41 KB

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