goutput.py 40 KB

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