-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPoolViewController.m
More file actions
1271 lines (1014 loc) · 40.5 KB
/
PoolViewController.m
File metadata and controls
1271 lines (1014 loc) · 40.5 KB
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
//
// PoolViewController.m
// Choreographer
//
// Created by Philippe Kocher on 26.06.09.
// Copyright 2011 Zurich University of the Arts. All rights reserved.
//
#import "CHGlobals.h"
#import "CHProjectDocument.h"
#import "AudioItem.h"
#import "AudioFile.h"
#import "AudioRegion.h"
#import "PoolViewController.h"
#import "PoolViews.h"
#import "TrajectoryInspectorWindowController.h"
#import "SettingsMenu.h"
#import "ImageAndTextCell.h"
#import "Path.h"
#import "SpatDIF.h"
#import "AudioEngine.h"
@implementation PoolViewController
@synthesize newTrajectoryName;
+ (PoolViewController *)poolViewControllerForDocument:(NSPersistentDocument *)document
{
PoolViewController *instance = [[[self alloc] initWithNibName:@"Pool" bundle:nil] autorelease];
[instance setValue:document forKey:@"document"];
[instance setValue:[[document valueForKey:@"projectSettings"] retain] forKey:@"projectSettings"];
return instance;
}
- (void) dealloc
{
NSLog(@"PoolViewController: dealloc");
[projectSettings release];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (void)awakeFromNib
{
// get stored settings
[tabControl setSelectedSegment:[[projectSettings valueForKey:@"poolSelectedTab"] intValue]];
[tabView selectTabViewItemAtIndex:[[projectSettings valueForKey:@"poolSelectedTab"] intValue]];
// make userOutlineView and tableView appear with gradient selection, and behave like the Finder, iTunes, etc.
[userOutlineView setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleSourceList];
[audioItemTableView setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleSourceList];
[trajectoryTableView setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleSourceList];
// set background color
NSColor *background = [NSColor colorWithCalibratedRed:0.8 green:0.8 blue:0.8 alpha:1.0];
[userOutlineView setBackgroundColor:background];
[audioItemTableView setBackgroundColor:background];
[trajectoryTableView setBackgroundColor:background];
[[audioItemTableView tableColumnWithIdentifier: @"audioItem"] setDataCell: [[[ImageAndTextCell alloc] init] autorelease]];
[[trajectoryTableView tableColumnWithIdentifier: @"trajectoryItem"] setDataCell: [[[ImageAndTextCell alloc] init] autorelease]];
// initialise context menu
[dropOrderMenu setModel:projectSettings key:@"poolDropOrder"];
// init array controllers
[trajectoryArrayController setFilterPredicate:[NSPredicate predicateWithFormat:@"type == %@", CHTrajectoryType]];
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease];
[trajectoryArrayController setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[audioItemArrayController setFilterPredicate:[NSPredicate predicateWithFormat:@"type == %@", CHAudioItemType]];
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease];
[audioItemArrayController setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
// register for drag and drop
[userOutlineView registerForDraggedTypes:[NSArray arrayWithObjects:CHAudioItemType, CHTrajectoryType, CHFolderType, NSFilenamesPboardType, nil]];
[audioItemTableView registerForDraggedTypes:[NSArray arrayWithObjects:CHAudioItemType, NSFilenamesPboardType, nil]];
[trajectoryTableView registerForDraggedTypes:[NSArray arrayWithObjects: CHTrajectoryType, nil]];
// double click behaviour
[userOutlineView setDoubleAction:@selector(showTrajectoryInspector:)];
[userOutlineView setTarget:self];
[audioItemTableView setDoubleAction:@selector(showTrajectoryInspector:)];
[audioItemTableView setTarget:self];
[trajectoryTableView setDoubleAction:@selector(showTrajectoryInspector:)];
[trajectoryTableView setTarget:self];
// register for notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(refresh:)
name:NSManagedObjectContextObjectsDidChangeNotification object:nil];
}
#pragma mark -
#pragma mark IB actions
// -----------------------------------------------------------
- (IBAction)poolAddFolder:(id)sender
{
NSArray *selected = [treeController selectedObjects];
NSManagedObject *parentNode = nil;
if([selected count] != 0)
{
NSManagedObject *selectedNode = [[treeController selectedObjects] objectAtIndex:0];
if(![selectedNode valueForKey:@"isLeaf"])
{
parentNode = selectedNode;
}
else if([selectedNode valueForKey:@"parent"])
{
parentNode = [selectedNode valueForKey:@"parent"];
}
}
NSManagedObject *newGroup = [NSEntityDescription insertNewObjectForEntityForName:@"Node" inManagedObjectContext:[document managedObjectContext]];
[newGroup setValue:parentNode forKey:@"parent"];
[newGroup setValue:@"Untitled Folder" forKey:@"name"];
[newGroup setValue:CHFolderType forKey:@"type"];
[newGroup setValue:[NSNumber numberWithBool:NO] forKey:@"isLeaf"];
}
- (IBAction)importAudioFiles:(id)sender
{
// choose audio file in an open panel
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel setTreatsFilePackagesAsDirectories:NO];
[openPanel setAllowsMultipleSelection:YES];
[openPanel setCanChooseDirectories:NO];
[openPanel setCanChooseFiles:YES];
[openPanel setAllowedFileTypes:[AudioFile allowedFileTypes]];
[openPanel beginSheetModalForWindow:[document windowForSheet] completionHandler:^(NSInteger result)
{
if (result == NSOKButton)
{
[openPanel orderOut:self]; // close panel before we might present an error
for(NSURL *url in [openPanel URLs])
{
[self importFile:url];
}
}
}];
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 2) // trajectory view
{
[tabControl setSelectedSegment:1];
[tabView selectTabViewItemAtIndex:1];
}
}
- (IBAction)newTrajectory:(id)sender
{
regionsForNewTrajectoryItem = nil;
[self showSheetForNewTrajectoryItem:@"untitled"];
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 1) // audio items view
{
[tabControl setSelectedSegment:2];
[tabView selectTabViewItemAtIndex:2];
}
// [userOutlineView deselectAll:nil];
// [audioItemTableView deselectAll:nil];
// [trajectoryTableView deselectAll:nil];
// todo: select new trajectory
}
- (IBAction)SpatDifImportTrajectories:(id)sender
{
// choose XML file in an open panel
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel setTreatsFilePackagesAsDirectories:NO];
[openPanel setAllowsMultipleSelection:YES];
[openPanel setCanChooseDirectories:NO];
[openPanel setCanChooseFiles:YES];
[openPanel setAllowedFileTypes:[NSArray arrayWithObjects:@"xml",nil]];
[openPanel beginSheetModalForWindow:[document windowForSheet] completionHandler:^(NSInteger result)
{
if (result == NSOKButton)
{
[openPanel orderOut:self]; // close panel before we might present an error
for(NSURL *url in [openPanel URLs])
{
[self importSpatDIF:url];
}
}
}];
}
- (IBAction)SpatDifExportTrajectories:(id)sender
{
NSArray *selectedTrajectories = nil;
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 0) selectedTrajectories = [treeController selectedObjects];
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 2) selectedTrajectories = [trajectoryArrayController selectedObjects];
NSSavePanel *savePanel = [NSSavePanel savePanel];
[savePanel setAllowedFileTypes:[NSArray arrayWithObjects:@"xml",nil]];
[savePanel setNameFieldStringValue:@"Trajectories.xml"];
[savePanel setPrompt:@"Save"];
[savePanel setExtensionHidden:NO];
[savePanel beginSheetModalForWindow:[document windowForSheet] completionHandler:^(NSInteger result)
{
if (result == NSOKButton)
{
[savePanel orderOut:self];
// write selected trajectories to xml formatted file
SpatDIF *spatDif = [[[SpatDIF alloc] init] autorelease];
[spatDif addTrajectories:selectedTrajectories];
[spatDif writeXmlToURL:[savePanel URL]];
}
}];
}
- (IBAction)deleteSelected:(id)sender
{
NSEnumerator *nodeEnumerator;
id node;
BOOL dirty = NO;
switch ([[projectSettings valueForKey:@"poolSelectedTab"] intValue])
{
case 0: // user view
nodeEnumerator = [[treeController selectedObjects] objectEnumerator];
break;
case 1: // audio items view
nodeEnumerator = [[audioItemArrayController selectedObjects] objectEnumerator];
break;
case 2: // trajectory view
nodeEnumerator = [[trajectoryArrayController selectedObjects] objectEnumerator];
break;
default:
nodeEnumerator = nil;
break;
}
while ((node = [nodeEnumerator nextObject]))
{
if ([self recursivelyDeleteNode:node])
dirty = YES;
}
if(dirty)
[[[document managedObjectContext] undoManager] setActionName:@"delete"];
}
- (IBAction)renameSelected:(id)sender
{
}
// tab to change between views
- (IBAction)poolTab:(id)sender
{
// update preferences
[projectSettings setValue:[NSNumber numberWithInt:[sender selectedSegment]] forKey:@"poolSelectedTab"];
[tabView selectTabViewItemAtIndex:[sender selectedSegment]];
}
- (IBAction)showTrajectoryInspector:(id)sender
{
id item = nil;
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 0) // user tab
{
//[treeController setSelectionIndexPath:[NSIndexPath indexPathWithIndex:[sender clickedRow]]];
item = [[[treeController selectedObjects] objectAtIndex:0] valueForKey:@"item"];
if(![item isKindOfClass:[TrajectoryItem class]])
{
item = nil;
}
}
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 2) // trajectory tab
{
item = [[[trajectoryArrayController selectedObjects] objectAtIndex:0] valueForKey:@"item"];
}
if(item) [[TrajectoryInspectorWindowController sharedTrajectoryInspectorWindowController] showInspectorModalForWindow:[[self view] window] trajectoryItem:item];
}
- (BOOL)validateMenuItem:(NSMenuItem *)item
{
if ([item action] == @selector(poolAddFolder:) && [[projectSettings valueForKey:@"poolSelectedTab"] intValue] != 0)
return NO;
else if ([item action] == @selector(showTrajectoryInspector:) ||
[item action] == @selector(SpatDifExportTrajectories:))
{
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 0 && [[treeController selectedObjects] count] == 0)
return NO;
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 1)
return NO;
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 2 && [[trajectoryArrayController selectedObjects] count] == 0)
return NO;
}
else if ([item action] == @selector(deleteSelected:))
{
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 0 && [[treeController selectedObjects] count] == 0)
return NO;
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 1 && [[audioItemArrayController selectedObjects] count] == 0)
return NO;
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 2 && [[trajectoryArrayController selectedObjects] count] == 0)
return NO;
}
return YES;
}
#pragma mark -
#pragma mark actions
// -----------------------------------------------------------
- (AudioItem *)importFile:(NSURL *)absoluteFilePath
{
// take the selectetd group node (if any) as parent node
NSManagedObject *parentNode = nil;
if([[treeController selectedObjects] count])
{
NSManagedObject *selectedNode = [[treeController selectedObjects] objectAtIndex:0];
if([selectedNode valueForKey:@"isLeaf"] == [NSNumber numberWithBool:NO])
{
parentNode = selectedNode;
}
}
NSLog(@"path: %@", absoluteFilePath);
// get file path
NSString *relativeFilePath = [Path path:absoluteFilePath relativeTo:[document fileURL]];
NSString *filePath = [[NSURL URLWithString:relativeFilePath relativeToURL:[document fileURL]] path];
// NSLog(@"**document: %@", [document fileURL]);
// NSLog(@"**file: %@", absoluteFilePath);
// NSLog(@"**relative: %@", relativeFilePath);
// NSLog(@"**absolute: %@", filePath);
// check if this audioFile already exists in data model
NSManagedObjectContext *context = [document managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"AudioItem" inManagedObjectContext:context];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
[request setPredicate:[NSPredicate predicateWithFormat:@"(isOriginal == YES) AND (audioFile.relativeFilePath == %@)", relativeFilePath]];
NSError *error;
NSArray *audioItemsArray = [context executeFetchRequest:request error:&error];
if([audioItemsArray count]) // duplicate
{
return [audioItemsArray objectAtIndex:0];
}
// insert audio file, node and audio item
AudioFile *newAudioFile = [NSEntityDescription insertNewObjectForEntityForName:@"AudioFile"
inManagedObjectContext:context];
NSManagedObject *newNode = [NSEntityDescription insertNewObjectForEntityForName:@"Node"
inManagedObjectContext:context];
AudioItem *newAudioItem = [NSEntityDescription insertNewObjectForEntityForName:@"AudioItem"
inManagedObjectContext:context];
// get filename from path
NSString *theName = [filePath lastPathComponent];
// set attributes and relationships
[newAudioFile setValue:relativeFilePath forKey:@"relativeFilePath"];
[newAudioFile setValue:[NSSet setWithObject:newAudioItem] forKey:@"audioItems"];
[newNode setValue:parentNode forKey:@"parent"];
[newNode setValue:[NSNumber numberWithBool:YES] forKey:@"isLeaf"];
[newNode setValue:theName forKey:@"name"];
[newNode setValue:CHAudioItemType forKey:@"type"];
[newNode setValue:newAudioItem forKey:@"item"];
[newAudioItem setValue:newNode forKey:@"node"];
[newAudioItem setValue:newAudioFile forKey:@"audioFile"];
[newAudioItem setValue:[NSNumber numberWithBool:YES] forKey:@"isOriginal"];
if(![newAudioFile openAudioFile])
{
// if opening the audio file wasn't successful delete the objects
[context deleteObject:newAudioFile];
[context deleteObject:newNode];
[context deleteObject:newAudioItem];
}
else
{
// for newly imported audio files:
// audio item has original length
[newAudioItem setValue:[NSNumber numberWithLongLong:[AudioFile durationOfAudioFileAtPath:filePath]] forKey:@"duration"];
// expand parent node
// [userOutlineView expandItem:parentNode];
// select the new item
//[userOutlineView adaptSelection:[NSSet setWithObject:newNode]];
[[userOutlineView window] makeFirstResponder:userOutlineView];
[[[document managedObjectContext] undoManager] setActionName:@"import audio"];
}
[(UserTreeController *)treeController updateSortIndex];
return newAudioItem;
}
- (void)showSheetForNewTrajectoryItem:(NSString *)name
{
[self setNewTrajectoryName:name];
[self setValue:[NSNumber numberWithInt:0] forKey:@"newTrajectoryType"];
[NSApp beginSheet:newTrajectorySheet
modalForWindow:[[self view] window]
modalDelegate:self
didEndSelector:@selector(newTrajectorySheetDidEnd: returnCode: contextInfo:)
contextInfo:nil];
}
- (void)newTrajectorySheetOK
{
[NSApp endSheet:newTrajectorySheet returnCode:NSOKButton];
}
- (void)newTrajectorySheetCancel;
{
[NSApp endSheet:newTrajectorySheet returnCode:NSCancelButton];
}
- (void)newTrajectorySheetDidEnd:(NSPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
[newTrajectorySheet orderOut:nil];
if(returnCode == NSOKButton)
{
TrajectoryItem *trajectoryItem = [self createNewTrajectoryItem];
[[TrajectoryInspectorWindowController sharedTrajectoryInspectorWindowController] showInspectorModalForWindow:[[self view] window] trajectoryItem:trajectoryItem];
}
}
- (void)importSpatDIF:(NSURL *)absoluteFilePath
{
NSError *err;
NSXMLDocument *xmlDoc;
xmlDoc = [[[NSXMLDocument alloc] initWithContentsOfURL:absoluteFilePath
options:(NSXMLNodePreserveWhitespace|NSXMLNodePreserveCDATA)
error:&err] autorelease];
if (xmlDoc == nil)
{
NSLog(@"2nd attempt");
xmlDoc = [[[NSXMLDocument alloc] initWithContentsOfURL:absoluteFilePath
options:NSXMLDocumentTidyXML
error:&err] autorelease];
}
if (xmlDoc == nil)
{
NSLog(@"failed opening: %@", [absoluteFilePath path]);
if (err)
{
// handle error
}
return;
}
SpatDIF *spatDif = [[[SpatDIF alloc] initWithXmlDoc:xmlDoc] autorelease];
if (![spatDif parse])
{
NSLog(@"no valid spatDIF in: %@", [absoluteFilePath path]);
return;
}
NSArray *trajectoryNames = [spatDif trajectoryNames];
NSArray *trajectories = [spatDif trajectories];
int count;
if ((count = [trajectories count]) == 0)
{
NSLog(@"no trajectory descriptions found in: %@", [absoluteFilePath path]);
return;
}
// present all trajectories in a list to
// pick the ones to be imported
// (show proposed names)
int i;
for(i=0;i<count;i++)
{
// new trajectory
[self setNewTrajectoryName:[trajectoryNames objectAtIndex:i]];
newTrajectoryType = breakpointType;
TrajectoryItem *trajectoryItem = [self createNewTrajectoryItem];
[trajectoryItem setTrajectory:[trajectories objectAtIndex:i]];
if([[[[trajectories objectAtIndex:i] positionBreakpointArray] objectAtIndex:0] breakpointType] == breakpointTypeAdaptiveInitial)
[trajectoryItem setValue:[NSNumber numberWithBool:YES] forKey:@"adaptiveInitialPosition"];
}
// change pool view
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 1) // audio view
{
[tabControl setSelectedSegment:1];
[tabView selectTabViewItemAtIndex:1];
}
}
- (TrajectoryItem *)createNewTrajectoryItem
{
// check if the name is unique
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"TrajectoryItem" inManagedObjectContext:[document managedObjectContext]];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
[request setPredicate:[NSPredicate predicateWithFormat:@"node.name == %@", newTrajectoryName]];
NSError *error;
NSString *newName = [[newTrajectoryName copy] autorelease];
if([[document managedObjectContext] countForFetchRequest:request error:&error])
{
BOOL unique = NO;
int i;
for(i=1;!unique;i++)
{
[request setPredicate:[NSPredicate predicateWithFormat:@"node.name == %@", [newTrajectoryName stringByAppendingString:[NSString stringWithFormat:@" %i", i]]]];
if([[document managedObjectContext] countForFetchRequest:request error:&error] == 0)
{
newName = [newTrajectoryName stringByAppendingString:[NSString stringWithFormat:@" %i", i]];
unique = YES;
}
}
}
NSManagedObject *parentNode = nil;
NSTreeNode *selectedTreeNode = nil;
if([[projectSettings valueForKey:@"poolSelectedTab"] intValue] == 0) // user view
{
// get (last) selected item
NSIndexSet *selectedIndices = [userOutlineView selectedRowIndexes];
selectedTreeNode = [userOutlineView itemAtRow:[selectedIndices lastIndex]];
NSManagedObject *selectedNode = [selectedTreeNode representedObject];
if([selectedIndices count] == 1 && ![[selectedNode valueForKey:@"isLeaf"] boolValue])
{
// the only selected item is a group
parentNode = selectedNode;
}
else
{
// insert as sibling of the last selected item
parentNode = [selectedNode valueForKey:@"parent"];
}
}
// insert trajectory item in model
NSManagedObject *newNode = [NSEntityDescription insertNewObjectForEntityForName:@"Node"
inManagedObjectContext:[document managedObjectContext]];
TrajectoryItem *newItem = [NSEntityDescription insertNewObjectForEntityForName:@"TrajectoryItem"
inManagedObjectContext:[document managedObjectContext]];
[newNode setValue:parentNode forKey:@"parent"];
[newNode setValue:newName forKey:@"name"];
[newNode setValue:CHTrajectoryType forKey:@"type"];
[newNode setValue:newItem forKey:@"item"];
[newItem setValue:[NSNumber numberWithInt:newTrajectoryType] forKey:@"trajectoryType"];
[newItem setValue:regionsForNewTrajectoryItem forKey:@"regions"];
for(id region in regionsForNewTrajectoryItem)
{
[region setValue:[NSNumber numberWithInt:1] forKey:@"trajectoryDurationMode"];
}
// store data
[newItem archiveData];
// undo
[[[document managedObjectContext] undoManager] setActionName:@"new trajectory"];
// expand group
[userOutlineView expandItem:selectedTreeNode];
// todo: select the new trajectory
return newItem;
}
- (BOOL)recursivelyDeleteNode:(id)node
{
NSEnumerator *nodeEnumerator;
id subnode;
BOOL dirty = NO;
BOOL groupIsEmpty = YES;
Region *region;
// node is a group (folder)
if([[node mutableSetValueForKeyPath:@"children"] count])
{
nodeEnumerator = [[node mutableSetValueForKeyPath:@"children"] objectEnumerator];
while ((subnode = [nodeEnumerator nextObject]))
{
BOOL flag = [self recursivelyDeleteNode:subnode];
if(flag)
dirty = YES;
if(!flag)
groupIsEmpty = NO;
}
if(groupIsEmpty)
[[document managedObjectContext] deleteObject:node];
return dirty;
}
// node is a single item
NSString *name = [node valueForKey:@"name"];
if([[node valueForKey:@"type"] isEqualToString:CHAudioItemType])
{
NSSet *regions = [node mutableSetValueForKeyPath:@"item.audioRegions"];
if([regions count])
{
NSAlert *alert = [NSAlert alertWithMessageText:@"Delete Audio?"
defaultButton:@"Cancel"
alternateButton:@"Delete"
otherButton:nil
informativeTextWithFormat:[NSString stringWithFormat:@"\"%@\" is used on the timeline. Do you want to delete it?", name]];
// show alert in a modal dialog
if ([alert runModal] == NSAlertDefaultReturn)
{
return NO;
}
// remove all regions from arrangerView
for (region in regions)
{
[region removeFromView];
}
}
// delete audio file if it isn't referenced anymore
AudioFile *audioFile = [node valueForKeyPath:@"item.audioFile"];
if([[audioFile valueForKey:@"audioItems"] count] == 1 && [node valueForKey:@"item"] == [[audioFile valueForKey:@"audioItems"] anyObject])
{
// NSLog(@"delete audioFile %@", audioFile);
[[document managedObjectContext] deleteObject:audioFile];
}
}
else if([[node valueForKey:@"type"] isEqualToString:CHTrajectoryType])
{
NSSet *regions = [node mutableSetValueForKeyPath:@"item.regions"];
if([regions count])
{
NSAlert *alert = [NSAlert alertWithMessageText:@"Delete Trajectory?"
defaultButton:@"Cancel"
alternateButton:@"Delete"
otherButton:nil
informativeTextWithFormat:[NSString stringWithFormat:@"\"%@\" is used on the timeline. Do you want to delete it?", name]];
// show alert in a modal dialog
if ([alert runModal] == NSAlertDefaultReturn)
{
return NO;
}
// nullify relations to regions
for (region in [[regions copy] autorelease])
{
[region setValue:NULL forKey:@"trajectoryItem"];
}
}
}
else
{
return NO;
}
[[document managedObjectContext] deleteObject:node];
return YES;
}
- (void)prelisten:(id)sender index:(int)i
{
if(i < 0)
{
[[AudioEngine sharedAudioEngine] stopPrelistening];
}
else if([[document valueForKey:@"keyboardModifierKeys"] intValue] == modifierAlt)
{
id item;
switch ([[projectSettings valueForKey:@"poolSelectedTab"] intValue])
{
case 0: // user view
item = [[[sender itemAtRow:i] representedObject] valueForKeyPath:@"item"];
break;
case 1: // audio items view
item = [[[audioItemArrayController arrangedObjects] objectAtIndex:i]valueForKeyPath:@"item"];
break;
default:
item = nil;
break;
}
if([item isKindOfClass:[AudioItem class]])
[[AudioEngine sharedAudioEngine] startPrelistening:item];
else
[[AudioEngine sharedAudioEngine] stopPrelistening];
}
}
#pragma mark -
#pragma mark accessors
// -----------------------------------------------------------
// binding in IB
- (NSManagedObjectContext *)managedObjectContext
{
return [document managedObjectContext];
}
#pragma mark -
#pragma mark selection
// -----------------------------------------------------------
- (void)outlineViewSelectionDidChange:(NSNotification *)notification
{
if ([[[notification object] valueForKey:@"hasFocus"] boolValue])
{
[(CHProjectDocument *)document selectionInPoolDidChange];
//NSLog(@"poolOutlineView: selection did change");
}
}
- (void)tableViewSelectionDidChange:(NSNotification *)notification
{
if ([[[notification object] valueForKey:@"hasFocus"] boolValue])
{
[(CHProjectDocument *)document selectionInPoolDidChange];
//NSLog(@"poolTableView: selection did change");
}
}
- (void)adaptSelection:(NSSet *)selectedAudioRegions
{
[userOutlineView deselectAll:nil];
[audioItemTableView deselectAll:nil];
[trajectoryTableView deselectAll:nil];
NSEnumerator *enumerator = [selectedAudioRegions objectEnumerator];
AudioRegion *region;
NSMutableSet *selectedAudioItems = [[[NSMutableSet alloc] init] autorelease];
while((region = [enumerator nextObject]))
{
if([region isKindOfClass:[AudioRegion class]])
[selectedAudioItems addObject:[region valueForKey:@"audioItem"]];
}
NSMutableIndexSet *selectedIndices = [[[NSMutableIndexSet alloc] init] autorelease];
NSArray *arrangedObjects = [audioItemArrayController arrangedObjects];
enumerator = [arrangedObjects objectEnumerator];
NSManagedObject *node;
while((node = [enumerator nextObject]))
{
if([selectedAudioItems containsObject:[node valueForKey:@"item"]])
{
[selectedIndices addIndex:[arrangedObjects indexOfObject:node]];
}
}
[audioItemTableView selectRowIndexes:selectedIndices byExtendingSelection:NO];
}
- (NSArray *)selectedTrajectories
{
NSMutableArray *selectedTrajectories = [[[NSMutableArray alloc] init] autorelease];
NSEnumerator *enumerator;
id object;
id item;
switch([[projectSettings valueForKey:@"poolSelectedTab"] intValue])
{
case 0:
enumerator = [[treeController selectedObjects] objectEnumerator];
break;
case 2:
enumerator = [[trajectoryArrayController selectedObjects] objectEnumerator];
break;
default:
return nil;
}
while ((object = [enumerator nextObject]))
{
if([[object valueForKey:@"type"] isEqualToString:CHAudioItemType])
{
return nil;
}
else if([[object valueForKey:@"type"] isEqualToString:CHTrajectoryType] && [[object valueForKey:@"isLeaf"] boolValue])
{
item = [object valueForKey:@"item"];
[item willAccessValueForKey:nil]; // fire fault
[selectedTrajectories addObject:item];
}
}
return selectedTrajectories;
}
#pragma mark -
#pragma mark notifications
// -----------------------------------------------------------
- (void)refresh:(NSNotification *)notification
{
NSDictionary *info = [notification userInfo];
for(id object in [info objectForKey:NSInsertedObjectsKey])
{
if([object isKindOfClass:[AudioItem class]] ||
[object isKindOfClass:[TrajectoryItem class]])
{
[audioItemArrayController fetch:NULL];
[trajectoryArrayController fetch:NULL];
return;
}
}
for(id object in [info objectForKey:NSDeletedObjectsKey])
{
if([object isKindOfClass:[AudioItem class]] ||
[object isKindOfClass:[TrajectoryItem class]])
{
[audioItemArrayController fetch:NULL];
[trajectoryArrayController fetch:NULL];
return;
}
}
}
#pragma mark -
#pragma mark etc...
// -----------------------------------------------------------
- (NSString *)nodeImageName:(id)node
{
/* depending on the type return the appropriate image */
if(![[node valueForKey:@"isLeaf"] boolValue])// == [NSNumber numberWithBool:NO])
return @"folder";
if([[node valueForKey:@"type"] isEqualToString:CHAudioItemType])
return @"audioItem";
else
return @"trajectoryItem";
}
- (NSColor *)nodeTextColor:(id)node
{
/* return the appropriate color */
if([[node valueForKey:@"type"] isEqualToString:CHAudioItemType] &&
![[node valueForKeyPath:@"item.audioFile"] audioFileID])
return [NSColor grayColor];
else
return [NSColor blackColor];
}
- (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
// We know that the cell at this column is our image and text cell
ImageAndTextCell *imageAndTextCell = (ImageAndTextCell *)cell;
NSImage *image = [NSImage imageNamed:[self nodeImageName:[item representedObject]]];
[imageAndTextCell setImage:image];
[imageAndTextCell setTextColor:[self nodeTextColor:[item representedObject]]];
}
- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tc row:(NSInteger)row
{
ImageAndTextCell *imageAndTextCell = (ImageAndTextCell *)cell;
NSImage *image = [NSImage imageNamed:[tc identifier]];
[imageAndTextCell setImage:image];
if([[tc identifier] isEqualToString:@"audioItem"] && ![[[[audioItemArrayController arrangedObjects] objectAtIndex:row] valueForKeyPath:@"item.audioFile"] audioFileID])
[imageAndTextCell setTextColor:[NSColor grayColor]];
else
[imageAndTextCell setTextColor:[NSColor blackColor]];
}
#pragma mark -
#pragma mark pool drag and drop
// -----------------------------------------------------------
/*
drag and drop only with one item at a time
(multiple selection NOT selected in IB)
*/
- (NSArray *)treeNodeSortDescriptors;
{
return [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"sortIndex" ascending:YES] autorelease]];
}
/*
Beginning the drag from the outline view.
*/
#define PoolPboardType @"PoolPboardType"
- (BOOL)outlineView:(NSOutlineView *)poolView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
{
// Type
// NSString *type = [[[items objectAtIndex:0] representedObject] valueForKey:@"type"];
// if(!type) type = CHFolderType;
draggedNodes = items; // Don't retain since this is just holding temporaral drag information, and it is only used during a drag! We could put this in the pboard actually.
[pboard declareTypes:[NSArray arrayWithObjects:PoolPboardType, /* NSFilesPromisePboardType, */ nil] owner:self];
// Query the NSTreeNode (not the underlying Core Data object) for its index path under the tree controller.
// NSIndexPath *pathToDraggedNode = [[items objectAtIndex:0] indexPath];
// Place the index path on the pasteboard.
// NSData *indexPathData = [NSKeyedArchiver archivedDataWithRootObject:pathToDraggedNode];
// [pboard setData:indexPathData forType:type];
// the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
[pboard setData:[NSData data] forType:[[[items objectAtIndex:0] representedObject] valueForKey:@"type"]];
[pboard setData:[NSData data] forType:PoolPboardType];
// set draggedItems (dragging to arranger view)
NSEnumerator *enumerator = [items objectEnumerator];
id item;
NSMutableArray *tempAudioArray = [[[NSMutableArray alloc] init] autorelease];
NSMutableArray *tempTrajectoryArray = [[[NSMutableArray alloc] init] autorelease];
while ((item = [enumerator nextObject]))
{
if([[[item representedObject] valueForKey:@"type"] isEqualToString:CHAudioItemType])
[tempAudioArray addObject:[item representedObject]];
else if([[[item representedObject] valueForKey:@"type"] isEqualToString:CHTrajectoryType])
[tempTrajectoryArray addObject:[item representedObject]];
}
[document setValue:[NSArray arrayWithArray:tempAudioArray] forKey:@"draggedAudioRegions"];
[document setValue:[NSArray arrayWithArray:tempTrajectoryArray] forKey:@"draggedTrajectories"];