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