protected override ITextBuffer GetTextBufferForOpenDocument(string filePath)
        {
            if (filePath is null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            JoinableTaskContext.AssertUIThread();

            EnsureDocumentTableAdvised();

            // Check if the document is already open and initialized, and associate a buffer if possible.
            uint cookie;

            if (_runningDocumentTable.IsMonikerValid(filePath) &&
                ((cookie = _runningDocumentTable.GetDocumentCookie(filePath)) != VSConstants.VSCOOKIE_NIL) &&
                (_runningDocumentTable.GetDocumentFlags(cookie) & (uint)_VSRDTFLAGS4.RDT_PendingInitialization) == 0)
            {
                // GetDocumentData requires the UI thread
                var documentData = _runningDocumentTable.GetDocumentData(cookie);

                var textBuffer = documentData is not VsTextBuffer vsTextBuffer
                    ? null
                    : _editorAdaptersFactory.GetDocumentBuffer(vsTextBuffer);
                return(textBuffer);
            }

            return(null);
        }
Example #2
0
        ITextBuffer IInteractiveWindowEditorFactoryService.CreateAndActivateBuffer(IInteractiveWindow window)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            // create buffer adapter to support undo/redo:
            if (!window.Properties.TryGetProperty(typeof(IContentType), out IContentType contentType))
            {
                contentType = _contentTypeRegistry.GetContentType("text");
            }

            var bufferAdapter = _adapterFactory.CreateVsTextBufferAdapter((IOleServiceProvider)_provider, contentType);

            bufferAdapter.InitializeContent("", 0);

            var commandFilter = GetCommandFilter(window);

            if (commandFilter.currentBufferCommandHandler != null)
            {
                ((IVsPersistDocData)commandFilter.currentBufferCommandHandler).Close();
            }

            commandFilter.currentBufferCommandHandler = (IOleCommandTarget)bufferAdapter;

            return(_adapterFactory.GetDocumentBuffer(bufferAdapter));
        }
        private async Task <Manifest> GetManifestAsync(string configFilePath, IDependencies dependencies)
        {
            RunningDocumentTable rdt            = new RunningDocumentTable(ServiceProvider.GlobalProvider);
            IVsTextBuffer        textBuffer     = rdt.FindDocument(configFilePath) as IVsTextBuffer;
            ITextBuffer          documentBuffer = null;
            Manifest             manifest       = null;

            if (textBuffer != null)
            {
                IComponentModel componentModel = ServiceProvider.GlobalProvider.GetService(typeof(SComponentModel)) as IComponentModel;
                IVsEditorAdaptersFactoryService editorAdapterService = componentModel.GetService <IVsEditorAdaptersFactoryService>();

                documentBuffer = editorAdapterService.GetDocumentBuffer(textBuffer);
            }

            // If the documentBuffer is null, then libman.json is not open. In that case, we'll use the manifest as is.
            // If documentBuffer is not null, then libman.json file is open and could be dirty. So we'll get the contents for the manifest from the buffer.
            if (documentBuffer != null)
            {
                manifest = Manifest.FromJson(documentBuffer.CurrentSnapshot.GetText(), dependencies);
            }
            else
            {
                manifest = await Manifest.FromFileAsync(configFilePath, dependencies, CancellationToken.None).ConfigureAwait(false);
            }

            return(manifest);
        }
Example #4
0
        IVsEditorAdaptersFactoryService editorFactoryService = null; // null is not really necessary, but to keep the compiler happy...

        void ApplyToProvider(Func <IntPtr> docGetter, Action <NodeProvider> action)
        {
            var docData = docGetter();

            try
            {
                IVsTextLines textLines = Marshal.GetObjectForIUnknown(docData) as IVsTextLines;
                if (textLines == null)
                {
                    IVsTextBufferProvider vsTextBufferProvider = Marshal.GetObjectForIUnknown(docData) as IVsTextBufferProvider;
                    if (vsTextBufferProvider != null)
                    {
                        ErrorHandler.ThrowOnFailure(vsTextBufferProvider.GetTextBuffer(out textLines));
                    }
                }
                if (textLines != null)
                {
                    var          textBuffer = editorFactoryService.GetDocumentBuffer((IVsTextBuffer)textLines);
                    NodeProvider provider;
                    if (textBuffer.Properties.TryGetProperty <NodeProvider>(typeof(NodeProvider), out provider))
                    {
                        action(provider);
                    }
                }
            }
            finally
            {
                Marshal.Release(docData);
            }
        }
