Ejemplo n.º 1
0
        private void GetFullUrl(LaunchConfiguration config, out Uri uri, out int port)
        {
            int p;

            if (!int.TryParse(config.GetLaunchOption(PythonConstants.WebBrowserPortSetting) ?? "", out p))
            {
                p = TestServerPort;
            }
            port = p;

            var host = config.GetLaunchOption(PythonConstants.WebBrowserUrlSetting);

            if (string.IsNullOrEmpty(host))
            {
                uri = null;
                return;
            }
            try {
                uri = GetFullUrl(host, p);
            } catch (UriFormatException) {
                var output = OutputWindowRedirector.GetGeneral(_serviceProvider);
                output.WriteErrorLine(Strings.ErrorInvalidLaunchUrl.FormatUI(host));
                output.ShowAndActivate();
                uri = null;
            }
        }
Ejemplo n.º 2
0
        public override async Task ApplyAsync()
        {
            try {
                await _ready.WaitAsync();
            } catch (ObjectDisposedException) {
                return;
            }

            try {
                var op = new AddVirtualEnvironmentOperation(
                    Site,
                    SelectedProject?.Node,
                    SelectedProject?.Workspace,
                    Path.Combine(LocationPath, VirtualEnvName),
                    BaseInterpreter.Id,
                    UseVEnv,
                    WillInstallRequirementsTxt,
                    RequirementsPath,
                    IsRegisterCustomEnv,
                    Description,
                    SetAsCurrent,
                    SetAsDefault,
                    ViewInEnvironmentWindow,
                    OutputWindowRedirector.GetGeneral(Site)
                    );

                await op.RunAsync();
            } finally {
                try {
                    _ready.Release();
                } catch (ObjectDisposedException) {
                }
            }
        }
Ejemplo n.º 3
0
        private void ShowCookiecutterPage()
        {
            Debug.Assert(_cookiecutterPage == null);

            var outputWindow = OutputWindowRedirector.GetGeneral(this);

            Debug.Assert(outputWindow != null);

            ReportPrereqsEvent(true);

            string feedUrl = CookiecutterPackage.Instance.RecommendedFeed;

            if (string.IsNullOrEmpty(feedUrl))
            {
                feedUrl = UrlConstants.DefaultRecommendedFeed;
            }

            object commonIdeFolderPath;
            var    shell = (IVsShell)GetService(typeof(SVsShell));

            ErrorHandler.ThrowOnFailure(shell.GetProperty((int)__VSSPROPID.VSSPROPID_InstallDirectory, out commonIdeFolderPath));

            var gitClient = GitClientProvider.Create(outputWindow, commonIdeFolderPath as string);

            _cookiecutterPage = new CookiecutterContainerPage(outputWindow, CookiecutterTelemetry.Current, gitClient, new Uri(feedUrl), OpenGeneratedFolder, UpdateCommandUI);
            _cookiecutterPage.ContextMenuRequested += OnContextMenuRequested;
            _cookiecutterPage.InitializeAsync(CookiecutterPackage.Instance.CheckForTemplateUpdate).HandleAllExceptions(this, GetType()).DoNotWait();

            ((Frame)Content).Content = _cookiecutterPage;
        }
        private async Task <bool> AttachWorker(AzureWebSiteInfo webSite)
        {
            using (new WaitDialog("Azure remote debugging", "Attaching to Azure web site at " + webSite.Uri, _serviceProvider, showProgress: true)) {
                // Get path (relative to site URL) for the debugger endpoint.
                XDocument webConfig;
                try {
                    webConfig = await GetWebConfig(webSite);
                } catch (WebException) {
                    return(false);
                } catch (IOException) {
                    return(false);
                } catch (XmlException) {
                    return(false);
                }
                if (webConfig == null)
                {
                    return(false);
                }

                var path =
                    (from add in webConfig.Elements("configuration").Elements("system.webServer").Elements("handlers").Elements("add")
                     let type = (string)add.Attribute("type")
                                where type != null
                                let components = type.Split(',')
                                                 where components[0].Trim() == "Microsoft.PythonTools.Debugger.WebSocketProxy"
                                                 select(string) add.Attribute("path")
                    ).FirstOrDefault();
                if (path == null)
                {
                    return(false);
                }

                var secret =
                    (from add in webConfig.Elements("configuration").Elements("appSettings").Elements("add")
                     where (string)add.Attribute("key") == "WSGI_PTVSD_SECRET"
                     select(string) add.Attribute("value")
                    ).FirstOrDefault();
                if (secret == null)
                {
                    return(false);
                }

                try {
                    AttachDebugger(new UriBuilder(webSite.Uri)
                    {
                        Scheme = "wss", Port = -1, Path = path, UserName = secret
                    }.Uri);
                } catch (Exception ex) {
                    // If we got to this point, the attach logic in debug engine will catch exceptions, display proper error message and
                    // ask the user to retry, so the only case where we actually get here is if user canceled on error. If this is the case,
                    // we don't want to pop any additional error messages, so always return true, but log the error in the Output window.
                    var output = OutputWindowRedirector.GetGeneral(_serviceProvider);
                    output.WriteErrorLine("Failed to attach to Azure web site: " + ex.Message);
                    output.ShowAndActivate();
                }
                return(true);
            }
        }
