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