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
|
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Threading;
using Tango.Scripting.Editors.Document;
using Tango.Scripting.Editors.Editing;
using Tango.Scripting.Editors.Rendering;
using Tango.Scripting.Editors.Utils;
namespace Tango.Scripting.Editors.Folding
{
/// <summary>
/// Stores a list of foldings for a specific TextView and TextDocument.
/// </summary>
public class FoldingManager : IWeakEventListener
{
internal readonly TextDocument document;
internal readonly List<TextView> textViews = new List<TextView>();
readonly TextSegmentCollection<FoldingSection> foldings;
#region Constructor
/// <summary>
/// Creates a new FoldingManager instance.
/// </summary>
public FoldingManager(TextDocument document)
{
if (document == null)
throw new ArgumentNullException("document");
this.document = document;
this.foldings = new TextSegmentCollection<FoldingSection>();
document.VerifyAccess();
TextDocumentWeakEventManager.Changed.AddListener(document, this);
}
/// <summary>
/// Creates a new FoldingManager instance.
/// </summary>
[Obsolete("Use the (TextDocument) constructor instead.")]
public FoldingManager(TextView textView, TextDocument document)
: this(document)
{
}
#endregion
#region ReceiveWeakEvent
/// <inheritdoc cref="IWeakEventListener.ReceiveWeakEvent"/>
protected virtual bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
if (managerType == typeof(TextDocumentWeakEventManager.Changed)) {
OnDocumentChanged((DocumentChangeEventArgs)e);
return true;
}
return false;
}
bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
return ReceiveWeakEvent(managerType, sender, e);
}
void OnDocumentChanged(DocumentChangeEventArgs e)
{
foldings.UpdateOffsets(e);
int newEndOffset = e.Offset + e.InsertionLength;
// extend end offset to the end of the line (including delimiter)
var endLine = document.GetLineByOffset(newEndOffset);
newEndOffset = endLine.Offset + endLine.TotalLength;
foreach (var affectedFolding in foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) {
if (affectedFolding.Length == 0) {
RemoveFolding(affectedFolding);
} else {
affectedFolding.ValidateCollapsedLineSections();
}
}
}
#endregion
#region Manage TextViews
internal void AddToTextView(TextView textView)
{
if (textView == null || textViews.Contains(textView))
throw new ArgumentException();
textViews.Add(textView);
foreach (FoldingSection fs in foldings) {
if (fs.collapsedSections != null) {
Array.Resize(ref fs.collapsedSections, textViews.Count);
fs.ValidateCollapsedLineSections();
}
}
}
internal void RemoveFromTextView(TextView textView)
{
int pos = textViews.IndexOf(textView);
if (pos < 0)
throw new ArgumentException();
textViews.RemoveAt(pos);
foreach (FoldingSection fs in foldings) {
if (fs.collapsedSections != null) {
var c = new CollapsedLineSection[textViews.Count];
Array.Copy(fs.collapsedSections, 0, c, 0, pos);
fs.collapsedSections[pos].Uncollapse();
Array.Copy(fs.collapsedSections, pos + 1, c, pos, c.Length - pos);
fs.collapsedSections = c;
}
}
}
internal void Redraw()
{
foreach (TextView textView in textViews)
textView.Redraw();
}
internal void Redraw(FoldingSection fs)
{
foreach (TextView textView in textViews)
textView.Redraw(fs);
}
#endregion
#region Create / Remove / Clear
/// <summary>
/// Creates a folding for the specified text section.
/// </summary>
public FoldingSection CreateFolding(int startOffset, int endOffset)
{
if (startOffset >= endOffset)
throw new ArgumentException("startOffset must be less than endOffset");
if (startOffset < 0 || endOffset > document.TextLength)
throw new ArgumentException("Folding must be within document boundary");
FoldingSection fs = new FoldingSection(this, startOffset, endOffset);
foldings.Add(fs);
Redraw(fs);
return fs;
}
/// <summary>
/// Removes a folding section from this manager.
/// </summary>
public void RemoveFolding(FoldingSection fs)
{
if (fs == null)
throw new ArgumentNullException("fs");
fs.IsFolded = false;
foldings.Remove(fs);
Redraw(fs);
}
/// <summary>
/// Removes all folding sections.
/// </summary>
public void Clear()
{
document.VerifyAccess();
foreach (FoldingSection s in foldings)
s.IsFolded = false;
foldings.Clear();
Redraw();
}
#endregion
#region Get...Folding
/// <summary>
/// Gets all foldings in this manager.
/// The foldings are returned sorted by start offset;
/// for multiple foldings at the same offset the order is undefined.
/// </summary>
public IEnumerable<FoldingSection> AllFoldings {
get { return foldings; }
}
/// <summary>
/// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts.
/// Returns -1 if there are no foldings after <paramref name="startOffset"/>.
/// </summary>
public int GetNextFoldedFoldingStart(int startOffset)
{
FoldingSection fs = foldings.FindFirstSegmentWithStartAfter(startOffset);
while (fs != null && !fs.IsFolded)
fs = foldings.GetNextSegment(fs);
return fs != null ? fs.StartOffset : -1;
}
/// <summary>
/// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to
/// <paramref name="startOffset"/>.
/// Returns null if there are no foldings after <paramref name="startOffset"/>.
/// </summary>
public FoldingSection GetNextFolding(int startOffset)
{
// TODO: returns the longest folding instead of any folding at the first position after startOffset
return foldings.FindFirstSegmentWithStartAfter(startOffset);
}
/// <summary>
/// Gets all foldings that start exactly at <paramref name="startOffset"/>.
/// </summary>
public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset)
{
List<FoldingSection> result = new List<FoldingSection>();
FoldingSection fs = foldings.FindFirstSegmentWithStartAfter(startOffset);
while (fs != null && fs.StartOffset == startOffset) {
result.Add(fs);
fs = foldings.GetNextSegment(fs);
}
return result.AsReadOnly();
}
/// <summary>
/// Gets all foldings that contain <paramref name="offset" />.
/// </summary>
public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset)
{
return foldings.FindSegmentsContaining(offset);
}
#endregion
#region UpdateFoldings
/// <summary>
/// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings.
/// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state
/// (<see cref="FoldingSection.IsFolded"/>) for existing foldings.
/// </summary>
/// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param>
/// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after
/// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>.
/// Use -1 for this parameter if there were no parse errors.</param>
public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset)
{
if (newFoldings == null)
throw new ArgumentNullException("newFoldings");
if (firstErrorOffset < 0)
firstErrorOffset = int.MaxValue;
var oldFoldings = this.AllFoldings.ToArray();
int oldFoldingIndex = 0;
int previousStartOffset = 0;
// merge new foldings into old foldings so that sections keep being collapsed
// both oldFoldings and newFoldings are sorted by start offset
foreach (NewFolding newFolding in newFoldings) {
// ensure newFoldings are sorted correctly
if (newFolding.StartOffset < previousStartOffset)
throw new ArgumentException("newFoldings must be sorted by start offset");
previousStartOffset = newFolding.StartOffset;
int startOffset = newFolding.StartOffset.CoerceValue(0, document.TextLength);
int endOffset = newFolding.EndOffset.CoerceValue(0, document.TextLength);
if (newFolding.StartOffset == newFolding.EndOffset)
continue; // ignore zero-length foldings
// remove old foldings that were skipped
while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) {
this.RemoveFolding(oldFoldings[oldFoldingIndex++]);
}
FoldingSection section;
// reuse current folding if its matching:
if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) {
section = oldFoldings[oldFoldingIndex++];
section.Length = newFolding.EndOffset - newFolding.StartOffset;
} else {
// no matching current folding; create a new one:
section = this.CreateFolding(newFolding.StartOffset, newFolding.EndOffset);
// auto-close #regions only when opening the document
section.IsFolded = newFolding.DefaultClosed;
section.Tag = newFolding;
}
section.Title = newFolding.Name;
}
// remove all outstanding old foldings:
while (oldFoldingIndex < oldFoldings.Length) {
FoldingSection oldSection = oldFoldings[oldFoldingIndex++];
if (oldSection.StartOffset >= firstErrorOffset)
break;
this.RemoveFolding(oldSection);
}
}
#endregion
#region Install
/// <summary>
/// Adds Folding support to the specified text area.
/// Warning: The folding manager is only valid for the text area's current document. The folding manager
/// must be uninstalled before the text area is bound to a different document.
/// </summary>
/// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns>
public static FoldingManager Install(TextArea textArea)
{
if (textArea == null)
throw new ArgumentNullException("textArea");
return new FoldingManagerInstallation(textArea);
}
/// <summary>
/// Uninstalls the folding manager.
/// </summary>
/// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception>
public static void Uninstall(FoldingManager manager)
{
if (manager == null)
throw new ArgumentNullException("manager");
FoldingManagerInstallation installation = manager as FoldingManagerInstallation;
if (installation != null) {
installation.Uninstall();
} else {
throw new ArgumentException("FoldingManager was not created using FoldingManager.Install");
}
}
sealed class FoldingManagerInstallation : FoldingManager
{
TextArea textArea;
FoldingMargin margin;
FoldingElementGenerator generator;
public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document)
{
this.textArea = textArea;
margin = new FoldingMargin() { FoldingManager = this };
generator = new FoldingElementGenerator() { FoldingManager = this };
textArea.LeftMargins.Add(margin);
textArea.TextView.Services.AddService(typeof(FoldingManager), this);
// HACK: folding only works correctly when it has highest priority
textArea.TextView.ElementGenerators.Insert(0, generator);
textArea.Caret.PositionChanged += textArea_Caret_PositionChanged;
}
/*
void DemoMode()
{
foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm };
foldingMargin = new FoldingMargin { FoldingManager = fm };
foldingMarginBorder = new Border {
Child = foldingMargin,
Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0)
};
foldingMarginBorder.SizeChanged += UpdateTextViewClip;
textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator);
textEditor.TextArea.LeftMargins.Add(foldingMarginBorder);
}
void UpdateTextViewClip(object sender, SizeChangedEventArgs e)
{
textEditor.TextArea.TextView.Clip = new RectangleGeometry(
new Rect(-foldingMarginBorder.ActualWidth,
0,
textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth,
textEditor.TextArea.TextView.ActualHeight));
}
*/
public void Uninstall()
{
Clear();
if (textArea != null) {
textArea.Caret.PositionChanged -= textArea_Caret_PositionChanged;
textArea.LeftMargins.Remove(margin);
textArea.TextView.ElementGenerators.Remove(generator);
textArea.TextView.Services.RemoveService(typeof(FoldingManager));
margin = null;
generator = null;
textArea = null;
}
}
void textArea_Caret_PositionChanged(object sender, EventArgs e)
{
// Expand Foldings when Caret is moved into them.
int caretOffset = textArea.Caret.Offset;
foreach (FoldingSection s in GetFoldingsContaining(caretOffset)) {
if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) {
s.IsFolded = false;
}
}
}
}
#endregion
}
}
|