goutput.py 35 KB

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