private Task <object> CreateChangedDocumentViewAsync(ITextBuffer oldBuffer, ITextBuffer newBuffer, string description,
                                                             List <LineSpan> originalSpans, List <LineSpan> changedSpans, PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace,
                                                             double zoomLevel, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (!(originalSpans.Any() && changedSpans.Any()))
            {
                // Both line spans must be non-empty. Otherwise, below projection buffer factory API call will throw.
                // So if either is empty (signalling that there are no changes to preview in the document), then we bail out.
                // This can happen in cases where the user has already applied the fix and light bulb has already been dismissed,
                // but platform hasn't cancelled the preview operation yet. Since the light bulb has already been dismissed at
                // this point, the preview that we return will never be displayed to the user. So returning null here is harmless.
                return(SpecializedTasks.Default <object>());
            }

            var originalBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation(
                _contentTypeRegistryService,
                _editorOptionsFactoryService.GlobalOptions,
                oldBuffer.CurrentSnapshot,
                "...",
                description,
                originalSpans.ToArray());

            var changedBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation(
                _contentTypeRegistryService,
                _editorOptionsFactoryService.GlobalOptions,
                newBuffer.CurrentSnapshot,
                "...",
                description,
                changedSpans.ToArray());

            return(CreateNewDifferenceViewerAsync(leftWorkspace, rightWorkspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken));
        }
        public void UpdatePreview(string text)
        {
            const string start = "//[";
            const string end   = "//]";

            var service   = MefV1HostServices.Create(_componentModel.DefaultExportProvider);
            var workspace = new PreviewWorkspace(service);
            var fileName  = string.Format("project.{0}", Language == "C#" ? "csproj" : "vbproj");
            var project   = workspace.CurrentSolution.AddProject(fileName, "assembly.dll", Language);

            // use the mscorlib, system, and system.core that are loaded in the current process.
            string[] references =
            {
                "mscorlib",
                "System",
                "System.Core"
            };

            var metadataService = workspace.Services.GetService <IMetadataService>();

            var referenceAssemblies = Thread.GetDomain().GetAssemblies()
                                      .Where(x => references.Contains(x.GetName(true).Name, StringComparer.OrdinalIgnoreCase))
                                      .Select(a => metadataService.GetReference(a.Location, MetadataReferenceProperties.Assembly));

            project = project.WithMetadataReferences(referenceAssemblies);

            var document  = project.AddDocument("document", SourceText.From(text, Encoding.UTF8));
            var formatted = Formatter.FormatAsync(document, this.Options).WaitAndGetResult(CancellationToken.None);

            var textBuffer = _textBufferFactoryService.CreateTextBuffer(formatted.GetTextAsync().Result.ToString(), _contentType);

            var container = textBuffer.AsTextContainer();
            var documentBackedByTextBuffer = document.WithText(container.CurrentText);

            var bufferText = textBuffer.CurrentSnapshot.GetText().ToString();
            var startIndex = bufferText.IndexOf(start, StringComparison.Ordinal);
            var endIndex   = bufferText.IndexOf(end, StringComparison.Ordinal);
            var startLine  = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(startIndex) + 1;
            var endLine    = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(endIndex);

            var projection = _projectionBufferFactory.CreateProjectionBufferWithoutIndentation(_contentTypeRegistryService,
                                                                                               _editorOptions.CreateOptions(),
                                                                                               textBuffer.CurrentSnapshot,
                                                                                               "",
                                                                                               LineSpan.FromBounds(startLine, endLine));

            var textView = _textEditorFactoryService.CreateTextView(projection,
                                                                    _textEditorFactoryService.CreateTextViewRoleSet(PredefinedTextViewRoles.Analyzable));

            this.TextViewHost = _textEditorFactoryService.CreateTextViewHost(textView, setFocus: false);

            workspace.TryApplyChanges(documentBackedByTextBuffer.Project.Solution);
            workspace.OpenDocument(document.Id);

            this.TextViewHost.Closed += (s, a) =>
            {
                workspace.Dispose();
                workspace = null;
            };
        }