Example #5
0
        private ITextDocument GetTextDocument(RunningDocumentInfo info)
        {
            // Get vs buffer
            IVsTextBuffer docData;

            try {
                docData = info.DocData as IVsTextBuffer;
            }
            catch (Exception e) {
                Logger.LogWarn(e, "Error getting IVsTextBuffer for document {0}, skipping document", info.Moniker);
                return(null);
            }
            if (docData == null)
            {
                return(null);
            }

            // Get ITextDocument
            var textBuffer = _vsEditorAdaptersFactoryService.GetDocumentBuffer(docData);

            if (textBuffer == null)
            {
                return(null);
            }

            ITextDocument document;

            if (!_textDocumentFactoryService.TryGetTextDocument(textBuffer, out document))
            {
                return(null);
            }

            return(document);
        }
Example #6
0
        private ITextBuffer GetTextBuffer(IVsTextBuffer document)
        {
            IComponentModel componentModel = Shell.ServiceProvider.GlobalProvider.GetService(typeof(SComponentModel)) as IComponentModel;
            IVsEditorAdaptersFactoryService adapterService = componentModel.GetService <IVsEditorAdaptersFactoryService>();

            return(adapterService.GetDocumentBuffer(document));
        }
Example #7
0
        public ITextDocument FindActiveDocument()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            // Get the current doc frame, if there is one
            monitorSelection.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out var pvarValue);
            if (!(pvarValue is IVsWindowFrame frame))
            {
                return(null);
            }

            // Now get the doc data, which should also be a text buffer
            frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var docData);
            if (!(docData is IVsTextBuffer vsTextBuffer))
            {
                return(null);
            }

            // Finally, convert from the legacy VS editor interface to the new-style interface
            var textBuffer = editorAdapterService.GetDocumentBuffer(vsTextBuffer);

            ITextDocument newTextDocument = null;

            textBuffer?.Properties?.TryGetProperty(
                typeof(ITextDocument), out newTextDocument);

            return(newTextDocument);
        }
Example #8
0
        private IFileNode GetFileNodeForViewImpl(IVsTextView view)
        {
            IVsTextLines lines;

            if (ErrorHandler.Failed(view.GetBuffer(out lines)))
            {
                return(null);
            }

            var buffer = lines as IVsTextBuffer;

            if (buffer == null)
            {
                return(null);
            }

            return(GetFileNodeForBuffer(bufferAdapterService.GetDocumentBuffer(buffer)));
        }
Example #9
0
        public void UpdateText(IReadOnlyList <TextChange> changes)
        {
            var buffer = _editorAdaptersFactoryService.GetDocumentBuffer(_textLines);

            if (buffer is null)
            {
                return;
            }
            TextEditApplication.UpdateText(changes.ToImmutableArray(), buffer, EditOptions.DefaultMinimalChange);
        }
        private ITextBuffer TextBufferFromCookie(uint docCookie)
        {
            var bufferAdapter = _runningDocumentTable.GetDocumentData(docCookie) as IVsTextBuffer;

            if (bufferAdapter == null)
            {
                return(null);
            }
            return(_editorAdaptersFactoryService.GetDocumentBuffer(bufferAdapter));
        }
 /// <summary>
 /// Tries to return an ITextBuffer representing the document from the document's DocData.
 /// </summary>
 /// <param name="docData">The DocData from the running document table.</param>
 /// <returns>The ITextBuffer. If one could not be found, this returns null.</returns>
 private ITextBuffer TryGetTextBufferFromDocData(object docData)
 {
     if (docData is IVsTextBuffer vsTestBuffer)
     {
         return(_editorAdaptersFactory.GetDocumentBuffer(vsTestBuffer));
     }
     else
     {
         return(null);
     }
 }
