download MKPart.m
Language: ObjectiveC
Copyright: (c) 1988-1992, NeXT Computer, Inc. (c) 1999-2003, The MusicKit Project. (c) 1994 NeXT Computer, Inc. and reproduced under license from NeXT (c) 1994 Stanford University
LOC: 786
Project Info
The MusicKit(musickit)
Server: SourceForge
Type: cvs
...sicKit\Frameworks\MusicKit\
   _ArielQP.h
   _DSPMK.h
   _error.h
   _midi.h
   _MKAppProxy.h
   _MKAppProxy.m
   _MKNameTable.h
   _MKNameTable.m
   _MKParameter.h
   _MTCHelper.h
   _MTCHelper.m
   _musickit.h
   _noteRecorder.h
   _OrchloopbeginUG.h
   _OrchloopbeginUG.m
   _ParName.h
   _ParName.m
   _scorefile.h
   _ScorefileVar.h
   _ScorefileVar.m
   _SharedSynthInfo.h
   _SharedSynthInfo.m
   _synthElementMethods.m
   _time.h
   ArielQP.h
   ArielQP.m
   classFuncs.h
   ConductorPrivate.h
   dsp_types.h
   DSPSerialPortDevice.h
   dspwrap.h
   EnvelopePrivate.h
   equalTempered.m
   errors.h
   fastFFT.c
   fastFFT.h
   GNUmakefile.postamble
   GNUmakefile.preamble.in
   InstrumentPrivate.h
   keynums.h
   libMusicKit.def
   Localized.strings
   make.sh
   Makefile.postamble
   Makefile.preamble
   midi_spec.h
   midifile.h
   midifile.m
   MidiPrivate.h
   midiTranslation.h
   MKConductor.h
   MKConductor.m
   MKConductorDelegate.h
   MKDeviceStatus.h
   MKEnvelope.h
   MKEnvelope.m
   MKFilePerformer.h
   MKFilePerformer.m
   MKFileWriter.h
   MKFileWriter.m
   MKInstrument.h
   MKInstrument.m
   MKMidi.h
   MKMidi.m
   MKMixerInstrument.h
   MKMixerInstrument.m
   MKMTCPerformer.h
   MKMTCPerformer.m
   MKNote.h
   MKNoteFilter.h
   MKNoteFilter.m
   MKNoteReceiver.h
   MKNoteReceiver.m
   MKNoteSender.h
   MKNoteSender.m
   MKOrchestra.h
   MKPart.m
   MKPartials.h
   MKPartials.m
   ...tialsWaveshapingTable.m
   MKPartPerformer.h
   MKPartPerformer.m
   MKPartRecorder.h
   MKPartRecorder.m
   MKPatch.h
   MKPatch.m
   MKPatchConnection.h
   MKPatchConnection.m
   MKPatchEntry.h
   MKPatchEntry.m
   MKPatchTemplate.h
   MKPatchTemplate.m
   MKPerformer.h
   MKPerformer.m
   MKPerformerDelegate.h
   MKPlugin.h
   MKSamplerInstrument.h
   MKSamplerInstrument.m
   MKSamples.h
   MKScore.h
   MKScore.m
   MKScorefileObject.h
   MKScorefilePerformer.h
   MKScorefilePerformer.m
   MKScorefileWriter.m
   MKScorePerformer.h
   MKScorePerformer.m
   MKScoreRecorder.h
   MKScoreRecorder.m
   MKSynthData.h
   MKSynthData.m
   MKSynthInstrument.h
   MKSynthPatch.h
   MKTimbre.h
   MKTimbre.m
   MKTuningSystem.h
   MKTuningSystem.m
   MKUnitGenerator.h
   MKUnitGenerator.m
   MKWaveTable.h
   MKWaveTable.m
   mtcMidi.m
   mtcMidiPrivate.m
   MusicKit-Info.plist
   MusicKit.h
   MusicKitConfig.h.in
   names.h
   noDVal.h
   noteDispatcherMethods.m
   NotePrivate.h
   noteRecorderCFuncs.m
   noteRecorderMethods.m
   orch.h
   OrchestraPrivate.h
   OrchloopbeginUG.h
   OrchloopbeginUG.m
   orchloopbeginUGInclude.m
   params.h
   parNames.m
   partialsDBInclude.m
   PartialsPrivate.h
   PartPerformerPrivate.h
   PartPrivate.h
   PartRecorderPrivate.h
   PatchTemplatePrivate.h
   PB.project
   PerformerPrivate.h
   pitches.h
   platform.make
   ...efilePerformerPrivate.h
   ScorePerformerPrivate.h
   ScorePrivate.h
   ScoreRecorderPrivate.h
   SynthDataPrivate.h
   synthElementCFuncs.m
   synthElementMethods.m
   SynthInstrumentPrivate.h
   SynthPatchList.h
   SynthPatchList.m
   SynthPatchPrivate.h
   timetagInclude.m
   timeunits.h
   tokenNames.m
   tokens.h
   trigonometry.c
   trigonometry.h
   TuningSystemPrivate.h
   UnitGeneratorPrivate.h
   win32-def.top
   writeBinary.m
   writeMidi.m
   writeScore.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
