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