Exemplo n.º 1
0
        public override void DoCommand(object sender, EventArgs args)
        {
            var activeView = PythonToolsPackage.GetActiveTextView(_serviceProvider);
            var pyProj     = activeView.TextBuffer.GetProject(_serviceProvider);
            var analyzer   = activeView.GetAnalyzerAtCaret(_serviceProvider);
            var window     = ExecuteInReplCommand.EnsureReplWindow(_serviceProvider, analyzer, pyProj);
            var eval       = window.InteractiveWindow.Evaluator as PythonReplEvaluator;

            string path = activeView.GetFilePath();
            string scope;

            if (path != null && (scope = eval.GetScopeByFilename(path)) != null)
            {
                // we're now in the correct module, execute the code
                window.InteractiveWindow.Operations.Cancel();
                // TODO: get correct prompt
                window.InteractiveWindow.WriteLine(">>>" + " $module " + scope);
                eval.SetScope(scope);

                base.DoCommand(sender, args);
            }
            else
            {
                window.InteractiveWindow.WriteLine("Could not find defining module.");
            }
        }
Exemplo n.º 2
0
        private void WarnAboutPythonSymbols(string moduleName)
        {
            const string content =
                "Python/native mixed-mode debugging requires symbol files for the Python interpreter that is being debugged. Please add the folder " +
                "containing those symbol files to your symbol search path, and force a reload of symbols for {0}.";

            var dialog = new TaskDialog(_serviceProvider);

            var openSymbolSettings = new TaskDialogButton("Open symbol settings dialog");
            var downloadSymbols    = new TaskDialogButton("Download symbols for my interpreter");

            dialog.Buttons.Add(openSymbolSettings);
            dialog.Buttons.Add(downloadSymbols);

            dialog.Buttons.Add(TaskDialogButton.Close);
            dialog.UseCommandLinks = true;
            dialog.Title           = "Python Symbols Required";
            dialog.Content         = string.Format(content, moduleName);
            dialog.Width           = 0;

            dialog.ShowModal();

            if (dialog.SelectedButton == openSymbolSettings)
            {
                var cmdId = new CommandID(VSConstants.GUID_VSStandardCommandSet97, VSConstants.cmdidToolsOptions);
                _serviceProvider.GlobalInvoke(cmdId, "1F5E080F-CBD2-459C-8267-39fd83032166");
            }
            else if (dialog.SelectedButton == downloadSymbols)
            {
                PythonToolsPackage.OpenWebBrowser(
                    string.Format("http://go.microsoft.com/fwlink/?LinkId=308954&clcid=0x{0:X}", CultureInfo.CurrentCulture.LCID));
            }
        }
Exemplo n.º 3
0
        public override void GotoSource(VSOBJGOTOSRCTYPE gotoType)
        {
            // We do not support the "Goto Reference"
            if (VSOBJGOTOSRCTYPE.GS_REFERENCE == gotoType)
            {
                return;
            }

            foreach (var completion in _value.Values)
            {
                foreach (var location in completion.locations.MaybeEnumerate())
                {
                    if (File.Exists(location.file))
                    {
                        PythonToolsPackage.NavigateTo(
                            Site,
                            location.file,
                            Guid.Empty,
                            location.line - 1,
                            location.column - 1
                            );
                        break;
                    }
                }
            }
        }
