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

TextDocumentFactoryService.cs « TextModel « Impl « Text « src - github.com/microsoft/vs-editor-api.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ff59ae33712aa6bf47c8bc5a775b7d8d71a04328 (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
//
//  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.Generic;
    using System.ComponentModel.Composition;
    using System.IO;
    using System.Linq;
    using System.Text;
    using Microsoft.VisualStudio.Text.Utilities;
    using Microsoft.VisualStudio.Utilities;
    using System.Diagnostics;
    using Microsoft.VisualStudio.Text.Editor;

    [Export(typeof(ITextDocumentFactoryService))]
    internal sealed partial class TextDocumentFactoryService : ITextDocumentFactoryService
    {
        #region Internal Consumptions
        
        [Import]
        internal ITextBufferFactoryService BufferFactoryService { get; set; }

        [ImportMany]
        internal List<Lazy<IEncodingDetector, IEncodingDetectorMetadata>> UnorderedEncodingDetectors { get; set; }

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

        #endregion

        internal static Encoding DefaultEncoding = Encoding.Default; // Exposed for unit tests.

        #region ITextDocumentFactoryService Members

        public ITextDocument CreateAndLoadTextDocument(string filePath, IContentType contentType)
        {
            bool unused;
            return CreateAndLoadTextDocument(filePath, contentType, attemptUtf8Detection: true, characterSubstitutionsOccurred: out unused);
        }

        public ITextDocument CreateAndLoadTextDocument(string filePath, IContentType contentType, Encoding encoding, out bool characterSubstitutionsOccurred)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }

            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }

            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            var fallbackDetector = new FallbackDetector(encoding.DecoderFallback);
            var modifiedEncoding = (Encoding)encoding.Clone();
            modifiedEncoding.DecoderFallback = fallbackDetector;

            ITextBuffer buffer;
            DateTime lastModified;
            long fileSize;
            using (Stream stream = OpenFile(filePath, out lastModified, out fileSize))
            {
                // Caller knows best, so don't use byte order marks.
                using (StreamReader reader = new StreamReader(stream, modifiedEncoding, detectEncodingFromByteOrderMarks: false))
                {
                    System.Diagnostics.Debug.Assert(encoding.CodePage == reader.CurrentEncoding.CodePage);
                    buffer = ((ITextBufferFactoryService2)BufferFactoryService).CreateTextBuffer(reader, contentType, fileSize, filePath);
                }
            }

            characterSubstitutionsOccurred = fallbackDetector.FallbackOccurred;

#if _DEBUG
            TextUtilities.TagBuffer(buffer, filePath);
