Example #1
0
        public void Invoke(CancellationToken cancellationToken)
        {
            if (_textDocument == null)
            {
                return;
            }

            var codeStreamService = ComponentModel?.GetService <ICodeStreamService>();

            if (codeStreamService == null)
            {
                return;
            }

            ThreadHelper.JoinableTaskFactory.Run(async delegate {
                try {
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                    var toolWindowProvider = Package.GetGlobalService(typeof(SToolWindowProvider)) as IToolWindowProvider;
                    toolWindowProvider?.ShowToolWindowSafe(Guids.WebViewToolWindowGuid);

                    _ = codeStreamService.NewCodemarkAsync(_textDocument.FilePath.ToUri(), _textSelection.Range, CodemarkType, "Lightbulb Menu", cancellationToken: cancellationToken);
                }
                catch (Exception ex) {
                    Log.Error(ex, nameof(CodemarkSuggestedActionBase));
                }
            });
        }
Example #2
0
        public void Invoke(CancellationToken cancellationToken)
        {
            if (_virtualTextDocument == null)
            {
                return;
            }

            var codeStreamService = ComponentModel?.GetService <ICodeStreamService>();

            if (codeStreamService == null)
            {
                return;
            }

            ThreadHelper.JoinableTaskFactory.Run(async delegate {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                try {
                    var toolWindowProvider = Package.GetGlobalService(typeof(SToolWindowProvider)) as IToolWindowProvider;
                    if (!toolWindowProvider.IsVisible(Guids.WebViewToolWindowGuid))
                    {
                        if (toolWindowProvider?.ShowToolWindowSafe(Guids.WebViewToolWindowGuid) == true)
                        {
                        }
                        else
                        {
                            Log.Warning("Could not activate tool window");
                        }
                    }
                    var sessionService = ComponentModel.GetService <ISessionService>();
                    if (sessionService.WebViewDidInitialize == true)
                    {
                        var editorState = _wpfTextView.GetEditorState();
                        _ = codeStreamService.NewCodemarkAsync(_virtualTextDocument.Uri, editorState?.Range, CodemarkType, "Lightbulb Menu", cancellationToken: cancellationToken);
                    }
                    else
                    {
                        var eventAggregator = ComponentModel.GetService <IEventAggregator>();
                        IDisposable d       = null;
                        d = eventAggregator.GetEvent <WebviewDidInitializeEvent>().Subscribe(e => {
                            try {
                                var editorState = _wpfTextView.GetEditorState();
                                _ = codeStreamService.NewCodemarkAsync(_virtualTextDocument.Uri, editorState?.Range, CodemarkType, "Lightbulb Menu", cancellationToken: cancellationToken); d.Dispose();
                            }
                            catch (Exception ex) {
                                Log.Error(ex, $"{nameof(CodemarkSuggestedActionBase)} event");
                            }
                        });
                    }
                }
                catch (Exception ex) {
                    Log.Error(ex, nameof(CodemarkSuggestedActionBase));
                }
            });
        }
Example #3
0
        internal static TService GetMefService <TService>() where TService : class
        {
            var mefService = ThreadHelper.JoinableTaskFactory.Run(async delegate
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                return((TService)ComponentModel?.GetService <TService>());
            });

            Debug.Assert(mefService != null);

            return(mefService);
        }
Example #4
0
        public int GetTextViewFilter(
            IVsIntellisenseHost intellisenseHost,
            IOleCommandTarget nextCmdTarget,
            out IVsTextViewFilter textViewFilter)
        {
            var wpfTextView = GetViewFromIVsIntellisenseHost(intellisenseHost);

            if (wpfTextView == null)
            {
                textViewFilter = null;
                return(VSConstants.E_FAIL);
            }

            var commandHandlerServiceFactory = ComponentModel.GetService <ICommandHandlerServiceFactory>();

            textViewFilter = new VenusCommandFilter <TPackage, TLanguageService>(_languageService, wpfTextView, commandHandlerServiceFactory, SubjectBuffer, nextCmdTarget, _editorAdaptersFactoryService);

            return(VSConstants.S_OK);
        }