Exemplo n.º 4
0
        public override int DebugLaunch(uint flags)
        {
            if (_project.ShouldWarnOnLaunch)
            {
                var pyService = ProjectMgr.Site.GetPythonToolsService();
                if (pyService.DebuggerOptions.PromptBeforeRunningWithBuildError)
                {
                    var res = new StartWithErrorsDialog(pyService).ShowDialog();
                    if (res == DialogResult.No)
                    {
                        return(VSConstants.S_OK);
                    }
                }
            }

            try {
                return(base.DebugLaunch(flags));
            } catch (MissingInterpreterException ex) {
                if (_project.ActiveInterpreter == _project.InterpreterRegistry.NoInterpretersValue)
                {
                    PythonToolsPackage.OpenNoInterpretersHelpPage(ProjectMgr.Site, ex.HelpPage);
                }
                else
                {
                    MessageBox.Show(ex.Message, Strings.ProductTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                return(VSConstants.S_OK);
            } catch (NoInterpretersException ex) {
                PythonToolsPackage.OpenNoInterpretersHelpPage(ProjectMgr.Site, ex.HelpPage);
                return(VSConstants.S_OK);
            }
        }
Exemplo n.º 5
0
        private void StartBrowser(string url, Func <bool> shortCircuitPredicate)
        {
            Uri uri;

            if (!String.IsNullOrWhiteSpace(url) && Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uri))
            {
                OnPortOpenedHandler.CreateHandler(
                    uri.Port,
                    shortCircuitPredicate: shortCircuitPredicate,
                    action: () => {
                    var web = _serviceProvider.GetService(typeof(SVsWebBrowsingService)) as IVsWebBrowsingService;
                    if (web == null)
                    {
                        PythonToolsPackage.OpenWebBrowser(url);
                        return;
                    }

                    ErrorHandler.ThrowOnFailure(
                        web.CreateExternalWebBrowser(
                            (uint)__VSCREATEWEBBROWSER.VSCWB_ForceNew,
                            VSPREVIEWRESOLUTION.PR_Default,
                            url
                            )
                        );
                }
                    );
            }
        }
Exemplo n.º 6
0
        private void WarnAboutPythonSymbols(string moduleName)
        {
            var dialog = new TaskDialog(_serviceProvider);

            var openSymbolSettings = new TaskDialogButton(Strings.MixedModeDebugSymbolsRequiredOpenSymbolSettings);
            var downloadSymbols    = new TaskDialogButton(Strings.MixedModeDebugSymbolsRequiredDownloadSymbols);

            dialog.Buttons.Add(openSymbolSettings);
            dialog.Buttons.Add(downloadSymbols);
            dialog.Buttons.Add(TaskDialogButton.Close);
            dialog.UseCommandLinks = true;
            dialog.Title           = Strings.MixedModeDebugSymbolsRequiredTitle;
            dialog.Content         = Strings.MixedModeDebugSymbolsRequiredMessage.FormatUI(moduleName);
            dialog.Width           = 0;

            dialog.ShowModal();

            if (dialog.SelectedButton == openSymbolSettings)
            {
                var cmdId = new CommandID(VSConstants.GUID_VSStandardCommandSet97, VSConstants.cmdidToolsOptions);
                _serviceProvider.GlobalInvoke(cmdId, "1F5E080F-CBD2-459C-8267-39fd83032166");
            }
            else if (dialog.SelectedButton == downloadSymbols)
            {
                PythonToolsPackage.OpenWebBrowser(
                    _serviceProvider,
                    string.Format("http://go.microsoft.com/fwlink/?LinkId=308954&clcid=0x{0:X}", CultureInfo.CurrentCulture.LCID)
                    );
            }
        }
        public override void DoCommand(object sender, EventArgs args)
        {
            VsProjectAnalyzer analyzer;
            string            filename, dir;
            var pyProj = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;

            if (!PythonToolsPackage.TryGetStartupFileAndDirectory(_serviceProvider, out filename, out dir, out analyzer))
            {
                // TODO: Error reporting
                return;
            }

            var            window      = (IReplWindow)EnsureReplWindow(_serviceProvider, analyzer, pyProj);
            IVsWindowFrame windowFrame = (IVsWindowFrame)((ToolWindowPane)window).Frame;

            ErrorHandler.ThrowOnFailure(windowFrame.Show());
            window.Focus();

            // The interpreter may take some time to startup, do this off the UI thread.
            ThreadPool.QueueUserWorkItem(x => {
                window.Reset();

                window.WriteLine(String.Format("Running {0}", filename));
                string scopeName = Path.GetFileNameWithoutExtension(filename);

                window.Evaluator.ExecuteFile(filename);
            });
        }
Exemplo n.º 8
0
        public override void LoadSettingsFromStorage()
        {
            _defaultInterpreter        = GetDefaultInterpreterId();
            _defaultInterpreterVersion = GetDefaultInterpreterVersion();

            var model        = (IComponentModel)PythonToolsPackage.GetGlobalService(typeof(SComponentModel));
            var interpreters = model.GetAllPythonInterpreterFactories();

            _options.Clear();
            foreach (var interpreter in interpreters)
            {
                _options.Add(
                    new InterpreterOptions()
                {
                    Display                 = interpreter.GetInterpreterDisplay(),
                    Id                      = interpreter.Id,
                    InteractiveOptions      = null,
                    InterpreterPath         = interpreter.Configuration.InterpreterPath,
                    WindowsInterpreterPath  = interpreter.Configuration.WindowsInterpreterPath,
                    Version                 = interpreter.Configuration.Version.ToString(),
                    Architecture            = FormatArchitecture(interpreter.Configuration.Architecture),
                    PathEnvironmentVariable = interpreter.Configuration.PathEnvironmentVariable,
                    IsConfigurable          = interpreter is ConfigurablePythonInterpreterFactory,
                    SupportsCompletionDb    = interpreter is IInterpreterWithCompletionDatabase,
                    Factory                 = interpreter
                }
                    );
            }
        }
Exemplo n.º 9
0
        public override void DoCommand(object sender, EventArgs args)
        {
            var activeView = PythonToolsPackage.GetActiveTextView();
            var analyzer   = activeView.GetAnalyzer();
            var window     = ExecuteInReplCommand.EnsureReplWindow(analyzer);
            var eval       = window.Evaluator as PythonReplEvaluator;

            string path = activeView.GetFilePath();
            string scope;

            if (path != null && (scope = eval.GetScopeByFilename(path)) != null)
            {
                // we're now in the correct module, execute the code
                eval.SetScope(scope);
                window.Cancel();
                window.WriteLine(window.GetOptionValue(ReplOptions.PrimaryPrompt) + " $module " + scope);
                window.WriteLine(String.Format("Current scope changed to {0}", scope));

                base.DoCommand(sender, args);
            }
            else
            {
                window.WriteLine("Could not find defining module.");
            }
        }
Exemplo n.º 10
0
 int IVsTaskItem.NavigateTo()
 {
     try {
         PythonToolsPackage.NavigateTo(_serviceProvider, SourceFile, Guid.Empty, Span.Start.Line - 1, Span.Start.Column - 1);
         return(VSConstants.S_OK);
     } catch (DirectoryNotFoundException) {
         // This may happen when the error was in a file that's located inside a .zip archive.
         // Let's walk the path and see if it is indeed the case.
         for (var path = SourceFile; PathUtils.IsValidPath(path); path = Path.GetDirectoryName(path))
         {
             if (!File.Exists(path))
             {
                 continue;
             }
             var ext = Path.GetExtension(path);
             if (string.Equals(ext, ".zip", StringComparison.OrdinalIgnoreCase) ||
                 string.Equals(ext, ".egg", StringComparison.OrdinalIgnoreCase))
             {
                 MessageBox.Show(
                     Strings.ErrorTaskItemZipArchiveNotSupportedMessage,
                     Strings.ErrorTaskItemZipArchiveNotSupportedCaption,
                     MessageBoxButtons.OK,
                     MessageBoxIcon.Information
                     );
                 return(VSConstants.S_FALSE);
             }
         }
         // If it failed for some other reason, let caller handle it.
         throw;
     }
 }
Exemplo n.º 11
0
        internal override int ExecCommandOnNode(Guid guidCmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            Debug.Assert(this.ProjectMgr != null, "The Dynamic FileNode has no project manager");
            Utilities.CheckNotNull(this.ProjectMgr);

            if (guidCmdGroup == GuidList.guidPythonToolsCmdSet)
            {
                switch (cmd)
                {
                case CommonConstants.SetAsStartupFileCmdId:
                    // Set the StartupFile project property to the Url of this node
                    ProjectMgr.SetProjectProperty(
                        CommonConstants.StartupFile,
                        PathUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, Url)
                        );
                    return(VSConstants.S_OK);

                case CommonConstants.StartDebuggingCmdId:
                case CommonConstants.StartWithoutDebuggingCmdId:
                    PythonToolsPackage.LaunchFile(ProjectMgr.Site, Url, cmd == CommonConstants.StartDebuggingCmdId, true);
                    return(VSConstants.S_OK);
                }
            }

            return(base.ExecCommandOnNode(guidCmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut));
        }
        public override void DoCommand(object sender, EventArgs args)
        {
            if (!Utilities.SaveDirtyFiles())
            {
                // Abort
                return;
            }

            // Launch with project context if there is one and it contains the active document
            // Fallback to using default python project
            var file = CommonPackage.GetActiveTextView(_serviceProvider).GetFilePath();
            var pythonProjectNode = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;

            if ((pythonProjectNode != null) && (pythonProjectNode.FindNodeByFullPath(file) == null))
            {
                pythonProjectNode = null;
            }
            IPythonProject pythonProject = pythonProjectNode as IPythonProject ?? new DefaultPythonProject(_serviceProvider, file);

            var launcher = PythonToolsPackage.GetLauncher(_serviceProvider, pythonProject);

            try {
                launcher.LaunchFile(file, CommandId == CommonConstants.StartDebuggingCmdId);
            } catch (NoInterpretersException ex) {
                PythonToolsPackage.OpenNoInterpretersHelpPage(_serviceProvider, ex.HelpPage);
            }
        }
