-
Notifications
You must be signed in to change notification settings - Fork 94
/
BookmarkController.m
480 lines (401 loc) · 12.9 KB
/
BookmarkController.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
//
// BookmarkController.m
// ichm
//
// Created by Robin Lu on 8/10/08.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import "BookmarkController.h"
#import "CHMDocument.h"
#import "CHMFile.h"
#import "CHMBookmark.h"
#import "CHMTag.h"
@interface BookmarkController (Private)
- (void)groupByTagsMenuNeedsUpdate:(NSMenu*)menu;
- (void)groupByFilesMenuNeedsUpdate:(NSMenu*)menu;
- (NSMenuItem *)createMenuItemForBookmark:(CHMBookmark*)bm;
- (void)setupDataSource;
- (void)addEmptyItemToMenu:(NSMenu*)menu;
@end
@interface FetchRequestItem : NSObject
{
NSFetchRequest *request;
NSMutableArray* children;
NSString *title;
}
@property (readwrite, retain) NSFetchRequest* request;
@property (readwrite, retain) NSString* title;
- (void)addChild:(FetchRequestItem*)child;
- (FetchRequestItem*)childAtIndex:(int)index;
- (int)numberOfChildren;
@end
@implementation FetchRequestItem
@synthesize request;
@synthesize title;
- (id)init
{
children = [[NSMutableArray alloc] init];
request = nil;
title = nil;
return self;
}
- (void)dealloc
{
if (request)
[request release];
if (title)
[title release];
[children release];
[super dealloc];
}
- (void)addChild:(FetchRequestItem*)child
{
[children addObject:child];
}
- (FetchRequestItem*)childAtIndex:(int)index
{
return [children objectAtIndex:index];
}
- (int)numberOfChildren
{
return [children count];
}
@end
@implementation BookmarkController
- (id)init
{
if (![super initWithWindowNibName:@"Bookmark"])
return nil;
tocSource = nil;
[CHMFile purgeWithContext:[self managedObjectContext]];
return self;
}
- (void)windowDidLoad
{
NSLog(@"Nib file is loaded");
[tableController fetch:self];
}
- (IBAction)showWindow:(id)sender
{
[self setupDataSource];
[super showWindow:sender];
}
- (IBAction)showAddBookmark:(id)sender
{
// force load of nib
[self window];
CHMDocument *doc = (CHMDocument*)sender;
[titleField setStringValue:[doc currentTitle]];
[titleField selectText:self];
CHMBookmark* bm = [CHMBookmark bookmarkByURL:[doc currentURL] withContext:[self managedObjectContext]];
if( bm && [bm.tags count] > 0 )
[tagField setStringValue:[bm tagsString]];
else
[tagField setStringValue:@""];
[NSApp beginSheet:addPanel modalForWindow:[doc windowForSheet] modalDelegate:self didEndSelector:@selector(addBookmarkDidEnd:returnCode:contextInfo:) contextInfo:doc];
}
- (IBAction)endAddBookmark:(id)sender
{
unsigned int tag = [sender tag];
[NSApp endSheet:addPanel returnCode:tag];
[addPanel orderOut:sender];
}
- (void)addBookmarkDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
NSLog(@"add bookmark ended with return code:%d", returnCode);
if( 0 == returnCode || !contextInfo)
return;
CHMDocument *doc = contextInfo;
NSError *error = nil;
NSManagedObjectContext *context =[self managedObjectContext];
CHMFile *chmFile = [CHMFile fileByPath:[doc filePath] withContext:context] ;
if (!chmFile)
{
chmFile = [NSEntityDescription
insertNewObjectForEntityForName:@"File"
inManagedObjectContext:context];
[chmFile setPath:[doc filePath]];
[chmFile setTitle:[doc docTitle]];
[context save:&error];
if ( ![context save:&error] )
NSLog(@"Can not fetch file info: %d",error );
}
CHMBookmark *bookmark = [CHMBookmark bookmarkByURL:[doc currentURL] withContext:[self managedObjectContext]];
if ( !bookmark )
{
bookmark = [NSEntityDescription
insertNewObjectForEntityForName:@"Bookmark"
inManagedObjectContext:context];
}
[bookmark setUrl:[doc currentURL]];
[bookmark setTitle:[titleField stringValue]];
[bookmark setCreatedAt:[NSDate date]];
[bookmark setFile:chmFile];
[bookmark setTagsString:[tagField stringValue]];
if ( ![context save:&error] )
{
NSLog(@"Can not fetch file info: %d",error );
return;
}
}
- (IBAction)filterBookmarks:(id)sender
{
int selectedRow = [tocView selectedRow];
if( selectedRow >= 0 ) {
FetchRequestItem *item = [tocView itemAtRow:selectedRow];
NSError *error;
if ([item request])
[tableController fetchWithRequest:[item request] merge:NO error:&error];
else
[tableController fetch:sender];
}
}
#pragma mark CoreData context
- (NSString *)applicationSupportFolder {
NSString *applicationSupportFolder = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
if ( [paths count] == 0 ) {
NSRunAlertPanel(@"Alert", @"Can't find application support folder", @"Quit", nil, nil);
[[NSApplication sharedApplication] terminate:self];
} else {
applicationSupportFolder = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"iChm"];
}
return applicationSupportFolder;
}
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel) return managedObjectModel;
NSMutableSet *allBundles = [[NSMutableSet alloc] init];
[allBundles addObject: [NSBundle mainBundle]];
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles: [allBundles allObjects]] retain];
[allBundles release];
return managedObjectModel;
}
- (NSManagedObjectContext *) managedObjectContext {
NSError *error;
NSString *applicationSupportFolder = nil;
NSURL *url;
NSFileManager *fileManager;
NSPersistentStoreCoordinator *coordinator;
if (managedObjectContext) {
return managedObjectContext;
}
fileManager = [NSFileManager defaultManager];
applicationSupportFolder = [self applicationSupportFolder];
if ( ![fileManager fileExistsAtPath:applicationSupportFolder isDirectory:NULL] ) {
[fileManager createDirectoryAtPath:applicationSupportFolder attributes:nil];
}
url = [NSURL fileURLWithPath: [applicationSupportFolder stringByAppendingPathComponent: @"Bookmarks.sqlite"]];
coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
if ([coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error]){
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
} else {
[[NSApplication sharedApplication] presentError:error];
}
[coordinator release];
return managedObjectContext;
}
#pragma mark Bookmark Menu
#define BOOKMARK_LIMIT 15
- (NSMenuItem *)createMenuItemForBookmark:(CHMBookmark*)bm
{
NSMenuItem *newitem = [[[NSMenuItem alloc] init] autorelease];
[newitem setTitle:bm.title];
[newitem setTarget:self];
[newitem setAction:@selector(openBookmark:)];
[newitem setRepresentedObject:bm];
[newitem setEnabled:[bm.file.isValid boolValue] ];
return newitem;
}
- (void)addEmptyItemToMenu:(NSMenu*)menu
{
NSMenuItem *newitem = [[[NSMenuItem alloc] init] autorelease];
[newitem setTitle:NSLocalizedString(@"(Empty)", @"(Empty menu)")];
[newitem setEnabled:NO];
[menu addItem:newitem];
}
- (void)groupByTagsMenuNeedsUpdate:(NSMenu*)menu
{
NSArray *tags = [CHMTag allTagswithContext:[self managedObjectContext]];
while([menu numberOfItems] != 0)
[menu removeItemAtIndex:0];
if ( !tags || [tags count] == 0)
{
[self addEmptyItemToMenu:menu];
return;
}
for (CHMTag* tag in tags)
{
NSSet * bookmarks = tag.bookmarks;
if ( [bookmarks count] == 0 )
continue;
NSMenuItem *newitem = [[[NSMenuItem alloc] init] autorelease];
[newitem setTitle:tag.tag];
[newitem setEnabled:YES];
NSMenu *newmenu = [[[NSMenu alloc] init] autorelease];
[newmenu setAutoenablesItems:NO];
[newitem setSubmenu:newmenu];
for (CHMBookmark * bm in bookmarks) {
[newmenu addItem:[self createMenuItemForBookmark:bm]];
}
[menu addItem:newitem];
}
if ([menu numberOfItems] == 0)
[self addEmptyItemToMenu:menu];
}
- (void)groupByFilesMenuNeedsUpdate:(NSMenu*)menu
{
NSArray *files = [CHMFile allFileswithContext:[self managedObjectContext]];
while([menu numberOfItems] != 0)
[menu removeItemAtIndex:0];
if ( !files || [files count] == 0)
{
[self addEmptyItemToMenu:menu];
return;
}
for (CHMFile* file in files)
{
NSSet * bookmarks = file.bookmarks;
if ( [bookmarks count] == 0 )
continue;
NSMenuItem *newitem = [[[NSMenuItem alloc] init] autorelease];
[newitem setTitle:file.title];
[newitem setEnabled:YES];
NSMenu *newmenu = [[[NSMenu alloc] init] autorelease];
[newmenu setAutoenablesItems:NO];
[newitem setSubmenu:newmenu];
for (CHMBookmark * bm in bookmarks) {
[newmenu addItem:[self createMenuItemForBookmark:bm]];
}
[menu addItem:newitem];
}
if ([menu numberOfItems] == 0)
[self addEmptyItemToMenu:menu];
}
- (void)menuNeedsUpdate:(NSMenu *)menu
{
NSDocumentController *controller = [NSDocumentController sharedDocumentController];
[[menu itemWithTag:0] setEnabled:(nil != [controller currentDocument])];
if (menu == groupByTagsMenu)
return [self groupByTagsMenuNeedsUpdate:groupByTagsMenu];
else if (menu == groupByFilesMenu)
return [self groupByFilesMenuNeedsUpdate:groupByFilesMenu];
while ([menu numberOfItems] > 0)
{
[menu removeItemAtIndex:0];
}
NSManagedObjectContext *context =[self managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *bookmarkEntity = [NSEntityDescription
entityForName:@"Bookmark" inManagedObjectContext:context];
[request setEntity:bookmarkEntity];
[request setFetchLimit:BOOKMARK_LIMIT];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey:@"createdAt" ascending:NO];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
NSError *error = nil;
NSArray *array = [context executeFetchRequest:request error:&error];
if (array == nil)
{
NSLog(@"Can not fetch file info: %d",error );
return;
}
for (CHMBookmark* bm in array) {
[menu addItem:[self createMenuItemForBookmark:bm]];
}
if ([menu numberOfItems] == 0)
[self addEmptyItemToMenu:menu];
}
- (IBAction)openBookmark:(id)sender
{
NSDocumentController *controller = [NSDocumentController sharedDocumentController];
NSError *error = nil;
CHMBookmark * bm = (CHMBookmark*)[sender representedObject];
NSURL *url = [NSURL fileURLWithPath:bm.file.path];
CHMDocument* doc = [controller openDocumentWithContentsOfURL:url display:YES error:&error];
[doc loadURL:[NSURL URLWithString:bm.url]];
}
# pragma mark NSOutlineView datasource
- (void)setupDataSource
{
if(tocSource)
[tocSource release];
tocSource = [[FetchRequestItem alloc] init];
FetchRequestItem * allItem = [[FetchRequestItem alloc] init];
[allItem setTitle:NSLocalizedString(@"All", @"All")];
[tocSource addChild:allItem];
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *bookmarkDescription = [NSEntityDescription
entityForName:@"Bookmark"
inManagedObjectContext:moc];
FetchRequestItem * tagsItem = [[FetchRequestItem alloc] init];
[tagsItem setTitle:NSLocalizedString(@"Tags", @"Tags")];
[tocSource addChild:tagsItem];
for (CHMTag* tag in [CHMTag allTagswithContext:moc])
{
if ([tag.bookmarks count] == 0)
continue;
FetchRequestItem * tagItem = [[FetchRequestItem alloc] init];
[tagItem setTitle:tag.tag];
NSFetchRequest * request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:bookmarkDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"(ANY tags.tag == %@)", tag.tag];
[request setPredicate:predicate];
[tagItem setRequest:request];
[tagsItem addChild:tagItem];
}
FetchRequestItem * filesItem = [[FetchRequestItem alloc] init];
[filesItem setTitle:NSLocalizedString(@"Files", @"Files")];
[tocSource addChild:filesItem];
for (CHMFile* file in [CHMFile allFileswithContext:moc])
{
if ([file.bookmarks count] == 0)
continue;
FetchRequestItem * fileItem = [[FetchRequestItem alloc] init];
[fileItem setTitle:file.title];
NSFetchRequest * request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:bookmarkDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"(file == %@)", file];
[request setPredicate:predicate];
[fileItem setRequest:request];
[filesItem addChild:fileItem];
}
[tocView reloadData];
}
- (int)outlineView:(NSOutlineView *)outlineView
numberOfChildrenOfItem:(id)item
{
if(!item)
item = tocSource;
return [(FetchRequestItem*)item numberOfChildren];
}
- (BOOL)outlineView:(NSOutlineView *)outlineView
isItemExpandable:(id)item
{
return [item numberOfChildren] > 0;
}
- (id)outlineView:(NSOutlineView *)outlineView
child:(int)theIndex
ofItem:(id)item
{
if (!item)
item = tocSource;
return [item childAtIndex:theIndex];
}
- (id)outlineView:(NSOutlineView *)outlineView
objectValueForTableColumn:(NSTableColumn *)tableColumn
byItem:(id)item
{
return [item title];
}
#pragma mark Bookmark manager window Delegate
- (void)windowWillClose:(NSNotification *)notification
{
NSError *error;
[CHMFile purgeWithContext:[self managedObjectContext]];
[[self managedObjectContext] save:&error];
}
@end