goutput.py 58 KB

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