Exemplo n.º 13
0
 private void OpenInteractiveOptions_Executed(object sender, ExecutedRoutedEventArgs e)
 {
     PythonToolsPackage.ShowOptionPage(
         _site,
         typeof(PythonInteractiveOptionsPage),
         ((EnvironmentView)e.Parameter).Factory
         );
 }
Exemplo n.º 14
0
        public void NavigateTo()
        {
            if (_location == null)
            {
                return;
            }

            PythonToolsPackage.NavigateTo(_services.Site, _location.file, Guid.Empty, _location.startLine - 1, _location.startColumn - 1);
        }
Exemplo n.º 15
0
        public void NavigateTo()
        {
            if (_location == null)
            {
                return;
            }

            PythonToolsPackage.NavigateTo(_site, _location.file, Guid.Empty, _location.line - 1, _location.column - 1);
        }
Exemplo n.º 16
0
 public override void GotoSource(VSOBJGOTOSRCTYPE SrcType)
 {
     PythonToolsPackage.NavigateTo(
         _serviceProvider,
         _locationInfo.FilePath,
         Guid.Empty,
         _locationInfo.StartLine - 1,
         _locationInfo.StartColumn - 1
         );
 }
Exemplo n.º 17
0
        public override int DebugLaunch(uint flags)
        {
            if (_project.ShouldWarnOnLaunch)
            {
                var pyService = ProjectMgr.Site.GetPythonToolsService();
                if (pyService.DebuggerOptions.PromptBeforeRunningWithBuildError)
                {
                    var res = new StartWithErrorsDialog(pyService).ShowDialog();
                    if (res == DialogResult.No)
                    {
                        return(VSConstants.S_OK);
                    }
                }
            }

            string errorMessage = null;

            try {
                return(base.DebugLaunch(flags));
            } catch (MissingInterpreterException ex) {
                if (_project.ActiveInterpreter == _project.InterpreterRegistry.NoInterpretersValue)
                {
                    PythonToolsPackage.OpenNoInterpretersHelpPage(ProjectMgr.Site, ex.HelpPage);
                }
                else
                {
                    errorMessage = ex.Message;
                }
            } catch (NoInterpretersException ex) {
                PythonToolsPackage.OpenNoInterpretersHelpPage(ProjectMgr.Site, ex.HelpPage);
            } catch (IOException ex) {
                errorMessage = ex.Message;
            } catch (NoStartupFileException ex) {
                errorMessage = ex.Message;
            } catch (ArgumentException ex) {
                // Previously used to handle "No startup file" which now has its own exception.
                // Keeping it in case some launchers started relying on us catching this.
                errorMessage = ex.Message;
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                var td = new TaskDialog(ProjectMgr.Site)
                {
                    Title             = Strings.ProductTitle,
                    MainInstruction   = Strings.FailedToLaunchDebugger,
                    Content           = errorMessage,
                    AllowCancellation = true
                };
                td.Buttons.Add(TaskDialogButton.Close);
                td.ShowModal();
            }

            return(VSConstants.S_OK);
        }
