Skip to content

Commit fd0a610

Browse files
committed
Coalesce stage diff rendering after index updates
gitx/gitx#530 gitx/gitx#428
1 parent 76d8454 commit fd0a610

4 files changed

Lines changed: 170 additions & 12 deletions

File tree

‎Classes/Controllers/PBWebChangesController.m‎

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,16 @@
88
static void *const UnstagedFileSelectedContext = @"UnstagedFileSelectedContext";
99
static void *const CachedFileSelectedContext = @"CachedFileSelectedContext";
1010

11+
@interface PBRefreshCoalescer : NSObject
12+
- (instancetype)initWithDeliveryHandler:(void (^)(void))deliveryHandler;
13+
- (void)requestRefresh;
14+
- (void)cancel;
15+
@end
16+
1117
@interface PBWebChangesController () <PBNativeContentViewDelegate>
1218
@property (nonatomic) NSUInteger contextLines;
1319
@property (nonatomic) NSTextField *contextValueLabel;
20+
@property (nonatomic) PBRefreshCoalescer *refreshCoalescer;
1421
@end
1522

1623
@implementation PBWebChangesController
@@ -19,6 +26,10 @@ - (void)awakeFromNib
1926
{
2027
[super awakeFromNib];
2128
self.nativeView.delegate = self;
29+
__weak typeof(self) weakSelf = self;
30+
self.refreshCoalescer = [[PBRefreshCoalescer alloc] initWithDeliveryHandler:^{
31+
[weakSelf refresh];
32+
}];
2233
NSNumber *savedContext = [[NSUserDefaults standardUserDefaults] objectForKey:@"PBStageDiffContextLines"];
2334
self.contextLines = savedContext ? savedContext.unsignedIntegerValue : 3;
2435
NSView *accessory = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 100, 34)];
@@ -59,6 +70,8 @@ - (void)contextLinesChanged:(NSStepper *)sender
5970