Example #5
0
        int IVsTextViewFilter.GetPairExtents(int iLine, int iIndex, TextSpan[] pSpan)
        {
            try
            {
                var result = VSConstants.S_OK;
                ComponentModel.GetService <IUIThreadOperationExecutor>().Execute(
                    "Intellisense",
                    defaultDescription: "",
                    allowCancellation: true,
                    showProgress: false,
                    action: c => result = GetPairExtentsWorker(iLine, iIndex, pSpan, c.UserCancellationToken));

                return(result);
            }
            catch (Exception e) when(FatalError.ReportAndCatch(e) && false)
            {
                throw ExceptionUtilities.Unreachable;
            }
        }
        /////////////////////////////////////////////////////////////////////////////
        // Overridden Package Implementation
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            packageInstaller     = ComponentModel.GetService <IVsPackageInstaller>();
            pkgInstallerServices = ComponentModel.GetService <IVsPackageInstallerServices>();
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            var mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;

            if (null != mcs)
            {
                // Create the command for the menu item.
                var cSharpProjContextAddReferenceCommandId = new CommandID(GuidList.guidVSServiceStackCmdSet, (int)PkgCmdIDList.cmdidCSharpAddServiceStackReference);
                var cSharpProjectAddReferenceMenuCommand   = new OleMenuCommand(CSharpAddReferenceCallback, cSharpProjContextAddReferenceCommandId);
                cSharpProjectAddReferenceMenuCommand.BeforeQueryStatus += CSharpQueryAddMenuItem;
                mcs.AddCommand(cSharpProjectAddReferenceMenuCommand);

                var fSharpProjContextAddReferenceCommandId = new CommandID(GuidList.guidVSServiceStackCmdSet, (int)PkgCmdIDList.cmdidFSharpAddServiceStackReference);
                var fSharpProjectContextOleMenuCommand     = new OleMenuCommand(FSharpAddReferenceCallback, fSharpProjContextAddReferenceCommandId);
                fSharpProjectContextOleMenuCommand.BeforeQueryStatus += FSharpQueryAddMenuItem;
                mcs.AddCommand(fSharpProjectContextOleMenuCommand);

                var vbNetProjContextAddReferenceCommandId = new CommandID(GuidList.guidVSServiceStackCmdSet, (int)PkgCmdIDList.cmdidVbNetAddServiceStackReference);
                var vbNetProjectContextOleMenuCommand     = new OleMenuCommand(VbNetAddReferenceCallback, vbNetProjContextAddReferenceCommandId);
                vbNetProjectContextOleMenuCommand.BeforeQueryStatus += VbNetQueryAddMenuItem;
                mcs.AddCommand(vbNetProjectContextOleMenuCommand);

                var typeScriptProjContextAddReferenceCommandId = new CommandID(GuidList.guidVSServiceStackCmdSet, (int)PkgCmdIDList.cmdidTypeScriptAddServiceStackReference);
                var typeScriptProjectContextOleMenuCommand     = new OleMenuCommand(TypeScriptAddReferenceCallback, typeScriptProjContextAddReferenceCommandId);
                typeScriptProjectContextOleMenuCommand.BeforeQueryStatus += TypeScriptQueryAddMenuItem;
                mcs.AddCommand(typeScriptProjectContextOleMenuCommand);

                var updateReferenceCommandId   = new CommandID(GuidList.guidVSServiceStackCmdSet, (int)PkgCmdIDList.cmdidUpdateServiceStackReference);
                var updateReferenceMenuCommand = new OleMenuCommand(UpdateReferenceCallback,
                                                                    updateReferenceCommandId);
                updateReferenceMenuCommand.BeforeQueryStatus += QueryUpdateMenuItem;
                mcs.AddCommand(updateReferenceMenuCommand);
            }

            solutionEventsListener = new SolutionEventsListener();
            solutionEventsListener.OnAfterOpenSolution += SolutionLoaded;
        }
Example #7
0
        internal IPythonInterpreterFactory GetDefaultInterpreter(IPythonInterpreterFactory[] factories)
        {
            IPythonInterpreterFactory lastInterpreter = null, defaultInterpreter = null;

            foreach (var interpreter in factories)
            {
                lastInterpreter = interpreter;

                if (interpreter.Id == InterpreterOptionsPage.DefaultInterpreter &&
                    interpreter.Configuration.Version == InterpreterOptionsPage.DefaultInterpreterVersion)
                {
                    defaultInterpreter = interpreter;
                    break;
                }
            }

            if (defaultInterpreter == null && lastInterpreter != null)
            {
                // default interpreter not configured, just select the last one and make it the default.
                defaultInterpreter = lastInterpreter;
                InterpreterOptionsPage.DefaultInterpreter        = defaultInterpreter.Id;
                InterpreterOptionsPage.DefaultInterpreterVersion = defaultInterpreter.Configuration.Version;
                InterpreterOptionsPage.SaveSettingsToStorage();
            }

            if (defaultInterpreter == null)
            {
                // no interpreters installed, create a default interpreter for analysis
                if (_noInterpretersFactory == null)
                {
                    _noInterpretersFactory = ComponentModel.GetService <IDefaultInterpreterFactoryCreator>().CreateInterpreterFactory(
                        new Dictionary <InterpreterFactoryOptions, object>()
                    {
                        { InterpreterFactoryOptions.Description, "Python 2.7 - No Interpreters Installed" },
                        { InterpreterFactoryOptions.Guid, _noInterpretersFactoryGuid }
                    }
                        );
                }
                defaultInterpreter = _noInterpretersFactory;
            }

            return(defaultInterpreter);
        }
