drop some debug output
[ardour2.git] / gtk2_ardour / au_pluginui.mm
blob66a66023b402f6dbb8a7d55f66d7a9acab5b4b73
1 #undef  Marker
2 #define Marker FuckYouAppleAndYourLackOfNameSpaces
4 #include <pbd/error.h>
5 #include <ardour/audio_unit.h>
6 #include <ardour/insert.h>
8 #undef check // stupid gtk, stupid apple
10 #include <gtkmm/button.h>
11 #include <gdk/gdkquartz.h>
13 #include <gtkmm2ext/utils.h>
15 #include "au_pluginui.h"
16 #include "gui_thread.h"
18 #include <appleutility/CAAudioUnit.h>
19 #include <appleutility/CAComponent.h>
21 #import <AudioUnit/AUCocoaUIView.h>
22 #import <CoreAudioKit/AUGenericView.h>
24 #undef Marker
26 #include "keyboard.h"
27 #include "utils.h"
28 #include "public_editor.h"
29 #include "i18n.h"
31 using namespace ARDOUR;
32 using namespace Gtk;
33 using namespace Gtkmm2ext;
34 using namespace sigc;
35 using namespace std;
36 using namespace PBD;
38 vector<string> AUPluginUI::automation_mode_strings;
40 static const gchar* _automation_mode_strings[] = {
41         X_("Manual"),
42         X_("Play"),
43         X_("Write"),
44         X_("Touch"),
45         0
48 @implementation NotificationObject
50 - (NotificationObject*) initWithPluginUI: (AUPluginUI*) apluginui andCocoaParent: (NSWindow*) cp andTopLevelParent: (NSWindow*) tlp
52         self = [ super init ];
54         if (self) {
55                 plugin_ui = apluginui;
56                 cocoa_parent = cp;
57                 top_level_parent = tlp;
59                 [[NSNotificationCenter defaultCenter] addObserver:self
60                  selector:@selector(cocoaParentActivationHandler:)
61                  name:NSWindowDidBecomeMainNotification
62                  object:nil];
64                 [[NSNotificationCenter defaultCenter] addObserver:self
65                  selector:@selector(cocoaParentBecameKeyHandler:)
66                  name:NSWindowDidBecomeKeyNotification
67                  object:nil];
68         }
70         return self;
72                 
73 - (void)cocoaParentActivationHandler:(NSNotification *)notification
75         NSWindow* notification_window = (NSWindow *)[notification object];
77         if (top_level_parent == notification_window || cocoa_parent == notification_window) {
78                 if ([notification_window isMainWindow]) {
79                         plugin_ui->activate();
80                 } else {
81                         plugin_ui->deactivate();
82                 }
83         } 
86 - (void)cocoaParentBecameKeyHandler:(NSNotification *)notification
88         NSWindow* notification_window = (NSWindow *)[notification object];
90         if (top_level_parent == notification_window || cocoa_parent == notification_window) {
91                 if ([notification_window isKeyWindow]) {
92                         plugin_ui->activate();
93                 } else {
94                         plugin_ui->deactivate();
95                 }
96         } 
99 - (void)auViewResized:(NSNotification *)notification;
101         plugin_ui->cocoa_view_resized();
104 @end
106 AUPluginUI::AUPluginUI (boost::shared_ptr<PluginInsert> insert)
107         : PlugUIBase (insert)
108         , automation_mode_label (_("Automation"))
109         , preset_label (_("Presets"))
110         
112         if (automation_mode_strings.empty()) {
113                 automation_mode_strings = I18N (_automation_mode_strings);
114         }
115         
116         set_popdown_strings (automation_mode_selector, automation_mode_strings);
117         automation_mode_selector.set_active_text (automation_mode_strings.front());
119         if ((au = boost::dynamic_pointer_cast<AUPlugin> (insert->plugin())) == 0) {
120                 error << _("unknown type of editor-supplying plugin (note: no AudioUnit support in this version of ardour)") << endmsg;
121                 throw failed_constructor ();
122         }
124         /* stuff some stuff into the top of the window */
126         HBox* smaller_hbox = manage (new HBox);
128         smaller_hbox->set_spacing (6);
129         smaller_hbox->pack_start (preset_label, false, false, 4);
130         smaller_hbox->pack_start (preset_combo, false, false);
131         smaller_hbox->pack_start (save_button, false, false);
132 #if 0
133         /* one day these might be useful with an AU plugin, but not yet */
134         smaller_hbox->pack_start (automation_mode_label, false, false);
135         smaller_hbox->pack_start (automation_mode_selector, false, false);
136 #endif
137         smaller_hbox->pack_start (bypass_button, false, true);
139         VBox* v1_box = manage (new VBox);
140         VBox* v2_box = manage (new VBox);
142         v1_box->pack_start (*smaller_hbox, false, true);
143         v2_box->pack_start (focus_button, false, true);
145         top_box.set_homogeneous (false);
146         top_box.set_spacing (6);
147         top_box.set_border_width (6);
149         top_box.pack_end (*v2_box, false, false);
150         top_box.pack_end (*v1_box, false, false);
152         set_spacing (6);
153         pack_start (top_box, false, false);
154         pack_start (low_box, false, false);
156         preset_label.show ();
157         preset_combo.show ();
158         automation_mode_label.show ();
159         automation_mode_selector.show ();
160         bypass_button.show ();
161         top_box.show ();
162         low_box.show ();
164         _activating_from_app = false;
165         cocoa_parent = 0;
166         _notify = 0;
167         cocoa_window = 0;
168         au_view = 0;
169         editView = 0;
171         /* prefer cocoa, fall back to cocoa, but use carbon if its there */
173         if (test_cocoa_view_support()) {
174                 create_cocoa_view ();
175         } else if (test_carbon_view_support()) {
176                 create_carbon_view ();
177         } else {
178                 create_cocoa_view ();
179         }
181         low_box.signal_realize().connect (mem_fun (this, &AUPluginUI::lower_box_realized));
184 AUPluginUI::~AUPluginUI ()
186         if (cocoa_parent) {
187                 NSWindow* win = get_nswindow();
188                 [[NSNotificationCenter defaultCenter] removeObserver:_notify];
189                 [win removeChildWindow:cocoa_parent];
191         } 
193         if (carbon_window) {
194                 /* not parented, just overlaid on top of our window */
195                 DisposeWindow (carbon_window);
196         }
198         if (editView) {
199                 CloseComponent (editView);
200         }
202         if (au_view) {
203                 /* remove whatever we packed into low_box so that GTK doesn't
204                    mess with it.
205                 */
207                 [au_view removeFromSuperview];
208         }
211 bool
212 AUPluginUI::test_carbon_view_support ()
214         bool ret = false;
215         
216         carbon_descriptor.componentType = kAudioUnitCarbonViewComponentType;
217         carbon_descriptor.componentSubType = 'gnrc';
218         carbon_descriptor.componentManufacturer = 'appl';
219         carbon_descriptor.componentFlags = 0;
220         carbon_descriptor.componentFlagsMask = 0;
221         
222         OSStatus err;
224         // ask the AU for its first editor component
225         UInt32 propertySize;
226         err = AudioUnitGetPropertyInfo(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, &propertySize, NULL);
227         if (!err) {
228                 int nEditors = propertySize / sizeof(ComponentDescription);
229                 ComponentDescription *editors = new ComponentDescription[nEditors];
230                 err = AudioUnitGetProperty(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, editors, &propertySize);
231                 if (!err) {
232                         // just pick the first one for now
233                         carbon_descriptor = editors[0];
234                         ret = true;
235                 }
236                 delete[] editors;
237         }
239         return ret;
241         
242 bool
243 AUPluginUI::test_cocoa_view_support ()
245         UInt32 dataSize   = 0;
246         Boolean isWritable = 0;
247         OSStatus err = AudioUnitGetPropertyInfo(*au->get_au(),
248                                                 kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
249                                                 0, &dataSize, &isWritable);
250         
251         return dataSize > 0 && err == noErr;
254 bool
255 AUPluginUI::plugin_class_valid (Class pluginClass)
257         if([pluginClass conformsToProtocol: @protocol(AUCocoaUIBase)]) {
258                 if([pluginClass instancesRespondToSelector: @selector(interfaceVersion)] &&
259                    [pluginClass instancesRespondToSelector: @selector(uiViewForAudioUnit:withSize:)]) {
260                                 return true;
261                 }
262         }
263         return false;
267 AUPluginUI::create_cocoa_view ()
269         BOOL wasAbleToLoadCustomView = NO;
270         AudioUnitCocoaViewInfo* cocoaViewInfo = NULL;
271         UInt32               numberOfClasses = 0;
272         UInt32     dataSize;
273         Boolean    isWritable;
274         NSString*           factoryClassName = 0;
275         NSURL*              CocoaViewBundlePath;
277         OSStatus result = AudioUnitGetPropertyInfo (*au->get_au(),
278                                                     kAudioUnitProperty_CocoaUI,
279                                                     kAudioUnitScope_Global, 
280                                                     0,
281                                                     &dataSize,
282                                                     &isWritable );
284         numberOfClasses = (dataSize - sizeof(CFURLRef)) / sizeof(CFStringRef);
285         
286         // Does view have custom Cocoa UI?
287         
288         if ((result == noErr) && (numberOfClasses > 0) ) {
289                 cocoaViewInfo = (AudioUnitCocoaViewInfo *)malloc(dataSize);
290                 if(AudioUnitGetProperty(*au->get_au(),
291                                         kAudioUnitProperty_CocoaUI,
292                                         kAudioUnitScope_Global,
293                                         0,
294                                         cocoaViewInfo,
295                                         &dataSize) == noErr) {
297                         CocoaViewBundlePath     = (NSURL *)cocoaViewInfo->mCocoaAUViewBundleLocation;
298                         
299                         // we only take the first view in this example.
300                         factoryClassName        = (NSString *)cocoaViewInfo->mCocoaAUViewClass[0];
302                 } else {
304                         if (cocoaViewInfo != NULL) {
305                                 free (cocoaViewInfo);
306                                 cocoaViewInfo = NULL;
307                         }
308                 }
309         }
311         NSRect crect = { { 0, 0 }, { 1, 1} };
313         // [A] Show custom UI if view has it
315         if (CocoaViewBundlePath && factoryClassName) {
316                 NSBundle *viewBundle    = [NSBundle bundleWithPath:[CocoaViewBundlePath path]];
317                 if (viewBundle == nil) {
318                         error << _("AUPluginUI: error loading AU view's bundle") << endmsg;
319                         return -1;
320                 } else {
321                         Class factoryClass = [viewBundle classNamed:factoryClassName];
322                         if (!factoryClass) {
323                                 error << _("AUPluginUI: error getting AU view's factory class from bundle") << endmsg;
324                                 return -1;
325                         }
326                         
327                         // make sure 'factoryClass' implements the AUCocoaUIBase protocol
328                         if (!plugin_class_valid (factoryClass)) {
329                                 error << _("AUPluginUI: U view's factory class does not properly implement the AUCocoaUIBase protocol") << endmsg;
330                                 return -1;
331                         }
332                         // make a factory
333                         id factoryInstance = [[[factoryClass alloc] init] autorelease];
334                         if (factoryInstance == nil) {
335                                 error << _("AUPluginUI: Could not create an instance of the AU view factory") << endmsg;
336                                 return -1;
337                         }
339                         // make a view
340                         au_view = [factoryInstance uiViewForAudioUnit:*au->get_au() withSize:crect.size];
341                         
342                         // cleanup
343                         [CocoaViewBundlePath release];
344                         if (cocoaViewInfo) {
345                                 UInt32 i;
346                                 for (i = 0; i < numberOfClasses; i++)
347                                         CFRelease(cocoaViewInfo->mCocoaAUViewClass[i]);
348                                 
349                                 free (cocoaViewInfo);
350                         }
351                         wasAbleToLoadCustomView = YES;
352                 }
353         }
355         if (!wasAbleToLoadCustomView) {
356                 // load generic Cocoa view
357                 au_view = [[AUGenericView alloc] initWithAudioUnit:*au->get_au()];
358                 [(AUGenericView *)au_view setShowsExpertParameters:YES];
359         }
361         // watch for size changes of the view
363          [[NSNotificationCenter defaultCenter] addObserver:_notify
364                selector:@selector(auViewResized:) name:NSWindowDidResizeNotification
365                object:au_view];
367         // Get the size of the new AU View's frame 
368         
369         NSRect packFrame;
370         packFrame = [au_view frame];
371         prefwidth = packFrame.size.width;
372         prefheight = packFrame.size.height;
373         low_box.set_size_request (prefwidth, prefheight);
374         
375         return 0;
378 void
379 AUPluginUI::cocoa_view_resized ()
381         NSRect packFrame = [au_view frame];
385 AUPluginUI::create_carbon_view ()
387         OSStatus err;
388         ControlRef root_control;
390         Component editComponent = FindNextComponent(NULL, &carbon_descriptor);
391         
392         OpenAComponent(editComponent, &editView);
393         if (!editView) {
394                 error << _("AU Carbon view: cannot open AU Component") << endmsg;
395                 return -1;
396         }
397         
398         Rect r = { 100, 100, 100, 100 };
399         WindowAttributes attr = WindowAttributes (kWindowStandardHandlerAttribute |
400                                                   kWindowCompositingAttribute|
401                                                   kWindowNoShadowAttribute|
402                                                   kWindowNoTitleBarAttribute);
404         if ((err = CreateNewWindow(kDocumentWindowClass, attr, &r, &carbon_window)) != noErr) {
405                 error << string_compose (_("AUPluginUI: cannot create carbon window (err: %1)"), err) << endmsg;
406                 CloseComponent (editView);
407                 return -1;
408         }
409         
410         if ((err = GetRootControl(carbon_window, &root_control)) != noErr) {
411                 error << string_compose (_("AUPlugin: cannot get root control of carbon window (err: %1)"), err) << endmsg;
412                 DisposeWindow (carbon_window);
413                 CloseComponent (editView);
414                 return -1;
415         }
417         ControlRef viewPane;
418         Float32Point location  = { 0.0, 0.0 };
419         Float32Point size = { 0.0, 0.0 } ;
421         if ((err = AudioUnitCarbonViewCreate (editView, *au->get_au(), carbon_window, root_control, &location, &size, &viewPane)) != noErr) {
422                 error << string_compose (_("AUPluginUI: cannot create carbon plugin view (err: %1)"), err) << endmsg;
423                 DisposeWindow (carbon_window);
424                 CloseComponent (editView);
425                 return -1;
426         }
428         // resize window
430         Rect bounds;
431         GetControlBounds(viewPane, &bounds);
432         size.x = bounds.right-bounds.left;
433         size.y = bounds.bottom-bounds.top;
435         prefwidth = (int) (size.x + 0.5);
436         prefheight = (int) (size.y + 0.5);
438         SizeWindow (carbon_window, prefwidth, prefheight,  true);
439         low_box.set_size_request (prefwidth, prefheight);
441         return 0;
444 NSWindow*
445 AUPluginUI::get_nswindow ()
447         Gtk::Container* toplevel = get_toplevel();
449         if (!toplevel || !toplevel->is_toplevel()) {
450                 error << _("AUPluginUI: no top level window!") << endmsg;
451                 return 0;
452         }
454         NSWindow* true_parent = gdk_quartz_window_get_nswindow (toplevel->get_window()->gobj());
456         if (!true_parent) {
457                 error << _("AUPluginUI: no top level window!") << endmsg;
458                 return 0;
459         }
461         return true_parent;
464 void
465 AUPluginUI::activate ()
467         ActivateWindow (carbon_window, TRUE);
468         // [cocoa_parent makeKeyAndOrderFront:nil];
471 void
472 AUPluginUI::deactivate ()
474         ActivateWindow (carbon_window, FALSE);
478 AUPluginUI::parent_carbon_window ()
480         NSWindow* win = get_nswindow ();
481         int x, y;
483         if (!win) {
484                 return -1;
485         }
487         Gtk::Container* toplevel = get_toplevel();
489         if (!toplevel || !toplevel->is_toplevel()) {
490                 error << _("AUPluginUI: no top level window!") << endmsg;
491                 return -1;
492         }
493         
494         toplevel->get_window()->get_root_origin (x, y);
496         /* compute how tall the title bar is, because we have to offset the position of the carbon window
497            by that much.
498         */
500         NSRect content_frame = [NSWindow contentRectForFrameRect:[win frame] styleMask:[win styleMask]];
501         NSRect wm_frame = [NSWindow frameRectForContentRect:content_frame styleMask:[win styleMask]];
503         int titlebar_height = wm_frame.size.height - content_frame.size.height;
505         int packing_extra = 6; // this is the total vertical packing in our top level window
507         MoveWindow (carbon_window, x, y + titlebar_height + top_box.get_height() + packing_extra, false);
508         ShowWindow (carbon_window);
510         // create the cocoa window for the carbon one and make it visible
511         cocoa_parent = [[NSWindow alloc] initWithWindowRef: carbon_window];
513         SetWindowActivationScope (carbon_window, kWindowActivationScopeNone);
515         _notify = [ [NotificationObject alloc] initWithPluginUI:this andCocoaParent:cocoa_parent andTopLevelParent:win ]; 
517         [win addChildWindow:cocoa_parent ordered:NSWindowAbove];
519         return 0;
520 }       
523 AUPluginUI::parent_cocoa_window ()
525         NSWindow* win = get_nswindow ();
526         NSRect packFrame;
528         if (!win) {
529                 return -1;
530         }
532         [win setAutodisplay:YES]; // turn of GTK stuff for this window
534         Gtk::Container* toplevel = get_toplevel();
536         if (!toplevel || !toplevel->is_toplevel()) {
537                 error << _("AUPluginUI: no top level window!") << endmsg;
538                 return -1;
539         }
541         NSView* view = gdk_quartz_window_get_nsview (get_toplevel()->get_window()->gobj());
542         GtkRequisition a = top_box.size_request ();
544         /* move the au_view down so that it doesn't overlap the top_box contents */
546         NSPoint origin = { 0, a.height };
548         [au_view setFrameOrigin:origin];
549         [view addSubview:au_view]; 
551         return 0;
554 static void
555 dump_view_tree (NSView* view, int depth)
557         NSArray* subviews = [view subviews];
558         unsigned long cnt = [subviews count];
560         for (int d = 0; d < depth; d++) {
561                 cerr << '\t';
562         }
563         cerr << " view @ " << view << endl;
564         
565         for (unsigned long i = 0; i < cnt; ++i) {
566                 NSView* subview = [subviews objectAtIndex:i];
567                 dump_view_tree (subview, depth+1);
568         }
571 void
572 AUPluginUI::forward_key_event (GdkEventKey* ev)
574         NSEvent* nsevent = gdk_quartz_event_get_nsevent ((GdkEvent*)ev);
576         if (au_view && nsevent) {
578                 /* filter on nsevent type here because GDK massages FlagsChanged
579                    messages into GDK_KEY_{PRESS,RELEASE} but Cocoa won't
580                    handle a FlagsChanged message as a keyDown or keyUp
581                 */
583                 if ([nsevent type] == NSKeyDown) {
584                         [[[au_view window] firstResponder] keyDown:nsevent];
585                 } else if ([nsevent type] == NSKeyUp) {
586                         [[[au_view window] firstResponder] keyUp:nsevent];
587                 } else if ([nsevent type] == NSFlagsChanged) {
588                         [[[au_view window] firstResponder] flagsChanged:nsevent];
589                 }
590         }
593 void
594 AUPluginUI::on_realize ()
596         VBox::on_realize ();
598         /* our windows should not have that resize indicator */
600         NSWindow* win = get_nswindow ();
601         if (win) {
602                 [win setShowsResizeIndicator:NO];
603         }
606 void
607 AUPluginUI::lower_box_realized ()
609         if (au_view) {
610                 parent_cocoa_window ();
611         } else if (carbon_window) {
612                 parent_carbon_window ();
613         }
616 bool
617 AUPluginUI::on_map_event (GdkEventAny* ev)
619         return false;
622 void
623 AUPluginUI::on_window_hide ()
625         if (carbon_window) {
626                 HideWindow (carbon_window);
627                 ActivateWindow (carbon_window, FALSE);
628         }
630         hide_all ();
633 bool
634 AUPluginUI::on_window_show (const Glib::ustring& title)
636         /* this is idempotent so just call it every time we show the window */
638         gtk_widget_realize (GTK_WIDGET(low_box.gobj()));
640         show_all ();
642         if (carbon_window) {
643                 ShowWindow (carbon_window);
644                 ActivateWindow (carbon_window, TRUE);
645         }
647         return true;
650 bool
651 AUPluginUI::start_updating (GdkEventAny* any)
653         return false;
656 bool
657 AUPluginUI::stop_updating (GdkEventAny* any)
659         return false;
662 PlugUIBase*
663 create_au_gui (boost::shared_ptr<PluginInsert> plugin_insert, VBox** box)
665         AUPluginUI* aup = new AUPluginUI (plugin_insert);
666         (*box) = aup;
667         return aup;
670 bool
671 AUPluginUI::on_focus_in_event (GdkEventFocus* ev)
673         //cerr << "au plugin focus in\n";
674         //Keyboard::magic_widget_grab_focus ();
675         return false;
678 bool
679 AUPluginUI::on_focus_out_event (GdkEventFocus* ev)
681         //cerr << "au plugin focus out\n";
682         //Keyboard::magic_widget_drop_focus ();
683         return false;