Exemplo n.º 18
0
        public virtual void AttachReplTest()
        {
            using (var interactive = Prepare(enableAttach: true)) {
                var app     = interactive.App;
                var project = app.OpenProject(@"TestData\DebuggerProject.sln");

                Assert.IsNotNull(PythonToolsPackage.GetStartupProject(app.ServiceProvider), "Startup project was not set");
                Assert.IsTrue(interactive.Settings.EnableAttach, "EnableAttach was not set");

                using (var dis = new DefaultInterpreterSetter(interactive.GetAnalyzer().InterpreterFactory)) {
                    var activeDescr = app.GetService <UIThreadBase>().Invoke(() => project.GetPythonProject().GetInterpreterFactory().Configuration.Description);
                    Assert.AreEqual(dis.CurrentDefault.Configuration.Description, activeDescr);

                    interactive.Reset();
                    interactive.ClearScreen();

                    const string attachCmd = "$attach";
                    interactive.SubmitCode(attachCmd);
                    app.OnDispose(() => {
                        if (app.Dte.Debugger.CurrentMode != EnvDTE.dbgDebugMode.dbgDesignMode)
                        {
                            app.DismissAllDialogs();
                            try {
                                app.ExecuteCommand("Debug.StopDebugging");
                            } catch (COMException) {
                            }
                            WaitForMode(app.Dte.Debugger, EnvDTE.dbgDebugMode.dbgDesignMode);
                        }
                    });

                    app.Dte.Debugger.Breakpoints.Add(File: "BreakpointTest.py", Line: 1);
                    interactive.WaitForText(">" + attachCmd, ">");

                    WaitForMode(app.Dte.Debugger, EnvDTE.dbgDebugMode.dbgRunMode);

                    interactive.Show();

                    const string import = "import BreakpointTest";
                    interactive.SubmitCode(import, wait: false);
                    interactive.WaitForText(">" + attachCmd, ">" + import, "");

                    WaitForMode(app.Dte.Debugger, EnvDTE.dbgDebugMode.dbgBreakMode);

                    Assert.AreEqual(EnvDTE.dbgEventReason.dbgEventReasonBreakpoint, app.Dte.Debugger.LastBreakReason);
                    Assert.AreEqual(app.Dte.Debugger.BreakpointLastHit.FileLine, 1);

                    app.ExecuteCommand("Debug.DetachAll");

                    WaitForMode(app.Dte.Debugger, EnvDTE.dbgDebugMode.dbgDesignMode);

                    interactive.WaitForText(">" + attachCmd, ">" + import, "hello", ">");
                }
            }
        }
