-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
537 lines (447 loc) · 21.1 KB
/
MainWindow.xaml.cs
File metadata and controls
537 lines (447 loc) · 21.1 KB
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia;
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;
using Avalonia.Layout;
using AvaloniaEdit.Snippets;
using Snippet = AvaloniaEdit.Snippets.Snippet;
using AvaloniaEdit.Demo.ViewModels;
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 _insertSnippetButton;
private ComboBox _syntaxModeCombo;
private TextBlock _statusTextBlock;
private ElementGenerator _generator = new ElementGenerator();
private RegistryOptions _registryOptions;
private int _currentTheme = (int)ThemeName.DarkPlus;
private CustomMargin _customMargin;
public MainWindow()
{
InitializeComponent();
this.AttachDevTools();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.AllowToggleOverstrikeMode = true;
_textEditor.Options.EnableTextDragDrop = true;
_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;
_textEditor.Options.HighlightCurrentLine = true;
_textEditor.Options.CompletionAcceptAction = CompletionAcceptAction.DoubleTapped;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_insertSnippetButton = this.FindControl<Button>("insertSnippetBtn");
_insertSnippetButton.Click += InsertSnippetButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
_textMateInstallation.AppliedTheme += TextMateInstallationOnAppliedTheme;
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);
// Add a custom margin at the left of the text area, which can be clicked.
_customMargin = new CustomMargin();
_textEditor.TextArea.LeftMargins.Insert(0, _customMargin);
var mainWindowVM = new MainWindowViewModel(_textMateInstallation, _registryOptions);
foreach (ThemeName themeName in Enum.GetValues<ThemeName>())
{
var themeViewModel = new ThemeViewModel(themeName);
mainWindowVM.AllThemes.Add(themeViewModel);
if (themeName == ThemeName.DarkPlus)
{
mainWindowVM.SelectedTheme = themeViewModel;
}
}
DataContext = mainWindowVM;
}
private void TextMateInstallationOnAppliedTheme(object sender, TextMate.TextMate.Installation e)
{
ApplyThemeColorsToEditor(e);
ApplyThemeColorsToWindow(e);
}
void ApplyThemeColorsToEditor(TextMate.TextMate.Installation e)
{
ApplyBrushAction(e, "editor.background",brush => _textEditor.Background = brush);
ApplyBrushAction(e, "editor.foreground",brush => _textEditor.Foreground = brush);
if (!ApplyBrushAction(e, "editor.selectionBackground",
brush => _textEditor.TextArea.SelectionBrush = brush))
{
if (Application.Current!.TryGetResource("TextAreaSelectionBrush", out var resourceObject))
{
if (resourceObject is IBrush brush)
{
_textEditor.TextArea.SelectionBrush = brush;
}
}
}
if (!ApplyBrushAction(e, "editor.lineHighlightBackground",
brush =>
{
_textEditor.TextArea.TextView.CurrentLineBackground = brush;
_textEditor.TextArea.TextView.CurrentLineBorder = new Pen(brush); // Todo: VS Code didn't seem to have a border but it might be nice to have that option. For now just make it the same..
}))
{
_textEditor.TextArea.TextView.SetDefaultHighlightLineColors();
}
//Todo: looks like the margin doesn't have a active line highlight, would be a nice addition
if (!ApplyBrushAction(e, "editorLineNumber.foreground",
brush => _textEditor.LineNumbersForeground = brush))
{
_textEditor.LineNumbersForeground = _textEditor.Foreground;
}
}
private void ApplyThemeColorsToWindow(TextMate.TextMate.Installation e)
{
var panel = this.Find<StackPanel>("StatusBar");
if (panel == null)
{
return;
}
if (!ApplyBrushAction(e, "statusBar.background", brush => panel.Background = brush))
{
panel.Background = Brushes.Purple;
}
if (!ApplyBrushAction(e, "statusBar.foreground", brush => _statusTextBlock.Foreground = brush))
{
_statusTextBlock.Foreground = Brushes.White;
}
if (!ApplyBrushAction(e, "sideBar.background", brush => _customMargin.BackGroundBrush = brush))
{
_customMargin.SetDefaultBackgroundBrush();
}
//Applying the Editor background to the whole window for demo sake.
ApplyBrushAction(e, "editor.background",brush => Background = brush);
ApplyBrushAction(e, "editor.foreground",brush => Foreground = brush);
}
bool ApplyBrushAction(TextMate.TextMate.Installation e, string colorKeyNameFromJson, Action<IBrush> applyColorAction)
{
if (!e.TryGetThemeColor(colorKeyNameFromJson, out var colorString))
return false;
if (!Color.TryParse(colorString, out Color color))
return false;
var colorBrush = new SolidColorBrush(color);
applyColorAction(colorBrush);
return 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 InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
var button = new Button() { Content = "Click me", Cursor = Cursor.Default };
// The VerticalAlignment controls the alignment within a text line.
button.VerticalAlignment = VerticalAlignment.Center;
// Optionally, TextBlock.BaseLineProperty can be set. Avalonia will align the baselines
// of all elements within a line.
TextBlock.SetBaselineOffset(button, 22);
_generator.controls.Add(new Pair(_textEditor.CaretOffset, button));
_generator.controls.Sort(0, _generator.controls.Count, _generator);
_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;
for (int i = 0; i < 500; i++)
{
data.Add(new MyCompletionData("Item" + i.ToString()));
}
data.Insert(20, new MyCompletionData("long item to demosntrate dynamic poup resizing"));
_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 => $"{SelectedIndex + 1} of {Count}";
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 IImage Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => _contentControl ??= BuildContentControl();
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);
}
Control BuildContentControl()
{
TextBlock textBlock = new TextBlock();
textBlock.Text = Text;
textBlock.Margin = new Thickness(5);
return textBlock;
}
Control _contentControl;
}
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);
}
}
private void InsertSnippetButton_Click(object sender, RoutedEventArgs e)
{
var className = new SnippetReplaceableTextElement { Text = "Name" };
var snippet = new Snippet
{
Elements =
{
new SnippetTextElement { Text = "public class " },
className,
new SnippetTextElement
{
Text = "\n{\n public "
},
new SnippetBoundElement { TargetElement = className },
new SnippetTextElement { Text = "()\n {\n " },
new SnippetCaretElement(),
new SnippetTextElement { Text = "\n }\n}" }
}
};
snippet.Insert(_textEditor.TextArea);
_textEditor.Focus();
}
}
}