示例#3
0
        public void UpdatePreview(string text)
        {
            const string start = "//[";
            const string end   = "//]";

            var sourceText = SourceText.From(text);
            var syntaxTree = SyntaxFactory.ParseSyntaxTree(sourceText);
            var edits      = Formatter.GetEdits(syntaxTree, new TextSpan(sourceText, 0, text.Length), _optionsService.FormattingOptions);
            var formatted  = Formatter.ApplyEdits(text, edits);

            var textBuffer = _textBufferFactoryService.CreateTextBuffer(formatted, _contentType);

            var bufferText = textBuffer.CurrentSnapshot.GetText().ToString();
            var startIndex = bufferText.IndexOf(start, StringComparison.Ordinal);
            var endIndex   = bufferText.IndexOf(end, StringComparison.Ordinal);
            var startLine  = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(startIndex) + 1;
            var endLine    = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(endIndex);

            var projection = _projectionBufferFactory.CreateProjectionBufferWithoutIndentation(_contentTypeRegistryService,
                                                                                               _editorOptions.CreateOptions(),
                                                                                               textBuffer.CurrentSnapshot,
                                                                                               "",
                                                                                               LineSpan.FromBounds(startLine, endLine));

            var textView = _textEditorFactoryService.CreateTextView(projection,
                                                                    _textEditorFactoryService.CreateTextViewRoleSet(PredefinedTextViewRoles.Analyzable));

            this.TextViewHost = _textEditorFactoryService.CreateTextViewHost(textView, setFocus: false);
        }
 private ITextBuffer CreateElisionBufferWithoutIndentation(
     SnapshotSpan shortHintSpan)
 {
     return(ProjectionBufferFactoryService.CreateProjectionBufferWithoutIndentation(
                EditorOptionsFactoryService.GlobalOptions,
                contentType: null,
                exposedSpans: shortHintSpan));
 }
示例#5
0
 private ITextBuffer CreateElisionBufferWithoutIndentation(
     ITextBuffer dataBuffer, Span shortHintSpan)
 {
     return(_projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation(
                _editorOptionsFactoryService.GlobalOptions,
                contentType: null,
                exposedSpans: new SnapshotSpan(dataBuffer.CurrentSnapshot, shortHintSpan)));
 }
示例#6
0
 private IProjectionBuffer CreateBuffer()
 {
     return(_projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation(
                _editorOptionsFactoryService.GlobalOptions,
                _contentType,
                _spans.ToArray()
                ));
 }
