-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFormattedTextEditor.cs
More file actions
416 lines (358 loc) · 13.5 KB
/
FormattedTextEditor.cs
File metadata and controls
416 lines (358 loc) · 13.5 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
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.VisualTree;
using AvaloniaEdit;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using ScriptRunner.GUI.ViewModels;
namespace ScriptRunner.GUI.Controls;
public class FormattedTextEditor : TextEditor
{
public static readonly StyledProperty<RunningJobViewModel?> ViewModelProperty =
AvaloniaProperty.Register<FormattedTextEditor, RunningJobViewModel?>(nameof(ViewModel));
public RunningJobViewModel? ViewModel
{
get => GetValue(ViewModelProperty);
set => SetValue(ViewModelProperty, value);
}
protected override Type StyleKeyOverride { get; } = typeof(TextEditor);
private FormattedTextColorizer? _colorizer;
public event EventHandler<ScrollChangedEventArgs>? ScrollChanged;
public FormattedTextEditor()
{
IsReadOnly = true;
ShowLineNumbers = false;
WordWrap = true;
Background = new SolidColorBrush(Color.FromRgb(30,30,30));
BorderBrush = new SolidColorBrush(Color.FromRgb(62,62,54));
BorderThickness = new Thickness(1);
FontFamily = new FontFamily("Consolas");
Options.AllowScrollBelowDocument = false;
Options.RequireControlModifierForHyperlinkClick = false;
Padding = new Thickness(15);
TextArea.TextView.LinkTextForegroundBrush = Brushes.LightBlue;
TextArea.TextView.ElementGenerators.Add(new FilePathElementGenerator());
// Add context menu
ContextMenu = CreateContextMenu();
// Subscribe to scroll changes
this.Loaded += (_, _) =>
{
var scrollViewer = this.GetVisualDescendants()
.OfType<ScrollViewer>()
.FirstOrDefault();
if (scrollViewer != null)
{
scrollViewer.ScrollChanged += OnScrollChanged;
}
};
}
private ContextMenu CreateContextMenu()
{
var contextMenu = new ContextMenu();
var copySelectedItem = new MenuItem
{
Header = "Copy Selected"
};
copySelectedItem.Click += (_, _) =>
{
if (!string.IsNullOrEmpty(SelectedText))
{
CopyToClipboard(SelectedText);
}
};
var copyAllItem = new MenuItem
{
Header = "Copy All"
};
copyAllItem.Click += (_, _) =>
{
if (Document != null)
{
CopyToClipboard(Document.Text);
}
};
var selectAllItem = new MenuItem
{
Header = "Select All"
};
selectAllItem.Click += (_, _) =>
{
if (Document != null)
{
SelectionStart = 0;
SelectionLength = Document.TextLength;
}
};
var searchItem = new MenuItem
{
Header = "Search (Ctrl+F)"
};
searchItem.Click += (_, _) =>
{
// Trigger the built-in search functionality
var searchPanel = AvaloniaEdit.Search.SearchPanel.Install(this);
searchPanel?.Open();
};
contextMenu.Items.Add(copySelectedItem);
contextMenu.Items.Add(copyAllItem);
contextMenu.Items.Add(selectAllItem);
contextMenu.Items.Add(new Separator());
contextMenu.Items.Add(searchItem);
// Update menu items based on selection when opening
contextMenu.Opening += (_, _) =>
{
copySelectedItem.IsEnabled = !string.IsNullOrEmpty(SelectedText);
copyAllItem.IsEnabled = Document != null && !string.IsNullOrEmpty(Document.Text);
};
return contextMenu;
}
private async void CopyToClipboard(string text)
{
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
if (clipboard != null)
{
await clipboard.SetTextAsync(text);
}
}
private void OnScrollChanged(object? sender, ScrollChangedEventArgs e)
{
ScrollChanged?.Invoke(this, e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == ViewModelProperty)
{
if (_colorizer != null)
{
TextArea.TextView.LineTransformers.Remove(_colorizer);
}
if (ViewModel != null)
{
Document = ViewModel.RichOutput;
_colorizer = new FormattedTextColorizer(ViewModel);
TextArea.TextView.LineTransformers.Add(_colorizer);
}
}
}
}
public class FormattedTextColorizer : DocumentColorizingTransformer
{
private readonly RunningJobViewModel _viewModel;
public FormattedTextColorizer(RunningJobViewModel viewModel)
{
_viewModel = viewModel;
}
protected override void ColorizeLine(DocumentLine line)
{
int lineStartOffset = line.Offset;
int lineEndOffset = line.EndOffset;
var segments = _viewModel.FormattingSegments;
foreach (var segment in segments)
{
// Skip segments completely before this line
if (segment.StartOffset + segment.Length <= lineStartOffset)
continue;
// Stop if segment is completely after this line
if (segment.StartOffset >= lineEndOffset)
break;
int segmentStart = Math.Max(segment.StartOffset, lineStartOffset);
int segmentEnd = Math.Min(segment.StartOffset + segment.Length, lineEndOffset);
if (segmentStart >= segmentEnd)
continue;
ChangeLinePart(segmentStart, segmentEnd, element =>
{
if (segment.Foreground != null)
{
element.TextRunProperties.SetForegroundBrush(segment.Foreground);
}
if (segment.Background != null && !segment.Background.Equals(Brushes.Transparent))
{
element.TextRunProperties.SetBackgroundBrush(segment.Background);
}
var typeface = element.TextRunProperties.Typeface;
var newTypeface = new Typeface(
typeface.FontFamily,
segment.IsItalic ? FontStyle.Italic : FontStyle.Normal,
segment.IsBold ? FontWeight.Bold : FontWeight.Normal
);
element.TextRunProperties.SetTypeface(newTypeface);
// Apply text decorations (underline and/or strikethrough)
if (segment.IsUnderline || segment.IsStrikethrough)
{
var decorations = new TextDecorationCollection();
if (segment.IsUnderline)
{
decorations.Add(new TextDecoration { Location = TextDecorationLocation.Underline });
}
if (segment.IsStrikethrough)
{
decorations.Add(new TextDecoration { Location = TextDecorationLocation.Strikethrough });
}
element.TextRunProperties.SetTextDecorations(decorations);
}
});
}
}
}
/// <summary>
/// Detects file and directory paths and makes them clickable.
/// </summary>
public class FilePathElementGenerator : VisualLineElementGenerator
{
// Windows paths:
// - Starts with drive letter (C:\) or UNC path (\\server\)
// - Can contain spaces and most characters except: < > : " | ? * [ ] and control chars
// - Terminates at: whitespace, quotes, brackets, or line break
// - For files: must end with extension (.txt, .cs, etc.)
// - For dirs: can end with \ or directory name
private static readonly Regex WindowsPathRegex = new Regex(
@"(?:[a-zA-Z]:\\|\\\\[^\\]+\\[^\\]+\\)" + // Drive (C:\) or UNC (\\server\share\)
@"(?:[^<>:""|?*\[\]\r\n]+\\)*" + // Intermediate directories (can have spaces)
@"(?:[^<>:""|?*\[\]\r\n\\]+(?:\.[a-zA-Z0-9]+)?|[^<>:""|?*\[\]\r\n\\]+\\)", // Final file with extension or directory
RegexOptions.Compiled);
// Unix paths:
// - Starts with / or ~/
// - Can contain spaces in directory/file names
// - Terminates at: whitespace, quotes, brackets, or special chars
private static readonly Regex UnixPathRegex = new Regex(
@"(?:~/|/)" + // Root or home
@"(?:[^<>:""\\\|?*\[\]\s\n]+/)*" + // Directories (terminated by /)
@"[^<>:""\\\|?*\[\]\s\n]+", // Final file or directory name
RegexOptions.Compiled);
public bool RequireControlModifierForClick { get; set; }
public FilePathElementGenerator()
{
RequireControlModifierForClick = false;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
// Try Windows paths first
var match = WindowsPathRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
// If no Windows path found, try Unix paths
if (!match.Success)
{
match = UnixPathRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
}
matchOffset = match.Success ? match.Index - relevantText.Offset + startOffset : -1;
return match;
}
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
public override VisualLineElement ConstructElement(int offset)
{
var match = GetMatch(offset, out var matchOffset);
if (match.Success && matchOffset == offset)
{
var path = match.Value;
// Validate that the path exists
if (File.Exists(path) || Directory.Exists(path))
{
return new FilePathLinkText(CurrentContext.VisualLine, match.Length)
{
Path = path,
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
return null;
}
}
/// <summary>
/// Visual line element representing a clickable file path.
/// </summary>
public class FilePathLinkText : VisualLineText
{
public string Path { get; set; }
public bool RequireControlModifierForClick { get; set; }
public FilePathLinkText(VisualLine parentVisualLine, int length)
: base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
// Apply link styling
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (string.IsNullOrEmpty(Path))
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
protected override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if (e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
OpenPath(Path);
e.Handled = true;
}
}
private static void OpenPath(string path)
{
try
{
if (File.Exists(path))
{
// Open file with default application
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = path,
UseShellExecute = true
});
}
else if (Directory.Exists(path))
{
// Open directory in file explorer
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = path,
UseShellExecute = true
});
}
}
catch (Exception ex)
{
// Handle errors (log or show notification)
System.Diagnostics.Debug.WriteLine($"Failed to open path: {ex.Message}");
}
}
protected override VisualLineText CreateInstance(int length)
{
return new FilePathLinkText(ParentVisualLine, length)
{
Path = Path,
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}