Exemplo n.º 19
0
        public override void DoCommand(object sender, EventArgs args)
        {
            if (!Utilities.SaveDirtyFiles())
            {
                // Abort
                return;
            }

            // Launch with project context if there is one and it contains the active document
            // Fallback to using default python project
            var         file = CommonPackage.GetActiveTextView(_serviceProvider).GetFilePath();
            var         sln  = (IVsSolution)_serviceProvider.GetService(typeof(SVsSolution));
            IEnumerable projects;

            try {
                projects = _serviceProvider.GetDTE().ActiveSolutionProjects as IEnumerable;
            } catch (COMException) {
                // ActiveSolutionProjects can fail if Solution Explorer has not been loaded
                projects = Enumerable.Empty <EnvDTE.Project>();
            }

            var pythonProject = (projects == null ? null : projects.OfType <EnvDTE.Project>()
                                 .Select(p => p.GetPythonProject())
                                 .FirstOrDefault(p => p != null && p.FindNodeByFullPath(file) != null) as IPythonProject)
                                ?? new DefaultPythonProject(_serviceProvider, file);

            var launcher = PythonToolsPackage.GetLauncher(_serviceProvider, pythonProject);

            try {
                var launcher2 = launcher as IProjectLauncher2;
                if (launcher2 != null)
                {
                    launcher2.LaunchFile(
                        file,
                        CommandId == CommonConstants.StartDebuggingCmdId,
                        new LaunchFileProperties(
                            null,
                            PathUtils.GetParent(file),
                            pythonProject.GetInterpreterFactory().Configuration.PathEnvironmentVariable,
                            pythonProject.GetWorkingDirectory()
                            )
                        );
                }
                else
                {
                    launcher.LaunchFile(file, CommandId == CommonConstants.StartDebuggingCmdId);
                }
            } catch (MissingInterpreterException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            } catch (NoInterpretersException ex) {
                PythonToolsPackage.OpenNoInterpretersHelpPage(_serviceProvider, ex.HelpPage);
            }
        }
