-
Notifications
You must be signed in to change notification settings - Fork 154
/
MainWindow.xaml.cs
403 lines (338 loc) · 16 KB
/
MainWindow.xaml.cs
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
using Avalonia.Diagnostics;
namespace AvaloniaEdit.Demo
{
using Pair = KeyValuePair<int, Control>;
public class MainWindow : Window
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
ItemsSource = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.ItemsSource = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}