Example #12
0
 /// <summary>
 /// Tries to return an ITextBuffer representing the document from the document's DocData.
 /// </summary>
 /// <param name="docData">The DocData from the running document table.</param>
 /// <returns>The ITextBuffer. If one could not be found, this returns null.</returns>
 private ITextBuffer TryGetTextBufferFromDocData(IntPtr docData)
 {
     if (Marshal.GetObjectForIUnknown(docData) is IVsTextBuffer shimTextBuffer)
     {
         return(_editorAdaptersFactoryService.GetDocumentBuffer(shimTextBuffer));
     }
     else
     {
         return(null);
     }
 }
Example #13
0
        internal ContainedLanguage(
            IVsTextBufferCoordinator bufferCoordinator,
            IComponentModel componentModel,
            VisualStudioProject project,
            IVsHierarchy hierarchy,
            uint itemid,
            VisualStudioProjectTracker projectTrackerOpt,
            ProjectId projectId,
            TLanguageService languageService,
            AbstractFormattingRule vbHelperFormattingRule = null)
        {
            this.BufferCoordinator = bufferCoordinator;
            this.ComponentModel    = componentModel;
            this.Project           = project;
            _languageService       = languageService;

            this.Workspace = projectTrackerOpt?.Workspace ?? componentModel.GetService <VisualStudioWorkspace>();

            _editorAdaptersFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>();
            _diagnosticAnalyzerService    = componentModel.GetService <IDiagnosticAnalyzerService>();

            // Get the ITextBuffer for the secondary buffer
            Marshal.ThrowExceptionForHR(bufferCoordinator.GetSecondaryBuffer(out var secondaryTextLines));
            var secondaryVsTextBuffer = (IVsTextBuffer)secondaryTextLines;

            SubjectBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(secondaryVsTextBuffer);

            // Get the ITextBuffer for the primary buffer
            Marshal.ThrowExceptionForHR(bufferCoordinator.GetPrimaryBuffer(out var primaryTextLines));
            DataBuffer = _editorAdaptersFactoryService.GetDataBuffer((IVsTextBuffer)primaryTextLines);

            // Create our tagger
            var bufferTagAggregatorFactory = ComponentModel.GetService <IBufferTagAggregatorFactoryService>();

            _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator <ITag>(SubjectBuffer);

            if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemid, out var filePath)))
            {
                // we couldn't look up the document moniker from an hierarchy for an itemid.
                // Since we only use this moniker as a key, we could fall back to something else, like the document name.
                Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy.");
                if (!hierarchy.TryGetItemName(itemid, out filePath))
                {
                    FatalError.Report(new System.Exception("Failed to get document moniker for a contained document"));
                }
            }

            DocumentId documentId;

            if (this.Project != null)
            {
                documentId = this.Project.AddSourceTextContainer(
                    SubjectBuffer.AsTextContainer(), filePath,
                    sourceCodeKind: SourceCodeKind.Regular, folders: default,
        protected override async Task InitializeCoreAsync(CancellationToken cancellationToken)
        {
            (IVsHierarchy unusedHier, uint unusedId, IVsPersistDocData docData, uint unusedCookie) =
                await _shellUtilities.GetRDTDocumentInfoAsync(_serviceProvider, _tempFilePath).ConfigureAwait(false);

            await _threadingService.SwitchToUIThread();

            var textBuffer = _editorAdaptersService.GetDocumentBuffer((IVsTextBuffer)docData);

            Assumes.True(_textDocumentFactoryService.TryGetTextDocument(textBuffer, out _textDoc));
            Assumes.NotNull(_textDoc);
            _textDoc.FileActionOccurred += TextDocument_FileActionOccurred;
        }
Example #15
0
        protected override ITextBuffer GetTextBufferForOpenDocument(string filePath)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            // Check if the document is already open and initialized, and associate a buffer if possible.
            uint cookie;

            if (_runningDocumentTable.IsMonikerValid(filePath) &&
                ((cookie = _runningDocumentTable.GetDocumentCookie(filePath)) != VSConstants.VSCOOKIE_NIL) &&
                (_runningDocumentTable.GetDocumentFlags(cookie) & (uint)_VSRDTFLAGS4.RDT_PendingInitialization) == 0)
            {
                var textBuffer = !(((object)_runningDocumentTable.GetDocumentData(cookie)) is VsTextBuffer vsTextBuffer)
                    ? null
                    : _editorAdaptersFactory.GetDocumentBuffer(vsTextBuffer);
                return(textBuffer);
            }

            return(null);
        }
Example #16
0
        public static bool TryGetBuffer(this IVsRunningDocumentTable4 runningDocumentTable, IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
                                        uint docCookie, [NotNullWhen(true)] out ITextBuffer?textBuffer)
        {
            textBuffer = null;

            if (runningDocumentTable.GetDocumentData(docCookie) is IVsTextBuffer bufferAdapter)
            {
                textBuffer = editorAdaptersFactoryService.GetDocumentBuffer(bufferAdapter);
                return(textBuffer != null);
            }

            return(false);
        }
        private void UpdateWindowContentType(Window window)
        {
            var vsTextBuffer = Utils.GetWindowVisualBuffer(window, _serviceProvider.ServiceProvider);

            if (vsTextBuffer == null)
            {
                return;
            }

            var textBuffer = _textEditorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);

            UpdateTextBufferContentType(textBuffer, window.Document.Name);
        }