/*
 $Id: MKPart.m,v 1.31 2006/02/05 17:57:10 leighsmith Exp $
 Defined In: The MusicKit

 Original Author: David A. Jaffe

 Copyright (c) 1988-1992, NeXT Computer, Inc.
 Portions Copyright (c) 1994 NeXT Computer, Inc. and reproduced under license from NeXT
 Portions Copyright (c) 1994 Stanford University
 Portions Copyright (c) 1999-2003, The MusicKit Project.
 */
/*
Modification history now in CVS at musickit.org

 pre-CVS history:
 01/24/90/daj - Fixed bug in removeNote:.
 03/19/90/daj - Added MKSetPartClass() and MKGetPartClass().
 03/21/90/daj - Added archiving support.
 04/21/90/daj - Small mods to get rid of -W compiler warnings.
 04/28/90/daj - Flushed scoreClass optimization, now that we're a shlib.
 08/14/90/daj - Fixed bug in addNote:. It wasn't checking to make sure notes exists.
 08/23/90/daj - Changed to zone API.
 10/04/90/daj - freeNotes now creates a new notes List.
 */

#import <stdlib.h>
#import "_musickit.h"
#import "ScorePrivate.h"
#import "NotePrivate.h"
#import "PartPrivate.h"

#define VERSION2 2

static id theSubclass = nil;

BOOL MKSetPartClass(id aClass)
{
  if (!_MKInheritsFrom(aClass, [MKPart class]))
    return NO;
  theSubclass = aClass;
  return YES;
}

id MKGetPartClass(void)
{
  if (!theSubclass)
    theSubclass = [MKPart class];
  return theSubclass;
}

@implementation MKPart

+ (void) initialize
{
    if (self == [MKPart class]) {
	[MKPart setVersion: VERSION2];
    }
}

+new
    /* Override default to return instance of theSubclass, if nec. */
{
    return [[MKGetPartClass() alloc] init];
}

+ (MKPart *) part
{
    return [[[MKGetPartClass() alloc] init] autorelease]; 
}

+ partWithName: (NSString *) partName
{
    MKPart *newPart = [self part];
    
    [newPart setPartName: partName];
    return newPart;
}

/* Format conversion methods. ---------------------------------------------*/


static id compact(MKPart *self)
{
  NSMutableArray *newList = [[NSMutableArray alloc] initWithCapacity:self->noteCount];
  IMP addObjectImp = [newList methodForSelector:@selector(addObject:)];
# define ADDNEW(x) (*addObjectImp)(newList, @selector(addObject:),x)
  int noteIndex, nc = [self->notes count];
  MKNote *aNote;
  SEL oaiSel = @selector(objectAtIndex:);
  IMP objectAtIndex = [self->notes methodForSelector: oaiSel];
# define OBJECTATINDEX(x)  (*objectAtIndex)(self->notes, oaiSel, (x))
  
  for (noteIndex = 0; noteIndex < nc; noteIndex++) {
    aNote = OBJECTATINDEX( noteIndex );
    if (_MKNoteIsPlaceHolder(aNote)) {
      [aNote _setPartLink:nil order:0];
    }
    else {
      ADDNEW(aNote);
    }
  }
  [self->notes release];
  self->notes = newList;
  self->noteCount = [newList count];
  return self;
# undef ADDNEW
# undef OBJECTATINDEX
}

static void removeNote(MKPart *self, MKNote *aNote);

- combineNotes
  /* TYPE: Editing
    * Attempts to minimize the number of MKNotes by creating
    * a single noteDur for every noteOn/noteOff pair
    * (see the MKNote class).  A noteOn is paired with the
    * earliest subsequent noteOff that has a matching noteTag. However,
    * if an intervening noteOn or noteDur is found, the noteOn is not
    * converted to a noteDur.
    * If a match isn't found, the MKNote is unaffected.
    * Returns the receiver.
    */
{
    MKNote *noteOn, *aNote;
    int noteTag, listSize;
    register int i, j;
    SEL oaiSel = @selector(objectAtIndex:);
    IMP objectAtIndex = [notes methodForSelector: oaiSel];
# define OBJECTATINDEX(x)  (*objectAtIndex)(notes, oaiSel, (x))
    
    if (!noteCount)
	return self;
    listSize = [notes count];
    
    for (i = 0; i < listSize; i++) {			/* For each note... */
	if ([(noteOn = OBJECTATINDEX(i)) noteType] == MK_noteOn) {
	    noteTag = [noteOn noteTag];			/* We got a noteOn */
	    if (noteTag == MAXINT)			/* Malformed MKPart. */
		continue;
	    for (j = i + 1; (j < listSize); j++) {	/* Search forward */
		if ([(aNote=OBJECTATINDEX(j)) noteTag] == noteTag) {	/* A hit ? */
		    switch ([aNote noteType]) {           /* Ok. What is it? */
			case MK_noteOff:
			    removeNote(self, aNote);           /* Remove aNote from us by tagging as _MKMakePlaceHolder */
			    [noteOn setDur: ([aNote timeTag] - [noteOn timeTag])];
			    [noteOn _unionWith: aNote];        /* Ah... love. */
			    /* No break; here */
			case MK_noteOn:                     /* We don't search on     */
			case MK_noteDur:                    /*   if we find on or dur */
			    j = listSize;                   /* Force abort. No break; */
			default:
			    break;
		    }                           /* End of switch */
		}
	    }                                   /* End of search forward */
	}                                       /* End of if noteOn */
    }

    compact(self); /* drops all notes that are PlaceHolder and remakes list without them */
    return self;
}
# undef OBJECTATINDEX