Exemplo n.º 20
0
        private bool EnsureInterpretersAvailable()
        {
            var registry = _serviceProvider.GetComponentModel().GetService <IInterpreterRegistryService>();

            if (registry.Configurations.Any())
            {
                return(true);
            }

            PythonToolsPackage.OpenNoInterpretersHelpPage(_serviceProvider);
            return(false);
        }
Exemplo n.º 21
0
        private void AddPerformanceSession(object sender, EventArgs e)
        {
            var    dte      = (EnvDTE.DTE)PythonToolsPackage.GetGlobalService(typeof(EnvDTE.DTE));
            string filename = "Performance.pyperf";
            bool   save     = false;

            if (dte.Solution.IsOpen && !String.IsNullOrEmpty(dte.Solution.FullName))
            {
                filename = Path.Combine(Path.GetDirectoryName(dte.Solution.FullName), filename);
                save     = true;
            }
            ShowPerformanceExplorer().Sessions.AddTarget(new ProfilingTarget(), filename, save);
        }
Exemplo n.º 22
0
 internal void GotoSource(IServiceProvider serviceProvider)
 {
     if (File.Exists(_filePath))
     {
         PythonToolsPackage.NavigateTo(
             serviceProvider,
             _filePath,
             Guid.Empty,
             Line - 1,
             Column - 1
             );
     }
 }
Exemplo n.º 23
0
        private static void ProfileProject(SessionNode session, PythonProjectNode project, bool openReport, bool useVTune)
        {
            LaunchConfiguration config = null;

            try {
                config = project?.GetLaunchConfigurationOrThrow();
            } catch (NoInterpretersException ex) {
                PythonToolsPackage.OpenNoInterpretersHelpPage(session._serviceProvider, ex.HelpPage);
                return;
            } catch (MissingInterpreterException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle);
                return;
            } catch (IOException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle);
                return;
            }
            if (config == null)
            {
                MessageBox.Show(Strings.ProjectInterpreterNotFound.FormatUI(project.GetNameProperty()), Strings.ProductTitle);
                return;
            }

            if (string.IsNullOrEmpty(config.ScriptName))
            {
                MessageBox.Show(Strings.NoProjectStartupFile, Strings.ProductTitle);
                return;
            }

            if (string.IsNullOrEmpty(config.WorkingDirectory) || config.WorkingDirectory == ".")
            {
                config.WorkingDirectory = project.ProjectHome;
                if (string.IsNullOrEmpty(config.WorkingDirectory))
                {
                    config.WorkingDirectory = Path.GetDirectoryName(config.ScriptName);
                }
            }

#if EXTERNAL_PROFILER_DRIVER
            if (useVTune)
            {
                RunVTune(session, config, openReport);
            }
            else
            {
#endif
            RunProfiler(session, config, openReport);
#if EXTERNAL_PROFILER_DRIVER
        }
#endif
        }