#endif
            TextDocument textDocument = new TextDocument(buffer, filePath, lastModified, this, encoding, explicitEncoding: true);

            RaiseTextDocumentCreated(textDocument);

            return textDocument;
        }

        public ITextDocument CreateAndLoadTextDocument(string filePath, IContentType contentType, bool attemptUtf8Detection, out bool characterSubstitutionsOccurred)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            characterSubstitutionsOccurred = false;

            Encoding chosenEncoding = null;
            ITextBuffer buffer = null;
            DateTime lastModified;
            long fileSize;

            // select matching detectors without instantiating any
            var detectors = ExtensionSelector.SelectMatchingExtensions(OrderedEncodingDetectors, contentType);

            using (Stream stream = OpenFile(filePath, out lastModified, out fileSize))
            {
                // First, look for a byte order marker and let the encoding detecters
                // suggest encodings.
                chosenEncoding = EncodedStreamReader.DetectEncoding(stream, detectors, GuardedOperations);

                // If that didn't produce a result, tentatively try to open as UTF 8.
                if (chosenEncoding == null && attemptUtf8Detection)
                {
                    try
                    {
                        var detectorEncoding = new ExtendedCharacterDetector();

                        using (StreamReader reader = new EncodedStreamReader.NonStreamClosingStreamReader(stream, detectorEncoding, false))
                        {
                            buffer = ((ITextBufferFactoryService2)BufferFactoryService).CreateTextBuffer(reader, contentType, fileSize, filePath);
                            characterSubstitutionsOccurred = false;
                        }

                        if (detectorEncoding.DecodedExtendedCharacters)
                        {
                            // Valid UTF-8 but has bytes that are not merely ASCII.
                            chosenEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
                        }
                        else
                        {
                            // Valid UTF8 but no extended characters, so it's valid ASCII.
                            // We don't use ASCII here because of the following scenario:
                            // The user with a non-ENU system encoding opens a code file with ASCII-only contents
                            chosenEncoding = DefaultEncoding;
                        }
                    }
                    catch (DecoderFallbackException)
                    {
                        // Not valid UTF-8.
                        // Proceed to the next if block to try the system's default codepage.
                        Debug.Assert(buffer == null);
                        buffer = null;
                        stream.Position = 0;
                    }
                }

                Debug.Assert(buffer == null || chosenEncoding != null);

                // If all else didn't work, use system's default encoding.
                if (chosenEncoding == null)
                {
                    chosenEncoding = DefaultEncoding;
                }

                if (buffer == null)
                {
                    var fallbackDetector = new FallbackDetector(chosenEncoding.DecoderFallback);
                    var modifiedEncoding = (Encoding)chosenEncoding.Clone();
                    modifiedEncoding.DecoderFallback = fallbackDetector;

                    Debug.Assert(stream.Position == 0);

                    using (StreamReader reader = new EncodedStreamReader.NonStreamClosingStreamReader(stream, modifiedEncoding, detectEncodingFromByteOrderMarks: false))
                    {
                        Debug.Assert(chosenEncoding.CodePage == reader.CurrentEncoding.CodePage);
                        buffer = ((ITextBufferFactoryService2)BufferFactoryService).CreateTextBuffer(reader, contentType, fileSize, filePath);
                    }

                    characterSubstitutionsOccurred = fallbackDetector.FallbackOccurred;
                }
            }

            TextDocument textDocument = new TextDocument(buffer, filePath, lastModified, this, chosenEncoding, attemptUtf8Detection: attemptUtf8Detection);

            RaiseTextDocumentCreated(textDocument);

            return textDocument;
        }

        public ITextDocument CreateTextDocument(ITextBuffer textBuffer, string filePath)
        {
            if (textBuffer == null)
            {
                throw new ArgumentNullException("textBuffer");
            }

            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }

            TextDocument textDocument = new TextDocument(textBuffer, filePath, DateTime.UtcNow, this, Encoding.UTF8);
            RaiseTextDocumentCreated(textDocument);

            return textDocument;
        }

        public bool TryGetTextDocument(ITextBuffer textBuffer, out ITextDocument textDocument)
        {
            if (textBuffer == null)
            {
                throw new ArgumentNullException("textBuffer");
            }

            textDocument = null;

            TextDocument document;
            if (textBuffer.Properties.TryGetProperty(typeof(ITextDocument), out document))
            {
                if(document != null && !document.IsDisposed)
                {
                    textDocument = document;
                    return true;
                }
                else
                {
                    Debug.Fail("There shouldn't be a null or disposed document in the buffer's property bag.  Did someone else put it there?");
                }
            }

            return false;
        }

        public event EventHandler<TextDocumentEventArgs> TextDocumentCreated;

        public event EventHandler<TextDocumentEventArgs> TextDocumentDisposed;

        #endregion

        #region helpers

        /// <summary>
        /// Helper method to raise the <see cref="ITextDocumentFactoryService.TextDocumentCreated"/> event.
        /// </summary>
        /// <param name="textDocument">The <see cref="ITextDocument"/> that was created.</param>
        private void RaiseTextDocumentCreated(ITextDocument textDocument)
        {
            EventHandler<TextDocumentEventArgs> documentCreated = this.TextDocumentCreated;
            if (documentCreated != null)
            {
                documentCreated.Invoke(this, new TextDocumentEventArgs(textDocument));
            }
        }

        /// <summary>
        /// Helper method to raise the <see cref="ITextDocumentFactoryService.TextDocumentDisposed"/> event.
        /// </summary>
        /// <param name="textDocument">The <see cref="ITextDocument"/> that was disposed.</param>
        internal void RaiseTextDocumentDisposed(ITextDocument textDocument)
        {
            EventHandler<TextDocumentEventArgs> documentDisposed = this.TextDocumentDisposed;
            if (documentDisposed != null)
            {
                documentDisposed.Invoke(this, new TextDocumentEventArgs(textDocument));
            }
        }

        private IList<Lazy<IEncodingDetector, IEncodingDetectorMetadata>> _orderedEncodingDetectors;

        internal IEnumerable<Lazy<IEncodingDetector, IEncodingDetectorMetadata>> OrderedEncodingDetectors
        {
            get
            {
                if (_orderedEncodingDetectors == null)
                {
                    if (UnorderedEncodingDetectors != null)
                    {
                        _orderedEncodingDetectors = Orderer.Order(UnorderedEncodingDetectors);
                    }
                    else
                    {
                        _orderedEncodingDetectors = new List<Lazy<IEncodingDetector, IEncodingDetectorMetadata>>();
                    }
                }
                return _orderedEncodingDetectors;
            }
            set // for unit test helper.
            {
                _orderedEncodingDetectors = new List<Lazy<IEncodingDetector, IEncodingDetectorMetadata>>(value);
            }
        }

        // Exposed for testing.
        internal Func<string, Stream> StreamCreator;

        private Stream OpenFile(string filePath, out DateTime lastModifiedTimeUtc, out long fileSize)
        {
            if (StreamCreator != null)
            {
                lastModifiedTimeUtc = DateTime.UtcNow;
                fileSize = -1;  // a signal that the file size is not known
                return StreamCreator(filePath);
            }
            else
            {
                return OpenFileGuts(filePath, out lastModifiedTimeUtc, out fileSize);
            }
        }

        internal static Stream OpenFileGuts(string filePath, out DateTime lastModifiedTimeUtc, out long fileSize)
        {
            // Sometimes files are held open with FILE_FLAG_DELETE_ON_CLOSE before the editor
            // is asked to open them. We should support that by allowing FileShare.Delete.
            Stream result = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
            FileInfo fileInfo = new FileInfo(filePath);
            lastModifiedTimeUtc = fileInfo.LastWriteTimeUtc;
            fileSize = fileInfo.Length;
            if (fileSize > int.MaxValue)
            {
                throw new InvalidOperationException(Strings.FileTooLarge);
            }

            return result;
        }

        // For unit testing purposes
        internal void Initialize(ITextBufferFactoryService bufferFactoryService)
        {
            Initialize(bufferFactoryService, null);
        }

        internal void Initialize(ITextBufferFactoryService bufferFactoryService, List<Lazy<IEncodingDetector, IEncodingDetectorMetadata>> detectors)
        {
            BufferFactoryService = bufferFactoryService;
            UnorderedEncodingDetectors = detectors ?? new List<Lazy<IEncodingDetector, IEncodingDetectorMetadata>>();
        }

        #endregion
    }
}