Example #8
0
        private int GetPairExtentsWorker(
            int iLine,
            int iIndex,
            TextSpan[] pSpan,
            CancellationToken cancellationToken
            )
        {
            var braceMatcher = ComponentModel.GetService <IBraceMatchingService>();

            return(GetPairExtentsWorker(
                       WpfTextView,
                       braceMatcher,
                       iLine,
                       iIndex,
                       pSpan,
                       (VSConstants.VSStd2KCmdID) this.CurrentlyExecutingCommand
                       == VSConstants.VSStd2KCmdID.GOTOBRACE_EXT,
                       cancellationToken
                       ));
        }
        protected override async Task LoadComponentsAsync(CancellationToken cancellationToken)
        {
            var workspace = ComponentModel.GetService <VisualStudioWorkspace>();

            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            // Ensure the nuget package services are initialized. This initialization pass will only run
            // once our package is loaded indirectly through a legacy COM service we proffer (like the legacy project systems
            // loading us) or through something like the IVsEditorFactory or a debugger service. Right now it's fine
            // we only load this there, because we only use these to provide code fixes. But we only show code fixes in
            // open files, and so you would have had to open a file, which loads the editor factory, which loads our package,
            // which will run this.
            //
            // This code will have to be moved elsewhere once any of that load path is changed such that the package
            // no longer loads if a file is opened.
            _packageInstallerService = workspace.Services.GetService <IPackageInstallerService>() as PackageInstallerService;
            _symbolSearchService     = workspace.Services.GetService <ISymbolSearchService>() as VisualStudioSymbolSearchService;

            _packageInstallerService?.Connect(this.RoslynLanguageName);
            _symbolSearchService?.Connect(this.RoslynLanguageName);
        }
