various fixes to MidiRegionView selection handling, key handling, drawing of ghost...
[ardour2.git] / gtk2_ardour / au_pluginui.mm
blob0f10af054d0cd488ea1920b0baf1e5d574c7cc2a
1 #include <gtkmm/stock.h>
3 #undef  Marker
4 #define Marker FuckYouAppleAndYourLackOfNameSpaces
6 #include "pbd/convert.h"
7 #include "pbd/error.h"
8 #include "ardour/audio_unit.h"
9 #include "ardour/plugin_insert.h"
11 #undef check // stupid gtk, stupid apple
13 #include <gtkmm/button.h>
14 #include <gdk/gdkquartz.h>
16 #include <gtkmm2ext/utils.h>
18 #include "au_pluginui.h"
19 #include "gui_thread.h"
21 #include "appleutility/CAAudioUnit.h"
22 #include "appleutility/CAComponent.h"
24 #import <AudioUnit/AUCocoaUIView.h>
25 #import <CoreAudioKit/AUGenericView.h>
27 #undef Marker
29 #include "keyboard.h"
30 #include "utils.h"
31 #include "public_editor.h"
32 #include "i18n.h"
34 using namespace ARDOUR;
35 using namespace Gtk;
36 using namespace Gtkmm2ext;
37 using namespace sigc;
38 using namespace std;
39 using namespace PBD;
41 vector<string> AUPluginUI::automation_mode_strings;
43 static const gchar* _automation_mode_strings[] = {
44         X_("Manual"),
45         X_("Play"),
46         X_("Write"),
47         X_("Touch"),
48         0
51 @implementation NotificationObject
53 - (NotificationObject*) initWithPluginUI: (AUPluginUI*) apluginui andCocoaParent: (NSWindow*) cp andTopLevelParent: (NSWindow*) tlp
55         self = [ super init ];
57         if (self) {
58                 plugin_ui = apluginui;
59                 cocoa_parent = cp;
60                 top_level_parent = tlp;
62                 [[NSNotificationCenter defaultCenter] addObserver:self
63                  selector:@selector(cocoaParentActivationHandler:)
64                  name:NSWindowDidBecomeMainNotification
65                  object:nil];
67                 [[NSNotificationCenter defaultCenter] addObserver:self
68                  selector:@selector(cocoaParentBecameKeyHandler:)
69                  name:NSWindowDidBecomeKeyNotification
70                  object:nil];
71         }
73         return self;
75                 
76 - (void)cocoaParentActivationHandler:(NSNotification *)notification
78         NSWindow* notification_window = (NSWindow *)[notification object];
80         if (top_level_parent == notification_window || cocoa_parent == notification_window) {
81                 if ([notification_window isMainWindow]) {
82                         plugin_ui->activate();
83                 } else {
84                         plugin_ui->deactivate();
85                 }
86         } 
89 - (void)cocoaParentBecameKeyHandler:(NSNotification *)notification
91         NSWindow* notification_window = (NSWindow *)[notification object];
93         if (top_level_parent == notification_window || cocoa_parent == notification_window) {
94                 if ([notification_window isKeyWindow]) {
95                         plugin_ui->activate();
96                 } else {
97                         plugin_ui->deactivate();
98                 }
99         } 
102 - (void)auViewResized:(NSNotification *)notification;
104         (void) notification;
105         plugin_ui->cocoa_view_resized();
108 @end
110 AUPluginUI::AUPluginUI (boost::shared_ptr<PluginInsert> insert)
111         : PlugUIBase (insert)
112         , automation_mode_label (_("Automation"))
113         , preset_label (_("Presets"))
114         
116         if (automation_mode_strings.empty()) {
117                 automation_mode_strings = I18N (_automation_mode_strings);
118         }
119         
120         set_popdown_strings (automation_mode_selector, automation_mode_strings);
121         automation_mode_selector.set_active_text (automation_mode_strings.front());
123         if ((au = boost::dynamic_pointer_cast<AUPlugin> (insert->plugin())) == 0) {
124                 error << _("unknown type of editor-supplying plugin (note: no AudioUnit support in this version of ardour)") << endmsg;
125                 throw failed_constructor ();
126         }
128         /* stuff some stuff into the top of the window */
130         HBox* smaller_hbox = manage (new HBox);
132         smaller_hbox->set_spacing (6);
133         smaller_hbox->pack_start (preset_label, false, false, 4);
134         smaller_hbox->pack_start (preset_combo, false, false);
135         smaller_hbox->pack_start (save_button, false, false);
136 #if 0
137         /* one day these might be useful with an AU plugin, but not yet */
138         smaller_hbox->pack_start (automation_mode_label, false, false);
139         smaller_hbox->pack_start (automation_mode_selector, false, false);
140 #endif
141         smaller_hbox->pack_start (bypass_button, false, true);
143         VBox* v1_box = manage (new VBox);
144         VBox* v2_box = manage (new VBox);
146         v1_box->pack_start (*smaller_hbox, false, true);
147         v2_box->pack_start (focus_button, false, true);
149         top_box.set_homogeneous (false);
150         top_box.set_spacing (6);
151         top_box.set_border_width (6);
153         top_box.pack_end (*v2_box, false, false);
154         top_box.pack_end (*v1_box, false, false);
156         set_spacing (6);
157         pack_start (top_box, false, false);
158         pack_start (low_box, false, false);
160         preset_label.show ();
161         preset_combo.show ();
162         automation_mode_label.show ();
163         automation_mode_selector.show ();
164         bypass_button.show ();
165         top_box.show ();
166         low_box.show ();
168         _activating_from_app = false;
169         cocoa_parent = 0;
170         _notify = 0;
171         cocoa_window = 0;
172         au_view = 0;
173         editView = 0;
175         /* prefer cocoa, fall back to cocoa, but use carbon if its there */
177         if (test_cocoa_view_support()) {
178                 create_cocoa_view ();
179         } else if (test_carbon_view_support()) {
180                 create_carbon_view ();
181         } else {
182                 create_cocoa_view ();
183         }
185         low_box.signal_realize().connect (mem_fun (this, &AUPluginUI::lower_box_realized));
188 AUPluginUI::~AUPluginUI ()
190         if (cocoa_parent) {
191                 NSWindow* win = get_nswindow();
192                 [[NSNotificationCenter defaultCenter] removeObserver:_notify];
193                 [win removeChildWindow:cocoa_parent];
195         } 
197         if (carbon_window) {
198                 /* not parented, just overlaid on top of our window */
199                 DisposeWindow (carbon_window);
200         }
202         if (editView) {
203                 CloseComponent (editView);
204         }
206         if (au_view) {
207                 /* remove whatever we packed into low_box so that GTK doesn't
208                    mess with it.
209                 */
211                 [au_view removeFromSuperview];
212         }
215 bool
216 AUPluginUI::test_carbon_view_support ()
218         bool ret = false;
219         
220         carbon_descriptor.componentType = kAudioUnitCarbonViewComponentType;
221         carbon_descriptor.componentSubType = 'gnrc';
222         carbon_descriptor.componentManufacturer = 'appl';
223         carbon_descriptor.componentFlags = 0;
224         carbon_descriptor.componentFlagsMask = 0;
225         
226         OSStatus err;
228         // ask the AU for its first editor component
229         UInt32 propertySize;
230         err = AudioUnitGetPropertyInfo(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, &propertySize, NULL);
231         if (!err) {
232                 int nEditors = propertySize / sizeof(ComponentDescription);
233                 ComponentDescription *editors = new ComponentDescription[nEditors];
234                 err = AudioUnitGetProperty(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, editors, &propertySize);
235                 if (!err) {
236                         // just pick the first one for now
237                         carbon_descriptor = editors[0];
238                         ret = true;
239                 }
240                 delete[] editors;
241         }
243         return ret;
245         
246 bool
247 AUPluginUI::test_cocoa_view_support ()
249         UInt32 dataSize   = 0;
250         Boolean isWritable = 0;
251         OSStatus err = AudioUnitGetPropertyInfo(*au->get_au(),
252                                                 kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
253                                                 0, &dataSize, &isWritable);
254         
255         return dataSize > 0 && err == noErr;
258 bool
259 AUPluginUI::plugin_class_valid (Class pluginClass)
261         if([pluginClass conformsToProtocol: @protocol(AUCocoaUIBase)]) {
262                 if([pluginClass instancesRespondToSelector: @selector(interfaceVersion)] &&
263                    [pluginClass instancesRespondToSelector: @selector(uiViewForAudioUnit:withSize:)]) {
264                                 return true;
265                 }
266         }
267         return false;
271 AUPluginUI::create_cocoa_view ()
273         BOOL wasAbleToLoadCustomView = NO;
274         AudioUnitCocoaViewInfo* cocoaViewInfo = NULL;
275         UInt32               numberOfClasses = 0;
276         UInt32     dataSize;
277         Boolean    isWritable;
278         NSString*           factoryClassName = 0;
279         NSURL*              CocoaViewBundlePath;
281         OSStatus result = AudioUnitGetPropertyInfo (*au->get_au(),
282                                                     kAudioUnitProperty_CocoaUI,
283                                                     kAudioUnitScope_Global, 
284                                                     0,
285                                                     &dataSize,
286                                                     &isWritable );
288         numberOfClasses = (dataSize - sizeof(CFURLRef)) / sizeof(CFStringRef);
289         
290         // Does view have custom Cocoa UI?
291         
292         if ((result == noErr) && (numberOfClasses > 0) ) {
293                 cocoaViewInfo = (AudioUnitCocoaViewInfo *)malloc(dataSize);
294                 if(AudioUnitGetProperty(*au->get_au(),
295                                         kAudioUnitProperty_CocoaUI,
296                                         kAudioUnitScope_Global,
297                                         0,
298                                         cocoaViewInfo,
299                                         &dataSize) == noErr) {
301                         CocoaViewBundlePath     = (NSURL *)cocoaViewInfo->mCocoaAUViewBundleLocation;
302                         
303                         // we only take the first view in this example.
304                         factoryClassName        = (NSString *)cocoaViewInfo->mCocoaAUViewClass[0];
306                 } else {
308                         if (cocoaViewInfo != NULL) {
309                                 free (cocoaViewInfo);
310                                 cocoaViewInfo = NULL;
311                         }
312                 }
313         }
315         NSRect crect = { { 0, 0 }, { 1, 1} };
317         // [A] Show custom UI if view has it
319         if (CocoaViewBundlePath && factoryClassName) {
320                 NSBundle *viewBundle    = [NSBundle bundleWithPath:[CocoaViewBundlePath path]];
321                 if (viewBundle == nil) {
322                         error << _("AUPluginUI: error loading AU view's bundle") << endmsg;
323                         return -1;
324                 } else {
325                         Class factoryClass = [viewBundle classNamed:factoryClassName];
326                         if (!factoryClass) {
327                                 error << _("AUPluginUI: error getting AU view's factory class from bundle") << endmsg;
328                                 return -1;
329                         }
330                         
331                         // make sure 'factoryClass' implements the AUCocoaUIBase protocol
332                         if (!plugin_class_valid (factoryClass)) {
333                                 error << _("AUPluginUI: U view's factory class does not properly implement the AUCocoaUIBase protocol") << endmsg;
334                                 return -1;
335                         }
336                         // make a factory
337                         id factoryInstance = [[[factoryClass alloc] init] autorelease];
338                         if (factoryInstance == nil) {
339                                 error << _("AUPluginUI: Could not create an instance of the AU view factory") << endmsg;
340                                 return -1;
341                         }
343                         // make a view
344                         au_view = [factoryInstance uiViewForAudioUnit:*au->get_au() withSize:crect.size];
345                         
346                         // cleanup
347                         [CocoaViewBundlePath release];
348                         if (cocoaViewInfo) {
349                                 UInt32 i;
350                                 for (i = 0; i < numberOfClasses; i++)
351                                         CFRelease(cocoaViewInfo->mCocoaAUViewClass[i]);
352                                 
353                                 free (cocoaViewInfo);
354                         }
355                         wasAbleToLoadCustomView = YES;
356                 }
357         }
359         if (!wasAbleToLoadCustomView) {
360                 // load generic Cocoa view
361                 au_view = [[AUGenericView alloc] initWithAudioUnit:*au->get_au()];
362                 [(AUGenericView *)au_view setShowsExpertParameters:YES];
363         }
365         // watch for size changes of the view
367          [[NSNotificationCenter defaultCenter] addObserver:_notify
368                selector:@selector(auViewResized:) name:NSWindowDidResizeNotification
369                object:au_view];
371         // Get the size of the new AU View's frame 
372         
373         NSRect packFrame;
374         packFrame = [au_view frame];
375         prefwidth = packFrame.size.width;
376         prefheight = packFrame.size.height;
377         low_box.set_size_request (prefwidth, prefheight);
378         
379         return 0;
382 void
383 AUPluginUI::cocoa_view_resized ()
385         NSRect packFrame = [au_view frame];
389 AUPluginUI::create_carbon_view ()
391         OSStatus err;
392         ControlRef root_control;
394         Component editComponent = FindNextComponent(NULL, &carbon_descriptor);
395         
396         OpenAComponent(editComponent, &editView);
397         if (!editView) {
398                 error << _("AU Carbon view: cannot open AU Component") << endmsg;
399                 return -1;
400         }
401         
402         Rect r = { 100, 100, 100, 100 };
403         WindowAttributes attr = WindowAttributes (kWindowStandardHandlerAttribute |
404                                                   kWindowCompositingAttribute|
405                                                   kWindowNoShadowAttribute|
406                                                   kWindowNoTitleBarAttribute);
408         if ((err = CreateNewWindow(kDocumentWindowClass, attr, &r, &carbon_window)) != noErr) {
409                 error << string_compose (_("AUPluginUI: cannot create carbon window (err: %1)"), err) << endmsg;
410                 CloseComponent (editView);
411                 return -1;
412         }
413         
414         if ((err = GetRootControl(carbon_window, &root_control)) != noErr) {
415                 error << string_compose (_("AUPlugin: cannot get root control of carbon window (err: %1)"), err) << endmsg;
416                 DisposeWindow (carbon_window);
417                 CloseComponent (editView);
418                 return -1;
419         }
421         ControlRef viewPane;
422         Float32Point location  = { 0.0, 0.0 };
423         Float32Point size = { 0.0, 0.0 } ;
425         if ((err = AudioUnitCarbonViewCreate (editView, *au->get_au(), carbon_window, root_control, &location, &size, &viewPane)) != noErr) {
426                 error << string_compose (_("AUPluginUI: cannot create carbon plugin view (err: %1)"), err) << endmsg;
427                 DisposeWindow (carbon_window);
428                 CloseComponent (editView);
429                 return -1;
430         }
432         // resize window
434         Rect bounds;
435         GetControlBounds(viewPane, &bounds);
436         size.x = bounds.right-bounds.left;
437         size.y = bounds.bottom-bounds.top;
439         prefwidth = (int) (size.x + 0.5);
440         prefheight = (int) (size.y + 0.5);
442         SizeWindow (carbon_window, prefwidth, prefheight,  true);
443         low_box.set_size_request (prefwidth, prefheight);
445         return 0;
448 NSWindow*
449 AUPluginUI::get_nswindow ()
451         Gtk::Container* toplevel = get_toplevel();
453         if (!toplevel || !toplevel->is_toplevel()) {
454                 error << _("AUPluginUI: no top level window!") << endmsg;
455                 return 0;
456         }
458         NSWindow* true_parent = gdk_quartz_window_get_nswindow (toplevel->get_window()->gobj());
460         if (!true_parent) {
461                 error << _("AUPluginUI: no top level window!") << endmsg;
462                 return 0;
463         }
465         return true_parent;
468 void
469 AUPluginUI::activate ()
471         ActivateWindow (carbon_window, TRUE);
472         // [cocoa_parent makeKeyAndOrderFront:nil];
475 void
476 AUPluginUI::deactivate ()
478         ActivateWindow (carbon_window, FALSE);
482 AUPluginUI::parent_carbon_window ()
484         NSWindow* win = get_nswindow ();
485         int x, y;
487         if (!win) {
488                 return -1;
489         }
491         Gtk::Container* toplevel = get_toplevel();
493         if (!toplevel || !toplevel->is_toplevel()) {
494                 error << _("AUPluginUI: no top level window!") << endmsg;
495                 return -1;
496         }
497         
498         toplevel->get_window()->get_root_origin (x, y);
500         /* compute how tall the title bar is, because we have to offset the position of the carbon window
501            by that much.
502         */
504         NSRect content_frame = [NSWindow contentRectForFrameRect:[win frame] styleMask:[win styleMask]];
505         NSRect wm_frame = [NSWindow frameRectForContentRect:content_frame styleMask:[win styleMask]];
507         int titlebar_height = wm_frame.size.height - content_frame.size.height;
509         int packing_extra = 6; // this is the total vertical packing in our top level window
511         MoveWindow (carbon_window, x, y + titlebar_height + top_box.get_height() + packing_extra, false);
512         ShowWindow (carbon_window);
514         // create the cocoa window for the carbon one and make it visible
515         cocoa_parent = [[NSWindow alloc] initWithWindowRef: carbon_window];
517         SetWindowActivationScope (carbon_window, kWindowActivationScopeNone);
519         _notify = [ [NotificationObject alloc] initWithPluginUI:this andCocoaParent:cocoa_parent andTopLevelParent:win ]; 
521         [win addChildWindow:cocoa_parent ordered:NSWindowAbove];
523         return 0;
524 }       
527 AUPluginUI::parent_cocoa_window ()
529         NSWindow* win = get_nswindow ();
531         if (!win) {
532                 return -1;
533         }
535         [win setAutodisplay:YES]; // turn of GTK stuff for this window
537         Gtk::Container* toplevel = get_toplevel();
539         if (!toplevel || !toplevel->is_toplevel()) {
540                 error << _("AUPluginUI: no top level window!") << endmsg;
541                 return -1;
542         }
544         NSView* view = gdk_quartz_window_get_nsview (get_toplevel()->get_window()->gobj());
545         GtkRequisition a = top_box.size_request ();
547         /* move the au_view down so that it doesn't overlap the top_box contents */
549         NSPoint origin = { 0, a.height };
551         [au_view setFrameOrigin:origin];
552         [view addSubview:au_view]; 
554         return 0;
557 static void
558 dump_view_tree (NSView* view, int depth)
560         NSArray* subviews = [view subviews];
561         unsigned long cnt = [subviews count];
563         for (int d = 0; d < depth; d++) {
564                 cerr << '\t';
565         }
566         cerr << " view @ " << view << endl;
567         
568         for (unsigned long i = 0; i < cnt; ++i) {
569                 NSView* subview = [subviews objectAtIndex:i];
570                 dump_view_tree (subview, depth+1);
571         }
574 void
575 AUPluginUI::forward_key_event (GdkEventKey* ev)
577         NSEvent* nsevent = gdk_quartz_event_get_nsevent ((GdkEvent*)ev);
579         if (au_view && nsevent) {
581                 /* filter on nsevent type here because GDK massages FlagsChanged
582                    messages into GDK_KEY_{PRESS,RELEASE} but Cocoa won't
583                    handle a FlagsChanged message as a keyDown or keyUp
584                 */
586                 if ([nsevent type] == NSKeyDown) {
587                         [[[au_view window] firstResponder] keyDown:nsevent];
588                 } else if ([nsevent type] == NSKeyUp) {
589                         [[[au_view window] firstResponder] keyUp:nsevent];
590                 } else if ([nsevent type] == NSFlagsChanged) {
591                         [[[au_view window] firstResponder] flagsChanged:nsevent];
592                 }
593         }
596 void
597 AUPluginUI::on_realize ()
599         VBox::on_realize ();
601         /* our windows should not have that resize indicator */
603         NSWindow* win = get_nswindow ();
604         if (win) {
605                 [win setShowsResizeIndicator:NO];
606         }
609 void
610 AUPluginUI::lower_box_realized ()
612         if (au_view) {
613                 parent_cocoa_window ();
614         } else if (carbon_window) {
615                 parent_carbon_window ();
616         }
619 bool
620 AUPluginUI::on_map_event (GdkEventAny*)
622         return false;
625 void
626 AUPluginUI::on_window_hide ()
628         if (carbon_window) {
629                 HideWindow (carbon_window);
630                 ActivateWindow (carbon_window, FALSE);
631         }
633         hide_all ();
636 bool
637 AUPluginUI::on_window_show (const string& /*title*/)
639         /* this is idempotent so just call it every time we show the window */
641         gtk_widget_realize (GTK_WIDGET(low_box.gobj()));
643         show_all ();
645         if (carbon_window) {
646                 ShowWindow (carbon_window);
647                 ActivateWindow (carbon_window, TRUE);
648         }
650         return true;
653 bool
654 AUPluginUI::start_updating (GdkEventAny*)
656         return false;
659 bool
660 AUPluginUI::stop_updating (GdkEventAny*)
662         return false;
665 PlugUIBase*
666 create_au_gui (boost::shared_ptr<PluginInsert> plugin_insert, VBox** box)
668         AUPluginUI* aup = new AUPluginUI (plugin_insert);
669         (*box) = aup;
670         return aup;
673 bool
674 AUPluginUI::on_focus_in_event (GdkEventFocus*)
676         //cerr << "au plugin focus in\n";
677         //Keyboard::magic_widget_grab_focus ();
678         return false;
681 bool
682 AUPluginUI::on_focus_out_event (GdkEventFocus*)
684         //cerr << "au plugin focus out\n";
685         //Keyboard::magic_widget_drop_focus ();
686         return false;