-splitNotes
  /* TYPE: Editing
    * Splits all noteDurs into a noteOn/noteOff pair.
    * This is done by changing the noteType of the noteDur to noteOn
    * and creating a noteOff with timeTag equal to the
    * timeTag of the original MKNote plus its duration.
    * However, if an intervening noteOn or noteDur of the same tag
    * appears, the noteOff is not added (the noteDur is still converted
					 * to a noteOn in this case).
    * Returns the receiver, or nil if the receiver contains no MKNotes.
    */
{
    NSArray *noteList;
    MKNote *noteOff;
    int noteIndex, matchIndex;
    BOOL matchFound;
    double timeTag;
    int noteTag;
    int originalNoteCount = noteCount;  // noteCount is updated by addNote:
    SEL oaiSel = @selector(objectAtIndex:);
    IMP objectAtIndex;
# define OBJECTATINDEX(x)  (*objectAtIndex)(noteList, oaiSel, (x))
    
    if (!noteCount)
	return self;
    noteList = [self notes]; /* local copy of list (autoreleased) */
    objectAtIndex = [noteList methodForSelector: oaiSel];
    
    for (noteIndex = 0; noteIndex < originalNoteCount; noteIndex++) {
	MKNote *note = OBJECTATINDEX(noteIndex);
	if ([note noteType] == MK_noteDur) {
	    noteOff = [note _splitNoteDurNoCopy];  // Split all noteDurs.
	    noteTag = [noteOff noteTag];
	    if (noteTag == MAXINT) {               // Add noteOff if no tag.
		[self addNote: noteOff];
	    }
	    else {                                 // Need to check for intervening MKNote.
		matchFound = NO;
		timeTag = [noteOff timeTag];
		// search for matching noteTag in the subsequent notes before the noteOff.
		// since addNote: adds noteoffs at the end of the array, we can just search to the original length.
		for (matchIndex = noteIndex + 1; (matchIndex < originalNoteCount) && !matchFound; matchIndex++) {
		    MKNote *candidateNote = OBJECTATINDEX(matchIndex);
		    if ([candidateNote timeTag] > timeTag)
			break;
		    if ([candidateNote noteTag] == noteTag) {
			switch ([candidateNote noteType]) {
			    case MK_noteOn:
				// we treat noteOns as a special case. An intervening noteOn with a matching noteTag is
				// a rearticulation of the current sounding note which can have an acoustic outcome different
				// from a noteOff, then noteOn. Therefore we simply let this one go past and keep searching.
				break;
			    case MK_noteOff:
			    case MK_noteDur:
				matchFound = YES;          // Forget it.
				break;
			    default:
				break;
			}
		    }
		}
		if (!matchFound) {                  /* No intervening notes. */
		    [self addNote: noteOff];
		}
	    }
	}
    }
    return self;
}
#undef OBJECTATINDEX

/* Reading and Writing files. ------------------------------------ */

// TODO should be able to be replaced with setInfoNote:
- _setInfo: (MKNote *) aInfo
    /* Needed by scorefile parser  */
{
    if (!info)
	info = [aInfo copy];
    else
	[info copyParsFrom:aInfo];
    return self;
}

/* MKScore Interface. ------------------------------------------------------- */


- addToScore: (MKScore *) newScore
     /* TYPE: Modifying
    * Removes the receiver from its present MKScore, if any, and adds it
    * to newScore.
    */
{
    return [newScore addPart: self];
}

-removeFromScore
  /* TYPE: Modifying
    * Removes the receiver from its present MKScore.
    * Returns the receiver, or nil if it isn't part of a MKScore.
    * (Implemented as [score removePart:self].)
    */
{
    return [score removePart: self];
}

/* Creation. ------------------------------------------------------------ */

-init
 /* TYPE: Creating and freeing a MKPart
  * Initializes the receiver:
    *
    * Sent by the superclass upon creation;
    * You never invoke this method directly.
    * An overriding subclass method should send [super initialize]
    * before setting its own defaults.
    */
{
    self = [super init];
    if (self != nil) {
	notes    = [NSMutableArray new];
	isSorted = YES;
    }
    return self;
}

/* Freeing. ------------------------------------------------------------- */

- (void) dealloc
 /* TYPE: Creating and freeing a MKPart
    * Frees the receiver and its MKNotes, including the info note, if any.
    * Also removes the name, if any, from the name table.
    * Illegal while the receiver is being performed (and should not
    * happen in this case).
    */
{
    if (![self releaseNotes]) {
	NSLog(@"MusicKit MKPart object: deallocation attempt while _activePerformanceObjs (should not happen). Ignoring.\n");
	//return;
    }
    if (score != nil)
	[score removePart: self];
    if (notes != nil) {
	[notes release];
	notes = nil;
    }
    MKRemoveObjectName(self);
    [super dealloc];
    // Changed on K. Hamels suggestion, used to message to releaseSelfOnly but this would cause a dealloc loop.
}

- (unsigned) hash
{
    unsigned val = 0;
    if (info) {
        val += 1000 * [info noteTag];
    }
    if (notes) {
        val += [notes count];
    }
    return val;
}

#define OBJECTATINDEX(_o,_x)  (*objectAtIndex)((_o), oaiSel, (_x))

