-
Notifications
You must be signed in to change notification settings - Fork 0
/
MySvnRepositoryBrowserView.m
729 lines (574 loc) · 20.6 KB
/
MySvnRepositoryBrowserView.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
//
// MySvnRepositoryBrowserView.m
//
#import "MySvnRepositoryBrowserView.h"
#import "MyDragSupportMatrix.h"
#import "MyApp.h"
#import "MySvn.h"
#import "MyRepository.h"
#import "RepoItem.h"
#import "SvnListParser.h"
#import "NSString+MyAdditions.h"
#import "Tasks.h"
#import "CommonUtils.h"
#import "SvnInterface.h"
static NSFont* gFont = nil;
static NSDictionary* gStyle = nil;
//----------------------------------------------------------------------------------------
// Compare names alphabetically & case insensitively.
static int
compareNames (id obj1, id obj2, void* context)
{
#pragma unused(context)
return [[obj1 name] compare: [obj2 name] options: kSortOptions];
}
//----------------------------------------------------------------------------------------
// Returns an array of RepoItems
static NSArray*
ToRepoItems (NSArray* dicts, NSString* revision)
{
NSMutableArray* result = [NSMutableArray array];
const SvnRevNum revNum = SvnRevNumFromString(revision);
for_each_obj(en, it, dicts)
{
id obj = [RepoItem repoItem: it revision: revNum];
[result addObject: obj];
[obj release];
}
[result sortUsingFunction: compareNames context: NULL];
return result;
}
//----------------------------------------------------------------------------------------
// Returns an array of dicts
static NSArray*
FromRepoItems (NSArray* repoItems)
{
NSMutableArray* result = [NSMutableArray array];
for_each_obj(en, it, repoItems)
{
[result addObject: [it dictionary]];
}
return result;
}
//----------------------------------------------------------------------------------------
static NSArray*
RepoItemsSetRevision (NSArray* repoItems, id revision)
{
const SvnRevNum revNum = SvnRevNumFromString(revision);
for_each_obj(en, it, repoItems)
{
[(RepoItem*) it setRevision: revNum];
}
[(NSMutableArray*) repoItems sortUsingFunction: compareNames context: NULL];
return repoItems;
}
//----------------------------------------------------------------------------------------
#pragma mark -
//----------------------------------------------------------------------------------------
@interface RepoCell : NSBrowserCell @end // RepoCell
enum {
kIconSize = 13,
kIconExtra = 1,
kIconWidth = kIconSize + kIconExtra,
};
//----------------------------------------------------------------------------------------
@implementation RepoCell
//----------------------------------------------------------------------------------------
- (id) initRepoCell: (RepoItem*) repoItem
{
if (self = [super initTextCell: [repoItem name]])
{
[self setRepresentedObject: repoItem];
}
return self;
}
//----------------------------------------------------------------------------------------
- (void) drawWithFrame: (NSRect) cellFrame
inView: (NSView*) controlView
{
RepoItem* const repoItem = [self representedObject];
if (repoItem != nil)
{
[([self isHighlighted] || [self state]
? [self highlightColorInView: controlView]
: [NSColor whiteColor]) setFill];
[NSBezierPath fillRect: cellFrame];
const CGRect rect = {{ kIconExtra, -kIconSize }, { kIconSize, kIconSize }};
CGContextRef ctx = [[NSGraphicsContext currentContext] graphicsPort];
CGAffineTransform mat = { 1, 0, 0, -1, cellFrame.origin.x,
cellFrame.origin.y + floor((cellFrame.size.height - kIconSize) * 0.5) };
CGContextSaveGState(ctx);
CGContextConcatCTM(ctx, mat);
WarnIf(PlotIconRefInContext(ctx, &rect, kAlignNone, kTransformNone,
NULL, kPlotIconRefNormalFlags, [repoItem icon]));
CGContextRestoreGState(ctx);
cellFrame.origin.x += kIconWidth;
cellFrame.origin.y += 1;
cellFrame.size.width -= kIconWidth;
cellFrame.size.height -= 2;
}
[super drawWithFrame: cellFrame inView: controlView]; // Draws the text
}
//----------------------------------------------------------------------------------------
@end // RepoCell
//----------------------------------------------------------------------------------------
#pragma mark -
//----------------------------------------------------------------------------------------
@interface MySvnRepositoryBrowserView (Private)
- (void) displayDirCache: info;
- (void) displayDirNoCache: info;
- (void) displayDirList: (NSArray*) dirList
info: (NSDictionary*) info
shouldCache: (BOOL) shouldCache;
@end // MySvnRepositoryBrowserView (Private)
//----------------------------------------------------------------------------------------
@implementation MySvnRepositoryBrowserView
- (id) initWithFrame: (NSRect) frameRect
{
if (gFont == nil)
gFont = [[NSFont labelFontOfSize: [NSFont labelFontSize]] retain];
if (gStyle == nil)
gStyle = [[NSDictionary dictionaryWithObjectsAndKeys:
gFont, NSFontAttributeName,
[NSNumber numberWithFloat: 0.4], NSObliquenessAttributeName,
nil] retain];
if (self = [super initWithFrame: frameRect])
{
showRoot = YES;
if ([NSBundle loadNibNamed: @"MySvnRepositoryBrowserView" owner: self])
{
[fView setFrame: [self bounds]];
[self addSubview: fView];
}
}
return self;
}
//----------------------------------------------------------------------------------------
- (void) dealloc
{
// dprintf("0x%X", self);
[self setBrowserPath: nil];
[super dealloc];
}
//----------------------------------------------------------------------------------------
- (void) unload
{
// the nib is responsible for releasing its top-level objects
// [fView release]; // this is done by super
// these objects are bound to the file owner and retain it
// we need to unbind them
[revisionTextField unbind: @"value"];
[super unload];
}
//----------------------------------------------------------------------------------------
- (BOOL) isFirstResponder
{
id view = [[self window] firstResponder];
return ISA(view, NSView) && [view isDescendantOf: self];
}
//----------------------------------------------------------------------------------------
// Note: <sender> is an NSCell in an NSMatrix in the NSBrowser <browser>
- (void) onDoubleClick: (id) sender
{
AssertClass(sender, NSCell);
if (!isSubBrowser)
{
[fRepository openItem: [sender representedObject] revision: [self revision]];
}
}
//----------------------------------------------------------------------------------------
#pragma mark -
#pragma mark public methods
//----------------------------------------------------------------------------------------
// Returns an array of the selected represented objects
- (NSArray*) selectedItems
{
return [[browser selectedCells] valueForKey: @"representedObject"];
}
//----------------------------------------------------------------------------------------
// If there is a single selected item then return it else return nil.
- (RepoItem*) selectedItemOrNil
{
NSArray* cells = [browser selectedCells];
return (cells != nil && [cells count] == 1) ? [[cells lastObject] representedObject] : nil;
}
//----------------------------------------------------------------------------------------
- (void) reset
{
[self setBrowserPath: nil];
[browser setPath: @"/"];
}
//----------------------------------------------------------------------------------------
- (void) setupForSubBrowser: (BOOL) showRoot_
allowsLeaves: (BOOL) allowsLeaves
allowsMultipleSelection: (BOOL) allowsMultiSel
{
isSubBrowser = YES;
showRoot = showRoot_;
disallowLeaves = !allowsLeaves;
[self setRevision: @"HEAD"];
[browser setAllowsEmptySelection: NO];
[browser setAllowsMultipleSelection: allowsMultiSel];
[self fetchSvn];
}
//----------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Browser delegate methods
//----------------------------------------------------------------------------------------
- (void) browser: (NSBrowser*) sender
createRowsForColumn: (int) column
inMatrix: (NSMatrix*) matrix
{
const id revision = [self revision];
if (revision == nil) return;
if (isSubBrowser)
[(MyDragSupportMatrix*) matrix setupForSubBrowser];
if ([matrix numberOfRows] != 0)
{
}
else if (column == 0 && showRoot)
{
[self setIsFetching: NO];
const BOOL isDir = ![fRepository rootIsFile];
NSURL* const url = [self url];
NSString* const name = isDir ? @"root" : [UnEscapeURL(url) lastPathComponent];
fNameLen = [name length] + 1;
RepoItem* repoItem = [RepoItem repoRoot: isDir name: name
revision: SvnRevNumFromString(revision) url: url];
RepoCell* const cell = [[RepoCell alloc] initRepoCell: repoItem];
[repoItem release];
[cell setAttributedStringValue: [[[NSAttributedString alloc]
initWithString: name attributes: gStyle] autorelease]];
[cell setLeaf: !isDir];
[cell setLineBreakMode: NSLineBreakByTruncatingTail];
[matrix addRowWithCells: [NSArray arrayWithObject: cell]];
[matrix putCell: cell atRow: 0 column: 0];
[cell release];
[matrix sizeToCells];
[matrix display];
}
else
[self fetchSvnListForUrl: [sender path] column: column matrix: matrix];
}
//----------------------------------------------------------------------------------------
#pragma mark -
#pragma mark svn related methods
//----------------------------------------------------------------------------------------
// Triggers the fetching
- (void) fetchSvn
{
[self setBrowserPath: [browser path]];
[super fetchSvn];
[browser reloadColumn: 0];
if (showRoot)
{
[browser selectRow: 0 inColumn: 0];
[browser setWidth: fNameLen * 8 ofColumn: 0];
}
}
//----------------------------------------------------------------------------------------
#pragma mark -
#pragma mark svn list
//----------------------------------------------------------------------------------------
typedef const svn_dirent_t* SvnListEntry;
typedef const svn_lock_t* SvnLock;
const UInt32 kListFlags = SVN_DIRENT_KIND | SVN_DIRENT_SIZE | SVN_DIRENT_CREATED_REV |
SVN_DIRENT_TIME | SVN_DIRENT_LAST_AUTHOR;
const NSPropertyListFormat kListCacheFormat = NSPropertyListBinaryFormat_v1_0;
//----------------------------------------------------------------------------------------
struct SvnListEnv
{
SvnRevNum fRevision;
NSMutableArray* fList;
// UInt64 fT0;
id fSelf;
};
typedef struct SvnListEnv SvnListEnv;
//----------------------------------------------------------------------------------------
// Repo 'svn list' callback. Appends to fList in (SvnListEnv*) baton.
static SvnError
svnListReceiver (void* baton,
const char* path,
SvnListEntry dirent,
SvnLock lock,
const char* abs_path,
SvnPool pool)
{
#pragma unused(lock, abs_path, pool)
/*dprintf("rev=%d kind=%d time=%qi author=%s path=<%s>",
dirent->created_rev, dirent->kind, dirent->time, dirent->last_author, path);*/
SvnListEnv* const env = (SvnListEnv*) baton;
if ([env->fSelf pendingTask] == nil)
return svn_error_create(SVN_ERR_CANCELLED, NULL, NULL);
if (*path != 0)
{
const char* str = strrchr(path, '/');
if (str != NULL)
path = str + 1;
id obj = [RepoItem repoItem: (dirent->kind == svn_node_dir)
name: UTF8(path)
author: UTF8(dirent->last_author)
revision: env->fRevision
modRev: dirent->created_rev
time: dirent->time * 1e-6 - kCFAbsoluteTimeIntervalSince1970
size: dirent->size];
[env->fList addObject: obj];
[obj release];
#if 0
if (env->fT0 && microseconds() - env->fT0 > 500 * 1000)
{
env->fT0 = 0;
[env->fSelf setIsFetching: YES];
}
#endif
}
return SVN_NO_ERROR;
}
//----------------------------------------------------------------------------------------
// svn list of info.url via SvnInterface (called by separate thread)
- (void) svnDoList: (NSDictionary*) info
{
Assert(fRepository);
// NSLog(@"svn list - begin");
// NSLog(@"svnDoList: rev=%@ url=<%@>", [self revision], [[info objectForKey: @"url"] absoluteString]);
[self retain];
NSAutoreleasePool* const autoPool = [[NSAutoreleasePool alloc] init];
const SvnPool pool = SvnNewPool(); // Create top-level memory pool.
@try
{
UInt64 t0 = microseconds();
SvnClient ctx = [fRepository svnClient];
char path[PATH_MAX * 2];
if (ToUTF8([[info objectForKey: @"url"] absoluteString], path, sizeof(path)))
{
int len = strlen(path);
if (len > 5 && path[len - 1] == '/' && path[len - 2] != '/')
path[len - 1] = 0;
NSString* const revision = [self revision];
const BOOL isHead = [revision isEqualToString: @"HEAD"];
svn_opt_revision_t rev_opt = { svn_opt_revision_head };
if (!isHead)
{
rev_opt.kind = svn_opt_revision_number;
rev_opt.value.number = [revision intValue];
}
SvnListEnv env = { SvnRevNumFromString(revision), [info objectForKey: @"result"], /*t0,*/ self };
// Retrive directory list from repository.
SvnThrowIf(svn_client_list(path, &rev_opt, &rev_opt, !kSvnRecurse,
kListFlags, false,
svnListReceiver, &env,
ctx, pool));
[env.fList sortUsingFunction: compareNames context: NULL];
const double t = microseconds() - t0;
/* dprintf("results=%d column=%@ matrix=%@",
[env.fList count], [info objectForKey: @"column"], [info objectForKey: @"matrix"]);
dprintf("rev=%@ results=%d column=%@ '%s'",
revision, [env.fList count], [info objectForKey: @"column"], strrchr(path, '/'));*/
#if qTime
dprintf("svn_client_list: time=%g ms", t * 1e-3);
#endif
[self performSelectorOnMainThread: (!isHead && t > 2e3 && GetPreferenceBool(@"cacheSvnQueries"))
? @selector(displayDirCache:)
: @selector(displayDirNoCache:)
withObject: info waitUntilDone: YES];
}
}
@catch (SvnException* ex)
{
SvnReportCatch(ex);
[self setIsFetching: NO];
if ([ex error]->apr_err != SVN_ERR_CANCELLED)
[self performSelectorOnMainThread: @selector(svnError:) withObject: [ex message] waitUntilDone: NO];
}
@finally
{
SvnDeletePool(pool);
[autoPool release];
[self setPendingTask: nil];
[self release];
// NSLog(@"svn list - end");
}
}
//----------------------------------------------------------------------------------------
- (void) fetchSvnListForUrl: (NSString*) theURL
column: (int) column
matrix: (NSMatrix*) matrix
{
NSString* url2 = theURL;
if (showRoot)
url2 = [url2 substringFromIndex: fNameLen]; // get rid of "root" prefix
NSURL* cleanUrl = [NSURL URLWithString: [[url2 trimSlashes] escapeURL] relativeToURL: [self url]];
NSString* const revision = [self revision];
NSData* cachedData;
if (GetPreferenceBool(@"cacheSvnQueries") &&
![revision isEqualToString: @"HEAD"] &&
(cachedData = [NSData dataWithContentsOfFile: [self getCachePathForUrl: cleanUrl]]))
{
NSString* errorString = nil;
NSArray* resultArray = ToRepoItems(
[NSPropertyListSerialization propertyListFromData: cachedData
mutabilityOption: NSPropertyListMutableContainers
format: NULL
errorDescription: &errorString], revision);
if (errorString != nil)
{
dprintf("WARNING: Could not parse plist cache: %@\n data=%@ error=%@",
cleanUrl, cachedData, errorString);
[errorString release];
}
[self displayResultArray: resultArray column: column matrix: matrix];
}
else
{
NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:
[NSMutableArray array], @"result",
matrix, @"matrix",
[NSNumber numberWithInt: column], @"column",
cleanUrl, @"url",
nil];
[self setIsFetching: YES];
if (SvnWantAndHave())
{
// dprintf("svnDoList url='%@'", cleanUrl);
[self setPendingTask: info]; // Use any old dict
[NSThread detachNewThreadSelector: @selector(svnDoList:)
toTarget: self
withObject: info];
}
else
{
[self setPendingTask:
[MySvn list: PathPegRevision(cleanUrl, revision)
generalOptions: [self svnOptionsInvocation]
options: [NSArray arrayWithObjects: @"--xml", @"-r", revision, nil]
callback: [self makeCallbackInvocationOfKind: 10]
callbackInfo: info
taskInfo: [self documentNameDict]]
];
}
}
}
//----------------------------------------------------------------------------------------
- (NSString*) pathToColumn: (int) column
{
NSString* result = [browser pathToColumn: column];
if (showRoot)
{
result = [result substringFromIndex: fNameLen]; // don't keep the "root" prefix
}
return result;
}
//----------------------------------------------------------------------------------------
- (void) fetchSvnReceiveDataFinished: (id) taskObj
{
NSArray* const resultArray = [SvnListParser parseData: stdOutData(taskObj)];
NSString* const revision = [self revision];
[self displayDirList: RepoItemsSetRevision(resultArray, revision)
info: callbackInfo(taskObj)
shouldCache: ![revision isEqualToString: @"HEAD"]];
}
//----------------------------------------------------------------------------------------
- (void) displayDirCache: info
{
[self displayDirList: [info objectForKey: @"result"]
info: info
shouldCache: YES];
}
//----------------------------------------------------------------------------------------
- (void) displayDirNoCache: info
{
[self displayDirList: [info objectForKey: @"result"]
info: info
shouldCache: NO];
}
//----------------------------------------------------------------------------------------
- (void) displayDirList: (NSArray*) dirList
info: (NSDictionary*) info
shouldCache: (BOOL) shouldCache
{
[super fetchSvnReceiveDataFinished: nil];
[self displayResultArray: dirList
column: [[info objectForKey: @"column"] intValue]
matrix: [info objectForKey: @"matrix"]];
if (shouldCache)
{
NSString* errorString = nil;
NSData* data = [NSPropertyListSerialization dataFromPropertyList: FromRepoItems(dirList)
format: kListCacheFormat
errorDescription: &errorString];
NSURL* fetchedUrl = [info objectForKey: @"url"];
if (data == nil || ![data writeToFile: [self getCachePathForUrl: fetchedUrl] atomically: YES])
{
dprintf("WARNING: Could not cache: %@\n data=%@ error=%@", fetchedUrl, data, errorString);
}
[errorString release];
}
}
//----------------------------------------------------------------------------------------
/*
Each cell has a representedObject type: RepoItem
isRoot: is root item (BOOL)
name: file name (NSString)
path: file path (NSString)
url: file URL (NSURL)
mod_rev: last change revision number (NSString)
revision: revision number (NSString)
fileType: file ext or NSFileTypeDirectory (NSString)
isDir: item is a dir (BOOL)
author: revision author (NSString)
date: file modification date (UTCTime)
size: file size (SInt64)
*/
- (void) displayResultArray: (NSArray*) resultArray
column: (int) column
matrix: (NSMatrix*) matrix
{
//NSLog(@"matrix %@ %@ %d %@", browser, matrix, column, [self pathToColumn: column]);
NSString* const pathToColumn = [self pathToColumn: column];
NSURL* const url = [self url];
const int count = [resultArray count];
for (int i = 0; i < count; ++i)
{
RepoItem* const item = [resultArray objectAtIndex: i];
const BOOL isDir = [item setUp: pathToColumn url: url];
RepoCell* const cell = [[RepoCell alloc] initRepoCell: item];
if (!isDir && disallowLeaves)
[cell setEnabled: NO];
[cell setFont: gFont];
[cell setLeaf: !isDir];
[cell setRepresentedObject: item];
// NSLog(@"item=%@", item);
[matrix addRowWithCells: [NSArray arrayWithObject: cell]];
[matrix setToolTip: [item toolTip] forCell: cell];
[matrix putCell: cell atRow: i column: 0];
[cell release];
}
[matrix sizeToCells];
[matrix display];
// if ( [self browserPath] != nil )
// {
// [browser setPath: [self browserPath]]; // attempt to restore the previously displayed path
// [self setBrowserPath: nil];
// }
}
//----------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Accessors
//----------------------------------------------------------------------------------------
- (NSString*) browserPath { return browserPath; }
//----------------------------------------------------------------------------------------
- (void) setBrowserPath: (NSString*) aBrowserPath
{
id old = browserPath;
browserPath = [aBrowserPath retain];
[old release];
}
//----------------------------------------------------------------------------------------
- (NSString*) getCachePathForUrl: (NSURL*) theURL
{
return [MySvn cachePathForKey: [NSString stringWithFormat: @"%@::%@ list3",
[theURL absoluteString], [self revision]]];
}
@end
//----------------------------------------------------------------------------------------
// End of MySvnRepositoryBrowserView.m