Example #10
0
        int IVsTextViewFilter.GetPairExtents(int iLine, int iIndex, TextSpan[] pSpan)
        {
            try
            {
                var result = VSConstants.S_OK;
                ComponentModel
                .GetService <IWaitIndicator>()
                .Wait(
                    "Intellisense",
                    allowCancel: true,
                    action: c =>
                    result = GetPairExtentsWorker(iLine, iIndex, pSpan, c.CancellationToken)
                    );

                return(result);
            }
            catch (Exception e) when(FatalError.ReportAndCatch(e) && false)
            {
                throw ExceptionUtilities.Unreachable;
            }
        }
        public int GetMemberNavigationPoint(string pszClassName, string pszUniqueMemberID, TextSpan[] pSpanNavPoint, out uint pItemID)
        {
            uint     itemId    = 0;
            TextSpan textSpan  = default;
            var      succeeded = false;

            var uiThreadOperationExecutor = ComponentModel.GetService <IUIThreadOperationExecutor>();

            uiThreadOperationExecutor.Execute(
                "Intellisense",
                defaultDescription: "",
                allowCancellation: false,
                showProgress: false,
                action: c =>
            {
                if (ContainedLanguageCodeSupport.TryGetMemberNavigationPoint(GetThisDocument(), GlobalOptions, pszClassName, pszUniqueMemberID, out textSpan, out var targetDocument, c.UserCancellationToken))
                {
                    succeeded = true;
                    itemId    = this.ContainedDocument.FindItemIdOfDocument(targetDocument);
                }
            });
Example #12
0
        internal PythonToolsService(IServiceContainer container)
        {
            _container = container;

            _langPrefs = new Lazy <LanguagePreferences>(() => new LanguagePreferences(this, typeof(PythonLanguageInfo).GUID));
            _interpreterOptionsService = new Lazy <IInterpreterOptionsService>(CreateInterpreterOptionsService);

            _optionsService = (IPythonToolsOptionsService)container.GetService(typeof(IPythonToolsOptionsService));

            _idleManager             = new IdleManager(container);
            _advancedOptions         = new Lazy <AdvancedEditorOptions>(CreateAdvancedEditorOptions);
            _debuggerOptions         = new Lazy <DebuggerOptions>(CreateDebuggerOptions);
            _generalOptions          = new Lazy <GeneralOptions>(CreateGeneralOptions);
            _surveyNews              = new Lazy <SurveyNewsService>(() => new SurveyNewsService(this));
            _suppressDialogOptions   = new Lazy <SuppressDialogOptions>(() => new SuppressDialogOptions(this));
            _interactiveOptions      = new Lazy <PythonInteractiveOptions>(() => CreateInteractiveOptions("Interactive"));
            _debugInteractiveOptions = new Lazy <PythonInteractiveOptions>(() => CreateInteractiveOptions("Debug Interactive Window"));
            _logger       = new PythonToolsLogger(ComponentModel.GetExtensions <IPythonToolsLogger>().ToArray());
            _entryService = ComponentModel.GetService <AnalysisEntryService>();

            _idleManager.OnIdle += OnIdleInitialization;
        }
Example #13
0
        protected override void Dispose(bool disposing)
        {
            if (!IsDisposed)
            {
                try {
                    ServiceProvider.GetUIThread().Invoke(() => {
                        var iwp = ComponentModel.GetService <InteractiveWindowProvider>();
                        if (iwp != null)
                        {
                            foreach (var w in iwp.AllOpenWindows)
                            {
                                w.InteractiveWindow.Close();
                            }
                        }
                    });
                } catch (Exception ex) {
                    Console.WriteLine("Error while closing all interactive windows");
                    Console.WriteLine(ex);
                }

                if (_deletePerformanceSessions)
                {
                    try {
                        dynamic profiling = Dte.GetObject("PythonProfiling");

                        for (dynamic session = profiling.GetSession(1);
                             session != null;
                             session = profiling.GetSession(1))
                        {
                            profiling.RemoveSession(session, true);
                        }
                    } catch (Exception ex) {
                        Console.WriteLine("Error while cleaning up profiling sessions");
                        Console.WriteLine(ex);
                    }
                }
            }
            base.Dispose(disposing);
        }
Example #14
0
        private async Task LoadInteractiveMenusAsync(CancellationToken cancellationToken)
        {
            // Obtain services and QueryInterface from the main thread
            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            var menuCommandService = (OleMenuCommandService) await GetServiceAsync(typeof(IMenuCommandService)).ConfigureAwait(true);

            var monitorSelectionService = (IVsMonitorSelection) await GetServiceAsync(typeof(SVsShellMonitorSelection)).ConfigureAwait(true);

            // Switch to the background object for constructing commands
            await TaskScheduler.Default;

            var threadingContext = ComponentModel.GetService <IThreadingContext>();

            await new CSharpResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel, threadingContext)
            .InitializeResetInteractiveFromProjectCommandAsync()
            .ConfigureAwait(true);

            await new VisualBasicResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel, threadingContext)
            .InitializeResetInteractiveFromProjectCommandAsync()
            .ConfigureAwait(true);
        }
Example #15
0
        private void InitializeLogging()
        {
            try {
                var registry = ComponentModel.GetService <IInterpreterRegistryService>();
                if (registry != null)
                {
                    // not available in some test cases...
                    // log interesting stats on startup
                    var installed   = registry.Configurations.Count();
                    var installedV2 = registry.Configurations.Count(c => c.Version.Major == 2);
                    var installedV3 = registry.Configurations.Count(c => c.Version.Major == 3);

                    Logger.LogEvent(PythonLogEvent.InstalledInterpreters, new Dictionary <string, object> {
                        { "Total", installed },
                        { "3x", installedV3 },
                        { "2x", installedV2 },
                    });
                }
            } catch (Exception ex) {
                Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
            }
        }
        private List <OpenReplCommand> GetReplCommands()
        {
            var replCommands       = new List <OpenReplCommand>();
            var interpreterService = ComponentModel.GetService <IInterpreterOptionsService>();
            var factories          = interpreterService.Interpreters.ToList();

            if (factories.Count == 0)
            {
                return(replCommands);
            }

            var defaultFactory = interpreterService.DefaultInterpreter;

            if (defaultFactory != interpreterService.NoInterpretersValue)
            {
                factories.Remove(defaultFactory);
                factories.Insert(0, defaultFactory);
            }

            for (int i = 0; i < (PkgCmdIDList.cmdidReplWindowF - PkgCmdIDList.cmdidReplWindow) && i < factories.Count; i++)
            {
                var factory = factories[i];

                var cmd = new OpenReplCommand(this, (int)PkgCmdIDList.cmdidReplWindow + i, factory);
                replCommands.Add(cmd);
            }

            if (defaultFactory != interpreterService.NoInterpretersValue)
            {
                // This command is a fallback for the Python.Interactive command
                // If no project is selected, the default environment will be
                // used.
                replCommands.Add(new OpenReplCommand(this, (int)PythonConstants.OpenInteractiveForEnvironment, defaultFactory));
            }
            return(replCommands);
        }
