hack to keep UI responsive with heavy AU views.
[ardour.git] / gtk2_ardour / au_pluginui.mm
1 #undef  Marker
2 #define Marker FuckYouAppleAndYourLackOfNameSpaces
3
4 #include <gtkmm/button.h>
5 #include <gdk/gdkquartz.h>
6
7 #include "pbd/convert.h"
8 #include "pbd/error.h"
9
10 #include "ardour/audio_unit.h"
11 #include "ardour/debug.h"
12 #include "ardour/plugin_insert.h"
13
14 #undef check // stupid gtk, stupid apple
15
16 #include <gtkmm2ext/utils.h>
17
18 #include "au_pluginui.h"
19 #include "gui_thread.h"
20
21 #include "CAAudioUnit.h"
22 #include "CAComponent.h"
23
24 #import <AudioUnit/AUCocoaUIView.h>
25 #import <CoreAudioKit/AUGenericView.h>
26
27 #undef Marker
28
29 #include "keyboard.h"
30 #include "utils.h"
31 #include "public_editor.h"
32 #include "i18n.h"
33
34 #ifdef COREAUDIO105
35 #define ArdourCloseComponent CloseComponent
36 #else
37 #define ArdourCloseComponent AudioComponentInstanceDispose
38 #endif
39 using namespace ARDOUR;
40 using namespace Gtk;
41 using namespace Gtkmm2ext;
42 using namespace std;
43 using namespace PBD;
44
45 vector<string> AUPluginUI::automation_mode_strings;
46
47 static const gchar* _automation_mode_strings[] = {
48         X_("Manual"),
49         X_("Play"),
50         X_("Write"),
51         X_("Touch"),
52         0
53 };
54
55 static void
56 dump_view_tree (NSView* view, int depth, int maxdepth)
57 {
58         NSArray* subviews = [view subviews];
59         unsigned long cnt = [subviews count];
60
61         for (int d = 0; d < depth; d++) {
62                 cerr << '\t';
63         }
64         NSRect frame = [view frame];
65         cerr << " view @ " <<  frame.origin.x << ", " << frame.origin.y
66                 << ' ' << frame.size.width << " x " << frame.size.height
67                 << endl;
68
69         if (depth >= maxdepth) {
70                 return;
71         }
72         for (unsigned long i = 0; i < cnt; ++i) {
73                 NSView* subview = [subviews objectAtIndex:i];
74                 dump_view_tree (subview, depth+1, maxdepth);
75         }
76 }
77
78 @implementation NotificationObject
79
80 - (NotificationObject*) initWithPluginUI: (AUPluginUI*) apluginui andCocoaParent: (NSWindow*) cp andTopLevelParent: (NSWindow*) tlp
81 {
82         self = [ super init ];
83
84         if (self) {
85                 plugin_ui = apluginui;
86                 top_level_parent = tlp;
87
88                 if (cp) {
89                         cocoa_parent = cp;
90
91                         [[NSNotificationCenter defaultCenter]
92                              addObserver:self
93                                 selector:@selector(cocoaParentActivationHandler:)
94                                     name:NSWindowDidBecomeMainNotification
95                                   object:NULL];
96
97                         [[NSNotificationCenter defaultCenter]
98                              addObserver:self
99                                 selector:@selector(cocoaParentBecameKeyHandler:)
100                                     name:NSWindowDidBecomeKeyNotification
101                                   object:NULL];
102                 }
103         }
104
105         return self;
106 }
107
108 - (void)cocoaParentActivationHandler:(NSNotification *)notification
109 {
110         NSWindow* notification_window = (NSWindow *)[notification object];
111
112         if (top_level_parent == notification_window || cocoa_parent == notification_window) {
113                 if ([notification_window isMainWindow]) {
114                         plugin_ui->activate();
115                 } else {
116                         plugin_ui->deactivate();
117                 }
118         }
119 }
120
121 - (void)cocoaParentBecameKeyHandler:(NSNotification *)notification
122 {
123         NSWindow* notification_window = (NSWindow *)[notification object];
124
125         if (top_level_parent == notification_window || cocoa_parent == notification_window) {
126                 if ([notification_window isKeyWindow]) {
127                         plugin_ui->activate();
128                 } else {
129                         plugin_ui->deactivate();
130                 }
131         }
132 }
133
134 - (void)auViewResized:(NSNotification *)notification
135 {
136         (void) notification; // stop complaints about unusued argument
137         plugin_ui->cocoa_view_resized();
138 }
139
140 @end
141
142 AUPluginUI::AUPluginUI (boost::shared_ptr<PluginInsert> insert)
143         : PlugUIBase (insert)
144         , automation_mode_label (_("Automation"))
145         , preset_label (_("Presets"))
146         , mapped (false)
147         , resizable (false)
148         , min_width (0)
149         , min_height (0)
150         , req_width (0)
151         , req_height (0)
152         , alo_width (0)
153         , alo_height (0)
154
155 {
156         if (automation_mode_strings.empty()) {
157                 automation_mode_strings = I18N (_automation_mode_strings);
158         }
159
160         set_popdown_strings (automation_mode_selector, automation_mode_strings);
161         automation_mode_selector.set_active_text (automation_mode_strings.front());
162
163         if ((au = boost::dynamic_pointer_cast<AUPlugin> (insert->plugin())) == 0) {
164                 error << _("unknown type of editor-supplying plugin (note: no AudioUnit support in this version of ardour)") << endmsg;
165                 throw failed_constructor ();
166         }
167
168         /* stuff some stuff into the top of the window */
169
170         HBox* smaller_hbox = manage (new HBox);
171
172         smaller_hbox->set_spacing (6);
173         smaller_hbox->pack_start (preset_label, false, false, 4);
174         smaller_hbox->pack_start (_preset_modified, false, false);
175         smaller_hbox->pack_start (_preset_combo, false, false);
176         smaller_hbox->pack_start (add_button, false, false);
177 #if 0
178         /* Ardour does not currently allow to overwrite existing presets
179          * see save_property_list() in audio_unit.cc
180          */
181         smaller_hbox->pack_start (save_button, false, false);
182 #endif
183 #if 0
184         /* one day these might be useful with an AU plugin, but not yet */
185         smaller_hbox->pack_start (automation_mode_label, false, false);
186         smaller_hbox->pack_start (automation_mode_selector, false, false);
187 #endif
188         smaller_hbox->pack_start (reset_button, false, false);
189         smaller_hbox->pack_start (bypass_button, false, true);
190
191         VBox* v1_box = manage (new VBox);
192         VBox* v2_box = manage (new VBox);
193
194         v1_box->pack_start (*smaller_hbox, false, true);
195         v2_box->pack_start (focus_button, false, true);
196
197         top_box.set_homogeneous (false);
198         top_box.set_spacing (6);
199         top_box.set_border_width (6);
200
201         top_box.pack_end (*v2_box, false, false);
202         top_box.pack_end (*v1_box, false, false);
203
204         set_spacing (6);
205         pack_start (top_box, false, false);
206         pack_start (low_box, true, true);
207
208         preset_label.show ();
209         _preset_combo.show ();
210         automation_mode_label.show ();
211         automation_mode_selector.show ();
212         bypass_button.show ();
213         top_box.show ();
214         low_box.show ();
215
216         cocoa_parent = 0;
217         cocoa_window = 0;
218
219 #ifdef WITH_CARBON
220         _activating_from_app = false;
221         _notify = 0;
222         au_view = 0;
223         editView = 0;
224         carbon_window = 0;
225 #endif
226
227         /* prefer cocoa, fall back to cocoa, but use carbon if its there */
228
229         if (test_cocoa_view_support()) {
230                 create_cocoa_view ();
231 #ifdef WITH_CARBON
232         } else if (test_carbon_view_support()) {
233                 create_carbon_view ();
234 #endif
235         } else {
236                 create_cocoa_view ();
237         }
238
239         low_box.add_events (Gdk::VISIBILITY_NOTIFY_MASK | Gdk::EXPOSURE_MASK);
240
241         low_box.signal_realize().connect (mem_fun (this, &AUPluginUI::lower_box_realized));
242         low_box.signal_visibility_notify_event ().connect (mem_fun (this, &AUPluginUI::lower_box_visibility_notify));
243         low_box.signal_size_request ().connect (mem_fun (this, &AUPluginUI::lower_box_size_request));
244         low_box.signal_size_allocate ().connect (mem_fun (this, &AUPluginUI::lower_box_size_allocate));
245         low_box.signal_map ().connect (mem_fun (this, &AUPluginUI::lower_box_map));
246         low_box.signal_unmap ().connect (mem_fun (this, &AUPluginUI::lower_box_unmap));
247         low_box.signal_expose_event ().connect (mem_fun (this, &AUPluginUI::lower_box_expose));
248 }
249
250 AUPluginUI::~AUPluginUI ()
251 {
252         if (_notify) {
253                 [[NSNotificationCenter defaultCenter] removeObserver:_notify];
254         }
255
256         if (cocoa_parent) {
257                 NSWindow* win = get_nswindow();
258                 [win removeChildWindow:cocoa_parent];
259         }
260
261 #ifdef WITH_CARBON
262         if (carbon_window) {
263                 /* not parented, just overlaid on top of our window */
264                 DisposeWindow (carbon_window);
265         }
266 #endif
267
268         if (editView) {
269                 ArdourCloseComponent (editView);
270         }
271
272         if (au_view) {
273                 /* remove whatever we packed into low_box so that GTK doesn't
274                    mess with it.
275                  */
276
277                 [au_view removeFromSuperview];
278         }
279 }
280
281 bool
282 AUPluginUI::test_carbon_view_support ()
283 {
284 #ifdef WITH_CARBON
285         bool ret = false;
286
287         carbon_descriptor.componentType = kAudioUnitCarbonViewComponentType;
288         carbon_descriptor.componentSubType = 'gnrc';
289         carbon_descriptor.componentManufacturer = 'appl';
290         carbon_descriptor.componentFlags = 0;
291         carbon_descriptor.componentFlagsMask = 0;
292
293         OSStatus err;
294
295         // ask the AU for its first editor component
296         UInt32 propertySize;
297         err = AudioUnitGetPropertyInfo(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, &propertySize, NULL);
298         if (!err) {
299                 int nEditors = propertySize / sizeof(ComponentDescription);
300                 ComponentDescription *editors = new ComponentDescription[nEditors];
301                 err = AudioUnitGetProperty(*au->get_au(), kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global, 0, editors, &propertySize);
302                 if (!err) {
303                         // just pick the first one for now
304                         carbon_descriptor = editors[0];
305                         ret = true;
306                 }
307                 delete[] editors;
308         }
309
310         return ret;
311 #else
312         return false;
313 #endif
314 }
315
316 bool
317 AUPluginUI::test_cocoa_view_support ()
318 {
319         UInt32 dataSize   = 0;
320         Boolean isWritable = 0;
321         OSStatus err = AudioUnitGetPropertyInfo(*au->get_au(),
322                                                 kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
323                                                 0, &dataSize, &isWritable);
324
325         return dataSize > 0 && err == noErr;
326 }
327
328 bool
329 AUPluginUI::plugin_class_valid (Class pluginClass)
330 {
331         if([pluginClass conformsToProtocol: @protocol(AUCocoaUIBase)]) {
332                 if([pluginClass instancesRespondToSelector: @selector(interfaceVersion)] &&
333                    [pluginClass instancesRespondToSelector: @selector(uiViewForAudioUnit:withSize:)]) {
334                                 return true;
335                 }
336         }
337         return false;
338 }
339
340 int
341 AUPluginUI::create_cocoa_view ()
342 {
343         bool wasAbleToLoadCustomView = false;
344         AudioUnitCocoaViewInfo* cocoaViewInfo = NULL;
345         UInt32               numberOfClasses = 0;
346         UInt32     dataSize;
347         Boolean    isWritable;
348         NSString*           factoryClassName = 0;
349         NSURL*              CocoaViewBundlePath = NULL;
350
351         OSStatus result = AudioUnitGetPropertyInfo (*au->get_au(),
352                                                     kAudioUnitProperty_CocoaUI,
353                                                     kAudioUnitScope_Global,
354                                                     0,
355                                                     &dataSize,
356                                                     &isWritable );
357
358         numberOfClasses = (dataSize - sizeof(CFURLRef)) / sizeof(CFStringRef);
359
360         // Does view have custom Cocoa UI?
361
362         if ((result == noErr) && (numberOfClasses > 0) ) {
363
364                 DEBUG_TRACE(DEBUG::AudioUnits,
365                             string_compose ( "based on %1, there are %2 cocoa UI classes\n", dataSize, numberOfClasses));
366
367                 cocoaViewInfo = (AudioUnitCocoaViewInfo *)malloc(dataSize);
368
369                 if(AudioUnitGetProperty(*au->get_au(),
370                                         kAudioUnitProperty_CocoaUI,
371                                         kAudioUnitScope_Global,
372                                         0,
373                                         cocoaViewInfo,
374                                         &dataSize) == noErr) {
375
376                         CocoaViewBundlePath     = (NSURL *)cocoaViewInfo->mCocoaAUViewBundleLocation;
377
378                         // we only take the first view in this example.
379                         factoryClassName        = (NSString *)cocoaViewInfo->mCocoaAUViewClass[0];
380
381                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("the factory name is %1 bundle is %2\n",
382                                                                         [factoryClassName UTF8String], CocoaViewBundlePath));
383
384                 } else {
385
386                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("No cocoaUI property cocoaViewInfo = %1\n", cocoaViewInfo));
387
388                         if (cocoaViewInfo != NULL) {
389                                 free (cocoaViewInfo);
390                                 cocoaViewInfo = NULL;
391                         }
392                 }
393         }
394
395         // [A] Show custom UI if view has it
396
397         if (CocoaViewBundlePath && factoryClassName) {
398                 NSBundle *viewBundle    = [NSBundle bundleWithPath:[CocoaViewBundlePath path]];
399
400                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("tried to create bundle, result = %1\n", viewBundle));
401
402                 if (viewBundle == NULL) {
403                         error << _("AUPluginUI: error loading AU view's bundle") << endmsg;
404                         return -1;
405                 } else {
406                         Class factoryClass = [viewBundle classNamed:factoryClassName];
407                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("tried to create factory class, result = %1\n", factoryClass));
408                         if (!factoryClass) {
409                                 error << _("AUPluginUI: error getting AU view's factory class from bundle") << endmsg;
410                                 return -1;
411                         }
412
413                         // make sure 'factoryClass' implements the AUCocoaUIBase protocol
414                         if (!plugin_class_valid (factoryClass)) {
415                                 error << _("AUPluginUI: U view's factory class does not properly implement the AUCocoaUIBase protocol") << endmsg;
416                                 return -1;
417                         }
418                         // make a factory
419                         id factory = [[[factoryClass alloc] init] autorelease];
420                         if (factory == NULL) {
421                                 error << _("AUPluginUI: Could not create an instance of the AU view factory") << endmsg;
422                                 return -1;
423                         }
424
425                         DEBUG_TRACE (DEBUG::AudioUnits, "got a factory instance\n");
426
427                         // make a view
428                         au_view = [factory uiViewForAudioUnit:*au->get_au() withSize:NSZeroSize];
429
430                         DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("view created @ %1\n", au_view));
431
432                         // cleanup
433                         [CocoaViewBundlePath release];
434                         if (cocoaViewInfo) {
435                                 UInt32 i;
436                                 for (i = 0; i < numberOfClasses; i++)
437                                         CFRelease(cocoaViewInfo->mCocoaAUViewClass[i]);
438
439                                 free (cocoaViewInfo);
440                         }
441                         wasAbleToLoadCustomView = true;
442                 }
443         }
444
445         if (!wasAbleToLoadCustomView) {
446                 // load generic Cocoa view
447                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("Loading generic view using %1 -> %2\n", au,
448                                                                 au->get_au()));
449                 au_view = [[AUGenericView alloc] initWithAudioUnit:*au->get_au()];
450                 DEBUG_TRACE (DEBUG::AudioUnits, string_compose ("view created @ %1\n", au_view));
451                 [(AUGenericView *)au_view setShowsExpertParameters:1];
452         }
453
454         // Get the initial size of the new AU View's frame
455         NSRect  frame = [au_view frame];
456         min_width  = req_width  = CGRectGetWidth(NSRectToCGRect(frame));
457         min_height = req_height = CGRectGetHeight(NSRectToCGRect(frame));
458         resizable  = [au_view autoresizingMask];
459
460         low_box.queue_resize ();
461
462         return 0;
463 }
464
465 void
466 AUPluginUI::cocoa_view_resized ()
467 {
468         if (!mapped || alo_width == 0 || alo_height == 0 || !resizable) {
469                 return;
470         }
471         /* check for self-resizing plugins (e.g expand settings in AUSampler)
472          * if the widget expands it moves its y-offset (cocoa y-axis points towards the top)
473          */
474         NSRect new_au_frame = [au_view frame];
475
476         //float dx = last_au_frame.origin.x - new_au_frame.origin.x;
477         float dy = last_au_frame.origin.y - new_au_frame.origin.y;
478         //req_width += dx;
479         req_height += dy;
480         if (req_width < min_width) req_width = min_width;
481         if (req_height < min_height) req_height = min_height;
482
483         last_au_frame = new_au_frame;
484         low_box.queue_resize ();
485 }
486
487 int
488 AUPluginUI::create_carbon_view ()
489 {
490 #ifdef WITH_CARBON
491         OSStatus err;
492         ControlRef root_control;
493
494         Component editComponent = FindNextComponent(NULL, &carbon_descriptor);
495
496         OpenAComponent(editComponent, &editView);
497         if (!editView) {
498                 error << _("AU Carbon view: cannot open AU Component") << endmsg;
499                 return -1;
500         }
501
502         Rect r = { 100, 100, 100, 100 };
503         WindowAttributes attr = WindowAttributes (kWindowStandardHandlerAttribute |
504                                                   kWindowCompositingAttribute|
505                                                   kWindowNoShadowAttribute|
506                                                   kWindowNoTitleBarAttribute);
507
508         if ((err = CreateNewWindow(kUtilityWindowClass, attr, &r, &carbon_window)) != noErr) {
509                 error << string_compose (_("AUPluginUI: cannot create carbon window (err: %1)"), err) << endmsg;
510                 ArdourCloseComponent (editView);
511                 return -1;
512         }
513
514         if ((err = GetRootControl(carbon_window, &root_control)) != noErr) {
515                 error << string_compose (_("AUPlugin: cannot get root control of carbon window (err: %1)"), err) << endmsg;
516                 DisposeWindow (carbon_window);
517                 ArdourCloseComponent (editView);
518                 return -1;
519         }
520
521         ControlRef viewPane;
522         Float32Point location  = { 0.0, 0.0 };
523         Float32Point size = { 0.0, 0.0 } ;
524
525         if ((err = AudioUnitCarbonViewCreate (editView, *au->get_au(), carbon_window, root_control, &location, &size, &viewPane)) != noErr) {
526                 error << string_compose (_("AUPluginUI: cannot create carbon plugin view (err: %1)"), err) << endmsg;
527                 DisposeWindow (carbon_window);
528                 ArdourCloseComponent (editView);
529                 return -1;
530         }
531
532         // resize window
533
534         Rect bounds;
535         GetControlBounds(viewPane, &bounds);
536         size.x = bounds.right-bounds.left;
537         size.y = bounds.bottom-bounds.top;
538
539         req_width = (int) (size.x + 0.5);
540         req_height = (int) (size.y + 0.5);
541
542         SizeWindow (carbon_window, prefwidth, req_height,  true);
543         low_box.set_size_request (prefwidth, req_height); // ??
544
545         return 0;
546 #else
547         error << _("AU Carbon GUI is not supported.") << endmsg;
548         return -1;
549 #endif
550 }
551
552 NSWindow*
553 AUPluginUI::get_nswindow ()
554 {
555         Gtk::Container* toplevel = get_toplevel();
556
557         if (!toplevel || !toplevel->is_toplevel()) {
558                 error << _("AUPluginUI: no top level window!") << endmsg;
559                 return 0;
560         }
561
562         NSWindow* true_parent = gdk_quartz_window_get_nswindow (toplevel->get_window()->gobj());
563
564         if (!true_parent) {
565                 error << _("AUPluginUI: no top level window!") << endmsg;
566                 return 0;
567         }
568
569         return true_parent;
570 }
571
572 void
573 AUPluginUI::activate ()
574 {
575 #ifdef WITH_CARBON
576         ActivateWindow (carbon_window, TRUE);
577 #endif
578 }
579
580 void
581 AUPluginUI::deactivate ()
582 {
583 #ifdef WITH_CARBON
584         ActivateWindow (carbon_window, FALSE);
585 #endif
586 }
587
588 int
589 AUPluginUI::parent_carbon_window ()
590 {
591 #ifdef WITH_CARBON
592         NSWindow* win = get_nswindow ();
593         Rect windowStructureBoundsRect;
594
595         if (!win) {
596                 return -1;
597         }
598
599         Gtk::Container* toplevel = get_toplevel();
600
601         if (!toplevel || !toplevel->is_toplevel()) {
602                 error << _("AUPluginUI: no top level window!") << endmsg;
603                 return -1;
604         }
605
606         /* figure out where the cocoa parent window is in carbon-coordinate space, which
607            differs from both cocoa-coordinate space and GTK-coordinate space
608         */
609
610         GetWindowBounds((WindowRef) [win windowRef], kWindowStructureRgn, &windowStructureBoundsRect);
611
612         /* compute how tall the title bar is, because we have to offset the position of the carbon window
613            by that much.
614         */
615
616         NSRect content_frame = [NSWindow contentRectForFrameRect:[win frame] styleMask:[win styleMask]];
617         NSRect wm_frame = [NSWindow frameRectForContentRect:content_frame styleMask:[win styleMask]];
618
619         int titlebar_height = wm_frame.size.height - content_frame.size.height;
620
621         int packing_extra = 6; // this is the total vertical packing in our top level window
622
623         /* move into position, based on parent window position */
624         MoveWindow (carbon_window,
625                     windowStructureBoundsRect.left,
626                     windowStructureBoundsRect.top + titlebar_height + top_box.get_height() + packing_extra,
627                     false);
628         ShowWindow (carbon_window);
629
630         // create the cocoa window for the carbon one and make it visible
631         cocoa_parent = [[NSWindow alloc] initWithWindowRef: carbon_window];
632
633         SetWindowActivationScope (carbon_window, kWindowActivationScopeNone);
634
635         _notify = [ [NotificationObject alloc] initWithPluginUI:this andCocoaParent:cocoa_parent andTopLevelParent:win ];
636
637         [win addChildWindow:cocoa_parent ordered:NSWindowAbove];
638         [win setAutodisplay:1]; // turn of GTK stuff for this window
639
640         return 0;
641 #else
642         return -1;
643 #endif
644 }
645
646 int
647 AUPluginUI::parent_cocoa_window ()
648 {
649         NSWindow* win = get_nswindow ();
650
651         if (!win) {
652                 return -1;
653         }
654
655         //[win setAutodisplay:1]; // turn off GTK stuff for this window
656
657         NSView* view = gdk_quartz_window_get_nsview (low_box.get_window()->gobj());
658         [view addSubview:au_view];
659
660         gint xx, yy;
661         gtk_widget_translate_coordinates(
662                         GTK_WIDGET(low_box.gobj()),
663                         GTK_WIDGET(low_box.get_parent()->gobj()),
664                         8, 6, &xx, &yy);
665         [au_view setFrame:NSMakeRect(xx, yy, req_width, req_height)];
666
667         last_au_frame = [au_view frame];
668         // watch for size changes of the view
669         _notify = [ [NotificationObject alloc] initWithPluginUI:this andCocoaParent:NULL andTopLevelParent:win ];
670
671         [[NSNotificationCenter defaultCenter] addObserver:_notify
672                 selector:@selector(auViewResized:) name:NSViewFrameDidChangeNotification
673                 object:au_view];
674
675         return 0;
676 }
677
678 void
679 AUPluginUI::grab_focus()
680 {
681         if (au_view) {
682                 [au_view becomeFirstResponder];
683         }
684 }
685 void
686 AUPluginUI::forward_key_event (GdkEventKey* ev)
687 {
688         NSEvent* nsevent = gdk_quartz_event_get_nsevent ((GdkEvent*)ev);
689
690         if (au_view && nsevent) {
691
692                 /* filter on nsevent type here because GDK massages FlagsChanged
693                    messages into GDK_KEY_{PRESS,RELEASE} but Cocoa won't
694                    handle a FlagsChanged message as a keyDown or keyUp
695                 */
696
697                 if ([nsevent type] == NSKeyDown) {
698                         [[[au_view window] firstResponder] keyDown:nsevent];
699                 } else if ([nsevent type] == NSKeyUp) {
700                         [[[au_view window] firstResponder] keyUp:nsevent];
701                 } else if ([nsevent type] == NSFlagsChanged) {
702                         [[[au_view window] firstResponder] flagsChanged:nsevent];
703                 }
704         }
705 }
706
707 void
708 AUPluginUI::on_realize ()
709 {
710         VBox::on_realize ();
711
712         /* our windows should not have that resize indicator */
713
714         NSWindow* win = get_nswindow ();
715         if (win) {
716                 [win setShowsResizeIndicator:0];
717         }
718 }
719
720 void
721 AUPluginUI::lower_box_realized ()
722 {
723         if (au_view) {
724                 parent_cocoa_window ();
725         } else if (carbon_window) {
726                 parent_carbon_window ();
727         }
728 }
729
730 bool
731 AUPluginUI::lower_box_visibility_notify (GdkEventVisibility* ev)
732 {
733 #ifdef WITH_CARBON
734         if (carbon_window  && ev->state != GDK_VISIBILITY_UNOBSCURED) {
735                 ShowWindow (carbon_window);
736                 ActivateWindow (carbon_window, TRUE);
737                 return true;
738         }
739 #endif
740         return false;
741 }
742
743 void
744 AUPluginUI::update_view_size ()
745 {
746         if (!mapped || alo_width == 0 || alo_height == 0) {
747                 return;
748         }
749         gint xx, yy;
750         gtk_widget_translate_coordinates(
751                         GTK_WIDGET(low_box.gobj()),
752                         GTK_WIDGET(low_box.get_parent()->gobj()),
753                         8, 6, &xx, &yy);
754
755         [[NSNotificationCenter defaultCenter] removeObserver:_notify
756                 name:NSViewFrameDidChangeNotification
757                 object:au_view];
758
759         if (!resizable) {
760                 xx += (alo_width - req_width) * .5;
761                 [au_view setFrame:NSMakeRect(xx, yy, req_width, req_height)];
762         } else {
763                 /* this mitigates issues with plugins that resize themselves
764                  * depending on visible options (e.g AUSampler)
765                  * since the OSX y-axis points upwards, the plugin adjusts its
766                  * own y-offset if the view expands to the bottom to accomodate
767                  * subviews inside the main view.
768                  */
769                 [au_view setAutoresizesSubviews:0];
770                 [au_view setFrame:NSMakeRect(xx, yy, alo_width, alo_height)];
771                 [au_view setAutoresizesSubviews:1];
772                 [au_view setNeedsDisplay:1];
773         }
774
775         last_au_frame = [au_view frame];
776
777         [[NSNotificationCenter defaultCenter]
778              addObserver:_notify
779                 selector:@selector(auViewResized:) name:NSViewFrameDidChangeNotification
780                   object:au_view];
781 }
782
783 void
784 AUPluginUI::lower_box_map ()
785 {
786         mapped = true;
787         [au_view setHidden:0];
788         update_view_size ();
789 }
790
791 void
792 AUPluginUI::lower_box_unmap ()
793 {
794         mapped = false;
795         [au_view setHidden:1];
796 }
797
798 void
799 AUPluginUI::lower_box_size_request (GtkRequisition* requisition)
800 {
801         requisition->width  = req_width;
802         requisition->height = req_height;
803 }
804
805 void
806 AUPluginUI::lower_box_size_allocate (Gtk::Allocation& allocation)
807 {
808         alo_width  = allocation.get_width ();
809         alo_height = allocation.get_height ();
810         update_view_size ();
811 }
812
813 gboolean
814 AUPluginUI::lower_box_expose (GdkEventExpose* event)
815 {
816 #if 0 // AU view magically redraws by itself
817         [au_view drawRect:NSMakeRect(event->area.x,
818                         event->area.y,
819                         event->area.width,
820                         event->area.height)];
821 #endif
822         /* hack to keep ardour responsive
823          * some UIs (e.g Addictive Drums) completely hog the CPU
824          */
825         ARDOUR::GUIIdle();
826
827         return true;
828 }
829
830 void
831 AUPluginUI::on_window_hide ()
832 {
833 #ifdef WITH_CARBON
834         if (carbon_window) {
835                 HideWindow (carbon_window);
836                 ActivateWindow (carbon_window, FALSE);
837         }
838 #endif
839         hide_all ();
840
841 #if 0
842         NSArray* wins = [NSApp windows];
843         for (uint32_t i = 0; i < [wins count]; i++) {
844                 id win = [wins objectAtIndex:i];
845         }
846 #endif
847 }
848
849 bool
850 AUPluginUI::on_window_show (const string& /*title*/)
851 {
852         /* this is idempotent so just call it every time we show the window */
853
854         gtk_widget_realize (GTK_WIDGET(low_box.gobj()));
855
856         show_all ();
857
858 #ifdef WITH_CARBON
859         if (carbon_window) {
860                 ShowWindow (carbon_window);
861                 ActivateWindow (carbon_window, TRUE);
862         }
863 #endif
864
865         return true;
866 }
867
868 bool
869 AUPluginUI::start_updating (GdkEventAny*)
870 {
871         return false;
872 }
873
874 bool
875 AUPluginUI::stop_updating (GdkEventAny*)
876 {
877         return false;
878 }
879
880 PlugUIBase*
881 create_au_gui (boost::shared_ptr<PluginInsert> plugin_insert, VBox** box)
882 {
883         AUPluginUI* aup = new AUPluginUI (plugin_insert);
884         (*box) = aup;
885         return aup;
886 }
887
888