tidy up AU GUIs, make bypass button work and add preset/automation placeholders
[ardour.git] / gtk2_ardour / au_pluginui.mm
1 #include <pbd/error.h>
2 #include <ardour/audio_unit.h>
3 #include <ardour/insert.h>
4
5 #undef check // stupid gtk, stupid apple
6
7 #include <gtkmm/button.h>
8 #include <gdk/gdkquartz.h>
9
10 #include <gtkmm2ext/utils.h>
11
12 #include "au_pluginui.h"
13 #include "gui_thread.h"
14
15 #include <appleutility/CAAudioUnit.h>
16 #include <appleutility/CAComponent.h>
17
18 #import <AudioUnit/AUCocoaUIView.h>
19 #import <CoreAudioKit/AUGenericView.h>
20
21 #include "i18n.h"
22
23 using namespace ARDOUR;
24 using namespace Gtk;
25 using namespace Gtkmm2ext;
26 using namespace sigc;
27 using namespace std;
28 using namespace PBD;
29
30 vector<string> AUPluginUI::automation_mode_strings;
31
32 static const gchar* _automation_mode_strings[] = {
33         X_("Manual"),
34         X_("Play"),
35         X_("Write"),
36         X_("Touch"),
37         0
38 };
39
40 AUPluginUI::AUPluginUI (boost::shared_ptr<PluginInsert> insert)
41         : PlugUIBase (insert)
42         , automation_mode_label (_("Automation"))
43         , preset_label (_("Presets"))
44         
45 {
46         if (automation_mode_strings.empty()) {
47                 automation_mode_strings = I18N (_automation_mode_strings);
48         }
49         
50         set_popdown_strings (automation_mode_selector, automation_mode_strings);
51         automation_mode_selector.set_active_text (automation_mode_strings.front());
52
53         if ((au = boost::dynamic_pointer_cast<AUPlugin> (insert->plugin())) == 0) {
54                 error << _("unknown type of editor-supplying plugin (note: no AudioUnit support in this version of ardour)") << endmsg;
55                 throw failed_constructor ();
56         }
57
58         /* stuff some stuff into the top of the window */
59
60         top_box.set_spacing (6);
61         top_box.set_border_width (6);
62
63         top_box.pack_end (bypass_button, false, true);
64         top_box.pack_end (automation_mode_selector, false, false);
65         top_box.pack_end (automation_mode_label, false, false);
66         top_box.pack_end (save_button, false, false);
67         top_box.pack_end (preset_combo, false, false);
68         top_box.pack_end (preset_label, false, false);
69
70         set_spacing (6);
71         pack_start (top_box, false, false);
72         pack_start (low_box, false, false);
73
74         preset_label.show ();
75         preset_combo.show ();
76         automation_mode_label.show ();
77         automation_mode_selector.show ();
78         bypass_button.show ();
79         top_box.show ();
80         low_box.show ();
81
82         _activating_from_app = false;
83         cocoa_parent = 0;
84         cocoa_window = 0;
85         au_view = 0;
86
87         /* prefer cocoa, fall back to cocoa, but use carbon if its there */
88
89         if (test_cocoa_view_support()) {
90                 create_cocoa_view ();
91         } else if (test_carbon_view_support()) {
92                 create_carbon_view ();
93         } else {
94                 create_cocoa_view ();
95         }
96
97         low_box.signal_realize().connect (mem_fun (this, &AUPluginUI::lower_box_realized));
98 }
99
100 AUPluginUI::~AUPluginUI ()
101 {
102         if (cocoa_parent) {
103                 NSWindow* win = get_nswindow();
104                 RemoveEventHandler(carbon_event_handler);
105                 [win removeChildWindow:cocoa_parent];
106         } else if (carbon_window) {
107                 /* never parented */
108                 DisposeWindow (carbon_window);
109         }
110
111 }
112
113 bool
114 AUPluginUI::test_carbon_view_support ()
115 {
116         bool ret = false;
117         
118         carbon_descriptor.componentType = kAudioUnitCarbonViewComponentType;
119         carbon_descriptor.componentSubType = 'gnrc';
120         carbon_descriptor.componentManufacturer = 'appl';
121         carbon_descriptor.componentFlags = 0;
122         carbon_descriptor.componentFlagsMask = 0;
123         
124         OSStatus err;
125
126         // ask the AU for its first editor component
127         UInt32 propertySize;
128         err = AudioUnitGetPropertyInfo(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, &propertySize, NULL);
129         if (!err) {
130                 int nEditors = propertySize / sizeof(ComponentDescription);
131                 ComponentDescription *editors = new ComponentDescription[nEditors];
132                 err = AudioUnitGetProperty(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, editors, &propertySize);
133                 if (!err) {
134                         // just pick the first one for now
135                         carbon_descriptor = editors[0];
136                         ret = true;
137                 }
138                 delete[] editors;
139         }
140
141         return ret;
142 }
143         
144 bool
145 AUPluginUI::test_cocoa_view_support ()
146 {
147         UInt32 dataSize   = 0;
148         Boolean isWritable = 0;
149         OSStatus err = AudioUnitGetPropertyInfo(*au->get_au(),
150                                                 kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
151                                                 0, &dataSize, &isWritable);
152         
153         return dataSize > 0 && err == noErr;
154 }
155
156 bool
157 AUPluginUI::plugin_class_valid (Class pluginClass)
158 {
159         if([pluginClass conformsToProtocol: @protocol(AUCocoaUIBase)]) {
160                 if([pluginClass instancesRespondToSelector: @selector(interfaceVersion)] &&
161                    [pluginClass instancesRespondToSelector: @selector(uiViewForAudioUnit:withSize:)]) {
162                                 return true;
163                 }
164         }
165         return false;
166 }
167
168 int
169 AUPluginUI::create_cocoa_view ()
170 {
171         BOOL wasAbleToLoadCustomView = NO;
172         AudioUnitCocoaViewInfo* cocoaViewInfo = NULL;
173         UInt32               numberOfClasses = 0;
174         UInt32     dataSize;
175         Boolean    isWritable;
176         NSString*           factoryClassName = 0;
177         NSURL*              CocoaViewBundlePath;
178
179         OSStatus result = AudioUnitGetPropertyInfo (*au->get_au(),
180                                                     kAudioUnitProperty_CocoaUI,
181                                                     kAudioUnitScope_Global, 
182                                                     0,
183                                                     &dataSize,
184                                                     &isWritable );
185
186         numberOfClasses = (dataSize - sizeof(CFURLRef)) / sizeof(CFStringRef);
187         
188         // Does view have custom Cocoa UI?
189         
190         if ((result == noErr) && (numberOfClasses > 0) ) {
191                 cocoaViewInfo = (AudioUnitCocoaViewInfo *)malloc(dataSize);
192                 if(AudioUnitGetProperty(*au->get_au(),
193                                         kAudioUnitProperty_CocoaUI,
194                                         kAudioUnitScope_Global,
195                                         0,
196                                         cocoaViewInfo,
197                                         &dataSize) == noErr) {
198
199                         CocoaViewBundlePath     = (NSURL *)cocoaViewInfo->mCocoaAUViewBundleLocation;
200                         
201                         // we only take the first view in this example.
202                         factoryClassName        = (NSString *)cocoaViewInfo->mCocoaAUViewClass[0];
203
204                 } else {
205
206                         if (cocoaViewInfo != NULL) {
207                                 free (cocoaViewInfo);
208                                 cocoaViewInfo = NULL;
209                         }
210                 }
211         }
212
213         NSRect crect = { { 0, 0 }, { 1, 1} };
214
215         // [A] Show custom UI if view has it
216
217         if (CocoaViewBundlePath && factoryClassName) {
218                 NSBundle *viewBundle    = [NSBundle bundleWithPath:[CocoaViewBundlePath path]];
219                 if (viewBundle == nil) {
220                         error << _("AUPluginUI: error loading AU view's bundle") << endmsg;
221                         return -1;
222                 } else {
223                         Class factoryClass = [viewBundle classNamed:factoryClassName];
224                         if (!factoryClass) {
225                                 error << _("AUPluginUI: error getting AU view's factory class from bundle") << endmsg;
226                                 return -1;
227                         }
228                         
229                         // make sure 'factoryClass' implements the AUCocoaUIBase protocol
230                         if (!plugin_class_valid (factoryClass)) {
231                                 error << _("AUPluginUI: U view's factory class does not properly implement the AUCocoaUIBase protocol") << endmsg;
232                                 return -1;
233                         }
234                         // make a factory
235                         id factoryInstance = [[[factoryClass alloc] init] autorelease];
236                         if (factoryInstance == nil) {
237                                 error << _("AUPluginUI: Could not create an instance of the AU view factory") << endmsg;
238                                 return -1;
239                         }
240
241                         // make a view
242                         au_view = [factoryInstance uiViewForAudioUnit:*au->get_au() withSize:crect.size];
243                         
244                         // cleanup
245                         [CocoaViewBundlePath release];
246                         if (cocoaViewInfo) {
247                                 UInt32 i;
248                                 for (i = 0; i < numberOfClasses; i++)
249                                         CFRelease(cocoaViewInfo->mCocoaAUViewClass[i]);
250                                 
251                                 free (cocoaViewInfo);
252                         }
253                         wasAbleToLoadCustomView = YES;
254                 }
255         }
256
257         if (!wasAbleToLoadCustomView) {
258                 // load generic Cocoa view
259                 au_view = [[AUGenericView alloc] initWithAudioUnit:*au->get_au()];
260                 [(AUGenericView *)au_view setShowsExpertParameters:YES];
261         }
262
263         return 0;
264 }
265
266 int
267 AUPluginUI::create_carbon_view ()
268 {
269         OSStatus err;
270         ControlRef root_control;
271
272         Component editComponent = FindNextComponent(NULL, &carbon_descriptor);
273         
274         OpenAComponent(editComponent, &editView);
275         if (!editView) {
276                 error << _("AU Carbon view: cannot open AU Component") << endmsg;
277                 return -1;
278         }
279         
280         Rect r = { 100, 100, 100, 100 };
281         WindowAttributes attr = WindowAttributes (kWindowStandardHandlerAttribute |
282                                                   kWindowCompositingAttribute|
283                                                   kWindowNoShadowAttribute|
284                                                   kWindowNoTitleBarAttribute);
285
286         if ((err = CreateNewWindow(kDocumentWindowClass, attr, &r, &carbon_window)) != noErr) {
287                 error << string_compose (_("AUPluginUI: cannot create carbon window (err: %1)"), err) << endmsg;
288                 return -1;
289         }
290         
291         if ((err = GetRootControl(carbon_window, &root_control)) != noErr) {
292                 error << string_compose (_("AUPlugin: cannot get root control of carbon window (err: %1)"), err) << endmsg;
293                 return -1;
294         }
295
296         ControlRef viewPane;
297         Float32Point location  = { 0.0, 0.0 };
298         Float32Point size = { 0.0, 0.0 } ;
299
300         if ((err = AudioUnitCarbonViewCreate (editView, *au->get_au(), carbon_window, root_control, &location, &size, &viewPane)) != noErr) {
301                 error << string_compose (_("AUPluginUI: cannot create carbon plugin view (err: %1)"), err) << endmsg;
302                 return -1;
303         }
304
305         // resize window
306
307         Rect bounds;
308         GetControlBounds(viewPane, &bounds);
309         size.x = bounds.right-bounds.left;
310         size.y = bounds.bottom-bounds.top;
311
312         prefwidth = (int) (size.x + 0.5);
313         prefheight = (int) (size.y + 0.5);
314
315         SizeWindow (carbon_window, prefwidth, prefheight,  true);
316         low_box.set_size_request (prefwidth, prefheight);
317
318         return 0;
319 }
320
321 NSWindow*
322 AUPluginUI::get_nswindow ()
323 {
324         Gtk::Container* toplevel = get_toplevel();
325
326         if (!toplevel || !toplevel->is_toplevel()) {
327                 error << _("AUPluginUI: no top level window!") << endmsg;
328                 return 0;
329         }
330
331         NSWindow* true_parent = gdk_quartz_window_get_nswindow (toplevel->get_window()->gobj());
332
333         if (!true_parent) {
334                 error << _("AUPluginUI: no top level window!") << endmsg;
335                 return 0;
336         }
337
338         return true_parent;
339 }
340
341 void
342 AUPluginUI::activate ()
343 {
344         cerr << "AUPluginUI:: activate!\n";
345
346         if (carbon_window && cocoa_parent) {
347                 cerr << "APP activated, activate carbon window " << insert->name() << endl;
348                 _activating_from_app = true;
349                 ActivateWindow (carbon_window, TRUE);
350                 _activating_from_app = false;
351                 [cocoa_parent makeKeyAndOrderFront:nil];
352         } 
353 }
354
355 void
356 AUPluginUI::deactivate ()
357 {
358         cerr << "APP DEactivated, for " << insert->name() << endl;
359         _activating_from_app = true;
360         ActivateWindow (carbon_window, FALSE);
361         _activating_from_app = false;
362 }
363
364
365 OSStatus 
366 _carbon_event (EventHandlerCallRef nextHandlerRef, EventRef event, void *userData) 
367 {
368         return ((AUPluginUI*)userData)->carbon_event (nextHandlerRef, event);
369 }
370
371 OSStatus 
372 AUPluginUI::carbon_event (EventHandlerCallRef nextHandlerRef, EventRef event)
373 {
374         cerr << "CARBON EVENT\n";
375
376         UInt32 eventKind = GetEventKind(event);
377         ClickActivationResult howToHandleClick;
378         NSWindow* win = get_nswindow ();
379
380         cerr << "window " << win << " carbon event type " << eventKind << endl;
381
382         switch (eventKind) {
383         case kEventWindowHandleActivate:
384                 cerr << "carbon window for " << insert->name() << " activated\n";
385                 if (_activating_from_app) {
386                         cerr << "app activation, ignore window activation\n";
387                         return noErr;
388                 }
389                 [win makeMainWindow];
390                 return eventNotHandledErr;
391                 break;
392
393         case kEventWindowHandleDeactivate:
394                 cerr << "carbon window for " << insert->name() << " deactivated\n";
395                 // never deactivate the carbon window
396                 return noErr;
397                 break;
398                 
399         case kEventWindowGetClickActivation:
400                 cerr << "carbon window CLICK activated\n";
401                 [win makeKeyAndOrderFront:nil];
402                 howToHandleClick = kActivateAndHandleClick;
403                 SetEventParameter(event, kEventParamClickActivation, typeClickActivationResult, 
404                                   sizeof(ClickActivationResult), &howToHandleClick);
405                 break;
406         }
407
408         return noErr;
409 }
410
411 int
412 AUPluginUI::parent_carbon_window ()
413 {
414         NSWindow* win = get_nswindow ();
415         int x, y;
416
417         if (!win) {
418                 return -1;
419         }
420
421         Gtk::Container* toplevel = get_toplevel();
422
423         if (!toplevel || !toplevel->is_toplevel()) {
424                 error << _("AUPluginUI: no top level window!") << endmsg;
425                 return -1;
426         }
427         
428         toplevel->get_window()->get_root_origin (x, y);
429
430         /* compute how tall the title bar is, because we have to offset the position of the carbon window
431            by that much.
432         */
433
434         NSRect content_frame = [NSWindow contentRectForFrameRect:[win frame] styleMask:[win styleMask]];
435         NSRect wm_frame = [NSWindow frameRectForContentRect:content_frame styleMask:[win styleMask]];
436
437         int titlebar_height = wm_frame.size.height - content_frame.size.height;
438
439         int packing_extra = 6; // this is the total vertical packing in our top level window
440
441         MoveWindow (carbon_window, x, y + titlebar_height + top_box.get_height() + packing_extra, false);
442         ShowWindow (carbon_window);
443
444         // create the cocoa window for the carbon one and make it visible
445         cocoa_parent = [[NSWindow alloc] initWithWindowRef: carbon_window];
446
447         EventTypeSpec   windowEventTypes[] = {
448                 {kEventClassWindow, kEventWindowGetClickActivation },
449                 {kEventClassWindow, kEventWindowHandleDeactivate }
450         };
451         
452         EventHandlerUPP   ehUPP = NewEventHandlerUPP(_carbon_event);
453         OSStatus result = InstallWindowEventHandler (carbon_window, ehUPP, 
454                                                      sizeof(windowEventTypes) / sizeof(EventTypeSpec), 
455                                                      windowEventTypes, this, &carbon_event_handler);
456         if (result != noErr) {
457                 return -1;
458         }
459
460         [win addChildWindow:cocoa_parent ordered:NSWindowAbove];
461
462         return 0;
463 }       
464
465 int
466 AUPluginUI::parent_cocoa_window ()
467 {
468         NSWindow* win = get_nswindow ();
469         NSView* packView = 0;
470         NSRect packFrame;
471
472         if (!win) {
473                 return -1;
474         }
475
476         Gtk::Container* toplevel = get_toplevel();
477
478         if (!toplevel || !toplevel->is_toplevel()) {
479                 error << _("AUPluginUI: no top level window!") << endmsg;
480                 return -1;
481         }
482         
483         // Get the size of the new AU View's frame 
484         packFrame = [au_view frame];
485         packFrame.origin.x = 0;
486         packFrame.origin.y = 0;
487
488         if (packFrame.size.width > 500 || packFrame.size.height > 500) {
489                 
490                 /* its too big - use a scrollview */
491
492                 NSRect frameRect = [[cocoa_window contentView] frame];
493                 scroll_view = [[[NSScrollView alloc] initWithFrame:frameRect] autorelease];
494                 [scroll_view setDrawsBackground:NO];
495                 [scroll_view setHasHorizontalScroller:YES];
496                 [scroll_view setHasVerticalScroller:YES];
497
498                 packFrame.size = [NSScrollView  frameSizeForContentSize:packFrame.size
499                                     hasHorizontalScroller:[scroll_view hasHorizontalScroller]
500                                     hasVerticalScroller:[scroll_view hasVerticalScroller]
501                                     borderType:[scroll_view borderType]];
502                 
503                 // Create a new frame with same origin as current
504                 // frame but size equal to the size of the new view
505                 NSRect newFrame;
506                 newFrame.origin = [scroll_view frame].origin;
507                 newFrame.size = packFrame.size;
508                 
509                 // Set the new frame and document views on the scroll view
510                 [scroll_view setFrame:newFrame];
511                 [scroll_view setDocumentView:au_view];
512                 
513                 packView = scroll_view;
514
515         } else {
516
517                 packView = au_view;
518         }
519
520         NSView* view = gdk_quartz_window_get_nsview (low_box.get_window()->gobj());
521         
522         [view setFrame:packFrame];
523         [view addSubview:packView]; 
524
525         low_box.set_size_request (packFrame.size.width, packFrame.size.height);
526
527         return 0;
528 }
529
530 void
531 AUPluginUI::on_realize ()
532 {
533         VBox::on_realize ();
534
535         /* our windows should not have that resize indicator */
536
537         NSWindow* win = get_nswindow ();
538         if (win) {
539                 [win setShowsResizeIndicator:NO];
540         }
541 }
542
543 void
544 AUPluginUI::lower_box_realized ()
545 {
546         if (au_view) {
547                 parent_cocoa_window ();
548         } else if (carbon_window) {
549                 parent_carbon_window ();
550         }
551 }
552
553 void
554 AUPluginUI::on_hide ()
555 {
556         // VBox::on_hide ();
557         cerr << "AU plugin window hidden\n";
558 }
559
560 bool
561 AUPluginUI::on_map_event (GdkEventAny* ev)
562 {
563         cerr << "AU plugin map event\n";
564
565         if (carbon_window) {
566
567                 // move top level GTK window to the correct level
568                 // to keep the stack together and not be sliceable
569                 
570                 NSWindow* win = get_nswindow ();
571                 // [win setLevel:NSFloatingWindowLevel];
572         }
573
574         return false;
575 }
576
577 void
578 AUPluginUI::on_show ()
579 {
580         cerr << "AU plugin window shown\n";
581
582         VBox::on_show ();
583
584         gtk_widget_realize (GTK_WIDGET(low_box.gobj()));
585
586         if (au_view) {
587                 show_all ();
588         } else if (carbon_window) {
589                 [cocoa_parent setIsVisible:YES];
590                 ShowWindow (carbon_window);
591         }
592 }
593
594 bool
595 AUPluginUI::start_updating (GdkEventAny* any)
596 {
597         return false;
598 }
599
600 bool
601 AUPluginUI::stop_updating (GdkEventAny* any)
602 {
603         return false;
604 }
605
606 PlugUIBase*
607 create_au_gui (boost::shared_ptr<PluginInsert> plugin_insert, VBox** box)
608 {
609         AUPluginUI* aup = new AUPluginUI (plugin_insert);
610         (*box) = aup;
611         return aup;
612 }
613
614 bool
615 AUPluginUI::on_focus_in_event (GdkEventFocus* ev)
616 {
617         cerr << "au plugin focus in\n";
618         return false;
619 }
620
621 bool
622 AUPluginUI::on_focus_out_event (GdkEventFocus* ev)
623 {
624         cerr << "au plugin focus out\n";
625         return false;
626 }
627