- (BOOL) isEqual:(MKPart *) anObject
{
    unsigned noteIndex,count;
    SEL oaiSel;
    IMP objectAtIndex;
    id othernotes;
    
    if (!anObject)                           return NO;
    if (self == anObject)                    return YES;
    if ([self class] != [anObject class])    return NO;
    if ([anObject noteCount] != noteCount)   return NO;
    if (![[anObject infoNote] isEqual:info]) return NO;
    count = [notes count];
    othernotes = [anObject notes];

    oaiSel = @selector(objectAtIndex:);
    objectAtIndex = [notes methodForSelector: oaiSel];
    
    for (noteIndex = 0 ; noteIndex < count ; noteIndex++) {
        if (![OBJECTATINDEX(notes,noteIndex) isEqual:OBJECTATINDEX(notes,noteIndex)]) {
            return NO;
        }
    }
    return YES;
}

static void unsetPartLinks(MKPart *aPart)
{
  id notes = aPart->notes;
  int noteIndex,count;

  if (notes) {
    SEL oaiSel = @selector(objectAtIndex:);
    IMP objectAtIndex = [notes methodForSelector: oaiSel];
    count = [notes count];
    for (noteIndex = 0 ; noteIndex < count ; noteIndex++) {
      [OBJECTATINDEX(notes, noteIndex) _setPartLink:nil order:0];
    }
  }
}

# undef OBJECTATINDEX

- releaseNotes
  /* TYPE: Editing
    * Removes and frees all MKNotes from the receiver including the info
    * note, if any.
    * Doesn't free the receiver.
    * Returns the receiver.
    */
{
    if (_activePerformanceObjs)
	return nil;
    [info release];
    info = nil;
    if (notes) {
	[self removeAllNotes];
    }
    return self;
}

// DEPRECATED - should remove (sbrandon, 01/2002)

-releaseSelfOnly
  /* TYPE: Creating and freeing a MKPart
    * Frees the receiver but not their MKNotes.
    * Returns the receiver. */
{
    [score removePart: self];
    [super release];
    return nil; /*sb: to match old behaviour of "free" */
}

/* Compaction and sorting ---------------------------------------- */

static id sortIfNeeded(MKPart *self)
{
    if (!self->isSorted) {
	[self->notes sortUsingSelector: @selector(compare:)];
	self->isSorted = YES;
	return self;
    }
    return nil;
}

- (BOOL) isSorted
{
    return isSorted;
}

- sort
    /* If the receiver needs to be sorted, sorts and returns self. Else
    returns nil. */
{
    return sortIfNeeded(self);
}

static int findNoteIndex(MKPart *self, MKNote *aNote)
{
    int matchedNote;
    if ((matchedNote = [self->notes indexOfObjectIdenticalTo:aNote]) != NSNotFound)
	return matchedNote;
    return -1;
}

static int findAux(MKPart *self,double timeTag)
{
    /* This function returns:
    If no elements in list, -1
    If the timeTag equals that of the first MKNote or the timeTag is less
    than that of the first MKNote, the index of the first MKNote.
    Otherwise, the index of the last MKNote with timeTag less than the one
    specified. */
    
    register int low = 0;
    register int high = low + self->noteCount;
    register int tmp = low + ((unsigned)((high - low) >> 1));
    
    if (self->noteCount == 0)
	return -1;
    while (low + 1 < high) {
	tmp = low + ((unsigned)((high - low) >> 1));
	if (timeTag > [[self->notes objectAtIndex:tmp] timeTag])
	    low = tmp;
	else high = tmp;
    }
    return low;
}

static int findAtOrAfterTime(MKPart *self, double firstTimeTag) /* sb did the change from id to int return */
{
    int el = findAux(self, firstTimeTag);

    if (el == -1)
	return -1;
    if ([[self->notes objectAtIndex: el] timeTag] >= firstTimeTag)
	return el;
    if ((unsigned) ++el < self->noteCount)
	return el;
    return -1;
}

static int findAtOrBeforeTime(MKPart *self, double lastTimeTag)
{
    int el = findAux(self, lastTimeTag);
    
    if (el == -1)
	return -1;
    
    if ((unsigned) ++el < self->noteCount)
	if ([[self->notes objectAtIndex: el] timeTag] <= lastTimeTag)
	    return el;
    el--;
    
    if (el < 0)
	return -1;
    if ([[self->notes objectAtIndex:el] timeTag] > lastTimeTag)
	return -1;
    return el;
}

/* Basic editing operations. ---------------------------------------  */

- (MKPart *) addNote: (MKNote *) aNote
 /* TYPE: Editing
    * Removes aNote from its present MKPart, if any, and adds it to the end of the receiver.
    * aNote must be a MKNote. Returns the old MKPart, if any.
    */
{
    id oldPart;
    if (!aNote)
	return nil;
    [aNote retain]; /* so the next statement does not dealloc it */
    [oldPart = [aNote part] removeNote:aNote];
    [aNote _setPartLink:self order:++_highestOrderTag];
    if ((noteCount++) && (isSorted)) {
	MKNote *lastObj = [notes lastObject];
	if (_MKNoteCompare(&aNote, &lastObj) == NSOrderedAscending)
	    isSorted = NO;
    }
    [notes addObject:aNote];
    [aNote release]; /* since "notes" holds the retain now */
    return oldPart;
}

- (MKNote *) addNoteCopy: (MKNote *) aNote
     /* TYPE: Editing
    * Adds a copy of aNote
    * to the receiver.
    * Returns the new MKNote.
    */
{
    MKNote *newNote = [aNote copyWithZone: NSDefaultMallocZone()];
    [self addNote: newNote];
    /* we were holding an extra retain from the copyWithZone */
    return [newNote autorelease];
}

