-
Notifications
You must be signed in to change notification settings - Fork 4
/
LHDocument.m
1180 lines (988 loc) · 35.9 KB
/
LHDocument.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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// LHDocument.m
// LastHistory
//
// Created by Frederik Seiffert on 04.10.09.
// Copyright Frederik Seiffert 2009 . All rights reserved.
//
#import "LHDocument.h"
#import "LHCommonMacros.h"
#import "LHAppDelegate.h"
#import "LHUser.h"
#import "LHTrack.h"
#import "LHArtist.h"
#import "LHTrackTag.h"
#import "LHTag.h"
#import "LHHistoryEntry.h"
#import "LHHistoryView.h"
#import "LHHistoryRetrievalOperation.h"
#import "LHWeightingOperation.h"
#import "LHTagRetrievalOperation.h"
#import "LHiTunesLibrary.h"
#import "NSDateFormatter-Extras.h"
#import "NSDate-Extras.h"
#define SEARCH_KEYS [NSArray arrayWithObjects:@"Any", @"Genre", @"Artist", @"Title", @"Album", @"Tags", nil]
#define SEARCH_KEY_MAPPING [NSDictionary dictionaryWithObjectsAndKeys: \
@"track.genre LIKE[cd] %@", @"Genre", \
@"track.artist.name CONTAINS[cd] %@", @"Artist", \
@"track.name CONTAINS[cd] %@", @"Track", \
@"track.album.name CONTAINS[cd] %@", @"Album", \
@"ANY track.trackTags.tag.name LIKE[cd] %@", @"Tags",\
nil]
#define INVERT_KEY @"NOT"
#define PLAYLIST_MAX_TRACKS 50
NSString *LHDocumentWillOpenNotification = @"LHDocumentWillOpenNotification";
NSString *LHDocumentDidOpenNotification = @"LHDocumentDidOpenNotification";
NSString *LHDocumentDidCloseNotification = @"LHDocumentDidCloseNotification";
@interface LHDocument (Player)
- (BOOL)historyEntryIsWithinCurrentEvent:(LHHistoryEntry *)historyEntry;
- (BOOL)loadHistoryEntry:(LHHistoryEntry *)historyEntry;
- (BOOL)loadNextAvailableHistoryEntryFromEntry:(LHHistoryEntry *)historyEntry ascending:(BOOL)ascending;
- (NSArray *)predicatesForEvent:(id <LHEvent>)event;
@end
@implementation LHDocument
@synthesize historyView;
@synthesize operationMode=_operationMode;
@synthesize chartsMode=_chartsMode;
@synthesize playlist=_playlist;
@synthesize currentHistoryEntry=_currentHistoryEntry;
@synthesize currentEvent=_currentEvent;
@synthesize currentSound=_currentSound;
@synthesize currentOperation=_currentOperation;
+ (NSSet *)keyPathsForValuesAffectingHistoryEntriesCount
{
return [NSSet setWithObject:@"historyEntries"];
}
+ (NSSet *)keyPathsForValuesAffectingInfoString
{
return [NSSet setWithObjects:@"historyEntries", @"visibleHistoryEntries", @"historyEntriesCount", nil];
}
- (id)init
{
self = [super init];
if (self != nil) {
[[NSNotificationCenter defaultCenter] postNotificationName:LHDocumentWillOpenNotification object:self];
}
return self;
}
- (id)initWithType:(NSString *)typeName error:(NSError **)outError
{
self = [super initWithType:typeName error:outError];
if (self)
{
// make sure window is showing before calling action
[self performSelector:@selector(loadHistory:) withObject:nil afterDelay:0];
}
return self;
}
- (void)setUsername:(NSString *)username
{
if ([self countForEntity:@"User"] == 0)
{
// create a user
LHUser *user = [LHUser insertInManagedObjectContext:[self managedObjectContext]];
user.name = username;
}
}
- (NSString *)displayName
{
// use user name as default file name if document hasn't been saved yet
if (![self fileURL])
{
LHUser *user = [[self objectsForEntity:@"User"] lastObject];
if (user)
return user.name;
}
return [super displayName];
}
- (NSString *)windowNibName
{
return @"LHDocument";
}
- (void)windowControllerDidLoadNib:(NSWindowController *)windowController
{
[super windowControllerDidLoadNib:windowController];
// setup observers
[self addObserver:self forKeyPath:@"operationMode" options:0 context:NULL];
// setup history view
[historyView windowControllerDidLoad];
[[NSNotificationCenter defaultCenter] postNotificationName:LHDocumentDidOpenNotification object:self];
}
- (void)close
{
[_queue cancelAllOperations];
[self stop:nil];
_firstHistoryEntry = nil;
_lastHistoryEntry = nil;
_cachedHistoryEntries = nil;
_currentHistoryEntry = nil;
_currentEvent = nil;
_queue = nil;
_currentOperation = nil;
[super close];
[[NSNotificationCenter defaultCenter] postNotificationName:LHDocumentDidCloseNotification object:self];
}
- (BOOL)ensureSavedDocumentBeforePerformingAction:(SEL)selector
{
if ([[[[self managedObjectContext] persistentStoreCoordinator] persistentStores] count] == 0) {
[self saveDocumentWithDelegate:self didSaveSelector:@selector(document:didSave:contextInfo:) contextInfo:selector];
return NO;
}
return YES;
}
- (void)document:(NSDocument *)doc didSave:(BOOL)didSave contextInfo:(void *)contextInfo
{
if (didSave) {
[self performSelector:contextInfo withObject:nil afterDelay:0];
} else {
[self close];
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"operationMode"])
{
// setup view according to operation mode
switch (self.operationMode) {
case 0: // Analysis
self.chartsMode = NO;
historyView.showHistoryEntryWeights = NO;
historyView.showReferenceStreams = NO;
[historyView scrollToDate:self.firstHistoryEntry.timestamp];
break;
case 1: // Personal
self.chartsMode = YES;
historyView.showHistoryEntryWeights = YES;
historyView.showReferenceStreams = YES;
[historyView scrollToDate:self.lastHistoryEntry.timestamp];
break;
}
}
}
- (void)runOperation:(LHOperation *)op
{
if (!_queue)
_queue = [[NSOperationQueue alloc] init];
[_queue addOperation:op];
}
- (void)updateOperation:(LHOperation *)op
{
if ([op isExecuting])
{
self.currentOperation = op;
}
else if ([op isFinished])
{
if (![op isCancelled])
{
// save file again so document is in sync with file
NSError *error = nil;
if (![self saveToURL:[self fileURL] ofType:[self fileType] forSaveOperation:NSSaveOperation error:&error])
[self presentError:error];
}
if (op == self.currentOperation)
self.currentOperation = nil;
}
}
// called by LHOperations to merge changes from their context
- (void)mergeChanges:(NSNotification *)notification
{
NSAssert([NSThread mainThread], @"Not on the main thread");
if ([notification object] != [self managedObjectContext]
&& [[[notification object] class] isEqual:[NSManagedObjectContext class]]) // ignore changes from CalManagedObjectContext
{
NSSet *insertedObjects = [[notification userInfo] objectForKey:NSInsertedObjectsKey];
BOOL didInsertHistoryEntries = [[insertedObjects valueForKey:@"class"] containsObject:[LHHistoryEntry class]];
BOOL isFirstHistoryEntry = didInsertHistoryEntries && _firstHistoryEntry == nil;
// inserting the first history entry causes historyEntries to update
// subsequent inserts only update historyEntriesCount
if (isFirstHistoryEntry)
[self willChangeValueForKey:@"historyEntries"];
else if (didInsertHistoryEntries)
[self willChangeValueForKey:@"historyEntriesCount"];
// merge changes from other thread
[[self managedObjectContext] mergeChangesFromContextDidSaveNotification:notification];
if (isFirstHistoryEntry)
[self didChangeValueForKey:@"historyEntries"];
else if (didInsertHistoryEntries)
[self didChangeValueForKey:@"historyEntriesCount"];
// insert history entries
if (!isFirstHistoryEntry && didInsertHistoryEntries) {
_cachedHistoryEntries = nil;
[historyView insertObjectsWithIDs:[insertedObjects valueForKey:@"objectID"]];
}
// update view
NSSet *updatedObjectIDs = [[[notification userInfo] objectForKey:NSUpdatedObjectsKey] valueForKey:@"objectID"];
[historyView updateObjectsWithIDs:updatedObjectIDs];
}
}
- (NSArray *)objectsForEntity:(NSString *)entityName
withPredicate:(NSPredicate *)predicate
fetchLimit:(NSUInteger)fetchLimit
ascending:(BOOL)ascending
inContext:(NSManagedObjectContext *)context
{
NSFetchRequest *request = [NSFetchRequest new];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
[request setEntity:entity];
[request setPredicate:predicate];
[request setFetchLimit:fetchLimit];
// fetch all relationships for history entries
if ([entityName isEqualToString:@"HistoryEntry"])
[request setRelationshipKeyPathsForPrefetching:[NSArray arrayWithObject:@"track.trackTags.tag"]];
// sort depending on entity
NSDictionary *sortKeysByEntityName = [NSDictionary dictionaryWithObjectsAndKeys:
@"timestamp", @"HistoryEntry",
@"count", @"TrackTag", nil];
NSString *sortKey = [sortKeysByEntityName objectForKey:entityName];
if (sortKey) {
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:ascending];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
}
NSError *error = nil;
NSArray *result = [context executeFetchRequest:request error:&error];
if (error)
[self presentError:error];
return result;
}
- (NSArray *)objectsForEntity:(NSString *)entityName
{
return [self objectsForEntity:entityName withPredicate:nil fetchLimit:0 ascending:YES inContext:[self managedObjectContext]];
}
- (NSUInteger)countForEntity:(NSString *)entityName
withPredicate:(NSPredicate *)predicate
inContext:(NSManagedObjectContext *)context
{
NSFetchRequest *request = [NSFetchRequest new];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
[request setEntity:entity];
[request setPredicate:predicate];
NSError *error;
return [context countForFetchRequest:request error:&error];
}
- (NSUInteger)countForEntity:(NSString *)entityName
{
return [self countForEntity:entityName withPredicate:nil inContext:[self managedObjectContext]];
}
- (NSString *)infoString
{
NSUInteger historyEntriesCount = self.historyEntriesCount;
NSUInteger tracksCount = self.tracksCount;
if (_hiddenHistoryEntriesCount > 0)
{
NSUInteger visibleHistoryEntriesCount = historyEntriesCount - _hiddenHistoryEntriesCount;
NSUInteger visibleTracksCount = tracksCount - _hiddenTracksCount;
float historyEntriesPercent = historyEntriesCount > 0 ? (float)visibleHistoryEntriesCount / historyEntriesCount : 0.0;
float tracksPercent = tracksCount > 0 ? (float)visibleTracksCount / tracksCount : 0.0;
return [NSString stringWithFormat:@"%u of %u history entries (%.2f%%), %u of %u tracks (%.2f%%)",
visibleHistoryEntriesCount, historyEntriesCount, historyEntriesPercent*100,
visibleTracksCount, tracksCount, tracksPercent*100];
}
else
{
return [NSString stringWithFormat:@"%u history entries, %u tracks",
historyEntriesCount, tracksCount];
}
}
- (NSArray *)tracks
{
return [self objectsForEntity:@"Track"];
}
- (NSUInteger)tracksCount
{
return [self countForEntity:@"Track"];
}
- (NSArray *)historyEntries
{
if (!_cachedHistoryEntries)
{
// result includes all relationships and can take up to multiple seconds to fetch
LHLog(@"Fetching history entries...");
_cachedHistoryEntries = [self objectsForEntity:@"HistoryEntry"];
_hiddenHistoryEntriesCount = 0;
_hiddenTracksCount = 0;
}
return _cachedHistoryEntries;
}
- (NSUInteger)historyEntriesCount
{
return [self countForEntity:@"HistoryEntry"];
}
- (NSArray *)visibleHistoryEntries
{
NSLog(@"visibleHistoryEntries");
// this value is just for key-value observing when the "hidden" property of some history entries changes
return nil;
}
- (LHHistoryEntry *)firstHistoryEntry
{
if (!_firstHistoryEntry)
_firstHistoryEntry = [[self objectsForEntity:@"HistoryEntry" withPredicate:nil fetchLimit:1 ascending:YES inContext:[self managedObjectContext]] lastObject];
return _firstHistoryEntry;
}
- (LHHistoryEntry *)lastHistoryEntry
{
if (!_lastHistoryEntry)
_lastHistoryEntry = [[self objectsForEntity:@"HistoryEntry" withPredicate:nil fetchLimit:1 ascending:NO inContext:[self managedObjectContext]] lastObject];
return _lastHistoryEntry;
}
#pragma mark -
#pragma mark Searching
- (NSArray *)tokenField:(NSTokenField *)tokenField completionsForSubstring:(NSString *)substring indexOfToken:(NSInteger)tokenIndex indexOfSelectedItem:(NSInteger *)selectedIndex
{
NSMutableArray *result = [NSMutableArray arrayWithCapacity:5];
NSPredicate *prefixPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[cd] %@", substring];
// check genres
[result addObject:[[LHTrack genres] filteredArrayUsingPredicate:prefixPredicate]];
// check weekdays/months
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setLocale:[NSLocale currentLocale]];
[result addObject:[[formatter standaloneWeekdaySymbols] filteredArrayUsingPredicate:prefixPredicate]];
[result addObject:[[formatter standaloneMonthSymbols] filteredArrayUsingPredicate:prefixPredicate]];
// check tags/artists
NSPredicate *entityPredicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", substring];
[result addObject:[[self objectsForEntity:@"Tag" withPredicate:entityPredicate fetchLimit:10 ascending:YES inContext:[self managedObjectContext]] valueForKey:@"name"]];
[result addObject:[[self objectsForEntity:@"Artist" withPredicate:entityPredicate fetchLimit:10 ascending:YES inContext:[self managedObjectContext]] valueForKey:@"name"]];
return [result valueForKeyPath:@"@distinctUnionOfArrays.self"];
}
- (id)tokenField:(NSTokenField *)tokenField representedObjectForEditingString:(NSString *)token
{
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setLocale:[NSLocale currentLocale]];
NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity:5];
if ([token hasPrefix:@"-"]) {
// minus prefix => NOT
token = [[token substringFromIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
[result setObject:[NSNumber numberWithBool:YES] forKey:@"invert"];
}
[result setObject:token forKey:@"token"];
[result setObject:[SEARCH_KEYS objectAtIndex:0] forKey:@"searchKey"]; // default search key: Any
// range specified?
NSString *firstToken = token, *lastToken = token;
NSArray *rangeTokens = [token componentsSeparatedByString:@"-"];
if ([rangeTokens count] == 2) {
firstToken = [rangeTokens objectAtIndex:0];
lastToken = [rangeTokens objectAtIndex:1];
}
NSInteger start, end;
if ([[NSScanner scannerWithString:firstToken] scanInteger:&start]
&& [[NSScanner scannerWithString:lastToken] scanInteger:&end]
&& start >= 0 && end >= 0 && end >= start)
{
[result setObject:[NSNumber numberWithInteger:start] forKey:@"start"];
[result setObject:[NSNumber numberWithInteger:end] forKey:@"end"];
// check year
NSInteger startYear = [[formatter twoDigitStartDate] year];
NSInteger endYear = [[NSDate date] year]+1;
if (start >= startYear && start <= endYear && end >= startYear && end <= endYear)
{
[result setObject:@"year" forKey:@"key"];
return result;
}
// check time
if (start <= 24 && end <= 24)
{
[result setObject:@"hour" forKey:@"key"];
return result;
}
}
// check weekday
start = [formatter weekdayForString:firstToken];
end = [formatter weekdayForString:lastToken];
if (start != NSNotFound && end != NSNotFound)
{
[result setObject:[NSNumber numberWithInteger:start] forKey:@"start"];
[result setObject:[NSNumber numberWithInteger:end] forKey:@"end"];
[result setObject:@"weekday" forKey:@"key"];
[result setObject:[NSNumber numberWithInteger:7] forKey:@"ordinality"];
return result;
}
// check month
start = [formatter monthForString:firstToken];
end = [formatter monthForString:lastToken];
if (start != NSNotFound && end != NSNotFound)
{
[result setObject:[NSNumber numberWithInteger:start] forKey:@"start"];
[result setObject:[NSNumber numberWithInteger:end] forKey:@"end"];
[result setObject:@"month" forKey:@"key"];
[result setObject:[NSNumber numberWithInteger:12] forKey:@"ordinality"];
return result;
}
return result;
}
- (NSString *)tokenField:(NSTokenField *)tokenField displayStringForRepresentedObject:(id)token
{
NSString *result = nil;
if ([token objectForKey:@"start"] && [token objectForKey:@"end"])
{
// range token
NSString *key = [token objectForKey:@"key"];
NSInteger start = [[token objectForKey:@"start"] integerValue];
NSInteger end = [[token objectForKey:@"end"] integerValue];
if ([token objectForKey:@"ordinality"])
{
// weekday or month range
NSDateFormatter *formatter = [NSDateFormatter new];
SEL symbolsSelector = NSSelectorFromString([NSString stringWithFormat:@"shortStandalone%@Symbols", [key capitalizedString]]);
if ([formatter respondsToSelector:symbolsSelector])
{
NSArray *symbols = [formatter performSelector:symbolsSelector];
if (start != end)
result = [NSString stringWithFormat:@"%@-%@", [symbols objectAtIndex:start-1], [symbols objectAtIndex:end-1]];
else
result = [symbols objectAtIndex:start-1];
}
}
else
{
// number (hour or year) range
NSDictionary *suffixes = [NSDictionary dictionaryWithObjectsAndKeys:@"h", @"hour", @"", @"year", nil];
NSString *suffix = [suffixes objectForKey:key];
if (!suffix)
suffix = @"";
if (start != end)
result = [NSString stringWithFormat:@"%d%@-%d%@", start, suffix, end, suffix];
else
result = [NSString stringWithFormat:@"%d%@", start, suffix];
}
}
if (!result)
result = [token objectForKey:@"token"];
NSString *searchKey = [token objectForKey:@"searchKey"];
if (searchKey && ![searchKey isEqualToString:[SEARCH_KEYS objectAtIndex:0]])
result = [NSString stringWithFormat:@"%@[%@]", result, [searchKey uppercaseString]];
if ([[token objectForKey:@"invert"] boolValue])
result = [NSString stringWithFormat:@"NOT %@", result];
[tokenField performSelector:@selector(setNeedsDisplay) withObject:nil afterDelay:0];
return result;
}
- (NSString *)tokenField:(NSTokenField *)tokenField editingStringForRepresentedObject:(id)token
{
return [token objectForKey:@"token"];
}
- (BOOL)tokenField:(NSTokenField *)tokenField hasMenuForRepresentedObject:(id)token
{
return YES;
}
- (NSMenu *)tokenField:(NSTokenField *)tokenField menuForRepresentedObject:(id)token
{
if (!token)
return nil;
NSMenu *menu = [NSMenu new];
[menu setAutoenablesItems:NO];
if (!([token objectForKey:@"start"] && [token objectForKey:@"end"]))
{
// add search key items
NSString *searchKey = [token objectForKey:@"searchKey"];
NSArray *searchKeys = SEARCH_KEYS;
for (NSString *key in searchKeys)
{
NSMenuItem *item = [menu addItemWithTitle:key action:@selector(tokenFieldMenuAction:) keyEquivalent:@""];
[item setTarget:self];
[item setRepresentedObject:token];
if ([key isEqualToString:searchKey]) {
[item setState:NSOnState];
} else if ([key isEqualToString:@"Genre"] && ![[LHTrack genres] containsObject:[[token objectForKey:@"token"] lowercaseString]]) {
// disable Genre item if token is not a valid genre
[item setEnabled:NO];
}
if ([key isEqualToString:[searchKeys objectAtIndex:0]])
[menu addItem:[NSMenuItem separatorItem]];
}
[menu addItem:[NSMenuItem separatorItem]];
}
// add NOT item
NSMenuItem *item = [menu addItemWithTitle:INVERT_KEY action:@selector(tokenFieldMenuAction:) keyEquivalent:@""];
[item setTarget:self];
[item setRepresentedObject:token];
if ([[token objectForKey:@"invert"] boolValue])
[item setState:NSOnState];
return menu;
}
- (void)tokenFieldMenuAction:(id)sender
{
NSMenuItem *item = sender;
NSMutableDictionary *token = [item representedObject];
if ([[item title] isEqualToString:INVERT_KEY])
{
[token setObject:[NSNumber numberWithBool:![item state]] forKey:@"invert"];
}
else
{
[token setObject:[item title] forKey:@"searchKey"];
}
// this updates the display string for the tokens
[[searchField window] makeFirstResponder:searchField];
}
- (NSPredicate *)predicateForToken:(NSDictionary *)token format:(NSString *)format, ...
{
va_list ap;
va_start(ap, format);
NSPredicate *predicate = [NSPredicate predicateWithFormat:format arguments:ap];
va_end(ap);
if ([[token objectForKey:@"invert"] boolValue])
predicate = [NSCompoundPredicate notPredicateWithSubpredicate:predicate];
return predicate;
}
- (IBAction)updateFilter:(id)sender
{
NSMutableArray *orPredicates = [NSMutableArray array];
NSMutableArray *andPredicates = [NSMutableArray array];
NSArray *searchTokens = [searchField objectValue];
for (NSDictionary *token in searchTokens)
{
NSString *key = [token objectForKey:@"key"];
NSNumber *start = [token objectForKey:@"start"];
NSNumber *end = [token objectForKey:@"end"];
if (key && start && end)
{
if ([token objectForKey:@"ordinality"])
{
// search discrete value range (weekday, month)
NSInteger ordinality = [[token objectForKey:@"ordinality"] integerValue];
NSMutableArray *subpredicates = [NSMutableArray arrayWithCapacity:ordinality];
NSUInteger index = [start integerValue]-1;
while (1) {
NSString *format = [NSString stringWithFormat:@"%@ = %%d", key];
[subpredicates addObject:[NSPredicate predicateWithFormat:format, index+1]];
if (index+1 == [end integerValue])
break;
index = ++index % ordinality;
}
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subpredicates];
if ([[token objectForKey:@"invert"] boolValue])
predicate = [NSCompoundPredicate notPredicateWithSubpredicate:predicate];
[orPredicates addObject:predicate];
}
else
{
// search range
NSString *format = [NSString stringWithFormat:@"%@ >= %%d AND %@ <= %%d", key, key];
NSPredicate *p = [self predicateForToken:token format:format, [start intValue], [end intValue]];
[orPredicates addObject:p];
}
}
else
{
// search title/artist
NSDictionary *searchKeyMapping = SEARCH_KEY_MAPPING;
NSString *searchExpression = [searchKeyMapping objectForKey:[token objectForKey:@"searchKey"]];
NSString *searchString = [token objectForKey:@"token"];
if (searchExpression) {
// search selected key
NSPredicate *p = [self predicateForToken:token format:searchExpression, searchString];
[andPredicates addObject:p];
} else {
// search all keys
NSMutableArray *subpredicates = [NSMutableArray arrayWithCapacity:[searchKeyMapping count]];
for (NSString *key in SEARCH_KEYS) {
searchExpression = [searchKeyMapping objectForKey:key];
if (searchExpression)
[subpredicates addObject:[NSPredicate predicateWithFormat:searchExpression, searchString]];
}
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subpredicates];
if ([[token objectForKey:@"invert"] boolValue])
predicate = [NSCompoundPredicate notPredicateWithSubpredicate:predicate];
[andPredicates addObject:predicate];
}
}
}
// integrate or-parts into predicate strings
if ([orPredicates count]) {
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:orPredicates];
[andPredicates insertObject:predicate atIndex:0];
}
NSPredicate *filter = nil;
if ([andPredicates count]) {
filter = [NSCompoundPredicate andPredicateWithSubpredicates:andPredicates];
NSLog(@"filter: %@", filter);
}
[self willChangeValueForKey:@"visibleHistoryEntries"];
// apply filter
_hiddenHistoryEntriesCount = 0;
for (LHHistoryEntry *historyEntry in self.historyEntries) {
BOOL hidden = filter ? ![filter evaluateWithObject:historyEntry] : NO;
historyEntry.hidden = hidden;
if (hidden)
_hiddenHistoryEntriesCount++;
}
// calculate number of visible tracks
NSPredicate *hiddenTracksPredicate = [NSPredicate predicateWithFormat:@"ANY historyEntries.hidden = YES"];
_hiddenTracksCount = [[self.tracks filteredArrayUsingPredicate:hiddenTracksPredicate] count];
[self didChangeValueForKey:@"visibleHistoryEntries"];
// un-focus search field
[[searchField window] makeFirstResponder:nil];
}
#pragma mark -
#pragma mark Actions
- (void)performFindPanelAction:(id)sender
{
[[searchField window] makeFirstResponder:searchField];
}
- (IBAction)toggleFullScreenMode:(id)sender
{
if ([historyView isInFullScreenMode])
[historyView exitFullScreenModeWithOptions:nil];
else
[historyView enterFullScreenMode:[NSScreen mainScreen]
withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
nil]];
}
- (IBAction)showTrackIniTunes:(id)sender
{
LHTrack *track = self.currentHistoryEntry.track;
LHiTunesLibrary *library = [LHiTunesLibrary defaultLibrary];
NSDictionary *iTunesTrackDict = [library trackForTrack:track.name artist:track.artist.name];
[library revealTrack:iTunesTrackDict];
}
- (IBAction)createPlaylistIniTunes:(id)sender
{
if ([self.playlist count] > 0)
{
[NSApp beginSheet:playlistNameSheet
modalForWindow:[self windowForSheet]
modalDelegate:self
didEndSelector:nil
contextInfo:nil];
}
}
- (IBAction)closePlaylistNameSheet:(id)sender
{
if ([sender tag] == 1)
{
NSString *playlistName = [playlistNameField stringValue];
if ([playlistName length] > 0)
{
LHiTunesLibrary *library = [LHiTunesLibrary defaultLibrary];
NSMutableArray *playlistTracks = [NSMutableArray arrayWithCapacity:[self.playlist count]];
for (LHTrack *track in self.playlist)
{
NSDictionary *iTunesTrackDict = [library trackForTrack:track.name artist:track.artist.name];
if (iTunesTrackDict)
[playlistTracks addObject:iTunesTrackDict];
}
[library createPlaylist:playlistName withTracks:playlistTracks];
}
else
{
NSRunAlertPanel(@"Invalid playlist name", @"Please enter a valid playlist name", nil, nil, nil);
return;
}
}
[NSApp endSheet:playlistNameSheet];
[playlistNameSheet orderOut:nil];
}
- (IBAction)stop:(id)sender
{
if (self.currentHistoryEntry)
{
[self.currentSound stop];
self.currentSound = nil;
self.currentHistoryEntry = nil;
self.currentEvent = nil;
}
}
- (IBAction)pause:(id)sender
{
if (_currentSoundIsPaused)
_currentSoundIsPaused = ![self.currentSound resume];
else
_currentSoundIsPaused = [self.currentSound pause];
}
- (IBAction)skipBackwards:(id)sender
{
[self loadNextAvailableHistoryEntryFromEntry:self.currentHistoryEntry ascending:NO];
}
- (IBAction)skipForward:(id)sender
{
[self loadNextAvailableHistoryEntryFromEntry:self.currentHistoryEntry ascending:YES];
}
- (BOOL)playHistoryEntry:(LHHistoryEntry *)historyEntry
{
// reset current event if track is not within
if (![self historyEntryIsWithinCurrentEvent:historyEntry])
self.currentEvent = nil;
self.playlist = nil; // reset playlist
return [self loadHistoryEntry:historyEntry];
}
- (BOOL)playHistoryEntriesForEvent:(id <LHEvent>)event
{
self.currentEvent = event;
self.playlist = nil; // reset playlist
return [self loadNextAvailableHistoryEntryFromEntry:nil ascending:YES];
}
- (NSUInteger)numberOfHistoryEntriesForEvent:(id <LHEvent>)event
{
NSArray *subpredicates = [self predicatesForEvent:event];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
return [self countForEntity:@"HistoryEntry" withPredicate:predicate inContext:[self managedObjectContext]];
}
#pragma mark -
#pragma mark History Loading
- (void)loadHistoryForUser:(NSString *)username
{
LHHistoryRetrievalOperation *operation = [[LHHistoryRetrievalOperation alloc] initWithDocument:self
andUsername:username];
[self runOperation:operation];
// add weighting and tag retrieval operations
LHWeightingOperation *weightingOperation = [[LHWeightingOperation alloc] initWithDocument:self];
[weightingOperation addDependency:operation];
[self runOperation:weightingOperation];
LHTagRetrievalOperation *tagRetrievalOperation = [[LHTagRetrievalOperation alloc] initWithDocument:self];
[tagRetrievalOperation addDependency:weightingOperation];
[self runOperation:tagRetrievalOperation];
}
- (IBAction)loadHistory:(id)sender
{
if (![self ensureSavedDocumentBeforePerformingAction:@selector(loadHistory:)])
return;
LHUser *user = [[self objectsForEntity:@"User"] lastObject];
if (user.name.length > 0) {
[self loadHistoryForUser:user.name];
} else {
[NSApp beginSheet:usernameSheet
modalForWindow:[self windowForSheet]
modalDelegate:self
didEndSelector:nil
contextInfo:nil];
}
}
- (IBAction)closeUsernameSheet:(id)sender
{
if ([sender tag] == 1)
{
NSString *username = [usernameField stringValue];
if ([username length] > 0) {
[self loadHistoryForUser:username];
} else {
NSRunAlertPanel(@"Invalid username", @"Please enter a valid username", nil, nil, nil);
return;
}
}
[NSApp endSheet:usernameSheet];
[usernameSheet orderOut:nil];
}
#pragma mark -
#pragma mark Last.fm Tag Loading
- (IBAction)retrieveTags:(id)sender
{
if (![self ensureSavedDocumentBeforePerformingAction:@selector(retrieveTags:)])
return;
LHTagRetrievalOperation *tagRetrievalOperation = [[LHTagRetrievalOperation alloc] initWithDocument:self];
[self runOperation:tagRetrievalOperation];
}
- (IBAction)showTopTags:(id)sender
{
NSArray *tags = [self objectsForEntity:@"Tag" withPredicate:nil fetchLimit:0 ascending:NO inContext:[self managedObjectContext]];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"countSum" ascending:NO];
NSArray *sortedTags = [tags sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
for (LHTag *tag in [sortedTags subarrayWithRange:NSMakeRange(0, 100)])
{
NSLog(@"%u: %@", tag.countSum, tag.name);
}
}
@end
#pragma mark -
@implementation LHDocument (Player)
- (BOOL)historyEntryIsWithinCurrentEvent:(LHHistoryEntry *)historyEntry
{
BOOL withinDate = [self.currentEvent.eventStart compare:historyEntry.timestamp] == NSOrderedAscending && [self.currentEvent.eventEnd compare:historyEntry.timestamp] == NSOrderedDescending;
BOOL withinTime = self.currentEvent.eventStartTime <= historyEntry.timeValue && self.currentEvent.eventEndTime >= historyEntry.timeValue;
if (!self.currentEvent)
return YES;
else if (self.currentEvent.eventStart && self.currentEvent.eventEnd && self.currentEvent.eventStartTime != LH_EVENT_TIME_UNDEFINED && self.currentEvent.eventEndTime != LH_EVENT_TIME_UNDEFINED)
return withinDate && withinTime;
else if (self.currentEvent.eventStart && self.currentEvent.eventEnd)
return withinDate;
else if (self.currentEvent.eventStartTime && self.currentEvent.eventEndTime)
return withinTime;
else
return NO;
}
- (BOOL)loadHistoryEntry:(LHHistoryEntry *)historyEntry
{
// play track from iTunes
LHTrack *track = historyEntry.track;
NSDictionary *iTunesTrack = [[LHiTunesLibrary defaultLibrary] trackForTrack:track.name
artist:track.artist.name];
if (iTunesTrack)
{
if ([[iTunesTrack objectForKey:@"Protected"] boolValue]) {
// skip DRM-protected songs
return NO;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *location = [NSURL URLWithString:[iTunesTrack objectForKey:@"Location"]];
if (location && [fileManager fileExistsAtPath:[location path]])
{
NSSound *sound = [[NSSound alloc] initWithContentsOfURL:location byReference:YES];
if (sound) {
[self.currentSound stop];
NSString *artist = [iTunesTrack objectForKey:@"Artist"];
NSString *name = [iTunesTrack objectForKey:@"Name"];
[sound setName:(artist && name) ? [NSString stringWithFormat:@"%@ - %@", artist, name] : name];
[sound setDelegate:self];
[sound play];
self.currentHistoryEntry = historyEntry;
self.currentSound = sound;
_currentSoundIsPaused = NO;
} else {
NSLog(@"Error: Failed to load '%@'.", location);