-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
RevisionGridControl.cs
3147 lines (2661 loc) · 125 KB
/
RevisionGridControl.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
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using GitCommands;
using GitCommands.Config;
using GitCommands.Git;
using GitExtUtils;
using GitExtUtils.GitUI;
using GitExtUtils.GitUI.Theming;
using GitUI.Avatars;
using GitUI.BuildServerIntegration;
using GitUI.CommandDialogs;
using GitUI.CommandsDialogs;
using GitUI.CommandsDialogs.BrowseDialog;
using GitUI.HelperDialogs;
using GitUI.Hotkey;
using GitUI.Properties;
using GitUI.UserControls;
using GitUI.UserControls.RevisionGrid;
using GitUI.UserControls.RevisionGrid.Columns;
using GitUIPluginInterfaces;
using Microsoft;
using Microsoft.VisualStudio.Threading;
using ResourceManager;
using TaskDialog = System.Windows.Forms.TaskDialog;
using TaskDialogButton = System.Windows.Forms.TaskDialogButton;
namespace GitUI
{
public enum RevisionGraphDrawStyle
{
Normal,
DrawNonRelativesGray,
HighlightSelected
}
public enum SortDirection
{
/// <summary>
/// Sort from smallest to largest. For example, A to Z.
/// </summary>
Ascending,
/// <summary>
/// Sort from largest to smallest. For example, Z to A.
/// </summary>
Descending
}
[DefaultEvent("DoubleClick")]
public sealed partial class RevisionGridControl : GitModuleControl, ICheckRefs, IRevisionGridFilter, IRevisionGridInfo, IRevisionGridUpdate
{
public event EventHandler<DoubleClickRevisionEventArgs>? DoubleClickRevision;
public event EventHandler<FilterChangedEventArgs>? FilterChanged;
public event EventHandler? SelectionChanged;
/// <summary>
/// Occurs whenever the revision graph has started loading the data.
/// </summary>
public event EventHandler<RevisionLoadEventArgs>? RevisionsLoading;
/// <summary>
/// Occurs whenever the revision graph has been populated with the data.
/// </summary>
public event EventHandler<RevisionLoadEventArgs>? RevisionsLoaded;
/// <summary>
/// Occurs whenever a user toggles between the artificial and the HEAD commits
/// via the navigation menu item or the shortcut command.
/// </summary>
public event EventHandler? ToggledBetweenArtificialAndHeadCommits;
public static readonly string HotkeySettingsName = "RevisionGrid";
private readonly TranslationString _droppingFilesBlocked = new("For you own protection dropping more than 10 patch files at once is blocked!");
private readonly TranslationString _noRevisionFoundError = new("No revision found.");
private readonly TranslationString _baseForCompareNotSelectedError = new("Base commit for compare is not selected.");
private readonly TranslationString _strLoading = new("Loading");
private readonly TranslationString _rebaseConfirmTitle = new("Rebase Confirmation");
private readonly TranslationString _rebaseBranch = new("Rebase branch.");
private readonly TranslationString _rebaseBranchInteractive = new("Rebase branch interactively.");
private readonly TranslationString _areYouSureRebase = new("Are you sure you want to rebase? This action will rewrite commit history.");
private readonly TranslationString _dontShowAgain = new("Don't show me this message again.");
private readonly TranslationString _noMergeBaseCommit = new("There is no common ancestor for the selected commits.");
private readonly TranslationString _invalidDiffContainsFilter = new("Filter text '{0}' not valid for \"Diff contains\" filter.");
private readonly FilterInfo _filterInfo = new();
private readonly NavigationHistory _navigationHistory = new();
private readonly Control _loadingControlText;
private readonly Control _loadingControlSpinner;
private readonly RevisionGridToolTipProvider _toolTipProvider;
private readonly QuickSearchProvider _quickSearchProvider;
private readonly ParentChildNavigationHistory _parentChildNavigationHistory;
private readonly AuthorRevisionHighlighting _authorHighlighting;
private readonly Lazy<IndexWatcher> _indexWatcher;
private readonly BuildServerWatcher _buildServerWatcher;
private readonly System.Windows.Forms.Timer _selectionTimer;
private readonly RevisionGraphColumnProvider _revisionGraphColumnProvider;
private readonly DataGridViewColumn _maximizedColumn;
private DataGridViewColumn? _lastVisibleResizableColumn;
private readonly ArtificialCommitChangeCount _workTreeChangeCount = new();
private readonly ArtificialCommitChangeCount _indexChangeCount = new();
private readonly CancellationTokenSequence _customDiffToolsSequence = new();
private readonly CancellationTokenSequence _refreshRevisionsSequence = new();
/// <summary>
/// The set of ref names that are ambiguous.
/// Any refs present in this collection should be displayed using their full name.
/// </summary>
private Lazy<IReadOnlyCollection<string>>? _ambiguousRefs;
private int _suspendRefreshCounter;
private IDisposable? _revisionSubscription;
private GitRevision? _baseCommitToCompare;
private string? _rebaseOnTopOf;
private bool _isRefreshingRevisions;
private SuperProjectInfo? _superprojectCurrentCheckout;
private int _latestSelectedRowIndex;
// NOTE internal properties aren't serialised by the WinForms designer
internal ObjectId? CurrentCheckout { get; private set; }
internal Lazy<string> CurrentBranch { get; private set; } = new(() => "");
internal FilterInfo CurrentFilter => _filterInfo;
internal bool ShowUncommittedChangesIfPossible { get; set; } = true;
internal bool ShowBuildServerInfo { get; set; }
internal bool DoubleClickDoesNotOpenCommitInfo { get; set; }
/// <summary>
/// The last selected commit in the grid (with related CommitInfo in Browse).
/// </summary>
internal ObjectId? SelectedId { private get; set; }
/// <summary>
/// The first selected, the first commit in a diff.
/// </summary>
internal ObjectId? FirstId { private get; set; }
internal RevisionGridMenuCommands MenuCommands { get; }
/// <summary>
/// The (first) seen name for commits, for FileHistory with path filters.
/// See BuildFilter() for limitations of commits included.
/// The property is explicitly initialized by FileHistory.
/// </summary>
internal Dictionary<ObjectId, string>? FilePathByObjectId { get; set; } = null;
public RevisionGridControl()
{
InitializeComponent();
openPullRequestPageStripMenuItem.AdaptImageLightness();
renameBranchToolStripMenuItem.AdaptImageLightness();
InitializeComplete();
_loadingControlText = new Label
{
Padding = DpiUtil.Scale(new Padding(7, 5, 7, 5)),
BorderStyle = BorderStyle.None,
ForeColor = SystemColors.InfoText,
BackColor = SystemColors.Info,
Font = AppSettings.Font,
Visible = false,
UseMnemonic = false,
AutoSize = true,
Text = _strLoading.Text
};
Controls.Add(_loadingControlText);
_loadingControlSpinner = new WaitSpinner
{
BackColor = SystemColors.Window,
Visible = false,
Size = DpiUtil.Scale(new Size(50, 50))
};
Controls.Add(_loadingControlSpinner);
// Delay raising the SelectionChanged event for a barely noticeable period to throttle
// rapid changes, for example by holding the down arrow key in the revision grid.
// 75ms is longer than the default keyboard repeat rate of 15 keypresses per second.
_selectionTimer = new System.Windows.Forms.Timer(components) { Interval = 75 };
_selectionTimer.Tick += (_, e) =>
{
_selectionTimer.Stop();
SelectionChanged?.Invoke(this, e);
};
_toolTipProvider = new RevisionGridToolTipProvider(_gridView);
_quickSearchProvider = new QuickSearchProvider(_gridView, () => Module.WorkingDir);
// Parent-child navigation can expect that SetSelectedRevision is always successful since it always uses first-parents
_parentChildNavigationHistory = new ParentChildNavigationHistory(objectId =>
{
if (!SetSelectedRevision(objectId))
{
MessageBoxes.RevisionFilteredInGrid(this, objectId);
}
});
_authorHighlighting = new AuthorRevisionHighlighting();
_indexWatcher = new Lazy<IndexWatcher>(() => new IndexWatcher(UICommandsSource));
copyToClipboardToolStripMenuItem.SetRevisionFunc(() => GetSelectedRevisions());
MenuCommands = new RevisionGridMenuCommands(this);
HotkeysEnabled = true;
// fill View context menu from MenuCommands
FillMenuFromMenuCommands(MenuCommands.ViewMenuCommands, viewToolStripMenuItem);
// fill Navigate context menu from MenuCommands
FillMenuFromMenuCommands(MenuCommands.NavigateMenuCommands, navigateToolStripMenuItem);
// Apply checkboxes changes also to FormBrowse main menu
MenuCommands.TriggerMenuChanged();
_gridView.ShowCellToolTips = false;
_gridView.AuthorHighlighting = _authorHighlighting;
_gridView.KeyPress += (_, e) => _quickSearchProvider.OnKeyPress(e);
_gridView.MouseDown += OnGridViewMouseDown;
_gridView.CellMouseDown += OnGridViewCellMouseDown;
_gridView.MouseDoubleClick += OnGridViewDoubleClick;
_gridView.MouseClick += OnGridViewMouseClick;
_gridView.CellMouseMove += (_, e) => _toolTipProvider.OnCellMouseMove(e);
// Allow to drop patch file on revision grid
_gridView.AllowDrop = true;
_gridView.DragEnter += OnGridViewDragEnter;
_gridView.DragDrop += OnGridViewDragDrop;
_buildServerWatcher = new BuildServerWatcher(revisionGrid: this, _gridView, revisionGridInfo: this, () => Module);
GitRevisionSummaryBuilder gitRevisionSummaryBuilder = new();
_revisionGraphColumnProvider = new RevisionGraphColumnProvider(_gridView._revisionGraph, gitRevisionSummaryBuilder);
_gridView.AddColumn(_revisionGraphColumnProvider);
_gridView.AddColumn(new MessageColumnProvider(this, gitRevisionSummaryBuilder));
_gridView.AddColumn(new AvatarColumnProvider(_gridView, AvatarService.DefaultProvider, AvatarService.CacheCleaner));
_gridView.AddColumn(new AuthorNameColumnProvider(this, _authorHighlighting));
_gridView.AddColumn(new DateColumnProvider(this));
_gridView.AddColumn(new CommitIdColumnProvider(this));
_gridView.AddColumn(_buildServerWatcher.ColumnProvider);
_maximizedColumn = _gridView.Columns.Cast<DataGridViewColumn>()
.FirstOrDefault(column => column.Resizable == DataGridViewTriState.True && column.AutoSizeMode == DataGridViewAutoSizeColumnMode.Fill);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
//// MenuCommands not disposable
//// _superprojectCurrentCheckout not disposable
//// _selectedObjectIds not disposable
//// _baseCommitToCompare not disposable
_revisionSubscription?.Dispose();
//// _artificialStatus not disposable
//// _ambiguousRefs not disposable
//// _refFilterOptions not disposable
//// _lastVisibleResizableColumn not owned
//// _maximizedColumn not owned
//// _revisionGraphColumnProvider not disposable
//// _selectionTimer handled by this.components
_buildServerWatcher?.Dispose();
_customDiffToolsSequence.Dispose();
_refreshRevisionsSequence.Dispose();
if (_indexWatcher.IsValueCreated)
{
_indexWatcher.Value.Dispose();
}
//// _authorHighlighting not disposable
//// _parentChildNavigationHistory not disposable
//// _quickSearchProvider not disposable
//// _toolTipProvider not disposable
//// _loadingControlSync handled by this.Controls
//// _loadingControlAsync handled by this.Controls
//// _navigationHistory not disposable
components?.Dispose();
if (!Controls.Contains(_gridView))
{
// Dispose _gridView explicitly since it won't be disposed automatically
_gridView.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// Reset the controls to the supplied content.
/// This is used to remove spinners added when loading and to replace the gridview at errors.
/// </summary>
/// <param name="content">The content to show.</param>
private void SetPage(Control content)
{
for (int i = Controls.Count - 1; i >= 0; i--)
{
Control oldControl = Controls[i];
if (!oldControl.Equals(content))
{
Controls.RemoveAt(i);
}
}
if (Controls.Count == 0)
{
Controls.Add(content);
}
}
internal int DrawColumnText(DataGridViewCellPaintingEventArgs e, string text, Font font, Color color, Rectangle bounds, bool useEllipsis = true)
{
TextFormatFlags flags =
TextFormatFlags.NoPrefix |
TextFormatFlags.VerticalCenter |
TextFormatFlags.NoPadding |
TextFormatFlags.SingleLine;
if (useEllipsis)
{
flags |= TextFormatFlags.EndEllipsis;
}
Size size = TextRenderer.MeasureText(e.Graphics, text, font, bounds.Size, flags);
TextRenderer.DrawText(e.Graphics, text, font, bounds, color, flags);
_toolTipProvider.SetTruncation(e.ColumnIndex, e.RowIndex, truncated: size.Width > bounds.Width);
return size.Width;
}
internal IndexWatcher IndexWatcher => _indexWatcher.Value;
internal GitRevision? LatestSelectedRevision => IsValidRevisionIndex(_latestSelectedRowIndex) ? GetRevision(_latestSelectedRowIndex) : null;
internal bool MultiSelect
{
get => _gridView.MultiSelect;
set => _gridView.MultiSelect = value;
}
private static void FillMenuFromMenuCommands(IEnumerable<MenuCommand> menuCommands, ToolStripDropDownItem targetItem)
{
foreach (MenuCommand menuCommand in menuCommands)
{
ToolStripItem item = MenuCommand.CreateToolStripItem(menuCommand);
if (item is ToolStripMenuItem menuItem)
{
menuCommand.RegisterMenuItem(menuItem);
}
targetItem.DropDownItems.Add(item);
}
}
// returns " --find-renames=..." according to app settings
private static ArgumentString FindRenamesOpt()
{
return AppSettings.FollowRenamesInFileHistoryExactOnly
? " --find-renames=\"100%\""
: " --find-renames";
}
// returns " --find-renames=... --find-copies=..." according to app settings
private static ArgumentString FindRenamesAndCopiesOpts()
{
string findCopies = AppSettings.FollowRenamesInFileHistoryExactOnly
? " --find-copies=\"100%\""
: " --find-copies";
return FindRenamesOpt() + findCopies;
}
public void ResetAllFilters()
{
_filterInfo.ResetAllFilters();
}
public void ResetAllFiltersAndRefresh()
{
_filterInfo.ResetAllFilters();
PerformRefreshRevisions();
}
public void SetAndApplyPathFilter(string filter)
{
_filterInfo.ByPathFilter = !string.IsNullOrWhiteSpace(filter);
if (_filterInfo.ByPathFilter)
{
_filterInfo.PathFilter = filter;
}
PerformRefreshRevisions();
}
private void InitiateRefAction(IReadOnlyList<IGitRef>? gitRefs, Action<IGitRef> action, FormQuickGitRefSelector.Action actionLabel)
{
if (gitRefs?.Count is not > 0)
{
return;
}
if (gitRefs.Count == 1)
{
action(gitRefs[0]);
return;
}
using FormQuickGitRefSelector dlg = new();
dlg.Init(actionLabel, gitRefs);
dlg.Location = GetQuickItemSelectorLocation();
if (dlg.ShowDialog(ParentForm) != DialogResult.OK || dlg.SelectedRef is null)
{
return;
}
action(dlg.SelectedRef);
}
public Point GetQuickItemSelectorLocation()
{
Rectangle rect = _gridView.GetCellDisplayRectangle(0, _latestSelectedRowIndex, true);
return PointToScreen(new Point(rect.Right, rect.Bottom));
}
#region Navigation
private void ResetNavigationHistory()
{
_navigationHistory.Clear();
}
public void NavigateBackward()
{
if (_navigationHistory.CanNavigateBackward)
{
ObjectId objectId = _navigationHistory.NavigateBackward();
if (!SetSelectedRevision(objectId))
{
MessageBoxes.RevisionFilteredInGrid(this, objectId);
}
}
}
public void NavigateForward()
{
if (_navigationHistory.CanNavigateForward)
{
ObjectId objectId = _navigationHistory.NavigateForward();
if (!SetSelectedRevision(objectId))
{
MessageBoxes.RevisionFilteredInGrid(this, objectId);
}
}
}
#endregion
public void DisableContextMenu()
{
_gridView.ContextMenuStrip = null;
}
/// <summary>
/// Prevents revisions refreshes and stops <see cref="PerformRefreshRevisions"/> from executing
/// until <see cref="ResumeRefreshRevisions"/> is called.
/// </summary>
internal void SuspendRefreshRevisions() => ++_suspendRefreshCounter;
/// <summary>
/// Resume revisions refreshes.
/// </summary>
internal void ResumeRefreshRevisions()
{
--_suspendRefreshCounter;
DebugHelpers.Assert(_suspendRefreshCounter >= 0, $"{nameof(ResumeRefreshRevisions)} was called without matching {nameof(SuspendRefreshRevisions)}!");
}
public void SetAndApplyBranchFilter(string filter)
{
_filterInfo.SetBranchFilter(filter);
PerformRefreshRevisions();
}
/// <summary>
/// Applies a revision filter.
/// </summary>
/// <param name="filter">The filter to apply.</param>
/// <exception cref="InvalidOperationException">Invalid 'diff contains' filter.</exception>
public void SetAndApplyRevisionFilter(RevisionFilter filter)
{
bool changed = _filterInfo.Apply(filter);
if (!changed)
{
return;
}
PerformRefreshRevisions();
}
public override void Refresh()
{
if (IsDisposed)
{
return;
}
if (_lastVisibleResizableColumn is not null)
{
// restore its resizable state
_lastVisibleResizableColumn.Resizable = DataGridViewTriState.True;
}
_gridView.Refresh(); // columns could change their Resizable state, e.g. the BuildStatusColumnProvider
base.Refresh();
_toolTipProvider.Clear();
// suppress the manual resizing of the last visible column because it will be resized when the maximized column is resized
//// LINQ because the following did not work reliable:
//// _lastVisibleResizableColumn = _gridView.Columns.GetLastColumn(DataGridViewElementStates.Visible | DataGridViewElementStates.Resizable, DataGridViewElementStates.None);
_lastVisibleResizableColumn = _gridView.Columns.Cast<DataGridViewColumn>()
.OrderBy(column => column.Index).Last(column => column.Visible && column.Resizable == DataGridViewTriState.True);
if (_lastVisibleResizableColumn is not null)
{
_lastVisibleResizableColumn.Resizable = DataGridViewTriState.False;
}
}
protected override void OnCreateControl()
{
base.OnCreateControl();
ShowLoading();
}
protected override void OnRuntimeLoad()
{
base.OnRuntimeLoad();
ReloadHotkeys();
LoadCustomDifftools();
}
public new void Load()
{
if (!DesignMode)
{
PerformRefreshRevisions();
}
}
public void LoadCustomDifftools()
{
List<CustomDiffMergeTool> menus =
[
new(openCommitsWithDiffToolMenuItem, diffSelectedCommitsMenuItem_Click)
];
new CustomDiffMergeToolProvider().LoadCustomDiffMergeTools(Module, menus, components, isDiff: true, cancellationToken: _customDiffToolsSequence.Next());
}
public void CancelLoadCustomDifftools()
{
_customDiffToolsSequence.CancelCurrent();
}
/// <summary>
/// Selects row containing revision matching <paramref name="objectId"/>.
/// Returns whether the required revision was found and selected.
/// </summary>
/// <param name="objectId">Id of the revision to select.</param>
/// <param name="toggleSelection">Toggle if the selected state for the revision.</param>
/// <returns><c>true</c> if the required revision was found and selected, otherwise <c>false</c>.</returns>
public bool SetSelectedRevision(ObjectId? objectId, bool toggleSelection = false, bool updateNavigationHistory = true)
{
_gridView.ClearToBeSelected();
if (_gridView.TryGetRevisionIndex(objectId) is not int index || index < 0 || index >= _gridView.RowCount)
{
return false;
}
Validates.NotNull(objectId);
SetSelectedIndex(_gridView, index, toggleSelection);
if (updateNavigationHistory)
{
_navigationHistory.Push(objectId);
}
return true;
static void SetSelectedIndex(RevisionDataGridView gridView, int index, bool toggleSelection = false)
{
try
{
gridView.Select();
// Prevent exception when changing of repository because the grid still contains no rows.
if (index >= gridView.Rows.Count)
{
return;
}
bool shallSelect;
bool wasSelected = gridView.Rows[index].Selected;
if (toggleSelection)
{
// Toggle the selection, but do not deselect if it is the last one.
shallSelect = !wasSelected || gridView.SelectedRows.Count == 1;
}
else
{
// Single select this line.
shallSelect = true;
if (!wasSelected || gridView.SelectedRows.Count > 1)
{
gridView.ClearSelection();
wasSelected = false;
}
}
if (wasSelected && shallSelect)
{
gridView.EnsureRowVisible(index);
return;
}
gridView.Rows[index].Selected = shallSelect;
// Set the first selected row as current.
// Assigning _gridView.CurrentCell results in a single selection of that row.
// So do not set row as current but make it visible at least.
DataGridViewSelectedRowCollection selectedRows = gridView.SelectedRows;
DataGridViewRow firstSelectedRow = selectedRows[0];
if (selectedRows.Count == 1)
{
gridView.CurrentCell = firstSelectedRow.Cells[1];
}
gridView.EnsureRowVisible(firstSelectedRow.Index);
}
catch (ArgumentException)
{
// Ignore if selection failed. Datagridview is not threadsafe
}
return;
}
}
public GitRevision? GetRevision(ObjectId objectId)
{
return _gridView.GetRevision(objectId);
}
private void HighlightBranch(ObjectId id)
{
_revisionGraphColumnProvider.RevisionGraphDrawStyle = RevisionGraphDrawStyle.HighlightSelected;
_revisionGraphColumnProvider.HighlightBranch(id);
_gridView.Update();
}
public string DescribeRevision(GitRevision revision, int maxLength = 0)
{
string description = revision.IsArtificial
? string.Empty
: revision.ObjectId.ToShortString() + ": ";
GitRefListsForRevision gitRefListsForRevision = new(revision);
IGitRef descriptiveRef = gitRefListsForRevision.AllBranches
.Concat(gitRefListsForRevision.AllTags)
.FirstOrDefault();
description += descriptiveRef is not null
? GetRefUnambiguousName(descriptiveRef)
: revision.Subject;
if (maxLength > 0)
{
description = description.ShortenTo(maxLength);
}
return description;
}
/// <summary>
/// Get the (last) selected revision in the grid.
/// </summary>
/// <returns>The selected revisions or <see langword="null"/> if none selected.</returns>
public GitRevision? GetSelectedRevisionOrDefault()
{
int rowCount = _gridView.RowCount;
foreach (DataGridViewRow row in _gridView.SelectedRows)
{
if (row.Index < rowCount
&& GetRevision(row.Index) is GitRevision revision)
{
return revision;
}
}
return null;
}
/// <summary>
/// Get the selected revisions in the grid.
/// Note that the parents may be rewritten if a filter is applied.
/// </summary>
/// <param name="direction">Sort direction if set.</param>
/// <returns>The selected revisions.</returns>
public IReadOnlyList<GitRevision> GetSelectedRevisions(SortDirection? direction = null)
{
IEnumerable<DataGridViewRow> rows = _gridView
.SelectedRows
.Cast<DataGridViewRow>()
.Where(row => _gridView.RowCount > row.Index);
if (direction.HasValue)
{
int d = direction.Value == SortDirection.Ascending ? 1 : -1;
rows = rows.OrderBy(row => row.Index, (r1, r2) => d * (r1 - r2));
}
return rows
.Select(row => GetRevision(row.Index))
.WhereNotNull()
.ToList();
}
private (ObjectId? firstId, GitRevision? selectedRev) GetFirstAndSelected()
{
IReadOnlyList<GitRevision> revisions = GetSelectedRevisions();
return revisions.Count switch
{
0 => (null, null),
1 => (firstId: revisions[0].FirstParentId, selectedRev: revisions[0]),
_ => (firstId: revisions[^1].ObjectId, selectedRev: revisions[0])
};
}
public IReadOnlyList<ObjectId> GetRevisionChildren(ObjectId objectId)
{
return _gridView.GetRevisionChildren(objectId);
}
private bool IsValidRevisionIndex(int index)
{
return index >= 0 && index < _gridView.RowCount;
}
private GitRevision? GetRevision(int row)
{
return _gridView.GetRevision(row);
}
/// <summary>
/// Get the actual GitRevision from grid or use GitModule if parents may be rewritten or the commit is not in the grid.
/// </summary>
/// <returns>The GitRevision or null if not found</returns>
public GitRevision? GetActualRevision(ObjectId objectId)
{
GitRevision revision = GetRevision(objectId);
if (revision is not null)
{
return GetActualRevision(revision);
}
// Revision is not in grid, try get from Git
return Module.GetRevision(objectId, shortFormat: true, loadRefs: true);
}
/// <summary>
/// Get the GitRevision with the actual parents as they may be rewritten in filtered grids.
/// </summary>
/// <param name="revision">The revision, likely from the grid.</param>
/// <returns>The input GitRevision if no changes and a clone with actual parents if parents are rewritten.</returns>
public GitRevision GetActualRevision(GitRevision revision)
{
// Index commits must have HEAD as parent already
if (ParentsAreRewritten && !revision.IsArtificial)
{
// Grid is filtered and revision may have incorrect parents
revision = revision.Clone();
revision.ParentIds = Module.GetParents(revision.ObjectId).ToList();
}
return revision;
}
public override bool ProcessHotkey(Keys keyData)
{
switch (keyData)
{
case Keys.Control | Keys.A:
if (FindForm() is GitExtensionsFormBase form)
{
form.ProcessHotkey(keyData);
}
return true; // never select all revisions
case Keys.Escape:
if (_toolTipProvider.Hide())
{
return true;
}
break;
}
return base.ProcessHotkey(keyData);
}
public void ReloadHotkeys()
{
LoadHotkeys(HotkeySettingsName);
MenuCommands.CreateOrUpdateMenuCommands();
}
public void ReloadTranslation()
{
Translator.Translate(this, AppSettings.CurrentTranslation);
}
/// <summary>
/// Show spinner (in the synchronous part of loading revisions
/// and creating the control), or the "Loading..." text when first revision is
/// handled and the grid is being updated.
/// Note that these controls are removed by SetPage() when the grid is loaded.
/// </summary>
/// <param name="showSpinner">Show the spinner or the text controls.</param>
private void ShowLoading(bool showSpinner = true)
{
_loadingControlSpinner.Visible = showSpinner;
_loadingControlSpinner.Left = (ClientSize.Width - _loadingControlSpinner.Width) / 2;
_loadingControlSpinner.Top = (ClientSize.Height - _loadingControlSpinner.Height) / 2;
_loadingControlText.Visible = !showSpinner;
_loadingControlText.Left = ClientSize.Width - _loadingControlSpinner.Width - SystemInformation.VerticalScrollBarWidth;
_loadingControlSpinner.BringToFront();
_loadingControlText.BringToFront();
}
/// <summary>
/// Indicates whether the revision grid can be refreshed,
/// i.e. it is not in a middle of reconfiguration process guarded by <see cref="SuspendRefreshRevisions"/>
/// and <see cref="ResumeRefreshRevisions"/>.
/// </summary>
private bool CanRefresh => _suspendRefreshCounter == 0;
#region PerformRefreshRevisions
/// <summary>
/// Queries git for the new set of revisions and refreshes the grid.
/// </summary>
/// <exception cref="Exception"></exception>
/// <param name="forceRefreshRefs">Refresh may be required as references may be changed.</param>
public void PerformRefreshRevisions(Func<RefsFilter, IReadOnlyList<IGitRef>> getRefs = null, bool forceRefreshRefs = false)
{
ThreadHelper.AssertOnUIThread();
if (!CanRefresh)
{
Trace.WriteLine("Ignoring refresh as RefreshRevisions() is suspended.");
return;
}
if (_isRefreshingRevisions)
{
Trace.WriteLine("Forcing refresh, cancel already running RefreshRevisions().");
if (!_gridView.IsDataLoadComplete)
{
_gridView.MarkAsDataLoadingComplete();
}
}
IGitModule capturedModule = Module;
// Reset the "cache" for current branch
CurrentBranch = new(() => Module.IsValidGitWorkingDir()
? Module.GetSelectedBranch(emptyIfDetached: true)
: "");
// Revision info is read in three parallel steps:
// 1. Read current commit, refs, prepare grid etc.
// 2. Read stashes (if enabled).
// 3. Read all revisions with git-log.
// Git will provide log information when available (so slower to first revision if sorting).
// These operations can take a long time and is done async in parallel.
// Step 3. requires that the information in 1 and 2 is available when adding revisions,
// and is therefore protected with a semaphore.
SemaphoreSlim semaphoreUpdateGrid = new(initialCount: 0, maxCount: 2);
CancellationToken cancellationToken = _refreshRevisionsSequence.Next();
_isRefreshingRevisions = true;
ILookup<ObjectId, IGitRef> refsByObjectId = null;
bool firstRevisionReceived = false;
bool headIsHandled = false;
Dictionary<ObjectId, GitRevision> stashesById = null;
Dictionary<ObjectId, GitRevision> untrackedByStashId = null;
ILookup<ObjectId, GitRevision> stashesByParentId = null;
// getRefs (refreshing from Browse) is Lazy already, but not from RevGrid (updating filters etc)
Lazy<IReadOnlyList<IGitRef>> getUnfilteredRefs = new(() => (getRefs ?? capturedModule.GetRefs)(RefsFilter.NoFilter));
_ambiguousRefs = new(() => GitRef.GetAmbiguousRefNames(getUnfilteredRefs.Value));
// Get the "main" stash commit, including the reflog selector
Lazy<IReadOnlyCollection<GitRevision>> getStashRevs = new(() =>
!AppSettings.ShowStashes
? Array.Empty<GitRevision>()
: new RevisionReader(capturedModule).GetStashes(cancellationToken));
try
{
_revisionGraphColumnProvider.RevisionGraphDrawStyle
= AppSettings.RevisionGraphDrawNonRelativesGray ? RevisionGraphDrawStyle.DrawNonRelativesGray : RevisionGraphDrawStyle.Normal;
// Apply checkboxes changes also to FormBrowse main menu
MenuCommands.TriggerMenuChanged();
FilterChanged?.Invoke(this, new FilterChangedEventArgs(_filterInfo));
_buildServerWatcher.CancelBuildStatusFetchOperation();
base.Refresh();
_superprojectCurrentCheckout = null;
Subject<GitRevision> observeRevisions = new();
_revisionSubscription?.Dispose();
_revisionSubscription = observeRevisions
.ObserveOn(ThreadPoolScheduler.Instance)
.Subscribe(OnRevisionRead, OnRevisionReaderError, OnRevisionReadCompleted);
IReadOnlyList<ObjectId>? currentlySelectedObjectIds = _gridView.SelectedObjectIds;
_gridView.SuspendLayout();
_gridView.SelectionChanged -= OnGridViewSelectionChanged;
_gridView.ClearSelection();
_gridView.Clear();
_gridView.Enabled = true;
_gridView.Focus();
_gridView.SelectionChanged += OnGridViewSelectionChanged;
_gridView.MarkAsDataLoading();
// Add the spinner controls, removed by SetPage()
Controls.Add(_loadingControlSpinner);
Controls.Add(_loadingControlText);
ShowLoading();
_gridView.ResumeLayout();
IndexWatcher.Reset();
// Selected is null: Update to trigger reset the tabs etc.
_selectionTimer.Stop();
_selectionTimer.Start();
cancellationToken.ThrowIfCancellationRequested();
Lazy<IGitRef?> headRef = new(() =>
!string.IsNullOrEmpty(CurrentBranch.Value)
? getUnfilteredRefs.Value.FirstOrDefault(i => i.CompleteName == $"{GitRefName.RefsHeadsPrefix}{CurrentBranch.Value}")
: null);
Lazy<ObjectId?> currentCheckout = new(() =>
headRef.Value?.ObjectId ?? capturedModule.GetCurrentCheckout());
ObjectId? previousCheckout = CurrentCheckout;
// Evaluate GitRefs and current commit
ThreadHelper.FileAndForget(async () =>
{
cancellationToken.ThrowIfCancellationRequested();
// If the current checkout (HEAD) is changed, don't get the currently selected rows,
// select the new current checkout instead.
CurrentCheckout = currentCheckout.Value;
if (CurrentCheckout != previousCheckout)
{
if (CurrentCheckout is null)
{
currentlySelectedObjectIds = null;
}
else
{
currentlySelectedObjectIds = new List<ObjectId> { CurrentCheckout };
}
}
// Exclude the 'stash' ref, it is specially handled when stashes are shown
refsByObjectId = (AppSettings.ShowStashes
? getUnfilteredRefs.Value.Where(r => r.CompleteName != GitRefName.RefsStashPrefix)
: getUnfilteredRefs.Value)