static BOOL suspendCompaction = NO;

static void removeNote(MKPart *self, MKNote *aNote)
{
    if ([self->notes containsObject:aNote])  /* MKNote in MKPart? */
	_MKMakePlaceHolder(aNote); /* Mark it as 'to be removed' */
}

- (MKNote *) removeNote: (MKNote *) aNote
    /* TYPE: Editing
    * Removes aNote from the receiver.
    * Returns the removed MKNote or nil if not found.
    * You shouldn't free the removed MKNote if
    * there are any active Performers using the receiver.
    *
    * Keep in mind that if you have to remove a large number of MKNotes,
  * it is more efficient to put them in a List and then use removeNotes:.
    */
{
    int where;
    if (!aNote)
	return nil;
    sortIfNeeded(self);
    if (suspendCompaction)
	removeNote(self, aNote);
    else {
	where = findNoteIndex(self,aNote);
	if (where > -1) {
	    noteCount--;
	    /*sb: reversed following 2 lines. If the removal does not immediately
	    * dealloc the note, it needs to be invalidated for any other Performers
	    * using the receiver (see above)
	    */
	    [aNote _setPartLink: nil order: 0]; /* Added Jan 24, 90 */
	    [notes removeObjectAtIndex: where];
	}
    }
    return nil;
}

/* Contents editing operations. ----------------------------------------- */


- removeNotes: (NSArray *) noteList
   /* TYPE: Editing
    * Removes from the receiver all MKNotes common to the receiver and noteList.
    * Returns the receiver.
    */
{
    int noteIndex, numOfNotes;
    SEL oaiSel = @selector(objectAtIndex:);
    IMP objectAtIndex;
# define OBJECTATINDEX(x)  (*objectAtIndex)(noteList, oaiSel, (x))
    if (!noteList)
	return self;
    objectAtIndex = [noteList methodForSelector: oaiSel];
    
    [self->notes removeObjectsInArray: noteList];
    numOfNotes = [noteList count];
    /* now unset partlink for each note, in case the notes are used in other
	* parts
	*/
    for (noteIndex = 0; noteIndex < numOfNotes; noteIndex++) {
	[OBJECTATINDEX(noteIndex) _setPartLink: nil order: 0];
    }
    return self;
# undef OBJECTATINDEX
}

- addNoteCopies: (NSArray *) noteList timeShift: (double) shift
   /* TYPE: Editing
    * Copies the MKNotes in noteList, shifts the copies'
    * timeTags by shift beats, and then adds them
    * to the receiver.  noteList isn't altered.
    * noteList should contain only MKNotes.
    * Returns the receiver.
    */
{
    int noteIndex, alc;
    double tTag;
    //    register id element, copyElement;
    NSZone *zone = NSDefaultMallocZone();
    IMP selfAddNote;
    MKNote *element, *copyElement;
    
    if (noteList == nil)
	return nil;
    selfAddNote = [self methodForSelector: @selector(addNote:)];
#   define SELFADDNOTE(x) (*selfAddNote)(self, @selector(addNote:), (x))
    
    alc = [noteList count];
    for (noteIndex = 0; noteIndex < alc; noteIndex++) {
	element = [noteList objectAtIndex: noteIndex];
	copyElement = [element copyWithZone: zone];
	tTag = [element timeTag];
	if (tTag < (MK_ENDOFTIME - 1))
	    [copyElement setTimeTag: tTag + shift];
	SELFADDNOTE(copyElement);
	[copyElement release]; /* we're holding extra retain from "copyWithZone" */
    }
#   undef SELFADDNOTE
    return self;
}

- addNotes: (NSArray *) noteList timeShift: (double) shift
  /* TYPE: Editing
    * noteList should contain only MKNotes.
    * For each MKNote in noteList, removes the MKNote
    * from its present MKPart, if any, shifts its timeTag by
    * shift beats, and adds it to the receiver.
    *
    * Returns the receiver.
    */
{
    /* In order to optimize the common case of moving notes from one
    MKPart to another, we do the following.
    
    First we go through the List, removing the MKNotes from their MKParts,
    with the suspendCompaction set. We also keep track of which MKParts we've
    seen.
    
    Then we compact each of the MKParts.
    
    Finally, we add the MKNotes. */
    
    register MKNote *el;
    MKPart *elPart;
    SEL oaiSel = @selector(objectAtIndex:);
    
    if (noteList == nil)
	return self;
    {
	id aPart;
	NSMutableArray *parts = [[NSMutableArray alloc] init];
	int noteIndex;
	int partsIndex, alc, pc;
	
	IMP objectAtIndex = [noteList methodForSelector: oaiSel];
# define OBJECTATINDEX(x)  (*objectAtIndex)(noteList, oaiSel, (x))
	IMP addPart = [parts methodForSelector:@selector(addObject:)];
# define ADDPART(x) (*addPart)(parts, @selector(addObject:), (x))
	IMP partsIndexOfObjectIdenticalTo = [parts methodForSelector: @selector(indexOfObjectIdenticalTo:)];
# define PARTSCONTAINSOBJECT(x) ( (int)((*partsIndexOfObjectIdenticalTo)\
					(parts, @selector(indexOfObjectIdenticalTo:), (x))) != NSNotFound )
					    
	suspendCompaction = YES;
	alc = [noteList count];
	for (noteIndex = 0; noteIndex < alc; noteIndex++) {
	    el = OBJECTATINDEX(noteIndex);
	    aPart = [el part];
	    if (aPart) {
		if (!PARTSCONTAINSOBJECT(aPart))
		    ADDPART(aPart);
		removeNote(aPart, el);
	    }
	}
	suspendCompaction = NO;
	pc = [parts count];
	for(partsIndex = 0; partsIndex < pc; partsIndex++) {
	    elPart = [parts objectAtIndex: partsIndex];
	    compact(elPart);
	}
	[parts release];
    }
    {
	double tTag;
	int noteIndex, alc;
	IMP selfAddNote = [self methodForSelector:@selector(addNote:)];
	IMP objectAtIndex = [noteList methodForSelector: oaiSel];
# define SELFADDNOTE(x) (*selfAddNote)(self, @selector(addNote:), (x))
	alc = [noteList count];
	for (noteIndex = 0; noteIndex < alc; noteIndex++) {
	    el = OBJECTATINDEX(noteIndex);
	    tTag = [el timeTag];
	    if (tTag < (MK_ENDOFTIME-1))
		[el setTimeTag:tTag + shift];
	    /* adding the note also gives it a positive ordertag, thus resetting
		* the "placeholder" status given it above
		*/
	    SELFADDNOTE(el);
	}
# undef SELFADDNOTE
# undef OBJECTATINDEX
# undef ADDPART
# undef PARTSCONTAINSOBJECT
    }
    return self;
}