Ejemplo n.º 5
0
        protected override void OnCreate()
        {
            base.OnCreate();

            _site = (IServiceProvider)this;

            _pyService = _site.GetPythonToolsService();

            // TODO: Get PYEnvironment added to image list
            BitmapImageMoniker = KnownMonikers.DockPanel;
            Caption            = Strings.Environments;

            _service = _site.GetComponentModel().GetService <IInterpreterOptionsService>();

            _outputWindow = OutputWindowRedirector.GetGeneral(_site);
            Debug.Assert(_outputWindow != null);
            _statusBar = _site.GetService(typeof(SVsStatusbar)) as IVsStatusbar;

            var list = new ToolWindow();

            list.Site         = _site;
            list.ViewCreated += List_ViewCreated;

            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInteractiveWindow,
                                         OpenInteractiveWindow_Executed,
                                         OpenInteractiveWindow_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInteractiveOptions,
                                         OpenInteractiveOptions_Executed,
                                         OpenInteractiveOptions_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentPathsExtension.StartInterpreter,
                                         StartInterpreter_Executed,
                                         StartInterpreter_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentPathsExtension.StartWindowsInterpreter,
                                         StartInterpreter_Executed,
                                         StartInterpreter_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         ApplicationCommands.Help,
                                         OnlineHelp_Executed,
                                         OnlineHelp_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         ToolWindow.UnhandledException,
                                         UnhandledException_Executed,
                                         UnhandledException_CanExecute
                                         ));

            list.Service = _service;

            Content = list;
        }
Ejemplo n.º 6
0
        protected override void OnCreate()
        {
            _outputWindow = OutputWindowRedirector.GetGeneral(this);
            Debug.Assert(_outputWindow != null);
            _statusBar      = GetService(typeof(SVsStatusbar)) as IVsStatusbar;
            _uiShell        = GetService(typeof(SVsUIShell)) as IVsUIShell;
            _dte            = GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
            _infoBarFactory = GetService(typeof(SVsInfoBarUIFactory)) as IVsInfoBarUIFactory;

            object control = null;

            if (!CookiecutterClientProvider.IsCompatiblePythonAvailable())
            {
                ReportPrereqsEvent(false);
                control = new MissingDependencies();
            }
            else
            {
                ReportPrereqsEvent(true);
                string feedUrl = CookiecutterPackage.Instance.RecommendedFeed;
                if (string.IsNullOrEmpty(feedUrl))
                {
                    feedUrl = UrlConstants.DefaultRecommendedFeed;
                }

                _cookiecutterControl = new CookiecutterControl(_outputWindow, CookiecutterTelemetry.Current, new Uri(feedUrl), OpenGeneratedFolder, UpdateCommandUI);
                _cookiecutterControl.ContextMenuRequested += OnContextMenuRequested;
                control = _cookiecutterControl;
                _cookiecutterControl.InitializeAsync(CookiecutterPackage.Instance.CheckForTemplateUpdate).HandleAllExceptions(this, GetType()).DoNotWait();
            }

            Content = control;

            RegisterCommands(new Command[] {
                new HomeCommand(this),
                new RunCommand(this),
                new UpdateCommand(this),
                new CheckForUpdatesCommand(this),
                new GitHubCommand(this, PackageIds.cmdidLinkGitHubHome),
                new GitHubCommand(this, PackageIds.cmdidLinkGitHubIssues),
                new GitHubCommand(this, PackageIds.cmdidLinkGitHubWiki),
            }, PackageGuids.guidCookiecutterCmdSet);

            RegisterCommands(new Command[] {
                new DeleteInstalledTemplateCommand(this),
            }, VSConstants.GUID_VSStandardCommandSet97);

            base.OnCreate();

            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;

            if (CookiecutterPackage.Instance.ShowHelp)
            {
                AddInfoBar();
            }
        }
