forked from flit/MidiKeys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAppController.m
1297 lines (1104 loc) · 36.3 KB
/
AppController.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
//
// AppController.m
// MidiKeys
//
// Created by Chris Reed on Tue Oct 15 2002.
// Copyright (c) 2002-2003 Chris Reed. All rights reserved.
//
#import "AppController.h"
#import "MidiKeyView.h"
#import "EndpointDefaults.h"
#import "ColourDefaults.h"
#import "KeyMapManager.h"
#import "MidiKeyMap.h"
#import "PreferencesController.h"
#import "MidiParser.h"
#import "OverlayIndicator.h"
#import <CoreAudio/HostTime.h>
#define MAX_OCTAVE_OFFSET (4)
#define MIN_OCTAVE_OFFSET (-4)
@interface AppController ()
- (void)setupRegisteredDefaults;
- (void)applicationWillFinishLaunching:(NSNotification *)notification;
- (void)applicationDidFinishLaunching:(NSNotification *)notification;
- (void)applicationWillTerminate:(NSNotification *)notification;
- (void)applicationDidBecomeActive:(NSNotification *)notification;
- (void)applicationDidResignActive:(NSNotification *)notification;
- (void)windowWillClose:(NSNotification *)notification;
- (BOOL)validateMenuItem:(NSMenuItem *)menuItem;
- (NSString *)uniqueTitle:(NSString *)title forMenu:(NSMenu *)menu;
- (void)updateDestinationMenu;
- (void)updateSourceMenu;
- (void)setWindowLevelFromPreferences;
- (void)preferencesDidChange:(NSNotification *)notification;
- (void)setClickThrough:(BOOL)clickThrough;
- (void)toggleMidiControls:(id)sender;
- (float)overlayTimeout;
- (void)overlayIndicatorDidClose:(OverlayIndicator *)theIndicator;
@end
@implementation AppController
- (void)dealloc
{
[_indicator close];
[keyMap release];
MIDIPortDispose(outputPort);
MIDIPortDispose(inputPort);
MIDIEndpointDispose(virtualSourceEndpoint);
MIDIClientDispose(clientRef);
[midiKeys setDelegate:nil]; // we're no longer valid
[super dealloc];
}
- (NSString *)uniqueTitle:(NSString *)title forMenu:(NSMenu *)menu
{
if ([menu itemWithTitle:title] == nil)
return title;
int n;
for (n=0;; ++n)
{
NSString *possibleTitle = [title stringByAppendingFormat:@" %d", n];
if ([menu itemWithTitle:possibleTitle] == nil)
return possibleTitle;
}
return nil;
}
- (void)updateDestinationMenu
{
// get our endpoint's uid
MIDIUniqueID selectedEndpointUID;
BOOL foundSelectedDestination = NO;
if (isDestinationConnected)
{
MIDIObjectGetIntegerProperty(selectedDestination, kMIDIPropertyUniqueID, &selectedEndpointUID);
}
// clean menu
[destinationPopup removeAllItems];
// insert the virtual source item
[destinationPopup addItemWithTitle:NSLocalizedString(@"Virtual source", @"Virtual source")];
if (!isDestinationConnected)
{
[destinationPopup selectItemAtIndex:0];
foundSelectedDestination = YES;
}
// now insert all available midi destinations
int i, numDevices = MIDIGetNumberOfDestinations();
// add a separator if there are any destinations
if (numDevices > 0)
[[destinationPopup menu] addItem:[NSMenuItem separatorItem]];
int iOffset = [destinationPopup numberOfItems];
for (i=iOffset; i<numDevices+iOffset; ++i) // so i is equal to the last menu item
{
MIDIUniqueID endpointUID;
MIDIEndpointRef theEndpoint = MIDIGetDestination(i - iOffset);
MIDIObjectGetIntegerProperty(theEndpoint, kMIDIPropertyUniqueID, &endpointUID);
// find a unique menu item name for the endpoint. it's possible that
// two or more endpoints end up with the same name through our formatting,
// so check the menu before trying to add the new item.
NSString *endpointTitle = [self uniqueTitle:[self nameForMidiEndpoint:theEndpoint] forMenu:[destinationPopup menu]];
[destinationPopup addItemWithTitle:endpointTitle];
[[destinationPopup itemAtIndex:i] setRepresentedObject:[NSData dataWithBytes:&theEndpoint length:sizeof theEndpoint]];
// if this endpoint matches the currently selected one, set the popup's selection
if (isDestinationConnected && endpointUID == selectedEndpointUID && !foundSelectedDestination)
{
[destinationPopup selectItemAtIndex:i];
foundSelectedDestination = YES;
}
}
// the selected destination went away!
if (!foundSelectedDestination && isDestinationConnected)
{
// go back to the virtual source
[destinationPopup selectItemAtIndex:0];
isDestinationConnected = NO;
}
}
- (void)updateSourceMenu
{
// find selected source's uid
MIDIUniqueID selectedEndpointUID;
if (isSourceConnected)
{
MIDIObjectGetIntegerProperty(selectedSource, kMIDIPropertyUniqueID, &selectedEndpointUID);
}
BOOL foundSelectedSource = NO;
// clean menu
[sourcePopup removeAllItems];
[sourcePopup setEnabled:YES];
[sourcePopup addItemWithTitle:NSLocalizedString(@"None", @"None")];
[[sourcePopup menu] addItem:[NSMenuItem separatorItem]];
// fill in menu with available sources
int i, numDevices = MIDIGetNumberOfSources();
for (i=0; i<numDevices; ++i)
{
MIDIUniqueID endpointUID;
MIDIEndpointRef theEndpoint = MIDIGetSource(i);
MIDIObjectGetIntegerProperty(theEndpoint, kMIDIPropertyUniqueID, &endpointUID);
// don't show our own virtual source
if (endpointUID == virtualSourceUID)
continue;
NSString *endpointTitle = [self uniqueTitle:[self nameForMidiEndpoint:theEndpoint] forMenu:[sourcePopup menu]];
[sourcePopup addItemWithTitle:endpointTitle];
int itemIndex = [sourcePopup numberOfItems] - 1; // the last item in the menu
[[sourcePopup itemAtIndex:itemIndex] setRepresentedObject:[NSData dataWithBytes:&theEndpoint length:sizeof theEndpoint]];
// if this endpoint matches the currently selected one, set the popup's selection
if (isSourceConnected && endpointUID == selectedEndpointUID && !foundSelectedSource)
{
[sourcePopup selectItemAtIndex:itemIndex];
foundSelectedSource = YES;
}
}
// handle empty source menu
if ([sourcePopup numberOfItems] == 2) // just None and separator
{
// disable menu, but make the None item show as selected
[sourcePopup setEnabled:NO];
[sourcePopup selectItemAtIndex:0];
isSourceConnected = NO;
// also disable the midi thru checkbox
[midiThruCheckbox setEnabled:NO];
}
else if (isSourceConnected && !foundSelectedSource)
{
// if we couldn't find the connected source, select the first one
[sourcePopup selectItemAtIndex:0];
[self sourceSelected:nil];
// also disable the midi thru checkbox
[midiThruCheckbox setEnabled:NO];
}
else
{
// there was a selected item so enable the midi thru checkbox
[midiThruCheckbox setEnabled:isSourceConnected];
}
}
- (void)setupRegisteredDefaults
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// Build up the registered defaults dictionary.
NSDictionary * defaultsDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
// [NSColor /*colorWithCalibratedRed:kDefaultHighlightRed green:kDefaultHighlightGreen blue:kDefaultHighlightBlue alpha:1.0*/ greenColor], kHighlightColourPrefKey,
[NSNumber numberWithFloat:(maxVelocity * 3.0 / 4.0)], kVelocityPrefKey, // 3/4 max velocity
[NSNumber numberWithInt:1], kChannelPrefKey,
[NSNumber numberWithInt:0], kOctaveOffsetPrefKey,
[NSNumber numberWithFloat:kDefaultWindowTransparency], kWindowTransparencyPrefKey,
[NSNumber numberWithInt:0], kHotKeysModifiersPrefKey,
[NSNumber numberWithBool:NO], kUseHotKeysPrefKey,
[NSNumber numberWithFloat:kDefaultVelocityHotKeyDelta], kVelocityHotKeyDeltaPrefKey,
[NSNumber numberWithFloat:kDefaultVelocityRepeatInterval], kVelocityRepeatIntervalPrefKey,
[NSNumber numberWithFloat:1.0], kOverlayTimeoutPrefKey,
[NSNumber numberWithBool:YES], SHOW_HOT_KEYS_OVERLAYS_PREF_KEY,
[NSNumber numberWithBool:YES], SHOW_OCTAVE_SHIFT_OVERLAYS_PREF_KEY,
[NSNumber numberWithBool:YES], SHOW_VELOCITY_OVERLAYS_PREF_KEY,
[NSNumber numberWithBool:YES], kShowKeyCapsPrefKey,
nil, nil];
[defaults registerDefaults:defaultsDefaults];
}
- (void)awakeFromNib
{
// Need to tell Cocoa that we want to support alpha in colors.
[NSColor setIgnoresAlpha:NO];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// Build up the registered defaults dictionary.
maxVelocity = [velocitySlider maxValue];
[self setupRegisteredDefaults];
// set up midi
MIDIClientCreate(kMyClientName, MyNotifyProc, (void *)self, &clientRef);
MIDIOutputPortCreate(clientRef, kMyClientName, &outputPort);
MIDIInputPortCreate(clientRef, kMyClientName, MyMidiReadProc, self, &inputPort);
MIDISourceCreate(clientRef, kMyClientName, &virtualSourceEndpoint);
// get the uid of our virtual source
MIDIObjectGetIntegerProperty(virtualSourceEndpoint, kMIDIPropertyUniqueID, &virtualSourceUID);
// MIDI thru
performMidiThru = [defaults boolForKey:kMidiThruPrefKey];
if (performMidiThru)
{
[midiThruCheckbox setIntValue:1];
}
// read selected destination and source from prefs
selectedDestination = [defaults endpointForKey:kDestinationPrefKey];
if (selectedDestination)
{
isDestinationConnected = YES;
}
selectedSource = [defaults endpointForKey:kSourcePrefKey];
if (selectedSource)
{
// if connecting the source fails, fall back to our virtual source
OSStatus err = MIDIPortConnectSource(inputPort, selectedSource, 0);
if (err == noErr)
{
isSourceConnected = YES;
}
else
{
selectedSource = 0;
}
}
// fill in popup menus
[self updateDestinationMenu];
[self updateSourceMenu];
// set up the keys view
[midiKeys setDelegate:self];
NSColor *highlightColour = [defaults colorForKey:kHighlightColourPrefKey];
if (!highlightColour)
{
highlightColour = [NSColor colorWithCalibratedRed:kDefaultHighlightRed green:kDefaultHighlightGreen blue:kDefaultHighlightBlue alpha:kDefaultHighlightTransparency];
[defaults setColor:highlightColour forKey:kHighlightColourPrefKey];
}
[midiKeys setHighlightColour:highlightColour];
[midiKeys setShowKeycaps:[defaults boolForKey:kShowKeyCapsPrefKey]];
// set current velocity and channel
currentVelocity = [defaults floatForKey:kVelocityPrefKey];
[velocitySlider setFloatValue:currentVelocity];
currentChannel = [defaults integerForKey:kChannelPrefKey];
[channelPopup selectItemWithTag:currentChannel - 1];
octaveOffset = [defaults integerForKey:kOctaveOffsetPrefKey];
[midiKeys setOctaveOffset:octaveOffset];
// set up the midi keys window
[[midiKeys window] setDelegate:self];
[[midiKeys window] setHidesOnDeactivate:NO];
[[[midiKeys window] standardWindowButton:NSWindowMiniaturizeButton] setEnabled:YES];
float windowTransparency = [defaults floatForKey:kWindowTransparencyPrefKey];
// but don't actually set the window transparency if we're active (which we probably are at this time)
if (!(makeWindowSolidWhenOnTop && [NSApp isActive]))
{
[[midiKeys window] setAlphaValue:windowTransparency];
}
[self setWindowLevelFromPreferences];
// toggled pref
BOOL toggledPref = [defaults boolForKey:kIsWindowToggledPrefKey];
if (toggledPref)
{
[self toggleMidiControls:nil];
}
makeWindowSolidWhenOnTop = [defaults boolForKey:kSolidOnTopPrefKey];
}
//! Finish the initialization that needs to be done after all the
//! -awakeFromNib calls have been made.
- (void)applicationWillFinishLaunching:(NSNotification *)notification
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// create our key map object
NSString *selectedKeyMap = [defaults stringForKey:kKeyMapPrefKey];
if (!selectedKeyMap)
{
// no keymap preference, so select the first one and save it
selectedKeyMap = [[keyMapManager allKeyMapNames] objectAtIndex:0];
[defaults setObject:selectedKeyMap forKey:kKeyMapPrefKey];
}
keyMap = [[keyMapManager keyMapWithName:selectedKeyMap] retain];
// now, with the keymap ready we can enable hotkeys
[self registerToggleHotKey];
if ([defaults boolForKey:kUseHotKeysPrefKey])
{
[self enableHotKeys];
}
// we're finally ready to show the window
[[midiKeys window] setIsVisible:YES];
}
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
// If hot keys are on by default, show the hot keys enabled overlay.
if ([[NSUserDefaults standardUserDefaults] boolForKey:kUseHotKeysPrefKey])
{
[self displayHotKeysOverlay];
}
}
- (void)applicationWillTerminate:(NSNotification *)notification
{
// remove hotkeys just to be safe
if (hotKeysAreRegistered)
{
[keyMap unregisterHotKeys];
[self unregisterOctaveHotKeys];
}
[self unregisterToggleHotKey];
[velocityHotKeyTimer invalidate];
}
//! @brief The application has become the frontmost app.
- (void)applicationDidBecomeActive:(NSNotification *)notification
{
if (makeWindowSolidWhenOnTop)
{
[[midiKeys window] setAlphaValue:1.0];
}
BOOL clickThrough = [[NSUserDefaults standardUserDefaults] boolForKey:kClickThroughPrefKey];
if (clickThrough)
{
[self setClickThrough:NO];
}
// We set the keyboard window to the normal window level so that the preferences window can
// be ordered in front of it when it's open. If the keyboard window was left floating, then
// the prefs window could be obscured by the keyboard.
NSWindow *mainWindow = [midiKeys window];
[mainWindow setLevel:NSNormalWindowLevel];
}
//! @brief Another application has become the frontmost application.
- (void)applicationDidResignActive:(NSNotification *)notification
{
if (makeWindowSolidWhenOnTop)
{
[[midiKeys window] setAlphaValue:[[NSUserDefaults standardUserDefaults] floatForKey:kWindowTransparencyPrefKey]];
}
BOOL clickThrough = [[NSUserDefaults standardUserDefaults] boolForKey:kClickThroughPrefKey];
if (clickThrough)
{
[self setClickThrough:YES];
}
// Here we set the keyboard window's window level to either normal or floating, depending
// on the preferences. This ensures that the keyboard will float above other windows while
// we're in the background (if that pref is set).
[self setWindowLevelFromPreferences];
}
//! Closing the window quits the application.
//!
- (void)windowWillClose:(NSNotification *)notification
{
[[NSApplication sharedApplication] terminate:self];
}
- (BOOL)validateMenuItem:(NSMenuItem *)menuItem
{
if ([[menuItem title] isEqualToString:NSLocalizedString(@"Octave Up", @"Octave Up")])
{
return octaveOffset < MAX_OCTAVE_OFFSET;
}
else if ([[menuItem title] isEqualToString:NSLocalizedString(@"Octave Down", @"Octave Down")])
{
return octaveOffset > MIN_OCTAVE_OFFSET;
}
return YES;
}
- (IBAction)destinationSelected:(id)sender
{
// handle virtual source being selected
if ([destinationPopup indexOfSelectedItem] == 0)
{
isDestinationConnected = NO;
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:kDestinationPrefKey];
return;
}
// other endpoint was selected
const MIDIEndpointRef *sourcePtr = (const MIDIEndpointRef *)[[[destinationPopup selectedItem] representedObject] bytes];
if (sourcePtr == NULL)
return;
selectedDestination = *sourcePtr;
isDestinationConnected = YES;
// save destination in prefs
[[NSUserDefaults standardUserDefaults] setEndpoint:selectedDestination forKey:kDestinationPrefKey];
}
- (IBAction)sourceSelected:(id)sender
{
// disconnect previous source
OSStatus err;
if (isSourceConnected)
{
err = MIDIPortDisconnectSource(inputPort, selectedSource);
if (err)
NSLog(@"error disconnecting previous source from input port: %d", err);
}
id sourceObject = [[sourcePopup selectedItem] representedObject];
if (sourceObject == nil)
{
// the None item
[midiThruCheckbox setEnabled:NO];
isSourceConnected = NO;
selectedSource = 0;
// get rid of the source preference
[[NSUserDefaults standardUserDefaults] removeObjectForKey:kSourcePrefKey];
return;
}
const MIDIEndpointRef *sourcePtr = (const MIDIEndpointRef *)[sourceObject bytes];
if (sourcePtr == NULL)
return;
selectedSource = *sourcePtr;
err = MIDIPortConnectSource(inputPort, selectedSource, 0);
if (err)
return;
isSourceConnected = YES;
// make sure the thru checkbox is enabled
[midiThruCheckbox setEnabled:YES];
// save destination in prefs
[[NSUserDefaults standardUserDefaults] setEndpoint:selectedSource forKey:kSourcePrefKey];
}
- (IBAction)velocitySliderChanged:(id)sender
{
currentVelocity = [velocitySlider floatValue];
// we don't want to ever actually play a velocity of 0
if (currentVelocity == 0.0)
currentVelocity = 1.0;
// and setting the velocity in prefs to 0 will reset it to 3/4 on restart
[[NSUserDefaults standardUserDefaults] setFloat:currentVelocity forKey:kVelocityPrefKey];
}
- (IBAction)channelDidChange:(id)sender
{
currentChannel = [channelPopup selectedTag] + 1;
[[NSUserDefaults standardUserDefaults] setInteger:currentChannel forKey:kChannelPrefKey];
}
- (IBAction)toggleMidiThru:(id)sender
{
performMidiThru = !performMidiThru;
[midiThruCheckbox setIntValue:performMidiThru];
// save preference
[[NSUserDefaults standardUserDefaults] setBool:performMidiThru forKey:kMidiThruPrefKey];
}
- (float)overlayTimeout
{
return [[NSUserDefaults standardUserDefaults] floatForKey:kOverlayTimeoutPrefKey];
}
- (void)overlayIndicatorDidClose:(OverlayIndicator *)theIndicator
{
if (_indicator == theIndicator)
{
_indicator = nil;
}
}
- (IBAction)octaveUp:(id)sender
{
if (octaveOffset < MAX_OCTAVE_OFFSET)
{
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
octaveOffset++;
[defaults setInteger:octaveOffset forKey:kOctaveOffsetPrefKey];
[midiKeys setOctaveOffset:octaveOffset];
if ([defaults boolForKey:SHOW_OCTAVE_SHIFT_OVERLAYS_PREF_KEY])
{
[_indicator close];
_indicator = [[OverlayIndicator alloc] initWithImage:[NSImage imageNamed:kOctaveUpOverlayImage]];
[_indicator setMessage:NSLocalizedString(@"Octave Up", nil)];
[_indicator setDelegate:self];
[_indicator showUntilDate:[NSDate dateWithTimeIntervalSinceNow:[self overlayTimeout]]];
}
}
}
- (IBAction)octaveDown:(id)sender
{
if (octaveOffset > MIN_OCTAVE_OFFSET)
{
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
octaveOffset--;
[defaults setInteger:octaveOffset forKey:kOctaveOffsetPrefKey];
[midiKeys setOctaveOffset:octaveOffset];
if ([defaults boolForKey:SHOW_OCTAVE_SHIFT_OVERLAYS_PREF_KEY])
{
[_indicator close];
_indicator = [[OverlayIndicator alloc] initWithImage:[NSImage imageNamed:kOctaveDownOverlayImage]];
[_indicator setMessage:NSLocalizedString(@"Octave Down", nil)];
[_indicator setDelegate:self];
[_indicator showUntilDate:[NSDate dateWithTimeIntervalSinceNow:[self overlayTimeout]]];
}
}
}
- (void)setWindowLevelFromPreferences
{
int level;
if ([[NSUserDefaults standardUserDefaults] boolForKey:kFloatWindowPrefKey])
{
level = NSModalPanelWindowLevel;
}
else
{
level = NSNormalWindowLevel;
}
[[midiKeys window] setLevel:level];
}
//! The prefs controller sends this when the prefs panel is closed.
//!
- (void)preferencesDidChange:(NSNotification *)notification
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// change window preferences
makeWindowSolidWhenOnTop = [defaults boolForKey:kSolidOnTopPrefKey];
[self setWindowLevelFromPreferences];
if (!(makeWindowSolidWhenOnTop && [NSApp isActive]))
{
[[midiKeys window] setAlphaValue:[defaults floatForKey:kWindowTransparencyPrefKey]];
}
else if (makeWindowSolidWhenOnTop && [NSApp isActive])
{
[[midiKeys window] setAlphaValue:1.0f];
}
// update key caps
[midiKeys setShowKeycaps:[defaults boolForKey:kShowKeyCapsPrefKey]];
// reload key map
[keyMap release]; // will unregister this keymaps hotkeys
keyMap = [[keyMapManager keyMapWithName:[defaults stringForKey:kKeyMapPrefKey]] retain];
[midiKeys setNeedsDisplay:YES]; // redraw midi keys
// Re-register hotkeys.
[self unregisterToggleHotKey];
[self registerToggleHotKey];
if (hotKeysAreRegistered)
{
[self unregisterOctaveHotKeys];
}
if ([defaults boolForKey:kUseHotKeysPrefKey])
{
[self enableHotKeys];
}
// highlight colour
NSColor *highlightColour = [defaults colorForKey:kHighlightColourPrefKey];
[midiKeys setHighlightColour:highlightColour];
}
- (void)setClickThrough:(BOOL)clickThrough
{
NSWindow *mainWindow = [midiKeys window];
// carbon
void *ref = [mainWindow windowRef];
if (clickThrough)
{
ChangeWindowAttributes(ref, kWindowIgnoreClicksAttribute, kWindowNoAttributes);
}
else
{
ChangeWindowAttributes(ref, kWindowNoAttributes, kWindowIgnoreClicksAttribute);
}
// cocoa
[mainWindow setIgnoresMouseEvents:clickThrough];
}
- (IBAction)toggleMidiControls:(id)sender
{
// resize window
NSWindow *window = [toggleView window];
NSRect newFrame = [window frame];
NSPoint newOrigin = [hiddenItemsView frame].origin;
if (isWindowToggled)
{
// move items back into place first, so they appear as the window
// is animated
newOrigin.x = 0;
[hiddenItemsView setFrameOrigin:newOrigin];
// increase window size
newFrame.size.height += toggleDelta;
[window setFrame:newFrame display:YES animate:YES];
isWindowToggled = NO;
}
else
{
// shrink window size
toggleDelta = NSHeight([[window contentView] frame]) - NSHeight([toggleView frame]);
newFrame.size.height -= toggleDelta;
[window setFrame:newFrame display:YES animate:YES];
// move items out of the way so they don't interfere with the title
// bar when used for dragging (they will trap clicks in the title)
newOrigin.x = NSWidth([window frame]);
[hiddenItemsView setFrameOrigin:newOrigin];
isWindowToggled = YES;
}
// save toggle preference
[[NSUserDefaults standardUserDefaults] setBool:isWindowToggled forKey:kIsWindowToggledPrefKey];
}
@end
@implementation AppController (HotKeys)
- (IBAction)toggleHotKeys:(id)sender
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// Enable or disable hot keys.
BOOL isActive = [defaults boolForKey:kUseHotKeysPrefKey];
if (isActive)
{
[self disableHotKeys];
}
else
{
[self enableHotKeys];
}
// Toggle defaults setting.
[defaults setBool:!isActive forKey:kUseHotKeysPrefKey];
}
//! @brief Enables hot keys and updates UI to match.
- (void)enableHotKeys
{
[self registerHotKeys];
// Put a check mark on the hot keys menu item.
[_toggleHotKeysMenuItem setState:NSOnState];
// Add a status item indicating that hot keys are currently enabled.
// NSStatusBar * bar = [NSStatusBar systemStatusBar];
// NSImage * statusImage = [NSImage imageNamed:@"RemoveShortcutPressed.tif"];
// _hotKeysStatusItem = [[bar statusItemWithLength:[statusImage size].width + 10.0] retain];
// [_hotKeysStatusItem setImage:statusImage];
// [_hotKeysStatusItem setToolTip:@"MidiKeys hot keys are enabled."];
// [_hotKeysStatusItem setTarget:self];
// [_hotKeysStatusItem setAction:@selector(toggleHotKeys:)];
// Set a badge on the app icon in the dock.
[[NSApp dockTile] setBadgeLabel:NSLocalizedString(@"HotKeyDockBadge", nil)];
}
//! @brief Disables hot keys are updates the UI to match.
- (void)disableHotKeys
{
// Unregister hot keys.
[self unregisterHotKeys];
// Remove the check mark from the hot keys menu item.
[_toggleHotKeysMenuItem setState:NSOffState];
// Remove the status item.
// if (_hotKeysStatusItem)
// {
// [[NSStatusBar systemStatusBar] removeStatusItem:_hotKeysStatusItem];
// [_hotKeysStatusItem release];
// _hotKeysStatusItem = nil;
// }
// Clear the app icon badge.
[[NSApp dockTile] setBadgeLabel:nil];
}
- (void)registerToggleHotKey
{
// Read the toggle hot key info from preferences.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary * toggleDict = [defaults dictionaryForKey:kToggleHotKeysShortcutPrefKey];
if (!toggleDict)
{
return;
}
int modifiers = [[toggleDict objectForKey:SHORTCUT_FLAGS_KEY] intValue];
int keycode = [[toggleDict objectForKey:SHORTCUT_KEYCODE_KEY] intValue];
EventHotKeyID hotKeyID = { 0, 0 };
OSStatus err = RegisterEventHotKey(keycode, modifiers, hotKeyID, GetApplicationEventTarget(), 0, &_toggleHotKeyRef);
if (err)
{
NSLog(@"unable to register toggle hot key shortcut (err=%d)", err);
}
}
- (void)unregisterToggleHotKey
{
if (_toggleHotKeyRef)
{
UnregisterEventHotKey(_toggleHotKeyRef);
_toggleHotKeyRef = NULL;
}
}
- (void)registerHotKeys
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// Get the modifier key.
int modifiers = [defaults integerForKey:kHotKeysModifiersPrefKey];
// Register both note keys and control keys.
[keyMap registerHotKeysWithModifiers:modifiers];
[self registerOctaveHotKeysWithModifiers:modifiers];
}
- (void)unregisterHotKeys
{
[self unregisterOctaveHotKeys];
[keyMap unregisterHotKeys];
}
- (void)registerOctaveHotKeysWithModifiers:(int)modifiers
{
OSStatus err1, err2, err3, err4;
EventHotKeyID hotKeyID = { 0, 0 };
// unregister previous hot keys if present, otherwise registering will fail
[self unregisterOctaveHotKeys];
err1 = RegisterEventHotKey(kRightArrowKeycode, modifiers, hotKeyID, GetApplicationEventTarget(), 0, &octaveUpHotKeyRef);
if (err1)
NSLog(@"octave up hot key could not be registered (err = %d)", err1);
err2 = RegisterEventHotKey(kLeftArrowKeycode, modifiers, hotKeyID, GetApplicationEventTarget(), 0, &octaveDownHotKeyRef);
if (err2)
NSLog(@"octave down hot key could not be registered (err = %d)", err2);
err3 = RegisterEventHotKey(kUpArrowKeycode, modifiers, hotKeyID, GetApplicationEventTarget(), 0, &velocityUpHotKeyRef);
if (err3)
NSLog(@"velocity up hot key could not be registered (err = %d)", err3);
err4 = RegisterEventHotKey(kDownArrowKeycode, modifiers, hotKeyID, GetApplicationEventTarget(), 0, &velocityDownHotKeyRef);
if (err4)
NSLog(@"velocity down hot key could not be registered (err = %d)", err4);
// only mark hot keys as registered if one of the keys was actually registered
if (err1 == noErr || err2 == noErr || err3 == noErr || err4 == noErr)
hotKeysAreRegistered = YES;
}
- (void)unregisterOctaveHotKeys
{
if (octaveUpHotKeyRef)
{
UnregisterEventHotKey(octaveUpHotKeyRef);
octaveUpHotKeyRef = NULL;
}
if (octaveDownHotKeyRef)
{
UnregisterEventHotKey(octaveDownHotKeyRef);
octaveDownHotKeyRef = NULL;
}
if (velocityUpHotKeyRef)
{
UnregisterEventHotKey(velocityUpHotKeyRef);
velocityUpHotKeyRef = NULL;
}
if (velocityDownHotKeyRef)
{
UnregisterEventHotKey(velocityDownHotKeyRef);
velocityDownHotKeyRef = NULL;
}
hotKeysAreRegistered = NO;
}
- (void)handleVelocityKeyPressedUpOrDown:(int)upOrDown
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
float delta = [defaults floatForKey:kVelocityHotKeyDeltaPrefKey];
// invert delta for down
if (upOrDown == kVelocityDown)
{
delta *= -1.0;
}
[self adjustVelocity:delta];
float interval = [defaults floatForKey:kVelocityRepeatIntervalPrefKey];
// If we receive another velocity hot key down message before the
// key up message, kill any previous timer.
if (velocityHotKeyTimer)
{
[velocityHotKeyTimer invalidate];
}
velocityHotKeyTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(velocityHotKeyTimerFired:) userInfo:[NSMutableDictionary dictionaryWithObject:[NSNumber numberWithFloat:delta] forKey:@"Delta"] repeats:YES];
}
- (void)velocityHotKeyTimerFired:(NSTimer *)timer
{
float delta = [[[timer userInfo] objectForKey:@"Delta"] floatValue];
[self adjustVelocity:delta];
// Increment delta every time the timer fires
delta *= 1.3f;
[[timer userInfo] setObject:[NSNumber numberWithFloat:delta] forKey:@"Delta"];
}
- (void)handleVelocityKeyReleased
{
[velocityHotKeyTimer invalidate];
velocityHotKeyTimer = nil;
}
//! @brief Present the hot keys enabled/disabled notification overlay.
//!
//! Whether the message says "Enabled" or "Disabled" depends on the current state of the @a
//! #hotKeysAreRegistered member variable, with true causing the message to say "Enabled".
//! This means that this method should be called after changing the hot keys state.
- (void)displayHotKeysOverlay
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:SHOW_HOT_KEYS_OVERLAYS_PREF_KEY])
{
[_indicator close];
_indicator = [[OverlayIndicator alloc] initWithImage:[NSImage imageNamed:@"Octave.png"]];
[_indicator setMessage:hotKeysAreRegistered ? NSLocalizedString(@"Hot Keys Enabled", nil) : NSLocalizedString(@"Hot Keys Disabled", nil)];
[_indicator setDelegate:self];
[_indicator showUntilDate:[NSDate dateWithTimeIntervalSinceNow:[self overlayTimeout]]];
}
}
//! @brief Handle a hot key event.
- (void)hotKeyPressed:(UInt32)identifier
{
if (identifier == (UInt32)_toggleHotKeyRef)
{
[self toggleHotKeys:self];
// Show an overlay indicator to tell the user that hot keys were toggled.
// This isn't done in toggleHotKeys because we only want to show the overlay
// in response to the toggle hot key itself, not the hot keys menu item.
[self displayHotKeysOverlay];
}
else if (identifier == (UInt32)octaveUpHotKeyRef)
{
[self octaveUp:nil];
}
else if (identifier == (UInt32)octaveDownHotKeyRef)
{
[self octaveDown:nil];
}
else if (identifier == (UInt32)velocityUpHotKeyRef)
{
[self handleVelocityKeyPressedUpOrDown:kVelocityUp];
}
else if (identifier == (UInt32)velocityDownHotKeyRef)
{
[self handleVelocityKeyPressedUpOrDown:kVelocityDown];
}
else
{
// look up note number
int midiNote = [keyMap midiNoteForHotKeyWithIdentifier:identifier] + octaveOffset * 12;
// send the note
int channel = currentChannel - 1;
int velocity = (unsigned char)(0x7f * currentVelocity / maxVelocity);
[self sendMidiNote:midiNote channel:channel velocity:velocity];
// update the key view
[midiKeys turnMidiNoteOn:midiNote];
}
}
- (void)hotKeyReleased:(UInt32)identifier
{
if (identifier == (UInt32)octaveUpHotKeyRef || identifier == (UInt32)octaveDownHotKeyRef)
{
// do nothing
}
else if (identifier == (UInt32)velocityUpHotKeyRef)
{
[self handleVelocityKeyReleased];
}
else if (identifier == (UInt32)velocityDownHotKeyRef)
{
[self handleVelocityKeyReleased];
}
else
{
// look up note number
int midiNote = [keyMap midiNoteForHotKeyWithIdentifier:identifier] + octaveOffset * 12;
// send the note
int channel = currentChannel - 1;
[self sendMidiNote:midiNote channel:channel velocity:0];
// update the key view
[midiKeys turnMidiNoteOff:midiNote];
}