use DEBUG_TRACE for some AudioUnit GUI debugging
[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_box, 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         au_view = 0;
175         editView = 0;
176
177         /* prefer cocoa, fall back to cocoa, but use carbon if its there */
178
179         if (test_cocoa_view_support()) {
180                 create_cocoa_view ();
181         } else if (test_carbon_view_support()) {
182                 create_carbon_view ();
183         } else {
184                 create_cocoa_view ();
185         }
186
187         low_box.signal_realize().connect (mem_fun (this, &AUPluginUI::lower_box_realized));
188 }
189
190 AUPluginUI::~AUPluginUI ()
191 {
192         if (cocoa_parent) {
193                 NSWindow* win = get_nswindow();
194                 [[NSNotificationCenter defaultCenter] removeObserver:_notify];
195                 [win removeChildWindow:cocoa_parent];
196
197         } 
198
199         if (carbon_window) {
200                 /* not parented, just overlaid on top of our window */
201                 DisposeWindow (carbon_window);
202         }
203
204         if (editView) {
205                 CloseComponent (editView);
206         }
207
208         if (au_view) {
209                 /* remove whatever we packed into low_box so that GTK doesn't
210                    mess with it.
211                 */
212
213                 [au_view removeFromSuperview];
214         }
215 }
216
217 bool
218 AUPluginUI::test_carbon_view_support ()
219 {
220         bool ret = false;
221         
222         carbon_descriptor.componentType = kAudioUnitCarbonViewComponentType;
223         carbon_descriptor.componentSubType = 'gnrc';
224         carbon_descriptor.componentManufacturer = 'appl';
225         carbon_descriptor.componentFlags = 0;
226         carbon_descriptor.componentFlagsMask = 0;
227         
228         OSStatus err;
229
230         // ask the AU for its first editor component
231         UInt32 propertySize;
232         err = AudioUnitGetPropertyInfo(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, &propertySize, NULL);
233         if (!err) {
234                 int nEditors = propertySize / sizeof(ComponentDescription);
235                 ComponentDescription *editors = new ComponentDescription[nEditors];
236                 err = AudioUnitGetProperty(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, editors, &propertySize);
237                 if (!err) {
238                         // just pick the first one for now
239                         carbon_descriptor = editors[0];
240                         ret = true;
241                 }
242                 delete[] editors;
243         }
244
245         return ret;
246 }
247         
248 bool
249 AUPluginUI::test_cocoa_view_support ()
250 {
251         UInt32 dataSize   = 0;
252         Boolean isWritable = 0;
253         OSStatus err = AudioUnitGetPropertyInfo(*au->get_au(),
254                                                 kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
255                                                 0, &dataSize, &isWritable);
256         
257         return dataSize > 0 && err == noErr;
258 }
259
260 bool
261 AUPluginUI::plugin_class_valid (Class pluginClass)
262 {
263         if([pluginClass conformsToProtocol: @protocol(AUCocoaUIBase)]) {
264                 if([pluginClass instancesRespondToSelector: @selector(interfaceVersion)] &&
265                    [pluginClass instancesRespondToSelector: @selector(uiViewForAudioUnit:withSize:)]) {
266                                 return true;
267                 }
268         }
269         return false;
270 }
271
272 int
273 AUPluginUI::create_cocoa_view ()
274 {
275         BOOL wasAbleToLoadCustomView = NO;
276         AudioUnitCocoaViewInfo* cocoaViewInfo = NULL;
277         UInt32               numberOfClasses = 0;
278         UInt32     dataSize;
279         Boolean    isWritable;
280         NSString*           factoryClassName = 0;
281         NSURL*              CocoaViewBundlePath = NULL;
282
283         OSStatus result = AudioUnitGetPropertyInfo (*au->get_au(),
284                                                     kAudioUnitProperty_CocoaUI,
285                                                     kAudioUnitScope_Global, 
286                                                     0,
287                                                     &dataSize,
288                                                     &isWritable );
289
290         numberOfClasses = (dataSize - sizeof(CFURLRef)) / sizeof(CFStringRef);
291
292         // Does view have custom Cocoa UI?
293         
294         if ((result == noErr) && (numberOfClasses > 0) ) {
295
296                 DEBUG_TRACE(DEBUG::AudioUnits,
297                             string_compose ( "based on %1, there are %2 cocoa UI classes\n", dataSize, numberOfClasses));
298
299                 cocoaViewInfo = (AudioUnitCocoaViewInfo *)malloc(dataSize);
300                 if(AudioUnitGetProperty(*au->get_au(),
301                                         kAudioUnitProperty_CocoaUI,
302                                         kAudioUnitScope_Global,
303                                         0,
304                                         cocoaViewInfo,
305                                         &dataSize) == noErr) {
306
307                         CocoaViewBundlePath     = (NSURL *)cocoaViewInfo->mCocoaAUViewBundleLocation;
308                                 
309                         // we only take the first view in this example.
310                         factoryClassName        = (NSString *)cocoaViewInfo->mCocoaAUViewClass[0];
311                         
312                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("the factory name is %1 bundle is %2\n",
313                                                                         factoryClassName, CocoaViewBundlePath));
314
315                 } else {
316
317                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("No cocoaUI property cocoaViewInfo = %1\n", cocoaViewInfo));
318
319                         if (cocoaViewInfo != NULL) {
320                                 free (cocoaViewInfo);
321                                 cocoaViewInfo = NULL;
322                         }
323                 }
324         }
325
326         NSRect crect = { { 0, 0 }, { 1, 1} };
327
328         // [A] Show custom UI if view has it
329
330         if (CocoaViewBundlePath && factoryClassName) {
331                 NSBundle *viewBundle    = [NSBundle bundleWithPath:[CocoaViewBundlePath path]];
332
333                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("tried to create bundle, result = %1\n", viewBundle));
334
335                 if (viewBundle == nil) {
336                         error << _("AUPluginUI: error loading AU view's bundle") << endmsg;
337                         return -1;
338                 } else {
339                         Class factoryClass = [viewBundle classNamed:factoryClassName];
340                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("tried to create factory class, result = %1\n", factoryClass));
341                         if (!factoryClass) {
342                                 error << _("AUPluginUI: error getting AU view's factory class from bundle") << endmsg;
343                                 return -1;
344                         }
345                         
346                         // make sure 'factoryClass' implements the AUCocoaUIBase protocol
347                         if (!plugin_class_valid (factoryClass)) {
348                                 error << _("AUPluginUI: U view's factory class does not properly implement the AUCocoaUIBase protocol") << endmsg;
349                                 return -1;
350                         }
351                         // make a factory
352                         id factoryInstance = [[[factoryClass alloc] init] autorelease];
353                         if (factoryInstance == nil) {
354                                 error << _("AUPluginUI: Could not create an instance of the AU view factory") << endmsg;
355                                 return -1;
356                         }
357
358                         DEBUG_TRACE (DEBUG::AudioUnits, "got a factory instance\n");
359
360                         // make a view
361                         au_view = [factoryInstance uiViewForAudioUnit:*au->get_au() withSize:crect.size];
362
363                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("view created @ %1\n", au_view));
364                         
365                         // cleanup
366                         [CocoaViewBundlePath release];
367                         if (cocoaViewInfo) {
368                                 UInt32 i;
369                                 for (i = 0; i < numberOfClasses; i++)
370                                         CFRelease(cocoaViewInfo->mCocoaAUViewClass[i]);
371                                 
372                                 free (cocoaViewInfo);
373                         }
374                         wasAbleToLoadCustomView = YES;
375                 }
376         }
377
378         if (!wasAbleToLoadCustomView) {
379                 // load generic Cocoa view
380                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Loading generic view using %1 -> %2\n", au,
381                                                                 au->get_au()));
382                 au_view = [[AUGenericView alloc] initWithAudioUnit:*au->get_au()];
383                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("view created @ %1\n", au_view));
384                 [(AUGenericView *)au_view setShowsExpertParameters:YES];
385         }
386
387         // watch for size changes of the view
388
389          [[NSNotificationCenter defaultCenter] addObserver:_notify
390                selector:@selector(auViewResized:) name:NSWindowDidResizeNotification
391                object:au_view];
392
393         // Get the size of the new AU View's frame 
394         
395         NSRect packFrame;
396         packFrame = [au_view frame];
397         prefwidth = packFrame.size.width;
398         prefheight = packFrame.size.height;
399         low_box.set_size_request (prefwidth, prefheight);
400         
401         return 0;
402 }
403
404 void
405 AUPluginUI::cocoa_view_resized ()
406 {
407         NSRect packFrame = [au_view frame];
408 }
409
410 int
411 AUPluginUI::create_carbon_view ()
412 {
413         OSStatus err;
414         ControlRef root_control;
415
416         Component editComponent = FindNextComponent(NULL, &carbon_descriptor);
417         
418         OpenAComponent(editComponent, &editView);
419         if (!editView) {
420                 error << _("AU Carbon view: cannot open AU Component") << endmsg;
421                 return -1;
422         }
423         
424         Rect r = { 100, 100, 100, 100 };
425         WindowAttributes attr = WindowAttributes (kWindowStandardHandlerAttribute |
426                                                   kWindowCompositingAttribute|
427                                                   kWindowNoShadowAttribute|
428                                                   kWindowNoTitleBarAttribute);
429
430         if ((err = CreateNewWindow(kDocumentWindowClass, attr, &r, &carbon_window)) != noErr) {
431                 error << string_compose (_("AUPluginUI: cannot create carbon window (err: %1)"), err) << endmsg;
432                 CloseComponent (editView);
433                 return -1;
434         }
435         
436         if ((err = GetRootControl(carbon_window, &root_control)) != noErr) {
437                 error << string_compose (_("AUPlugin: cannot get root control of carbon window (err: %1)"), err) << endmsg;
438                 DisposeWindow (carbon_window);
439                 CloseComponent (editView);
440                 return -1;
441         }
442
443         ControlRef viewPane;
444         Float32Point location  = { 0.0, 0.0 };
445         Float32Point size = { 0.0, 0.0 } ;
446
447         if ((err = AudioUnitCarbonViewCreate (editView, *au->get_au(), carbon_window, root_control, &location, &size, &viewPane)) != noErr) {
448                 error << string_compose (_("AUPluginUI: cannot create carbon plugin view (err: %1)"), err) << endmsg;
449                 DisposeWindow (carbon_window);
450                 CloseComponent (editView);
451                 return -1;
452         }
453
454         // resize window
455
456         Rect bounds;
457         GetControlBounds(viewPane, &bounds);
458         size.x = bounds.right-bounds.left;
459         size.y = bounds.bottom-bounds.top;
460
461         prefwidth = (int) (size.x + 0.5);
462         prefheight = (int) (size.y + 0.5);
463
464         SizeWindow (carbon_window, prefwidth, prefheight,  true);
465         low_box.set_size_request (prefwidth, prefheight);
466
467         return 0;
468 }
469
470 NSWindow*
471 AUPluginUI::get_nswindow ()
472 {
473         Gtk::Container* toplevel = get_toplevel();
474
475         if (!toplevel || !toplevel->is_toplevel()) {
476                 error << _("AUPluginUI: no top level window!") << endmsg;
477                 return 0;
478         }
479
480         NSWindow* true_parent = gdk_quartz_window_get_nswindow (toplevel->get_window()->gobj());
481
482         if (!true_parent) {
483                 error << _("AUPluginUI: no top level window!") << endmsg;
484                 return 0;
485         }
486
487         return true_parent;
488 }
489
490 void
491 AUPluginUI::activate ()
492 {
493         ActivateWindow (carbon_window, TRUE);
494         // [cocoa_parent makeKeyAndOrderFront:nil];
495 }
496
497 void
498 AUPluginUI::deactivate ()
499 {
500         ActivateWindow (carbon_window, FALSE);
501 }
502
503 int
504 AUPluginUI::parent_carbon_window ()
505 {
506         NSWindow* win = get_nswindow ();
507         int x, y;
508
509         if (!win) {
510                 return -1;
511         }
512
513         Gtk::Container* toplevel = get_toplevel();
514
515         if (!toplevel || !toplevel->is_toplevel()) {
516                 error << _("AUPluginUI: no top level window!") << endmsg;
517                 return -1;
518         }
519         
520         toplevel->get_window()->get_root_origin (x, y);
521
522         /* compute how tall the title bar is, because we have to offset the position of the carbon window
523            by that much.
524         */
525
526         NSRect content_frame = [NSWindow contentRectForFrameRect:[win frame] styleMask:[win styleMask]];
527         NSRect wm_frame = [NSWindow frameRectForContentRect:content_frame styleMask:[win styleMask]];
528
529         int titlebar_height = wm_frame.size.height - content_frame.size.height;
530
531         int packing_extra = 6; // this is the total vertical packing in our top level window
532
533         MoveWindow (carbon_window, x, y + titlebar_height + top_box.get_height() + packing_extra, false);
534         ShowWindow (carbon_window);
535
536         // create the cocoa window for the carbon one and make it visible
537         cocoa_parent = [[NSWindow alloc] initWithWindowRef: carbon_window];
538
539         SetWindowActivationScope (carbon_window, kWindowActivationScopeNone);
540
541         _notify = [ [NotificationObject alloc] initWithPluginUI:this andCocoaParent:cocoa_parent andTopLevelParent:win ]; 
542
543         [win addChildWindow:cocoa_parent ordered:NSWindowAbove];
544
545         return 0;
546 }       
547
548 int
549 AUPluginUI::parent_cocoa_window ()
550 {
551         NSWindow* win = get_nswindow ();
552
553         if (!win) {
554                 return -1;
555         }
556
557         [win setAutodisplay:YES]; // turn of GTK stuff for this window
558
559         Gtk::Container* toplevel = get_toplevel();
560
561         if (!toplevel || !toplevel->is_toplevel()) {
562                 error << _("AUPluginUI: no top level window!") << endmsg;
563                 return -1;
564         }
565
566         NSView* view = gdk_quartz_window_get_nsview (get_toplevel()->get_window()->gobj());
567         GtkRequisition a = top_box.size_request ();
568
569         /* move the au_view down so that it doesn't overlap the top_box contents */
570
571         NSPoint origin = { 0, a.height };
572
573         [au_view setFrameOrigin:origin];
574         [view addSubview:au_view]; 
575
576         return 0;
577 }
578
579 static void
580 dump_view_tree (NSView* view, int depth)
581 {
582         NSArray* subviews = [view subviews];
583         unsigned long cnt = [subviews count];
584
585         for (int d = 0; d < depth; d++) {
586                 cerr << '\t';
587         }
588         cerr << " view @ " << view << endl;
589         
590         for (unsigned long i = 0; i < cnt; ++i) {
591                 NSView* subview = [subviews objectAtIndex:i];
592                 dump_view_tree (subview, depth+1);
593         }
594 }
595
596 void
597 AUPluginUI::forward_key_event (GdkEventKey* ev)
598 {
599         NSEvent* nsevent = gdk_quartz_event_get_nsevent ((GdkEvent*)ev);
600
601         if (au_view && nsevent) {
602
603                 /* filter on nsevent type here because GDK massages FlagsChanged
604                    messages into GDK_KEY_{PRESS,RELEASE} but Cocoa won't
605                    handle a FlagsChanged message as a keyDown or keyUp
606                 */
607
608                 if ([nsevent type] == NSKeyDown) {
609                         [[[au_view window] firstResponder] keyDown:nsevent];
610                 } else if ([nsevent type] == NSKeyUp) {
611                         [[[au_view window] firstResponder] keyUp:nsevent];
612                 } else if ([nsevent type] == NSFlagsChanged) {
613                         [[[au_view window] firstResponder] flagsChanged:nsevent];
614                 }
615         }
616 }
617
618 void
619 AUPluginUI::on_realize ()
620 {
621         VBox::on_realize ();
622
623         /* our windows should not have that resize indicator */
624
625         NSWindow* win = get_nswindow ();
626         if (win) {
627                 [win setShowsResizeIndicator:NO];
628         }
629 }
630
631 void
632 AUPluginUI::lower_box_realized ()
633 {
634         if (au_view) {
635                 parent_cocoa_window ();
636         } else if (carbon_window) {
637                 parent_carbon_window ();
638         }
639 }
640
641 bool
642 AUPluginUI::on_map_event (GdkEventAny*)
643 {
644         return false;
645 }
646
647 void
648 AUPluginUI::on_window_hide ()
649 {
650         if (carbon_window) {
651                 HideWindow (carbon_window);
652                 ActivateWindow (carbon_window, FALSE);
653         }
654
655         hide_all ();
656 }
657
658 bool
659 AUPluginUI::on_window_show (const string& /*title*/)
660 {
661         /* this is idempotent so just call it every time we show the window */
662
663         gtk_widget_realize (GTK_WIDGET(low_box.gobj()));
664
665         show_all ();
666
667         if (carbon_window) {
668                 ShowWindow (carbon_window);
669                 ActivateWindow (carbon_window, TRUE);
670         }
671
672         return true;
673 }
674
675 bool
676 AUPluginUI::start_updating (GdkEventAny*)
677 {
678         return false;
679 }
680
681 bool
682 AUPluginUI::stop_updating (GdkEventAny*)
683 {
684         return false;
685 }
686
687 PlugUIBase*
688 create_au_gui (boost::shared_ptr<PluginInsert> plugin_insert, VBox** box)
689 {
690         AUPluginUI* aup = new AUPluginUI (plugin_insert);
691         (*box) = aup;
692         return aup;
693 }
694
695 bool
696 AUPluginUI::on_focus_in_event (GdkEventFocus*)
697 {
698         //cerr << "au plugin focus in\n";
699         //Keyboard::magic_widget_grab_focus ();
700         return false;
701 }
702
703 bool
704 AUPluginUI::on_focus_out_event (GdkEventFocus*)
705 {
706         //cerr << "au plugin focus out\n";
707         //Keyboard::magic_widget_drop_focus ();
708         return false;
709 }
710