Ejemplo n.º 7
0
        protected override void OnCreate()
        {
            _site = (IServiceProvider)this;

            _outputWindow = OutputWindowRedirector.GetGeneral(CookiecutterPackage.Instance);
            Debug.Assert(_outputWindow != null);
            _statusBar      = _site.GetService(typeof(SVsStatusbar)) as IVsStatusbar;
            _uiShell        = _site.GetService(typeof(SVsUIShell)) as IVsUIShell;
            _dte            = _site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
            _infoBarFactory = _site.GetService(typeof(SVsInfoBarUIFactory)) as IVsInfoBarUIFactory;

            object control = null;

            _missingDependencies = CheckDependencies(out _missingGit, out _missingPython, out _missingCookiecutter);
            if (_missingDependencies)
            {
                control = new MissingDependencies();
            }
            else
            {
                string feedUrl = CookiecutterPackage.Instance.RecommendedFeed;
                if (string.IsNullOrEmpty(feedUrl))
                {
                    feedUrl = UrlConstants.DefaultRecommendedFeed;
                }

                _cookiecutterControl = new CookiecutterControl(_outputWindow, new Uri(feedUrl), OpenGeneratedFolder, UpdateCommandUI);
                _cookiecutterControl.ContextMenuRequested += OnContextMenuRequested;
                control = _cookiecutterControl;
            }

            Content = control;

            RegisterCommands(new Command[] {
                new HomeCommand(this),
                new RunCommand(this),
                new GitHubCommand(this, PackageIds.cmdidLinkGitHubHome),
                new GitHubCommand(this, PackageIds.cmdidLinkGitHubIssues),
                new GitHubCommand(this, PackageIds.cmdidLinkGitHubWiki),
            }, PackageGuids.guidCookiecutterCmdSet);

            RegisterCommands(new Command[] {
                new DeleteInstalledTemplateCommand(this),
            }, VSConstants.GUID_VSStandardCommandSet97);

            base.OnCreate();

            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;

            if (CookiecutterPackage.Instance.ShowHelp || _missingDependencies)
            {
                AddInfoBar();
            }
        }
Ejemplo n.º 8
0
        private async Task ReanalyzeWorkspaceAsync(IPythonInterpreterFactory factory)
        {
            _site.MustBeCalledFromUIThread();

#if DEBUG
            var output = OutputWindowRedirector.GetGeneral(_site);
            await ReanalyzeWorkspaceHelperAsync(factory, output);
#else
            await ReanalyzeWorkspaceHelperAsync(factory, null);
#endif
        }
Ejemplo n.º 9
0
        private string GetFullUrl() {
            var host = _project.GetProjectProperty(NodejsConstants.LaunchUrl);

            try {
                return GetFullUrl(host, TestServerPort);
            } catch (UriFormatException) {
                var output = OutputWindowRedirector.GetGeneral(NodejsPackage.Instance);
                output.WriteErrorLine(SR.GetString(SR.ErrorInvalidLaunchUrl, host));
                output.ShowAndActivate();
                return string.Empty;
            }
        }