Example #18
0
        internal ContainedLanguage(
            IVsTextBufferCoordinator bufferCoordinator,
            IComponentModel componentModel,
            Workspace workspace,
            ProjectId projectId,
            VisualStudioProject?project,
            string filePath,
            Guid languageServiceGuid,
            AbstractFormattingRule?vbHelperFormattingRule = null
            )
        {
            this.BufferCoordinator = bufferCoordinator;
            this.ComponentModel    = componentModel;
            this.Project           = project;
            _languageServiceGuid   = languageServiceGuid;

            this.Workspace = workspace;

            _editorAdaptersFactoryService =
                componentModel.GetService <IVsEditorAdaptersFactoryService>();
            _diagnosticAnalyzerService = componentModel.GetService <IDiagnosticAnalyzerService>();

            // Get the ITextBuffer for the secondary buffer
            Marshal.ThrowExceptionForHR(
                bufferCoordinator.GetSecondaryBuffer(out var secondaryTextLines)
                );
            SubjectBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(secondaryTextLines) !;

            // Get the ITextBuffer for the primary buffer
            Marshal.ThrowExceptionForHR(
                bufferCoordinator.GetPrimaryBuffer(out var primaryTextLines)
                );
            DataBuffer = _editorAdaptersFactoryService.GetDataBuffer(primaryTextLines) !;

            // Create our tagger
            var bufferTagAggregatorFactory =
                ComponentModel.GetService <IBufferTagAggregatorFactoryService>();

            _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator <ITag>(
                SubjectBuffer
                );

            DocumentId documentId;

            if (this.Project != null)
            {
                documentId = this.Project.AddSourceTextContainer(
                    SubjectBuffer.AsTextContainer(),
                    filePath,
                    sourceCodeKind: SourceCodeKind.Regular,
                    folders: default,
        protected override async Task <bool> TryHandleCommandAsync(IProjectTree node, bool focused, Int64 commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut)
        {
            if (!ShouldHandle(node))
            {
                return(false);
            }

            var projectFileName = Path.GetFileName(_unconfiguredProject.FullPath);

            var projPath = await GetFileAsync(projectFileName).ConfigureAwait(false);

            await _threadingService.SwitchToUIThread();

            IVsWindowFrame frame;

            frame = _shellUtilities.OpenDocumentWithSpecificEditor(_serviceProvider, projPath, XmlEditorFactoryGuid, Guid.Empty);

            IMsBuildModelWatcher watcher = _watcherFactory.CreateExport();
            await watcher.InitializeAsync(projPath).ConfigureAwait(true);

            // When the document is closed, clean up the file on disk
            var fileCleanupListener = new EditProjectFileCleanupFrameNotifyListener(projPath, _fileSystem, watcher);

            Verify.HResult(frame.SetProperty((int)__VSFPROPID.VSFPROPID_ViewHelper, fileCleanupListener));

            // Ensure that the window is not reopened when the solution is closed
            Verify.HResult(frame.SetProperty((int)__VSFPROPID5.VSFPROPID_DontAutoOpen, true));

            // Set up a save listener, that will overwrite the project file on save.
            IVsHierarchy      unusedHier;
            uint              unusedId;
            uint              unusedCookie;
            IVsPersistDocData docData;

            _shellUtilities.GetRDTDocumentInfo(_serviceProvider, projPath, out unusedHier, out unusedId, out docData, out unusedCookie);

            var           textBuffer = _editorFactoryService.GetDocumentBuffer((IVsTextBuffer)docData);
            ITextDocument textDoc;

            if (!_textDocumentFactoryService.TryGetTextDocument(textBuffer, out textDoc))
            {
                return(false);
            }

            Assumes.NotNull(textDoc);
            textDoc.FileActionOccurred += TextDocument_FileActionOccurred;

            Verify.HResult(frame.Show());

            return(true);
        }
        private bool TryGetBuffer(uint docCookie, out ITextBuffer textBuffer)
        {
            textBuffer = null;

            // The cast from dynamic to object doesn't change semantics, but avoids loading the dynamic binder
            // which saves us JIT time in this method and an assembly load.
            if ((object)_runningDocumentTable.GetDocumentData(docCookie) is IVsTextBuffer bufferAdapter)
            {
                textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(bufferAdapter);
                return(textBuffer != null);
            }

            return(false);
        }
        public static bool TryGetBuffer(this IVsRunningDocumentTable4 runningDocumentTable, IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
                                        uint docCookie, [NotNullWhen(true)] out ITextBuffer?textBuffer)
        {
            textBuffer = null;

            // The cast from dynamic to object doesn't change semantics, but avoids loading the dynamic binder
            // which saves us JIT time in this method and an assembly load.
            if ((object)runningDocumentTable.GetDocumentData(docCookie) is IVsTextBuffer bufferAdapter)
            {
                textBuffer = editorAdaptersFactoryService.GetDocumentBuffer(bufferAdapter);
                return(textBuffer != null);
            }

            return(false);
        }
        private async Task InitializeTextBufferAsync()
        {
            (IVsHierarchy unusedHier, uint unusedId, IVsPersistDocData docData, uint unusedCookie) =
                await _shellUtilities.GetRDTDocumentInfoAsync(_serviceProvider, FilePath).ConfigureAwait(false);

            _docData = docData;

            await _threadingService.SwitchToUIThread();

            _textBuffer = (IVsTextBuffer)_docData;

            var textBufferAdapter = _editorAdaptersService.GetDocumentBuffer(_textBuffer);

            Assumes.True(_textDocumentService.TryGetTextDocument(textBufferAdapter, out _textDocument));
        }
        private bool FetchRunningDocumentTable()
        {
            var rdt = new RunningDocumentTable(_serviceProvider);

            foreach (var info in rdt)
            {
                // Get doc data
                if (!FullPath.IsValid(info.Moniker))
                {
                    continue;
                }

                var path = new FullPath(info.Moniker);
                if (_openDocuments.ContainsKey(path))
                {
                    continue;
                }

                // Get vs buffer
                IVsTextBuffer docData = null;
                try {
                    docData = info.DocData as IVsTextBuffer;
                }
                catch (Exception e) {
                    Logger.LogWarning(e, "Error getting IVsTextBuffer for document {0}, skipping document", path);
                }
                if (docData == null)
                {
                    continue;
                }

                // Get ITextDocument
                var textBuffer = _vsEditorAdaptersFactoryService.GetDocumentBuffer(docData);
                if (textBuffer == null)
                {
                    continue;
                }

                ITextDocument document;
                if (!_textDocumentFactoryService.TryGetTextDocument(textBuffer, out document))
                {
                    continue;
                }

                _openDocuments[path] = document;
            }
            return(true);
        }
Example #24
0
        public ContainedLanguage(
            IVsTextBufferCoordinator bufferCoordinator,
            IComponentModel componentModel,
            TProject project,
            IVsHierarchy hierarchy,
            uint itemid,
            TLanguageService languageService,
            SourceCodeKind sourceCodeKind,
            IFormattingRule vbHelperFormattingRule = null)
            : base(project)
        {
            this.BufferCoordinator = bufferCoordinator;
            this.ComponentModel    = componentModel;
            this.Project           = project;
            _languageService       = languageService;

            this.Workspace = componentModel.GetService <VisualStudioWorkspace>();
            _editorAdaptersFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>();

            // Get the ITextBuffer for the secondary buffer
            IVsTextLines secondaryTextLines;

            Marshal.ThrowExceptionForHR(bufferCoordinator.GetSecondaryBuffer(out secondaryTextLines));
            var secondaryVsTextBuffer = (IVsTextBuffer)secondaryTextLines;

            SetSubjectBuffer(_editorAdaptersFactoryService.GetDocumentBuffer(secondaryVsTextBuffer));

            var bufferTagAggregatorFactory = ComponentModel.GetService <IBufferTagAggregatorFactoryService>();

            _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator <ITag>(SubjectBuffer);

            IVsTextLines primaryTextLines;

            Marshal.ThrowExceptionForHR(bufferCoordinator.GetPrimaryBuffer(out primaryTextLines));
            var primaryVsTextBuffer = (IVsTextBuffer)primaryTextLines;
            var dataBuffer          = (IProjectionBuffer)_editorAdaptersFactoryService.GetDataBuffer(primaryVsTextBuffer);

            SetDataBuffer(dataBuffer);

            this.ContainedDocument = new ContainedDocument(
                this, sourceCodeKind, this.Workspace, hierarchy, itemid, componentModel, vbHelperFormattingRule);

            // TODO: Can contained documents be linked or shared?
            this.Project.AddDocument(this.ContainedDocument, isCurrentContext: true);
        }
Example #25
0
        private void OnNewFile(object sender, HierarchyEventArgs args)
        {
            IVsHierarchy hierarchy = sender as IVsHierarchy;

            if (null == hierarchy)
            {
                return;
            }

            ITextBuffer buffer = null;

            if (null != args.TextBuffer)
            {
                buffer = _adapterFactory.GetDocumentBuffer(args.TextBuffer);
            }

            OnNewFile(new LibraryTask(args.CanonicalName, buffer, new ModuleId(hierarchy, args.ItemID)));
        }
Example #26
0
        ITextBuffer IInteractiveWindowEditorFactoryService.CreateAndActivateBuffer(IInteractiveWindow window, IContentType contentType)
        {
            // create buffer adapter to support undo/redo:
            var bufferAdapter = _adapterFactory.CreateVsTextBufferAdapter(_provider, contentType);

            bufferAdapter.InitializeContent("", 0);

            var commandFilter = GetCommandFilter(window);

            if (commandFilter.currentBufferCommandHandler != null)
            {
                ((IVsPersistDocData)commandFilter.currentBufferCommandHandler).Close();
            }

            commandFilter.currentBufferCommandHandler = (IOleCommandTarget)bufferAdapter;

            return(_adapterFactory.GetDocumentBuffer(bufferAdapter));
        }
Example #27
0
        public ITextDocument GetFromFrame(IVsWindowFrame frame)
        {
            // Get the doc data, which should also be a text buffer
            frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var docData);
            if (!(docData is IVsTextBuffer vsTextBuffer))
            {
                return(null);
            }

            // Finally, convert from the legacy VS editor interface to the new-style interface
            var textBuffer = editorAdapterService.GetDocumentBuffer(vsTextBuffer);

            ITextDocument newTextDocument = null;

            textBuffer?.Properties?.TryGetProperty(
                typeof(ITextDocument), out newTextDocument);

            return(newTextDocument);
        }
Example #28
0
        public static Result <ITextBuffer> GetTextBuffer(this IVsWindowFrame vsWindowFrame, IVsEditorAdaptersFactoryService factoryService)
        {
            var result = GetTextLines(vsWindowFrame);

            if (result.IsError)
            {
                return(Result.CreateError(result.HResult));
            }

            var vsTextLines = result.Value;
            var textBuffer  = factoryService.GetDocumentBuffer(vsTextLines);

            if (textBuffer == null)
            {
                return(Result.Error);
            }

            return(Result.CreateSuccess(textBuffer));
        }
Example #29
0
        public IEditorInterfaces GetOrOpenDocument(string path)
        {
            OpenFileInEditor(path);
            IVsRunningDocumentTable runningDocumentTable = (IVsRunningDocumentTable)visualStudio.ServiceProvider.GetService(typeof(SVsRunningDocumentTable));

            IVsHierarchy hierarchy;
            uint         itemId;
            IntPtr       documentData = IntPtr.Zero;
            uint         cookie;

            try
            {
                int hr = runningDocumentTable.FindAndLockDocument(
                    (uint)_VSRDTFLAGS.RDT_NoLock,
                    path,
                    out hierarchy,
                    out itemId,
                    out documentData,
                    out cookie);

                if (hr == NativeMethods.S_OK && documentData != IntPtr.Zero)
                {
                    IVsTextBuffer vsTextBuffer = Marshal.GetObjectForIUnknown(documentData) as IVsTextBuffer;
                    if (vsTextBuffer != null)
                    {
                        IVsEditorAdaptersFactoryService editorAdaptersFactory = visualStudio.ComponentModel.GetService <IVsEditorAdaptersFactoryService>();
                        ITextBuffer   buffer   = editorAdaptersFactory.GetDocumentBuffer(vsTextBuffer);
                        ITextDocument document = buffer.Properties.GetProperty <ITextDocument>(typeof(ITextDocument));

                        return(new EditorInterfaces(buffer, document, vsTextBuffer));
                    }
                }

                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.FailedToOpenFile, path));
            }
            finally
            {
                if (documentData != IntPtr.Zero)
                {
                    Marshal.Release(documentData);
                }
            }
        }
