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