Exemplo n.º 24
0
        public override void LoadSettingsFromStorage()
        {
            var model        = (IComponentModel)PythonToolsPackage.GetGlobalService(typeof(SComponentModel));
            var interpreters = model.GetAllPythonInterpreterFactories();

            _options.Clear();
            foreach (var interpreter in interpreters)
            {
                string interpreterId = interpreter.GetInterpreterPath() + "\\";

                _options[interpreter] =
                    ReadOptions(interpreterId);
            }
        }
Exemplo n.º 25
0
 public void Navigate(INavigableRelationship relationship)
 {
     try {
         PythonToolsPackage.NavigateTo(
             _serviceProvider,
             Variable.Location.FilePath,
             Guid.Empty,
             Variable.Location.StartLine - 1,
             Variable.Location.StartColumn - 1
             );
     } catch (Exception ex) when(!ex.IsCriticalException())
     {
         MessageBox.Show(Strings.CannotGoToDefn_Name.FormatUI(SymbolSpan.GetText()), Strings.ProductTitle);
     }
 }
Exemplo n.º 26
0
 public void Navigate(INavigableRelationship relationship)
 {
     try {
         PythonToolsPackage.NavigateTo(
             _serviceProvider,
             CommonUtils.GetLocalFilePath(VariableLocation.Uri),
             Guid.Empty,
             VariableLocation.Range.Start.Line,
             VariableLocation.Range.Start.Character
             );
     } catch (Exception ex) when(!ex.IsCriticalException())
     {
         MessageBox.Show(Strings.CannotGoToDefn_Name.FormatUI(SymbolSpan.GetText()), Strings.ProductTitle);
     }
 }
Exemplo n.º 27
0
        public static ExecutionMode[] GetRegisteredModes(IServiceProvider serviceProvider)
        {
            List <ExecutionMode> res = new List <ExecutionMode>();

            // ExecutionMode is structured like:
            // HKLM\Software\VisualStudio\Hive\PythonTools:
            //      ReplExecutionModes\
            //          ModeID\
            //              Type
            //              FriendlyName
            //              SupportsMultipleScopes
            //              SupportsMultipleCompleteStatementInputs
            //
            var settingsManager = PythonToolsPackage.GetSettings(serviceProvider);
            var store           = settingsManager.GetReadOnlySettingsStore(SettingsScope.Configuration);
            var itemCount       = store.GetSubCollectionCount(PythonInteractiveOptionsControl.PythonExecutionModeKey);

            foreach (string modeID in store.GetSubCollectionNames(PythonInteractiveOptionsControl.PythonExecutionModeKey))
            {
                var  value = store.GetString(PythonInteractiveOptionsControl.PythonExecutionModeKey + "\\" + modeID, "SupportsMultipleScopes", "True");
                bool multipleScopes;
                if (!Boolean.TryParse(value, out multipleScopes))
                {
                    multipleScopes = true;
                }

                value = store.GetString(PythonInteractiveOptionsControl.PythonExecutionModeKey + "\\" + modeID, "SupportsMultipleCompleteStatementInputs", "True");
                bool supportsMultipleCompleteStatementInputs;
                if (!Boolean.TryParse(value, out supportsMultipleCompleteStatementInputs))
                {
                    supportsMultipleCompleteStatementInputs = false;
                }

                var type         = store.GetString(PythonInteractiveOptionsControl.PythonExecutionModeKey + "\\" + modeID, "Type");
                var friendlyName = store.GetString(PythonInteractiveOptionsControl.PythonExecutionModeKey + "\\" + modeID, "FriendlyName");
                res.Add(
                    new ExecutionMode(
                        modeID,
                        type,
                        friendlyName,
                        multipleScopes,
                        supportsMultipleCompleteStatementInputs
                        )
                    );
            }
            res.Sort((x, y) => String.Compare(x.FriendlyName, y.FriendlyName, true));
            return(res.ToArray());
        }
