forked from dgrijalva/gitx
-
Notifications
You must be signed in to change notification settings - Fork 76
/
GLFileView.m
767 lines (641 loc) · 27.4 KB
/
GLFileView.m
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
//
// GLFileView.m
// GitX
//
// Created by German Laullon on 14/09/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "GLFileView.h"
#import "PBGitGradientBarView.h"
#define GROUP_LABEL @"Label" // string
#define GROUP_SEPARATOR @"HasSeparator" // BOOL as NSNumber
#define GROUP_SELECTION_MODE @"SelectionMode" // MGScopeBarGroupSelectionMode (int) as NSNumber
#define GROUP_ITEMS @"Items" // array of dictionaries, each containing the following keys:
#define ITEM_IDENTIFIER @"Identifier" // string
#define ITEM_NAME @"Name" // string
@interface GLFileView ()
- (void)saveSplitViewPosition;
- (void)updateSearch;
- (void)updateSearchUI;
+ (NSString *)parseDiffBlock:(NSString *)txt;
+ (NSString *)parseDiffHeader:(NSString *)txt;
+ (NSString *)parseDiffChunk:(NSString *)txt;
+ (NSString *)parseBinaryDiff:(NSString *)txt;
@end
@implementation GLFileView
@synthesize historyController, typeBar, stepper, searchField, numberOfMatches, groups, logFormat;
- (void) awakeFromNib
{
NSString *formatFile = [[NSBundle mainBundle] pathForResource:@"format" ofType:@"html" inDirectory:@"html/views/log"];
if(formatFile!=nil)
logFormat=[NSString stringWithContentsOfURL:[NSURL fileURLWithPath:formatFile] encoding:NSUTF8StringEncoding error:nil];
startFile = @"fileview";
//repository = historyController.repository;
[super awakeFromNib];
[historyController.treeController addObserver:self forKeyPath:@"selection" options:0 context:@"treeController"];
self.groups = [NSMutableArray arrayWithCapacity:0];
NSArray *items = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
startFile, ITEM_IDENTIFIER,
@"Source", ITEM_NAME,
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"blame", ITEM_IDENTIFIER,
@"Blame", ITEM_NAME,
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"log", ITEM_IDENTIFIER,
@"History", ITEM_NAME,
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"diff", ITEM_IDENTIFIER,
@"Diff", ITEM_NAME,
nil],
nil];
[self.groups addObject:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:NO], GROUP_SEPARATOR,
[NSNumber numberWithInt:MGRadioSelectionMode], GROUP_SELECTION_MODE, // single selection group.
items, GROUP_ITEMS,
nil]];
NSArray *difft = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
@"l", ITEM_IDENTIFIER,
@"Local", ITEM_NAME,
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"h", ITEM_IDENTIFIER,
@"HEAD", ITEM_NAME,
nil],
nil];
[self.groups addObject:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:NO], GROUP_SEPARATOR,
[NSNumber numberWithInt:MGRadioSelectionMode], GROUP_SELECTION_MODE, // single selection group.
difft, GROUP_ITEMS,
@"Diff with:",GROUP_LABEL,
nil]];
[typeBar reloadData];
[fileListSplitView setHidden:YES];
[self performSelector:@selector(restoreSplitViewPositiion) withObject:nil afterDelay:0];
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
[self showFile];
}
- (void) showFile
{
NSError *theError = nil;
NSArray *files=[historyController.treeController selectedObjects];
if ([files count]>0) {
PBGitTree *file=[files objectAtIndex:0];
DLog(@"file=%@ == %@ => %d",file,lastFile,[file isEqualTo:lastFile]);
if(![file isEqualTo:lastFile]){
lastFile=file;
NSString *fileTxt = @"";
if(startFile==@"fileview"){
fileTxt=[file textContents:&theError];
if(!theError)
fileTxt=[GLFileView escapeHTML:fileTxt];
}else if(startFile==@"blame"){
fileTxt=[file blame:&theError];
if(!theError)
fileTxt=[self parseBlame:fileTxt];
}else if(startFile==@"log"){
fileTxt=[file log:logFormat error:&theError];
}else if(startFile==@"diff"){
fileTxt=[file diff:diffType error:&theError];
if(!theError)
fileTxt=[GLFileView parseDiff:fileTxt];
}
id script = [view windowScriptObject];
if(!theError){
NSString *filePath = [file fullPath];
fileTxt=[fileTxt stringByReplacingOccurrencesOfString:@"\t" withString:@" "];
DLog(@"file.sha='%@'",file.sha);
fileTxt=[fileTxt stringByReplacingOccurrencesOfString:@"{SHA_PREV}" withString:file.sha];
if(diffType==@"h") {
fileTxt=[fileTxt stringByReplacingOccurrencesOfString:@"{SHA}" withString:@"HEAD"];
}else {
fileTxt=[fileTxt stringByReplacingOccurrencesOfString:@"{SHA}" withString:@"--"];
}
[script callWebScriptMethod:@"showFile" withArguments:[NSArray arrayWithObjects:fileTxt, filePath, nil]];
}else{
[script callWebScriptMethod:@"setMessage" withArguments:[NSArray arrayWithObjects:[theError localizedDescription], nil]];
}
[self updateSearch];
}
}
#ifdef DEBUG_BUILD
DOMHTMLElement *dom=(DOMHTMLElement *)[[[view mainFrame] DOMDocument] documentElement];
NSString *domH=[dom outerHTML];
NSString *tmpFile=@"~/tmp/test.html";
[domH writeToFile:[tmpFile stringByExpandingTildeInPath] atomically:true encoding:NSUTF8StringEncoding error:nil];
#endif
}
#pragma mark JavaScript log.js methods
- (void) selectCommit:(NSString*)c
{
[historyController selectCommit:c];
}
// TODO: need to be refactoring
- (void) openFileMerge:(NSString*)file sha:(NSString *)sha sha2:(NSString *)sha2;
{
NSArray *args=[NSArray arrayWithObjects:@"difftool",@"--no-prompt",@"--tool=opendiff",sha,sha2,file,nil];
[historyController.repository handleInWorkDirForArguments:args];
}
#pragma mark MGScopeBarDelegate methods
- (int)numberOfGroupsInScopeBar:(MGScopeBar *)theScopeBar
{
return [self.groups count];
}
- (NSArray *)scopeBar:(MGScopeBar *)theScopeBar itemIdentifiersForGroup:(int)groupNumber
{
return [[self.groups objectAtIndex:groupNumber] valueForKeyPath:[NSString stringWithFormat:@"%@.%@", GROUP_ITEMS, ITEM_IDENTIFIER]];
}
- (NSString *)scopeBar:(MGScopeBar *)theScopeBar labelForGroup:(int)groupNumber
{
return [[self.groups objectAtIndex:groupNumber] objectForKey:GROUP_LABEL]; // might be nil, which is fine (nil means no label).
}
- (NSString *)scopeBar:(MGScopeBar *)theScopeBar titleOfItem:(NSString *)identifier inGroup:(int)groupNumber
{
NSArray *items = [[self.groups objectAtIndex:groupNumber] objectForKey:GROUP_ITEMS];
if (items) {
for (NSDictionary *item in items) {
if ([[item objectForKey:ITEM_IDENTIFIER] isEqualToString:identifier]) {
return [item objectForKey:ITEM_NAME];
break;
}
}
}
return nil;
}
- (MGScopeBarGroupSelectionMode)scopeBar:(MGScopeBar *)theScopeBar selectionModeForGroup:(int)groupNumber
{
return [[[self.groups objectAtIndex:groupNumber] objectForKey:GROUP_SELECTION_MODE] intValue];
}
- (void)scopeBar:(MGScopeBar *)theScopeBar selectedStateChanged:(BOOL)selected forItem:(NSString *)identifier inGroup:(int)groupNumber
{
if((groupNumber==0) && (startFile!=identifier)){
NSString *path = [NSString stringWithFormat:@"html/views/%@", identifier];
NSString *html = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:path];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:html]];
[[view mainFrame] loadRequest:request];
startFile=identifier;
}else if(groupNumber==1){
diffType=identifier;
if(startFile==@"diff"){
[[view mainFrame] reload];
}
}
lastFile=nil;
}
- (NSView *)accessoryViewForScopeBar:(MGScopeBar *)scopeBar
{
return accessoryView;
}
- (void) didLoad
{
[self showFile];
}
- (void)closeView
{
[historyController.treeController removeObserver:self forKeyPath:@"selection"];
[self saveSplitViewPosition];
[super closeView];
}
+ (NSString *) escapeHTML:(NSString *)txt
{
if (txt == nil)
return txt;
NSMutableString *newTxt = [NSMutableString stringWithString:txt];
[newTxt replaceOccurrencesOfString:@"&" withString:@"&" options:NSLiteralSearch range:NSMakeRange(0, [newTxt length])];
[newTxt replaceOccurrencesOfString:@"<" withString:@"<" options:NSLiteralSearch range:NSMakeRange(0, [newTxt length])];
[newTxt replaceOccurrencesOfString:@">" withString:@">" options:NSLiteralSearch range:NSMakeRange(0, [newTxt length])];
[newTxt replaceOccurrencesOfString:@"\"" withString:@""" options:NSLiteralSearch range:NSMakeRange(0, [newTxt length])];
[newTxt replaceOccurrencesOfString:@"'" withString:@"'" options:NSLiteralSearch range:NSMakeRange(0, [newTxt length])];
return newTxt;
}
+ (NSString *)parseDiffTree:(NSString *)txt withStats:(NSMutableDictionary *)stats
{
NSInteger granTotal=1;
for(NSArray *stat in [stats allValues]){
NSInteger add=[[stat objectAtIndex:0] integerValue];
NSInteger rem=[[stat objectAtIndex:1] integerValue];
NSInteger tot=add+rem;
if(tot>granTotal)
granTotal=tot;
[stats setObject:[NSArray arrayWithObjects:[NSNumber numberWithInteger:add],[NSNumber numberWithInteger:rem],[NSNumber numberWithInteger:tot],nil] forKey:[stat objectAtIndex:2]];
}
NSArray *lines = [txt componentsSeparatedByString:@"\n"];
NSMutableString *res=[NSMutableString string];
[res appendString:@"<table id='filelist'>"];
for (__strong NSString *line in lines) {
if([line length]<98) continue;
line=[line substringFromIndex:97];
NSArray *fileStatus=[line componentsSeparatedByString:@"\t"];
NSString *status=[[fileStatus objectAtIndex:0] substringToIndex:1]; // ignore the score
NSString *file=[fileStatus objectAtIndex:1];
NSString *txt=file;
NSString *fileName=file;
if([status isEqualToString:@"C"] || [status isEqualToString:@"R"]){
txt=[NSString stringWithFormat:@"%@ -> %@",file,[fileStatus objectAtIndex:2]];
fileName=[fileStatus objectAtIndex:2];
}
NSArray *stat=[stats objectForKey:fileName];
NSInteger add=[[stat objectAtIndex:0] integerValue];
NSInteger rem=[[stat objectAtIndex:1] integerValue];
[res appendString:@"<tr><td class='name'>"];
[res appendString:[NSString stringWithFormat:@"<a class='%@' href='#%@' representedFile='%@'>%@</a>",status,file,fileName,txt]];
[res appendString:@"</td><td class='bar'>"];
[res appendString:@"<div>"];
[res appendString:[NSString stringWithFormat:@"<span class='add' style='width:%d%%'></span>",((add*100)/granTotal)]];
[res appendString:[NSString stringWithFormat:@"<span class='rem' style='width:%d%%'></span>",((rem*100)/granTotal)]];
[res appendString:@"</div>"];
[res appendString:[NSString stringWithFormat:@"</td><td class='add'>+ %d</td><td class='rem'>- %d</td></tr>",add,rem]];
}
[res appendString:@"</table>"];
return res;
}
+ (NSString *)parseDiff:(NSString *)txt
{
txt=[self escapeHTML:txt];
NSMutableString *res=[NSMutableString string];
NSScanner *scan=[NSScanner scannerWithString:txt];
NSString *block;
if(![txt hasPrefix:@"diff --"])
[scan scanUpToString:@"diff --" intoString:&block]; //move to first diff
while([scan scanString:@"diff --" intoString:NULL]){ // is a diff start?
[scan scanUpToString:@"\ndiff --" intoString:&block];
[res appendString:[GLFileView parseDiffBlock:[NSString stringWithFormat:@"diff --%@",block]]];
}
return [NSString stringWithFormat:@"<div id='diffs'>%@</div>",res];
}
+ (NSString *)parseDiffBlock:(NSString *)txt
{
NSMutableString *res=[NSMutableString string];
NSScanner *scan=[NSScanner scannerWithString:txt];
NSString *block;
[scan scanUpToString:@"\n@@" intoString:&block];
[res appendString:@"<div class='diff-header'><table class='diff'><thead>"];
[res appendString:[GLFileView parseDiffHeader:block]];
[res appendString:@"</td></tr></thead></table></div><div class='diff-body'><table class='diff'><tbody>"];
if([block rangeOfString:@"Binary files"].location!=NSNotFound){
[res appendString:[GLFileView parseBinaryDiff:block]];
}
while([scan scanString:@"@@" intoString:NULL]){
[scan scanUpToString:@"\n@@" intoString:&block];
[res appendString:[GLFileView parseDiffChunk:[NSString stringWithFormat:@"@@%@",block]]];
}
[res appendString:@"</tbody></table></div>"];
return res;
}
+ (NSString *)parseBinaryDiff:(NSString *)txt
{
NSMutableString *res=[NSMutableString string];
NSScanner *scan=[NSScanner scannerWithString:txt];
NSString *block;
[scan scanUpToString:@"Binary files" intoString:NULL];
[scan scanUpToString:@"" intoString:&block];
NSArray *files=[self getFilesNames:block];
[res appendString:@"<tr class='images'><td>"];
[res appendString:[NSString stringWithFormat:@"%@<br/>",[files objectAtIndex:0]]];
if(![[files objectAtIndex:0] isAbsolutePath]){
if([GLFileView isImage:[files objectAtIndex:0]]){
[res appendString:[NSString stringWithFormat:@"<img src='GitX://{SHA}:/prev/%@'/>",[files objectAtIndex:0]]];
}
}
[res appendString:@"</td><td>=></td><td>"];
[res appendString:[NSString stringWithFormat:@"%@<br/>",[files objectAtIndex:1]]];
if(![[files objectAtIndex:1] isAbsolutePath]){
if([GLFileView isImage:[files objectAtIndex:1]]){
[res appendString:[NSString stringWithFormat:@"<img src='GitX://{SHA}:/%@'/>",[files objectAtIndex:1]]];
}
}
[res appendString:@"</td></tr>"];
return res;
}
+ (NSString *)parseDiffChunk:(NSString *)txt
{
NSEnumerator *lines = [[txt componentsSeparatedByString:@"\n"] objectEnumerator];
NSMutableString *res=[NSMutableString string];
NSString *line;
int l_line[32]; // FIXME: make dynamic
int r_line;
line=[lines nextObject];
DLog(@"-=%@=-",line);
int arity = 0; /* How many files are merged here? Count the '@'! */
while ([line characterAtIndex:arity] == '@')
arity++;
NSRange hr = NSMakeRange(arity+1, [line rangeOfString:@" @@"].location-arity-1);
NSString *header=[line substringWithRange:hr];
NSArray *pos=[header componentsSeparatedByString:@" "];
NSArray *pos_r=[[pos objectAtIndex:arity-1] componentsSeparatedByString:@","];
for(int i=0; i<arity-1; i++){
NSArray *pos_l=[[pos objectAtIndex:i] componentsSeparatedByString:@","];
l_line[i]=abs([[pos_l objectAtIndex:0]integerValue]);
}
r_line=[[pos_r objectAtIndex:0]integerValue];
[res appendString:[NSString stringWithFormat:@"<tr class='header'><td colspan='%d'>%@</td></tr>",arity+1,line]];
while((line=[lines nextObject])){
NSString *prefix=[line substringToIndex:arity-1];
if([prefix rangeOfString:@"-"].location != NSNotFound){
[res appendString:@"<tr class='l'>"];
for(int i=0; i<arity-1; i++){
if([prefix characterAtIndex:i] == '-'){
[res appendString:[NSString stringWithFormat:@"<td class='l'>%d</td>",l_line[i]++]];
}else{
[res appendString:@"<td class='l'></td>"];
}
}
[res appendString:@"<td class='r'></td>"];
}else if([prefix rangeOfString:@"+"].location != NSNotFound){
[res appendString:@"<tr class='r'>"];
for(int i=0; i<arity-1; i++){
if([prefix characterAtIndex:i] == ' '){
[res appendString:[NSString stringWithFormat:@"<td class='l'>%d</td>",l_line[i]++]];
}else{
[res appendString:@"<td class='l'></td>"];
}
}
[res appendString:[NSString stringWithFormat:@"<td class='r'>%d</td>",r_line++]];
}else{
[res appendString:@"<tr>"];
for(int i=0; i<arity-1; i++){
[res appendString:[NSString stringWithFormat:@"<td class='l'>%d</td>",l_line[i]++]];
}
[res appendString:[NSString stringWithFormat:@"<td class='r'>%d</td>",r_line++]];
}
if(![prefix hasPrefix:@"\\"]){
[res appendString:[NSString stringWithFormat:@"<td class='code'>%@</td></tr>",[line substringFromIndex:arity-1]]];
}
}
return res;
}
+ (NSString *)parseDiffHeader:(NSString *)txt
{
NSEnumerator *lines = [[txt componentsSeparatedByString:@"\n"] objectEnumerator];
NSMutableString *res=[NSMutableString string];
NSString *line=[lines nextObject];
NSString *fileName=[self getFileName:line];
[res appendString:[NSString stringWithFormat:@"<tr id='%@'><td colspan='33'><div style='float:left;'>",fileName]];
do{
[res appendString:[NSString stringWithFormat:@"<p>%@</p>",line]];
}while((line=[lines nextObject]));
[res appendString:@"</div>"];
if([txt rangeOfString:@"Binary files"].location==NSNotFound){
[res appendString:[NSString stringWithFormat:@"<div class='filemerge'><a href='' onclick='openFileMerge(\"%@\",\"{SHA_PREV}\",\"{SHA}\"); return false;'><img src='GitX://app:/filemerge' width='32' height='32'/><br/>open in<br/>FileMerge</a></div>",fileName]];
}
[res appendString:@"</td></tr>"];
return res;
}
+(NSString *)getFileName:(NSString *)line
{
NSRange b = [line rangeOfString:@"b/"];
if (b.length == 0)
b = [line rangeOfString:@"--cc "];
NSString *file=[line substringFromIndex:b.location+b.length];
DLog(@"line=%@",line);
DLog(@"file=%@",file);
return file;
}
+(NSArray *)getFilesNames:(NSString *)line
{
NSString *a = nil;
NSString *b = nil;
NSScanner *scanner=[NSScanner scannerWithString:line];
if([scanner scanString:@"Binary files " intoString:NULL]){
[scanner scanUpToString:@" and" intoString:&a];
[scanner scanString:@"and" intoString:NULL];
[scanner scanUpToString:@" differ" intoString:&b];
}
if (![a isAbsolutePath]) {
a=[a substringFromIndex:2];
}
if (![b isAbsolutePath]) {
b=[b substringFromIndex:2];
}
return [NSArray arrayWithObjects:a,b,nil];
}
+(NSString*)mimeTypeForFileName:(NSString*)name
{
NSString *mimeType = nil;
NSInteger i=[name rangeOfString:@"." options:NSBackwardsSearch].location;
if(i!=NSNotFound){
NSString *ext=[name substringFromIndex:i+1];
CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)ext, NULL);
if(UTI){
CFStringRef registeredType = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType);
if(registeredType){
mimeType = [NSString stringWithFormat:@"%@",registeredType];
CFRelease(registeredType);
}
CFRelease(UTI);
}
}
return mimeType;
}
+(BOOL)isDiffHeader:(NSString*)line
{
unichar c=[line characterAtIndex:0];
return (c=='i') || (c=='m') || (c=='n') || (c=='d') || (c=='-') || (c=='+');
}
+(BOOL)isImage:(NSString*)file
{
NSString *mimeType=[GLFileView mimeTypeForFileName:file];
return (mimeType!=nil) && ([mimeType rangeOfString:@"image/" options:NSCaseInsensitiveSearch].location!=NSNotFound);
}
+(BOOL)isBinaryFile:(NSString *)line
{
return [line hasPrefix:@"Binary files"];
}
+(BOOL)isStartDiff:(NSString *)line
{
return [line hasPrefix:@"diff --"];
}
+(BOOL)isStartBlock:(NSString *)line
{
return [line hasPrefix:@"@@"];
}
- (NSString *) parseBlame:(NSString *)txt
{
txt=[GLFileView escapeHTML:txt];
NSArray *lines = [txt componentsSeparatedByString:@"\n"];
NSString *line;
NSMutableDictionary *headers=[NSMutableDictionary dictionary];
NSMutableString *res=[NSMutableString string];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] initWithDateFormat:@"%Y-%m-%d %H:%M:%S" allowNaturalLanguage:NO];
[res appendString:@"<table class='blocks'>\n"];
int i=0;
while(i<[lines count]){
line=[lines objectAtIndex:i];
NSArray *header=[line componentsSeparatedByString:@" "];
if([header count]==4){
NSString *commitID = (NSString *)[header objectAtIndex:0];
int nLines=[(NSString *)[header objectAtIndex:3] intValue];
[res appendFormat:@"<tr class='block l%d'>\n",nLines];
line=[lines objectAtIndex:++i];
if([[[line componentsSeparatedByString:@" "] objectAtIndex:0] isEqual:@"author"]){
NSString *author=[line stringByReplacingOccurrencesOfString:@"author " withString:@""];
NSString *timestamp=nil;
while(timestamp==nil){
line=[lines objectAtIndex:i++];
if([[[line componentsSeparatedByString:@" "] objectAtIndex:0] isEqual:@"author-time"]){
timestamp=[line stringByReplacingOccurrencesOfString:@"author-time " withString:@""];
}
}
NSString *timezone=nil;
while(timezone==nil){
line=[lines objectAtIndex:i++];
if([[[line componentsSeparatedByString:@" "] objectAtIndex:0] isEqual:@"author-tz"]){
timezone=[line stringByReplacingOccurrencesOfString:@"author-tz " withString:@""];
}
}
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue]];
NSString *dateString = [NSString stringWithFormat:@"%@ %@",[dateFormatter stringFromDate: date],timezone];
NSString *summary=nil;
while(summary==nil){
line=[lines objectAtIndex:i++];
if([[[line componentsSeparatedByString:@" "] objectAtIndex:0] isEqual:@"summary"]){
summary=[line stringByReplacingOccurrencesOfString:@"summary " withString:@""];
}
}
NSRange trunc_c={0,7};
NSString *truncate_c=commitID;
if([commitID length]>8){
truncate_c=[commitID substringWithRange:trunc_c];
}
NSRange trunc={0,22};
NSString *truncate_a=author;
if([author length]>22){
truncate_a=[author substringWithRange:trunc];
}
NSString *truncate_s=summary;
if([summary length]>30){
truncate_s=[summary substringWithRange:trunc];
}
NSString *tooltip = [NSString stringWithFormat:@"%@\nAuthor: %@\nDate: %@\n\n%@",commitID,author,dateString,summary];
NSString *block=[NSString stringWithFormat:@"<td><p class='author'><a title='%@' href='' onclick='selectCommit(\"%@\"); return false;'>%@</a> %@</p><p class='summary'>%@</p></td>\n<td>\n",tooltip,commitID,truncate_c,truncate_a,truncate_s];
[headers setObject:block forKey:[header objectAtIndex:0]];
}
[res appendString:[headers objectForKey:[header objectAtIndex:0]]];
NSMutableString *code=[NSMutableString string];
do{
line=[lines objectAtIndex:i++];
}while([line characterAtIndex:0]!='\t');
line=[line substringFromIndex:1];
[code appendString:line];
[code appendString:@"\n"];
int n;
for(n=1;n<nLines;n++){
do{
line=[lines objectAtIndex:i++];
}while([line characterAtIndex:0]!='\t');
line=[line substringFromIndex:1];
[code appendString:line];
[code appendString:@"\n"];
}
[res appendFormat:@"<pre class='first-line: %@;brush: objc'>%@</pre>",[header objectAtIndex:2],code];
[res appendString:@"</td>\n"];
}else{
break;
}
[res appendString:@"</tr>\n"];
}
[res appendString:@"</table>\n"];
//DLog(@"%@",res);
return (NSString *)res;
}
#pragma mark NSSplitView delegate methods
#define kFileListSplitViewLeftMin 120
#define kFileListSplitViewRightMin 180
#define kHFileListSplitViewPositionDefault @"File List SplitView Position"
- (CGFloat)splitView:(NSSplitView *)splitView constrainMinCoordinate:(CGFloat)proposedMin ofSubviewAt:(NSInteger)dividerIndex
{
return kFileListSplitViewLeftMin;
}
- (CGFloat)splitView:(NSSplitView *)splitView constrainMaxCoordinate:(CGFloat)proposedMax ofSubviewAt:(NSInteger)dividerIndex
{
return [splitView frame].size.width - [splitView dividerThickness] - kFileListSplitViewRightMin;
}
// while the user resizes the window keep the left (file list) view constant and just resize the right view
// unless the right view gets too small
- (void)splitView:(NSSplitView *)splitView resizeSubviewsWithOldSize:(NSSize)oldSize
{
NSRect newFrame = [splitView frame];
float dividerThickness = [splitView dividerThickness];
NSView *leftView = [[splitView subviews] objectAtIndex:0];
NSRect leftFrame = [leftView frame];
leftFrame.size.height = newFrame.size.height;
if ((newFrame.size.width - leftFrame.size.width - dividerThickness) < kFileListSplitViewRightMin) {
leftFrame.size.width = newFrame.size.width - kFileListSplitViewRightMin - dividerThickness;
}
NSView *rightView = [[splitView subviews] objectAtIndex:1];
NSRect rightFrame = [rightView frame];
rightFrame.origin.x = leftFrame.size.width + dividerThickness;
rightFrame.size.width = newFrame.size.width - rightFrame.origin.x;
rightFrame.size.height = newFrame.size.height;
[leftView setFrame:leftFrame];
[rightView setFrame:rightFrame];
}
// NSSplitView does not save and restore the position of the SplitView correctly so do it manually
- (void)saveSplitViewPosition
{
float position = [[[fileListSplitView subviews] objectAtIndex:0] frame].size.width;
[[NSUserDefaults standardUserDefaults] setFloat:position forKey:kHFileListSplitViewPositionDefault];
[[NSUserDefaults standardUserDefaults] synchronize];
}
// make sure this happens after awakeFromNib
- (void)restoreSplitViewPositiion
{
float position = [[NSUserDefaults standardUserDefaults] floatForKey:kHFileListSplitViewPositionDefault];
if (position < 1.0)
position = 200;
[fileListSplitView setPosition:position ofDividerAtIndex:0];
[fileListSplitView setHidden:NO];
}
// -------------
// File search
// -------------
#pragma mark -
#pragma mark Search
NSString *searchString;
- (NSString *)numberOfMatchesString
{
if ([view resultCount] == 0)
return @"Not found";
if ([view resultCount] == 1)
return @"1 match";
return [NSString stringWithFormat:@"%d matches", [view resultCount]];
}
- (void) updateSearch
{
[view search:searchField update:YES grabFocus:NO direction:YES];
[self updateSearchUI];
}
- (void) updateSearchUI
{
if ([searchString length] == 0) {
[numberOfMatches setHidden:YES];
[stepper setHidden:YES];
}
else {
[numberOfMatches setHidden:NO];
[stepper setHidden:NO];
[numberOfMatches setStringValue:[self numberOfMatchesString]];
[stepper setEnabled:([view resultCount]>0)];
}
}
- (IBAction)searchFieldChanged:(id)sender
{
BOOL update=[[searchField stringValue] isEqualToString:searchString]? NO: YES;
searchString=[searchField stringValue];
[view search:searchField update:update grabFocus:YES direction:YES];
[self updateSearchUI];
}
- (IBAction)stepperPressed:(id)sender {
NSInteger selectedSegment = [sender selectedSegment];
if (selectedSegment == 0)
[view search:searchField update:NO grabFocus:YES direction:NO];
else
[view search:searchField update:NO grabFocus:YES direction:YES];
}
@end