2 #define Marker FuckYouAppleAndYourLackOfNameSpaces
4 #include <gtkmm/button.h>
5 #include <gdk/gdkquartz.h>
7 #include "pbd/convert.h"
10 #include "ardour/audio_unit.h"
11 #include "ardour/debug.h"
12 #include "ardour/plugin_insert.h"
14 #undef check // stupid gtk, stupid apple
16 #include <gtkmm2ext/utils.h>
18 #include "au_pluginui.h"
19 #include "gui_thread.h"
21 #include "CAAudioUnit.h"
22 #include "CAComponent.h"
24 #import <AudioUnit/AUCocoaUIView.h>
25 #import <CoreAudioKit/AUGenericView.h>
31 #include "public_editor.h"
35 #define ArdourCloseComponent CloseComponent
37 #define ArdourCloseComponent AudioComponentInstanceDispose
39 using namespace ARDOUR;
41 using namespace Gtkmm2ext;
45 vector<string> AUPluginUI::automation_mode_strings;
47 static const gchar* _automation_mode_strings[] = {
56 dump_view_tree (NSView* view, int depth, int maxdepth)
58 NSArray* subviews = [view subviews];
59 unsigned long cnt = [subviews count];
61 for (int d = 0; d < depth; d++) {
64 NSRect frame = [view frame];
65 cerr << " view @ " << frame.origin.x << ", " << frame.origin.y
66 << ' ' << frame.size.width << " x " << frame.size.height
69 if (depth >= maxdepth) {
72 for (unsigned long i = 0; i < cnt; ++i) {
73 NSView* subview = [subviews objectAtIndex:i];
74 dump_view_tree (subview, depth+1, maxdepth);
78 @implementation NotificationObject
80 - (NotificationObject*) initWithPluginUI: (AUPluginUI*) apluginui andCocoaParent: (NSWindow*) cp andTopLevelParent: (NSWindow*) tlp
82 self = [ super init ];
85 plugin_ui = apluginui;
86 top_level_parent = tlp;
91 [[NSNotificationCenter defaultCenter]
93 selector:@selector(cocoaParentActivationHandler:)
94 name:NSWindowDidBecomeMainNotification
97 [[NSNotificationCenter defaultCenter]
99 selector:@selector(cocoaParentBecameKeyHandler:)
100 name:NSWindowDidBecomeKeyNotification
108 - (void)cocoaParentActivationHandler:(NSNotification *)notification
110 NSWindow* notification_window = (NSWindow *)[notification object];
112 if (top_level_parent == notification_window || cocoa_parent == notification_window) {
113 if ([notification_window isMainWindow]) {
114 plugin_ui->activate();
116 plugin_ui->deactivate();
121 - (void)cocoaParentBecameKeyHandler:(NSNotification *)notification
123 NSWindow* notification_window = (NSWindow *)[notification object];
125 if (top_level_parent == notification_window || cocoa_parent == notification_window) {
126 if ([notification_window isKeyWindow]) {
127 plugin_ui->activate();
129 plugin_ui->deactivate();
134 - (void)auViewResized:(NSNotification *)notification
136 (void) notification; // stop complaints about unusued argument
137 plugin_ui->cocoa_view_resized();
142 AUPluginUI::AUPluginUI (boost::shared_ptr<PluginInsert> insert)
143 : PlugUIBase (insert)
144 , automation_mode_label (_("Automation"))
145 , preset_label (_("Presets"))
156 if (automation_mode_strings.empty()) {
157 automation_mode_strings = I18N (_automation_mode_strings);
160 set_popdown_strings (automation_mode_selector, automation_mode_strings);
161 automation_mode_selector.set_active_text (automation_mode_strings.front());
163 if ((au = boost::dynamic_pointer_cast<AUPlugin> (insert->plugin())) == 0) {
164 error << _("unknown type of editor-supplying plugin (note: no AudioUnit support in this version of ardour)") << endmsg;
165 throw failed_constructor ();
168 /* stuff some stuff into the top of the window */
170 HBox* smaller_hbox = manage (new HBox);
172 smaller_hbox->set_spacing (6);
173 smaller_hbox->pack_start (preset_label, false, false, 4);
174 smaller_hbox->pack_start (_preset_modified, false, false);
175 smaller_hbox->pack_start (_preset_combo, false, false);
176 smaller_hbox->pack_start (add_button, false, false);
178 /* Ardour does not currently allow to overwrite existing presets
179 * see save_property_list() in audio_unit.cc
181 smaller_hbox->pack_start (save_button, false, false);
184 /* one day these might be useful with an AU plugin, but not yet */
185 smaller_hbox->pack_start (automation_mode_label, false, false);
186 smaller_hbox->pack_start (automation_mode_selector, false, false);
188 smaller_hbox->pack_start (reset_button, false, false);
189 smaller_hbox->pack_start (bypass_button, false, true);
191 VBox* v1_box = manage (new VBox);
192 VBox* v2_box = manage (new VBox);
194 v1_box->pack_start (*smaller_hbox, false, true);
195 v2_box->pack_start (focus_button, false, true);
197 top_box.set_homogeneous (false);
198 top_box.set_spacing (6);
199 top_box.set_border_width (6);
201 top_box.pack_end (*v2_box, false, false);
202 top_box.pack_end (*v1_box, false, false);
205 pack_start (top_box, false, false);
206 pack_start (low_box, true, true);
208 preset_label.show ();
209 _preset_combo.show ();
210 automation_mode_label.show ();
211 automation_mode_selector.show ();
212 bypass_button.show ();
220 _activating_from_app = false;
227 /* prefer cocoa, fall back to cocoa, but use carbon if its there */
229 if (test_cocoa_view_support()) {
230 create_cocoa_view ();
232 } else if (test_carbon_view_support()) {
233 create_carbon_view ();
236 create_cocoa_view ();
239 low_box.add_events (Gdk::VISIBILITY_NOTIFY_MASK | Gdk::EXPOSURE_MASK);
241 low_box.signal_realize().connect (mem_fun (this, &AUPluginUI::lower_box_realized));
242 low_box.signal_visibility_notify_event ().connect (mem_fun (this, &AUPluginUI::lower_box_visibility_notify));
243 low_box.signal_size_request ().connect (mem_fun (this, &AUPluginUI::lower_box_size_request));
244 low_box.signal_size_allocate ().connect (mem_fun (this, &AUPluginUI::lower_box_size_allocate));
245 low_box.signal_map ().connect (mem_fun (this, &AUPluginUI::lower_box_map));
246 low_box.signal_unmap ().connect (mem_fun (this, &AUPluginUI::lower_box_unmap));
247 low_box.signal_expose_event ().connect (mem_fun (this, &AUPluginUI::lower_box_expose));
250 AUPluginUI::~AUPluginUI ()
253 [[NSNotificationCenter defaultCenter] removeObserver:_notify];
257 NSWindow* win = get_nswindow();
258 [win removeChildWindow:cocoa_parent];
263 /* not parented, just overlaid on top of our window */
264 DisposeWindow (carbon_window);
269 ArdourCloseComponent (editView);
273 /* remove whatever we packed into low_box so that GTK doesn't
277 [au_view removeFromSuperview];
282 AUPluginUI::test_carbon_view_support ()
287 carbon_descriptor.componentType = kAudioUnitCarbonViewComponentType;
288 carbon_descriptor.componentSubType = 'gnrc';
289 carbon_descriptor.componentManufacturer = 'appl';
290 carbon_descriptor.componentFlags = 0;
291 carbon_descriptor.componentFlagsMask = 0;
295 // ask the AU for its first editor component
297 err = AudioUnitGetPropertyInfo(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, &propertySize, NULL);
299 int nEditors = propertySize / sizeof(ComponentDescription);
300 ComponentDescription *editors = new ComponentDescription[nEditors];
301 err = AudioUnitGetProperty(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, editors, &propertySize);
303 // just pick the first one for now
304 carbon_descriptor = editors[0];
317 AUPluginUI::test_cocoa_view_support ()
320 Boolean isWritable = 0;
321 OSStatus err = AudioUnitGetPropertyInfo(*au->get_au(),
322 kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
323 0, &dataSize, &isWritable);
325 return dataSize > 0 && err == noErr;
329 AUPluginUI::plugin_class_valid (Class pluginClass)
331 if([pluginClass conformsToProtocol: @protocol(AUCocoaUIBase)]) {
332 if([pluginClass instancesRespondToSelector: @selector(interfaceVersion)] &&
333 [pluginClass instancesRespondToSelector: @selector(uiViewForAudioUnit:withSize:)]) {
341 AUPluginUI::create_cocoa_view ()
343 bool wasAbleToLoadCustomView = false;
344 AudioUnitCocoaViewInfo* cocoaViewInfo = NULL;
345 UInt32 numberOfClasses = 0;
348 NSString* factoryClassName = 0;
349 NSURL* CocoaViewBundlePath = NULL;
351 OSStatus result = AudioUnitGetPropertyInfo (*au->get_au(),
352 kAudioUnitProperty_CocoaUI,
353 kAudioUnitScope_Global,
358 numberOfClasses = (dataSize - sizeof(CFURLRef)) / sizeof(CFStringRef);
360 // Does view have custom Cocoa UI?
362 if ((result == noErr) && (numberOfClasses > 0) ) {
364 DEBUG_TRACE(DEBUG::AudioUnits,
365 string_compose ( "based on %1, there are %2 cocoa UI classes\n", dataSize, numberOfClasses));
367 cocoaViewInfo = (AudioUnitCocoaViewInfo *)malloc(dataSize);
369 if(AudioUnitGetProperty(*au->get_au(),
370 kAudioUnitProperty_CocoaUI,
371 kAudioUnitScope_Global,
374 &dataSize) == noErr) {
376 CocoaViewBundlePath = (NSURL *)cocoaViewInfo->mCocoaAUViewBundleLocation;
378 // we only take the first view in this example.
379 factoryClassName = (NSString *)cocoaViewInfo->mCocoaAUViewClass[0];
381 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("the factory name is %1 bundle is %2\n",
382 [factoryClassName UTF8String], CocoaViewBundlePath));
386 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("No cocoaUI property cocoaViewInfo = %1\n", cocoaViewInfo));
388 if (cocoaViewInfo != NULL) {
389 free (cocoaViewInfo);
390 cocoaViewInfo = NULL;
395 // [A] Show custom UI if view has it
397 if (CocoaViewBundlePath && factoryClassName) {
398 NSBundle *viewBundle = [NSBundle bundleWithPath:[CocoaViewBundlePath path]];
400 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("tried to create bundle, result = %1\n", viewBundle));
402 if (viewBundle == NULL) {
403 error << _("AUPluginUI: error loading AU view's bundle") << endmsg;
406 Class factoryClass = [viewBundle classNamed:factoryClassName];
407 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("tried to create factory class, result = %1\n", factoryClass));
409 error << _("AUPluginUI: error getting AU view's factory class from bundle") << endmsg;
413 // make sure 'factoryClass' implements the AUCocoaUIBase protocol
414 if (!plugin_class_valid (factoryClass)) {
415 error << _("AUPluginUI: U view's factory class does not properly implement the AUCocoaUIBase protocol") << endmsg;
419 id factory = [[[factoryClass alloc] init] autorelease];
420 if (factory == NULL) {
421 error << _("AUPluginUI: Could not create an instance of the AU view factory") << endmsg;
425 DEBUG_TRACE (DEBUG::AudioUnits, "got a factory instance\n");
428 au_view = [factory uiViewForAudioUnit:*au->get_au() withSize:NSZeroSize];
430 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("view created @ %1\n", au_view));
433 [CocoaViewBundlePath release];
436 for (i = 0; i < numberOfClasses; i++)
437 CFRelease(cocoaViewInfo->mCocoaAUViewClass[i]);
439 free (cocoaViewInfo);
441 wasAbleToLoadCustomView = true;
445 if (!wasAbleToLoadCustomView) {
446 // load generic Cocoa view
447 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Loading generic view using %1 -> %2\n", au,
449 au_view = [[AUGenericView alloc] initWithAudioUnit:*au->get_au()];
450 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("view created @ %1\n", au_view));
451 [(AUGenericView *)au_view setShowsExpertParameters:1];
454 // Get the initial size of the new AU View's frame
455 NSRect frame = [au_view frame];
456 min_width = req_width = CGRectGetWidth(NSRectToCGRect(frame));
457 min_height = req_height = CGRectGetHeight(NSRectToCGRect(frame));
458 resizable = [au_view autoresizingMask];
460 low_box.queue_resize ();
466 AUPluginUI::cocoa_view_resized ()
468 if (!mapped || alo_width == 0 || alo_height == 0 || !resizable) {
471 /* check for self-resizing plugins (e.g expand settings in AUSampler)
472 * if the widget expands it moves its y-offset (cocoa y-axis points towards the top)
474 NSRect new_au_frame = [au_view frame];
476 //float dx = last_au_frame.origin.x - new_au_frame.origin.x;
477 float dy = last_au_frame.origin.y - new_au_frame.origin.y;
480 if (req_width < min_width) req_width = min_width;
481 if (req_height < min_height) req_height = min_height;
483 last_au_frame = new_au_frame;
484 low_box.queue_resize ();
488 AUPluginUI::create_carbon_view ()
492 ControlRef root_control;
494 Component editComponent = FindNextComponent(NULL, &carbon_descriptor);
496 OpenAComponent(editComponent, &editView);
498 error << _("AU Carbon view: cannot open AU Component") << endmsg;
502 Rect r = { 100, 100, 100, 100 };
503 WindowAttributes attr = WindowAttributes (kWindowStandardHandlerAttribute |
504 kWindowCompositingAttribute|
505 kWindowNoShadowAttribute|
506 kWindowNoTitleBarAttribute);
508 if ((err = CreateNewWindow(kUtilityWindowClass, attr, &r, &carbon_window)) != noErr) {
509 error << string_compose (_("AUPluginUI: cannot create carbon window (err: %1)"), err) << endmsg;
510 ArdourCloseComponent (editView);
514 if ((err = GetRootControl(carbon_window, &root_control)) != noErr) {
515 error << string_compose (_("AUPlugin: cannot get root control of carbon window (err: %1)"), err) << endmsg;
516 DisposeWindow (carbon_window);
517 ArdourCloseComponent (editView);
522 Float32Point location = { 0.0, 0.0 };
523 Float32Point size = { 0.0, 0.0 } ;
525 if ((err = AudioUnitCarbonViewCreate (editView, *au->get_au(), carbon_window, root_control, &location, &size, &viewPane)) != noErr) {
526 error << string_compose (_("AUPluginUI: cannot create carbon plugin view (err: %1)"), err) << endmsg;
527 DisposeWindow (carbon_window);
528 ArdourCloseComponent (editView);
535 GetControlBounds(viewPane, &bounds);
536 size.x = bounds.right-bounds.left;
537 size.y = bounds.bottom-bounds.top;
539 req_width = (int) (size.x + 0.5);
540 req_height = (int) (size.y + 0.5);
542 SizeWindow (carbon_window, prefwidth, req_height, true);
543 low_box.set_size_request (prefwidth, req_height); // ??
547 error << _("AU Carbon GUI is not supported.") << endmsg;
553 AUPluginUI::get_nswindow ()
555 Gtk::Container* toplevel = get_toplevel();
557 if (!toplevel || !toplevel->is_toplevel()) {
558 error << _("AUPluginUI: no top level window!") << endmsg;
562 NSWindow* true_parent = gdk_quartz_window_get_nswindow (toplevel->get_window()->gobj());
565 error << _("AUPluginUI: no top level window!") << endmsg;
573 AUPluginUI::activate ()
576 ActivateWindow (carbon_window, TRUE);
581 AUPluginUI::deactivate ()
584 ActivateWindow (carbon_window, FALSE);
589 AUPluginUI::parent_carbon_window ()
592 NSWindow* win = get_nswindow ();
593 Rect windowStructureBoundsRect;
599 Gtk::Container* toplevel = get_toplevel();
601 if (!toplevel || !toplevel->is_toplevel()) {
602 error << _("AUPluginUI: no top level window!") << endmsg;
606 /* figure out where the cocoa parent window is in carbon-coordinate space, which
607 differs from both cocoa-coordinate space and GTK-coordinate space
610 GetWindowBounds((WindowRef) [win windowRef], kWindowStructureRgn, &windowStructureBoundsRect);
612 /* compute how tall the title bar is, because we have to offset the position of the carbon window
616 NSRect content_frame = [NSWindow contentRectForFrameRect:[win frame] styleMask:[win styleMask]];
617 NSRect wm_frame = [NSWindow frameRectForContentRect:content_frame styleMask:[win styleMask]];
619 int titlebar_height = wm_frame.size.height - content_frame.size.height;
621 int packing_extra = 6; // this is the total vertical packing in our top level window
623 /* move into position, based on parent window position */
624 MoveWindow (carbon_window,
625 windowStructureBoundsRect.left,
626 windowStructureBoundsRect.top + titlebar_height + top_box.get_height() + packing_extra,
628 ShowWindow (carbon_window);
630 // create the cocoa window for the carbon one and make it visible
631 cocoa_parent = [[NSWindow alloc] initWithWindowRef: carbon_window];
633 SetWindowActivationScope (carbon_window, kWindowActivationScopeNone);
635 _notify = [ [NotificationObject alloc] initWithPluginUI:this andCocoaParent:cocoa_parent andTopLevelParent:win ];
637 [win addChildWindow:cocoa_parent ordered:NSWindowAbove];
638 [win setAutodisplay:1]; // turn of GTK stuff for this window
647 AUPluginUI::parent_cocoa_window ()
649 NSWindow* win = get_nswindow ();
655 //[win setAutodisplay:1]; // turn off GTK stuff for this window
657 NSView* view = gdk_quartz_window_get_nsview (low_box.get_window()->gobj());
658 [view addSubview:au_view];
661 gtk_widget_translate_coordinates(
662 GTK_WIDGET(low_box.gobj()),
663 GTK_WIDGET(low_box.get_parent()->gobj()),
665 [au_view setFrame:NSMakeRect(xx, yy, req_width, req_height)];
667 last_au_frame = [au_view frame];
668 // watch for size changes of the view
669 _notify = [ [NotificationObject alloc] initWithPluginUI:this andCocoaParent:NULL andTopLevelParent:win ];
671 [[NSNotificationCenter defaultCenter] addObserver:_notify
672 selector:@selector(auViewResized:) name:NSViewFrameDidChangeNotification
679 AUPluginUI::grab_focus()
682 [au_view becomeFirstResponder];
686 AUPluginUI::forward_key_event (GdkEventKey* ev)
688 NSEvent* nsevent = gdk_quartz_event_get_nsevent ((GdkEvent*)ev);
690 if (au_view && nsevent) {
692 /* filter on nsevent type here because GDK massages FlagsChanged
693 messages into GDK_KEY_{PRESS,RELEASE} but Cocoa won't
694 handle a FlagsChanged message as a keyDown or keyUp
697 if ([nsevent type] == NSKeyDown) {
698 [[[au_view window] firstResponder] keyDown:nsevent];
699 } else if ([nsevent type] == NSKeyUp) {
700 [[[au_view window] firstResponder] keyUp:nsevent];
701 } else if ([nsevent type] == NSFlagsChanged) {
702 [[[au_view window] firstResponder] flagsChanged:nsevent];
708 AUPluginUI::on_realize ()
712 /* our windows should not have that resize indicator */
714 NSWindow* win = get_nswindow ();
716 [win setShowsResizeIndicator:0];
721 AUPluginUI::lower_box_realized ()
724 parent_cocoa_window ();
725 } else if (carbon_window) {
726 parent_carbon_window ();
731 AUPluginUI::lower_box_visibility_notify (GdkEventVisibility* ev)
734 if (carbon_window && ev->state != GDK_VISIBILITY_UNOBSCURED) {
735 ShowWindow (carbon_window);
736 ActivateWindow (carbon_window, TRUE);
744 AUPluginUI::update_view_size ()
746 if (!mapped || alo_width == 0 || alo_height == 0) {
750 gtk_widget_translate_coordinates(
751 GTK_WIDGET(low_box.gobj()),
752 GTK_WIDGET(low_box.get_parent()->gobj()),
755 [[NSNotificationCenter defaultCenter] removeObserver:_notify
756 name:NSViewFrameDidChangeNotification
760 xx += (alo_width - req_width) * .5;
761 [au_view setFrame:NSMakeRect(xx, yy, req_width, req_height)];
763 /* this mitigates issues with plugins that resize themselves
764 * depending on visible options (e.g AUSampler)
765 * since the OSX y-axis points upwards, the plugin adjusts its
766 * own y-offset if the view expands to the bottom to accomodate
767 * subviews inside the main view.
769 [au_view setAutoresizesSubviews:0];
770 [au_view setFrame:NSMakeRect(xx, yy, alo_width, alo_height)];
771 [au_view setAutoresizesSubviews:1];
772 [au_view setNeedsDisplay:1];
775 last_au_frame = [au_view frame];
777 [[NSNotificationCenter defaultCenter]
779 selector:@selector(auViewResized:) name:NSViewFrameDidChangeNotification
784 AUPluginUI::lower_box_map ()
787 [au_view setHidden:0];
792 AUPluginUI::lower_box_unmap ()
795 [au_view setHidden:1];
799 AUPluginUI::lower_box_size_request (GtkRequisition* requisition)
801 requisition->width = req_width;
802 requisition->height = req_height;
806 AUPluginUI::lower_box_size_allocate (Gtk::Allocation& allocation)
808 alo_width = allocation.get_width ();
809 alo_height = allocation.get_height ();
814 AUPluginUI::lower_box_expose (GdkEventExpose* event)
816 #if 0 // AU view magically redraws by itself
817 [au_view drawRect:NSMakeRect(event->area.x,
820 event->area.height)];
822 /* hack to keep ardour responsive
823 * some UIs (e.g Addictive Drums) completely hog the CPU
831 AUPluginUI::on_window_hide ()
835 HideWindow (carbon_window);
836 ActivateWindow (carbon_window, FALSE);
842 NSArray* wins = [NSApp windows];
843 for (uint32_t i = 0; i < [wins count]; i++) {
844 id win = [wins objectAtIndex:i];
850 AUPluginUI::on_window_show (const string& /*title*/)
852 /* this is idempotent so just call it every time we show the window */
854 gtk_widget_realize (GTK_WIDGET(low_box.gobj()));
860 ShowWindow (carbon_window);
861 ActivateWindow (carbon_window, TRUE);
869 AUPluginUI::start_updating (GdkEventAny*)
875 AUPluginUI::stop_updating (GdkEventAny*)
881 create_au_gui (boost::shared_ptr<PluginInsert> plugin_insert, VBox** box)
883 AUPluginUI* aup = new AUPluginUI (plugin_insert);