goutput.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  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, lmgr = self.parent).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, lmgr = self.parent).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. else:
  678. wx.CallAfter(self.btnCmdProtocol.SetValue, False)
  679. dlg.Destroy()
  680. event.Skip()
  681. def OnCmdAbort(self, event):
  682. """!Abort running command"""
  683. self.cmdThread.abort()
  684. def OnCmdRun(self, event):
  685. """!Run command"""
  686. if self.parent.GetName() == 'Modeler':
  687. self.parent.OnCmdRun(event)
  688. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  689. self.btnCmdAbort.Enable()
  690. def OnCmdPrepare(self, event):
  691. """!Prepare for running command"""
  692. if self.parent.GetName() == 'Modeler':
  693. self.parent.OnCmdPrepare(event)
  694. event.Skip()
  695. def OnCmdDone(self, event):
  696. """!Command done (or aborted)"""
  697. if self.parent.GetName() == 'Modeler':
  698. self.parent.OnCmdDone(event)
  699. # Process results here
  700. try:
  701. ctime = time.time() - event.time
  702. if ctime < 60:
  703. stime = _("%d sec") % int(ctime)
  704. else:
  705. mtime = int(ctime / 60)
  706. stime = _("%(min)d min %(sec)d sec") % { 'min' : mtime,
  707. 'sec' : int(ctime - (mtime * 60)) }
  708. except KeyError:
  709. # stopped deamon
  710. stime = _("unknown")
  711. if event.aborted:
  712. # Thread aborted (using our convention of None return)
  713. self.WriteLog(_('Please note that the data are left in inconsistent state '
  714. 'and may be corrupted'), self.cmdOutput.StyleWarning)
  715. msg = _('Command aborted')
  716. else:
  717. msg = _('Command finished')
  718. self.WriteCmdLog('(%s) %s (%s)' % (str(time.ctime()), msg, stime))
  719. self.btnCmdAbort.Enable(False)
  720. if event.onDone:
  721. event.onDone(cmd = event.cmd, returncode = event.returncode)
  722. self.progressbar.SetValue(0) # reset progress bar on '0%'
  723. self.cmdOutputTimer.Stop()
  724. if event.cmd[0] == 'g.gisenv':
  725. Debug.SetLevel()
  726. self.Redirect()
  727. if self.parent.GetName() == "LayerManager":
  728. self.btnCmdAbort.Enable(False)
  729. if event.cmd[0] not in globalvar.grassCmd or \
  730. event.cmd[0] == 'r.mapcalc':
  731. return
  732. display = self.parent.GetLayerTree().GetMapDisplay()
  733. if not display or not display.IsAutoRendered():
  734. return
  735. mapLayers = map(lambda x: x.GetName(),
  736. display.GetMap().GetListOfLayers(l_type = 'raster') +
  737. display.GetMap().GetListOfLayers(l_type = 'vector'))
  738. try:
  739. task = GUI(show = None).ParseCommand(event.cmd)
  740. except GException, e:
  741. print >> sys.stderr, e
  742. task = None
  743. return
  744. for p in task.get_options()['params']:
  745. if p.get('prompt', '') not in ('raster', 'vector'):
  746. continue
  747. mapName = p.get('value', '')
  748. if '@' not in mapName:
  749. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  750. if mapName in mapLayers:
  751. display.GetWindow().UpdateMap(render = True)
  752. return
  753. elif self.parent.GetName() == 'Modeler':
  754. pass
  755. else: # standalone dialogs
  756. dialog = self.parent.parent
  757. if hasattr(self.parent.parent, "btn_abort"):
  758. dialog.btn_abort.Enable(False)
  759. if hasattr(self.parent.parent, "btn_cancel"):
  760. dialog.btn_cancel.Enable(True)
  761. if hasattr(self.parent.parent, "btn_clipboard"):
  762. dialog.btn_clipboard.Enable(True)
  763. if hasattr(self.parent.parent, "btn_help"):
  764. dialog.btn_help.Enable(True)
  765. if hasattr(self.parent.parent, "btn_run"):
  766. dialog.btn_run.Enable(True)
  767. if event.returncode == 0 and not event.aborted:
  768. try:
  769. winName = self.parent.parent.parent.GetName()
  770. except AttributeError:
  771. winName = ''
  772. if winName == 'LayerManager':
  773. mapTree = self.parent.parent.parent.GetLayerTree()
  774. elif winName == 'LayerTree':
  775. mapTree = self.parent.parent.parent
  776. elif winName: # GMConsole
  777. mapTree = self.parent.parent.parent.parent.GetLayerTree()
  778. else:
  779. mapTree = None
  780. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  781. if hasattr(dialog, "addbox") and dialog.addbox.IsChecked():
  782. # add created maps into layer tree
  783. for p in dialog.task.get_options()['params']:
  784. prompt = p.get('prompt', '')
  785. if prompt in ('raster', 'vector', '3d-raster') and \
  786. p.get('age', 'old') == 'new' and \
  787. p.get('value', None):
  788. name, found = utils.GetLayerNameFromCmd(cmd, fullyQualified = True,
  789. param = p.get('name', ''))
  790. if mapTree.GetMap().GetListOfLayers(l_name = name):
  791. continue
  792. if prompt == 'raster':
  793. lcmd = ['d.rast',
  794. 'map=%s' % name]
  795. else:
  796. defaultParams = GetDisplayVectSettings()
  797. lcmd = ['d.vect',
  798. 'map=%s' % name] + defaultParams
  799. mapTree.AddLayer(ltype = prompt,
  800. lcmd = lcmd,
  801. lname = name)
  802. if hasattr(dialog, "get_dcmd") and \
  803. dialog.get_dcmd is None and \
  804. hasattr(dialog, "closebox") and \
  805. dialog.closebox.IsChecked() and \
  806. (event.returncode == 0 or event.aborted):
  807. self.cmdOutput.Update()
  808. time.sleep(2)
  809. dialog.Close()
  810. def OnProcessPendingOutputWindowEvents(self, event):
  811. self.ProcessPendingEvents()
  812. def ResetFocus(self):
  813. """!Reset focus"""
  814. self.cmdPrompt.SetFocus()
  815. class GMStdout:
  816. """!GMConsole standard output
  817. Based on FrameOutErr.py
  818. Name: FrameOutErr.py
  819. Purpose: Redirecting stdout / stderr
  820. Author: Jean-Michel Fauth, Switzerland
  821. Copyright: (c) 2005-2007 Jean-Michel Fauth
  822. Licence: GPL
  823. """
  824. def __init__(self, parent):
  825. self.parent = parent # GMConsole
  826. def write(self, s):
  827. if len(s) == 0 or s == '\n':
  828. return
  829. for line in s.splitlines():
  830. if len(line) == 0:
  831. continue
  832. evt = wxCmdOutput(text = line + '\n',
  833. type = '')
  834. wx.PostEvent(self.parent.cmdOutput, evt)
  835. class GMStderr:
  836. """!GMConsole standard error output
  837. Based on FrameOutErr.py
  838. Name: FrameOutErr.py
  839. Purpose: Redirecting stdout / stderr
  840. Author: Jean-Michel Fauth, Switzerland
  841. Copyright: (c) 2005-2007 Jean-Michel Fauth
  842. Licence: GPL
  843. """
  844. def __init__(self, parent):
  845. self.parent = parent # GMConsole
  846. self.type = ''
  847. self.message = ''
  848. self.printMessage = False
  849. def flush(self):
  850. pass
  851. def write(self, s):
  852. if "GtkPizza" in s:
  853. return
  854. # remove/replace escape sequences '\b' or '\r' from stream
  855. progressValue = -1
  856. for line in s.splitlines():
  857. if len(line) == 0:
  858. continue
  859. if 'GRASS_INFO_PERCENT' in line:
  860. value = int(line.rsplit(':', 1)[1].strip())
  861. if value >= 0 and value < 100:
  862. progressValue = value
  863. else:
  864. progressValue = 0
  865. elif 'GRASS_INFO_MESSAGE' in line:
  866. self.type = 'message'
  867. self.message += line.split(':', 1)[1].strip() + '\n'
  868. elif 'GRASS_INFO_WARNING' in line:
  869. self.type = 'warning'
  870. self.message += line.split(':', 1)[1].strip() + '\n'
  871. elif 'GRASS_INFO_ERROR' in line:
  872. self.type = 'error'
  873. self.message += line.split(':', 1)[1].strip() + '\n'
  874. elif 'GRASS_INFO_END' in line:
  875. self.printMessage = True
  876. elif self.type == '':
  877. if len(line) == 0:
  878. continue
  879. evt = wxCmdOutput(text = line,
  880. type = '')
  881. wx.PostEvent(self.parent.cmdOutput, evt)
  882. elif len(line) > 0:
  883. self.message += line.strip() + '\n'
  884. if self.printMessage and len(self.message) > 0:
  885. evt = wxCmdOutput(text = self.message,
  886. type = self.type)
  887. wx.PostEvent(self.parent.cmdOutput, evt)
  888. self.type = ''
  889. self.message = ''
  890. self.printMessage = False
  891. # update progress message
  892. if progressValue > -1:
  893. # self.gmgauge.SetValue(progressValue)
  894. evt = wxCmdProgress(value = progressValue)
  895. wx.PostEvent(self.parent.progressbar, evt)
  896. class GMStc(stc.StyledTextCtrl):
  897. """!Styled GMConsole
  898. Based on FrameOutErr.py
  899. Name: FrameOutErr.py
  900. Purpose: Redirecting stdout / stderr
  901. Author: Jean-Michel Fauth, Switzerland
  902. Copyright: (c) 2005-2007 Jean-Michel Fauth
  903. Licence: GPL
  904. """
  905. def __init__(self, parent, id, margin = False, wrap = None):
  906. stc.StyledTextCtrl.__init__(self, parent, id)
  907. self.parent = parent
  908. self.SetUndoCollection(True)
  909. self.SetReadOnly(True)
  910. #
  911. # styles
  912. #
  913. self.SetStyle()
  914. #
  915. # line margins
  916. #
  917. # TODO print number only from cmdlog
  918. self.SetMarginWidth(1, 0)
  919. self.SetMarginWidth(2, 0)
  920. if margin:
  921. self.SetMarginType(0, stc.STC_MARGIN_NUMBER)
  922. self.SetMarginWidth(0, 30)
  923. else:
  924. self.SetMarginWidth(0, 0)
  925. #
  926. # miscellaneous
  927. #
  928. self.SetViewWhiteSpace(False)
  929. self.SetTabWidth(4)
  930. self.SetUseTabs(False)
  931. self.UsePopUp(True)
  932. self.SetSelBackground(True, "#FFFF00")
  933. self.SetUseHorizontalScrollBar(True)
  934. #
  935. # bindings
  936. #
  937. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  938. def OnTextSelectionChanged(self, event):
  939. """!Copy selected text to clipboard and skip event.
  940. The same function is in TextCtrlAutoComplete class (prompt.py).
  941. """
  942. wx.CallAfter(self.Copy)
  943. event.Skip()
  944. def SetStyle(self):
  945. """!Set styles for styled text output windows with type face
  946. and point size selected by user (Courier New 10 is default)"""
  947. settings = Settings()
  948. typeface = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'type')
  949. if typeface == "":
  950. typeface = "Courier New"
  951. typesize = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'size')
  952. if typesize == None or typesize <= 0:
  953. typesize = 10
  954. typesize = float(typesize)
  955. self.StyleDefault = 0
  956. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  957. self.StyleCommand = 1
  958. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  959. self.StyleOutput = 2
  960. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  961. # fatal error
  962. self.StyleError = 3
  963. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  964. # warning
  965. self.StyleWarning = 4
  966. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  967. # message
  968. self.StyleMessage = 5
  969. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  970. # unknown
  971. self.StyleUnknown = 6
  972. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  973. # default and clear => init
  974. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  975. self.StyleClearAll()
  976. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  977. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  978. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  979. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  980. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  981. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  982. def OnDestroy(self, evt):
  983. """!The clipboard contents can be preserved after
  984. the app has exited"""
  985. wx.TheClipboard.Flush()
  986. evt.Skip()
  987. def AddTextWrapped(self, txt, wrap = None):
  988. """!Add string to text area.
  989. String is wrapped and linesep is also added to the end
  990. of the string"""
  991. # allow writing to output window
  992. self.SetReadOnly(False)
  993. if wrap:
  994. txt = textwrap.fill(txt, wrap) + '\n'
  995. else:
  996. if txt[-1] != '\n':
  997. txt += '\n'
  998. if '\r' in txt:
  999. self.parent.linePos = -1
  1000. for seg in txt.split('\r'):
  1001. if self.parent.linePos > -1:
  1002. self.SetCurrentPos(self.parent.linePos)
  1003. self.ReplaceSelection(seg)
  1004. else:
  1005. self.parent.linePos = self.GetCurrentPos()
  1006. self.AddText(seg)
  1007. else:
  1008. self.parent.linePos = self.GetCurrentPos()
  1009. try:
  1010. self.AddText(txt)
  1011. except UnicodeDecodeError:
  1012. enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
  1013. if enc:
  1014. txt = unicode(txt, enc)
  1015. elif 'GRASS_DB_ENCODING' in os.environ:
  1016. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  1017. else:
  1018. txt = EncodeString(txt)
  1019. self.AddText(txt)
  1020. # reset output window to read only
  1021. self.SetReadOnly(True)
  1022. class PyStc(stc.StyledTextCtrl):
  1023. """!Styled Python output (see gmodeler::frame::PythonPanel for
  1024. usage)
  1025. Based on StyledTextCtrl_2 from wxPython demo
  1026. """
  1027. def __init__(self, parent, id = wx.ID_ANY, statusbar = None):
  1028. stc.StyledTextCtrl.__init__(self, parent, id)
  1029. self.parent = parent
  1030. self.statusbar = statusbar
  1031. self.modified = False # content modified ?
  1032. self.faces = { 'times': 'Times New Roman',
  1033. 'mono' : 'Courier New',
  1034. 'helv' : 'Arial',
  1035. 'other': 'Comic Sans MS',
  1036. 'size' : 10,
  1037. 'size2': 8,
  1038. }
  1039. self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN)
  1040. self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT)
  1041. self.SetLexer(stc.STC_LEX_PYTHON)
  1042. self.SetKeyWords(0, " ".join(keyword.kwlist))
  1043. self.SetProperty("fold", "1")
  1044. self.SetProperty("tab.timmy.whinge.level", "1")
  1045. self.SetMargins(0, 0)
  1046. self.SetTabWidth(4)
  1047. self.SetUseTabs(False)
  1048. self.SetEdgeMode(stc.STC_EDGE_BACKGROUND)
  1049. self.SetEdgeColumn(78)
  1050. # setup a margin to hold fold markers
  1051. self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
  1052. self.SetMarginMask(2, stc.STC_MASK_FOLDERS)
  1053. self.SetMarginSensitive(2, True)
  1054. self.SetMarginWidth(2, 12)
  1055. # like a flattened tree control using square headers
  1056. self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_BOXMINUS, "white", "#808080")
  1057. self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_BOXPLUS, "white", "#808080")
  1058. self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "#808080")
  1059. self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNER, "white", "#808080")
  1060. self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_BOXPLUSCONNECTED, "white", "#808080")
  1061. self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080")
  1062. self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNER, "white", "#808080")
  1063. self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI)
  1064. self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick)
  1065. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
  1066. # Make some styles, the lexer defines what each style is used
  1067. # for, we just have to define what each style looks like.
  1068. # This set is adapted from Scintilla sample property files.
  1069. # global default styles for all languages
  1070. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % self.faces)
  1071. self.StyleClearAll() # reset all to be like the default
  1072. # global default styles for all languages
  1073. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % self.faces)
  1074. self.StyleSetSpec(stc.STC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(helv)s,size:%(size2)d" % self.faces)
  1075. self.StyleSetSpec(stc.STC_STYLE_CONTROLCHAR, "face:%(other)s" % self.faces)
  1076. self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, "fore:#FFFFFF,back:#0000FF,bold")
  1077. self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold")
  1078. # Python styles
  1079. # Default
  1080. self.StyleSetSpec(stc.STC_P_DEFAULT, "fore:#000000,face:%(helv)s,size:%(size)d" % self.faces)
  1081. # Comments
  1082. self.StyleSetSpec(stc.STC_P_COMMENTLINE, "fore:#007F00,face:%(other)s,size:%(size)d" % self.faces)
  1083. # Number
  1084. self.StyleSetSpec(stc.STC_P_NUMBER, "fore:#007F7F,size:%(size)d" % self.faces)
  1085. # String
  1086. self.StyleSetSpec(stc.STC_P_STRING, "fore:#7F007F,face:%(helv)s,size:%(size)d" % self.faces)
  1087. # Single quoted string
  1088. self.StyleSetSpec(stc.STC_P_CHARACTER, "fore:#7F007F,face:%(helv)s,size:%(size)d" % self.faces)
  1089. # Keyword
  1090. self.StyleSetSpec(stc.STC_P_WORD, "fore:#00007F,bold,size:%(size)d" % self.faces)
  1091. # Triple quotes
  1092. self.StyleSetSpec(stc.STC_P_TRIPLE, "fore:#7F0000,size:%(size)d" % self.faces)
  1093. # Triple double quotes
  1094. self.StyleSetSpec(stc.STC_P_TRIPLEDOUBLE, "fore:#7F0000,size:%(size)d" % self.faces)
  1095. # Class name definition
  1096. self.StyleSetSpec(stc.STC_P_CLASSNAME, "fore:#0000FF,bold,underline,size:%(size)d" % self.faces)
  1097. # Function or method name definition
  1098. self.StyleSetSpec(stc.STC_P_DEFNAME, "fore:#007F7F,bold,size:%(size)d" % self.faces)
  1099. # Operators
  1100. self.StyleSetSpec(stc.STC_P_OPERATOR, "bold,size:%(size)d" % self.faces)
  1101. # Identifiers
  1102. self.StyleSetSpec(stc.STC_P_IDENTIFIER, "fore:#000000,face:%(helv)s,size:%(size)d" % self.faces)
  1103. # Comment-blocks
  1104. self.StyleSetSpec(stc.STC_P_COMMENTBLOCK, "fore:#7F7F7F,size:%(size)d" % self.faces)
  1105. # End of line where string is not closed
  1106. self.StyleSetSpec(stc.STC_P_STRINGEOL, "fore:#000000,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" % self.faces)
  1107. self.SetCaretForeground("BLUE")
  1108. def OnKeyPressed(self, event):
  1109. """!Key pressed
  1110. @todo implement code completion (see wxPython demo)
  1111. """
  1112. if not self.modified:
  1113. self.modified = True
  1114. if self.statusbar:
  1115. self.statusbar.SetStatusText(_('Python script contains local modifications'), 0)
  1116. event.Skip()
  1117. def OnUpdateUI(self, evt):
  1118. # check for matching braces
  1119. braceAtCaret = -1
  1120. braceOpposite = -1
  1121. charBefore = None
  1122. caretPos = self.GetCurrentPos()
  1123. if caretPos > 0:
  1124. charBefore = self.GetCharAt(caretPos - 1)
  1125. styleBefore = self.GetStyleAt(caretPos - 1)
  1126. # check before
  1127. if charBefore and chr(charBefore) in "[]{}()" and styleBefore == stc.STC_P_OPERATOR:
  1128. braceAtCaret = caretPos - 1
  1129. # check after
  1130. if braceAtCaret < 0:
  1131. charAfter = self.GetCharAt(caretPos)
  1132. styleAfter = self.GetStyleAt(caretPos)
  1133. if charAfter and chr(charAfter) in "[]{}()" and styleAfter == stc.STC_P_OPERATOR:
  1134. braceAtCaret = caretPos
  1135. if braceAtCaret >= 0:
  1136. braceOpposite = self.BraceMatch(braceAtCaret)
  1137. if braceAtCaret != -1 and braceOpposite == -1:
  1138. self.BraceBadLight(braceAtCaret)
  1139. else:
  1140. self.BraceHighlight(braceAtCaret, braceOpposite)
  1141. def OnMarginClick(self, evt):
  1142. # fold and unfold as needed
  1143. if evt.GetMargin() == 2:
  1144. if evt.GetShift() and evt.GetControl():
  1145. self.FoldAll()
  1146. else:
  1147. lineClicked = self.LineFromPosition(evt.GetPosition())
  1148. if self.GetFoldLevel(lineClicked) & stc.STC_FOLDLEVELHEADERFLAG:
  1149. if evt.GetShift():
  1150. self.SetFoldExpanded(lineClicked, True)
  1151. self.Expand(lineClicked, True, True, 1)
  1152. elif evt.GetControl():
  1153. if self.GetFoldExpanded(lineClicked):
  1154. self.SetFoldExpanded(lineClicked, False)
  1155. self.Expand(lineClicked, False, True, 0)
  1156. else:
  1157. self.SetFoldExpanded(lineClicked, True)
  1158. self.Expand(lineClicked, True, True, 100)
  1159. else:
  1160. self.ToggleFold(lineClicked)
  1161. def FoldAll(self):
  1162. lineCount = self.GetLineCount()
  1163. expanding = True
  1164. # find out if we are folding or unfolding
  1165. for lineNum in range(lineCount):
  1166. if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG:
  1167. expanding = not self.GetFoldExpanded(lineNum)
  1168. break
  1169. lineNum = 0
  1170. while lineNum < lineCount:
  1171. level = self.GetFoldLevel(lineNum)
  1172. if level & stc.STC_FOLDLEVELHEADERFLAG and \
  1173. (level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE:
  1174. if expanding:
  1175. self.SetFoldExpanded(lineNum, True)
  1176. lineNum = self.Expand(lineNum, True)
  1177. lineNum = lineNum - 1
  1178. else:
  1179. lastChild = self.GetLastChild(lineNum, -1)
  1180. self.SetFoldExpanded(lineNum, False)
  1181. if lastChild > lineNum:
  1182. self.HideLines(lineNum+1, lastChild)
  1183. lineNum = lineNum + 1
  1184. def Expand(self, line, doExpand, force=False, visLevels=0, level=-1):
  1185. lastChild = self.GetLastChild(line, level)
  1186. line = line + 1
  1187. while line <= lastChild:
  1188. if force:
  1189. if visLevels > 0:
  1190. self.ShowLines(line, line)
  1191. else:
  1192. self.HideLines(line, line)
  1193. else:
  1194. if doExpand:
  1195. self.ShowLines(line, line)
  1196. if level == -1:
  1197. level = self.GetFoldLevel(line)
  1198. if level & stc.STC_FOLDLEVELHEADERFLAG:
  1199. if force:
  1200. if visLevels > 1:
  1201. self.SetFoldExpanded(line, True)
  1202. else:
  1203. self.SetFoldExpanded(line, False)
  1204. line = self.Expand(line, doExpand, force, visLevels-1)
  1205. else:
  1206. if doExpand and self.GetFoldExpanded(line):
  1207. line = self.Expand(line, True, force, visLevels-1)
  1208. else:
  1209. line = self.Expand(line, False, force, visLevels-1)
  1210. else:
  1211. line = line + 1
  1212. return line