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

BraceCompletionStack.cs « BraceCompletion « Impl « Text « src - github.com/microsoft/vs-editor-api.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 311d49305dfc0c9195a88054bf7f50423acf6eae (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
//
//  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.BraceCompletion.Implementation
{
    using Microsoft.VisualStudio.Text;
    using Microsoft.VisualStudio.Text.BraceCompletion;
    using Microsoft.VisualStudio.Text.Editor;
    using Microsoft.VisualStudio.Text.Utilities;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;

    /// <summary>
    /// Represents the stack of active brace completion sessions.
    /// The stack handles removing sessions no longer in focus as
    /// well as marking the inner most closing brace with the 
    /// adornment.
    /// </summary>
    internal class BraceCompletionStack : IBraceCompletionStack
    {
        #region Private Members
        private Stack<IBraceCompletionSession> _stack;

        private ITextView _textView;
        private ITextBuffer _currentSubjectBuffer;

        private IBraceCompletionAdornmentServiceFactory _adornmentServiceFactory;
        private IBraceCompletionAdornmentService _adornmentService;
        private GuardedOperations _guardedOperations;
        #endregion

        #region Constructors
        public BraceCompletionStack(ITextView textView, IBraceCompletionAdornmentServiceFactory adornmentFactory, GuardedOperations guardedOperations)
        {
            _adornmentServiceFactory = adornmentFactory;
            _stack = new Stack<IBraceCompletionSession>();

            _textView = textView;
            _guardedOperations = guardedOperations;

            RegisterEvents();
        }
        #endregion

        #region IBraceCompletionStack
        public IBraceCompletionSession TopSession
        {
            get
            {
                return (_stack.Count > 0 ? _stack.Peek() : null);
            }
        }

        public void PushSession(IBraceCompletionSession session)
        {
            ITextView view = null;
            ITextBuffer buffer = null;

            _guardedOperations.CallExtensionPoint(() =>
            {
                view = session.TextView;
                buffer = session.SubjectBuffer;
            });

            if (view != null && buffer != null)
            {
                SetCurrentBuffer(buffer);
                bool validStart = false;

                // start the session to add the closing brace
                _guardedOperations.CallExtensionPoint(() =>
                {
                    session.Start();

                    // verify the session is valid before going on.
                    // some sessions may want to leave the stack at this point
                    validStart = (session.OpeningPoint != null && session.ClosingPoint != null);
                });

                if (validStart)
                {
                    // highlight the brace
                    ITrackingPoint closingPoint = null;
                    _guardedOperations.CallExtensionPoint(() =>
                    {
                        closingPoint = session.ClosingPoint;
                    });

                    HighlightSpan(closingPoint);

                    // put it on the stack for tracking
                    _stack.Push(session);
                }
            }
        }

        public ReadOnlyObservableCollection<IBraceCompletionSession> Sessions
        {
            get
            {
                return new ReadOnlyObservableCollection<IBraceCompletionSession>(new ObservableCollection<IBraceCompletionSession>(_stack));
            }
        }

        public void RemoveOutOfRangeSessions(SnapshotPoint point)
        {
            bool updateHighlightSpan = false;

            while (_stack.Count > 0 && !Contains(TopSession, point))
            {
                updateHighlightSpan = true;

                // remove the session and call Finish
                PopSession();
            }

            if (updateHighlightSpan)
            {
                HighlightSpan(TopSession != null ? TopSession.ClosingPoint : null);
            }
        }

        public void Clear()
        {
            while (_stack.Count > 0)
            {
                PopSession();
            }

            SetCurrentBuffer(null);
            HighlightSpan(null);
        }

        #endregion

        #region Events

        private void RegisterEvents()
        {
            if (_adornmentServiceFactory != null)
            {
                _adornmentService = _adornmentServiceFactory.GetOrCreateService(_textView);
            }

            _textView.Caret.PositionChanged += Caret_PositionChanged;
            _textView.Closed += TextView_Closed;
        }

        private void UnregisterEvents()
        {
            _textView.Caret.PositionChanged -= Caret_PositionChanged;
            _textView.Closed -= TextView_Closed;

            // unhook subject buffer
            SetCurrentBuffer(null);

            _textView = null;
        }

        public void ConnectSubjectBuffer(ITextBuffer subjectBuffer)
        {
            subjectBuffer.PostChanged += SubjectBuffer_PostChanged;
        }

        public void DisconnectSubjectBuffer(ITextBuffer subjectBuffer)
        {
            subjectBuffer.PostChanged -= SubjectBuffer_PostChanged;
        }

        private void TextView_Closed(object sender, EventArgs e)
        {
            UnregisterEvents();
        }

        // Remove any sessions that no longer contain the caret
        private void Caret_PositionChanged(object sender, CaretPositionChangedEventArgs e)
        {
            if (_stack.Count > 0)
            {
                // use the new position if possible, otherwise map to the subject buffer
                if (_currentSubjectBuffer != null && e.TextView.TextBuffer != _currentSubjectBuffer)
                {
                    SnapshotPoint? newPosition = e.NewPosition.Point.GetPoint(_currentSubjectBuffer, PositionAffinity.Successor);

                    if (newPosition.HasValue)
                    {
                        RemoveOutOfRangeSessions(newPosition.Value);
                    }
                    else
                    {
                        // caret is no longer in the subject buffer. probably
                        // moved to different buffer in the same view.
                        // clear all tracks
                        _stack.Clear();
                    }
                }
                else
                {
                    RemoveOutOfRangeSessions(e.NewPosition.BufferPosition);
                }
            }
        }

        // Verify that the top most session is still valid after a buffer change
        // This handles any issues that could result from text being replaced
        // or multi view scenarios where the caret is not being moved in the 
        // current view.
        private void SubjectBuffer_PostChanged(object sender, EventArgs e)
        {
            bool updateHighlightSpan = false;

            // only check the top most session
            // outer sessions could become invalid while the inner most
            // sessions stay valid, but there is no reason to check them every time
            while (_stack.Count > 0 && !IsSessionValid(TopSession))
            {
                updateHighlightSpan = true;
                _stack.Pop().Finish();
            }

            if (updateHighlightSpan)
            {
                ITrackingPoint closingPoint = null;

                if (TopSession != null)
                {
                    _guardedOperations.CallExtensionPoint(() => closingPoint = TopSession.ClosingPoint);
                }

                HighlightSpan(closingPoint);
            }
        }

        private bool IsSessionValid(IBraceCompletionSession session)
        {
            bool isValid = false;

            _guardedOperations.CallExtensionPoint(() =>
            {
                if (session.ClosingPoint != null && session.OpeningPoint != null && session.SubjectBuffer != null)
                {
                    ITextSnapshot snapshot = session.SubjectBuffer.CurrentSnapshot;
                    SnapshotPoint closingSnapshotPoint = session.ClosingPoint.GetPoint(snapshot);
                    SnapshotPoint openingSnapshotPoint = session.OpeningPoint.GetPoint(snapshot);

                    // Verify that the closing and opening points still match the expected braces
                    isValid = closingSnapshotPoint.Position > 1
                        && openingSnapshotPoint.Position <= (closingSnapshotPoint.Position - 2)
                        && openingSnapshotPoint.GetChar() == session.OpeningBrace
                        && closingSnapshotPoint.Subtract(1).GetChar() == session.ClosingBrace;
                }
            });

            return isValid;
        }

        #endregion

        #region Private Helpers

        private void SetCurrentBuffer(ITextBuffer buffer)
        {
            // Connect to the subject buffer of the session
            if (_currentSubjectBuffer != buffer)
            {
                if (_currentSubjectBuffer != null)
                {
                    DisconnectSubjectBuffer(_currentSubjectBuffer);
                }

                _currentSubjectBuffer = buffer;

                if (_currentSubjectBuffer != null)
                {
                    ConnectSubjectBuffer(_currentSubjectBuffer);
                }
            }
        }

        private void PopSession()
        {
            IBraceCompletionSession session = _stack.Pop();
            ITextBuffer nextSubjectBuffer = null;

            _guardedOperations.CallExtensionPoint(() =>
            {
                // call finish to allow the session to do any cleanup
                session.Finish();

                if (TopSession != null)
                {
                    nextSubjectBuffer = TopSession.SubjectBuffer;
                }
            });

            SetCurrentBuffer(nextSubjectBuffer);
        }

        private void HighlightSpan(ITrackingPoint point)
        {
            if (_adornmentService != null)
            {
                _adornmentService.Point = point;
            }
        }

        private bool Contains(IBraceCompletionSession session, SnapshotPoint point)
        {
            bool contains = false;

            _guardedOperations.CallExtensionPoint(() =>
            {
                // remove any sessions with nulls, if they decide they need to get off the stack
                // they can do it this way.
                if (session.OpeningPoint != null && session.ClosingPoint != null
                    && session.OpeningPoint.TextBuffer == session.ClosingPoint.TextBuffer
                    && point.Snapshot.TextBuffer == session.OpeningPoint.TextBuffer)
                {
                    ITextSnapshot snapshot = point.Snapshot;

                    contains = session.OpeningPoint.GetPosition(snapshot) < point.Position
                        && session.ClosingPoint.GetPosition(snapshot) > point.Position;
                }
            });

            return contains;
        }
        #endregion
    }
}