- (void) removeAllNotes
 /* TYPE: Editing
    * Removes the receiver's MKNotes which may free them.
    * Returns the receiver.
    */
{
    unsetPartLinks(self);
    [notes removeAllObjects];
    noteCount = 0;
}

- shiftTime: (double) shift
    /* TYPE: Editing
    * Shift is added to the timeTags of all notes in the MKPart.
  * Implemented in terms of addNotes:timeShift:.
    */
{
    NSArray *noteList = _MKLightweightArrayCopy(notes);
    id ret = [self addNotes: noteList timeShift: shift];
    [noteList release];
    return ret;
}

- scaleTime: (double) scale
 /* TYPE: Editing
  * Shift is added to the timeTags of all notes in the MKPart.
  * Implemented in terms of addNotes:timeShift:.
  */
{
    NSArray *noteList = _MKLightweightArrayCopy(notes);
    MKNote  *mkn;
    SEL oaiSel = @selector(objectAtIndex:);
    IMP objectAtIndex = [noteList methodForSelector: oaiSel];
# define OBJECTATINDEX(x)  (*objectAtIndex)(noteList, oaiSel, (x))
    int noteIndex, numOfNotes = [noteList count];
    
    for (noteIndex = 0 ; noteIndex < numOfNotes; noteIndex++) {
	mkn = OBJECTATINDEX(noteIndex);
	[mkn setTimeTag:  [mkn timeTag]  * scale];
	if ([mkn noteType] == MK_noteDur)
	    [mkn setDur: [mkn dur] * scale];
    }
    [noteList release];
    return self;
}
# undef OBJECTATINDEX

/* Accessing ------------------------------------------------------------- */

- firstTimeTag: (double) firstTimeTag lastTimeTag: (double) lastTimeTag
       /* TYPE: Querying the object
    * Creates and returns a List containing the receiver's MKNotes
    * between firstTimeTag and lastTimeTag in time order.
    * The notes are not copied. This method is useful in conjunction with
    * addNotes:timeShift:, removeNotes:, etc.
    */
{
    NSMutableArray *anArray;
    int firstEl, lastEl;
    
    if (!noteCount)
	return [[[NSMutableArray alloc] init] autorelease];
    sortIfNeeded(self);
    firstEl = findAtOrAfterTime(self, firstTimeTag);
    lastEl = findAtOrBeforeTime(self, lastTimeTag);
    if (firstEl == -1 || lastEl == -1 || firstEl > lastEl) {
	return [[[NSMutableArray alloc] init] autorelease];
    }
    anArray = [NSMutableArray arrayWithCapacity: (unsigned)(lastEl - firstEl) + 1];
    [anArray replaceObjectsInRange: NSMakeRange(0,0)
	      withObjectsFromArray: self->notes
			     range: NSMakeRange(firstEl, (lastEl - firstEl) + 1)];
    return anArray;
}

- (unsigned) noteCount
 /* TYPE: Querying
    * Return the number of MKNotes in the receiver.
    */
{
    return noteCount;
}

- (BOOL) containsNote: (MKNote *) aNote
 /* TYPE: Querying
  * Returns YES if the receiver contains aNote.
 */
{
    return [aNote part] == self;
}

- (BOOL) hasSoundingNotes
{
    int  noteIndex, numOfNotes;
    BOOL bFound = FALSE;
    SEL oaiSel = @selector(objectAtIndex:);
    IMP objectAtIndex = [notes methodForSelector: oaiSel];
# define OBJECTATINDEX(x)  (*objectAtIndex)(notes, oaiSel, (x))
    
    numOfNotes = [notes count];
    for (noteIndex = 0; noteIndex < numOfNotes; noteIndex++) {
	MKNote *aNote = OBJECTATINDEX(noteIndex);
	MKNoteType t = [aNote noteType];
	if (t == MK_noteDur || t == MK_noteOn) {
	    bFound = TRUE;
	    break;
	}
    }
    return bFound;
}
# undef OBJECTATINDEX


