-
Notifications
You must be signed in to change notification settings - Fork 385
Expand file tree
/
Copy pathCommitMessageToolBox.axaml.cs
More file actions
641 lines (537 loc) · 22.4 KB
/
CommitMessageToolBox.axaml.cs
File metadata and controls
641 lines (537 loc) · 22.4 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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace SourceGit.Views
{
public class CommitMessageCodeCompletionData : ICompletionData
{
public IImage Image
{
get => null;
}
public string Text
{
get;
}
public object Content
{
get => Text;
}
public object Description
{
get => null;
}
public double Priority
{
get => 0;
}
public CommitMessageCodeCompletionData(string text)
{
Text = text;
}
public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
public class CommitMessageTextEditor : TextEditor
{
public static readonly StyledProperty<string> CommitMessageProperty =
AvaloniaProperty.Register<CommitMessageTextEditor, string>(nameof(CommitMessage), string.Empty);
public string CommitMessage
{
get => GetValue(CommitMessageProperty);
set => SetValue(CommitMessageProperty, value);
}
public static readonly StyledProperty<string> PlaceholderProperty =
AvaloniaProperty.Register<CommitMessageTextEditor, string>(nameof(Placeholder), string.Empty);
public string Placeholder
{
get => GetValue(PlaceholderProperty);
set => SetValue(PlaceholderProperty, value);
}
public static readonly StyledProperty<int> ColumnProperty =
AvaloniaProperty.Register<CommitMessageTextEditor, int>(nameof(Column), 1);
public int Column
{
get => GetValue(ColumnProperty);
set => SetValue(ColumnProperty, value);
}
public static readonly StyledProperty<int> SubjectLengthProperty =
AvaloniaProperty.Register<CommitMessageTextEditor, int>(nameof(SubjectLength));
public int SubjectLength
{
get => GetValue(SubjectLengthProperty);
set => SetValue(SubjectLengthProperty, value);
}
public static readonly StyledProperty<int> SubjectGuideLengthProperty =
AvaloniaProperty.Register<CommitMessageTextEditor, int>(nameof(SubjectGuideLength));
public int SubjectGuideLength
{
get => GetValue(SubjectGuideLengthProperty);
set => SetValue(SubjectGuideLengthProperty, value);
}
public static readonly StyledProperty<bool> IsSubjectWarningIconVisibleProperty =
AvaloniaProperty.Register<CommitMessageTextEditor, bool>(nameof(IsSubjectWarningIconVisible));
public bool IsSubjectWarningIconVisible
{
get => GetValue(IsSubjectWarningIconVisibleProperty);
set => SetValue(IsSubjectWarningIconVisibleProperty, value);
}
public static readonly StyledProperty<IBrush> SubjectLineBrushProperty =
AvaloniaProperty.Register<CommitMessageTextEditor, IBrush>(nameof(SubjectLineBrush), Brushes.Gray);
public IBrush SubjectLineBrush
{
get => GetValue(SubjectLineBrushProperty);
set => SetValue(SubjectLineBrushProperty, value);
}
protected override Type StyleKeyOverride => typeof(TextEditor);
public CommitMessageTextEditor() : base(new TextArea(), new TextDocument())
{
IsReadOnly = false;
WordWrap = true;
ShowLineNumbers = false;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
ClipToBounds = true;
TextArea.TextView.Margin = new Thickness(4, 2);
TextArea.TextView.ClipToBounds = false;
TextArea.TextView.Options.EnableHyperlinks = false;
TextArea.TextView.Options.EnableEmailHyperlinks = false;
}
public override void Render(DrawingContext context)
{
base.Render(context);
var w = Bounds.Width;
var pixelHeight = PixelSnapHelpers.GetPixelSize(this).Height;
var pen = new Pen(SubjectLineBrush) { DashStyle = DashStyle.Dash };
if (SubjectLength == 0)
{
var placeholder = Placeholder;
if (!string.IsNullOrEmpty(placeholder))
{
var formatted = new FormattedText(
Placeholder,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(FontFamily),
FontSize,
Brushes.Gray);
context.DrawText(formatted, new Point(4, 2));
}
return;
}
if (TextArea.TextView is not { VisualLinesValid: true } view)
return;
var lines = new List<VisualLine>();
foreach (var line in view.VisualLines)
{
if (line.IsDisposed || line.FirstDocumentLine == null || line.FirstDocumentLine.IsDeleted)
continue;
lines.Add(line);
}
if (lines.Count == 0)
return;
lines.Sort((l, r) => l.StartOffset - r.StartOffset);
for (var i = 0; i < lines.Count; i++)
{
var line = lines[i];
if (line.FirstDocumentLine.LineNumber == _subjectEndLine)
{
var y = line.GetTextLineVisualYPosition(line.TextLines[^1], VisualYPosition.LineBottom) - view.VerticalOffset + 4;
y = PixelSnapHelpers.PixelAlign(y, pixelHeight);
context.DrawLine(pen, new Point(0, y), new Point(w, y));
var subjectEndTip = new FormattedText(
"SUBJECT END",
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(FontFamily, FontStyle.Italic),
10,
Brushes.Gray);
context.DrawText(subjectEndTip, new Point(w - subjectEndTip.WidthIncludingTrailingWhitespace - 6, y + 1));
return;
}
}
}
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
TextArea.TextView.VisualLinesChanged += OnTextViewVisualLinesChanged;
TextArea.TextView.ContextRequested += OnTextViewContextRequested;
TextArea.Caret.PositionChanged += OnCaretPositionChanged;
}
protected override void OnUnloaded(RoutedEventArgs e)
{
TextArea.TextView.ContextRequested -= OnTextViewContextRequested;
TextArea.TextView.VisualLinesChanged -= OnTextViewVisualLinesChanged;
TextArea.Caret.PositionChanged -= OnCaretPositionChanged;
base.OnUnloaded(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == CommitMessageProperty)
{
if (!_isEditing)
Text = CommitMessage;
var lines = CommitMessage.ReplaceLineEndings("\n").Split('\n');
var subjectLen = 0;
var foundSubjectEnd = false;
for (var i = 0; i < lines.Length; i++)
{
var line = lines[i];
if (string.IsNullOrWhiteSpace(line))
{
if (subjectLen == 0)
continue;
_subjectEndLine = i;
foundSubjectEnd = true;
break;
}
var validCharLen = line.TrimEnd().Length;
if (subjectLen > 0)
subjectLen += (validCharLen + 1);
else
subjectLen = validCharLen;
}
if (!foundSubjectEnd)
_subjectEndLine = lines.Length;
SetCurrentValue(SubjectLengthProperty, subjectLen);
}
else if (change.Property == PlaceholderProperty && IsLoaded)
{
if (string.IsNullOrWhiteSpace(CommitMessage))
InvalidateVisual();
}
else if (change.Property == SubjectLengthProperty ||
change.Property == SubjectGuideLengthProperty)
{
SetCurrentValue(IsSubjectWarningIconVisibleProperty, SubjectLength > SubjectGuideLength);
}
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
if (!IsLoaded)
return;
_isEditing = true;
SetCurrentValue(CommitMessageProperty, Text);
_isEditing = false;
var caretOffset = CaretOffset;
var lineStart = caretOffset;
for (; lineStart > 0; lineStart--)
{
var ch = Text[lineStart - 1];
if (ch == '\n')
break;
if (!char.IsAscii(ch))
return;
}
if (lineStart == 0 || caretOffset < lineStart + 2)
{
_completionWnd?.Close();
return;
}
var word = Text.Substring(lineStart, caretOffset - lineStart);
var matches = new List<CommitMessageCodeCompletionData>();
foreach (var t in _trailers)
{
if (t.StartsWith(word, StringComparison.OrdinalIgnoreCase) && t.Length != word.Length)
matches.Add(new(t));
}
if (matches.Count > 0)
{
if (_completionWnd == null)
{
_completionWnd = new CompletionWindow(TextArea);
_completionWnd.Closed += (_, _) => _completionWnd = null;
_completionWnd.Show();
}
_completionWnd.CompletionList.CompletionData.Clear();
_completionWnd.CompletionList.CompletionData.AddRange(matches);
_completionWnd.StartOffset = lineStart;
_completionWnd.EndOffset = caretOffset;
}
else
{
_completionWnd?.Close();
}
}
private void OnTextViewContextRequested(object sender, ContextRequestedEventArgs e)
{
var selection = TextArea.Selection;
var hasSelected = selection is { IsEmpty: false };
var copy = new MenuItem();
copy.Header = App.Text("Copy");
copy.Icon = this.CreateMenuIcon("Icons.Copy");
copy.IsEnabled = hasSelected;
copy.Click += (_, ev) =>
{
Copy();
ev.Handled = true;
};
var cut = new MenuItem();
cut.Header = App.Text("Cut");
cut.Icon = this.CreateMenuIcon("Icons.Cut");
cut.IsEnabled = hasSelected;
cut.Click += (_, ev) =>
{
Cut();
ev.Handled = true;
};
var paste = new MenuItem();
paste.Header = App.Text("Paste");
paste.Icon = this.CreateMenuIcon("Icons.Paste");
paste.Click += (_, ev) =>
{
Paste();
ev.Handled = true;
};
var menu = new ContextMenu();
menu.Items.Add(copy);
menu.Items.Add(cut);
menu.Items.Add(paste);
menu.Open(TextArea.TextView);
e.Handled = true;
}
private void OnTextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateVisual();
}
private void OnCaretPositionChanged(object sender, EventArgs e)
{
var col = TextArea.Caret.Column;
SetCurrentValue(ColumnProperty, col);
}
private readonly List<string> _trailers =
[
"Acked-by: ",
"BREAKING CHANGE: ",
"Co-authored-by: ",
"Fixes: ",
"Helped-by: ",
"Issue: ",
"Milestone: ",
"on-behalf-of: @",
"Reference-to: ",
"Refs: ",
"Reviewed-by: ",
"See-also: ",
"Signed-off-by: ",
];
private bool _isEditing = false;
private int _subjectEndLine = 0;
private CompletionWindow _completionWnd = null;
}
public partial class CommitMessageToolBox : UserControl
{
public static readonly StyledProperty<bool> ShowAdvancedOptionsProperty =
AvaloniaProperty.Register<CommitMessageToolBox, bool>(nameof(ShowAdvancedOptions));
public bool ShowAdvancedOptions
{
get => GetValue(ShowAdvancedOptionsProperty);
set => SetValue(ShowAdvancedOptionsProperty, value);
}
public static readonly StyledProperty<string> CommitMessageProperty =
AvaloniaProperty.Register<CommitMessageToolBox, string>(nameof(CommitMessage), string.Empty);
public string CommitMessage
{
get => GetValue(CommitMessageProperty);
set => SetValue(CommitMessageProperty, value);
}
public CommitMessageToolBox()
{
InitializeComponent();
}
private async void OnOpenCommitMessagePicker(object sender, RoutedEventArgs e)
{
if (sender is Button button && DataContext is ViewModels.WorkingCopy vm && ShowAdvancedOptions)
{
var repo = vm.Repository;
var foreground = this.FindResource("Brush.FG1") as IBrush;
var menu = new ContextMenu();
menu.MaxWidth = 480;
var gitTemplate = await new Commands.Config(repo.FullPath).GetAsync("commit.template");
var templateCount = repo.Settings.CommitTemplates.Count;
if (templateCount == 0 && string.IsNullOrEmpty(gitTemplate))
{
menu.Items.Add(new MenuItem()
{
Header = App.Text("WorkingCopy.NoCommitTemplates"),
Icon = this.CreateMenuIcon("Icons.Code"),
IsEnabled = false
});
}
else
{
for (int i = 0; i < templateCount; i++)
{
var icon = this.CreateMenuIcon("Icons.Code");
icon.Fill = foreground;
var template = repo.Settings.CommitTemplates[i];
var item = new MenuItem();
item.Header = App.Text("WorkingCopy.UseCommitTemplate", template.Name);
item.Icon = icon;
item.Click += (_, ev) =>
{
vm.ApplyCommitMessageTemplate(template);
ev.Handled = true;
};
menu.Items.Add(item);
}
if (!string.IsNullOrEmpty(gitTemplate))
{
if (!Path.IsPathRooted(gitTemplate))
gitTemplate = Native.OS.GetAbsPath(repo.FullPath, gitTemplate);
var friendlyName = gitTemplate;
if (!OperatingSystem.IsWindows())
{
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var prefixLen = home.EndsWith('/') ? home.Length - 1 : home.Length;
if (gitTemplate.StartsWith(home, StringComparison.Ordinal))
friendlyName = $"~{gitTemplate.AsSpan(prefixLen)}";
}
var icon = this.CreateMenuIcon("Icons.Code");
icon.Fill = foreground;
var gitTemplateItem = new MenuItem();
gitTemplateItem.Header = App.Text("WorkingCopy.UseCommitTemplate", friendlyName);
gitTemplateItem.Icon = icon;
gitTemplateItem.Click += (_, ev) =>
{
if (File.Exists(gitTemplate))
vm.CommitMessage = File.ReadAllText(gitTemplate);
ev.Handled = true;
};
menu.Items.Add(gitTemplateItem);
}
}
menu.Items.Add(new MenuItem() { Header = "-" });
var historiesCount = repo.Settings.CommitMessages.Count;
if (historiesCount == 0)
{
menu.Items.Add(new MenuItem()
{
Header = App.Text("WorkingCopy.NoCommitHistories"),
Icon = this.CreateMenuIcon("Icons.Histories"),
IsEnabled = false
});
}
else
{
for (int i = 0; i < historiesCount; i++)
{
var dup = repo.Settings.CommitMessages[i].Trim();
var header = new TextBlock()
{
Text = dup.ReplaceLineEndings(" "),
VerticalAlignment = VerticalAlignment.Center,
TextTrimming = TextTrimming.CharacterEllipsis
};
var icon = this.CreateMenuIcon("Icons.Histories");
icon.Fill = foreground;
var item = new MenuItem();
item.Header = header;
item.Icon = icon;
item.Click += (_, ev) =>
{
vm.CommitMessage = dup;
ev.Handled = true;
};
menu.Items.Add(item);
}
menu.Items.Add(new MenuItem() { Header = "-" });
var clearIcon = this.CreateMenuIcon("Icons.Clear");
clearIcon.Fill = foreground;
var clearHistoryItem = new MenuItem();
clearHistoryItem.Header = App.Text("WorkingCopy.ClearCommitHistories");
clearHistoryItem.Icon = clearIcon;
clearHistoryItem.Click += async (_, ev) =>
{
await vm.ClearCommitMessageHistoryAsync();
ev.Handled = true;
};
menu.Items.Add(clearHistoryItem);
}
button.IsEnabled = false;
menu.Placement = PlacementMode.TopEdgeAlignedLeft;
menu.Closed += (_, _) => button.IsEnabled = true;
menu.Open(button);
}
e.Handled = true;
}
private async void OnOpenOpenAIHelper(object sender, RoutedEventArgs e)
{
if (DataContext is ViewModels.WorkingCopy vm && sender is Button button && ShowAdvancedOptions)
{
var repo = vm.Repository;
if (vm.Staged == null || vm.Staged.Count == 0)
{
repo.SendNotification("No files added to commit!", true);
e.Handled = true;
return;
}
var services = repo.GetPreferredOpenAIServices();
if (services.Count == 0)
{
repo.SendNotification("Bad configuration for OpenAI", true);
e.Handled = true;
return;
}
if (services.Count == 1)
{
await App.ShowDialog(new ViewModels.AIAssistant(repo, services[0], vm.Staged));
e.Handled = true;
return;
}
var menu = new ContextMenu();
foreach (var service in services)
{
var dup = service;
var item = new MenuItem();
item.Header = service.Name;
item.Click += async (_, ev) =>
{
await App.ShowDialog(new ViewModels.AIAssistant(repo, dup, vm.Staged));
ev.Handled = true;
};
menu.Items.Add(item);
}
button.IsEnabled = false;
menu.Placement = PlacementMode.TopEdgeAlignedLeft;
menu.Closed += (_, _) => button.IsEnabled = true;
menu.Open(button);
}
e.Handled = true;
}
private void OnOpenConventionalCommitHelper(object _, RoutedEventArgs e)
{
var owner = TopLevel.GetTopLevel(this) as Window;
if (owner == null)
return;
var conventionalTypesOverride = owner switch
{
Launcher { DataContext: ViewModels.Launcher { ActivePage: { Data: ViewModels.Repository repo } } } => repo.Settings.ConventionalTypesOverride,
RepositoryConfigure { DataContext: ViewModels.RepositoryConfigure config } => config.ConventionalTypesOverride,
CommitMessageEditor editor => editor.ConventionalTypesOverride,
_ => string.Empty
};
var vm = new ViewModels.ConventionalCommitMessageBuilder(conventionalTypesOverride, text => CommitMessage = text);
var builder = new ConventionalCommitMessageBuilder() { DataContext = vm };
builder.Show(owner);
e.Handled = true;
}
}
}