Example #17
0
 private void InitializeColors()
 {
     // Initialize ColorSchemeName support
     _colorSchemeApplier = ComponentModel.GetService <ColorSchemeApplier>();
     _colorSchemeApplier.Initialize();
 }
Example #18
0
 protected override VisualStudioWorkspaceImpl CreateWorkspace() => ComponentModel.GetService <VisualStudioWorkspaceImpl>();
Example #19
0
        private void FormatDocumentCreatedFromTemplate(IVsHierarchy hierarchy, uint itemid, string filePath, CancellationToken cancellationToken)
        {
            // A file has been created on disk which the user added from the "Add Item" dialog. We need
            // to include this in a workspace to figure out the right options it should be formatted with.
            // This requires us to place it in the correct project.
            var workspace = ComponentModel.GetService <VisualStudioWorkspace>();
            var solution  = workspace.CurrentSolution;

            ProjectId projectIdToAddTo = null;

            foreach (var projectId in solution.ProjectIds)
            {
                if (workspace.GetHierarchy(projectId) == hierarchy)
                {
                    projectIdToAddTo = projectId;
                    break;
                }
            }

            if (projectIdToAddTo == null)
            {
                // We don't have a project for this, so we'll just make up a fake project altogether
                var temporaryProject = solution.AddProject(
                    name: nameof(FormatDocumentCreatedFromTemplate),
                    assemblyName: nameof(FormatDocumentCreatedFromTemplate),
                    language: LanguageName);

                solution         = temporaryProject.Solution;
                projectIdToAddTo = temporaryProject.Id;
            }

            var documentId     = DocumentId.CreateNewId(projectIdToAddTo);
            var forkedSolution = solution.AddDocument(DocumentInfo.Create(documentId, filePath, loader: new FileTextLoader(filePath, defaultEncoding: null), filePath: filePath));
            var addedDocument  = forkedSolution.GetDocument(documentId);

            var rootToFormat = addedDocument.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);

            var formattedTextChanges = Formatter.GetFormattedTextChanges(rootToFormat, workspace, addedDocument.Options, cancellationToken);
            var formattedText        = addedDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).WithChanges(formattedTextChanges);

            // Ensure the line endings are normalized. The formatter doesn't touch everything if it doesn't need to.
            string targetLineEnding = addedDocument.Options.GetOption(FormattingOptions.NewLine);

            var originalText = formattedText;

            foreach (var originalLine in originalText.Lines)
            {
                string originalNewLine = originalText.ToString(CodeAnalysis.Text.TextSpan.FromBounds(originalLine.End, originalLine.EndIncludingLineBreak));

                // Check if we have a line ending, so we don't go adding one to the end if we don't need to.
                if (originalNewLine.Length > 0 && originalNewLine != targetLineEnding)
                {
                    var currentLine = formattedText.Lines[originalLine.LineNumber];
                    var currentSpan = CodeAnalysis.Text.TextSpan.FromBounds(currentLine.End, currentLine.EndIncludingLineBreak);
                    formattedText = formattedText.WithChanges(new TextChange(currentSpan, targetLineEnding));
                }
            }

            IOUtilities.PerformIO(() =>
            {
                using (var textWriter = new StreamWriter(filePath, append: false, encoding: formattedText.Encoding))
                {
                    // We pass null here for cancellation, since cancelling in the middle of the file write would leave the file corrupted
                    formattedText.Write(textWriter, cancellationToken: CancellationToken.None);
                }
            });
        }