- (BOOL) isEmpty
 /* TYPE: Querying
  * Returns YES if the receiver contains no MKNotes.
  */
{
    return (noteCount == 0);
}

- (MKNote *) atTime: (double) timeTag
 /* TYPE: Accessing MKNotes
    * Returns the first MKNote found at time timeTag, or nil if
    * no such MKNote.
    * Doesn't copy the MKNote.
    */
{
    MKNote *el;
    int elReturned;
    
    sortIfNeeded(self);
    elReturned = findAtOrAfterTime(self, timeTag);
    if (elReturned == -1)
	return nil;
    el = [self->notes objectAtIndex: elReturned];
    if ([el timeTag] != timeTag)
	return nil;
    return [[el retain] autorelease];
}

- (MKNote *) atOrAfterTime: (double) timeTag
   /* TYPE: Accessing MKNotes
    * Returns the first MKNote found at or after time timeTag,
    * or nil if no such MKNote.
    * Doesn't copy the MKNote.
    */
{
    int elReturned;
    
    sortIfNeeded(self);
    elReturned = findAtOrAfterTime(self, timeTag);
    if (elReturned == -1) 
	return nil;
    return [[[self->notes objectAtIndex: elReturned] retain] autorelease];
}

- (MKNote *) atOrBeforeTime: (double) timeTag
   /* TYPE: Accessing MKNotes
    * Returns the first MKNote found at or after time timeTag,
    * or nil if no such MKNote.
    * Doesn't copy the MKNote.
    */
{
    int elReturned;
    
    sortIfNeeded(self);
    elReturned = findAtOrBeforeTime(self, timeTag);
    if (elReturned == -1)
	return nil;
    return [[[self->notes objectAtIndex: elReturned] retain] autorelease];
}

- (MKNote *) nth: (unsigned) n
 /* TYPE: Accessing MKNotes
    * Returns the nth MKNote (0-based), or nil if no such MKNote.
    * Doesn't copy the MKNote. */
{
    sortIfNeeded(self);
    return [[[notes objectAtIndex: n] retain] autorelease];
}

- (MKNote *) atOrAfterTime: (double) timeTag nth: (unsigned) n
       /* TYPE: Accessing MKNotes
    * Returns the nth MKNote (0-based) at or after time timeTag,
    * or nil if no such MKNote.
    * Doesn't copy the MKNote.
    */
{
    unsigned int arrEnd;
    int elReturned;
    
    sortIfNeeded(self);
    elReturned = findAtOrAfterTime(self, timeTag);
    if (elReturned == -1)
	return nil;
    
    arrEnd = [notes count];
    if (elReturned + n >= arrEnd) {
	return nil;
    }
    return [[[notes objectAtIndex: elReturned + n] retain] autorelease];
}

- (MKNote *) atTime: (double) timeTag nth: (unsigned) n
   /* TYPE: Accessing MKNotes
    * Returns the nth MKNote (0-based) at time timeTag,
    * or nil if no such MKNote.
    * Doesn't copy the MKNote.
    */
{
    MKNote *aNote = [self atOrAfterTime: timeTag nth: n];
    
    if (!aNote)
	return nil;
    if ([aNote timeTag] == timeTag)
	return aNote;
    return nil;
}

- (MKNote *) next: (MKNote *) aNote
 /* TYPE: Accessing MKNotes
    * Returns the MKNote immediately following aNote, or nil
    * if no such MKNote.
    */
{
    int elReturned;
    
    if (!aNote)
	return nil;
    sortIfNeeded(self);
    elReturned = findNoteIndex(self, aNote);
    if (elReturned == -1)
	return nil;
    
    if ((unsigned) ++elReturned == noteCount)
	return nil;
    return [[[self->notes objectAtIndex: elReturned] retain] autorelease];
}

// Return the time of the first note.
- (double) earliestNoteTime
{
    if([notes count] > 0) {
	MKNote *earliestNote = [notes objectAtIndex: 0];
	return [earliestNote timeTag];	
    }
    else
	return 0.0;
}

/* Querying --------------------------------------------------- */

- copyWithZone: (NSZone *) zone
   /* TYPE: Creating a MKPart
    * Creates and returns a new MKPart that contains
    * a copy of the contents of the receiver. The info is copied as well.
    */
{
    MKPart *rtn = [MKPart allocWithZone: zone];
    [rtn init];
    [rtn addNoteCopies: notes timeShift: 0];
    rtn->info = [info copy];
    return rtn;
}

- copy
{
    return [self copyWithZone: [self zone]];
}

- (NSMutableArray *) notesNoCopy
{
    return [[notes retain] autorelease];
}

- (NSArray *) notes
{
    sortIfNeeded(self);
    //    return _MKLightweightArrayCopy(notes);
    // Joerg reports [notes mutableCopy] is needed to produce a mutable deep
    // copy, but this does not appear to be the case on GNUStep. Thus the MK
    // defines its own explicit deep array copy mechanism.
    return [NSArray arrayWithArray: _MKDeepMutableArrayCopy(notes)];
}

- (MKScore *) score
  /* TYPE: Querying
  * Returns the MKScore of the receiver's owner.
  */
{
    return [[score retain] autorelease];
}

- (MKNote *) infoNote
  /* Returns 'header note', a collection of info associated with each MKPart,
  which may be used by the App in any way it wants. */
{
    return [[info retain] autorelease];
}

