Merge with 2.0-ongoing R3071.
[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         return;
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         return;
359         cerr << "APP DEactivated, for " << insert->name() << endl;
360         _activating_from_app = true;
361         ActivateWindow (carbon_window, FALSE);
362         _activating_from_app = false;
363 }
364
365
366 OSStatus 
367 _carbon_event (EventHandlerCallRef nextHandlerRef, EventRef event, void *userData) 
368 {
369         return ((AUPluginUI*)userData)->carbon_event (nextHandlerRef, event);
370 }
371
372 OSStatus 
373 AUPluginUI::carbon_event (EventHandlerCallRef nextHandlerRef, EventRef event)
374 {
375         cerr << "CARBON EVENT\n";
376
377         UInt32 eventKind = GetEventKind(event);
378         ClickActivationResult howToHandleClick;
379         NSWindow* win = get_nswindow ();
380
381         cerr << "window " << win << " carbon event type " << eventKind << endl;
382
383         switch (eventKind) {
384         case kEventWindowHandleActivate:
385                 cerr << "carbon window for " << insert->name() << " activated\n";
386                 if (_activating_from_app) {
387                         cerr << "app activation, ignore window activation\n";
388                         return noErr;
389                 }
390                 [win makeMainWindow];
391                 return eventNotHandledErr;
392                 break;
393
394         case kEventWindowHandleDeactivate:
395                 cerr << "carbon window for " << insert->name() << " deactivated\n";
396                 // never deactivate the carbon window
397                 return noErr;
398                 break;
399                 
400         case kEventWindowGetClickActivation:
401                 cerr << "carbon window CLICK activated\n";
402                 [win makeKeyAndOrderFront:nil];
403                 howToHandleClick = kActivateAndHandleClick;
404                 SetEventParameter(event, kEventParamClickActivation, typeClickActivationResult, 
405                                   sizeof(ClickActivationResult), &howToHandleClick);
406                 break;
407         }
408
409         return noErr;
410 }
411
412 int
413 AUPluginUI::parent_carbon_window ()
414 {
415         NSWindow* win = get_nswindow ();
416         int x, y;
417
418         if (!win) {
419                 return -1;
420         }
421
422         Gtk::Container* toplevel = get_toplevel();
423
424         if (!toplevel || !toplevel->is_toplevel()) {
425                 error << _("AUPluginUI: no top level window!") << endmsg;
426                 return -1;
427         }
428         
429         toplevel->get_window()->get_root_origin (x, y);
430
431         /* compute how tall the title bar is, because we have to offset the position of the carbon window
432            by that much.
433         */
434
435         NSRect content_frame = [NSWindow contentRectForFrameRect:[win frame] styleMask:[win styleMask]];
436         NSRect wm_frame = [NSWindow frameRectForContentRect:content_frame styleMask:[win styleMask]];
437
438         int titlebar_height = wm_frame.size.height - content_frame.size.height;
439
440         int packing_extra = 6; // this is the total vertical packing in our top level window
441
442         MoveWindow (carbon_window, x, y + titlebar_height + top_box.get_height() + packing_extra, false);
443         ShowWindow (carbon_window);
444
445         // create the cocoa window for the carbon one and make it visible
446         cocoa_parent = [[NSWindow alloc] initWithWindowRef: carbon_window];
447
448         EventTypeSpec   windowEventTypes[] = {
449                 {kEventClassWindow, kEventWindowGetClickActivation },
450                 {kEventClassWindow, kEventWindowHandleDeactivate }
451         };
452         
453         EventHandlerUPP   ehUPP = NewEventHandlerUPP(_carbon_event);
454         OSStatus result = InstallWindowEventHandler (carbon_window, ehUPP, 
455                                                      sizeof(windowEventTypes) / sizeof(EventTypeSpec), 
456                                                      windowEventTypes, this, &carbon_event_handler);
457         if (result != noErr) {
458                 return -1;
459         }
460
461         [win addChildWindow:cocoa_parent ordered:NSWindowAbove];
462
463         return 0;
464 }       
465
466 int
467 AUPluginUI::parent_cocoa_window ()
468 {
469         NSWindow* win = get_nswindow ();
470         NSView* packView = 0;
471         NSRect packFrame;
472
473         if (!win) {
474                 return -1;
475         }
476
477         Gtk::Container* toplevel = get_toplevel();
478
479         if (!toplevel || !toplevel->is_toplevel()) {
480                 error << _("AUPluginUI: no top level window!") << endmsg;
481                 return -1;
482         }
483         
484         // Get the size of the new AU View's frame 
485         packFrame = [au_view frame];
486         packFrame.origin.x = 0;
487         packFrame.origin.y = 0;
488
489         if (packFrame.size.width > 500 || packFrame.size.height > 500) {
490                 
491                 /* its too big - use a scrollview */
492
493                 NSRect frameRect = [[cocoa_window contentView] frame];
494                 scroll_view = [[[NSScrollView alloc] initWithFrame:frameRect] autorelease];
495                 [scroll_view setDrawsBackground:NO];
496                 [scroll_view setHasHorizontalScroller:YES];
497                 [scroll_view setHasVerticalScroller:YES];
498
499                 packFrame.size = [NSScrollView  frameSizeForContentSize:packFrame.size
500                                     hasHorizontalScroller:[scroll_view hasHorizontalScroller]
501                                     hasVerticalScroller:[scroll_view hasVerticalScroller]
502                                     borderType:[scroll_view borderType]];
503                 
504                 // Create a new frame with same origin as current
505                 // frame but size equal to the size of the new view
506                 NSRect newFrame;
507                 newFrame.origin = [scroll_view frame].origin;
508                 newFrame.size = packFrame.size;
509                 
510                 // Set the new frame and document views on the scroll view
511                 [scroll_view setFrame:newFrame];
512                 [scroll_view setDocumentView:au_view];
513                 
514                 packView = scroll_view;
515
516         } else {
517
518                 packView = au_view;
519         }
520
521         NSView* view = gdk_quartz_window_get_nsview (low_box.get_window()->gobj());
522         
523         [view setFrame:packFrame];
524         [view addSubview:packView]; 
525
526         low_box.set_size_request (packFrame.size.width, packFrame.size.height);
527
528         return 0;
529 }
530
531 void
532 AUPluginUI::on_realize ()
533 {
534         VBox::on_realize ();
535
536         /* our windows should not have that resize indicator */
537
538         NSWindow* win = get_nswindow ();
539         if (win) {
540                 [win setShowsResizeIndicator:NO];
541         }
542 }
543
544 void
545 AUPluginUI::lower_box_realized ()
546 {
547         if (au_view) {
548                 parent_cocoa_window ();
549         } else if (carbon_window) {
550                 parent_carbon_window ();
551         }
552 }
553
554 void
555 AUPluginUI::on_hide ()
556 {
557         // VBox::on_hide ();
558         cerr << "AU plugin window hidden\n";
559 }
560
561 bool
562 AUPluginUI::on_map_event (GdkEventAny* ev)
563 {
564         cerr << "AU plugin map event\n";
565
566         if (carbon_window) {
567
568                 // move top level GTK window to the correct level
569                 // to keep the stack together and not be sliceable
570                 
571                 NSWindow* win = get_nswindow ();
572                 // [win setLevel:NSFloatingWindowLevel];
573         }
574
575         return false;
576 }
577
578 void
579 AUPluginUI::on_show ()
580 {
581         cerr << "AU plugin window shown\n";
582
583         VBox::on_show ();
584
585         gtk_widget_realize (GTK_WIDGET(low_box.gobj()));
586
587         if (au_view) {
588                 show_all ();
589         } else if (carbon_window) {
590                 [cocoa_parent setIsVisible:YES];
591                 ShowWindow (carbon_window);
592         }
593 }
594
595 bool
596 AUPluginUI::start_updating (GdkEventAny* any)
597 {
598         return false;
599 }
600
601 bool
602 AUPluginUI::stop_updating (GdkEventAny* any)
603 {
604         return false;
605 }
606
607 PlugUIBase*
608 create_au_gui (boost::shared_ptr<PluginInsert> plugin_insert, VBox** box)
609 {
610         AUPluginUI* aup = new AUPluginUI (plugin_insert);
611         (*box) = aup;
612         return aup;
613 }
614
615 bool
616 AUPluginUI::on_focus_in_event (GdkEventFocus* ev)
617 {
618         cerr << "au plugin focus in\n";
619         return false;
620 }
621
622 bool
623 AUPluginUI::on_focus_out_event (GdkEventFocus* ev)
624 {
625         cerr << "au plugin focus out\n";
626         return false;
627 }
628