Example #20
0
        protected override void Initialize()
        {
            base.Initialize();

            Store = ComponentModel.GetService <IEmojiStore>();
        }
        protected int GetDataTipTextImpl(ITextBuffer subjectBuffer, TextSpan[] pSpan, out string pbstrText)
        {
            pbstrText = null;

            var vsBuffer = EditorAdaptersFactory.GetBufferAdapter(subjectBuffer);

            // TODO: broken in REPL
            if (vsBuffer == null)
            {
                return(VSConstants.E_FAIL);
            }

            using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_GetDataTipText, CancellationToken.None))
            {
                pbstrText = null;
                if (pSpan == null || pSpan.Length != 1)
                {
                    return(VSConstants.E_INVALIDARG);
                }

                var    result            = VSConstants.E_FAIL;
                string pbstrTextInternal = null;

                var uiThreadOperationExecutor = ComponentModel.GetService <IUIThreadOperationExecutor>();
                uiThreadOperationExecutor.Execute(
                    title: ServicesVSResources.Debugger,
                    defaultDescription: ServicesVSResources.Getting_DataTip_text,
                    allowCancellation: true,
                    showProgress: false,
                    action: context =>
                {
                    IServiceProvider serviceProvider = ComponentModel.GetService <SVsServiceProvider>();
                    var debugger  = (IVsDebugger)serviceProvider.GetService(typeof(SVsShellDebugger));
                    var debugMode = new DBGMODE[1];

                    var cancellationToken = context.UserCancellationToken;
                    if (ErrorHandler.Succeeded(debugger.GetMode(debugMode)) && debugMode[0] != DBGMODE.DBGMODE_Design)
                    {
                        var textSpan = pSpan[0];

                        var textSnapshot = subjectBuffer.CurrentSnapshot;
                        var document     = textSnapshot.GetOpenDocumentInCurrentContextWithChanges();

                        if (document != null)
                        {
                            var languageDebugInfo = document.Project.LanguageServices.GetService <ILanguageDebugInfoService>();
                            if (languageDebugInfo != null)
                            {
                                var spanOpt = textSnapshot.TryGetSpan(textSpan);
                                if (spanOpt.HasValue)
                                {
                                    var dataTipInfo = languageDebugInfo.GetDataTipInfoAsync(document, spanOpt.Value.Start, cancellationToken).WaitAndGetResult(cancellationToken);
                                    if (!dataTipInfo.IsDefault)
                                    {
                                        var resultSpan = dataTipInfo.Span.ToSnapshotSpan(textSnapshot);
                                        var textOpt    = dataTipInfo.Text;

                                        pSpan[0] = resultSpan.ToVsTextSpan();
                                        result   = debugger.GetDataTipValue((IVsTextLines)vsBuffer, pSpan, textOpt, out pbstrTextInternal);
                                    }
                                }
                            }
                        }
                    }
                });

                pbstrText = pbstrTextInternal;
                return(result);
            }
        }
 public static TServiceInterface GetComponentModelService <TServiceInterface>() where TServiceInterface : class
 {
     return(ComponentModel.GetService <TServiceInterface>());
 }
Example #23
0
        /////////////////////////////////////////////////////////////////////////////
        // Overriden Package Implementation

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initilaization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Trace.WriteLine("Entering Initialize() of: {0}".FormatUI(this));
            base.Initialize();

            var services = (IServiceContainer)this;

            // register our options service which provides registry access for various options
            services.AddService(typeof(IPythonToolsOptionsService), PythonToolsOptionsService.CreateService, promote: true);

            services.AddService(typeof(IClipboardService), new ClipboardService(), promote: true);

            services.AddService(typeof(IPythonToolsToolWindowService), this, promote: true);

            // register our PythonToolsService which provides access to core PTVS functionality
            PythonToolsService pyService;

            try {
                pyService = _pyService = new PythonToolsService(services);
            } catch (Exception ex) when(!ex.IsCriticalException())
            {
                ex.ReportUnhandledException(services, GetType(), allowUI: false);
                throw;
            }

            services.AddService(typeof(PythonToolsService), pyService, promote: true);

            _autoObject = new PythonAutomation(this);

            services.AddService(
                typeof(ErrorTaskProvider),
                (container, serviceType) => {
                var errorList     = GetService(typeof(SVsErrorList)) as IVsTaskList;
                var model         = ComponentModel;
                var errorProvider = model != null ? model.GetService <IErrorProviderFactory>() : null;
                return(new ErrorTaskProvider(this, errorList, errorProvider));
            },
                promote: true);

            services.AddService(
                typeof(CommentTaskProvider),
                (container, serviceType) => {
                var taskList      = GetService(typeof(SVsTaskList)) as IVsTaskList;
                var model         = ComponentModel;
                var errorProvider = model != null ? model.GetService <IErrorProviderFactory>() : null;
                return(new CommentTaskProvider(this, taskList, errorProvider));
            },
                promote: true);


            var solutionEventListener = new SolutionEventsListener(this);

            solutionEventListener.StartListeningForChanges();

            services.AddService(
                typeof(SolutionEventsListener),
                solutionEventListener,
                promote: true
                );

            // Register custom debug event service
            var customDebuggerEventHandler = new CustomDebuggerEventHandler(this);

            services.AddService(customDebuggerEventHandler.GetType(), customDebuggerEventHandler, promote: true);

            // Enable the mixed-mode debugger UI context
            UIContext.FromUIContextGuid(DkmEngineId.NativeEng).IsActive = true;

            // Add our command handlers for menu (commands must exist in the .vsct file)
            RegisterCommands(new Command[] {
                new OpenReplCommand(this, (int)PkgCmdIDList.cmdidReplWindow),
                new OpenReplCommand(this, (int)PythonConstants.OpenInteractiveForEnvironment),
                new OpenDebugReplCommand(this),
                new ExecuteInReplCommand(this),
                new SendToReplCommand(this),
                new StartWithoutDebuggingCommand(this),
                new StartDebuggingCommand(this),
                new FillParagraphCommand(this),
                new DiagnosticsCommand(this),
                new RemoveImportsCommand(this, true),
                new RemoveImportsCommand(this, false),
                new OpenInterpreterListCommand(this),
                new ImportWizardCommand(this),
                new SurveyNewsCommand(this),
                new ImportCoverageCommand(this),
                new ShowPythonViewCommand(this),
                new ShowCppViewCommand(this),
                new ShowNativePythonFrames(this),
                new UsePythonStepping(this),
                new AzureExplorerAttachDebuggerCommand(this),
            }, GuidList.guidPythonToolsCmdSet);


            // Enable the Python debugger UI context
            UIContext.FromUIContextGuid(AD7Engine.DebugEngineGuid).IsActive = true;

            var interpreters       = ComponentModel.GetService <IInterpreterRegistryService>();
            var interpreterService = ComponentModel.GetService <IInterpreterOptionsService>();

            // The variable is inherited by child processes backing Test Explorer, and is used in PTVS
            // test discoverer and test executor to connect back to VS.
            Environment.SetEnvironmentVariable("_PTVS_PID", Process.GetCurrentProcess().Id.ToString());

            Trace.WriteLine("Leaving Initialize() of: {0}".FormatUI(this));
        }