Ejemplo n.º 10
0
        protected override void OnCreate()
        {
            base.OnCreate();

            _site = (IServiceProvider)this;

            _pyService = _site.GetPythonToolsService();

            BitmapResourceID = PythonConstants.ResourceIdForReplImages;
            BitmapIndex      = 0;
            Caption          = SR.GetString(SR.Environments);

            _service = _site.GetComponentModel().GetService <IInterpreterOptionsService>();

            _outputWindow = OutputWindowRedirector.GetGeneral(_site);
            Debug.Assert(_outputWindow != null);
            _statusBar = _site.GetService(typeof(SVsStatusbar)) as IVsStatusbar;

            var list = new ToolWindow();

            list.ViewCreated += List_ViewCreated;

            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInteractiveWindow,
                                         OpenInteractiveWindow_Executed,
                                         OpenInteractiveWindow_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInteractiveOptions,
                                         OpenInteractiveOptions_Executed,
                                         OpenInteractiveOptions_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentPathsExtension.StartInterpreter,
                                         StartInterpreter_Executed,
                                         StartInterpreter_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentPathsExtension.StartWindowsInterpreter,
                                         StartInterpreter_Executed,
                                         StartInterpreter_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         ToolWindow.UnhandledException,
                                         UnhandledException_Executed,
                                         UnhandledException_CanExecute
                                         ));

            list.Service = _service;

            Content = list;
        }
Ejemplo n.º 11
0
        private string GetFullUrl()
        {
            var host = _project.GetProjectProperty(NodeProjectProperty.LaunchUrl);

            try {
                return(GetFullUrl(host, TestServerPort));
            } catch (UriFormatException) {
                var output = OutputWindowRedirector.GetGeneral(NodejsPackage.Instance);
                output.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, Resources.ErrorInvalidLaunchUrl, host));
                output.ShowAndActivate();
                return(string.Empty);
            }
        }