Exemplo n.º 28
0
        public override int DebugLaunch(uint flags)
        {
            if (_project.ShouldWarnOnLaunch)
            {
                var pyService = ProjectMgr.Site.GetPythonToolsService();
                if (pyService.DebuggerOptions.PromptBeforeRunningWithBuildError)
                {
                    var res = new StartWithErrorsDialog(pyService).ShowDialog();
                    if (res == DialogResult.No)
                    {
                        return(VSConstants.S_OK);
                    }
                }
            }

            string errorMessage = null;

            try {
                return(base.DebugLaunch(flags));
            } catch (MissingInterpreterException ex) {
                if (_project.ActiveInterpreter == _project.InterpreterRegistry.NoInterpretersValue)
                {
                    PythonToolsPackage.OpenNoInterpretersHelpPage(ProjectMgr.Site, ex.HelpPage);
                }
                else
                {
                    errorMessage = ex.Message;
                }
            } catch (NoInterpretersException ex) {
                PythonToolsPackage.OpenNoInterpretersHelpPage(ProjectMgr.Site, ex.HelpPage);
            } catch (ArgumentException ex) {
                errorMessage = ex.Message;
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                var td = new TaskDialog(ProjectMgr.Site)
                {
                    Title           = Strings.ProductTitle,
                    MainInstruction = Strings.FailedToLaunchDebugger,
                    Content         = errorMessage
                };
                td.Buttons.Add(TaskDialogButton.Close);
                td.ShowModal();
            }

            return(VSConstants.S_OK);
        }
Exemplo n.º 29
0
            private void OnNavigate(object sender, EventArgs e)
            {
                var task = sender as ErrorTask;

                if (task != null)
                {
                    string document;
                    try {
                        document = PathUtils.GetAbsoluteFilePath(_workingDirectory, task.Document);
                    } catch (ArgumentException) {
                        // If it's not a valid path, then it's not a navigable error item.
                        return;
                    }
                    PythonToolsPackage.NavigateTo(_serviceProvider, document, Guid.Empty, task.Line, task.Column < 0 ? 0 : task.Column);
                }
            }
Exemplo n.º 30
0
        private void QueryStatusMethod(object sender, EventArgs args)
        {
            var oleMenu = sender as OleMenuCommand;
            VsProjectAnalyzer analyzer;
            var    interpreterService = _serviceProvider.GetComponentModel().GetService <IInterpreterOptionsService>();
            string filename, dir;

            if (!PythonToolsPackage.TryGetStartupFileAndDirectory(_serviceProvider, out filename, out dir, out analyzer) ||
                interpreterService == null ||
                interpreterService.NoInterpretersValue == analyzer.InterpreterFactory)
            {
                // no interpreters installed, disable the command.
                oleMenu.Visible   = true;
                oleMenu.Enabled   = false;
                oleMenu.Supported = true;
            }
            else
            {
                IWpfTextView textView;
                var          pyProj = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;
                var          window = (IReplWindow)EnsureReplWindow(_serviceProvider, analyzer, pyProj);
                if (pyProj != null)
                {
                    // startup project, enabled in Start in REPL mode.
                    oleMenu.Visible   = true;
                    oleMenu.Enabled   = true;
                    oleMenu.Supported = true;
                    oleMenu.Text      = "Execute Project in P&ython Interactive";
                }
                else if ((textView = CommonPackage.GetActiveTextView(_serviceProvider)) != null &&
                         textView.TextBuffer.ContentType == _serviceProvider.GetPythonContentType())
                {
                    // enabled in Execute File mode...
                    oleMenu.Visible   = true;
                    oleMenu.Enabled   = true;
                    oleMenu.Supported = true;
                    oleMenu.Text      = "Execute File in P&ython Interactive";
                }
                else
                {
                    oleMenu.Visible   = false;
                    oleMenu.Enabled   = false;
                    oleMenu.Supported = false;
                }
            }
        }
Exemplo n.º 31
0
 public PythonLibraryManager(PythonToolsPackage/*!*/ package)
     : base(package) {
     _package = package;
 }
Exemplo n.º 32
0
 public PythonWebProjectFactory(PythonToolsPackage package) {
     _package = package;
 }