ab14d4aafdb9ecdf1ee557902bb26cf56e94837c
[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         packView = 0;
87
88         /* prefer cocoa, fall back to cocoa, but use carbon if its there */
89
90         if (test_cocoa_view_support()) {
91                 create_cocoa_view ();
92         } else if (test_carbon_view_support()) {
93                 create_carbon_view ();
94         } else {
95                 create_cocoa_view ();
96         }
97
98         low_box.signal_realize().connect (mem_fun (this, &AUPluginUI::lower_box_realized));
99 }
100
101 AUPluginUI::~AUPluginUI ()
102 {
103         if (cocoa_parent) {
104                 NSWindow* win = get_nswindow();
105                 RemoveEventHandler(carbon_event_handler);
106                 [win removeChildWindow:cocoa_parent];
107         } else if (carbon_window) {
108                 /* never parented */
109                 DisposeWindow (carbon_window);
110         }
111
112         if (packView && packView != au_view) {
113                 [packView release];
114         }
115 }
116
117 bool
118 AUPluginUI::test_carbon_view_support ()
119 {
120         bool ret = false;
121         
122         carbon_descriptor.componentType = kAudioUnitCarbonViewComponentType;
123         carbon_descriptor.componentSubType = 'gnrc';
124         carbon_descriptor.componentManufacturer = 'appl';
125         carbon_descriptor.componentFlags = 0;
126         carbon_descriptor.componentFlagsMask = 0;
127         
128         OSStatus err;
129
130         // ask the AU for its first editor component
131         UInt32 propertySize;
132         err = AudioUnitGetPropertyInfo(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, &propertySize, NULL);
133         if (!err) {
134                 int nEditors = propertySize / sizeof(ComponentDescription);
135                 ComponentDescription *editors = new ComponentDescription[nEditors];
136                 err = AudioUnitGetProperty(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, editors, &propertySize);
137                 if (!err) {
138                         // just pick the first one for now
139                         carbon_descriptor = editors[0];
140                         ret = true;
141                 }
142                 delete[] editors;
143         }
144
145         return ret;
146 }
147         
148 bool
149 AUPluginUI::test_cocoa_view_support ()
150 {
151         UInt32 dataSize   = 0;
152         Boolean isWritable = 0;
153         OSStatus err = AudioUnitGetPropertyInfo(*au->get_au(),
154                                                 kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
155                                                 0, &dataSize, &isWritable);
156         
157         return dataSize > 0 && err == noErr;
158 }
159
160 bool
161 AUPluginUI::plugin_class_valid (Class pluginClass)
162 {
163         if([pluginClass conformsToProtocol: @protocol(AUCocoaUIBase)]) {
164                 if([pluginClass instancesRespondToSelector: @selector(interfaceVersion)] &&
165                    [pluginClass instancesRespondToSelector: @selector(uiViewForAudioUnit:withSize:)]) {
166                                 return true;
167                 }
168         }
169         return false;
170 }
171
172 int
173 AUPluginUI::create_cocoa_view ()
174 {
175         BOOL wasAbleToLoadCustomView = NO;
176         AudioUnitCocoaViewInfo* cocoaViewInfo = NULL;
177         UInt32               numberOfClasses = 0;
178         UInt32     dataSize;
179         Boolean    isWritable;
180         NSString*           factoryClassName = 0;
181         NSURL*              CocoaViewBundlePath;
182
183         OSStatus result = AudioUnitGetPropertyInfo (*au->get_au(),
184                                                     kAudioUnitProperty_CocoaUI,
185                                                     kAudioUnitScope_Global, 
186                                                     0,
187                                                     &dataSize,
188                                                     &isWritable );
189
190         numberOfClasses = (dataSize - sizeof(CFURLRef)) / sizeof(CFStringRef);
191         
192         // Does view have custom Cocoa UI?
193         
194         if ((result == noErr) && (numberOfClasses > 0) ) {
195                 cocoaViewInfo = (AudioUnitCocoaViewInfo *)malloc(dataSize);
196                 if(AudioUnitGetProperty(*au->get_au(),
197                                         kAudioUnitProperty_CocoaUI,
198                                         kAudioUnitScope_Global,
199                                         0,
200                                         cocoaViewInfo,
201                                         &dataSize) == noErr) {
202
203                         CocoaViewBundlePath     = (NSURL *)cocoaViewInfo->mCocoaAUViewBundleLocation;
204                         
205                         // we only take the first view in this example.
206                         factoryClassName        = (NSString *)cocoaViewInfo->mCocoaAUViewClass[0];
207
208                 } else {
209
210                         if (cocoaViewInfo != NULL) {
211                                 free (cocoaViewInfo);
212                                 cocoaViewInfo = NULL;
213                         }
214                 }
215         }
216
217         NSRect crect = { { 0, 0 }, { 1, 1} };
218
219         // [A] Show custom UI if view has it
220
221         if (CocoaViewBundlePath && factoryClassName) {
222                 NSBundle *viewBundle    = [NSBundle bundleWithPath:[CocoaViewBundlePath path]];
223                 if (viewBundle == nil) {
224                         error << _("AUPluginUI: error loading AU view's bundle") << endmsg;
225                         return -1;
226                 } else {
227                         Class factoryClass = [viewBundle classNamed:factoryClassName];
228                         if (!factoryClass) {
229                                 error << _("AUPluginUI: error getting AU view's factory class from bundle") << endmsg;
230                                 return -1;
231                         }
232                         
233                         // make sure 'factoryClass' implements the AUCocoaUIBase protocol
234                         if (!plugin_class_valid (factoryClass)) {
235                                 error << _("AUPluginUI: U view's factory class does not properly implement the AUCocoaUIBase protocol") << endmsg;
236                                 return -1;
237                         }
238                         // make a factory
239                         id factoryInstance = [[[factoryClass alloc] init] autorelease];
240                         if (factoryInstance == nil) {
241                                 error << _("AUPluginUI: Could not create an instance of the AU view factory") << endmsg;
242                                 return -1;
243                         }
244
245                         // make a view
246                         au_view = [factoryInstance uiViewForAudioUnit:*au->get_au() withSize:crect.size];
247                         
248                         // cleanup
249                         [CocoaViewBundlePath release];
250                         if (cocoaViewInfo) {
251                                 UInt32 i;
252                                 for (i = 0; i < numberOfClasses; i++)
253                                         CFRelease(cocoaViewInfo->mCocoaAUViewClass[i]);
254                                 
255                                 free (cocoaViewInfo);
256                         }
257                         wasAbleToLoadCustomView = YES;
258                 }
259         }
260
261         if (!wasAbleToLoadCustomView) {
262                 // load generic Cocoa view
263                 au_view = [[AUGenericView alloc] initWithAudioUnit:*au->get_au()];
264                 [(AUGenericView *)au_view setShowsExpertParameters:YES];
265         }
266
267         NSRect packFrame;
268
269         // Get the size of the new AU View's frame 
270         packFrame = [au_view frame];
271
272         packFrame.origin.x = 0;
273         packFrame.origin.y = 0;
274
275         if (packFrame.size.width > 500 || packFrame.size.height > 500) {
276                 
277                 /* its too big - use a scrollview */
278
279                 NSRect frameRect = [[cocoa_window contentView] frame];
280                 scroll_view = [[[NSScrollView alloc] initWithFrame:frameRect] autorelease];
281                 [scroll_view setDrawsBackground:NO];
282                 [scroll_view setHasHorizontalScroller:YES];
283                 [scroll_view setHasVerticalScroller:YES];
284
285                 packFrame.size = [NSScrollView  frameSizeForContentSize:packFrame.size
286                                     hasHorizontalScroller:[scroll_view hasHorizontalScroller]
287                                     hasVerticalScroller:[scroll_view hasVerticalScroller]
288                                     borderType:[scroll_view borderType]];
289                 
290                 // Create a new frame with same origin as current
291                 // frame but size equal to the size of the new view
292                 NSRect newFrame;
293                 newFrame.origin = [scroll_view frame].origin;
294                 newFrame.size = packFrame.size;
295                 
296                 // Set the new frame and document views on the scroll view
297                 [scroll_view setFrame:newFrame];
298                 [scroll_view setDocumentView:au_view];
299                 
300                 packView = scroll_view;
301
302         } else {
303
304                 packView = au_view;
305         }
306
307         prefwidth = packFrame.size.width;
308         prefheight = packFrame.size.height;
309
310         return 0;
311 }
312
313 int
314 AUPluginUI::create_carbon_view ()
315 {
316         OSStatus err;
317         ControlRef root_control;
318
319         Component editComponent = FindNextComponent(NULL, &carbon_descriptor);
320         
321         OpenAComponent(editComponent, &editView);
322         if (!editView) {
323                 error << _("AU Carbon view: cannot open AU Component") << endmsg;
324                 return -1;
325         }
326         
327         Rect r = { 100, 100, 100, 100 };
328         WindowAttributes attr = WindowAttributes (kWindowStandardHandlerAttribute |
329                                                   kWindowCompositingAttribute|
330                                                   kWindowNoShadowAttribute|
331                                                   kWindowNoTitleBarAttribute);
332
333         if ((err = CreateNewWindow(kDocumentWindowClass, attr, &r, &carbon_window)) != noErr) {
334                 error << string_compose (_("AUPluginUI: cannot create carbon window (err: %1)"), err) << endmsg;
335                 return -1;
336         }
337         
338         if ((err = GetRootControl(carbon_window, &root_control)) != noErr) {
339                 error << string_compose (_("AUPlugin: cannot get root control of carbon window (err: %1)"), err) << endmsg;
340                 return -1;
341         }
342
343         ControlRef viewPane;
344         Float32Point location  = { 0.0, 0.0 };
345         Float32Point size = { 0.0, 0.0 } ;
346
347         if ((err = AudioUnitCarbonViewCreate (editView, *au->get_au(), carbon_window, root_control, &location, &size, &viewPane)) != noErr) {
348                 error << string_compose (_("AUPluginUI: cannot create carbon plugin view (err: %1)"), err) << endmsg;
349                 return -1;
350         }
351
352         // resize window
353
354         Rect bounds;
355         GetControlBounds(viewPane, &bounds);
356         size.x = bounds.right-bounds.left;
357         size.y = bounds.bottom-bounds.top;
358
359         prefwidth = (int) (size.x + 0.5);
360         prefheight = (int) (size.y + 0.5);
361
362         SizeWindow (carbon_window, prefwidth, prefheight,  true);
363         low_box.set_size_request (prefwidth, prefheight);
364
365         return 0;
366 }
367
368 NSWindow*
369 AUPluginUI::get_nswindow ()
370 {
371         Gtk::Container* toplevel = get_toplevel();
372
373         if (!toplevel || !toplevel->is_toplevel()) {
374                 error << _("AUPluginUI: no top level window!") << endmsg;
375                 return 0;
376         }
377
378         NSWindow* true_parent = gdk_quartz_window_get_nswindow (toplevel->get_window()->gobj());
379
380         if (!true_parent) {
381                 error << _("AUPluginUI: no top level window!") << endmsg;
382                 return 0;
383         }
384
385         return true_parent;
386 }
387
388 void
389 AUPluginUI::activate ()
390 {
391         if (carbon_window && cocoa_parent) {
392                 cerr << "APP activated, activate carbon window " << insert->name() << endl;
393                 _activating_from_app = true;
394                 ActivateWindow (carbon_window, TRUE);
395                 _activating_from_app = false;
396                 [cocoa_parent makeKeyAndOrderFront:nil];
397         } 
398 }
399
400 void
401 AUPluginUI::deactivate ()
402 {
403         return;
404         cerr << "APP DEactivated, for " << insert->name() << endl;
405         _activating_from_app = true;
406         ActivateWindow (carbon_window, FALSE);
407         _activating_from_app = false;
408 }
409
410
411 OSStatus 
412 _carbon_event (EventHandlerCallRef nextHandlerRef, EventRef event, void *userData) 
413 {
414         return ((AUPluginUI*)userData)->carbon_event (nextHandlerRef, event);
415 }
416
417 OSStatus 
418 AUPluginUI::carbon_event (EventHandlerCallRef nextHandlerRef, EventRef event)
419 {
420         cerr << "CARBON EVENT\n";
421
422         UInt32 eventKind = GetEventKind(event);
423         ClickActivationResult howToHandleClick;
424         NSWindow* win = get_nswindow ();
425
426         cerr << "window " << win << " carbon event type " << eventKind << endl;
427
428         switch (eventKind) {
429         case kEventWindowHandleActivate:
430                 cerr << "carbon window for " << insert->name() << " activated\n";
431                 if (_activating_from_app) {
432                         cerr << "app activation, ignore window activation\n";
433                         return noErr;
434                 }
435                 [win makeMainWindow];
436                 return eventNotHandledErr;
437                 break;
438
439         case kEventWindowHandleDeactivate:
440                 cerr << "carbon window for " << insert->name() << " would have been deactivated\n";
441                 // never deactivate the carbon window
442                 return noErr;
443                 break;
444                 
445         case kEventWindowGetClickActivation:
446                 cerr << "carbon window CLICK activated\n";
447                 [win makeKeyAndOrderFront:nil];
448                 howToHandleClick = kActivateAndHandleClick;
449                 SetEventParameter(event, kEventParamClickActivation, typeClickActivationResult, 
450                                   sizeof(ClickActivationResult), &howToHandleClick);
451                 break;
452         }
453
454         return noErr;
455 }
456
457 int
458 AUPluginUI::parent_carbon_window ()
459 {
460         NSWindow* win = get_nswindow ();
461         int x, y;
462
463         if (!win) {
464                 return -1;
465         }
466
467         Gtk::Container* toplevel = get_toplevel();
468
469         if (!toplevel || !toplevel->is_toplevel()) {
470                 error << _("AUPluginUI: no top level window!") << endmsg;
471                 return -1;
472         }
473         
474         toplevel->get_window()->get_root_origin (x, y);
475
476         /* compute how tall the title bar is, because we have to offset the position of the carbon window
477            by that much.
478         */
479
480         NSRect content_frame = [NSWindow contentRectForFrameRect:[win frame] styleMask:[win styleMask]];
481         NSRect wm_frame = [NSWindow frameRectForContentRect:content_frame styleMask:[win styleMask]];
482
483         int titlebar_height = wm_frame.size.height - content_frame.size.height;
484
485         int packing_extra = 6; // this is the total vertical packing in our top level window
486
487         MoveWindow (carbon_window, x, y + titlebar_height + top_box.get_height() + packing_extra, false);
488         ShowWindow (carbon_window);
489
490         // create the cocoa window for the carbon one and make it visible
491         cocoa_parent = [[NSWindow alloc] initWithWindowRef: carbon_window];
492
493         EventTypeSpec   windowEventTypes[] = {
494                 {kEventClassWindow, kEventWindowGetClickActivation },
495                 {kEventClassWindow, kEventWindowHandleDeactivate }
496         };
497         
498         EventHandlerUPP   ehUPP = NewEventHandlerUPP(_carbon_event);
499         OSStatus result = InstallWindowEventHandler (carbon_window, ehUPP, 
500                                                      sizeof(windowEventTypes) / sizeof(EventTypeSpec), 
501                                                      windowEventTypes, this, &carbon_event_handler);
502         if (result != noErr) {
503                 return -1;
504         }
505
506         [win addChildWindow:cocoa_parent ordered:NSWindowAbove];
507
508         return 0;
509 }       
510
511 int
512 AUPluginUI::parent_cocoa_window ()
513 {
514         NSWindow* win = get_nswindow ();
515         NSRect packFrame;
516
517         if (!win) {
518                 return -1;
519         }
520
521         Gtk::Container* toplevel = get_toplevel();
522
523         if (!toplevel || !toplevel->is_toplevel()) {
524                 error << _("AUPluginUI: no top level window!") << endmsg;
525                 return -1;
526         }
527         
528         // Get the size of the new AU View's frame 
529         packFrame = [au_view frame];
530
531         NSView* view = gdk_quartz_window_get_nsview (low_box.get_window()->gobj());
532         
533         [view setFrame:packFrame];
534         [view addSubview:packView]; 
535
536         low_box.set_size_request (packFrame.size.width, packFrame.size.height);
537
538         return 0;
539 }
540
541 void
542 AUPluginUI::on_realize ()
543 {
544         VBox::on_realize ();
545
546         /* our windows should not have that resize indicator */
547
548         NSWindow* win = get_nswindow ();
549         if (win) {
550                 [win setShowsResizeIndicator:NO];
551         }
552 }
553
554 void
555 AUPluginUI::lower_box_realized ()
556 {
557         if (au_view) {
558                 parent_cocoa_window ();
559         } else if (carbon_window) {
560                 parent_carbon_window ();
561         }
562 }
563
564 void
565 AUPluginUI::on_hide ()
566 {
567         // VBox::on_hide ();
568         cerr << "AU plugin window hidden\n";
569 }
570
571 bool
572 AUPluginUI::on_map_event (GdkEventAny* ev)
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