Welcome to mirror list, hosted at ThFree Co, Russian Federation.

BufferFactoryService.cs « TextModel « Impl « Text « Editor « src - github.com/microsoft/vs-editor-api.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 66cee1899bbb825cc3e6fa262daa30d50a8d11e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//
//  Copyright (c) Microsoft Corporation. All rights reserved.
//  Licensed under the MIT License. See License.txt in the project root for license information.
//
// This file contain implementations details that are subject to change without notice.
// Use at your own risk.
//
namespace Microsoft.VisualStudio.Text.Implementation
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.Diagnostics;
    using System.IO;
    using System.IO.MemoryMappedFiles;
    using System.Text;
    using Microsoft.VisualStudio.Text.Differencing;
    using Microsoft.VisualStudio.Text.Document;
    using Microsoft.VisualStudio.Text.Projection;
    using Microsoft.VisualStudio.Text.Projection.Implementation;
    using Microsoft.VisualStudio.Text.Utilities;
    using Microsoft.VisualStudio.Utilities;

    /// <summary>
    /// Factory for TextBuffers and ProjectionBuffers.
    /// </summary>
    [Export(typeof(ITextImageFactoryService))]
    [Export(typeof(ITextImageFactoryService2))]
    [Export(typeof(ITextBufferFactoryService))]
    [Export(typeof(ITextBufferFactoryService2))]
    [Export(typeof(ITextBufferFactoryService3))]
    [Export(typeof(IProjectionBufferFactoryService))]
    internal partial class BufferFactoryService : ITextBufferFactoryService2, ITextBufferFactoryService3, IProjectionBufferFactoryService, IInternalTextBufferFactory, ITextImageFactoryService2
    {
        #region Standard Content Type Definitions
        [Export]
        [Name("any")]
        public ContentTypeDefinition anyContentTypeDefinition;

        [Export]
        [Name("text")]
        [BaseDefinition("any")]
        public ContentTypeDefinition textContentTypeDefinition;

        [Export]
        [Name("projection")]
        [BaseDefinition("any")]
        public ContentTypeDefinition projectionContentTypeDefinition;

        [Export]
        [Name("plaintext")]
        [BaseDefinition("text")]
        public ContentTypeDefinition plaintextContentTypeDefinition;

        [Export]
        [Name("code")]
        [BaseDefinition("text")]
        public ContentTypeDefinition codeContentType;

        [Export]
        [Name("inert")]
        // N.B.: This ContentType does NOT inherit from anything
        public ContentTypeDefinition inertContentTypeDefinition;
        #endregion

        #region Service Consumptions

        [Import]
        internal IContentTypeRegistryService _contentTypeRegistryService { get; set; }

        [Import]
        internal IDifferenceService _differenceService { get; set; }

        [Import]
        internal ITextDifferencingSelectorService _textDifferencingSelectorService { get; set; }

        [Import]
        internal GuardedOperations _guardedOperations { get; set; }

        [Import]
        internal IWhitespaceManagerFactory _whitespaceManagerFactory { get; set; }

        #endregion

        #region Private state
        private IContentType textContentType;
        private IContentType plaintextContentType;
        private IContentType inertContentType;
        private IContentType projectionContentType;
        #endregion

        #region ContentType accessors
        public IContentType TextContentType
        {
            get
            {
                if (this.textContentType == null)
                {
                    // it's OK to evaluate this more than once, and the assignment is atomic, so we don't protect this with a lock
                    this.textContentType = _contentTypeRegistryService.GetContentType("text");
                }
                return this.textContentType;
            }
        }

        public IContentType PlaintextContentType
        {
            get
            {
                if (this.plaintextContentType == null)
                {
                    // it's OK to evaluate this more than once, and the assignment is atomic, so we don't protect this with a lock
                    this.plaintextContentType = _contentTypeRegistryService.GetContentType("plaintext");
                }
                return this.plaintextContentType;
            }
        }

        public IContentType InertContentType
        {
            get
            {
                if (this.inertContentType == null)
                {
                    // it's OK to evaluate this more than once, and the assignment is atomic, so we don't protect this with a lock
                    this.inertContentType = _contentTypeRegistryService.GetContentType("inert");
                }
                return this.inertContentType;
            }
        }

        public IContentType ProjectionContentType
        {
            get
            {
                if (this.projectionContentType == null)
                {
                    // it's OK to evaluate this more than once, and the assignment is atomic, so we don't protect this with a lock
                    this.projectionContentType = _contentTypeRegistryService.GetContentType("projection");
                }
                return this.projectionContentType;
            }
        }
        #endregion

        public ITextBuffer CreateTextBuffer()
        {
            return Make(TextContentType, StringRebuilder.Empty, false);
        }

        public ITextBuffer CreateTextBuffer(IContentType contentType)
        {
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }
            return Make(contentType, StringRebuilder.Empty, false);
        }

        public ITextBuffer CreateTextBuffer(string text, IContentType contentType)
        {
            return CreateTextBuffer(text, contentType, false);
        }

        public ITextBuffer CreateTextBuffer(SnapshotSpan span, IContentType contentType)
        {
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            StringRebuilder content = StringRebuilderFromSnapshotSpan(span);

            return Make(contentType, content, false);
        }

        public ITextBuffer CreateTextBuffer(ITextImage image, IContentType contentType)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            StringRebuilder content = StringRebuilder.Create(image);

            return Make(contentType, content, false);
        }

        public ITextBuffer CreateTextBuffer(string text, IContentType contentType, bool spurnGroup)
        {
            if (text == null)
            {
                throw new ArgumentNullException(nameof(text));
            }
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }
            return Make(contentType, StringRebuilder.Create(text), spurnGroup);
        }

        public ITextBuffer CreateTextBuffer(TextReader reader, IContentType contentType, long length, string traceId)
        {
            return this.CreateTextBuffer(reader, contentType, length, traceId, throwOnInvalidCharacters: false);
        }

        public ITextBuffer CreateTextBuffer(TextReader reader, IContentType contentType, long length, string traceId, bool throwOnInvalidCharacters)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }
            if (length > int.MaxValue)
            {
                throw new InvalidOperationException(Strings.FileTooLarge);
            }

            int longestLineLength;
            StringRebuilder content = TextImageLoader.Load(
                reader,
                length,
                out var newlineState,
                out var leadingWhitespaceState,
                out longestLineLength,
                throwOnInvalidCharacters: throwOnInvalidCharacters);

            ITextBuffer buffer = Make(contentType, content, false);

            // Make the call to GetWhitespaceManager to add the manager to the properties. We don't need the return value here.
            var _ = _whitespaceManagerFactory.GetOrCreateWhitespaceManager(buffer, newlineState, leadingWhitespaceState);

            // Leave a sign about the longest line in the buffer. This is rather nasty, but for now
            // we don't want to pollute the API with this factoid
            buffer.Properties["LongestLineLength"] = longestLineLength;

            return buffer;
        }

        public ITextBuffer CreateTextBuffer(TextReader reader, IContentType contentType)
        {
            return CreateTextBuffer(reader, contentType, -1, "legacy", throwOnInvalidCharacters: false);
        }

        internal static StringRebuilder StringRebuilderFromSnapshotAndSpan(ITextSnapshot snapshot, Span span)
        {
            return AppendStringRebuildersFromSnapshotAndSpan(StringRebuilder.Empty, snapshot, span);
        }

        internal static StringRebuilder StringRebuilderFromSnapshotSpan(SnapshotSpan span)
        {
            return StringRebuilderFromSnapshotAndSpan(span.Snapshot, span.Span);
        }

        internal static StringRebuilder StringRebuilderFromSnapshotSpans(IList<SnapshotSpan> sourceSpans, Span selectedSourceSpans)
        {
            StringRebuilder content = StringRebuilder.Empty;
            for (int i = 0; (i < selectedSourceSpans.Length); ++i)
            {
                var span = sourceSpans[selectedSourceSpans.Start + i];
                content = AppendStringRebuildersFromSnapshotAndSpan(content, span.Snapshot, span.Span);
            }

            return content;
        }

        internal static StringRebuilder AppendStringRebuildersFromSnapshotAndSpan(StringRebuilder content, ITextSnapshot snapshot, Span span)
        {
            if (span.Length != 0)
            {
                var baseSnapshot = snapshot as BaseSnapshot;
                if (baseSnapshot != null)
                {
                    content = content.Append(baseSnapshot.Content.GetSubText(span));
                }
                else
                {
                    // The we don't know what to do fallback. This should never be called unless someone provides a new snapshot
                    // implementation.
                    content = content.Append(snapshot.GetText(span));
                }
            }

            return content;
        }

        #region ITextImageFactoryService members
        public ITextImage CreateTextImage(string text)
        {
            return CachingTextImage.Create(StringRebuilder.Create(text), null);
        }

        public ITextImage CreateTextImage(TextReader reader, long length)
        {
            return CachingTextImage.Create(TextImageLoader.Load(reader, length, out var _, out var _, out var _), null);
        }

        public ITextImage CreateTextImage(MemoryMappedFile source)
        {
            // Evil implementation (for now) that just reads the entire contents of the MMF.
            // Eventually to be replaced with something along the lines of a version of the StringRebuilderForCompressedChars that uses the MMF directly.
            using (var stream = source.CreateViewStream())
            {
                using (var reader = new StreamReader(stream, Encoding.Unicode))
                {
                    return this.CreateTextImage(reader, -1);
                }
            }
        }
        #endregion

        private TextBuffer Make(IContentType contentType, StringRebuilder content, bool spurnGroup)
        {
            TextBuffer buffer = new TextBuffer(contentType, content, _textDifferencingSelectorService.DefaultTextDifferencingService, _guardedOperations, spurnGroup);
            RaiseTextBufferCreatedEvent(buffer);
            return buffer;
        }

        public IProjectionBuffer CreateProjectionBuffer(IProjectionEditResolver projectionEditResolver,
                                                        IList<object> trackingSpans,
                                                        ProjectionBufferOptions options,
                                                        IContentType contentType)
        {
            // projectionEditResolver is allowed to be null.
            if (trackingSpans == null)
            {
                throw new ArgumentNullException(nameof(trackingSpans));
            }
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }
            IProjectionBuffer buffer =
                new ProjectionBuffer(this, projectionEditResolver, contentType, trackingSpans, _differenceService, _textDifferencingSelectorService.DefaultTextDifferencingService, options, _guardedOperations);
            RaiseProjectionBufferCreatedEvent(buffer);
            return buffer;
        }

        public IProjectionBuffer CreateProjectionBuffer(IProjectionEditResolver projectionEditResolver,
                                                        IList<object> trackingSpans,
                                                        ProjectionBufferOptions options)
        {
            // projectionEditResolver is allowed to be null.
            if (trackingSpans == null)
            {
                throw new ArgumentNullException(nameof(trackingSpans));
            }

            IProjectionBuffer buffer =
                new ProjectionBuffer(this, projectionEditResolver, ProjectionContentType, trackingSpans, _differenceService, _textDifferencingSelectorService.DefaultTextDifferencingService, options, _guardedOperations);
            RaiseProjectionBufferCreatedEvent(buffer);
            return buffer;
        }

        public IElisionBuffer CreateElisionBuffer(IProjectionEditResolver projectionEditResolver,
                                                  NormalizedSnapshotSpanCollection exposedSpans,
                                                  ElisionBufferOptions options,
                                                  IContentType contentType)
        {
            // projectionEditResolver is allowed to be null.
            if (exposedSpans == null)
            {
                throw new ArgumentNullException(nameof(exposedSpans));
            }
            if (exposedSpans.Count == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(exposedSpans));  // really?
            }
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            if (exposedSpans[0].Snapshot != exposedSpans[0].Snapshot.TextBuffer.CurrentSnapshot)
            {
                // TODO:
                // build against given snapshot and then move forward if necessary?
                throw new ArgumentException("Elision buffer must be created against the current snapshot of its source buffer");
            }

            IElisionBuffer buffer = new ElisionBuffer(projectionEditResolver, contentType, exposedSpans[0].Snapshot.TextBuffer,
                                                      exposedSpans, options, _textDifferencingSelectorService.DefaultTextDifferencingService, _guardedOperations);
            RaiseProjectionBufferCreatedEvent(buffer);
            return buffer;
        }

        public IElisionBuffer CreateElisionBuffer(IProjectionEditResolver projectionEditResolver,
                                                  NormalizedSnapshotSpanCollection exposedSpans,
                                                  ElisionBufferOptions options)
        {
            return CreateElisionBuffer(projectionEditResolver, exposedSpans, options, ProjectionContentType);
        }

        public event EventHandler<TextBufferCreatedEventArgs> TextBufferCreated;
        public event EventHandler<TextBufferCreatedEventArgs> ProjectionBufferCreated;

        private void RaiseTextBufferCreatedEvent(ITextBuffer buffer)
        {
            EventHandler<TextBufferCreatedEventArgs> handler = TextBufferCreated;
            if (handler != null)
            {
                handler(this, new TextBufferCreatedEventArgs(buffer));
            }
        }

        private void RaiseProjectionBufferCreatedEvent(IProjectionBufferBase buffer)
        {
            EventHandler<TextBufferCreatedEventArgs> handler = ProjectionBufferCreated;
            if (handler != null)
            {
                handler(this, new TextBufferCreatedEventArgs(buffer));
            }
        }
    }
}