/// <summary> /// Creates a new Python REPL window which is independent from the /// default Python REPL windows. /// /// This window will not persist across VS sessions. /// </summary> /// <param name="id">An ID which can be used to retrieve the window again and can survive across VS sessions. /// /// The ID cannot include the | character.</param> /// <param name="title">The title of the window to be displayed</param> /// <param name="interpreter">The interpreter to be used. This implies the language version and provides the path to the Python interpreter to be used.</param> /// <param name="startupFile">The file to be executed on the startup of the REPL. Can be null, which will result in an interactive REPL.</param> /// <param name="workingDir">The working directory of the REPL process</param> /// <param name="project">The IVsHierarchy representing the Python project.</param> public IReplWindow CreatePythonRepl(string id, string title, IPythonInterpreterFactory interpreter, string workingDir, Dictionary <string, string> envVars = null, IVsHierarchy project = null) { Utilities.ArgumentNotNull("interpreter", interpreter); Utilities.ArgumentNotNull("id", id); Utilities.ArgumentNotNull("title", title); // The previous format of repl ID would produce new windows for // distinct working directories and/or env vars. To emulate this, // we now put all of these values into the user ID part, even though // they must still be manually provided after the evaluator is // created. var realId = string.Format( "{0};{1};{2}", id, workingDir ?? "", envVars == null ? "" : string.Join(";", envVars.Select(kvp => kvp.Key + "=" + kvp.Value)) ); string replId = PythonReplEvaluatorProvider.GetConfigurableReplId(realId); #if DEV14_OR_LATER var replProvider = ComponentModel.GetService <InteractiveWindowProvider>(); var vsWindow = #else var replProvider = ComponentModel.GetService <IReplWindowProvider>(); var window = #endif replProvider.FindReplWindow(replId) ?? replProvider.CreateReplWindow( this.GetPythonContentType(), title, typeof(PythonLanguageInfo).GUID, replId ); #if DEV14_OR_LATER var window = vsWindow.InteractiveWindow; #endif var commandProvider = project as IPythonProject2; if (commandProvider != null) { commandProvider.AddActionOnClose((object)window, BasePythonReplEvaluator.CloseReplWindow); } var evaluator = window.Evaluator as BasePythonReplEvaluator; var options = (evaluator != null) ? evaluator.CurrentOptions as ConfigurablePythonReplOptions : null; if (options == null) { throw new NotSupportedException("Cannot modify options of " + window.Evaluator.GetType().FullName); } options.InterpreterFactory = interpreter; options.Project = project as PythonProjectNode; options._workingDir = workingDir; options._envVars = new Dictionary <string, string>(envVars); evaluator.Reset(quiet: true) .HandleAllExceptions(SR.ProductName, GetType()) .DoNotWait(); return(window); }
void IVsPython.OpenInteractive(string description) { var compModel = _pyService.ComponentModel; if (compModel == null) { throw new InvalidOperationException("Could not activate component model"); } var provider = compModel.GetService <InteractiveWindowProvider>(); var interpreters = compModel.GetService <IInterpreterRegistryService>(); var factory = interpreters.Configurations.FirstOrDefault( f => f.Description.Equals(description, StringComparison.CurrentCultureIgnoreCase) ); if (factory == null) { throw new KeyNotFoundException("Could not create interactive window with name: " + description); } var window = provider.OpenOrCreate( PythonReplEvaluatorProvider.GetEvaluatorId(factory) ); if (window == null) { throw new InvalidOperationException("Could not create interactive window"); } window.Show(true); }
internal static IReplWindow /*!*/ EnsureReplWindow(IServiceProvider serviceProvider, IPythonInterpreterFactory factory, PythonProjectNode project) { var compModel = serviceProvider.GetComponentModel(); var provider = compModel.GetService <IReplWindowProvider>(); string replId = PythonReplEvaluatorProvider.GetReplId(factory, project); var window = provider.FindReplWindow(replId); if (window == null) { window = provider.CreateReplWindow( serviceProvider.GetPythonContentType(), factory.Description + " Interactive", typeof(PythonLanguageInfo).GUID, replId ); var pyService = serviceProvider.GetPythonToolsService(); window.SetOptionValue( ReplOptions.UseSmartUpDown, pyService.GetInteractiveOptions(factory).ReplSmartHistory ); } if (project != null && project.Interpreters.IsProjectSpecific(factory)) { project.AddActionOnClose(window, BasePythonReplEvaluator.CloseReplWindow); } return(window); }
private void OpenInteractiveWindow_Executed(object sender, ExecutedRoutedEventArgs e) { var view = (EnvironmentView)e.Parameter; var config = view.Factory.Configuration; var replId = PythonReplEvaluatorProvider.GetEvaluatorId(config); var compModel = _site.GetComponentModel(); var service = compModel.GetService <InteractiveWindowProvider>(); IVsInteractiveWindow window; // TODO: Figure out another way to get the project //var provider = _service.KnownProviders.OfType<LoadedProjectInterpreterFactoryProvider>().FirstOrDefault(); //var vsProject = provider == null ? // null : // provider.GetProject(factory); //PythonProjectNode project = vsProject == null ? null : vsProject.GetPythonProject(); try { window = service.OpenOrCreate(replId); } catch (Exception ex) when(!ex.IsCriticalException()) { TaskDialog.ForException(_site, ex, Strings.ErrorOpeningInteractiveWindow, PythonConstants.IssueTrackerUrl).ShowModal(); return; } window?.Show(true); }
internal static IVsInteractiveWindow /*!*/ EnsureReplWindow(IServiceProvider serviceProvider, InterpreterConfiguration config, PythonProjectNode project) { var compModel = serviceProvider.GetComponentModel(); var provider = compModel.GetService <InteractiveWindowProvider>(); var vsProjectContext = compModel.GetService <VsProjectContextProvider>(); var projectId = project != null?PythonReplEvaluatorProvider.GetEvaluatorId(project) : null; var configId = config != null?PythonReplEvaluatorProvider.GetEvaluatorId(config) : null; if (config?.IsRunnable() == false) { throw new MissingInterpreterException( Strings.MissingEnvironment.FormatUI(config.Description, config.Version) ); } IVsInteractiveWindow window; // If we find an open window for the project, prefer that to a per-config one if (!string.IsNullOrEmpty(projectId)) { window = provider.Open( projectId, e => ((e as SelectableReplEvaluator)?.Evaluator as PythonCommonInteractiveEvaluator)?.AssociatedProjectHasChanged != true ); if (window != null) { return(window); } } // If we find an open window for the configuration, return that if (!string.IsNullOrEmpty(configId)) { window = provider.Open(configId); if (window != null) { return(window); } } // No window found, so let's create one if (!string.IsNullOrEmpty(projectId)) { window = provider.Create(projectId); project.AddActionOnClose(window, w => InteractiveWindowProvider.CloseIfEvaluatorMatches(w, projectId)); } else if (!string.IsNullOrEmpty(configId)) { window = provider.Create(configId); } else { var interpService = compModel.GetService <IInterpreterOptionsService>(); window = provider.Create(PythonReplEvaluatorProvider.GetEvaluatorId(interpService.DefaultInterpreter.Configuration)); } return(window); }
internal static IVsInteractiveWindow /*!*/ EnsureReplWindow(IServiceProvider serviceProvider, InterpreterConfiguration config, PythonProjectNode project) { var compModel = serviceProvider.GetComponentModel(); var provider = compModel.GetService <InteractiveWindowProvider>(); var vsProjectContext = compModel.GetService <VsProjectContextProvider>(); var projectId = project != null?PythonReplEvaluatorProvider.GetEvaluatorId(project) : null; var configId = config != null?PythonReplEvaluatorProvider.GetEvaluatorId(config) : null; IVsInteractiveWindow window; // If we find an open window for the project, prefer that to a per-config one if (!string.IsNullOrEmpty(projectId)) { window = provider.Open(projectId); if (window != null) { if (window.InteractiveWindow.GetPythonEvaluator()?.AssociatedProjectHasChanged == true) { // We have an existing window, but it needs to be reset. // Let's create a new one window = provider.Create(projectId); project.AddActionOnClose(window, w => InteractiveWindowProvider.CloseIfEvaluatorMatches(w, projectId)); } return(window); } } // If we find an open window for the configuration, return that if (!string.IsNullOrEmpty(configId)) { window = provider.Open(configId); if (window != null) { return(window); } } // No window found, so let's create one if (!string.IsNullOrEmpty(projectId)) { window = provider.Create(projectId); project.AddActionOnClose(window, w => InteractiveWindowProvider.CloseIfEvaluatorMatches(w, projectId)); } else if (!string.IsNullOrEmpty(configId)) { window = provider.Create(configId); } else { var interpService = compModel.GetService <IInterpreterOptionsService>(); window = provider.Create(PythonReplEvaluatorProvider.GetEvaluatorId(interpService.DefaultInterpreter.Configuration)); } return(window); }
public override ToolWindowPane ActivateInteractiveWindow(VisualStudioApp app, string executionMode) { string description = null; if (Version.IsCPython) { description = string.Format("{0} {1}", Version.Isx64 ? "Python 64-bit" : "Python 32-bit", Version.Version.ToVersion() ); } else if (Version.IsIronPython) { description = string.Format("{0} {1}", Version.Isx64 ? "IronPython 64-bit" : "IronPython", Version.Version.ToVersion() ); } Assert.IsNotNull(description, "Unknown interpreter"); var automation = (IVsPython)app.Dte.GetObject("VsPython"); var options = (IPythonOptions)automation; var replOptions = options.Interactive; Assert.IsNotNull(replOptions, "Could not find options for " + description); var oldAddNewLineAtEndOfFullyTypedWord = options.Intellisense.AddNewLineAtEndOfFullyTypedWord; app.OnDispose(() => options.Intellisense.AddNewLineAtEndOfFullyTypedWord = oldAddNewLineAtEndOfFullyTypedWord); options.Intellisense.AddNewLineAtEndOfFullyTypedWord = AddNewLineAtEndOfFullyTypedWord; bool success = false; for (int retries = 1; retries < 20; ++retries) { try { app.ExecuteCommand("Python.Interactive", "/e:\"" + description + "\""); success = true; break; } catch (AggregateException) { } app.DismissAllDialogs(); app.SetFocus(); Thread.Sleep(retries * 100); } Assert.IsTrue(success, "Unable to open " + description + " through DTE"); var interpreters = app.ComponentModel.GetService <IInterpreterRegistryService>(); var replId = PythonReplEvaluatorProvider.GetEvaluatorId( interpreters.FindConfiguration(Version.Id) ); return(app.ServiceProvider.GetUIThread().Invoke(() => { var provider = app.ComponentModel.GetService <InteractiveWindowProvider>(); return (ToolWindowPane)provider.OpenOrCreate(replId); })); }
private static ToolWindowPane ActivateInteractiveWindow(ReplWindowProxySettings settings, VisualStudioApp app, string projectName, string workspaceName, string backend) { string description = null; if (settings.Version.IsCPython) { description = string.Format("{0} {1}", settings.Version.Isx64 ? "Python 64-bit" : "Python 32-bit", settings.Version.Version.ToVersion() ); } else if (settings.Version.IsIronPython) { description = string.Format("{0} {1}", settings.Version.Isx64 ? "IronPython 64-bit" : "IronPython", settings.Version.Version.ToVersion() ); } Assert.IsNotNull(description, "Unknown interpreter"); var automation = (IVsPython)app.Dte.GetObject("VsPython"); var options = (IPythonOptions)automation; var replOptions = options.Interactive; Assert.IsNotNull(replOptions, "Could not find options for " + description); var oldAddNewLineAtEndOfFullyTypedWord = options.Intellisense.AddNewLineAtEndOfFullyTypedWord; app.OnDispose(() => options.Intellisense.AddNewLineAtEndOfFullyTypedWord = oldAddNewLineAtEndOfFullyTypedWord); options.Intellisense.AddNewLineAtEndOfFullyTypedWord = settings.AddNewLineAtEndOfFullyTypedWord; var interpreters = app.ComponentModel.GetService <IInterpreterRegistryService>(); var replId = PythonReplEvaluatorProvider.GetEvaluatorId( interpreters.FindConfiguration(settings.Version.Id) ); if (!string.IsNullOrEmpty(projectName)) { var dteProj = app.GetProject(projectName); var proj = (PythonProjectNode)dteProj.GetCommonProject(); replId = PythonReplEvaluatorProvider.GetEvaluatorId(proj); } else if (!string.IsNullOrEmpty(workspaceName)) { var workspaceContextProvider = app.ComponentModel.GetService <IPythonWorkspaceContextProvider>(); replId = PythonReplEvaluatorProvider.GetEvaluatorId(workspaceContextProvider.Workspace); } return(app.ServiceProvider.GetUIThread().Invoke(() => { app.ServiceProvider.GetPythonToolsService().InteractiveBackendOverride = backend; var provider = app.ComponentModel.GetService <InteractiveWindowProvider>(); return (ToolWindowPane)provider.OpenOrCreate(replId); })); }
internal static IVsInteractiveWindow /*!*/ EnsureReplWindow(IServiceProvider serviceProvider, InterpreterConfiguration config, PythonProjectNode project) { var compModel = serviceProvider.GetComponentModel(); var provider = compModel.GetService <InteractiveWindowProvider>(); var vsProjectContext = compModel.GetService <VsProjectContextProvider>(); string replId = config != null? PythonReplEvaluatorProvider.GetEvaluatorId(config) : PythonReplEvaluatorProvider.GetEvaluatorId(project); var window = provider.OpenOrCreate(replId); project?.AddActionOnClose(window, InteractiveWindowProvider.Close); return(window); }
public override ToolWindowPane ActivateInteractiveWindow(VisualStudioApp app, string executionMode) { string description = null; if (Version.IsCPython) { description = string.Format("{0} {1}", Version.Isx64 ? "Python 64-bit" : "Python 32-bit", Version.Version.ToVersion() ); } else if (Version.IsIronPython) { description = string.Format("{0} {1}", Version.Isx64 ? "IronPython 64-bit" : "IronPython", Version.Version.ToVersion() ); } Assert.IsNotNull(description, "Unknown interpreter"); var automation = (IVsPython)app.Dte.GetObject("VsPython"); var options = (IPythonOptions)automation; var replOptions = options.Interactive; Assert.IsNotNull(replOptions, "Could not find options for " + description); var oldAddNewLineAtEndOfFullyTypedWord = options.Intellisense.AddNewLineAtEndOfFullyTypedWord; app.OnDispose(() => options.Intellisense.AddNewLineAtEndOfFullyTypedWord = oldAddNewLineAtEndOfFullyTypedWord); options.Intellisense.AddNewLineAtEndOfFullyTypedWord = AddNewLineAtEndOfFullyTypedWord; var interpreters = app.ComponentModel.GetService <IInterpreterRegistryService>(); var replId = PythonReplEvaluatorProvider.GetEvaluatorId( interpreters.FindConfiguration(Version.Id) ); return(app.ServiceProvider.GetUIThread().Invoke(() => { var provider = app.ComponentModel.GetService <InteractiveWindowProvider>(); return (ToolWindowPane)provider.OpenOrCreate(replId); })); }
internal static IReplWindow /*!*/ EnsureReplWindow(IPythonInterpreterFactory factory) { var compModel = PythonToolsPackage.ComponentModel; var provider = compModel.GetExtensions <IReplWindowProvider>().First(); string replId = PythonReplEvaluatorProvider.GetReplId(factory); var window = provider.FindReplWindow(replId); if (window == null) { window = provider.CreateReplWindow( PythonToolsPackage.Instance.ContentType, factory.GetInterpreterDisplay() + " Interactive", typeof(PythonLanguageInfo).GUID, replId ); window.SetOptionValue(ReplOptions.UseSmartUpDown, PythonToolsPackage.Instance.InteractiveOptionsPage.GetOptions(factory).ReplSmartHistory); } return(window); }
internal static IVsInteractiveWindow /*!*/ EnsureReplWindow(IServiceProvider serviceProvider, InterpreterConfiguration config, PythonProjectNode project) { var compModel = serviceProvider.GetComponentModel(); var provider = compModel.GetService <InteractiveWindowProvider>(); var vsProjectContext = compModel.GetService <VsProjectContextProvider>(); string replId = PythonReplEvaluatorProvider.GetReplId(config.Id, project); var window = provider.FindReplWindow(replId); if (window == null) { window = provider.CreateInteractiveWindow( serviceProvider.GetPythonContentType(), config.FullDescription + " Interactive", typeof(PythonLanguageInfo).GUID, replId ); #if DEV14 var toolWindow = window as ToolWindowPane; if (toolWindow != null) { toolWindow.BitmapImageMoniker = KnownMonikers.PYInteractiveWindow; } #endif var pyService = serviceProvider.GetPythonToolsService(); window.InteractiveWindow.SetSmartUpDown(pyService.GetInteractiveOptions(config).ReplSmartHistory); } if (project != null && vsProjectContext.IsProjectSpecific(config)) { project.AddActionOnClose(window, BasePythonReplEvaluator.CloseReplWindow); } return(window); }
internal static IReplWindowToolWindow /*!*/ EnsureReplWindow(IServiceProvider serviceProvider, IPythonInterpreterFactory factory, PythonProjectNode project) { var compModel = serviceProvider.GetComponentModel(); var provider = compModel.GetService <IReplWindowProvider>(); string replId = PythonReplEvaluatorProvider.GetReplId(factory, project); var window = provider.FindReplWindow(replId); if (window == null) { window = provider.CreateReplWindow( serviceProvider.GetPythonContentType(), factory.Description + " Interactive", typeof(PythonLanguageInfo).GUID, replId ); var toolWindow = window as ToolWindowPane; if (toolWindow != null) { #if DEV14_OR_LATER toolWindow.BitmapImageMoniker = KnownMonikers.PYInteractiveWindow; #else // TODO: Add image here for VS 2013 #endif } var pyService = serviceProvider.GetPythonToolsService(); window.SetSmartUpDown(pyService.GetInteractiveOptions(factory).ReplSmartHistory); } if (project != null && project.Interpreters.IsProjectSpecific(factory)) { project.AddActionOnClose(window, BasePythonReplEvaluator.CloseReplWindow); } return(window); }
private async Task <bool> RunInRepl(IPythonProject2 project, CommandStartInfo startInfo) { var executeIn = string.IsNullOrEmpty(startInfo.ExecuteIn) ? CreatePythonCommandItem.ExecuteInRepl : startInfo.ExecuteIn; bool resetRepl = executeIn.StartsWith("R", StringComparison.InvariantCulture); var replTitle = executeIn.Substring(4).TrimStart(' ', ':'); if (string.IsNullOrEmpty(replTitle)) { replTitle = SR.GetString(SR.CustomCommandReplTitle, DisplayLabelWithoutAccessKeys); } else { var match = _customCommandLabelRegex.Match(replTitle); if (match.Success) { replTitle = LoadResourceFromAssembly( match.Groups["assembly"].Value, match.Groups["namespace"].Value, match.Groups["key"].Value ); } } replTitle = PerformSubstitutions(project, replTitle); var replWindowId = PythonReplEvaluatorProvider.GetConfigurableReplId(ReplId + executeIn.Substring(4)); var model = _project.Site.GetComponentModel(); var replProvider = model.GetService <IReplWindowProvider>(); if (replProvider == null) { return(false); } var replWindow = replProvider.FindReplWindow(replWindowId); bool created = replWindow == null; if (created) { replWindow = replProvider.CreateReplWindow( _project.Site.GetPythonContentType(), replTitle, typeof(PythonLanguageInfo).GUID, replWindowId ); } var replToolWindow = replWindow as ToolWindowPane; var replFrame = (replToolWindow != null) ? replToolWindow.Frame as IVsWindowFrame : null; var pyEvaluator = replWindow.Evaluator as PythonReplEvaluator; var options = (pyEvaluator != null) ? pyEvaluator.CurrentOptions as ConfigurablePythonReplOptions : null; if (options == null) { if (created && replFrame != null) { // We created the window, but it isn't valid, so we'll close // it again immediately. replFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } return(false); } if (pyEvaluator.IsExecuting) { throw new InvalidOperationException(SR.GetString(SR.ErrorCommandAlreadyRunning)); } options.InterpreterFactory = project.GetInterpreterFactory(); options.Project = project as PythonProjectNode; options._workingDir = startInfo.WorkingDirectory; options._envVars = startInfo.EnvironmentVariables; project.AddActionOnClose((object)replWindow, BasePythonReplEvaluator.CloseReplWindow); var pane = replWindow as ToolWindowPane; var frame = pane != null ? pane.Frame as IVsWindowFrame : null; if (frame != null) { ErrorHandler.ThrowOnFailure(frame.Show()); } var result = await pyEvaluator.Reset(quiet : true); if (result.IsSuccessful) { try { var filename = startInfo.Filename; var arguments = startInfo.Arguments; if (startInfo.IsScript) { pyEvaluator.Window.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments)); Debug.WriteLine("Executing {0} {1}", filename, arguments); result = await pyEvaluator.ExecuteFile(filename, arguments); } else if (startInfo.IsModule) { pyEvaluator.Window.WriteLine(string.Format("Executing -m {0} {1}", filename, arguments)); Debug.WriteLine("Executing -m {0} {1}", filename, arguments); result = await pyEvaluator.ExecuteModule(filename, arguments); } else if (startInfo.IsCode) { Debug.WriteLine("Executing -c \"{0}\"", filename, arguments); result = await pyEvaluator.ExecuteText(filename); } else { pyEvaluator.Window.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments)); Debug.WriteLine("Executing {0} {1}", filename, arguments); result = await pyEvaluator.ExecuteProcess(filename, arguments); } if (resetRepl) { // We really close the backend, rather than resetting. pyEvaluator.Close(); } } catch (Exception ex) { ActivityLog.LogError(SR.ProductName, SR.GetString(SR.ErrorRunningCustomCommand, _label, ex)); var outWindow = OutputWindowRedirector.GetGeneral(project.Site); if (outWindow != null) { outWindow.WriteErrorLine(SR.GetString(SR.ErrorRunningCustomCommand, _label, ex)); outWindow.Show(); } } return(true); } return(false); }
private static ReplWindow OpenInteractive( PythonVisualStudioApp app, ReplWindowProxySettings settings, string executionMode ) { string description = null; if (settings.Version.IsCPython) { description = string.Format("{0} {1}", settings.Version.Isx64 ? CPythonInterpreterFactoryConstants.Description64 : CPythonInterpreterFactoryConstants.Description32, settings.Version.Version.ToVersion() ); } else if (settings.Version.IsIronPython) { description = string.Format("{0} {1}", settings.Version.Isx64 ? "IronPython 64-bit" : "IronPython", settings.Version.Version.ToVersion() ); } Assert.IsNotNull(description, "Unknown interpreter"); var automation = (IVsPython)app.Dte.GetObject("VsPython"); var options = ((IPythonOptions)automation).GetInteractiveOptions(description); Assert.IsNotNull(options, "Could not find options for " + description); options.InlinePrompts = settings.InlinePrompts; options.UseInterpreterPrompts = settings.UseInterpreterPrompts; options.PrimaryPrompt = settings.PrimaryPrompt; options.SecondaryPrompt = settings.SecondaryPrompt; options.EnableAttach = settings.EnableAttach; var oldExecutionMode = options.ExecutionMode; app.OnDispose(() => options.ExecutionMode = oldExecutionMode); options.ExecutionMode = executionMode; bool success = false; for (int retries = 1; retries < 20; ++retries) { try { app.ExecuteCommand("Python.Interactive", "/e:\"" + description + "\""); success = true; break; } catch (AggregateException) { } app.DismissAllDialogs(); app.SetFocus(); Thread.Sleep(retries * 100); } Assert.IsTrue(success, "Unable to open " + description + " through DTE"); var provider = app.ComponentModel.GetService <IReplWindowProvider>(); var interpreters = app.ComponentModel.GetService <IInterpreterOptionsService>(); var replId = PythonReplEvaluatorProvider.GetReplId( interpreters.FindInterpreter(settings.Version.Id, settings.Version.Version.ToVersion()) ); var interactive = provider.FindReplWindow(replId) as ReplWindow; if (interactive == null) { // This is a failure, since we check if the environment is // installed in TestInitialize(). Assert.Fail("Need " + description); } return(interactive); }
private async Task <bool> RunInRepl(IPythonProject project, CommandStartInfo startInfo) { var executeIn = string.IsNullOrEmpty(startInfo.ExecuteIn) ? CreatePythonCommandItem.ExecuteInRepl : startInfo.ExecuteIn; bool resetRepl = executeIn.StartsWith("R", StringComparison.InvariantCulture); var replTitle = executeIn.Substring(4).TrimStart(' ', ':'); if (string.IsNullOrEmpty(replTitle)) { replTitle = Strings.CustomCommandReplTitle.FormatUI(DisplayLabelWithoutAccessKeys); } else { var match = _customCommandLabelRegex.Match(replTitle); if (match.Success) { replTitle = LoadResourceFromAssembly( match.Groups["assembly"].Value, match.Groups["namespace"].Value, match.Groups["key"].Value ); } } replTitle = PerformSubstitutions(project, replTitle); var replWindowId = PythonReplEvaluatorProvider.GetTemporaryId( ReplId + executeIn.Substring(4), _project.GetInterpreterFactory().Configuration ); var model = _project.Site.GetComponentModel(); var replProvider = model.GetService <InteractiveWindowProvider>(); if (replProvider == null) { return(false); } bool created; var replWindow = replProvider.OpenOrCreateTemporary(replWindowId, replTitle, out created); // TODO: Find alternative way of closing repl window on Dev15 var replFrame = (replWindow as ToolWindowPane)?.Frame as IVsWindowFrame; var interactive = replWindow.InteractiveWindow; var pyEvaluator = replWindow.InteractiveWindow.Evaluator as PythonInteractiveEvaluator; if (pyEvaluator == null) { if (created && replFrame != null) { // We created the window, but it isn't valid, so we'll close // it again immediately. replFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } return(false); } if (pyEvaluator.IsExecuting) { throw new InvalidOperationException(Strings.ErrorCommandAlreadyRunning); } pyEvaluator.ProjectMoniker = _project.GetMkDocument(); pyEvaluator.Configuration = new LaunchConfiguration(startInfo.Interpreter) { WorkingDirectory = startInfo.WorkingDirectory, Environment = startInfo.EnvironmentVariables.ToDictionary(kv => kv.Key, kv => kv.Value) }; project.AddActionOnClose((object)replWindow, InteractiveWindowProvider.Close); replWindow.Show(true); var result = await pyEvaluator.ResetAsync(false, quiet : true); if (result.IsSuccessful) { try { var filename = startInfo.Filename; var arguments = startInfo.Arguments ?? string.Empty; if (startInfo.IsScript) { interactive.WriteLine(Strings.CustomCommandExecutingScript.FormatUI(Path.GetFileName(filename), arguments)); Debug.WriteLine("Executing {0} {1}", filename, arguments); await pyEvaluator.ExecuteFileAsync(filename, arguments); } else if (startInfo.IsModule) { interactive.WriteLine(Strings.CustomCommandExecutingModule.FormatUI(filename, arguments)); Debug.WriteLine("Executing -m {0} {1}", filename, arguments); await pyEvaluator.ExecuteModuleAsync(filename, arguments); } else if (startInfo.IsCode) { Debug.WriteLine("Executing -c \"{0}\"", filename, arguments); await pyEvaluator.ExecuteCodeAsync(filename); } else { interactive.WriteLine(Strings.CustomCommandExecutingOther.FormatUI(Path.GetFileName(filename), arguments)); Debug.WriteLine("Executing {0} {1}", filename, arguments); await pyEvaluator.ExecuteProcessAsync(filename, arguments); } if (resetRepl) { // We really close the backend, rather than resetting. pyEvaluator.Dispose(); } } catch (Exception ex) { ActivityLog.LogError(Strings.ProductTitle, Strings.ErrorRunningCustomCommand.FormatUI(_label, ex)); var outWindow = OutputWindowRedirector.GetGeneral(project.Site); if (outWindow != null) { outWindow.WriteErrorLine(Strings.ErrorRunningCustomCommand.FormatUI(_label, ex)); outWindow.Show(); } } return(true); } return(false); }
public override ToolWindowPane ActivateInteractiveWindow(VisualStudioApp app, string executionMode) { string description = null; if (Version.IsCPython) { description = string.Format("{0} {1}", Version.Isx64 ? CPythonInterpreterFactoryConstants.Description64 : CPythonInterpreterFactoryConstants.Description32, Version.Version.ToVersion() ); } else if (Version.IsIronPython) { description = string.Format("{0} {1}", Version.Isx64 ? "IronPython 64-bit" : "IronPython", Version.Version.ToVersion() ); } Assert.IsNotNull(description, "Unknown interpreter"); var automation = (IVsPython)app.Dte.GetObject("VsPython"); var options = (IPythonOptions)automation; var replOptions = options.GetInteractiveOptions(description); Assert.IsNotNull(replOptions, "Could not find options for " + description); replOptions.InlinePrompts = InlinePrompts; replOptions.UseInterpreterPrompts = UseInterpreterPrompts; replOptions.PrimaryPrompt = PrimaryPrompt; replOptions.SecondaryPrompt = SecondaryPrompt; replOptions.EnableAttach = EnableAttach; var oldExecutionMode = replOptions.ExecutionMode; app.OnDispose(() => replOptions.ExecutionMode = oldExecutionMode); replOptions.ExecutionMode = executionMode; var oldAddNewLineAtEndOfFullyTypedWord = options.Intellisense.AddNewLineAtEndOfFullyTypedWord; app.OnDispose(() => options.Intellisense.AddNewLineAtEndOfFullyTypedWord = oldAddNewLineAtEndOfFullyTypedWord); options.Intellisense.AddNewLineAtEndOfFullyTypedWord = AddNewLineAtEndOfFullyTypedWord; bool success = false; for (int retries = 1; retries < 20; ++retries) { try { app.ExecuteCommand("Python.Interactive", "/e:\"" + description + "\""); success = true; break; } catch (AggregateException) { } app.DismissAllDialogs(); app.SetFocus(); Thread.Sleep(retries * 100); } Assert.IsTrue(success, "Unable to open " + description + " through DTE"); var interpreters = app.ComponentModel.GetService <IInterpreterOptionsService>(); var replId = PythonReplEvaluatorProvider.GetReplId( interpreters.FindInterpreter(Version.Id, Version.Version.ToVersion()) ); var provider = app.ComponentModel.GetService <InteractiveWindowProvider>(); return((ToolWindowPane)provider.FindReplWindow(replId)); }