6071
- (void)closeView
6172
{
73+
[self.refreshCoalescer cancel];
74+
self.refreshCoalescer = nil;
6275
[unstagedFilesController removeObserver:self forKeyPath:@"selection"];
6376
[stagedFilesController removeObserver:self forKeyPath:@"selection"];
6477
[super closeView];
@@ -72,7 +85,7 @@ - (void)didLoad
7285
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
7386
{
7487
if (context == UnstagedFileSelectedContext || context == CachedFileSelectedContext) {
75-
[self refresh];
88+
[self.refreshCoalescer requestRefresh];
7689
return;
7790
}
7891
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
@@ -95,8 +108,11 @@ - (void)refresh
95108
NSMutableArray<NSDictionary *> *sections = [NSMutableArray array];
96109
for (PBChangedFile *file in stagedFilesController.selectedObjects) [sections addObject:[self sectionForFile:file staged:YES]];
97110
for (PBChangedFile *file in unstagedFilesController.selectedObjects) [sections addObject:[self sectionForFile:file staged:NO]];
98-
if (sections.count == 0) [self.nativeView showMessage:@"No file selected"];
99-
else [self.nativeView showDiffSections:sections];
111+
NSLog(@"[GitX] Rendering %lu selected stage-diff sections", (unsigned long)sections.count);
112+
if (sections.count == 0)
113+
[self.nativeView showMessage:@"No file selected"];
114+
else
115+
[self.nativeView showDiffSections:sections];
100116
}
101117

102118
- (void)showMultiple:(NSArray *)files
@@ -112,23 +128,23 @@ - (void)setStateMessage:(NSString *)state
112128
- (void)nativeContentView:(PBNativeContentView *)view performDiffAction:(NSString *)action patch:(NSString *)patch
113129
{
114130
if ([action isEqualToString:@"stage"]) {
131+
NSLog(@"[GitX] Applying a partial stage patch");
115132
[controller.index applyPatch:patch stage:YES reverse:NO];
116-
[self refresh];
117133
} else if ([action isEqualToString:@"unstage"]) {
134+
NSLog(@"[GitX] Applying a partial unstage patch");
118135
[controller.index applyPatch:patch stage:YES reverse:YES];
119-
[self refresh];
120136
} else if ([action isEqualToString:@"discard"]) {
121137
NSAlert *alert = [[NSAlert alloc] init];
122138
alert.messageText = NSLocalizedString(@"Discard hunk", @"");
123139
alert.informativeText = NSLocalizedString(@"Are you sure you wish to discard this hunk? This operation cannot be undone.", @"");
124140
[alert addButtonWithTitle:NSLocalizedString(@"Discard", @"")];
125141
[alert addButtonWithTitle:NSLocalizedString(@"Cancel", @"")];
126-
[alert beginSheetModalForWindow:self.view.window completionHandler:^(NSModalResponse response) {
127-
if (response == NSAlertFirstButtonReturn) {
128-
[self->controller.index applyPatch:patch stage:NO reverse:YES];
129-
[self refresh];
130-
}
131-
}];
142+
[alert beginSheetModalForWindow:self.view.window
143+
completionHandler:^(NSModalResponse response) {
144+
if (response == NSAlertFirstButtonReturn) {
145+
[self->controller.index applyPatch:patch stage:NO reverse:YES];
146+
}
147+
}];
132148
}
133149
}
134150

‎Classes/git/PBGitIndex.m‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,10 @@ - (void)refresh
201201
[self addFilesFromDictionary:unstagedDictionary staged:NO tracked:YES];
202202
if (untrackedDictionary)
203203
[self addFilesFromDictionary:untrackedDictionary staged:NO tracked:NO];
204+
NSLog(@"[GitX] Merged index refresh snapshots: %lu staged, %lu unstaged, %lu untracked",
205+
(unsigned long)stagedDictionary.count,
206+
(unsigned long)unstagedDictionary.count,
207+
(unsigned long)untrackedDictionary.count);
204208

205209
// We need to find all files that don't have either
206210
// staged or unstaged files, and delete them
@@ -555,6 +559,7 @@ - (BOOL)performStageOrUnstage:(BOOL)stage withFiles:(NSArray *)files
555559
NSError *error = nil;
556560
BOOL success = NO;
557561
if (stage) {
562+
NSLog(@"[GitX] Staging paths %lu-%lu of %lu", (unsigned long)loopFrom, (unsigned long)loopTo, (unsigned long)filesCount);
558563
// Input is a NUL-delimited list of paths, equivalent to git add.
559564
NSMutableString *input = [NSMutableString string];
560565
for (NSUInteger i = loopFrom; i < loopTo; i++) {
@@ -565,9 +570,11 @@ - (BOOL)performStageOrUnstage:(BOOL)stage withFiles:(NSArray *)files
565570
input:input
566571
error:&error];
567572
} else {
573+
NSString *parentTree = [self parentTree];
574+
NSLog(@"[GitX] Unstaging paths %lu-%lu of %lu from %@", (unsigned long)loopFrom, (unsigned long)loopTo, (unsigned long)filesCount, parentTree);
568575
// Reset paths from the comparison tree instead of trusting cached
569576
// PBChangedFile blob metadata, which can lag behind partial staging.
570-
NSMutableArray<NSString *> *arguments = [NSMutableArray arrayWithObjects:@"reset", @"--quiet", [self parentTree], @"--", nil];
577+
NSMutableArray<NSString *> *arguments = [NSMutableArray arrayWithObjects:@"reset", @"--quiet", parentTree, @"--", nil];
571578
for (NSUInteger i = loopFrom; i < loopTo; i++) {
572579
PBChangedFile *file = [files objectAtIndex:i];
573580
[arguments addObject:file.path];

‎Classes/git/RepositoryRefreshCoordinator.swift‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,67 @@ private final class DispatchRepositoryRefreshScheduler: RepositoryRefreshSchedul
4242
}
4343
}
4444

45+
/// Coalesces duplicate controller invalidations into one refresh on the next main-loop turn.
46+
@objc(PBRefreshCoalescer)
47+
final class RefreshCoalescer: NSObject { // swiftlint:disable:this unused_declaration
48+
private let deliveryHandler: () -> Void
49+
private let lock = NSLock()
50+
private var generation: UInt64 = 0
51+
private var scheduledGeneration: UInt64?
52+
53+
@objc(initWithDeliveryHandler:)
54+
init(deliveryHandler: @escaping () -> Void) {
55+
self.deliveryHandler = deliveryHandler
56+
}
57+
58+
deinit {
59+
cancel()
60+
}
61+
62+
@objc
63+
func requestRefresh() {
64+
lock.lock()
65+
guard scheduledGeneration == nil else {
66+
lock.unlock()
67+
NSLog("[GitX] Coalesced a duplicate stage-diff refresh request")
68+
return
69+
}
70+
71+
generation &+= 1
72+
let requestedGeneration = generation
73+
scheduledGeneration = requestedGeneration
74+
lock.unlock()
75+
76+
NSLog("[GitX] Scheduled a stage-diff refresh for the next main-loop turn")
77+
78+
DispatchQueue.main.async { [weak self] in
79+
self?.deliver(generation: requestedGeneration)
80+
}
81+
}
82+
83+
@objc
84+
func cancel() {
85+
lock.lock()
86+
generation &+= 1
87+
scheduledGeneration = nil
88+
lock.unlock()
89+
NSLog("[GitX] Cancelled the pending stage-diff refresh")
90+
}
91+
92+
private func deliver(generation requestedGeneration: UInt64) {
93+
lock.lock()
94+
guard scheduledGeneration == requestedGeneration else {
95+
lock.unlock()
96+
return
97+
}
98+
scheduledGeneration = nil
99+
lock.unlock()
100+
101+
NSLog("[GitX] Delivering one coalesced stage-diff refresh")
102+
deliveryHandler()
103+
}
104+
}
105+
45106
/// Debounces repository events for the Objective-C repository watcher.
46107
@objc(PBRepositoryRefreshCoordinator)
47108
final class RepositoryRefreshCoordinator: NSObject { // swiftlint:disable:this unused_declaration

‎GitXTests/RepositoryRefreshCoordinatorTests.m‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,83 @@ - (BOOL)shouldRefreshForSnapshotComponents:(NSArray<NSData *> *)snapshotComponen
1919
- (void)reset;
2020
@end
2121

22+
@interface NSObject (PBRefreshCoalescerTesting)
23+
- (instancetype)initWithDeliveryHandler:(void (^)(void))deliveryHandler;
24+
- (void)requestRefresh;
25+
- (void)cancel;
26+
@end
27+
2228
@interface RepositoryRefreshCoordinatorTests : XCTestCase
2329
@end
2430

31+
@interface RefreshCoalescerTests : XCTestCase
32+
@end
33+
34+
@implementation RefreshCoalescerTests
35+
36+
- (void)testBurstOfRefreshRequestsDeliversOnce
37+
{
38+
Class coalescerClass = NSClassFromString(@"PBRefreshCoalescer");
39+
XCTAssertNotNil(coalescerClass);
40+
if (!coalescerClass) return;
41+
XCTestExpectation *delivered = [self expectationWithDescription:@"Refresh delivered"];
42+
__block NSUInteger deliveryCount = 0;
43+
id coalescer = [[coalescerClass alloc] initWithDeliveryHandler:^{
44+
deliveryCount++;
45+
[delivered fulfill];
46+
}];
47+
48+
[coalescer requestRefresh];
49+
[coalescer requestRefresh];
50+
[coalescer requestRefresh];
51+
52+
[self waitForExpectations:@[ delivered ] timeout:1.0];
53+
XCTAssertEqual(deliveryCount, (NSUInteger)1);
54+
}
55+
56+
- (void)testRequestDuringDeliveryProducesOneTrailingRefresh
57+
{
58+
Class coalescerClass = NSClassFromString(@"PBRefreshCoalescer");
59+
XCTAssertNotNil(coalescerClass);
60+
if (!coalescerClass) return;
61+
XCTestExpectation *delivered = [self expectationWithDescription:@"Initial and trailing refresh delivered"];
62+
delivered.expectedFulfillmentCount = 2;
63+
__block NSUInteger deliveryCount = 0;
64+
__block id coalescer = nil;
65+
coalescer = [[coalescerClass alloc] initWithDeliveryHandler:^{
66+
deliveryCount++;
67+
if (deliveryCount == 1) {
68+
[coalescer requestRefresh];
69+
[coalescer requestRefresh];
70+
}
71+
[delivered fulfill];
72+
}];
73+
74+
[coalescer requestRefresh];
75+
76+
[self waitForExpectations:@[ delivered ] timeout:1.0];
77+
XCTAssertEqual(deliveryCount, (NSUInteger)2);
78+
}
79+
80+
- (void)testCancellationDropsPendingRefresh
81+
{
82+
Class coalescerClass = NSClassFromString(@"PBRefreshCoalescer");
83+
XCTAssertNotNil(coalescerClass);
84+
if (!coalescerClass) return;
85+
XCTestExpectation *delivered = [self expectationWithDescription:@"Cancelled refresh is not delivered"];
86+
delivered.inverted = YES;
87+
id coalescer = [[coalescerClass alloc] initWithDeliveryHandler:^{
88+
[delivered fulfill];
89+
}];
90+
91+
[coalescer requestRefresh];
92+
[coalescer cancel];
93+
94+
[self waitForExpectations:@[ delivered ] timeout:0.1];
95+
}
96+
97+
@end
98+
2599
NS_ASSUME_NONNULL_END
26100

27101
@implementation RepositoryRefreshCoordinatorTests

0 commit comments

Comments
 (0)