-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathLNXcodeSupport.mm
451 lines (360 loc) · 17.9 KB
/
LNXcodeSupport.mm
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
//
// LNXcodeSupport.m
// LNProvider
//
// Created by John Holdsworth on 31/03/2017.
// Copyright © 2017 John Holdsworth. All rights reserved.
//
// Repo: https://github.com/johnno1962/GitDiff
//
// $Id: //depot/GitDiff/LNXcodeSupport/LNXcodeSupport.mm#11 $
//
#import "LNXcodeSupport.h"
#import "LNXcodeSupport-Swift.h"
#import "LNExtensionClientDO.h"
#import "LNHighlightGutter.h"
#import "XcodePrivate.h"
#import <objc/runtime.h>
#define REFRESH_INTERVAL 60.
#define REVERT_DELAY 1.5
static LNXcodeSupport *lineNumberPlugin;
static NSString *lastSaved;
@interface LNXcodeSupport () <LNRegistration, LNConnectionDelegate>
@property NSMutableArray<LNExtensionClient *> *extensions;
@property NSMutableDictionary<NSString *, void (^)()> *onupdate;
@property Class sourceDocClass, scrollerClass;
@property NSTextView *popover;
@property NSButton *undoButton;
@end
@implementation LNXcodeSupport
+ (void)pluginDidLoad:(NSBundle *)pluginBundle {
NSString *currentApplicationName = [NSBundle mainBundle].infoDictionary[@"CFBundleName"];
static dispatch_once_t onceToken;
if ([currentApplicationName isEqualToString:@"Xcode"]) {
dispatch_once(&onceToken, ^{
LNXcodeSupport *plugin = lineNumberPlugin = [[self alloc] init];
plugin.extensions = [NSMutableArray new];
plugin.onupdate = [NSMutableDictionary new];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
[self swizzleClass:[NSDocument class]
exchange:@selector(_finishSavingToURL:ofType:forSaveOperation:changeCount:)
with:@selector(ln_finishSavingToURL:ofType:forSaveOperation:changeCount:)];
[self swizzleClass:objc_getClass("IDEEditorDocument")
exchange:@selector(closeToRevert)
with:@selector(ln_closeToRevert)];
[self swizzleClass:objc_getClass("DVTMarkedScroller")
exchange:@selector(drawKnobSlotInRect:highlight:)
with:@selector(ln_drawKnobSlotInRect:highlight:)];
#pragma clang diagnostic pop
dispatch_async(dispatch_get_main_queue(), ^{
plugin.sourceDocClass = objc_getClass("IDEEditorDocument"); //IDESourceCodeDocument");
plugin.scrollerClass = objc_getClass("SourceEditorScrollView");
plugin.undoButton = [[NSButton alloc] initWithFrame:NSZeroRect];
plugin.undoButton.bordered = FALSE;
NSBundle *pluginBundle = [NSBundle bundleForClass:self];
NSString *path = [pluginBundle pathForResource:@"undo" ofType:@"png"];
plugin.undoButton.image = [[NSImage alloc] initWithContentsOfFile:path];
plugin.undoButton.imageScaling = NSImageScaleProportionallyDown;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
NSConnection *registrationDO = [[NSConnection alloc] init];
[registrationDO setRootObject:plugin];
[registrationDO registerName:XCODE_LINE_NUMBER_REGISTRATION];
NSURL *appURL = [pluginBundle URLForResource:@"LNProvider" withExtension:@"app"];
[[NSWorkspace sharedWorkspace] openURL:appURL];
[[NSRunLoop currentRunLoop] run];
});
});
});
}
}
+ (void)swizzleClass:(Class)aClass exchange:(SEL)origMethod with:(SEL)altMethod {
method_exchangeImplementations(class_getInstanceMethod(aClass, origMethod),
class_getInstanceMethod(aClass, altMethod));
}
- (oneway void)registerLineNumberService:(NSString *)serviceName {
[self deregisterService:serviceName];
NSLog(@"Registering %@ ...", serviceName);
[self.extensions addObject:[[LNExtensionClientDO alloc] initServiceName:serviceName delegate:self]];
}
- (oneway void)ping {
}
- (oneway void)deregisterService:(NSString *_Nonnull)serviceName {
for (LNExtensionClient *extension in self.extensions) {
if ([extension.serviceName isEqualToString:serviceName]) {
[self.extensions removeObject:extension];
break;
}
}
}
- (void)updateHighlights:(NSData *)json error:(NSError *)error forFile:(NSString *)filepath {
dispatch_async(dispatch_get_main_queue(), ^{
if (error)
[[NSAlert alertWithError:error] runModal];
else if (auto update = self.onupdate[filepath])
update();
});
}
- (void)updateGutter:(NSString *)filepath {
self.onupdate[filepath]();
}
- (void)updateLinenumberHighlightsForFile:(NSString *)filepath {
for (LNExtensionClient *extension in self.extensions)
[extension requestHighlightsForFile:filepath];
}
- (void)updateConfig:(LNConfig)config forService:(NSString *_Nonnull)serviceName {
NSLog(@"%@ updateConfig: %@", serviceName, config);
}
- (void)initialOrOccaisionalLineNumberUpdate:(NSString *)filepath {
// update if not already in memory or 60 seconds has passed
NSTimeInterval stale = [NSDate timeIntervalSinceReferenceDate] - REFRESH_INTERVAL;
for (LNExtensionClient *extension in self.extensions) {
if (filepath && extension[filepath].updated < stale) {
if (!extension[filepath])
extension.highightsByFile[filepath] = [[LNFileHighlights alloc] initWithData:nil
service:extension.serviceName];
[extension requestHighlightsForFile:filepath];
}
}
}
@end
@implementation NSDocument (IDESourceCodeDocument)
- (void)forceLineNumberUpdate {
if ([self isKindOfClass:lineNumberPlugin.sourceDocClass])
[lineNumberPlugin updateLinenumberHighlightsForFile:lastSaved = [[self fileURL] path]];
}
// source file is being saved
- (void)ln_finishSavingToURL:(id)a0 ofType:(id)a1 forSaveOperation:(NSUInteger)a2 changeCount:(id)a3 {
[self ln_finishSavingToURL:a0 ofType:a1 forSaveOperation:a2 changeCount:a3];
[self forceLineNumberUpdate];
}
// revert on change on disk
- (void)ln_closeToRevert {
[self ln_closeToRevert];
[self forceLineNumberUpdate];
}
@end
@implementation NSString (LineNumber)
// https://stackoverflow.com/questions/1085524/how-to-count-the-number-of-lines-in-an-objective-c-string-nsstring
- (NSUInteger)numberOfLines {
NSUInteger numberOfLines, index, stringLength = [self length];
for (index = 0, numberOfLines = 0; index < stringLength; numberOfLines++)
index = NSMaxRange([self lineRangeForRange:NSMakeRange(index, 0)]);
return numberOfLines;
}
- (NSUInteger)indexForLine:(NSUInteger)lineNumber {
NSUInteger numberOfLines, index, stringLength = [self length];
for (index = 0, numberOfLines = 0; index < stringLength && numberOfLines < lineNumber; numberOfLines++)
index = NSMaxRange([self lineRangeForRange:NSMakeRange(index, 0)]);
return index;
}
@end
@implementation NSScroller (LineNumber)
- (NSString *)editedDocPath {
return lastSaved ?: @"";
id name = [KeyPath objectFor:@"hostingEditor.dataSource.name" from:self.superview.superview];
return [name isKindOfClass:[NSString class]] ? name : @"";
}
// scroll bar overview
- (void)ln_drawKnobSlotInRect:(CGRect)rect highlight:(BOOL)highlight {
[self ln_drawKnobSlotInRect:rect highlight:highlight];
if (![self.superview isKindOfClass:lineNumberPlugin.scrollerClass])
return;
NSString *filepath = [self editedDocPath];
[lineNumberPlugin initialOrOccaisionalLineNumberUpdate:filepath];
NSLog(@"ln_drawKnobSlotInRect: %@ %@", self, filepath);
__weak NSScroller *weakSelf = self;
lineNumberPlugin.onupdate[filepath] = ^{
[weakSelf updateLineNumberFlecksFor:filepath];
[weakSelf updateScrollbarMarkersFor:filepath in:rect];
};
[NSObject cancelPreviousPerformRequestsWithTarget:lineNumberPlugin];
[lineNumberPlugin performSelector:@selector(updateGutter:) withObject:filepath afterDelay:.1];
}
static CGFloat gutterWidth;
- (void)updateLineNumberFlecksFor:(NSString *)filepath {
NSView *floatingContainer = self.superview.subviews[1];
NSArray *floating = floatingContainer.subviews;
LNHighlightGutter *highlightGutter = floating.lastObject;
SourceEditorGutterMarginContentView *lineNumberGutter;
if (![highlightGutter isKindOfClass:[LNHighlightGutter class]]) {
lineNumberGutter = floating.lastObject;
highlightGutter = [[LNHighlightGutter alloc] initWithFrame:NSZeroRect];
[floatingContainer addSubview:highlightGutter];
} else
lineNumberGutter = floating.firstObject;
NSLog(@"updateLineNumberFlecksFor: %@ %@ %@ %@", filepath, highlightGutter,
NSStringFromRect(highlightGutter.frame), lineNumberGutter);
static Class gutterContentClasss;
if (!gutterContentClasss)
gutterContentClasss = objc_getClass("SourceEditor.SourceEditorGutterMarginContentView");
if (![lineNumberGutter isKindOfClass:gutterContentClasss] &&
!(floating.count > 1 &&
[lineNumberGutter = floating[1] isKindOfClass:gutterContentClasss]))
return;
NSRect rect = lineNumberGutter.frame;
gutterWidth = rect.size.width;
rect.origin.y = 0.;
rect.origin.x += gutterWidth - 3.;
rect.size.width = 8.;
rect.size.height += 5000.;
if (!NSEqualRects(highlightGutter.frame, rect))
highlightGutter.frame = rect;
NSDictionary *lineNumberLayers = [KeyPath objectFor:@"lineNumberLayers" from:lineNumberGutter];
NSMutableArray<LNHighlightFleck *> *next = [NSMutableArray new];
SourceEditorContentView *sourceTextView = self.superview.subviews[0].subviews[0];
CGFloat lineHeight = [sourceTextView defaultLineHeight];
for (NSNumber *line in lineNumberLayers) {
SourceEditorFontSmoothingTextLayer *layer = lineNumberLayers[line];
NSRect rect = layer.frame;
rect.size.width = LNFLECK_WIDTH;
rect.size.height = lineHeight;
rect.origin.x = NSWidth(highlightGutter.frame) - NSWidth(rect);
rect.origin.y = NSHeight(highlightGutter.frame) -
lineNumberGutter.frame.origin.y - rect.origin.y - lineHeight + 4.;
for (LNExtensionClient *extension in lineNumberPlugin.extensions.reverseObjectEnumerator) {
if (LNFileHighlights *diffs = extension[filepath]) {
if (LNHighlightElement *element = diffs[line.integerValue + 1]) {
LNHighlightFleck *fleck = [LNHighlightFleck fleck];
fleck.frame = rect;
fleck.element = element;
fleck.extension = extension;
fleck.yoffset = [lineNumberLayers[@(element.start - 1)] frame].origin.y;
[next addObject:fleck];
rect.origin.x -= LNFLECK_VISIBLE;
}
}
}
}
#define NSOrderedCompare(a, b) a<b ? NSOrderedAscending : a>b ? NSOrderedDescending : NSOrderedSame
[next sortUsingComparator:^NSComparisonResult(LNHighlightFleck *obj1, LNHighlightFleck *obj2) {
return NSOrderedCompare(obj1.yoffset, obj2.yoffset);
}];
if (![[highlightGutter subviews] isEqualToArray:next]) {
[[[highlightGutter subviews] copy] makeObjectsPerformSelector:@selector(removeFromSuperview)];
for (LNHighlightFleck *fleck in next)
[highlightGutter addSubview:fleck];
} else
[LNHighlightFleck recycle:next];
}
- (void)updateScrollbarMarkersFor:(NSString *)filepath in:(NSRect)rect {
static NSMutableDictionary<NSString *, NSNumber *> *lineCountCache;
if (!lineCountCache)
lineCountCache = [NSMutableDictionary new];
SourceEditorContentView *sourceTextView = self.superview.subviews[0].subviews[0];
NSInteger lines = lineCountCache[filepath].intValue;
if (!lines)
lineCountCache[filepath] = @(lines = [sourceTextView.accessibilityValue numberOfLines] ?: 1);
CGFloat lineHeight = [sourceTextView defaultLineHeight];
CGFloat scale = lines * lineHeight < NSHeight(self.frame) ? lineHeight : NSHeight(self.frame) / lines;
NSMutableArray *marks = [NSMutableArray new], *markRects = [NSMutableArray new];
static Class markerListClass9_2;
if (!markerListClass9_2 && (markerListClass9_2 = objc_getClass("_DVTMarkerList"))) {
markerListClass9_2 = objc_allocateClassPair(markerListClass9_2, "ln_DVTMarkerList", 0);
class_addMethod(markerListClass9_2, @selector(_recomputeMarkRects),
imp_implementationWithBlock(^{}), "v16@0:8");
objc_registerClassPair(markerListClass9_2);
}
if (!markerListClass9_2)
[self clearDiffMarks];
for (LNExtensionClient *extension in lineNumberPlugin.extensions) {
if (LNFileHighlights *diffs = extension[filepath]) {
[diffs foreachHighlightRange:^(NSRange range, LNHighlightElement *element) {
if (markerListClass9_2) {
NSRect rect = NSMakeRect(4., (range.location - 1) * scale, 2., MAX(range.length * scale, 2.));
[marks addObject:@((range.location - 1.) / lines)];
[markRects addObject:[NSValue valueWithRect:rect]];
} else
[self addMark:(range.location - 1.) / lines onLine:range.location ofType:2];
}];
}
}
if (markerListClass9_2) {
_DVTMarkerList *markers = [[markerListClass9_2 alloc] initWithSlotRect:rect];
[markers setValue:marks forKey:@"_marks"];
[markers setValue:markRects forKey:@"_markRects"];
[self setValue:markers forKey:@"_diffMarks"];
}
}
@end
@implementation LNHighlightFleck (LNXcodeSupport)
- (SourceEditorContentView *)editorContentView {
return self.superview.superview.superview.subviews[0].subviews[0];
}
- (void)mouseEntered:(NSEvent *)theEvent {
if (!self.element.text)
return;
NSLog(@"mouseEntered: %@", self);
// NSUInteger start = self.element.start;
NSMutableAttributedString *attString = [[self.element attributedText] mutableCopy];
// https://panupan.com/2012/06/04/trim-leading-and-trailing-whitespaces-from-nsmutableattributedstring/
// Trim trailing whitespace and newlines.
NSCharacterSet *charSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSRange range = [attString.string rangeOfCharacterFromSet:charSet
options:NSBackwardsSearch];
while (range.length != 0 && NSMaxRange(range) == attString.length) {
[attString replaceCharactersInRange:range
withString:@""];
range = [attString.string rangeOfCharacterFromSet:charSet
options:NSBackwardsSearch];
}
SourceEditorContentView *sourceTextView = [self editorContentView];
CGFloat lineHeight = [sourceTextView defaultLineHeight];
NSMutableParagraphStyle *myStyle = [NSMutableParagraphStyle new];
[myStyle setMinimumLineHeight:lineHeight];
[attString setAttributes:@{NSParagraphStyleAttributeName : myStyle}
range:NSMakeRange(0, attString.length)];
[lineNumberPlugin.popover removeFromSuperview];
NSTextView *popover =
lineNumberPlugin.popover = [[NSTextView alloc] initWithFrame:NSZeroRect];
[[popover textStorage] setAttributedString:attString];
popover.font = [KeyPath objectFor:@"layoutManager.fontTheme.plainTextFont" from:sourceTextView];
CGFloat width = NSWidth(sourceTextView.frame);
CGFloat height = lineHeight * [popover.string numberOfLines];
popover.frame = NSMakeRect(gutterWidth + 5., self.yoffset - 4., width, height);
NSLog(@"%@ %f %f - %@ %@", NSStringFromRect(popover.frame), lineHeight, height, self.element.range, sourceTextView);
NSString *popoverColor = self.extension.config[LNPopoverColorKey] ?: @"1 0.914 0.662 1";
popover.backgroundColor = [NSColor colorWithString:popoverColor];
[sourceTextView addSubview:popover];
if (self.element.range)
[self performSelector:@selector(showUndoButton) withObject:nil afterDelay:REVERT_DELAY];
}
- (void)mouseExited:(NSEvent *)theEvent {
[lineNumberPlugin.popover removeFromSuperview];
[lineNumberPlugin.undoButton removeFromSuperview];
}
- (void)showUndoButton {
if (lineNumberPlugin.popover.superview) {
NSButton *undoButton = lineNumberPlugin.undoButton;
undoButton.action = @selector(performUndo:);
undoButton.target = self;
CGFloat width = NSWidth(self.superview.frame);
undoButton.frame = NSMakeRect(0, self.frame.origin.y + width, width, width);
[self.superview addSubview:undoButton];
}
}
- (void)performUndo:(NSButton *)sender {
SourceEditorContentView *sourceTextView = [self editorContentView];
NSRange lineRange, charRange;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
LNConfig config = self.extension.config;
if (sscanf(self.element.range.UTF8String ?: "", "%ld %ld", &lineRange.location, &lineRange.length) != 2 ||
[[NSAlert alertWithMessageText:config[LNApplyTitleKey] ?: @"Line Number Plugin:"
defaultButton:config[LNApplyConfirmKey] ?: @"Modify"
alternateButton:@"Cancel"
otherButton:nil
informativeTextWithFormat:config[LNApplyPromptKey] ?: @"Apply suggested changes at line %d-%d?",
(int)lineRange.location, (int)(lineRange.location + MAX(lineRange.length, 1) - 1)]
runModal] == NSAlertAlternateReturn)
return;
#pragma clang diagnostic pop
lineRange.location--;
NSString *buffer = sourceTextView.accessibilityValue;
charRange.location = [buffer indexForLine:lineRange.location];
charRange.length = [buffer indexForLine:lineRange.location + lineRange.length] - charRange.location;
NSLog(@"performUndo: %@ %@", sourceTextView, [buffer substringWithRange:charRange]);
[sourceTextView setAccessibilitySelectedTextRange:charRange];
[sourceTextView setAccessibilitySelectedText:self.element.attributedText.string];
}
@end