do not attempt to use scroll view for AU plugin GUIs (fixes crash-on-delete of Cocoa...
[ardour2.git] / gtk2_ardour / au_pluginui.mm
blob1d7029365a87b0656a06ca82d49e45f018a0bfb9
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 AUPluginUI::AUPluginUI (boost::shared_ptr<PluginInsert> insert)
49         : PlugUIBase (insert)
50         , automation_mode_label (_("Automation"))
51         , preset_label (_("Presets"))
52         
54         if (automation_mode_strings.empty()) {
55                 automation_mode_strings = I18N (_automation_mode_strings);
56         }
57         
58         set_popdown_strings (automation_mode_selector, automation_mode_strings);
59         automation_mode_selector.set_active_text (automation_mode_strings.front());
61         if ((au = boost::dynamic_pointer_cast<AUPlugin> (insert->plugin())) == 0) {
62                 error << _("unknown type of editor-supplying plugin (note: no AudioUnit support in this version of ardour)") << endmsg;
63                 throw failed_constructor ();
64         }
66         /* stuff some stuff into the top of the window */
68         HBox* smaller_hbox = manage (new HBox);
70         smaller_hbox->set_spacing (6);
71         smaller_hbox->pack_start (preset_label, false, false, 4);
72         smaller_hbox->pack_start (preset_combo, false, false);
73         smaller_hbox->pack_start (save_button, false, false);
74         smaller_hbox->pack_start (automation_mode_label, false, false);
75         smaller_hbox->pack_start (automation_mode_selector, false, false);
76         smaller_hbox->pack_start (bypass_button, false, true);
78         VBox* v1_box = manage (new VBox);
79         VBox* v2_box = manage (new VBox);
81         v1_box->pack_start (*smaller_hbox, false, true);
82         v2_box->pack_start (focus_button, false, true);
84         top_box.set_homogeneous (false);
85         top_box.set_spacing (6);
86         top_box.set_border_width (6);
88         top_box.pack_end (*v2_box, false, false);
89         top_box.pack_end (*v1_box, false, false);
91         set_spacing (6);
92         pack_start (top_box, false, false);
93         pack_start (low_box, false, false);
95         preset_label.show ();
96         preset_combo.show ();
97         automation_mode_label.show ();
98         automation_mode_selector.show ();
99         bypass_button.show ();
100         top_box.show ();
101         low_box.show ();
103         _activating_from_app = false;
104         cocoa_parent = 0;
105         cocoa_window = 0;
106         au_view = 0;
107         packView = 0;
109         /* prefer cocoa, fall back to cocoa, but use carbon if its there */
111         if (test_cocoa_view_support()) {
112                 create_cocoa_view ();
113         } else if (test_carbon_view_support()) {
114                 create_carbon_view ();
115         } else {
116                 create_cocoa_view ();
117         }
119         low_box.signal_realize().connect (mem_fun (this, &AUPluginUI::lower_box_realized));
122 AUPluginUI::~AUPluginUI ()
124         if (cocoa_parent) {
125                 NSWindow* win = get_nswindow();
126                 RemoveEventHandler(carbon_event_handler);
127                 [win removeChildWindow:cocoa_parent];
128         } else if (carbon_window) {
129                 /* never parented */
130                 DisposeWindow (carbon_window);
131         }
133         if (packView) {
134                 /* remove whatever we packed into low_box so that GTK doesn't
135                    mess with it.
136                 */
138                 [packView removeFromSuperview];
139         }
142 bool
143 AUPluginUI::test_carbon_view_support ()
145         bool ret = false;
146         
147         carbon_descriptor.componentType = kAudioUnitCarbonViewComponentType;
148         carbon_descriptor.componentSubType = 'gnrc';
149         carbon_descriptor.componentManufacturer = 'appl';
150         carbon_descriptor.componentFlags = 0;
151         carbon_descriptor.componentFlagsMask = 0;
152         
153         OSStatus err;
155         // ask the AU for its first editor component
156         UInt32 propertySize;
157         err = AudioUnitGetPropertyInfo(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, &propertySize, NULL);
158         if (!err) {
159                 int nEditors = propertySize / sizeof(ComponentDescription);
160                 ComponentDescription *editors = new ComponentDescription[nEditors];
161                 err = AudioUnitGetProperty(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, editors, &propertySize);
162                 if (!err) {
163                         // just pick the first one for now
164                         carbon_descriptor = editors[0];
165                         ret = true;
166                 }
167                 delete[] editors;
168         }
170         return ret;
172         
173 bool
174 AUPluginUI::test_cocoa_view_support ()
176         UInt32 dataSize   = 0;
177         Boolean isWritable = 0;
178         OSStatus err = AudioUnitGetPropertyInfo(*au->get_au(),
179                                                 kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
180                                                 0, &dataSize, &isWritable);
181         
182         return dataSize > 0 && err == noErr;
185 bool
186 AUPluginUI::plugin_class_valid (Class pluginClass)
188         if([pluginClass conformsToProtocol: @protocol(AUCocoaUIBase)]) {
189                 if([pluginClass instancesRespondToSelector: @selector(interfaceVersion)] &&
190                    [pluginClass instancesRespondToSelector: @selector(uiViewForAudioUnit:withSize:)]) {
191                                 return true;
192                 }
193         }
194         return false;
198 AUPluginUI::create_cocoa_view ()
200         BOOL wasAbleToLoadCustomView = NO;
201         AudioUnitCocoaViewInfo* cocoaViewInfo = NULL;
202         UInt32               numberOfClasses = 0;
203         UInt32     dataSize;
204         Boolean    isWritable;
205         NSString*           factoryClassName = 0;
206         NSURL*              CocoaViewBundlePath;
208         OSStatus result = AudioUnitGetPropertyInfo (*au->get_au(),
209                                                     kAudioUnitProperty_CocoaUI,
210                                                     kAudioUnitScope_Global, 
211                                                     0,
212                                                     &dataSize,
213                                                     &isWritable );
215         numberOfClasses = (dataSize - sizeof(CFURLRef)) / sizeof(CFStringRef);
216         
217         // Does view have custom Cocoa UI?
218         
219         if ((result == noErr) && (numberOfClasses > 0) ) {
220                 cocoaViewInfo = (AudioUnitCocoaViewInfo *)malloc(dataSize);
221                 if(AudioUnitGetProperty(*au->get_au(),
222                                         kAudioUnitProperty_CocoaUI,
223                                         kAudioUnitScope_Global,
224                                         0,
225                                         cocoaViewInfo,
226                                         &dataSize) == noErr) {
228                         CocoaViewBundlePath     = (NSURL *)cocoaViewInfo->mCocoaAUViewBundleLocation;
229                         
230                         // we only take the first view in this example.
231                         factoryClassName        = (NSString *)cocoaViewInfo->mCocoaAUViewClass[0];
233                 } else {
235                         if (cocoaViewInfo != NULL) {
236                                 free (cocoaViewInfo);
237                                 cocoaViewInfo = NULL;
238                         }
239                 }
240         }
242         NSRect crect = { { 0, 0 }, { 1, 1} };
244         // [A] Show custom UI if view has it
246         if (CocoaViewBundlePath && factoryClassName) {
247                 NSBundle *viewBundle    = [NSBundle bundleWithPath:[CocoaViewBundlePath path]];
248                 if (viewBundle == nil) {
249                         error << _("AUPluginUI: error loading AU view's bundle") << endmsg;
250                         return -1;
251                 } else {
252                         Class factoryClass = [viewBundle classNamed:factoryClassName];
253                         if (!factoryClass) {
254                                 error << _("AUPluginUI: error getting AU view's factory class from bundle") << endmsg;
255                                 return -1;
256                         }
257                         
258                         // make sure 'factoryClass' implements the AUCocoaUIBase protocol
259                         if (!plugin_class_valid (factoryClass)) {
260                                 error << _("AUPluginUI: U view's factory class does not properly implement the AUCocoaUIBase protocol") << endmsg;
261                                 return -1;
262                         }
263                         // make a factory
264                         id factoryInstance = [[[factoryClass alloc] init] autorelease];
265                         if (factoryInstance == nil) {
266                                 error << _("AUPluginUI: Could not create an instance of the AU view factory") << endmsg;
267                                 return -1;
268                         }
270                         // make a view
271                         au_view = [factoryInstance uiViewForAudioUnit:*au->get_au() withSize:crect.size];
272                         
273                         // cleanup
274                         [CocoaViewBundlePath release];
275                         if (cocoaViewInfo) {
276                                 UInt32 i;
277                                 for (i = 0; i < numberOfClasses; i++)
278                                         CFRelease(cocoaViewInfo->mCocoaAUViewClass[i]);
279                                 
280                                 free (cocoaViewInfo);
281                         }
282                         wasAbleToLoadCustomView = YES;
283                 }
284         }
286         if (!wasAbleToLoadCustomView) {
287                 // load generic Cocoa view
288                 au_view = [[AUGenericView alloc] initWithAudioUnit:*au->get_au()];
289                 [(AUGenericView *)au_view setShowsExpertParameters:YES];
290         }
292         packView = au_view;
294         // Get the size of the new AU View's frame 
295         
296         NSRect packFrame;
297         packFrame = [au_view frame];
298         prefwidth = packFrame.size.width;
299         prefheight = packFrame.size.height;
301         return 0;
305 AUPluginUI::create_carbon_view ()
307         OSStatus err;
308         ControlRef root_control;
310         Component editComponent = FindNextComponent(NULL, &carbon_descriptor);
311         
312         OpenAComponent(editComponent, &editView);
313         if (!editView) {
314                 error << _("AU Carbon view: cannot open AU Component") << endmsg;
315                 return -1;
316         }
317         
318         Rect r = { 100, 100, 100, 100 };
319         WindowAttributes attr = WindowAttributes (kWindowStandardHandlerAttribute |
320                                                   kWindowCompositingAttribute|
321                                                   kWindowNoShadowAttribute|
322                                                   kWindowNoTitleBarAttribute);
324         if ((err = CreateNewWindow(kDocumentWindowClass, attr, &r, &carbon_window)) != noErr) {
325                 error << string_compose (_("AUPluginUI: cannot create carbon window (err: %1)"), err) << endmsg;
326                 return -1;
327         }
328         
329         if ((err = GetRootControl(carbon_window, &root_control)) != noErr) {
330                 error << string_compose (_("AUPlugin: cannot get root control of carbon window (err: %1)"), err) << endmsg;
331                 return -1;
332         }
334         ControlRef viewPane;
335         Float32Point location  = { 0.0, 0.0 };
336         Float32Point size = { 0.0, 0.0 } ;
338         if ((err = AudioUnitCarbonViewCreate (editView, *au->get_au(), carbon_window, root_control, &location, &size, &viewPane)) != noErr) {
339                 error << string_compose (_("AUPluginUI: cannot create carbon plugin view (err: %1)"), err) << endmsg;
340                 return -1;
341         }
343         // resize window
345         Rect bounds;
346         GetControlBounds(viewPane, &bounds);
347         size.x = bounds.right-bounds.left;
348         size.y = bounds.bottom-bounds.top;
350         prefwidth = (int) (size.x + 0.5);
351         prefheight = (int) (size.y + 0.5);
353         SizeWindow (carbon_window, prefwidth, prefheight,  true);
354         low_box.set_size_request (prefwidth, prefheight);
356         return 0;
359 NSWindow*
360 AUPluginUI::get_nswindow ()
362         Gtk::Container* toplevel = get_toplevel();
364         if (!toplevel || !toplevel->is_toplevel()) {
365                 error << _("AUPluginUI: no top level window!") << endmsg;
366                 return 0;
367         }
369         NSWindow* true_parent = gdk_quartz_window_get_nswindow (toplevel->get_window()->gobj());
371         if (!true_parent) {
372                 error << _("AUPluginUI: no top level window!") << endmsg;
373                 return 0;
374         }
376         return true_parent;
379 void
380 AUPluginUI::activate ()
382         if (carbon_window && cocoa_parent) {
383                 cerr << "APP activated, activate carbon window " << insert->name() << endl;
384                 _activating_from_app = true;
385                 ActivateWindow (carbon_window, TRUE);
386                 _activating_from_app = false;
387                 [cocoa_parent makeKeyAndOrderFront:nil];
388         } 
391 void
392 AUPluginUI::deactivate ()
394         return;
395         cerr << "APP DEactivated, for " << insert->name() << endl;
396         _activating_from_app = true;
397         ActivateWindow (carbon_window, FALSE);
398         _activating_from_app = false;
402 OSStatus 
403 _carbon_event (EventHandlerCallRef nextHandlerRef, EventRef event, void *userData) 
405         return ((AUPluginUI*)userData)->carbon_event (nextHandlerRef, event);
408 OSStatus 
409 AUPluginUI::carbon_event (EventHandlerCallRef nextHandlerRef, EventRef event)
411         cerr << "CARBON EVENT\n";
413         UInt32 eventKind = GetEventKind(event);
414         ClickActivationResult howToHandleClick;
415         NSWindow* win = get_nswindow ();
417         cerr << "window " << win << " carbon event type " << eventKind << endl;
419         switch (eventKind) {
420         case kEventWindowHandleActivate:
421                 cerr << "carbon window for " << insert->name() << " activated\n";
422                 if (_activating_from_app) {
423                         cerr << "app activation, ignore window activation\n";
424                         return noErr;
425                 }
426                 [win makeMainWindow];
427                 return eventNotHandledErr;
428                 break;
430         case kEventWindowHandleDeactivate:
431                 cerr << "carbon window for " << insert->name() << " would have been deactivated\n";
432                 // never deactivate the carbon window
433                 return noErr;
434                 break;
435                 
436         case kEventWindowGetClickActivation:
437                 cerr << "carbon window CLICK activated\n";
438                 [win makeKeyAndOrderFront:nil];
439                 howToHandleClick = kActivateAndHandleClick;
440                 SetEventParameter(event, kEventParamClickActivation, typeClickActivationResult, 
441                                   sizeof(ClickActivationResult), &howToHandleClick);
442                 break;
443         }
445         return noErr;
449 AUPluginUI::parent_carbon_window ()
451         NSWindow* win = get_nswindow ();
452         int x, y;
454         if (!win) {
455                 return -1;
456         }
458         Gtk::Container* toplevel = get_toplevel();
460         if (!toplevel || !toplevel->is_toplevel()) {
461                 error << _("AUPluginUI: no top level window!") << endmsg;
462                 return -1;
463         }
464         
465         toplevel->get_window()->get_root_origin (x, y);
467         /* compute how tall the title bar is, because we have to offset the position of the carbon window
468            by that much.
469         */
471         NSRect content_frame = [NSWindow contentRectForFrameRect:[win frame] styleMask:[win styleMask]];
472         NSRect wm_frame = [NSWindow frameRectForContentRect:content_frame styleMask:[win styleMask]];
474         int titlebar_height = wm_frame.size.height - content_frame.size.height;
476         int packing_extra = 6; // this is the total vertical packing in our top level window
478         MoveWindow (carbon_window, x, y + titlebar_height + top_box.get_height() + packing_extra, false);
479         ShowWindow (carbon_window);
481         // create the cocoa window for the carbon one and make it visible
482         cocoa_parent = [[NSWindow alloc] initWithWindowRef: carbon_window];
484         EventTypeSpec   windowEventTypes[] = {
485                 {kEventClassWindow, kEventWindowGetClickActivation },
486                 {kEventClassWindow, kEventWindowHandleDeactivate }
487         };
488         
489         EventHandlerUPP   ehUPP = NewEventHandlerUPP(_carbon_event);
490         OSStatus result = InstallWindowEventHandler (carbon_window, ehUPP, 
491                                                      sizeof(windowEventTypes) / sizeof(EventTypeSpec), 
492                                                      windowEventTypes, this, &carbon_event_handler);
493         if (result != noErr) {
494                 return -1;
495         }
497         [win addChildWindow:cocoa_parent ordered:NSWindowAbove];
499         return 0;
500 }       
503 AUPluginUI::parent_cocoa_window ()
505         NSWindow* win = get_nswindow ();
506         NSRect packFrame;
508         if (!win) {
509                 return -1;
510         }
512         [win setAutodisplay:YES]; // turn of GTK stuff for this window
514         Gtk::Container* toplevel = get_toplevel();
516         if (!toplevel || !toplevel->is_toplevel()) {
517                 error << _("AUPluginUI: no top level window!") << endmsg;
518                 return -1;
519         }
520         
521         // Get the size of the new AU View's frame 
522         packFrame = [au_view frame];
524         NSView* view = gdk_quartz_window_get_nsview (low_box.get_window()->gobj());
526         [view setFrame:packFrame];
527         [view addSubview:packView]; 
529         low_box.set_size_request (packFrame.size.width, packFrame.size.height);
531         return 0;
534 void
535 AUPluginUI::on_realize ()
537         VBox::on_realize ();
539         /* our windows should not have that resize indicator */
541         NSWindow* win = get_nswindow ();
542         if (win) {
543                 [win setShowsResizeIndicator:NO];
544         }
547 void
548 AUPluginUI::lower_box_realized ()
550         if (au_view) {
551                 parent_cocoa_window ();
552         } else if (carbon_window) {
553                 parent_carbon_window ();
554         }
557 void
558 AUPluginUI::on_hide ()
560         // VBox::on_hide ();
561         cerr << "AU plugin window hidden\n";
564 bool
565 AUPluginUI::on_map_event (GdkEventAny* ev)
567         return false;
570 void
571 AUPluginUI::on_show ()
573         cerr << "AU plugin window shown\n";
575         VBox::on_show ();
577         gtk_widget_realize (GTK_WIDGET(low_box.gobj()));
579         if (au_view) {
580                 show_all ();
581         } else if (carbon_window) {
582                 [cocoa_parent setIsVisible:YES];
583                 ShowWindow (carbon_window);
584         }
587 bool
588 AUPluginUI::start_updating (GdkEventAny* any)
590         return false;
593 bool
594 AUPluginUI::stop_updating (GdkEventAny* any)
596         return false;
599 PlugUIBase*
600 create_au_gui (boost::shared_ptr<PluginInsert> plugin_insert, VBox** box)
602         AUPluginUI* aup = new AUPluginUI (plugin_insert);
603         (*box) = aup;
604         return aup;
607 bool
608 AUPluginUI::on_focus_in_event (GdkEventFocus* ev)
610         //cerr << "au plugin focus in\n";
611         //Keyboard::magic_widget_grab_focus ();
612         return false;
615 bool
616 AUPluginUI::on_focus_out_event (GdkEventFocus* ev)
618         //cerr << "au plugin focus out\n";
619         //Keyboard::magic_widget_drop_focus ();
620         return false;