Example #24
0
        public TreeNode CreateVirtualEnvironment(EnvDTE.Project project, out string envName, out string envPath)
        {
            var environmentsNode = OpenSolutionExplorer().FindChildOfProject(project, Strings.Environments);

            environmentsNode.Select();

            using (var pss = new ProcessScope("python")) {
                using (var createVenv = AutomationDialog.FromDte(this, "Python.AddVirtualEnvironment")) {
                    envPath = new TextBox(createVenv.FindByAutomationId("VirtualEnvPath")).GetValue();
                    var baseInterp = new ComboBox(createVenv.FindByAutomationId("BaseInterpreter")).GetSelectedItemName();

                    var baseConfig = ComponentModel.GetService <IInterpreterRegistryService>().Configurations
                                     .FirstOrDefault(c => c.FullDescription == baseInterp);

                    if (baseConfig == null)
                    {
                        envName = "{0} ({1})".FormatUI(envPath, baseInterp);
                    }
                    else
                    {
                        envName = "{0} {1} {2} ({3})".FormatUI(
                            envPath,
                            baseConfig.Architecture == System.Reflection.ProcessorArchitecture.Amd64 ? "64-bit" : "32-bit",
                            baseConfig.Version,
                            baseInterp
                            );
                    }

                    Console.WriteLine("Expecting environment named: {0}", envName);

                    // Force a wait for the view to be updated.
                    var wnd = (DialogWindowVersioningWorkaround)HwndSource.FromHwnd(
                        new IntPtr(createVenv.Element.Current.NativeWindowHandle)
                        ).RootVisual;
                    wnd.Dispatcher.Invoke(() => {
                        var view = (AddVirtualEnvironmentView)wnd.DataContext;
                        return(view.UpdateInterpreter(view.BaseInterpreter));
                    }).Wait();

                    createVenv.ClickButtonByAutomationId("Create");
                    createVenv.ClickButtonAndClose("Close", nameIsAutomationId: true);
                }

                var nowRunning = pss.WaitForNewProcess(TimeSpan.FromMinutes(1));
                if (nowRunning == null || !nowRunning.Any())
                {
                    Assert.Fail("Failed to see python process start to create virtualenv");
                }
                foreach (var p in nowRunning)
                {
                    if (p.HasExited)
                    {
                        continue;
                    }
                    try {
                        p.WaitForExit(30000);
                    } catch (Win32Exception ex) {
                        Console.WriteLine("Error waiting for process ID {0}\n{1}", p.Id, ex);
                    }
                }
            }

            try {
                return(OpenSolutionExplorer().WaitForChildOfProject(project, Strings.Environments, envName));
            } finally {
                var text = GetOutputWindowText("General");
                if (!string.IsNullOrEmpty(text))
                {
                    Console.WriteLine("** Output Window text");
                    Console.WriteLine(text);
                    Console.WriteLine("***");
                    Console.WriteLine();
                }
            }
        }
        /////////////////////////////////////////////////////////////////////////////
        // Overriden Package Implementation

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initilaization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

            var services = (IServiceContainer)this;

            // register our options service which provides registry access for various options
            var optionsService = new PythonToolsOptionsService(this);

            services.AddService(typeof(IPythonToolsOptionsService), optionsService, promote: true);

            services.AddService(typeof(IClipboardService), new ClipboardService(), promote: true);

            services.AddService(typeof(IPythonToolsToolWindowService), this, promote: true);

            // register our PythonToolsService which provides access to core PTVS functionality
            var pyService = _pyService = new PythonToolsService(services);

            services.AddService(typeof(PythonToolsService), pyService, promote: true);

            _autoObject = new PythonAutomation(this);

            services.AddService(
                typeof(ErrorTaskProvider),
                (container, serviceType) => {
                var errorList     = GetService(typeof(SVsErrorList)) as IVsTaskList;
                var model         = ComponentModel;
                var errorProvider = model != null ? model.GetService <IErrorProviderFactory>() : null;
                return(new ErrorTaskProvider(this, errorList, errorProvider));
            },
                promote: true);

            services.AddService(
                typeof(CommentTaskProvider),
                (container, serviceType) => {
                var taskList      = GetService(typeof(SVsTaskList)) as IVsTaskList;
                var model         = ComponentModel;
                var errorProvider = model != null ? model.GetService <IErrorProviderFactory>() : null;
                return(new CommentTaskProvider(this, taskList, errorProvider));
            },
                promote: true);

            var solutionEventListener = new SolutionEventsListener(this);

            solutionEventListener.StartListeningForChanges();

            services.AddService(
                typeof(SolutionEventsListener),
                solutionEventListener,
                promote: true
                );

