goutput.py 59 KB

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