示例#7
0
        public void UpdatePreview(string text)
        {
            var service   = VisualStudioMefHostServices.Create(_componentModel.GetService <ExportProvider>());
            var workspace = new PreviewWorkspace(service);
            var fileName  = "project." + (Language == "C#" ? "csproj" : "vbproj");
            var project   = workspace.CurrentSolution.AddProject(fileName, "assembly.dll", Language);

            // use the mscorlib, system, and system.core that are loaded in the current process.
            string[] references =
            {
                "mscorlib",
                "System",
                "System.Core"
            };

            var metadataService = workspace.Services.GetService <IMetadataService>();

            var referenceAssemblies = Thread.GetDomain().GetAssemblies()
                                      .Where(x => references.Contains(x.GetName(true).Name, StringComparer.OrdinalIgnoreCase))
                                      .Select(a => metadataService.GetReference(a.Location, MetadataReferenceProperties.Assembly));

            project = project.WithMetadataReferences(referenceAssemblies);

            var document = project.AddDocument("document", SourceText.From(text, Encoding.UTF8));
            var fallbackFormattingOptions = _globalOptions.GetSyntaxFormattingOptions(document.Project.LanguageServices);
            var optionService             = workspace.Services.GetRequiredService <IOptionService>();
            var configOptions             = OptionStore.GetOptions().AsAnalyzerConfigOptions(optionService, document.Project.Language);
            var formattingService         = document.GetRequiredLanguageService <ISyntaxFormattingService>();
            var formattingOptions         = formattingService.GetFormattingOptions(configOptions, fallbackFormattingOptions);
            var formatted = Formatter.FormatAsync(document, formattingOptions, CancellationToken.None).WaitAndGetResult(CancellationToken.None);

            var textBuffer = _textBufferFactoryService.CreateTextBuffer(formatted.GetTextSynchronously(CancellationToken.None).ToString(), _contentType);

            var container = textBuffer.AsTextContainer();

            var projection = _projectionBufferFactory.CreateProjectionBufferWithoutIndentation(_contentTypeRegistryService,
                                                                                               _editorOptions.CreateOptions(),
                                                                                               textBuffer.CurrentSnapshot,
                                                                                               separator: "",
                                                                                               exposedLineSpans: GetExposedLineSpans(textBuffer.CurrentSnapshot).ToArray());

            var textView = _textEditorFactoryService.CreateTextView(projection,
                                                                    _textEditorFactoryService.CreateTextViewRoleSet(PredefinedTextViewRoles.Interactive));

            this.TextViewHost = _textEditorFactoryService.CreateTextViewHost(textView, setFocus: false);

            workspace.TryApplyChanges(document.Project.Solution);
            workspace.OpenDocument(document.Id, container);

            this.TextViewHost.Closed += (s, a) =>
            {
                workspace.Dispose();
                workspace = null;
            };
        }
 public static IProjectionBuffer CreateProjectionBufferWithoutIndentation(
     this IProjectionBufferFactoryService factoryService,
     IEditorOptions editorOptions,
     IContentType contentType = null,
     params SnapshotSpan[] exposedSpans)
 {
     return(factoryService.CreateProjectionBufferWithoutIndentation(
                editorOptions,
                contentType,
                (IEnumerable <SnapshotSpan>)exposedSpans));
 }
        private async ValueTask <DifferenceViewerPreview?> CreateChangedDocumentViewAsync(ITextBuffer oldBuffer, ITextBuffer newBuffer, string?description,
                                                                                          List <LineSpan> originalSpans, List <LineSpan> changedSpans, PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace,
                                                                                          double zoomLevel, CancellationToken cancellationToken)
        {
            if (!(originalSpans.Any() && changedSpans.Any()))
            {
                // Both line spans must be non-empty. Otherwise, below projection buffer factory API call will throw.
                // So if either is empty (signaling that there are no changes to preview in the document), then we bail out.
                // This can happen in cases where the user has already applied the fix and light bulb has already been dismissed,
                // but platform hasn't cancelled the preview operation yet. Since the light bulb has already been dismissed at
                // this point, the preview that we return will never be displayed to the user. So returning null here is harmless.

                // TODO: understand how this can even happen. The diff input is stable -- we shouldn't be depending on some sort of
                // state that could change underneath us. If we know the file changed, how would we discover here it didn't?
                return(null);
            }

            // IProjectionBufferFactoryService is a Visual Studio API which is not documented as free-threaded
            await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            var originalBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation(
                _contentTypeRegistryService,
                _editorOptionsFactoryService.GlobalOptions,
                oldBuffer.CurrentSnapshot,
                "...",
                description,
                originalSpans.ToArray());

            var changedBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation(
                _contentTypeRegistryService,
                _editorOptionsFactoryService.GlobalOptions,
                newBuffer.CurrentSnapshot,
                "...",
                description,
                changedSpans.ToArray());

#pragma warning disable CA2007 // Consider calling ConfigureAwait on the awaited task (containing method uses JTF)
            return(await CreateNewDifferenceViewerAsync(leftWorkspace, rightWorkspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken));

#pragma warning restore CA2007 // Consider calling ConfigureAwait on the awaited task
        }
 public static IProjectionBuffer CreateProjectionBufferWithoutIndentation(
     this IProjectionBufferFactoryService factoryService,
     IContentTypeRegistryService registryService,
     IEditorOptions editorOptions,
     ITextSnapshot snapshot,
     string separator,
     params LineSpan[] exposedLineSpans)
 {
     return(factoryService.CreateProjectionBufferWithoutIndentation(
                registryService,
                editorOptions,
                snapshot,
                separator,
                suffixOpt: null,
                exposedLineSpans: exposedLineSpans));
 }
        public void UpdatePreview(string text)
        {
            const string start = "//[";
            const string end   = "//]";

            var service   = MefV1HostServices.Create(_componentModel.DefaultExportProvider);
            var workspace = new PreviewWorkspace(service);

            var document  = workspace.OpenDocument(DocumentId.CreateNewId("document"), SourceText.From(text), Language);
            var formatted = Formatter.FormatAsync(document, this.Options).WaitAndGetResult(CancellationToken.None);

            var textBuffer = _textBufferFactoryService.CreateTextBuffer(formatted.SourceText.ToString(), _contentType);

            var container = textBuffer.AsTextContainer();
            var documentBackedByTextBuffer = document.WithText(container.CurrentText);

            var bufferText = textBuffer.CurrentSnapshot.GetText().ToString();
            var startIndex = bufferText.IndexOf(start, StringComparison.Ordinal);
            var endIndex   = bufferText.IndexOf(end, StringComparison.Ordinal);
            var startLine  = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(startIndex) + 1;
            var endLine    = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(endIndex);

            var projection = _projectionBufferFactory.CreateProjectionBufferWithoutIndentation(_contentTypeRegistryService,
                                                                                               _editorOptions.CreateOptions(),
                                                                                               textBuffer.CurrentSnapshot,
                                                                                               "",
                                                                                               LineSpan.FromBounds(startLine, endLine));

            var textView = _textEditorFactoryService.CreateTextView(projection,
                                                                    _textEditorFactoryService.CreateTextViewRoleSet());

            this.TextViewHost = _textEditorFactoryService.CreateTextViewHost(textView, setFocus: false);

            workspace.CloseDocument(document.Id);
            workspace.OpenDocument(document.Id, documentBackedByTextBuffer.SourceText, Language);
            //workspace.UpdateDocument(documentBackedByTextBuffer.Id, documentBackedByTextBuffer.SourceText);
        }
示例#12
0
 private IProjectionBuffer CreateBuffer(ProjectionBufferDeferredContent deferredContent)
 {
     return(_projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation(
                _editorOptionsFactoryService.GlobalOptions, deferredContent.ContentType, deferredContent.Span));
 }