#if DEV11_OR_LATER
            // Register custom debug event service
            var customDebuggerEventHandler = new CustomDebuggerEventHandler(this);
            services.AddService(customDebuggerEventHandler.GetType(), customDebuggerEventHandler, promote: true);

            // Enable the mixed-mode debugger UI context
            UIContext.FromUIContextGuid(DkmEngineId.NativeEng).IsActive = true;
#endif

            // Add our command handlers for menu (commands must exist in the .vsct file)
            RegisterCommands(new Command[] {
                new OpenDebugReplCommand(this),
                new ExecuteInReplCommand(this),
                new SendToReplCommand(this),
                new StartWithoutDebuggingCommand(this),
                new StartDebuggingCommand(this),
                new FillParagraphCommand(this),
                new SendToDefiningModuleCommand(this),
                new DiagnosticsCommand(this),
                new RemoveImportsCommand(this),
                new RemoveImportsCurrentScopeCommand(this),
                new OpenInterpreterListCommand(this),
                new ImportWizardCommand(this),
                new SurveyNewsCommand(this),
#if DEV11_OR_LATER
                new ShowPythonViewCommand(this),
                new ShowCppViewCommand(this),
                new ShowNativePythonFrames(this),
                new UsePythonStepping(this),
#endif
            }, GuidList.guidPythonToolsCmdSet);

#if FEATURE_AZURE_REMOTE_DEBUG
            try {
                RegisterCommands(new Command[] {
                    new AzureExplorerAttachDebuggerCommand(this)
                }, GuidList.guidPythonToolsCmdSet);
            } catch (NotSupportedException) {
            }
#endif


            RegisterCommands(GetReplCommands(), GuidList.guidPythonToolsCmdSet);

            RegisterProjectFactory(new PythonWebProjectFactory(this));

#if DEV11_OR_LATER
            // Enable the Python debugger UI context
            UIContext.FromUIContextGuid(AD7Engine.DebugEngineGuid).IsActive = true;
#endif

            var interpreterService = ComponentModel.GetService <IInterpreterOptionsService>();
            interpreterService.InterpretersChanged       += RefreshReplCommands;
            interpreterService.DefaultInterpreterChanged += RefreshReplCommands;

            var loadedProjectProvider = interpreterService.KnownProviders
                                        .OfType <LoadedProjectInterpreterFactoryProvider>()
                                        .FirstOrDefault();
            // Ensure the provider is available - if not, you probably need to
            // rebuild or clean your experimental hive.
            Debug.Assert(loadedProjectProvider != null, "Expected LoadedProjectInterpreterFactoryProvider");
            if (loadedProjectProvider != null)
            {
                loadedProjectProvider.SetSolution((IVsSolution)GetService(typeof(SVsSolution)));
            }

            // The variable is inherited by child processes backing Test Explorer, and is used in PTVS
            // test discoverer and test executor to connect back to VS.
            Environment.SetEnvironmentVariable("_PTVS_PID", Process.GetCurrentProcess().Id.ToString());
        }