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