Example #30
0
        private void OnBeforeSaveWorker(uint docCookie)
        {
            var docData = IntPtr.Zero;

            try
            {
                // We want to raise a save event for this document. First let's try to get the docData
                Marshal.ThrowExceptionForHR(_runningDocumentTable.GetDocumentInfo(docCookie, out var flags, out var readLocks, out var writeLocks, out var moniker, out var hierarchy, out var itemid, out docData));

                if (Marshal.GetObjectForIUnknown(docData) is IVsTextBuffer textBufferAdapter)
                {
                    var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(textBufferAdapter);

                    // Do a quick check that this is a Roslyn file at all before we go do more expensive things
                    if (textBuffer != null && textBuffer.ContentType.IsOfType(ContentTypeNames.RoslynContentType))
                    {
                        if (textBufferAdapter != null)
                        {
                            // OK, we want to go and raise a save event. Currently, CommandArgs demands that we have a view, so let's try to go and find one.
                            _textManager.EnumViews(textBufferAdapter, out var enumTextViews);
                            var  views   = new IVsTextView[1];
                            uint fetched = 0;

                            if (ErrorHandler.Succeeded(enumTextViews.Next(1, views, ref fetched)) && fetched == 1)
                            {
                                var view = _editorAdaptersFactoryService.GetWpfTextView(views[0]);
                                var commandHandlerService = _commandHandlerServiceFactory.GetService(textBuffer);
                                commandHandlerService.Execute(textBuffer.ContentType, new SaveCommandArgs(view, textBuffer));
                            }
                        }
                    }
                }
            }
            finally
            {
                if (docData != IntPtr.Zero)
                {
                    Marshal.Release(docData);
                }
            }
        }