Ejemplo n.º 12
0
        protected override void SetInnerProject(IntPtr innerIUnknown)
        {
            var inner = Marshal.GetObjectForIUnknown(innerIUnknown);

            // The reason why we keep a reference to those is that doing a QI after being
            // aggregated would do the AddRef on the outer object.
            _innerVsProjectFlavorCfgProvider = inner as IVsProjectFlavorCfgProvider;
            _innerProject     = inner as IVsProject;
            _innerProject3    = inner as IVsProject3;
            _innerVsHierarchy = inner as IVsHierarchy;

            // Ensure we have a service provider as this is required for menu items to work
            if (serviceProvider == null)
            {
                serviceProvider = _serviceProvider;
            }

            // Now let the base implementation set the inner object
            base.SetInnerProject(innerIUnknown);

            // Add our commands (this must run after we called base.SetInnerProject)
            _menuService = ((System.IServiceProvider) this).GetService(typeof(IMenuCommandService)) as OleMenuCommandService;

#if !DJANGO_HTML_EDITOR
            try
            {
                var outputWindow = OutputWindowRedirector.GetGeneral(this);
                outputWindow.WriteErrorLine("NOTE: Django template support has been disabled in the editor due to a\r\n" +
                                            "compatibility issue and will be restored in a future update.");
                outputWindow.ShowAndActivate();

                var shell = ((System.IServiceProvider) this).GetService(typeof(SVsUIShell)) as IVsUIShell;
                if (shell != null)
                {
                    var windowGuid = new Guid("{34E76E81-EE4A-11D0-AE2E-00A0C90FFFC3}");
                    if (ErrorHandler.Succeeded(shell.FindToolWindow(0, ref windowGuid, out IVsWindowFrame wnd)) && wnd != null)
                    {
                        wnd.Show();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
            }
#endif
        }
Ejemplo n.º 13
0
        private void ExecuteCommand(string name, string args)
        {
            try {
                _dte.ExecuteCommand(name, args ?? string.Empty);
            } catch (Exception ex) when(!ex.IsCriticalException())
            {
#if !DEV15_OR_LATER
                if (name == "File.OpenFolder")
                {
                    OpenInWindowsExplorer(args.Trim('"'));
                    return;
                }
#endif
                var outputWindow = OutputWindowRedirector.GetGeneral(this);
                outputWindow.WriteErrorLine(ex.Message);
            }
        }
Ejemplo n.º 14
0
        public AddCondaEnvironmentOperation(
            IServiceProvider site,
            ICondaEnvironmentManager condaMgr,
            PythonProjectNode project,
            IPythonWorkspaceContext workspace,
            string envNameOrPath,
            string envFilePath,
            List <PackageSpec> packages,
            bool setAsCurrent,
            bool setAsDefault,
            bool viewInEnvWindow
            )
        {
            _site            = site ?? throw new ArgumentNullException(nameof(site));
            _condaMgr        = condaMgr ?? throw new ArgumentNullException(nameof(condaMgr));
            _project         = project;
            _workspace       = workspace;
            _envNameOrPath   = envNameOrPath ?? throw new ArgumentNullException(nameof(envNameOrPath));
            _envFilePath     = envFilePath;
            _packages        = packages ?? throw new ArgumentNullException(nameof(packages));
            _setAsCurrent    = setAsCurrent;
            _setAsDefault    = setAsDefault;
            _viewInEnvWindow = viewInEnvWindow;

            // If passed a path, the actual name reported by conda will the last part
            _actualName = PathUtils.GetFileOrDirectoryName(_envNameOrPath);
            if (_actualName.Length == 0)
            {
                _actualName = _envNameOrPath;
            }

            _outputWindow = OutputWindowRedirector.GetGeneral(_site);
            _statusBar    = _site.GetService(typeof(SVsStatusbar)) as IVsStatusbar;
            _showAndActiveOutputWindow = _site.GetPythonToolsService().GeneralOptions.ShowOutputWindowForVirtualEnvCreate;
            _statusCenter    = _site.GetService(typeof(SVsTaskStatusCenterService)) as IVsTaskStatusCenterService;
            _registry        = _site.GetComponentModel().GetService <IInterpreterRegistryService>();
            _options         = _site.GetComponentModel().GetService <IInterpreterOptionsService>();
            _logger          = _site.GetService(typeof(IPythonToolsLogger)) as IPythonToolsLogger;
            _factoryProvider = _site.GetComponentModel().GetService <CondaEnvironmentFactoryProvider>();
        }
Ejemplo n.º 15
0
        private void ShowCookiecutterPage()
        {
            Debug.Assert(_cookiecutterPage == null);

            var outputWindow = OutputWindowRedirector.GetGeneral(this);

            Debug.Assert(outputWindow != null);

            ReportPrereqsEvent(true);

            string feedUrl = CookiecutterPackage.Instance.RecommendedFeed;

            if (string.IsNullOrEmpty(feedUrl))
            {
                feedUrl = UrlConstants.DefaultRecommendedFeed;
            }

            _cookiecutterPage = new CookiecutterContainerPage(outputWindow, CookiecutterTelemetry.Current, new Uri(feedUrl), OpenGeneratedFolder, UpdateCommandUI);
            _cookiecutterPage.ContextMenuRequested += OnContextMenuRequested;
            _cookiecutterPage.InitializeAsync(CookiecutterPackage.Instance.CheckForTemplateUpdate).HandleAllExceptions(this, GetType()).DoNotWait();

            ((Frame)Content).Content = _cookiecutterPage;
        }
Ejemplo n.º 16
0
        public async Task RunAsync()
        {
            var outputWindow = OutputWindowRedirector.GetGeneral(_site);
            var taskHandler  = _statusCenter?.PreRegister(
                new TaskHandlerOptions()
            {
                ActionsAfterCompletion = CompletionActions.RetainAndNotifyOnFaulted | CompletionActions.RetainAndNotifyOnRanToCompletion,
                Title = Strings.InstallPackagesStatusCenterTitle.FormatUI(PathUtils.GetFileOrDirectoryName(_pm.Factory.Configuration.Description)),
                DisplayTaskDetails = (t) => { outputWindow.ShowAndActivate(); }
            },
                new TaskProgressData()
            {
                CanBeCanceled   = false,
                ProgressText    = Strings.InstallPackagesStatusCenterProgressPreparing,
                PercentComplete = null,
            }
                );

            var task = InstallPackagesAsync(taskHandler);

            taskHandler?.RegisterTask(task);
            _site.ShowTaskStatusCenter();
        }
Ejemplo n.º 17
0
        public async Task RunAsync()
        {
            var outputWindow = OutputWindowRedirector.GetGeneral(_site);
            var taskHandler  = _statusCenter.PreRegister(
                new TaskHandlerOptions()
            {
                ActionsAfterCompletion = CompletionActions.RetainAndNotifyOnFaulted | CompletionActions.RetainAndNotifyOnRanToCompletion,
                Title = Strings.VirtualEnvStatusCenterCreateTitle.FormatUI(PathUtils.GetFileOrDirectoryName(_virtualEnvPath)),
                DisplayTaskDetails = (t) => { outputWindow.ShowAndActivate(); }
            },
                new TaskProgressData()
            {
                CanBeCanceled   = false,
                ProgressText    = Strings.VirtualEnvStatusCenterCreateProgressPreparing,
                PercentComplete = null,
            }
                );

            var task = CreateVirtualEnvironmentAsync(taskHandler);

            taskHandler?.RegisterTask(task);
            _site.ShowTaskStatusCenter();
        }
Ejemplo n.º 18
0
        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);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Creates a virtual environment using venv. If venv is not available,
 /// the task will succeed but error text will be passed to the
 /// redirector.
 /// </summary>
 public static Task CreateWithVEnv(IServiceProvider provider, IPythonInterpreterFactory factory, string path)
 {
     factory.ThrowIfNotRunnable();
     return(ContinueCreate(provider, factory, path, true, OutputWindowRedirector.GetGeneral(provider)));
 }
Ejemplo n.º 20
0
        private async Task ExecuteWorker(PythonProjectNode project)
        {
            _errorListProvider.Tasks.Clear();

            var interpFactory = project.GetInterpreterFactoryOrThrow();
            var startInfo     = GetStartInfo(project);

            var packagesToInstall = new List <string>();

            foreach (var pkg in startInfo.RequiredPackages)
            {
                if (!await Pip.IsInstalled(interpFactory, pkg))
                {
                    packagesToInstall.Add(pkg);
                }
            }

            if (packagesToInstall.Any())
            {
                var installMissingButton = new TaskDialogButton(
                    Strings.CustomCommandPrerequisitesInstallMissing,
                    Strings.CustomCommandPrerequisitesInstallMissingSubtext + "\r\n\r\n" + string.Join("\r\n", packagesToInstall));
                var runAnywayButton = new TaskDialogButton(Strings.CustomCommandPrerequisitesRunAnyway);
                var doNotRunButton  = new TaskDialogButton(Strings.CustomCommandPrerequisitesDoNotRun);

                var taskDialog = new TaskDialog(project.Site)
                {
                    Title             = Strings.ProductTitle,
                    MainInstruction   = Strings.CustomCommandPrerequisitesInstruction,
                    Content           = Strings.CustomCommandPrerequisitesContent.FormatUI(DisplayLabelWithoutAccessKeys),
                    AllowCancellation = true,
                    Buttons           = { installMissingButton, runAnywayButton, doNotRunButton, TaskDialogButton.Cancel }
                };

                var selectedButton = taskDialog.ShowModal();
                if (selectedButton == installMissingButton)
                {
                    await Pip.Install(
                        project.Site,
                        interpFactory,
                        string.Join(" ", packagesToInstall),
                        false,
                        OutputWindowRedirector.GetGeneral(project.Site));
                }
                else if (selectedButton == runAnywayButton)
                {
                }
                else
                {
                    throw new TaskCanceledException();
                }
            }

            if (startInfo.TargetType == CreatePythonCommandItem.TargetTypePip)
            {
                if (startInfo.ExecuteInOutput)
                {
                    await Pip.Install(
                        _project.Site,
                        interpFactory,
                        string.IsNullOrEmpty(startInfo.Arguments)?
                        startInfo.Filename :
                        string.Format("{0} {1}", startInfo.Filename, startInfo.Arguments),
                        project.Site,
                        false,
                        OutputWindowRedirector.GetGeneral(project.Site)
                        );

                    return;
                }

                // Rewrite start info to execute
                startInfo.TargetType = CreatePythonCommandItem.TargetTypeModule;
                startInfo.AddArgumentAtStart(startInfo.Filename);
                startInfo.Filename = "pip";
            }

            if (startInfo.ExecuteInRepl)
            {
                if (await RunInRepl(project, startInfo))
                {
                    return;
                }
            }

            startInfo.AdjustArgumentsForProcessStartInfo(GetInterpreterPath(project, false));

            if (startInfo.ExecuteInOutput)
            {
                RunInOutput(project, startInfo);
            }
            else
            {
                RunInConsole(project, startInfo);
            }
        }