- setInfoNote: (MKNote *) aNote
  /* Sets 'header note', a collection of info associated with each MKPart,
  which may be used by the App in any way it wants. aNote is copied.
  The old info, if any, is freed. */
{
    [info release];
    info = [aNote copy];
    return self;
}

- (NSString *) partName
{
    return MKGetObjectName(self);
}

- (void) setPartName: (NSString *) newPartName
{
    MKNameObject(newPartName, self);    
}

- (void) encodeWithCoder: (NSCoder *) aCoder
    /* You never send this message directly.
    Archives MKNotes and info. Also archives MKScore using
    NXWriteObjectReference(). */
{
    NSString *partName = [self partName];
    
    sortIfNeeded(self);
    [aCoder encodeConditionalObject: score];
    [aCoder encodeValuesOfObjCTypes:"@@ic@i", &notes, &info, &noteCount, &isSorted, &partName, &_highestOrderTag];
}

- (id) initWithCoder: (NSCoder *) aDecoder
{
    NSString *str;
    NSMutableDictionary *tagTable;
    
    self = [super init];
    if (self != nil) {	
	if ([aDecoder versionForClassName: @"MKPart"] == VERSION2) {
	    score = [[aDecoder decodeObject] retain];
	    [aDecoder decodeValuesOfObjCTypes:"@@ic@i", &notes, &info, &noteCount, &isSorted, &str, &_highestOrderTag];
	    if (str) {
		[self setPartName: str];
	    }
	}
	/* from awake (sb) */
	if ([MKScore _isUnarchiving])
	    return self;
	tagTable = [NSMutableDictionary dictionary];
	[self _mapTags: tagTable];
    }
    return self;
}

// for debugging, just return the concatenation of the note descriptions (which have newlines).
- (NSString *) description
{
    int noteIndex, numOfNotes;
    NSMutableString *partDescription = [[NSMutableString alloc] initWithFormat: @"%@ containing MKNotes:\n", [super description]];
    NSArray *noteList = [self notes];
    MKNote *aNote;
    
    numOfNotes = [noteList count];
    for(noteIndex = 0; noteIndex < numOfNotes; noteIndex++) {
	aNote = [noteList objectAtIndex: noteIndex];
	[partDescription appendString: [aNote description]];
    }
    [partDescription appendFormat: @"With MKPart info note:\n%@", [[self infoNote] description]];
    
    return [partDescription autorelease];
}

@end

@implementation MKPart(Private)

- (void) _mapTags: (NSMutableDictionary *) hashTable
    /* Must be method to avoid loading MKScore. hashTable is a NSMutableDictionary object
    that maps ints to ints. */
{
    int oldTag;
    unsigned nc;
    MKNote *el;
    NSNumber *newTagNum;
    NSNumber *oldTagNum;
    unsigned noteIndex;

    sortIfNeeded(self);
    nc = [notes count];
    for (noteIndex = 0; noteIndex < nc; noteIndex++) {
	el = [notes objectAtIndex: noteIndex];
	oldTag = [el noteTag];
	if (oldTag != MAXINT) { /* Ignore unset tags */
	    oldTagNum = [NSNumber numberWithInt: oldTag];
	    newTagNum = [hashTable objectForKey: oldTagNum];
	    if (!newTagNum) {
		newTagNum = [NSNumber numberWithInt: MKNoteTag()];
		[hashTable setObject: newTagNum forKey: oldTagNum];
	    }
	    [el setNoteTag: [newTagNum intValue]];
	}
    }
}

- (void) _setNoteSender: (MKNoteSender *) aNS
    /* Private. Used only by scorefilePerformers. */
{
    [_aNoteSender release];
    _aNoteSender = [aNS retain];
}

- (MKNoteSender *) _noteSender
    /* Private. Used only by scorefilePerformers. */
{
    // we didn't allocate it, so we don't autorelease it.
    return _aNoteSender;
}

- _addPerformanceObj: (MKPerformer *) aPerformer
{
    if (!_activePerformanceObjs)
	_activePerformanceObjs = [[NSMutableArray alloc] init];
    if (![_activePerformanceObjs containsObject: aPerformer])
	[_activePerformanceObjs addObject:aPerformer];
    return self;
}

- _removePerformanceObj: (MKPerformer *) aPerformer
{
    if (!_activePerformanceObjs)
	return nil;
    [_activePerformanceObjs removeObject: aPerformer];
    if ([_activePerformanceObjs count] == 0) {
	[_activePerformanceObjs release];
	_activePerformanceObjs = nil;
    }
    return self;
}

- (void) _unsetScore
    /* Private method. Sets score to nil.
    Here we have the classic retain cycle in that the MKPart is retained by
    it's MKScore (indirectly by MKScore retaining the NSArray of MKParts).
    The solution is that we don't release the score. */
{
    score = nil;
}

- (MKScore *) _setScore: (MKScore *) newScore
    /* Removes receiver from the score it is a part of, if any. Does not
    add the receiver to newScore; just sets instance variable. It
    is illegal to remove an active performer.
    Here we have the classic retain cycle in that the MKPart is retained by
    it's MKScore (indirectly by MKScore retaining the NSArray of MKParts).
    The solution is that we don't retain the score. */
{
    id oldScore = score;
    if (score)
	[score removePart: self];
    score = newScore;
    return oldScore;
}

@end

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us