goutput.py 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  1. """!
  2. @package gui_core.goutput
  3. @brief Command output widgets
  4. Classes:
  5. - goutput::CmdThread
  6. - goutput::GMConsole
  7. - goutput::GMStdout
  8. - goutput::GMStderr
  9. - goutput::GMStc
  10. - goutput::PyStc
  11. (C) 2007-2012 by the GRASS Development Team
  12. This program is free software under the GNU General Public License
  13. (>=v2). Read the file COPYING that comes with GRASS for details.
  14. @author Michael Barton (Arizona State University)
  15. @author Martin Landa <landa.martin gmail.com>
  16. @author Vaclav Petras <wenzeslaus gmail.com> (copy&paste customization)
  17. """
  18. import os
  19. import sys
  20. import textwrap
  21. import time
  22. import threading
  23. import Queue
  24. import codecs
  25. import locale
  26. import keyword
  27. import wx
  28. from wx import stc
  29. from wx.lib.newevent import NewEvent
  30. import grass.script as grass
  31. from grass.script import task as gtask
  32. from core import globalvar
  33. from core import utils
  34. from core.gcmd import CommandThread, GMessage, GError, GException, EncodeString
  35. from gui_core.forms import GUI
  36. from gui_core.prompt import GPromptSTC
  37. from core.debug import Debug
  38. from core.settings import UserSettings, Settings
  39. from gui_core.ghelp import SearchModuleWindow
  40. wxCmdOutput, EVT_CMD_OUTPUT = NewEvent()
  41. wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
  42. wxCmdRun, EVT_CMD_RUN = NewEvent()
  43. wxCmdDone, EVT_CMD_DONE = NewEvent()
  44. wxCmdAbort, EVT_CMD_ABORT = NewEvent()
  45. wxCmdPrepare, EVT_CMD_PREPARE = NewEvent()
  46. def GrassCmd(cmd, env = None, stdout = None, stderr = None):
  47. """!Return GRASS command thread"""
  48. return CommandThread(cmd, env = env,
  49. stdout = stdout, stderr = stderr)
  50. class CmdThread(threading.Thread):
  51. """!Thread for GRASS commands"""
  52. requestId = 0
  53. def __init__(self, parent, requestQ, resultQ, **kwds):
  54. threading.Thread.__init__(self, **kwds)
  55. self.setDaemon(True)
  56. self.parent = parent # GMConsole
  57. self._want_abort_all = False
  58. self.requestQ = requestQ
  59. self.resultQ = resultQ
  60. self.start()
  61. def RunCmd(self, *args, **kwds):
  62. CmdThread.requestId += 1
  63. self.requestCmd = None
  64. self.requestQ.put((CmdThread.requestId, args, kwds))
  65. return CmdThread.requestId
  66. def SetId(self, id):
  67. """!Set starting id"""
  68. CmdThread.requestId = id
  69. def run(self):
  70. os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
  71. while True:
  72. requestId, args, kwds = self.requestQ.get()
  73. for key in ('callable', 'onDone', 'onPrepare', 'userData'):
  74. if key in kwds:
  75. vars()[key] = kwds[key]
  76. del kwds[key]
  77. else:
  78. vars()[key] = None
  79. if not vars()['callable']:
  80. vars()['callable'] = GrassCmd
  81. requestTime = time.time()
  82. # prepare
  83. event = wxCmdPrepare(cmd = args[0],
  84. time = requestTime,
  85. pid = requestId,
  86. onPrepare = vars()['onPrepare'],
  87. userData = vars()['userData'])
  88. wx.PostEvent(self.parent, event)
  89. # run command
  90. event = wxCmdRun(cmd = args[0],
  91. pid = requestId)
  92. wx.PostEvent(self.parent, event)
  93. time.sleep(.1)
  94. self.requestCmd = vars()['callable'](*args, **kwds)
  95. if self._want_abort_all:
  96. self.requestCmd.abort()
  97. if self.requestQ.empty():
  98. self._want_abort_all = False
  99. self.resultQ.put((requestId, self.requestCmd.run()))
  100. try:
  101. returncode = self.requestCmd.module.returncode
  102. except AttributeError:
  103. returncode = 0 # being optimistic
  104. try:
  105. aborted = self.requestCmd.aborted
  106. except AttributeError:
  107. aborted = False
  108. time.sleep(.1)
  109. # set default color table for raster data
  110. if UserSettings.Get(group = 'cmd', key = 'rasterColorTable', subkey = 'enabled') and \
  111. args[0][0][:2] == 'r.':
  112. colorTable = UserSettings.Get(group = 'cmd', key = 'rasterColorTable', subkey = 'selection')
  113. mapName = None
  114. if args[0][0] == 'r.mapcalc':
  115. try:
  116. mapName = args[0][1].split('=', 1)[0].strip()
  117. except KeyError:
  118. pass
  119. else:
  120. moduleInterface = GUI(show = None).ParseCommand(args[0])
  121. outputParam = moduleInterface.get_param(value = 'output', raiseError = False)
  122. if outputParam and outputParam['prompt'] == 'raster':
  123. mapName = outputParam['value']
  124. if mapName:
  125. argsColor = list(args)
  126. argsColor[0] = [ 'r.colors',
  127. 'map=%s' % mapName,
  128. 'color=%s' % colorTable ]
  129. self.requestCmdColor = vars()['callable'](*argsColor, **kwds)
  130. self.resultQ.put((requestId, self.requestCmdColor.run()))
  131. event = wxCmdDone(cmd = args[0],
  132. aborted = aborted,
  133. returncode = returncode,
  134. time = requestTime,
  135. pid = requestId,
  136. onDone = vars()['onDone'],
  137. userData = vars()['userData'])
  138. # send event
  139. wx.PostEvent(self.parent, event)
  140. def abort(self, abortall = True):
  141. """!Abort command(s)"""
  142. if abortall:
  143. self._want_abort_all = True
  144. self.requestCmd.abort()
  145. if self.requestQ.empty():
  146. self._want_abort_all = False
  147. class GMConsole(wx.SplitterWindow):
  148. """!Create and manage output console for commands run by GUI.
  149. """
  150. def __init__(self, parent, id = wx.ID_ANY, margin = False,
  151. notebook = None,
  152. style = wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  153. **kwargs):
  154. wx.SplitterWindow.__init__(self, parent, id, style = style, *kwargs)
  155. self.SetName("GMConsole")
  156. self.panelOutput = wx.Panel(parent = self, id = wx.ID_ANY)
  157. self.panelPrompt = wx.Panel(parent = self, id = wx.ID_ANY)
  158. # initialize variables
  159. self.parent = parent # GMFrame | CmdPanel | ?
  160. if notebook:
  161. self._notebook = notebook
  162. else:
  163. self._notebook = self.parent.notebook
  164. self.lineWidth = 80
  165. # remember position of line begining (used for '\r')
  166. self.linePos = -1
  167. # create queues
  168. self.requestQ = Queue.Queue()
  169. self.resultQ = Queue.Queue()
  170. # progress bar
  171. self.progressbar = wx.Gauge(parent = self.panelOutput, id = wx.ID_ANY,
  172. range = 100, pos = (110, 50), size = (-1, 25),
  173. style = wx.GA_HORIZONTAL)
  174. self.progressbar.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
  175. # text control for command output
  176. self.cmdOutput = GMStc(parent = self.panelOutput, id = wx.ID_ANY, margin = margin,
  177. wrap = None)
  178. self.cmdOutputTimer = wx.Timer(self.cmdOutput, id = wx.ID_ANY)
  179. self.cmdOutput.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
  180. self.cmdOutput.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  181. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  182. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  183. self.Bind(EVT_CMD_PREPARE, self.OnCmdPrepare)
  184. # search & command prompt
  185. self.cmdPrompt = GPromptSTC(parent = self)
  186. if self.parent.GetName() != 'LayerManager':
  187. self.search = None
  188. self.cmdPrompt.Hide()
  189. else:
  190. self.infoCollapseLabelExp = _("Click here to show search module engine")
  191. self.infoCollapseLabelCol = _("Click here to hide search module engine")
  192. self.searchPane = wx.CollapsiblePane(parent = self.panelOutput,
  193. label = self.infoCollapseLabelExp,
  194. style = wx.CP_DEFAULT_STYLE |
  195. wx.CP_NO_TLW_RESIZE | wx.EXPAND)
  196. self.MakeSearchPaneContent(self.searchPane.GetPane())
  197. self.searchPane.Collapse(True)
  198. self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnSearchPaneChanged, self.searchPane)
  199. self.search.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  200. # stream redirection
  201. self.cmdStdOut = GMStdout(self)
  202. self.cmdStdErr = GMStderr(self)
  203. # thread
  204. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  205. self.outputBox = wx.StaticBox(parent = self.panelOutput, id = wx.ID_ANY,
  206. label = " %s " % _("Output window"))
  207. self.cmdBox = wx.StaticBox(parent = self.panelOutput, id = wx.ID_ANY,
  208. label = " %s " % _("Command prompt"))
  209. # buttons
  210. self.btnOutputClear = wx.Button(parent = self.panelOutput, id = wx.ID_CLEAR)
  211. self.btnOutputClear.SetToolTipString(_("Clear output window content"))
  212. self.btnCmdClear = wx.Button(parent = self.panelOutput, id = wx.ID_CLEAR)
  213. self.btnCmdClear.SetToolTipString(_("Clear command prompt content"))
  214. self.btnOutputSave = wx.Button(parent = self.panelOutput, id = wx.ID_SAVE)
  215. self.btnOutputSave.SetToolTipString(_("Save output window content to the file"))
  216. self.btnCmdAbort = wx.Button(parent = self.panelOutput, id = wx.ID_STOP)
  217. self.btnCmdAbort.SetToolTipString(_("Abort running command"))
  218. self.btnCmdAbort.Enable(False)
  219. self.btnCmdProtocol = wx.ToggleButton(parent = self.panelOutput, id = wx.ID_ANY,
  220. label = _("&Protocol"))
  221. self.btnCmdProtocol.SetToolTipString(_("Toggle to save list of executed commands into file; "
  222. "content saved when switching off."))
  223. if self.parent.GetName() != 'LayerManager':
  224. self.btnCmdClear.Hide()
  225. self.btnCmdProtocol.Hide()
  226. self.btnCmdClear.Bind(wx.EVT_BUTTON, self.cmdPrompt.OnCmdErase)
  227. self.btnOutputClear.Bind(wx.EVT_BUTTON, self.OnOutputClear)
  228. self.btnOutputSave.Bind(wx.EVT_BUTTON, self.OnOutputSave)
  229. self.btnCmdAbort.Bind(wx.EVT_BUTTON, self.OnCmdAbort)
  230. self.btnCmdAbort.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  231. self.btnCmdProtocol.Bind(wx.EVT_TOGGLEBUTTON, self.OnCmdProtocol)
  232. self._layout()
  233. def _layout(self):
  234. """!Do layout"""
  235. outputSizer = wx.BoxSizer(wx.VERTICAL)
  236. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  237. outBtnSizer = wx.StaticBoxSizer(self.outputBox, wx.HORIZONTAL)
  238. cmdBtnSizer = wx.StaticBoxSizer(self.cmdBox, wx.HORIZONTAL)
  239. if self.cmdPrompt.IsShown():
  240. promptSizer = wx.BoxSizer(wx.VERTICAL)
  241. promptSizer.Add(item = self.cmdPrompt, proportion = 1,
  242. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border = 3)
  243. if self.search and self.search.IsShown():
  244. outputSizer.Add(item = self.searchPane, proportion = 0,
  245. flag = wx.EXPAND | wx.ALL, border = 3)
  246. outputSizer.Add(item = self.cmdOutput, proportion = 1,
  247. flag = wx.EXPAND | wx.ALL, border = 3)
  248. outputSizer.Add(item = self.progressbar, proportion = 0,
  249. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 3)
  250. outBtnSizer.Add(item = self.btnOutputClear, proportion = 1,
  251. flag = wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT, border = 5)
  252. outBtnSizer.Add(item = self.btnOutputSave, proportion = 1,
  253. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 5)
  254. cmdBtnSizer.Add(item = self.btnCmdProtocol, proportion = 1,
  255. flag = wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border = 5)
  256. cmdBtnSizer.Add(item = self.btnCmdClear, proportion = 1,
  257. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
  258. cmdBtnSizer.Add(item = self.btnCmdAbort, proportion = 1,
  259. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
  260. if self.parent.GetName() != 'LayerManager':
  261. proportion = (1, 1)
  262. else:
  263. proportion = (2, 3)
  264. btnSizer.Add(item = outBtnSizer, proportion = proportion[0],
  265. flag = wx.ALL | wx.ALIGN_CENTER, border = 5)
  266. btnSizer.Add(item = cmdBtnSizer, proportion = proportion[1],
  267. flag = wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, border = 5)
  268. outputSizer.Add(item = btnSizer, proportion = 0,
  269. flag = wx.EXPAND)
  270. outputSizer.Fit(self)
  271. outputSizer.SetSizeHints(self)
  272. self.panelOutput.SetSizer(outputSizer)
  273. if self.cmdPrompt.IsShown():
  274. promptSizer.Fit(self)
  275. promptSizer.SetSizeHints(self)
  276. self.panelPrompt.SetSizer(promptSizer)
  277. # split window
  278. if self.cmdPrompt.IsShown():
  279. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -50)
  280. else:
  281. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -45)
  282. self.Unsplit()
  283. self.SetMinimumPaneSize(self.btnCmdClear.GetSize()[1] + 25)
  284. self.SetSashGravity(1.0)
  285. # layout
  286. self.SetAutoLayout(True)
  287. self.Layout()
  288. def MakeSearchPaneContent(self, pane):
  289. """!Create search pane"""
  290. border = wx.BoxSizer(wx.VERTICAL)
  291. self.search = SearchModuleWindow(parent = pane, cmdPrompt = self.cmdPrompt)
  292. border.Add(item = self.search, proportion = 0,
  293. flag = wx.EXPAND | wx.ALL, border = 1)
  294. pane.SetSizer(border)
  295. border.Fit(pane)
  296. def OnSearchPaneChanged(self, event):
  297. """!Collapse search module box"""
  298. if self.searchPane.IsExpanded():
  299. self.searchPane.SetLabel(self.infoCollapseLabelCol)
  300. else:
  301. self.searchPane.SetLabel(self.infoCollapseLabelExp)
  302. self.panelOutput.Layout()
  303. self.panelOutput.SendSizeEvent()
  304. def GetPanel(self, prompt = True):
  305. """!Get panel
  306. @param prompt get prompt / output panel
  307. @return wx.Panel reference
  308. """
  309. if prompt:
  310. return self.panelPrompt
  311. return self.panelOutput
  312. def Redirect(self):
  313. """!Redirect stdout/stderr
  314. """
  315. if Debug.GetLevel() == 0 and int(grass.gisenv().get('DEBUG', 0)) == 0:
  316. # don't redirect when debugging is enabled
  317. sys.stdout = self.cmdStdOut
  318. sys.stderr = self.cmdStdErr
  319. else:
  320. enc = locale.getdefaultlocale()[1]
  321. if enc:
  322. sys.stdout = codecs.getwriter(enc)(sys.__stdout__)
  323. sys.stderr = codecs.getwriter(enc)(sys.__stderr__)
  324. else:
  325. sys.stdout = sys.__stdout__
  326. sys.stderr = sys.__stderr__
  327. def WriteLog(self, text, style = None, wrap = None,
  328. switchPage = False):
  329. """!Generic method for writing log message in
  330. given style
  331. @param line text line
  332. @param style text style (see GMStc)
  333. @param stdout write to stdout or stderr
  334. """
  335. self.cmdOutput.SetStyle()
  336. if switchPage:
  337. self._notebook.SetSelectionByName('output')
  338. if not style:
  339. style = self.cmdOutput.StyleDefault
  340. # p1 = self.cmdOutput.GetCurrentPos()
  341. p1 = self.cmdOutput.GetEndStyled()
  342. # self.cmdOutput.GotoPos(p1)
  343. self.cmdOutput.DocumentEnd()
  344. for line in text.splitlines():
  345. # fill space
  346. if len(line) < self.lineWidth:
  347. diff = self.lineWidth - len(line)
  348. line += diff * ' '
  349. self.cmdOutput.AddTextWrapped(line, wrap = wrap) # adds '\n'
  350. p2 = self.cmdOutput.GetCurrentPos()
  351. self.cmdOutput.StartStyling(p1, 0xff)
  352. self.cmdOutput.SetStyling(p2 - p1, style)
  353. self.cmdOutput.EnsureCaretVisible()
  354. def WriteCmdLog(self, line, pid = None, switchPage = True):
  355. """!Write message in selected style
  356. @param line message to be printed
  357. @param pid process pid or None
  358. @param switchPage True to switch page
  359. """
  360. if pid:
  361. line = '(' + str(pid) + ') ' + line
  362. self.WriteLog(line, style = self.cmdOutput.StyleCommand, switchPage = switchPage)
  363. def WriteWarning(self, line):
  364. """!Write message in warning style"""
  365. self.WriteLog(line, style = self.cmdOutput.StyleWarning, switchPage = True)
  366. def WriteError(self, line):
  367. """!Write message in error style"""
  368. self.WriteLog(line, style = self.cmdOutput.StyleError, switchPage = True)
  369. def RunCmd(self, command, compReg = True, switchPage = False, skipInterface = False,
  370. onDone = None, onPrepare = None, userData = None):
  371. """!Run command typed into console command prompt (GPrompt).
  372. @todo Display commands (*.d) are captured and processed
  373. separately by mapdisp.py. Display commands are rendered in map
  374. display widget that currently has the focus (as indicted by
  375. mdidx).
  376. @param command command given as a list (produced e.g. by utils.split())
  377. @param compReg True use computation region
  378. @param switchPage switch to output page
  379. @param skipInterface True to do not launch GRASS interface
  380. parser when command has no arguments given
  381. @param onDone function to be called when command is finished
  382. @param onPrepare function to be called before command is launched
  383. @param userData data defined for the command
  384. """
  385. if len(command) == 0:
  386. Debug.msg(2, "GPrompt:RunCmd(): empty command")
  387. return
  388. # update history file
  389. env = grass.gisenv()
  390. try:
  391. fileHistory = codecs.open(os.path.join(env['GISDBASE'],
  392. env['LOCATION_NAME'],
  393. env['MAPSET'],
  394. '.bash_history'),
  395. encoding = 'utf-8', mode = 'a')
  396. except IOError, e:
  397. GError(_("Unable to write file '%s'.\n\nDetails: %s") % (path, e),
  398. parent = self.parent)
  399. fileHistory = None
  400. if fileHistory:
  401. try:
  402. fileHistory.write(' '.join(command) + os.linesep)
  403. finally:
  404. fileHistory.close()
  405. if command[0] in globalvar.grassCmd:
  406. # send GRASS command without arguments to GUI command interface
  407. # except display commands (they are handled differently)
  408. if self.parent.GetName() == "LayerManager" and \
  409. command[0][0:2] == "d." and \
  410. 'help' not in ' '.join(command[1:]):
  411. # display GRASS commands
  412. try:
  413. layertype = {'d.rast' : 'raster',
  414. 'd.rast3d' : '3d-raster',
  415. 'd.rgb' : 'rgb',
  416. 'd.his' : 'his',
  417. 'd.shaded' : 'shaded',
  418. 'd.legend' : 'rastleg',
  419. 'd.rast.arrow' : 'rastarrow',
  420. 'd.rast.num' : 'rastnum',
  421. 'd.rast.leg' : 'maplegend',
  422. 'd.vect' : 'vector',
  423. 'd.thematic.area': 'thememap',
  424. 'd.vect.chart' : 'themechart',
  425. 'd.grid' : 'grid',
  426. 'd.geodesic' : 'geodesic',
  427. 'd.rhumbline' : 'rhumb',
  428. 'd.labels' : 'labels',
  429. 'd.barscale' : 'barscale',
  430. 'd.redraw' : 'redraw'}[command[0]]
  431. except KeyError:
  432. GMessage(parent = self.parent,
  433. message = _("Command '%s' not yet implemented in the WxGUI. "
  434. "Try adding it as a command layer instead.") % command[0])
  435. return
  436. if layertype == 'barscale':
  437. self.parent.curr_page.maptree.GetMapDisplay().OnAddBarscale(None)
  438. elif layertype == 'rastleg':
  439. self.parent.curr_page.maptree.GetMapDisplay().OnAddLegend(None)
  440. elif layertype == 'redraw':
  441. self.parent.curr_page.maptree.GetMapDisplay().OnRender(None)
  442. else:
  443. # add layer into layer tree
  444. lname, found = utils.GetLayerNameFromCmd(command, fullyQualified = True,
  445. layerType = layertype)
  446. if self.parent.GetName() == "LayerManager":
  447. self.parent.curr_page.maptree.AddLayer(ltype = layertype,
  448. lname = lname,
  449. lcmd = command)
  450. else:
  451. # other GRASS commands (r|v|g|...)
  452. try:
  453. task = GUI(show = None).ParseCommand(command)
  454. except GException, e:
  455. GError(parent = self,
  456. message = unicode(e),
  457. showTraceback = False)
  458. return
  459. hasParams = False
  460. if task:
  461. options = task.get_options()
  462. hasParams = options['params'] and options['flags']
  463. # check for <input>=-
  464. for p in options['params']:
  465. if p.get('prompt', '') == 'input' and \
  466. p.get('element', '') == 'file' and \
  467. p.get('age', 'new') == 'old' and \
  468. p.get('value', '') == '-':
  469. GError(parent = self,
  470. message = _("Unable to run command:\n%(cmd)s\n\n"
  471. "Option <%(opt)s>: read from standard input is not "
  472. "supported by wxGUI") % { 'cmd': ' '.join(command),
  473. 'opt': p.get('name', '') })
  474. return
  475. if len(command) == 1 and hasParams and \
  476. command[0] != 'v.krige':
  477. # no arguments given
  478. try:
  479. GUI(parent = self).ParseCommand(command)
  480. except GException, e:
  481. print >> sys.stderr, e
  482. return
  483. # switch to 'Command output' if required
  484. if switchPage:
  485. self._notebook.SetSelectionByName('output')
  486. self.parent.SetFocus()
  487. self.parent.Raise()
  488. # activate computational region (set with g.region)
  489. # for all non-display commands.
  490. if compReg:
  491. tmpreg = os.getenv("GRASS_REGION")
  492. if "GRASS_REGION" in os.environ:
  493. del os.environ["GRASS_REGION"]
  494. # process GRASS command with argument
  495. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  496. onDone = onDone, onPrepare = onPrepare, userData = userData,
  497. env = os.environ.copy())
  498. self.cmdOutputTimer.Start(50)
  499. # deactivate computational region and return to display settings
  500. if compReg and tmpreg:
  501. os.environ["GRASS_REGION"] = tmpreg
  502. else:
  503. # Send any other command to the shell. Send output to
  504. # console output window
  505. if len(command) == 1 and not skipInterface:
  506. try:
  507. task = gtask.parse_interface(command[0])
  508. except:
  509. task = None
  510. else:
  511. task = None
  512. if task:
  513. # process GRASS command without argument
  514. GUI(parent = self).ParseCommand(command)
  515. else:
  516. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  517. onDone = onDone, onPrepare = onPrepare, userData = userData)
  518. self.cmdOutputTimer.Start(50)
  519. def OnOutputClear(self, event):
  520. """!Clear content of output window"""
  521. self.cmdOutput.SetReadOnly(False)
  522. self.cmdOutput.ClearAll()
  523. self.cmdOutput.SetReadOnly(True)
  524. self.progressbar.SetValue(0)
  525. def GetProgressBar(self):
  526. """!Return progress bar widget"""
  527. return self.progressbar
  528. def GetLog(self, err = False):
  529. """!Get widget used for logging
  530. @param err True to get stderr widget
  531. """
  532. if err:
  533. return self.cmdStdErr
  534. return self.cmdStdOut
  535. def OnOutputSave(self, event):
  536. """!Save (selected) text from output window to the file"""
  537. text = self.cmdOutput.GetSelectedText()
  538. if not text:
  539. text = self.cmdOutput.GetText()
  540. # add newline if needed
  541. if len(text) > 0 and text[-1] != '\n':
  542. text += '\n'
  543. dlg = wx.FileDialog(self, message = _("Save file as..."),
  544. defaultFile = "grass_cmd_output.txt",
  545. wildcard = _("%s (*.txt)|*.txt|%s (*)|*") % (_("Text files"), _("Files")),
  546. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  547. # Show the dialog and retrieve the user response. If it is the OK response,
  548. # process the data.
  549. if dlg.ShowModal() == wx.ID_OK:
  550. path = dlg.GetPath()
  551. try:
  552. output = open(path, "w")
  553. output.write(text)
  554. except IOError, e:
  555. GError(_("Unable to write file '%s'.\n\nDetails: %s") % (path, e))
  556. finally:
  557. output.close()
  558. self.parent.SetStatusText(_("Commands output saved into '%s'") % path)
  559. dlg.Destroy()
  560. def GetCmd(self):
  561. """!Get running command or None"""
  562. return self.requestQ.get()
  563. def SetCopyingOfSelectedText(self, copy):
  564. """!Enable or disable copying of selected text in to clipboard.
  565. Effects prompt and output.
  566. @param copy True for enable, False for disable
  567. """
  568. if copy:
  569. self.cmdPrompt.Bind(stc.EVT_STC_PAINTED, self.cmdPrompt.OnTextSelectionChanged)
  570. self.cmdOutput.Bind(stc.EVT_STC_PAINTED, self.cmdOutput.OnTextSelectionChanged)
  571. else:
  572. self.cmdPrompt.Unbind(stc.EVT_STC_PAINTED)
  573. self.cmdOutput.Unbind(stc.EVT_STC_PAINTED)
  574. def OnUpdateStatusBar(self, event):
  575. """!Update statusbar text"""
  576. if event.GetString():
  577. nItems = len(self.cmdPrompt.GetCommandItems())
  578. self.parent.SetStatusText(_('%d modules match') % nItems, 0)
  579. else:
  580. self.parent.SetStatusText('', 0)
  581. event.Skip()
  582. def OnCmdOutput(self, event):
  583. """!Print command output"""
  584. message = event.text
  585. type = event.type
  586. if self._notebook.GetSelection() != self._notebook.GetPageIndexByName('output'):
  587. page = self._notebook.GetPageIndexByName('output')
  588. textP = self._notebook.GetPageText(page)
  589. if textP[-1] != ')':
  590. textP += ' (...)'
  591. self._notebook.SetPageText(page, textP)
  592. # message prefix
  593. if type == 'warning':
  594. messege = 'WARNING: ' + message
  595. elif type == 'error':
  596. message = 'ERROR: ' + message
  597. p1 = self.cmdOutput.GetEndStyled()
  598. self.cmdOutput.GotoPos(p1)
  599. if '\b' in message:
  600. if self.linepos < 0:
  601. self.linepos = p1
  602. last_c = ''
  603. for c in message:
  604. if c == '\b':
  605. self.linepos -= 1
  606. else:
  607. if c == '\r':
  608. pos = self.cmdOutput.GetCurLine()[1]
  609. # self.cmdOutput.SetCurrentPos(pos)
  610. else:
  611. self.cmdOutput.SetCurrentPos(self.linepos)
  612. self.cmdOutput.ReplaceSelection(c)
  613. self.linepos = self.cmdOutput.GetCurrentPos()
  614. if c != ' ':
  615. last_c = c
  616. if last_c not in ('0123456789'):
  617. self.cmdOutput.AddTextWrapped('\n', wrap = None)
  618. self.linepos = -1
  619. else:
  620. self.linepos = -1 # don't force position
  621. if '\n' not in message:
  622. self.cmdOutput.AddTextWrapped(message, wrap = 60)
  623. else:
  624. self.cmdOutput.AddTextWrapped(message, wrap = None)
  625. p2 = self.cmdOutput.GetCurrentPos()
  626. if p2 >= p1:
  627. self.cmdOutput.StartStyling(p1, 0xff)
  628. if type == 'error':
  629. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleError)
  630. elif type == 'warning':
  631. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleWarning)
  632. elif type == 'message':
  633. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleMessage)
  634. else: # unknown
  635. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleUnknown)
  636. self.cmdOutput.EnsureCaretVisible()
  637. def OnCmdProgress(self, event):
  638. """!Update progress message info"""
  639. self.progressbar.SetValue(event.value)
  640. def CmdProtocolSave(self):
  641. """Save commands protocol into the file"""
  642. if not hasattr(self, 'cmdFileProtocol'):
  643. return # it should not happen
  644. try:
  645. output = open(self.cmdFileProtocol, "w")
  646. cmds = self.cmdPrompt.GetCommands()
  647. output.write('\n'.join(cmds))
  648. if len(cmds) > 0:
  649. output.write('\n')
  650. except IOError, e:
  651. GError(_("Unable to write file '%s'.\n\nDetails: %s") % (path, e))
  652. finally:
  653. output.close()
  654. self.parent.SetStatusText(_("Commands protocol saved into '%s'") % self.cmdFileProtocol)
  655. del self.cmdFileProtocol
  656. def OnCmdProtocol(self, event = None):
  657. """!Save commands into file"""
  658. if not event.IsChecked():
  659. # stop capturing commands, save list of commands to the
  660. # protocol file
  661. self.CmdProtocolSave()
  662. else:
  663. # start capturing commands
  664. self.cmdPrompt.ClearCommands()
  665. # ask for the file
  666. dlg = wx.FileDialog(self, message = _("Save file as..."),
  667. defaultFile = "grass_cmd_protocol.txt",
  668. wildcard = _("%s (*.txt)|*.txt|%s (*)|*") % (_("Text files"), _("Files")),
  669. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  670. if dlg.ShowModal() == wx.ID_OK:
  671. self.cmdFileProtocol = dlg.GetPath()
  672. dlg.Destroy()
  673. def OnCmdAbort(self, event):
  674. """!Abort running command"""
  675. self.cmdThread.abort()
  676. def OnCmdRun(self, event):
  677. """!Run command"""
  678. if self.parent.GetName() == 'Modeler':
  679. self.parent.OnCmdRun(event)
  680. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  681. self.btnCmdAbort.Enable()
  682. def OnCmdPrepare(self, event):
  683. """!Prepare for running command"""
  684. if self.parent.GetName() == 'Modeler':
  685. self.parent.OnCmdPrepare(event)
  686. event.Skip()
  687. def OnCmdDone(self, event):
  688. """!Command done (or aborted)"""
  689. if self.parent.GetName() == 'Modeler':
  690. self.parent.OnCmdDone(event)
  691. # Process results here
  692. try:
  693. ctime = time.time() - event.time
  694. if ctime < 60:
  695. stime = _("%d sec") % int(ctime)
  696. else:
  697. mtime = int(ctime / 60)
  698. stime = _("%(min)d min %(sec)d sec") % { 'min' : mtime,
  699. 'sec' : int(ctime - (mtime * 60)) }
  700. except KeyError:
  701. # stopped deamon
  702. stime = _("unknown")
  703. if event.aborted:
  704. # Thread aborted (using our convention of None return)
  705. self.WriteLog(_('Please note that the data are left in inconsistent state '
  706. 'and may be corrupted'), self.cmdOutput.StyleWarning)
  707. msg = _('Command aborted')
  708. else:
  709. msg = _('Command finished')
  710. self.WriteCmdLog('(%s) %s (%s)' % (str(time.ctime()), msg, stime))
  711. self.btnCmdAbort.Enable(False)
  712. if event.onDone:
  713. event.onDone(cmd = event.cmd, returncode = event.returncode)
  714. self.progressbar.SetValue(0) # reset progress bar on '0%'
  715. self.cmdOutputTimer.Stop()
  716. if event.cmd[0] == 'g.gisenv':
  717. Debug.SetLevel()
  718. self.Redirect()
  719. if self.parent.GetName() == "LayerManager":
  720. self.btnCmdAbort.Enable(False)
  721. if event.cmd[0] not in globalvar.grassCmd or \
  722. event.cmd[0] == 'r.mapcalc':
  723. return
  724. display = self.parent.GetLayerTree().GetMapDisplay()
  725. if not display or not display.IsAutoRendered():
  726. return
  727. mapLayers = map(lambda x: x.GetName(),
  728. display.GetMap().GetListOfLayers(l_type = 'raster') +
  729. display.GetMap().GetListOfLayers(l_type = 'vector'))
  730. try:
  731. task = GUI(show = None).ParseCommand(event.cmd)
  732. except GException, e:
  733. print >> sys.stderr, e
  734. task = None
  735. return
  736. for p in task.get_options()['params']:
  737. if p.get('prompt', '') not in ('raster', 'vector'):
  738. continue
  739. mapName = p.get('value', '')
  740. if '@' not in mapName:
  741. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  742. if mapName in mapLayers:
  743. display.GetWindow().UpdateMap(render = True)
  744. return
  745. elif self.parent.GetName() == 'Modeler':
  746. pass
  747. else: # standalone dialogs
  748. dialog = self.parent.parent
  749. if hasattr(self.parent.parent, "btn_abort"):
  750. dialog.btn_abort.Enable(False)
  751. if hasattr(self.parent.parent, "btn_cancel"):
  752. dialog.btn_cancel.Enable(True)
  753. if hasattr(self.parent.parent, "btn_clipboard"):
  754. dialog.btn_clipboard.Enable(True)
  755. if hasattr(self.parent.parent, "btn_help"):
  756. dialog.btn_help.Enable(True)
  757. if hasattr(self.parent.parent, "btn_run"):
  758. dialog.btn_run.Enable(True)
  759. if event.returncode == 0 and not event.aborted:
  760. try:
  761. winName = self.parent.parent.parent.GetName()
  762. except AttributeError:
  763. winName = ''
  764. if winName == 'LayerManager':
  765. mapTree = self.parent.parent.parent.GetLayerTree()
  766. elif winName == 'LayerTree':
  767. mapTree = self.parent.parent.parent
  768. elif winName: # GMConsole
  769. mapTree = self.parent.parent.parent.parent.GetLayerTree()
  770. else:
  771. mapTree = None
  772. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  773. if hasattr(dialog, "addbox") and dialog.addbox.IsChecked():
  774. # add created maps into layer tree
  775. for p in dialog.task.get_options()['params']:
  776. prompt = p.get('prompt', '')
  777. if prompt in ('raster', 'vector', '3d-raster') and \
  778. p.get('age', 'old') == 'new' and \
  779. p.get('value', None):
  780. name, found = utils.GetLayerNameFromCmd(cmd, fullyQualified = True,
  781. param = p.get('name', ''))
  782. if mapTree.GetMap().GetListOfLayers(l_name = name):
  783. continue
  784. if prompt == 'raster':
  785. lcmd = ['d.rast',
  786. 'map=%s' % name]
  787. else:
  788. lcmd = ['d.vect',
  789. 'map=%s' % name]
  790. mapTree.AddLayer(ltype = prompt,
  791. lcmd = lcmd,
  792. lname = name)
  793. if hasattr(dialog, "get_dcmd") and \
  794. dialog.get_dcmd is None and \
  795. hasattr(dialog, "closebox") and \
  796. dialog.closebox.IsChecked() and \
  797. (event.returncode == 0 or event.aborted):
  798. self.cmdOutput.Update()
  799. time.sleep(2)
  800. dialog.Close()
  801. def OnProcessPendingOutputWindowEvents(self, event):
  802. self.ProcessPendingEvents()
  803. def ResetFocus(self):
  804. """!Reset focus"""
  805. self.cmdPrompt.SetFocus()
  806. class GMStdout:
  807. """!GMConsole standard output
  808. Based on FrameOutErr.py
  809. Name: FrameOutErr.py
  810. Purpose: Redirecting stdout / stderr
  811. Author: Jean-Michel Fauth, Switzerland
  812. Copyright: (c) 2005-2007 Jean-Michel Fauth
  813. Licence: GPL
  814. """
  815. def __init__(self, parent):
  816. self.parent = parent # GMConsole
  817. def write(self, s):
  818. if len(s) == 0 or s == '\n':
  819. return
  820. for line in s.splitlines():
  821. if len(line) == 0:
  822. continue
  823. evt = wxCmdOutput(text = line + '\n',
  824. type = '')
  825. wx.PostEvent(self.parent.cmdOutput, evt)
  826. class GMStderr:
  827. """!GMConsole standard error output
  828. Based on FrameOutErr.py
  829. Name: FrameOutErr.py
  830. Purpose: Redirecting stdout / stderr
  831. Author: Jean-Michel Fauth, Switzerland
  832. Copyright: (c) 2005-2007 Jean-Michel Fauth
  833. Licence: GPL
  834. """
  835. def __init__(self, parent):
  836. self.parent = parent # GMConsole
  837. self.type = ''
  838. self.message = ''
  839. self.printMessage = False
  840. def flush(self):
  841. pass
  842. def write(self, s):
  843. if "GtkPizza" in s:
  844. return
  845. # remove/replace escape sequences '\b' or '\r' from stream
  846. progressValue = -1
  847. for line in s.splitlines():
  848. if len(line) == 0:
  849. continue
  850. if 'GRASS_INFO_PERCENT' in line:
  851. value = int(line.rsplit(':', 1)[1].strip())
  852. if value >= 0 and value < 100:
  853. progressValue = value
  854. else:
  855. progressValue = 0
  856. elif 'GRASS_INFO_MESSAGE' in line:
  857. self.type = 'message'
  858. self.message += line.split(':', 1)[1].strip() + '\n'
  859. elif 'GRASS_INFO_WARNING' in line:
  860. self.type = 'warning'
  861. self.message += line.split(':', 1)[1].strip() + '\n'
  862. elif 'GRASS_INFO_ERROR' in line:
  863. self.type = 'error'
  864. self.message += line.split(':', 1)[1].strip() + '\n'
  865. elif 'GRASS_INFO_END' in line:
  866. self.printMessage = True
  867. elif self.type == '':
  868. if len(line) == 0:
  869. continue
  870. evt = wxCmdOutput(text = line,
  871. type = '')
  872. wx.PostEvent(self.parent.cmdOutput, evt)
  873. elif len(line) > 0:
  874. self.message += line.strip() + '\n'
  875. if self.printMessage and len(self.message) > 0:
  876. evt = wxCmdOutput(text = self.message,
  877. type = self.type)
  878. wx.PostEvent(self.parent.cmdOutput, evt)
  879. self.type = ''
  880. self.message = ''
  881. self.printMessage = False
  882. # update progress message
  883. if progressValue > -1:
  884. # self.gmgauge.SetValue(progressValue)
  885. evt = wxCmdProgress(value = progressValue)
  886. wx.PostEvent(self.parent.progressbar, evt)
  887. class GMStc(stc.StyledTextCtrl):
  888. """!Styled GMConsole
  889. Based on FrameOutErr.py
  890. Name: FrameOutErr.py
  891. Purpose: Redirecting stdout / stderr
  892. Author: Jean-Michel Fauth, Switzerland
  893. Copyright: (c) 2005-2007 Jean-Michel Fauth
  894. Licence: GPL
  895. """
  896. def __init__(self, parent, id, margin = False, wrap = None):
  897. stc.StyledTextCtrl.__init__(self, parent, id)
  898. self.parent = parent
  899. self.SetUndoCollection(True)
  900. self.SetReadOnly(True)
  901. #
  902. # styles
  903. #
  904. self.SetStyle()
  905. #
  906. # line margins
  907. #
  908. # TODO print number only from cmdlog
  909. self.SetMarginWidth(1, 0)
  910. self.SetMarginWidth(2, 0)
  911. if margin:
  912. self.SetMarginType(0, stc.STC_MARGIN_NUMBER)
  913. self.SetMarginWidth(0, 30)
  914. else:
  915. self.SetMarginWidth(0, 0)
  916. #
  917. # miscellaneous
  918. #
  919. self.SetViewWhiteSpace(False)
  920. self.SetTabWidth(4)
  921. self.SetUseTabs(False)
  922. self.UsePopUp(True)
  923. self.SetSelBackground(True, "#FFFF00")
  924. self.SetUseHorizontalScrollBar(True)
  925. #
  926. # bindings
  927. #
  928. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  929. def OnTextSelectionChanged(self, event):
  930. """!Copy selected text to clipboard and skip event.
  931. The same function is in TextCtrlAutoComplete class (prompt.py).
  932. """
  933. wx.CallAfter(self.Copy)
  934. event.Skip()
  935. def SetStyle(self):
  936. """!Set styles for styled text output windows with type face
  937. and point size selected by user (Courier New 10 is default)"""
  938. settings = Settings()
  939. typeface = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'type')
  940. if typeface == "":
  941. typeface = "Courier New"
  942. typesize = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'size')
  943. if typesize == None or typesize <= 0:
  944. typesize = 10
  945. typesize = float(typesize)
  946. self.StyleDefault = 0
  947. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  948. self.StyleCommand = 1
  949. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  950. self.StyleOutput = 2
  951. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  952. # fatal error
  953. self.StyleError = 3
  954. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  955. # warning
  956. self.StyleWarning = 4
  957. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  958. # message
  959. self.StyleMessage = 5
  960. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  961. # unknown
  962. self.StyleUnknown = 6
  963. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  964. # default and clear => init
  965. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  966. self.StyleClearAll()
  967. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  968. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  969. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  970. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  971. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  972. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  973. def OnDestroy(self, evt):
  974. """!The clipboard contents can be preserved after
  975. the app has exited"""
  976. wx.TheClipboard.Flush()
  977. evt.Skip()
  978. def AddTextWrapped(self, txt, wrap = None):
  979. """!Add string to text area.
  980. String is wrapped and linesep is also added to the end
  981. of the string"""
  982. # allow writing to output window
  983. self.SetReadOnly(False)
  984. if wrap:
  985. txt = textwrap.fill(txt, wrap) + '\n'
  986. else:
  987. if txt[-1] != '\n':
  988. txt += '\n'
  989. if '\r' in txt:
  990. self.parent.linePos = -1
  991. for seg in txt.split('\r'):
  992. if self.parent.linePos > -1:
  993. self.SetCurrentPos(self.parent.linePos)
  994. self.ReplaceSelection(seg)
  995. else:
  996. self.parent.linePos = self.GetCurrentPos()
  997. self.AddText(seg)
  998. else:
  999. self.parent.linePos = self.GetCurrentPos()
  1000. try:
  1001. self.AddText(txt)
  1002. except UnicodeDecodeError:
  1003. enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
  1004. if enc:
  1005. txt = unicode(txt, enc)
  1006. elif 'GRASS_DB_ENCODING' in os.environ:
  1007. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  1008. else:
  1009. txt = EncodeString(txt)
  1010. self.AddText(txt)
  1011. # reset output window to read only
  1012. self.SetReadOnly(True)
  1013. class PyStc(stc.StyledTextCtrl):
  1014. """!Styled Python output (see gmodeler::frame::PythonPanel for
  1015. usage)
  1016. Based on StyledTextCtrl_2 from wxPython demo
  1017. """
  1018. def __init__(self, parent, id = wx.ID_ANY, statusbar = None):
  1019. stc.StyledTextCtrl.__init__(self, parent, id)
  1020. self.parent = parent
  1021. self.statusbar = statusbar
  1022. self.modified = False # content modified ?
  1023. self.faces = { 'times': 'Times New Roman',
  1024. 'mono' : 'Courier New',
  1025. 'helv' : 'Arial',
  1026. 'other': 'Comic Sans MS',
  1027. 'size' : 10,
  1028. 'size2': 8,
  1029. }
  1030. self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN)
  1031. self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT)
  1032. self.SetLexer(stc.STC_LEX_PYTHON)
  1033. self.SetKeyWords(0, " ".join(keyword.kwlist))
  1034. self.SetProperty("fold", "1")
  1035. self.SetProperty("tab.timmy.whinge.level", "1")
  1036. self.SetMargins(0, 0)
  1037. self.SetTabWidth(4)
  1038. self.SetUseTabs(False)
  1039. self.SetEdgeMode(stc.STC_EDGE_BACKGROUND)
  1040. self.SetEdgeColumn(78)
  1041. # setup a margin to hold fold markers
  1042. self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
  1043. self.SetMarginMask(2, stc.STC_MASK_FOLDERS)
  1044. self.SetMarginSensitive(2, True)
  1045. self.SetMarginWidth(2, 12)
  1046. # like a flattened tree control using square headers
  1047. self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_BOXMINUS, "white", "#808080")
  1048. self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_BOXPLUS, "white", "#808080")
  1049. self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "#808080")
  1050. self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNER, "white", "#808080")
  1051. self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_BOXPLUSCONNECTED, "white", "#808080")
  1052. self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080")
  1053. self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNER, "white", "#808080")
  1054. self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI)
  1055. self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick)
  1056. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
  1057. # Make some styles, the lexer defines what each style is used
  1058. # for, we just have to define what each style looks like.
  1059. # This set is adapted from Scintilla sample property files.
  1060. # global default styles for all languages
  1061. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % self.faces)
  1062. self.StyleClearAll() # reset all to be like the default
  1063. # global default styles for all languages
  1064. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % self.faces)
  1065. self.StyleSetSpec(stc.STC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(helv)s,size:%(size2)d" % self.faces)
  1066. self.StyleSetSpec(stc.STC_STYLE_CONTROLCHAR, "face:%(other)s" % self.faces)
  1067. self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, "fore:#FFFFFF,back:#0000FF,bold")
  1068. self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold")
  1069. # Python styles
  1070. # Default
  1071. self.StyleSetSpec(stc.STC_P_DEFAULT, "fore:#000000,face:%(helv)s,size:%(size)d" % self.faces)
  1072. # Comments
  1073. self.StyleSetSpec(stc.STC_P_COMMENTLINE, "fore:#007F00,face:%(other)s,size:%(size)d" % self.faces)
  1074. # Number
  1075. self.StyleSetSpec(stc.STC_P_NUMBER, "fore:#007F7F,size:%(size)d" % self.faces)
  1076. # String
  1077. self.StyleSetSpec(stc.STC_P_STRING, "fore:#7F007F,face:%(helv)s,size:%(size)d" % self.faces)
  1078. # Single quoted string
  1079. self.StyleSetSpec(stc.STC_P_CHARACTER, "fore:#7F007F,face:%(helv)s,size:%(size)d" % self.faces)
  1080. # Keyword
  1081. self.StyleSetSpec(stc.STC_P_WORD, "fore:#00007F,bold,size:%(size)d" % self.faces)
  1082. # Triple quotes
  1083. self.StyleSetSpec(stc.STC_P_TRIPLE, "fore:#7F0000,size:%(size)d" % self.faces)
  1084. # Triple double quotes
  1085. self.StyleSetSpec(stc.STC_P_TRIPLEDOUBLE, "fore:#7F0000,size:%(size)d" % self.faces)
  1086. # Class name definition
  1087. self.StyleSetSpec(stc.STC_P_CLASSNAME, "fore:#0000FF,bold,underline,size:%(size)d" % self.faces)
  1088. # Function or method name definition
  1089. self.StyleSetSpec(stc.STC_P_DEFNAME, "fore:#007F7F,bold,size:%(size)d" % self.faces)
  1090. # Operators
  1091. self.StyleSetSpec(stc.STC_P_OPERATOR, "bold,size:%(size)d" % self.faces)
  1092. # Identifiers
  1093. self.StyleSetSpec(stc.STC_P_IDENTIFIER, "fore:#000000,face:%(helv)s,size:%(size)d" % self.faces)
  1094. # Comment-blocks
  1095. self.StyleSetSpec(stc.STC_P_COMMENTBLOCK, "fore:#7F7F7F,size:%(size)d" % self.faces)
  1096. # End of line where string is not closed
  1097. self.StyleSetSpec(stc.STC_P_STRINGEOL, "fore:#000000,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" % self.faces)
  1098. self.SetCaretForeground("BLUE")
  1099. def OnKeyPressed(self, event):
  1100. """!Key pressed
  1101. @todo implement code completion (see wxPython demo)
  1102. """
  1103. if not self.modified:
  1104. self.modified = True
  1105. if self.statusbar:
  1106. self.statusbar.SetStatusText(_('Python script contains local modifications'), 0)
  1107. event.Skip()
  1108. def OnUpdateUI(self, evt):
  1109. # check for matching braces
  1110. braceAtCaret = -1
  1111. braceOpposite = -1
  1112. charBefore = None
  1113. caretPos = self.GetCurrentPos()
  1114. if caretPos > 0:
  1115. charBefore = self.GetCharAt(caretPos - 1)
  1116. styleBefore = self.GetStyleAt(caretPos - 1)
  1117. # check before
  1118. if charBefore and chr(charBefore) in "[]{}()" and styleBefore == stc.STC_P_OPERATOR:
  1119. braceAtCaret = caretPos - 1
  1120. # check after
  1121. if braceAtCaret < 0:
  1122. charAfter = self.GetCharAt(caretPos)
  1123. styleAfter = self.GetStyleAt(caretPos)
  1124. if charAfter and chr(charAfter) in "[]{}()" and styleAfter == stc.STC_P_OPERATOR:
  1125. braceAtCaret = caretPos
  1126. if braceAtCaret >= 0:
  1127. braceOpposite = self.BraceMatch(braceAtCaret)
  1128. if braceAtCaret != -1 and braceOpposite == -1:
  1129. self.BraceBadLight(braceAtCaret)
  1130. else:
  1131. self.BraceHighlight(braceAtCaret, braceOpposite)
  1132. def OnMarginClick(self, evt):
  1133. # fold and unfold as needed
  1134. if evt.GetMargin() == 2:
  1135. if evt.GetShift() and evt.GetControl():
  1136. self.FoldAll()
  1137. else:
  1138. lineClicked = self.LineFromPosition(evt.GetPosition())
  1139. if self.GetFoldLevel(lineClicked) & stc.STC_FOLDLEVELHEADERFLAG:
  1140. if evt.GetShift():
  1141. self.SetFoldExpanded(lineClicked, True)
  1142. self.Expand(lineClicked, True, True, 1)
  1143. elif evt.GetControl():
  1144. if self.GetFoldExpanded(lineClicked):
  1145. self.SetFoldExpanded(lineClicked, False)
  1146. self.Expand(lineClicked, False, True, 0)
  1147. else:
  1148. self.SetFoldExpanded(lineClicked, True)
  1149. self.Expand(lineClicked, True, True, 100)
  1150. else:
  1151. self.ToggleFold(lineClicked)
  1152. def FoldAll(self):
  1153. lineCount = self.GetLineCount()
  1154. expanding = True
  1155. # find out if we are folding or unfolding
  1156. for lineNum in range(lineCount):
  1157. if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG:
  1158. expanding = not self.GetFoldExpanded(lineNum)
  1159. break
  1160. lineNum = 0
  1161. while lineNum < lineCount:
  1162. level = self.GetFoldLevel(lineNum)
  1163. if level & stc.STC_FOLDLEVELHEADERFLAG and \
  1164. (level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE:
  1165. if expanding:
  1166. self.SetFoldExpanded(lineNum, True)
  1167. lineNum = self.Expand(lineNum, True)
  1168. lineNum = lineNum - 1
  1169. else:
  1170. lastChild = self.GetLastChild(lineNum, -1)
  1171. self.SetFoldExpanded(lineNum, False)
  1172. if lastChild > lineNum:
  1173. self.HideLines(lineNum+1, lastChild)
  1174. lineNum = lineNum + 1
  1175. def Expand(self, line, doExpand, force=False, visLevels=0, level=-1):
  1176. lastChild = self.GetLastChild(line, level)
  1177. line = line + 1
  1178. while line <= lastChild:
  1179. if force:
  1180. if visLevels > 0:
  1181. self.ShowLines(line, line)
  1182. else:
  1183. self.HideLines(line, line)
  1184. else:
  1185. if doExpand:
  1186. self.ShowLines(line, line)
  1187. if level == -1:
  1188. level = self.GetFoldLevel(line)
  1189. if level & stc.STC_FOLDLEVELHEADERFLAG:
  1190. if force:
  1191. if visLevels > 1:
  1192. self.SetFoldExpanded(line, True)
  1193. else:
  1194. self.SetFoldExpanded(line, False)
  1195. line = self.Expand(line, doExpand, force, visLevels-1)
  1196. else:
  1197. if doExpand and self.GetFoldExpanded(line):
  1198. line = self.Expand(line, True, force, visLevels-1)
  1199. else:
  1200. line = self.Expand(line, False, force, visLevels-1)
  1201. else:
  1202. line = line + 1
  1203. return line