goutput.py 58 KB

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