Make Carbon GUI support for AU's optional at compile time (from Robin)
[ardour.git] / gtk2_ardour / au_pluginui.mm
1 #include <gtkmm/stock.h>
2
3 #undef  Marker
4 #define Marker FuckYouAppleAndYourLackOfNameSpaces
5
6 #include "pbd/convert.h"
7 #include "pbd/error.h"
8
9 #include "ardour/audio_unit.h"
10 #include "ardour/debug.h"
11 #include "ardour/plugin_insert.h"
12
13 #undef check // stupid gtk, stupid apple
14
15 #include <gtkmm/button.h>
16 #include <gdk/gdkquartz.h>
17
18 #include <gtkmm2ext/utils.h>
19
20 #include "au_pluginui.h"
21 #include "gui_thread.h"
22
23 #include "appleutility/CAAudioUnit.h"
24 #include "appleutility/CAComponent.h"
25
26 #import <AudioUnit/AUCocoaUIView.h>
27 #import <CoreAudioKit/AUGenericView.h>
28
29 #undef Marker
30
31 #include "keyboard.h"
32 #include "utils.h"
33 #include "public_editor.h"
34 #include "i18n.h"
35
36 using namespace ARDOUR;
37 using namespace Gtk;
38 using namespace Gtkmm2ext;
39 using namespace sigc;
40 using namespace std;
41 using namespace PBD;
42
43 vector<string> AUPluginUI::automation_mode_strings;
44
45 static const gchar* _automation_mode_strings[] = {
46         X_("Manual"),
47         X_("Play"),
48         X_("Write"),
49         X_("Touch"),
50         0
51 };
52
53 @implementation NotificationObject
54
55 - (NotificationObject*) initWithPluginUI: (AUPluginUI*) apluginui andCocoaParent: (NSWindow*) cp andTopLevelParent: (NSWindow*) tlp
56 {
57         self = [ super init ];
58
59         if (self) {
60                 plugin_ui = apluginui;
61                 cocoa_parent = cp;
62                 top_level_parent = tlp;
63
64                 [[NSNotificationCenter defaultCenter] addObserver:self
65                  selector:@selector(cocoaParentActivationHandler:)
66                  name:NSWindowDidBecomeMainNotification
67                  object:nil];
68
69                 [[NSNotificationCenter defaultCenter] addObserver:self
70                  selector:@selector(cocoaParentBecameKeyHandler:)
71                  name:NSWindowDidBecomeKeyNotification
72                  object:nil];
73         }
74
75         return self;
76 }
77                 
78 - (void)cocoaParentActivationHandler:(NSNotification *)notification
79 {
80         NSWindow* notification_window = (NSWindow *)[notification object];
81
82         if (top_level_parent == notification_window || cocoa_parent == notification_window) {
83                 if ([notification_window isMainWindow]) {
84                         plugin_ui->activate();
85                 } else {
86                         plugin_ui->deactivate();
87                 }
88         } 
89 }
90
91 - (void)cocoaParentBecameKeyHandler:(NSNotification *)notification
92 {
93         NSWindow* notification_window = (NSWindow *)[notification object];
94
95         if (top_level_parent == notification_window || cocoa_parent == notification_window) {
96                 if ([notification_window isKeyWindow]) {
97                         plugin_ui->activate();
98                 } else {
99                         plugin_ui->deactivate();
100                 }
101         } 
102 }
103
104 - (void)auViewResized:(NSNotification *)notification;
105 {
106         (void) notification;
107         plugin_ui->cocoa_view_resized();
108 }
109
110 @end
111
112 AUPluginUI::AUPluginUI (boost::shared_ptr<PluginInsert> insert)
113         : PlugUIBase (insert)
114         , automation_mode_label (_("Automation"))
115         , preset_label (_("Presets"))
116         
117 {
118         if (automation_mode_strings.empty()) {
119                 automation_mode_strings = I18N (_automation_mode_strings);
120         }
121         
122         set_popdown_strings (automation_mode_selector, automation_mode_strings);
123         automation_mode_selector.set_active_text (automation_mode_strings.front());
124
125         if ((au = boost::dynamic_pointer_cast<AUPlugin> (insert->plugin())) == 0) {
126                 error << _("unknown type of editor-supplying plugin (note: no AudioUnit support in this version of ardour)") << endmsg;
127                 throw failed_constructor ();
128         }
129
130         /* stuff some stuff into the top of the window */
131
132         HBox* smaller_hbox = manage (new HBox);
133
134         smaller_hbox->set_spacing (6);
135         smaller_hbox->pack_start (preset_label, false, false, 4);
136         smaller_hbox->pack_start (_preset_combo, false, false);
137         smaller_hbox->pack_start (save_button, false, false);
138 #if 0
139         /* one day these might be useful with an AU plugin, but not yet */
140         smaller_hbox->pack_start (automation_mode_label, false, false);
141         smaller_hbox->pack_start (automation_mode_selector, false, false);
142 #endif
143         smaller_hbox->pack_start (bypass_button, false, true);
144
145         VBox* v1_box = manage (new VBox);
146         VBox* v2_box = manage (new VBox);
147
148         v1_box->pack_start (*smaller_hbox, false, true);
149         v2_box->pack_start (focus_button, false, true);
150
151         top_box.set_homogeneous (false);
152         top_box.set_spacing (6);
153         top_box.set_border_width (6);
154
155         top_box.pack_end (*v2_box, false, false);
156         top_box.pack_end (*v1_box, false, false);
157
158         set_spacing (6);
159         pack_start (top_box, false, false);
160         pack_start (low_box, false, false);
161
162         preset_label.show ();
163         _preset_combo.show ();
164         automation_mode_label.show ();
165         automation_mode_selector.show ();
166         bypass_button.show ();
167         top_box.show ();
168         low_box.show ();
169
170         _activating_from_app = false;
171         cocoa_parent = 0;
172         _notify = 0;
173         cocoa_window = 0;
174         carbon_window = 0;
175         au_view = 0;
176         editView = 0;
177
178         /* prefer cocoa, fall back to cocoa, but use carbon if its there */
179
180         if (test_cocoa_view_support()) {
181                 create_cocoa_view ();
182 #ifdef WITH_CARBON
183         } else if (test_carbon_view_support()) {
184                 create_carbon_view ();
185 #endif
186         } else {
187                 create_cocoa_view ();
188         }
189
190         low_box.signal_realize().connect (mem_fun (this, &AUPluginUI::lower_box_realized));
191 }
192
193 AUPluginUI::~AUPluginUI ()
194 {
195         if (cocoa_parent) {
196                 NSWindow* win = get_nswindow();
197                 [[NSNotificationCenter defaultCenter] removeObserver:_notify];
198                 [win removeChildWindow:cocoa_parent];
199
200         } 
201
202 #ifdef WITH_CARBON
203         if (carbon_window) {
204                 /* not parented, just overlaid on top of our window */
205                 DisposeWindow (carbon_window);
206         }
207 #endif
208
209         if (editView) {
210                 CloseComponent (editView);
211         }
212
213         if (au_view) {
214                 /* remove whatever we packed into low_box so that GTK doesn't
215                    mess with it.
216                 */
217
218                 [au_view removeFromSuperview];
219         }
220 }
221
222 bool
223 AUPluginUI::test_carbon_view_support ()
224 {
225         bool ret = false;
226         
227         carbon_descriptor.componentType = kAudioUnitCarbonViewComponentType;
228         carbon_descriptor.componentSubType = 'gnrc';
229         carbon_descriptor.componentManufacturer = 'appl';
230         carbon_descriptor.componentFlags = 0;
231         carbon_descriptor.componentFlagsMask = 0;
232         
233         OSStatus err;
234
235         // ask the AU for its first editor component
236         UInt32 propertySize;
237         err = AudioUnitGetPropertyInfo(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, &propertySize, NULL);
238         if (!err) {
239                 int nEditors = propertySize / sizeof(ComponentDescription);
240                 ComponentDescription *editors = new ComponentDescription[nEditors];
241                 err = AudioUnitGetProperty(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, editors, &propertySize);
242                 if (!err) {
243                         // just pick the first one for now
244                         carbon_descriptor = editors[0];
245                         ret = true;
246                 }
247                 delete[] editors;
248         }
249
250         return ret;
251 }
252         
253 bool
254 AUPluginUI::test_cocoa_view_support ()
255 {
256         UInt32 dataSize   = 0;
257         Boolean isWritable = 0;
258         OSStatus err = AudioUnitGetPropertyInfo(*au->get_au(),
259                                                 kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
260                                                 0, &dataSize, &isWritable);
261         
262         return dataSize > 0 && err == noErr;
263 }
264
265 bool
266 AUPluginUI::plugin_class_valid (Class pluginClass)
267 {
268         if([pluginClass conformsToProtocol: @protocol(AUCocoaUIBase)]) {
269                 if([pluginClass instancesRespondToSelector: @selector(interfaceVersion)] &&
270                    [pluginClass instancesRespondToSelector: @selector(uiViewForAudioUnit:withSize:)]) {
271                                 return true;
272                 }
273         }
274         return false;
275 }
276
277 int
278 AUPluginUI::create_cocoa_view ()
279 {
280         BOOL wasAbleToLoadCustomView = NO;
281         AudioUnitCocoaViewInfo* cocoaViewInfo = NULL;
282         UInt32               numberOfClasses = 0;
283         UInt32     dataSize;
284         Boolean    isWritable;
285         NSString*           factoryClassName = 0;
286         NSURL*              CocoaViewBundlePath = NULL;
287
288         OSStatus result = AudioUnitGetPropertyInfo (*au->get_au(),
289                                                     kAudioUnitProperty_CocoaUI,
290                                                     kAudioUnitScope_Global, 
291                                                     0,
292                                                     &dataSize,
293                                                     &isWritable );
294
295         numberOfClasses = (dataSize - sizeof(CFURLRef)) / sizeof(CFStringRef);
296
297         // Does view have custom Cocoa UI?
298         
299         if ((result == noErr) && (numberOfClasses > 0) ) {
300
301                 DEBUG_TRACE(DEBUG::AudioUnits,
302                             string_compose ( "based on %1, there are %2 cocoa UI classes\n", dataSize, numberOfClasses));
303
304                 cocoaViewInfo = (AudioUnitCocoaViewInfo *)malloc(dataSize);
305                 if(AudioUnitGetProperty(*au->get_au(),
306                                         kAudioUnitProperty_CocoaUI,
307                                         kAudioUnitScope_Global,
308                                         0,
309                                         cocoaViewInfo,
310                                         &dataSize) == noErr) {
311
312                         CocoaViewBundlePath     = (NSURL *)cocoaViewInfo->mCocoaAUViewBundleLocation;
313                                 
314                         // we only take the first view in this example.
315                         factoryClassName        = (NSString *)cocoaViewInfo->mCocoaAUViewClass[0];
316                         
317                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("the factory name is %1 bundle is %2\n",
318                                                                         factoryClassName, CocoaViewBundlePath));
319
320                 } else {
321
322                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("No cocoaUI property cocoaViewInfo = %1\n", cocoaViewInfo));
323
324                         if (cocoaViewInfo != NULL) {
325                                 free (cocoaViewInfo);
326                                 cocoaViewInfo = NULL;
327                         }
328                 }
329         }
330
331         NSRect crect = { { 0, 0 }, { 1, 1} };
332
333         // [A] Show custom UI if view has it
334
335         if (CocoaViewBundlePath && factoryClassName) {
336                 NSBundle *viewBundle    = [NSBundle bundleWithPath:[CocoaViewBundlePath path]];
337
338                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("tried to create bundle, result = %1\n", viewBundle));
339
340                 if (viewBundle == nil) {
341                         error << _("AUPluginUI: error loading AU view's bundle") << endmsg;
342                         return -1;
343                 } else {
344                         Class factoryClass = [viewBundle classNamed:factoryClassName];
345                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("tried to create factory class, result = %1\n", factoryClass));
346                         if (!factoryClass) {
347                                 error << _("AUPluginUI: error getting AU view's factory class from bundle") << endmsg;
348                                 return -1;
349                         }
350                         
351                         // make sure 'factoryClass' implements the AUCocoaUIBase protocol
352                         if (!plugin_class_valid (factoryClass)) {
353                                 error << _("AUPluginUI: U view's factory class does not properly implement the AUCocoaUIBase protocol") << endmsg;
354                                 return -1;
355                         }
356                         // make a factory
357                         id factoryInstance = [[[factoryClass alloc] init] autorelease];
358                         if (factoryInstance == nil) {
359                                 error << _("AUPluginUI: Could not create an instance of the AU view factory") << endmsg;
360                                 return -1;
361                         }
362
363                         DEBUG_TRACE (DEBUG::AudioUnits, "got a factory instance\n");
364
365                         // make a view
366                         au_view = [factoryInstance uiViewForAudioUnit:*au->get_au() withSize:crect.size];
367
368                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("view created @ %1\n", au_view));
369                         
370                         // cleanup
371                         [CocoaViewBundlePath release];
372                         if (cocoaViewInfo) {
373                                 UInt32 i;
374                                 for (i = 0; i < numberOfClasses; i++)
375                                         CFRelease(cocoaViewInfo->mCocoaAUViewClass[i]);
376                                 
377                                 free (cocoaViewInfo);
378                         }
379                         wasAbleToLoadCustomView = YES;
380                 }
381         }
382
383         if (!wasAbleToLoadCustomView) {
384                 // load generic Cocoa view
385                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Loading generic view using %1 -> %2\n", au,
386                                                                 au->get_au()));
387                 au_view = [[AUGenericView alloc] initWithAudioUnit:*au->get_au()];
388                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("view created @ %1\n", au_view));
389                 [(AUGenericView *)au_view setShowsExpertParameters:YES];
390         }
391
392         // watch for size changes of the view
393
394          [[NSNotificationCenter defaultCenter] addObserver:_notify
395                selector:@selector(auViewResized:) name:NSWindowDidResizeNotification
396                object:au_view];
397
398         // Get the size of the new AU View's frame 
399         
400         NSRect packFrame;
401         packFrame = [au_view frame];
402         prefwidth = packFrame.size.width;
403         prefheight = packFrame.size.height;
404         low_box.set_size_request (prefwidth, prefheight);
405         
406         return 0;
407 }
408
409 void
410 AUPluginUI::cocoa_view_resized ()
411 {
412         NSRect packFrame = [au_view frame];
413 }
414
415 int
416 AUPluginUI::create_carbon_view ()
417 {
418 #ifdef WITH_CARBON
419         OSStatus err;
420         ControlRef root_control;
421
422         Component editComponent = FindNextComponent(NULL, &carbon_descriptor);
423         
424         OpenAComponent(editComponent, &editView);
425         if (!editView) {
426                 error << _("AU Carbon view: cannot open AU Component") << endmsg;
427                 return -1;
428         }
429         
430         Rect r = { 100, 100, 100, 100 };
431         WindowAttributes attr = WindowAttributes (kWindowStandardHandlerAttribute |
432                                                   kWindowCompositingAttribute|
433                                                   kWindowNoShadowAttribute|
434                                                   kWindowNoTitleBarAttribute);
435
436         if ((err = CreateNewWindow(kDocumentWindowClass, attr, &r, &carbon_window)) != noErr) {
437                 error << string_compose (_("AUPluginUI: cannot create carbon window (err: %1)"), err) << endmsg;
438                 CloseComponent (editView);
439                 return -1;
440         }
441         
442         if ((err = GetRootControl(carbon_window, &root_control)) != noErr) {
443                 error << string_compose (_("AUPlugin: cannot get root control of carbon window (err: %1)"), err) << endmsg;
444                 DisposeWindow (carbon_window);
445                 CloseComponent (editView);
446                 return -1;
447         }
448
449         ControlRef viewPane;
450         Float32Point location  = { 0.0, 0.0 };
451         Float32Point size = { 0.0, 0.0 } ;
452
453         if ((err = AudioUnitCarbonViewCreate (editView, *au->get_au(), carbon_window, root_control, &location, &size, &viewPane)) != noErr) {
454                 error << string_compose (_("AUPluginUI: cannot create carbon plugin view (err: %1)"), err) << endmsg;
455                 DisposeWindow (carbon_window);
456                 CloseComponent (editView);
457                 return -1;
458         }
459
460         // resize window
461
462         Rect bounds;
463         GetControlBounds(viewPane, &bounds);
464         size.x = bounds.right-bounds.left;
465         size.y = bounds.bottom-bounds.top;
466
467         prefwidth = (int) (size.x + 0.5);
468         prefheight = (int) (size.y + 0.5);
469
470         SizeWindow (carbon_window, prefwidth, prefheight,  true);
471         low_box.set_size_request (prefwidth, prefheight);
472
473         return 0;
474 #else
475         error << _("AU Carbon GUI is not supported.") << endmsg;
476         return -1;
477 #endif
478 }
479
480 NSWindow*
481 AUPluginUI::get_nswindow ()
482 {
483         Gtk::Container* toplevel = get_toplevel();
484
485         if (!toplevel || !toplevel->is_toplevel()) {
486                 error << _("AUPluginUI: no top level window!") << endmsg;
487                 return 0;
488         }
489
490         NSWindow* true_parent = gdk_quartz_window_get_nswindow (toplevel->get_window()->gobj());
491
492         if (!true_parent) {
493                 error << _("AUPluginUI: no top level window!") << endmsg;
494                 return 0;
495         }
496
497         return true_parent;
498 }
499
500 void
501 AUPluginUI::activate ()
502 {
503 #ifdef WITH_CARBON
504         ActivateWindow (carbon_window, TRUE);
505 #endif
506         // [cocoa_parent makeKeyAndOrderFront:nil];
507 }
508
509 void
510 AUPluginUI::deactivate ()
511 {
512 #ifdef WITH_CARBON
513         ActivateWindow (carbon_window, FALSE);
514 #endif
515 }
516
517 int
518 AUPluginUI::parent_carbon_window ()
519 {
520 #ifdef WITH_CARBON
521         NSWindow* win = get_nswindow ();
522         int x, y;
523
524         if (!win) {
525                 return -1;
526         }
527
528         Gtk::Container* toplevel = get_toplevel();
529
530         if (!toplevel || !toplevel->is_toplevel()) {
531                 error << _("AUPluginUI: no top level window!") << endmsg;
532                 return -1;
533         }
534         
535         toplevel->get_window()->get_root_origin (x, y);
536
537         /* compute how tall the title bar is, because we have to offset the position of the carbon window
538            by that much.
539         */
540
541         NSRect content_frame = [NSWindow contentRectForFrameRect:[win frame] styleMask:[win styleMask]];
542         NSRect wm_frame = [NSWindow frameRectForContentRect:content_frame styleMask:[win styleMask]];
543
544         int titlebar_height = wm_frame.size.height - content_frame.size.height;
545
546         int packing_extra = 6; // this is the total vertical packing in our top level window
547
548         MoveWindow (carbon_window, x, y + titlebar_height + top_box.get_height() + packing_extra, false);
549         ShowWindow (carbon_window);
550
551         // create the cocoa window for the carbon one and make it visible
552         cocoa_parent = [[NSWindow alloc] initWithWindowRef: carbon_window];
553
554         SetWindowActivationScope (carbon_window, kWindowActivationScopeNone);
555
556         _notify = [ [NotificationObject alloc] initWithPluginUI:this andCocoaParent:cocoa_parent andTopLevelParent:win ]; 
557
558         [win addChildWindow:cocoa_parent ordered:NSWindowAbove];
559
560         return 0;
561 #else
562         return -1;
563 #endif
564 }       
565
566 int
567 AUPluginUI::parent_cocoa_window ()
568 {
569         NSWindow* win = get_nswindow ();
570
571         if (!win) {
572                 return -1;
573         }
574
575         [win setAutodisplay:YES]; // turn of GTK stuff for this window
576
577         Gtk::Container* toplevel = get_toplevel();
578
579         if (!toplevel || !toplevel->is_toplevel()) {
580                 error << _("AUPluginUI: no top level window!") << endmsg;
581                 return -1;
582         }
583
584         NSView* view = gdk_quartz_window_get_nsview (get_toplevel()->get_window()->gobj());
585         GtkRequisition a = top_box.size_request ();
586
587         /* move the au_view down so that it doesn't overlap the top_box contents */
588
589         NSPoint origin = { 0, a.height };
590
591         [au_view setFrameOrigin:origin];
592         [view addSubview:au_view]; 
593
594         return 0;
595 }
596
597 static void
598 dump_view_tree (NSView* view, int depth)
599 {
600         NSArray* subviews = [view subviews];
601         unsigned long cnt = [subviews count];
602
603         for (int d = 0; d < depth; d++) {
604                 cerr << '\t';
605         }
606         cerr << " view @ " << view << endl;
607         
608         for (unsigned long i = 0; i < cnt; ++i) {
609                 NSView* subview = [subviews objectAtIndex:i];
610                 dump_view_tree (subview, depth+1);
611         }
612 }
613
614 void
615 AUPluginUI::forward_key_event (GdkEventKey* ev)
616 {
617         NSEvent* nsevent = gdk_quartz_event_get_nsevent ((GdkEvent*)ev);
618
619         if (au_view && nsevent) {
620
621                 /* filter on nsevent type here because GDK massages FlagsChanged
622                    messages into GDK_KEY_{PRESS,RELEASE} but Cocoa won't
623                    handle a FlagsChanged message as a keyDown or keyUp
624                 */
625
626                 if ([nsevent type] == NSKeyDown) {
627                         [[[au_view window] firstResponder] keyDown:nsevent];
628                 } else if ([nsevent type] == NSKeyUp) {
629                         [[[au_view window] firstResponder] keyUp:nsevent];
630                 } else if ([nsevent type] == NSFlagsChanged) {
631                         [[[au_view window] firstResponder] flagsChanged:nsevent];
632                 }
633         }
634 }
635
636 void
637 AUPluginUI::on_realize ()
638 {
639         VBox::on_realize ();
640
641         /* our windows should not have that resize indicator */
642
643         NSWindow* win = get_nswindow ();
644         if (win) {
645                 [win setShowsResizeIndicator:NO];
646         }
647 }
648
649 void
650 AUPluginUI::lower_box_realized ()
651 {
652         if (au_view) {
653                 parent_cocoa_window ();
654         } else if (carbon_window) {
655                 parent_carbon_window ();
656         }
657 }
658
659 bool
660 AUPluginUI::on_map_event (GdkEventAny*)
661 {
662         return false;
663 }
664
665 void
666 AUPluginUI::on_window_hide ()
667 {
668 #ifdef WITH_CARBON
669         if (carbon_window) {
670                 HideWindow (carbon_window);
671                 ActivateWindow (carbon_window, FALSE);
672         }
673 #endif
674
675         hide_all ();
676 }
677
678 bool
679 AUPluginUI::on_window_show (const string& /*title*/)
680 {
681         /* this is idempotent so just call it every time we show the window */
682
683         gtk_widget_realize (GTK_WIDGET(low_box.gobj()));
684
685         show_all ();
686
687 #ifdef WITH_CARBON
688         if (carbon_window) {
689                 ShowWindow (carbon_window);
690                 ActivateWindow (carbon_window, TRUE);
691         }
692 #endif
693
694         return true;
695 }
696
697 bool
698 AUPluginUI::start_updating (GdkEventAny*)
699 {
700         return false;
701 }
702
703 bool
704 AUPluginUI::stop_updating (GdkEventAny*)
705 {
706         return false;
707 }
708
709 PlugUIBase*
710 create_au_gui (boost::shared_ptr<PluginInsert> plugin_insert, VBox** box)
711 {
712         AUPluginUI* aup = new AUPluginUI (plugin_insert);
713         (*box) = aup;
714         return aup;
715 }
716
717 bool
718 AUPluginUI::on_focus_in_event (GdkEventFocus*)
719 {
720         //cerr << "au plugin focus in\n";
721         //Keyboard::magic_widget_grab_focus ();
722         return false;
723 }
724
725 bool
726 AUPluginUI::on_focus_out_event (GdkEventFocus*)
727 {
728         //cerr << "au plugin focus out\n";
729         //Keyboard::magic_widget_drop_focus ();
730         return false;
731 }
732