Add Menu channel for rendering system menus with native APIs on macOS. (flutter/engine#32358)

This commit is contained in:
Greg Spencer
2022-03-31 10:30:03 -07:00
committed by GitHub
parent fffb0a94b5
commit b52c5a9fe5
9 changed files with 700 additions and 0 deletions

View File

@@ -1425,6 +1425,7 @@ FILE: ../../../flutter/shell/platform/common/json_method_codec_unittests.cc
FILE: ../../../flutter/shell/platform/common/path_utils.cc
FILE: ../../../flutter/shell/platform/common/path_utils.h
FILE: ../../../flutter/shell/platform/common/path_utils_unittests.cc
FILE: ../../../flutter/shell/platform/common/platform_provided_menu.h
FILE: ../../../flutter/shell/platform/common/public/flutter_export.h
FILE: ../../../flutter/shell/platform/common/public/flutter_messenger.h
FILE: ../../../flutter/shell/platform/common/public/flutter_plugin_registrar.h
@@ -1650,6 +1651,10 @@ FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeybo
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManagerUnittests.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardViewDelegate.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMacOSExternalTexture.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPluginTest.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin_Internal.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalCompositor.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalCompositor.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalCompositorUnittests.mm

View File

@@ -56,6 +56,15 @@ source_set("common_cpp_input") {
deps = [ "//flutter/fml:fml" ]
}
source_set("common_cpp_enums") {
public = [ "platform_provided_menu.h" ]
public_configs = [
"//flutter:config",
"//flutter/common:flutter_config",
]
}
source_set("common_cpp_switches") {
public = [ "engine_switches.h" ]

View File

@@ -0,0 +1,52 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PLATFORM_COMMON_PLATFORM_PROVIDED_MENU_H_
#define PLATFORM_COMMON_PLATFORM_PROVIDED_MENU_H_
namespace flutter {
// Enumerates the provided menus that a platform may support.
// Must be kept in sync with the framework enum in widgets/menu.dart.
enum class PlatformProvidedMenu {
// orderFrontStandardAboutPanel macOS provided menu
kAbout,
// terminate macOS provided menu
kQuit,
// Services macOS provided submenu.
kServicesSubmenu,
// hide macOS provided menu
kHide,
// hideOtherApplications macOS provided menu
kHideOtherApplications,
// unhideAllApplications macOS provided menu
kShowAllApplications,
// startSpeaking macOS provided menu
kStartSpeaking,
// stopSpeaking macOS provided menu
kStopSpeaking,
// toggleFullScreen macOS provided menu
kToggleFullScreen,
// performMiniaturize macOS provided menu
kMinimizeWindow,
// performZoom macOS provided menu
kZoomWindow,
// arrangeInFront macOS provided menu
kArrangeWindowsInFront,
};
} // namespace flutter
#endif // PLATFORM_COMMON_PLATFORM_provided_MENU_H_

View File

@@ -87,6 +87,9 @@ source_set("flutter_framework_source") {
"framework/Source/FlutterKeyboardViewDelegate.h",
"framework/Source/FlutterMacOSExternalTexture.h",
"framework/Source/FlutterMacOSExternalTexture.h",
"framework/Source/FlutterMenuPlugin.h",
"framework/Source/FlutterMenuPlugin.mm",
"framework/Source/FlutterMenuPlugin_Internal.h",
"framework/Source/FlutterMetalCompositor.h",
"framework/Source/FlutterMetalCompositor.mm",
"framework/Source/FlutterMetalRenderer.h",
@@ -130,6 +133,7 @@ source_set("flutter_framework_source") {
"//flutter/flow:flow",
"//flutter/fml",
"//flutter/shell/platform/common:common_cpp_accessibility",
"//flutter/shell/platform/common:common_cpp_enums",
"//flutter/shell/platform/common:common_cpp_input",
"//flutter/shell/platform/common:common_cpp_switches",
"//flutter/shell/platform/darwin/common:framework_shared",
@@ -185,6 +189,7 @@ executable("flutter_desktop_darwin_unittests") {
"framework/Source/FlutterFrameBufferProviderUnittests.mm",
"framework/Source/FlutterGLCompositorUnittests.mm",
"framework/Source/FlutterKeyboardManagerUnittests.mm",
"framework/Source/FlutterMenuPluginTest.mm",
"framework/Source/FlutterMetalCompositorUnittests.mm",
"framework/Source/FlutterMetalRendererTest.mm",
"framework/Source/FlutterMetalSurfaceManagerTest.mm",
@@ -208,6 +213,7 @@ executable("flutter_desktop_darwin_unittests") {
":flutter_desktop_darwin_fixtures",
":flutter_framework_source",
"//flutter/shell/platform/common:common_cpp_accessibility",
"//flutter/shell/platform/common:common_cpp_enums",
"//flutter/shell/platform/darwin/common:framework_shared",
"//flutter/shell/platform/darwin/graphics",
"//flutter/shell/platform/embedder:embedder_as_internal_library",

View File

@@ -0,0 +1,23 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <AppKit/AppKit.h>
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h"
/**
* A plugin to configure and control the native system menu.
*
* Responsible for bridging the native macOS menu system with the Flutter
* framework's PlatformMenuBar class, via method channels.
*/
@interface FlutterMenuPlugin : NSObject <FlutterPlugin>
/**
* Registers a FlutterMenuPlugin with the given registrar.
*/
+ (void)registerWithRegistrar:(nonnull id<FlutterPluginRegistrar>)registrar;
@end

View File

@@ -0,0 +1,416 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FlutterMenuPlugin.h"
#include <map>
#import "flutter/shell/platform/common/platform_provided_menu.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h"
// Channel constants
static NSString* const kChannelName = @"flutter/menu";
static NSString* const kMenuSetMethod = @"Menu.setMenu";
static NSString* const kMenuItemSelectedCallbackMethod = @"Menu.selectedCallback";
static NSString* const kMenuItemOpenedMethod = @"Menu.opened";
static NSString* const kMenuItemClosedMethod = @"Menu.closed";
// Serialization keys for menu objects
static NSString* const kIdKey = @"id";
static NSString* const kLabelKey = @"label";
static NSString* const kEnabledKey = @"enabled";
static NSString* const kChildrenKey = @"children";
static NSString* const kDividerKey = @"isDivider";
static NSString* const kShortcutEquivalentKey = @"shortcutEquivalent";
static NSString* const kShortcutTriggerKey = @"shortcutTrigger";
static NSString* const kShortcutModifiersKey = @"shortcutModifiers";
static NSString* const kPlatformProvidedMenuKey = @"platformProvidedMenu";
// Key shortcut constants
constexpr int kFlutterShortcutModifierMeta = 1 << 0;
constexpr int kFlutterShortcutModifierShift = 1 << 1;
constexpr int kFlutterShortcutModifierAlt = 1 << 2;
constexpr int kFlutterShortcutModifierControl = 1 << 3;
constexpr uint64_t kFlutterKeyIdPlaneMask = 0xff00000000l;
constexpr uint64_t kFlutterKeyIdUnicodePlane = 0x0000000000l;
constexpr uint64_t kFlutterKeyIdValueMask = 0x00ffffffffl;
static const NSDictionary* logicalKeyToKeyCode = {};
// What to look for in menu titles to replace with the application name.
static NSString* const kAppName = @"APP_NAME";
// Odd facts about AppKit key equivalents:
//
// 1) ⌃⇧1 and ⇧1 cannot exist in the same app, or the former triggers the latter’s
// action.
// 2) ⌃⌥⇧1 and ⇧1 cannot exist in the same app, or the former triggers the latter’s
// action.
// 3) ⌃⌥⇧1 and ⌃⇧1 cannot exist in the same app, or the former triggers the latter’s
// action.
// 4) ⌃⇧a is equivalent to ⌃A: If a keyEquivalent is a capitalized alphabetical
// letter and keyEquivalentModifierMask does not include
// NSEventModifierFlagShift, AppKit will add ⇧ automatically in the UI.
/*
* Maps the string used by NSMenuItem for the given special key equivalent.
* Keys are the logical key ids of matching trigger keys.
*/
static NSDictionary<NSNumber*, NSNumber*>* GetMacOsSpecialKeys() {
return @{
@0x00100000008 : [NSNumber numberWithInt:NSBackspaceCharacter],
@0x00100000009 : [NSNumber numberWithInt:NSTabCharacter],
@0x0010000000a : [NSNumber numberWithInt:NSNewlineCharacter],
@0x0010000000c : [NSNumber numberWithInt:NSFormFeedCharacter],
@0x0010000000d : [NSNumber numberWithInt:NSCarriageReturnCharacter],
@0x0010000007f : [NSNumber numberWithInt:NSDeleteCharacter],
@0x00100000801 : [NSNumber numberWithInt:NSF1FunctionKey],
@0x00100000802 : [NSNumber numberWithInt:NSF2FunctionKey],
@0x00100000803 : [NSNumber numberWithInt:NSF3FunctionKey],
@0x00100000804 : [NSNumber numberWithInt:NSF4FunctionKey],
@0x00100000805 : [NSNumber numberWithInt:NSF5FunctionKey],
@0x00100000806 : [NSNumber numberWithInt:NSF6FunctionKey],
@0x00100000807 : [NSNumber numberWithInt:NSF7FunctionKey],
@0x00100000808 : [NSNumber numberWithInt:NSF8FunctionKey],
@0x00100000809 : [NSNumber numberWithInt:NSF9FunctionKey],
@0x0010000080a : [NSNumber numberWithInt:NSF10FunctionKey],
@0x0010000080b : [NSNumber numberWithInt:NSF11FunctionKey],
@0x0010000080c : [NSNumber numberWithInt:NSF12FunctionKey],
@0x0010000080d : [NSNumber numberWithInt:NSF13FunctionKey],
@0x0010000080e : [NSNumber numberWithInt:NSF14FunctionKey],
@0x0010000080f : [NSNumber numberWithInt:NSF15FunctionKey],
@0x00100000810 : [NSNumber numberWithInt:NSF16FunctionKey],
@0x00100000811 : [NSNumber numberWithInt:NSF17FunctionKey],
@0x00100000812 : [NSNumber numberWithInt:NSF18FunctionKey],
@0x00100000813 : [NSNumber numberWithInt:NSF19FunctionKey],
@0x00100000814 : [NSNumber numberWithInt:NSF20FunctionKey],
// For some reason, there don't appear to be constants for these in ObjC. In
// Swift, there is a class with static members for these: KeyEquivalent. The
// values below are taken from that (where they don't already appear above).
@0x00100000302 : @0xf702, // ArrowLeft
@0x00100000303 : @0xf703, // ArrowRight
@0x00100000304 : @0xf700, // ArrowUp
@0x00100000301 : @0xf701, // ArrowDown
@0x00100000306 : @0xf729, // Home
@0x00100000305 : @0xf72B, // End
@0x00100000308 : @0xf72c, // PageUp
@0x00100000307 : @0xf72d, // PageDown
@0x0010000001b : @0x001B, // Escape
};
}
/*
* The mapping from the PlatformProvidedMenu enum to the macOS selectors for the provided
* menus.
*/
static const std::map<flutter::PlatformProvidedMenu, SEL> GetMacOSProvidedMenus() {
return {
{flutter::PlatformProvidedMenu::kAbout, @selector(orderFrontStandardAboutPanel:)},
{flutter::PlatformProvidedMenu::kQuit, @selector(terminate:)},
// servicesSubmenu is handled specially below: it is assumed to be the first
// submenu in the preserved platform provided menus, since it doesn't have a
// definitive selector like the rest.
{flutter::PlatformProvidedMenu::kServicesSubmenu, @selector(submenuAction:)},
{flutter::PlatformProvidedMenu::kHide, @selector(hide:)},
{flutter::PlatformProvidedMenu::kHideOtherApplications, @selector(hideOtherApplications:)},
{flutter::PlatformProvidedMenu::kShowAllApplications, @selector(unhideAllApplications:)},
{flutter::PlatformProvidedMenu::kStartSpeaking, @selector(startSpeaking:)},
{flutter::PlatformProvidedMenu::kStopSpeaking, @selector(stopSpeaking:)},
{flutter::PlatformProvidedMenu::kToggleFullScreen, @selector(toggleFullScreen:)},
{flutter::PlatformProvidedMenu::kMinimizeWindow, @selector(performMiniaturize:)},
{flutter::PlatformProvidedMenu::kZoomWindow, @selector(performZoom:)},
{flutter::PlatformProvidedMenu::kArrangeWindowsInFront, @selector(arrangeInFront:)},
};
}
/*
* Returns the NSEventModifierFlags of |modifiers|, a value from
* kShortcutKeyModifiers.
*/
static NSEventModifierFlags KeyEquivalentModifierMaskForModifiers(NSNumber* modifiers) {
int flutterModifierFlags = modifiers.intValue;
NSEventModifierFlags flags = 0;
if (flutterModifierFlags & kFlutterShortcutModifierMeta) {
flags |= NSEventModifierFlagCommand;
}
if (flutterModifierFlags & kFlutterShortcutModifierShift) {
flags |= NSEventModifierFlagShift;
}
if (flutterModifierFlags & kFlutterShortcutModifierAlt) {
flags |= NSEventModifierFlagOption;
}
if (flutterModifierFlags & kFlutterShortcutModifierControl) {
flags |= NSEventModifierFlagControl;
}
// There are also modifier flags for things like the function (Fn) key, but
// the framework doesn't support those.
return flags;
}
/*
* An NSMenuDelegate used to listen for changes in the menu when it opens and
* closes.
*/
@interface FlutterMenuDelegate : NSObject <NSMenuDelegate>
/*
* When this delegate receives notification that the menu opened or closed, it
* will send a message on the given channel to that effect for the menu item
* with the given id (the ID comes from the data supplied by the framework to
* FlutterMenuPlugin.setMenu).
*/
- (instancetype)initWithIdentifier:(int64_t)identifier channel:(FlutterMethodChannel*)channel;
@end
@implementation FlutterMenuDelegate {
FlutterMethodChannel* _channel;
int64_t _identifier;
}
- (instancetype)initWithIdentifier:(int64_t)identifier channel:(FlutterMethodChannel*)channel {
self = [super init];
if (self) {
_identifier = identifier;
_channel = channel;
}
return self;
}
- (void)menuWillOpen:(NSMenu*)menu {
[_channel invokeMethod:kMenuItemOpenedMethod arguments:@(_identifier)];
}
- (void)menuDidClose:(NSMenu*)menu {
[_channel invokeMethod:kMenuItemClosedMethod arguments:@(_identifier)];
}
@end
@interface FlutterMenuPlugin ()
// Initialize the plugin with the given method channel.
- (instancetype)initWithChannel:(FlutterMethodChannel*)channel;
// Iterates through the given menu hierarchy, and replaces "APP_NAME"
// with the localized running application name.
- (void)replaceAppName:(NSArray<NSMenuItem*>*)items;
// Look up the menu item with the given selector in the list of provided menus
// and return it.
- (NSMenuItem*)findProvidedMenuItem:(NSMenu*)menu ofType:(SEL)selector;
// Create a platform-provided menu from the given enum type.
- (NSMenuItem*)createPlatformProvidedMenu:(flutter::PlatformProvidedMenu)type;
// Create an NSMenuItem from information in the dictionary sent by the framework.
- (NSMenuItem*)menuItemFromFlutterRepresentation:(NSDictionary*)representation;
// Invokes kMenuItemSelectedCallbackMethod with the senders ID.
//
// Used as the callback for all Flutter-created menu items that have IDs.
- (void)flutterMenuItemSelected:(id)sender;
// Replaces the NSApp.mainMenu with menus created from an array of top level
// menus sent by the framework.
- (void)setMenu:(nonnull NSDictionary*)representation;
@end
@implementation FlutterMenuPlugin {
// The channel used to communicate with Flutter.
FlutterMethodChannel* _channel;
// This contains a copy of the default platform provided items.
NSArray<NSMenuItem*>* _platformProvidedItems;
// These are the menu delegates that will listen to open/close events for menu
// items. This array is holding them so that we can deallocate them when
// rebuilding the menus.
NSMutableArray<FlutterMenuDelegate*>* _menuDelegates;
}
#pragma mark - Private Methods
- (instancetype)initWithChannel:(FlutterMethodChannel*)channel {
self = [super init];
if (self) {
_channel = channel;
_platformProvidedItems = @[];
_menuDelegates = [[NSMutableArray alloc] init];
// Make a copy of all the platform provided menus for later use.
_platformProvidedItems = [[NSApp.mainMenu itemArray] mutableCopy];
// As copied, these platform provided menu items don't yet have the APP_NAME
// string replaced in them, so this rectifies that.
[self replaceAppName:_platformProvidedItems];
}
return self;
}
/**
* Iterates through the given menu hierarchy, and replaces "APP_NAME"
* with the localized running application name.
*/
- (void)replaceAppName:(NSArray<NSMenuItem*>*)items {
NSString* appName = [NSRunningApplication currentApplication].localizedName;
for (NSMenuItem* item in items) {
if ([[item title] containsString:kAppName]) {
[item setTitle:[[item title] stringByReplacingOccurrencesOfString:kAppName
withString:appName]];
}
if ([item hasSubmenu]) {
[self replaceAppName:[[item submenu] itemArray]];
}
}
}
- (NSMenuItem*)findProvidedMenuItem:(NSMenu*)menu ofType:(SEL)selector {
const NSArray<NSMenuItem*>* items = menu ? menu.itemArray : _platformProvidedItems;
for (NSMenuItem* item in items) {
if ([item action] == selector) {
return item;
}
if ([[item submenu] numberOfItems] > 0) {
NSMenuItem* foundChild = [self findProvidedMenuItem:[item submenu] ofType:selector];
if (foundChild) {
return foundChild;
}
}
}
return nil;
}
- (NSMenuItem*)createPlatformProvidedMenu:(flutter::PlatformProvidedMenu)type {
const std::map<flutter::PlatformProvidedMenu, SEL> providedMenus = GetMacOSProvidedMenus();
auto found_type = providedMenus.find(type);
if (found_type == providedMenus.end()) {
return nil;
}
SEL selectorTarget = found_type->second;
// Since it doesn't have a definitive selector, the Services submenu is
// assumed to be the first item with a submenu action in the first menu item
// of the default menu set. We can't just get the title to check, since that
// is localized, and the contents of the menu aren't fixed (or even available).
NSMenu* startingMenu = type == flutter::PlatformProvidedMenu::kServicesSubmenu
? [_platformProvidedItems[0] submenu]
: nil;
NSMenuItem* found = [self findProvidedMenuItem:startingMenu ofType:selectorTarget];
// Return a copy because the original menu item might not have been removed
// from the main menu yet, and AppKit doesn't like menu items that exist in
// more than one menu at a time.
return [found copy];
}
- (NSMenuItem*)menuItemFromFlutterRepresentation:(NSDictionary*)representation {
if ([(NSNumber*)([representation valueForKey:kDividerKey]) intValue] == YES) {
return [NSMenuItem separatorItem];
}
NSNumber* platformProvidedMenuId = representation[kPlatformProvidedMenuKey];
NSString* keyEquivalent = @"";
if (platformProvidedMenuId) {
return [self
createPlatformProvidedMenu:(flutter::PlatformProvidedMenu)platformProvidedMenuId.intValue];
} else {
if (representation[kShortcutEquivalentKey]) {
keyEquivalent = representation[kShortcutEquivalentKey];
} else {
NSNumber* triggerKeyId = representation[kShortcutTriggerKey];
const NSDictionary<NSNumber*, NSNumber*>* specialKeys = GetMacOsSpecialKeys();
NSNumber* trigger = specialKeys[triggerKeyId];
if (trigger) {
keyEquivalent = [NSString stringWithFormat:@"%C", [trigger unsignedShortValue]];
} else {
if (([triggerKeyId unsignedLongLongValue] & kFlutterKeyIdPlaneMask) ==
kFlutterKeyIdUnicodePlane) {
keyEquivalent = [[NSString
stringWithFormat:@"%C", (unichar)([triggerKeyId unsignedLongLongValue] &
kFlutterKeyIdValueMask)] lowercaseString];
}
}
}
}
NSNumber* identifier = representation[kIdKey];
SEL action = (identifier ? @selector(flutterMenuItemSelected:) : NULL);
NSString* appName = [NSRunningApplication currentApplication].localizedName;
NSString* title = [representation[kLabelKey] stringByReplacingOccurrencesOfString:kAppName
withString:appName];
NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:title
action:action
keyEquivalent:keyEquivalent];
if ([keyEquivalent length] > 0) {
item.keyEquivalentModifierMask =
KeyEquivalentModifierMaskForModifiers(representation[kShortcutModifiersKey]);
}
if (identifier) {
item.tag = identifier.longLongValue;
item.target = self;
}
NSNumber* enabled = representation[kEnabledKey];
if (enabled) {
item.enabled = enabled.boolValue;
}
NSArray* children = representation[kChildrenKey];
if (children && children.count > 0) {
NSMenu* submenu = [[NSMenu alloc] initWithTitle:title];
FlutterMenuDelegate* delegate = [[FlutterMenuDelegate alloc] initWithIdentifier:item.tag
channel:_channel];
[_menuDelegates addObject:delegate];
submenu.delegate = delegate;
submenu.autoenablesItems = NO;
for (NSDictionary* child in children) {
NSMenuItem* newItem = [self menuItemFromFlutterRepresentation:child];
if (newItem) {
[submenu addItem:newItem];
}
}
item.submenu = submenu;
}
return item;
}
- (void)flutterMenuItemSelected:(id)sender {
NSMenuItem* item = sender;
[_channel invokeMethod:kMenuItemSelectedCallbackMethod arguments:@(item.tag)];
}
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
if ([call.method isEqualToString:kMenuSetMethod]) {
NSDictionary* menus = call.arguments;
[self setMenu:menus];
result(nil);
} else {
result(FlutterMethodNotImplemented);
}
}
- (void)setMenu:(NSDictionary*)representation {
[_menuDelegates removeAllObjects];
NSMenu* newMenu = [[NSMenu alloc] init];
// There's currently only one window, named "0", but there could be other
// eventually, with different menu configurations.
for (NSDictionary* item in representation[@"0"]) {
NSMenuItem* menuItem = [self menuItemFromFlutterRepresentation:item];
menuItem.representedObject = self;
NSNumber* identifier = item[kIdKey];
FlutterMenuDelegate* delegate =
[[FlutterMenuDelegate alloc] initWithIdentifier:identifier.longLongValue channel:_channel];
[_menuDelegates addObject:delegate];
[menuItem submenu].delegate = delegate;
[newMenu addItem:menuItem];
}
NSApp.mainMenu = newMenu;
}
#pragma mark - Public Class Methods
+ (void)registerWithRegistrar:(nonnull id<FlutterPluginRegistrar>)registrar {
FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:kChannelName
binaryMessenger:registrar.messenger];
FlutterMenuPlugin* instance = [[FlutterMenuPlugin alloc] initWithChannel:channel];
[registrar addMethodCallDelegate:instance channel:channel];
}
@end

View File

@@ -0,0 +1,172 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginRegistrarMacOS.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h"
#include "flutter/shell/platform/common/platform_provided_menu.h"
#include "gtest/gtest.h"
#import <OCMock/OCMock.h>
#import "flutter/testing/testing.h"
@interface FlutterMenuPluginTestObjc : NSObject
- (bool)testSetMenu;
@end
@implementation FlutterMenuPluginTestObjc
- (bool)testSetMenu {
// Build a simulation of the default main menu.
NSMenu* mainMenu = [[NSMenu alloc] init];
NSMenuItem* appNameMenu = [[NSMenuItem alloc] initWithTitle:@"APP_NAME"
action:nil
keyEquivalent:@""];
NSMenu* submenu = [[NSMenu alloc] initWithTitle:@"Prexisting APP_NAME menu"];
[submenu addItem:[[NSMenuItem alloc] initWithTitle:@"About APP_NAME"
action:nil
keyEquivalent:@""]];
appNameMenu.submenu = submenu;
[mainMenu addItem:appNameMenu];
[NSApp setMainMenu:mainMenu];
id<FlutterPluginRegistrar> pluginRegistrarMock =
OCMProtocolMock(@protocol(FlutterPluginRegistrar));
__block FlutterMethodChannel* pluginChannel;
__block FlutterMenuPlugin* plugin;
id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub([pluginRegistrarMock messenger]).andReturn(binaryMessengerMock);
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[pluginRegistrarMock addMethodCallDelegate:[OCMArg any] channel:[OCMArg any]])
.andDo(^(NSInvocation* invocation) {
id<FlutterPlugin> delegate;
FlutterMethodChannel* channel;
[invocation getArgument:&delegate atIndex:2];
[invocation getArgument:&channel atIndex:3];
pluginChannel = channel;
plugin = delegate;
[channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
[delegate handleMethodCall:call result:result];
}];
});
[FlutterMenuPlugin registerWithRegistrar:pluginRegistrarMock];
NSDictionary* testMenus = @{
@"0" : @[
@{
@"id" : [NSNumber numberWithInt:1],
@"label" : @"APP_NAME",
@"enabled" : @(YES),
@"children" : @[
@{
@"id" : [NSNumber numberWithInt:3],
@"platformProvidedMenu" : @(static_cast<int>(flutter::PlatformProvidedMenu::kQuit)),
@"enabled" : @(YES),
},
@{
@"id" : [NSNumber numberWithInt:2],
@"label" : @"APP_NAME Info",
@"enabled" : @(YES),
@"shortcutTrigger" : [NSNumber numberWithUnsignedLongLong:0x61],
@"shortcutModifiers" : [NSNumber numberWithUnsignedInt:0],
},
],
},
@{
@"id" : [NSNumber numberWithInt:4],
@"label" : @"Help for APP_NAME",
@"enabled" : @(YES),
@"children" : @[
@{
@"id" : [NSNumber numberWithInt:5],
@"label" : @"Help me!",
@"enabled" : @(YES),
},
@{
@"id" : [NSNumber numberWithInt:6],
@"label" : @"",
@"enabled" : @(NO),
@"isDivider" : @(YES),
},
@{
@"id" : [NSNumber numberWithInt:7],
@"label" : @"Search help",
@"enabled" : @(NO),
},
],
},
],
};
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"Menu.setMenu"
arguments:testMenus]
result:^(id _Nullable result){
}];
EXPECT_EQ([NSApp.mainMenu numberOfItems], 2);
NSMenuItem* firstMenu = [NSApp.mainMenu itemAtIndex:0];
EXPECT_TRUE([[firstMenu title] isEqualToString:@"flutter_desktop_darwin_unittests"]);
EXPECT_EQ([firstMenu tag], 1);
EXPECT_TRUE([firstMenu isEnabled]);
EXPECT_FALSE([firstMenu isHidden]);
EXPECT_TRUE([[firstMenu keyEquivalent] isEqualToString:@"\0"]);
EXPECT_EQ([[firstMenu submenu] numberOfItems], 1);
NSMenuItem* firstItem = [[firstMenu submenu] itemAtIndex:0];
EXPECT_TRUE([[firstItem title] isEqualToString:@"flutter_desktop_darwin_unittests Info"]);
EXPECT_TRUE([[firstItem keyEquivalent] isEqualToString:@"a"]);
EXPECT_TRUE([firstItem isEnabled]);
EXPECT_FALSE([firstItem isHidden]);
EXPECT_TRUE(
[NSStringFromSelector([firstItem action]) isEqualToString:@"flutterMenuItemSelected:"]);
EXPECT_EQ([firstItem tag], 2);
NSMenuItem* secondMenu = [NSApp.mainMenu itemAtIndex:1];
EXPECT_TRUE([[secondMenu title] isEqualToString:@"Help for flutter_desktop_darwin_unittests"]);
EXPECT_EQ([secondMenu tag], 4);
EXPECT_TRUE([secondMenu isEnabled]);
EXPECT_FALSE([secondMenu isHidden]);
EXPECT_EQ([[secondMenu submenu] numberOfItems], 3);
NSMenuItem* secondMenuFirst = [[secondMenu submenu] itemAtIndex:0];
EXPECT_TRUE([[secondMenuFirst title] isEqualToString:@"Help me!"]);
EXPECT_TRUE([secondMenuFirst isEnabled]);
EXPECT_FALSE([secondMenuFirst isHidden]);
EXPECT_TRUE(
[NSStringFromSelector([secondMenuFirst action]) isEqualToString:@"flutterMenuItemSelected:"]);
EXPECT_EQ([secondMenuFirst tag], 5);
NSMenuItem* secondMenuDivider = [[secondMenu submenu] itemAtIndex:1];
EXPECT_TRUE([[secondMenuDivider title] isEqualToString:@""]);
EXPECT_TRUE([[secondMenuDivider keyEquivalent] isEqualToString:@""]);
EXPECT_FALSE([secondMenuDivider isEnabled]);
EXPECT_FALSE([secondMenuDivider isHidden]);
EXPECT_EQ([secondMenuDivider action], nil);
EXPECT_EQ([secondMenuDivider tag], 0);
NSMenuItem* secondMenuLast = [[secondMenu submenu] itemAtIndex:2];
EXPECT_TRUE([[secondMenuLast title] isEqualToString:@"Search help"]);
EXPECT_FALSE([secondMenuLast isEnabled]);
EXPECT_FALSE([secondMenuLast isHidden]);
EXPECT_TRUE(
[NSStringFromSelector([secondMenuLast action]) isEqualToString:@"flutterMenuItemSelected:"]);
EXPECT_EQ([secondMenuLast tag], 7);
return true;
}
@end
namespace flutter::testing {
TEST(FlutterMenuPluginTest, TestSetMenu) {
ASSERT_TRUE([[FlutterMenuPluginTestObjc alloc] testSetMenu]);
}
} // namespace flutter::testing

View File

@@ -0,0 +1,15 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h"
/**
* Internal methods used in testing.
*/
@interface FlutterMenuPlugin ()
// Handles method calls received from the framework.
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result;
@end

View File

@@ -12,6 +12,7 @@
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalRenderer.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRenderer.h"
@@ -452,6 +453,7 @@ static void CommonInit(FlutterViewController* controller) {
- (void)addInternalPlugins {
__weak FlutterViewController* weakSelf = self;
[FlutterMouseCursorPlugin registerWithRegistrar:[self registrarForPlugin:@"mousecursor"]];
[FlutterMenuPlugin registerWithRegistrar:[self registrarForPlugin:@"menu"]];
[self initializeKeyboard];
_settingsChannel =
[FlutterBasicMessageChannel messageChannelWithName:@"flutter/settings"