diff options
Diffstat (limited to 'platform/macos/display_server_macos.mm')
-rw-r--r-- | platform/macos/display_server_macos.mm | 638 |
1 files changed, 445 insertions, 193 deletions
diff --git a/platform/macos/display_server_macos.mm b/platform/macos/display_server_macos.mm index 56cb4938ec..0d4a5e784d 100644 --- a/platform/macos/display_server_macos.mm +++ b/platform/macos/display_server_macos.mm @@ -75,7 +75,7 @@ const NSMenu *DisplayServerMacOS::_get_menu_root(const String &p_menu_root) cons } else { // Submenu. if (submenu.has(p_menu_root)) { - menu = submenu[p_menu_root]; + menu = submenu[p_menu_root].menu; } } if (menu == apple_menu) { @@ -99,9 +99,10 @@ NSMenu *DisplayServerMacOS::_get_menu_root(const String &p_menu_root) { NSMenu *n_menu = [[NSMenu alloc] initWithTitle:[NSString stringWithUTF8String:p_menu_root.utf8().get_data()]]; [n_menu setAutoenablesItems:NO]; [n_menu setDelegate:menu_delegate]; - submenu[p_menu_root] = n_menu; + submenu[p_menu_root].menu = n_menu; + submenu_inv[n_menu] = p_menu_root; } - menu = submenu[p_menu_root]; + menu = submenu[p_menu_root].menu; } if (menu == apple_menu) { // Do not allow to change Apple menu. @@ -117,7 +118,7 @@ DisplayServerMacOS::WindowID DisplayServerMacOS::_create_window(WindowMode p_mod WindowData wd; wd.window_delegate = [[GodotWindowDelegate alloc] init]; - ERR_FAIL_COND_V_MSG(wd.window_delegate == nil, INVALID_WINDOW_ID, "Can't create a window delegate"); + ERR_FAIL_NULL_V_MSG(wd.window_delegate, INVALID_WINDOW_ID, "Can't create a window delegate"); [wd.window_delegate setWindowID:window_id_counter]; int rq_screen = get_screen_from_rect(p_rect); @@ -143,11 +144,11 @@ DisplayServerMacOS::WindowID DisplayServerMacOS::_create_window(WindowMode p_mod styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; - ERR_FAIL_COND_V_MSG(wd.window_object == nil, INVALID_WINDOW_ID, "Can't create a window"); + ERR_FAIL_NULL_V_MSG(wd.window_object, INVALID_WINDOW_ID, "Can't create a window"); [wd.window_object setWindowID:window_id_counter]; wd.window_view = [[GodotContentView alloc] init]; - ERR_FAIL_COND_V_MSG(wd.window_view == nil, INVALID_WINDOW_ID, "Can't create a window view"); + ERR_FAIL_NULL_V_MSG(wd.window_view, INVALID_WINDOW_ID, "Can't create a window view"); [wd.window_view setWindowID:window_id_counter]; [wd.window_view setWantsLayer:TRUE]; @@ -190,7 +191,8 @@ DisplayServerMacOS::WindowID DisplayServerMacOS::_create_window(WindowMode p_mod ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create an OpenGL context."); } if (gl_manager_angle) { - Error err = gl_manager_angle->window_create(window_id_counter, nullptr, (__bridge void *)[wd.window_view layer], p_rect.size.width, p_rect.size.height); + CALayer *layer = [(NSView *)wd.window_view layer]; + Error err = gl_manager_angle->window_create(window_id_counter, nullptr, (__bridge void *)layer, p_rect.size.width, p_rect.size.height); ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create an OpenGL context."); } window_set_vsync_mode(p_vsync_mode, window_id_counter); @@ -401,11 +403,6 @@ void DisplayServerMacOS::_dispatch_input_event(const Ref<InputEvent> &p_event) { if (!in_dispatch_input_event) { in_dispatch_input_event = true; - Variant ev = p_event; - Variant *evp = &ev; - Variant ret; - Callable::CallError ce; - { List<WindowID>::Element *E = popup_list.back(); if (E && Object::cast_to<InputEventKey>(*p_event)) { @@ -413,7 +410,7 @@ void DisplayServerMacOS::_dispatch_input_event(const Ref<InputEvent> &p_event) { if (windows.has(E->get())) { Callable callable = windows[E->get()].input_event_callback; if (callable.is_valid()) { - callable.callp((const Variant **)&evp, 1, ret, ce); + callable.call(p_event); } } in_dispatch_input_event = false; @@ -427,7 +424,7 @@ void DisplayServerMacOS::_dispatch_input_event(const Ref<InputEvent> &p_event) { if (windows.has(event_from_window->get_window_id())) { Callable callable = windows[event_from_window->get_window_id()].input_event_callback; if (callable.is_valid()) { - callable.callp((const Variant **)&evp, 1, ret, ce); + callable.call(p_event); } } } else { @@ -435,7 +432,7 @@ void DisplayServerMacOS::_dispatch_input_event(const Ref<InputEvent> &p_event) { for (KeyValue<WindowID, WindowData> &E : windows) { Callable callable = E.value.input_event_callback; if (callable.is_valid()) { - callable.callp((const Variant **)&evp, 1, ret, ce); + callable.call(p_event); } } } @@ -570,7 +567,7 @@ NSImage *DisplayServerMacOS::_convert_to_nsimg(Ref<Image> &p_image) const { colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:int(p_image->get_width()) * 4 bitsPerPixel:32]; - ERR_FAIL_COND_V(imgrep == nil, nil); + ERR_FAIL_NULL_V(imgrep, nil); uint8_t *pixels = [imgrep bitmapData]; int len = p_image->get_width() * p_image->get_height(); @@ -586,7 +583,7 @@ NSImage *DisplayServerMacOS::_convert_to_nsimg(Ref<Image> &p_image) const { } NSImage *nsimg = [[NSImage alloc] initWithSize:NSMakeSize(p_image->get_width(), p_image->get_height())]; - ERR_FAIL_COND_V(nsimg == nil, nil); + ERR_FAIL_NULL_V(nsimg, nil); [nsimg addRepresentation:imgrep]; return nsimg; } @@ -609,6 +606,26 @@ NSMenu *DisplayServerMacOS::get_dock_menu() const { return dock_menu; } +void DisplayServerMacOS::menu_open(NSMenu *p_menu) { + if (submenu_inv.has(p_menu)) { + MenuData &md = submenu[submenu_inv[p_menu]]; + md.is_open = true; + if (md.open.is_valid()) { + md.open.call(); + } + } +} + +void DisplayServerMacOS::menu_close(NSMenu *p_menu) { + if (submenu_inv.has(p_menu)) { + MenuData &md = submenu[submenu_inv[p_menu]]; + md.is_open = false; + if (md.close.is_valid()) { + md.close.call(); + } + } +} + void DisplayServerMacOS::menu_callback(id p_sender) { if (![p_sender representedObject]) { return; @@ -632,7 +649,7 @@ void DisplayServerMacOS::menu_callback(id p_sender) { } } - if (value->callback != Callable()) { + if (value->callback.is_valid()) { MenuCall mc; mc.tag = value->meta; mc.callback = value->callback; @@ -674,12 +691,9 @@ void DisplayServerMacOS::send_event(NSEvent *p_event) { void DisplayServerMacOS::send_window_event(const WindowData &wd, WindowEvent p_event) { _THREAD_SAFE_METHOD_ - if (!wd.event_callback.is_null()) { + if (wd.event_callback.is_valid()) { Variant event = int(p_event); - Variant *eventp = &event; - Variant ret; - Callable::CallError ce; - wd.event_callback.callp((const Variant **)&eventp, 1, ret, ce); + wd.event_callback.call(event); } } @@ -749,6 +763,7 @@ void DisplayServerMacOS::window_destroy(WindowID p_window) { } #endif windows.erase(p_window); + update_presentation_mode(); } void DisplayServerMacOS::window_resize(WindowID p_window, int p_width, int p_height) { @@ -815,6 +830,24 @@ bool DisplayServerMacOS::_has_help_menu() const { } } +bool DisplayServerMacOS::_is_menu_opened(NSMenu *p_menu) const { + if (submenu_inv.has(p_menu)) { + const MenuData &md = submenu[submenu_inv[p_menu]]; + if (md.is_open) { + return true; + } + } + for (NSInteger i = (p_menu == [NSApp mainMenu]) ? 1 : 0; i < [p_menu numberOfItems]; i++) { + const NSMenuItem *menu_item = [p_menu itemAtIndex:i]; + if ([menu_item submenu]) { + if (_is_menu_opened([menu_item submenu])) { + return true; + } + } + } + return false; +} + NSMenuItem *DisplayServerMacOS::_menu_add_item(const String &p_menu_root, const String &p_label, Key p_accel, int p_index, int *r_out) { NSMenu *menu = _get_menu_root(p_menu_root); if (menu) { @@ -998,6 +1031,23 @@ int DisplayServerMacOS::global_menu_add_multistate_item(const String &p_menu_roo return out; } +void DisplayServerMacOS::global_menu_set_popup_callbacks(const String &p_menu_root, const Callable &p_open_callback, const Callable &p_close_callback) { + _THREAD_SAFE_METHOD_ + + if (p_menu_root != "" && p_menu_root.to_lower() != "_main" && p_menu_root.to_lower() != "_dock") { + // Submenu. + if (!submenu.has(p_menu_root)) { + NSMenu *n_menu = [[NSMenu alloc] initWithTitle:[NSString stringWithUTF8String:p_menu_root.utf8().get_data()]]; + [n_menu setAutoenablesItems:NO]; + [n_menu setDelegate:menu_delegate]; + submenu[p_menu_root].menu = n_menu; + submenu_inv[n_menu] = p_menu_root; + } + submenu[p_menu_root].open = p_open_callback; + submenu[p_menu_root].close = p_close_callback; + } +} + int DisplayServerMacOS::global_menu_add_submenu_item(const String &p_menu_root, const String &p_label, const String &p_submenu, int p_index) { _THREAD_SAFE_METHOD_ @@ -1251,13 +1301,9 @@ String DisplayServerMacOS::global_menu_get_item_submenu(const String &p_menu_roo ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], String()); const NSMenuItem *menu_item = [menu itemAtIndex:p_idx]; if (menu_item) { - const NSMenu *sub_menu = [menu_item submenu]; - if (sub_menu) { - for (const KeyValue<String, NSMenu *> &E : submenu) { - if (E.value == sub_menu) { - return E.key; - } - } + NSMenu *sub_menu = [menu_item submenu]; + if (sub_menu && submenu_inv.has(sub_menu)) { + return submenu_inv[sub_menu]; } } } @@ -1318,6 +1364,24 @@ bool DisplayServerMacOS::global_menu_is_item_disabled(const String &p_menu_root, return false; } +bool DisplayServerMacOS::global_menu_is_item_hidden(const String &p_menu_root, int p_idx) const { + _THREAD_SAFE_METHOD_ + + const NSMenu *menu = _get_menu_root(p_menu_root); + if (menu) { + ERR_FAIL_COND_V(p_idx < 0, false); + if (menu == [NSApp mainMenu]) { // Skip Apple menu. + p_idx++; + } + ERR_FAIL_COND_V(p_idx >= [menu numberOfItems], false); + const NSMenuItem *menu_item = [menu itemAtIndex:p_idx]; + if (menu_item) { + return [menu_item isHidden]; + } + } + return false; +} + String DisplayServerMacOS::global_menu_get_item_tooltip(const String &p_menu_root, int p_idx) const { _THREAD_SAFE_METHOD_ @@ -1497,6 +1561,25 @@ void DisplayServerMacOS::global_menu_set_item_callback(const String &p_menu_root } } +void DisplayServerMacOS::global_menu_set_item_hover_callbacks(const String &p_menu_root, int p_idx, const Callable &p_callback) { + _THREAD_SAFE_METHOD_ + + NSMenu *menu = _get_menu_root(p_menu_root); + if (menu) { + ERR_FAIL_COND(p_idx < 0); + if (menu == [NSApp mainMenu]) { // Skip Apple menu. + p_idx++; + } + ERR_FAIL_COND(p_idx >= [menu numberOfItems]); + NSMenuItem *menu_item = [menu itemAtIndex:p_idx]; + if (menu_item) { + GodotMenuItem *obj = [menu_item representedObject]; + ERR_FAIL_NULL(obj); + obj->hover_callback = p_callback; + } + } +} + void DisplayServerMacOS::global_menu_set_item_key_callback(const String &p_menu_root, int p_idx, const Callable &p_key_callback) { _THREAD_SAFE_METHOD_ @@ -1556,6 +1639,23 @@ void DisplayServerMacOS::global_menu_set_item_submenu(const String &p_menu_root, _THREAD_SAFE_METHOD_ NSMenu *menu = _get_menu_root(p_menu_root); + if (menu && p_submenu.is_empty()) { + ERR_FAIL_COND(p_idx < 0); + if (menu == [NSApp mainMenu]) { // Skip Apple menu. + p_idx++; + } + ERR_FAIL_COND(p_idx >= [menu numberOfItems]); + NSMenuItem *menu_item = [menu itemAtIndex:p_idx]; + if (menu_item) { + if ([menu_item submenu] && _is_menu_opened([menu_item submenu])) { + ERR_PRINT("Can't remove open menu!"); + return; + } + [menu setSubmenu:nil forItem:menu_item]; + } + return; + } + NSMenu *sub_menu = _get_menu_root(p_submenu); if (menu && sub_menu) { if (sub_menu == menu) { @@ -1590,9 +1690,13 @@ void DisplayServerMacOS::global_menu_set_item_accelerator(const String &p_menu_r ERR_FAIL_COND(p_idx >= [menu numberOfItems]); NSMenuItem *menu_item = [menu itemAtIndex:p_idx]; if (menu_item) { - [menu_item setKeyEquivalentModifierMask:KeyMappingMacOS::keycode_get_native_mask(p_keycode)]; - String keycode = KeyMappingMacOS::keycode_get_native_string(p_keycode & KeyModifierMask::CODE_MASK); - [menu_item setKeyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()]]; + if (p_keycode == Key::NONE) { + [menu_item setKeyEquivalent:@""]; + } else { + [menu_item setKeyEquivalentModifierMask:KeyMappingMacOS::keycode_get_native_mask(p_keycode)]; + String keycode = KeyMappingMacOS::keycode_get_native_string(p_keycode & KeyModifierMask::CODE_MASK); + [menu_item setKeyEquivalent:[NSString stringWithUTF8String:keycode.utf8().get_data()]]; + } } } } @@ -1614,6 +1718,23 @@ void DisplayServerMacOS::global_menu_set_item_disabled(const String &p_menu_root } } +void DisplayServerMacOS::global_menu_set_item_hidden(const String &p_menu_root, int p_idx, bool p_hidden) { + _THREAD_SAFE_METHOD_ + + NSMenu *menu = _get_menu_root(p_menu_root); + if (menu) { + ERR_FAIL_COND(p_idx < 0); + if (menu == [NSApp mainMenu]) { // Skip Apple menu. + p_idx++; + } + ERR_FAIL_COND(p_idx >= [menu numberOfItems]); + NSMenuItem *menu_item = [menu itemAtIndex:p_idx]; + if (menu_item) { + [menu_item setHidden:p_hidden]; + } + } +} + void DisplayServerMacOS::global_menu_set_item_tooltip(const String &p_menu_root, int p_idx, const String &p_tooltip) { _THREAD_SAFE_METHOD_ @@ -1741,6 +1862,11 @@ void DisplayServerMacOS::global_menu_remove_item(const String &p_menu_root, int p_idx++; } ERR_FAIL_COND(p_idx >= [menu numberOfItems]); + NSMenuItem *menu_item = [menu itemAtIndex:p_idx]; + if ([menu_item submenu] && _is_menu_opened([menu_item submenu])) { + ERR_PRINT("Can't remove open menu!"); + return; + } [menu removeItemAtIndex:p_idx]; } } @@ -1750,6 +1876,10 @@ void DisplayServerMacOS::global_menu_clear(const String &p_menu_root) { NSMenu *menu = _get_menu_root(p_menu_root); if (menu) { + if (_is_menu_opened(menu)) { + ERR_PRINT("Can't remove open menu!"); + return; + } [menu removeAllItems]; // Restore Apple menu. if (menu == [NSApp mainMenu]) { @@ -1757,6 +1887,7 @@ void DisplayServerMacOS::global_menu_clear(const String &p_menu_root) { [menu setSubmenu:apple_menu forItem:menu_item]; } if (submenu.has(p_menu_root)) { + submenu_inv.erase(submenu[p_menu_root].menu); submenu.erase(p_menu_root); } } @@ -1860,181 +1991,257 @@ Error DisplayServerMacOS::dialog_show(String p_title, String p_description, Vect } if (!p_callback.is_null()) { - Variant button = button_pressed; - Variant *buttonp = &button; - Variant fun_ret; - Callable::CallError ce; - p_callback.callp((const Variant **)&buttonp, 1, fun_ret, ce); + p_callback.call(button_pressed); } return OK; } -Error DisplayServerMacOS::file_dialog_show(const String &p_title, const String &p_current_directory, const String &p_filename, bool p_show_hidden, FileDialogMode p_mode, const Vector<String> &p_filters, const Callable &p_callback) { - _THREAD_SAFE_METHOD_ +@interface FileDialogDropdown : NSObject { + NSSavePanel *dialog; + NSMutableArray *allowed_types; + int cur_index; +} + +- (instancetype)initWithDialog:(NSSavePanel *)p_dialog fileTypes:(NSMutableArray *)p_allowed_types; +- (void)popupAction:(id)sender; +- (int)getIndex; + +@end + +@implementation FileDialogDropdown + +- (int)getIndex { + return cur_index; +} + +- (instancetype)initWithDialog:(NSSavePanel *)p_dialog fileTypes:(NSMutableArray *)p_allowed_types { + if ((self = [super init])) { + dialog = p_dialog; + allowed_types = p_allowed_types; + cur_index = 0; + } + return self; +} + +- (void)popupAction:(id)sender { + NSUInteger index = [sender indexOfSelectedItem]; + if (index < [allowed_types count]) { + [dialog setAllowedFileTypes:[allowed_types objectAtIndex:index]]; + cur_index = index; + } else { + [dialog setAllowedFileTypes:@[]]; + cur_index = -1; + } +} + +@end + +FileDialogDropdown *_make_accessory_view(NSSavePanel *p_panel, const Vector<String> &p_filters) { + NSView *group = [[NSView alloc] initWithFrame:NSZeroRect]; + group.translatesAutoresizingMaskIntoConstraints = NO; + + NSTextField *label = [NSTextField labelWithString:[NSString stringWithUTF8String:RTR("Format").utf8().get_data()]]; + label.translatesAutoresizingMaskIntoConstraints = NO; + if (@available(macOS 10.14, *)) { + label.textColor = NSColor.secondaryLabelColor; + } + if (@available(macOS 11.10, *)) { + label.font = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]]; + } + [group addSubview:label]; + + NSPopUpButton *popup = [[NSPopUpButton alloc] initWithFrame:NSZeroRect pullsDown:NO]; + popup.translatesAutoresizingMaskIntoConstraints = NO; - NSString *url = [NSString stringWithUTF8String:p_current_directory.utf8().get_data()]; NSMutableArray *allowed_types = [[NSMutableArray alloc] init]; bool allow_other = false; for (int i = 0; i < p_filters.size(); i++) { Vector<String> tokens = p_filters[i].split(";"); - if (tokens.size() > 0) { - if (tokens[0].strip_edges() == "*.*") { - allow_other = true; - } else { - [allowed_types addObject:[NSString stringWithUTF8String:tokens[0].replace("*.", "").strip_edges().utf8().get_data()]]; + if (tokens.size() >= 1) { + String flt = tokens[0].strip_edges(); + int filter_slice_count = flt.get_slice_count(","); + + NSMutableArray *type_filters = [[NSMutableArray alloc] init]; + for (int j = 0; j < filter_slice_count; j++) { + String str = (flt.get_slice(",", j).strip_edges()); + if (str.strip_edges() == "*.*" || str.strip_edges() == "*") { + allow_other = true; + } else if (!str.is_empty()) { + [type_filters addObject:[NSString stringWithUTF8String:str.replace("*.", "").strip_edges().utf8().get_data()]]; + } + } + + if ([type_filters count] > 0) { + NSString *name_str = [NSString stringWithUTF8String:((tokens.size() == 1) ? tokens[0] : vformat("%s (%s)", tokens[1], tokens[0])).strip_edges().utf8().get_data()]; + [allowed_types addObject:type_filters]; + [popup addItemWithTitle:name_str]; } } } + FileDialogDropdown *handler = [[FileDialogDropdown alloc] initWithDialog:p_panel fileTypes:allowed_types]; + popup.target = handler; + popup.action = @selector(popupAction:); - Callable callback = p_callback; // Make a copy for async completion handler. - switch (p_mode) { - case FILE_DIALOG_MODE_SAVE_FILE: { - NSSavePanel *panel = [NSSavePanel savePanel]; + [group addSubview:popup]; - [panel setDirectoryURL:[NSURL fileURLWithPath:url]]; - if ([allowed_types count]) { - [panel setAllowedFileTypes:allowed_types]; - } - [panel setAllowsOtherFileTypes:allow_other]; - [panel setExtensionHidden:YES]; - [panel setCanSelectHiddenExtension:YES]; - [panel setCanCreateDirectories:YES]; - [panel setShowsHiddenFiles:p_show_hidden]; - if (p_filename != "") { - NSString *fileurl = [NSString stringWithUTF8String:p_filename.utf8().get_data()]; - [panel setNameFieldStringValue:fileurl]; - } + NSView *view = [[NSView alloc] initWithFrame:NSZeroRect]; + view.translatesAutoresizingMaskIntoConstraints = NO; + [view addSubview:group]; + + NSMutableArray *constraints = [NSMutableArray array]; + [constraints addObject:[popup.topAnchor constraintEqualToAnchor:group.topAnchor constant:10]]; + [constraints addObject:[label.leadingAnchor constraintEqualToAnchor:group.leadingAnchor constant:10]]; + [constraints addObject:[popup.leadingAnchor constraintEqualToAnchor:label.trailingAnchor constant:10]]; + [constraints addObject:[popup.firstBaselineAnchor constraintEqualToAnchor:label.firstBaselineAnchor]]; + [constraints addObject:[group.trailingAnchor constraintEqualToAnchor:popup.trailingAnchor constant:10]]; + [constraints addObject:[group.bottomAnchor constraintEqualToAnchor:popup.bottomAnchor constant:10]]; + [constraints addObject:[group.topAnchor constraintEqualToAnchor:view.topAnchor]]; + [constraints addObject:[group.centerXAnchor constraintEqualToAnchor:view.centerXAnchor]]; + [constraints addObject:[view.bottomAnchor constraintEqualToAnchor:group.bottomAnchor]]; + [NSLayoutConstraint activateConstraints:constraints]; + + [p_panel setAllowsOtherFileTypes:allow_other]; + if ([allowed_types count] > 0) { + [p_panel setAccessoryView:view]; + [p_panel setAllowedFileTypes:[allowed_types objectAtIndex:0]]; + } + + return handler; +} + +Error DisplayServerMacOS::file_dialog_show(const String &p_title, const String &p_current_directory, const String &p_filename, bool p_show_hidden, FileDialogMode p_mode, const Vector<String> &p_filters, const Callable &p_callback) { + _THREAD_SAFE_METHOD_ - [panel beginSheetModalForWindow:[[NSApplication sharedApplication] mainWindow] - completionHandler:^(NSInteger ret) { - if (ret == NSModalResponseOK) { - // Save bookmark for folder. - if (OS::get_singleton()->is_sandboxed()) { - NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"]; + ERR_FAIL_INDEX_V(int(p_mode), FILE_DIALOG_MODE_SAVE_MAX, FAILED); + + NSString *url = [NSString stringWithUTF8String:p_current_directory.utf8().get_data()]; + FileDialogDropdown *handler = nullptr; + + WindowID prev_focus = last_focused_window; + + Callable callback = p_callback; // Make a copy for async completion handler. + if (p_mode == FILE_DIALOG_MODE_SAVE_FILE) { + NSSavePanel *panel = [NSSavePanel savePanel]; + + [panel setDirectoryURL:[NSURL fileURLWithPath:url]]; + handler = _make_accessory_view(panel, p_filters); + [panel setExtensionHidden:YES]; + [panel setCanSelectHiddenExtension:YES]; + [panel setCanCreateDirectories:YES]; + [panel setShowsHiddenFiles:p_show_hidden]; + if (p_filename != "") { + NSString *fileurl = [NSString stringWithUTF8String:p_filename.utf8().get_data()]; + [panel setNameFieldStringValue:fileurl]; + } + + [panel beginSheetModalForWindow:[[NSApplication sharedApplication] mainWindow] + completionHandler:^(NSInteger ret) { + if (ret == NSModalResponseOK) { + // Save bookmark for folder. + if (OS::get_singleton()->is_sandboxed()) { + NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"]; + bool skip = false; + for (id bookmark in bookmarks) { + NSError *error = nil; + BOOL isStale = NO; + NSURL *exurl = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error]; + if (!error && !isStale && ([[exurl path] compare:[[panel directoryURL] path]] == NSOrderedSame)) { + skip = true; + break; + } + } + if (!skip) { + NSError *error = nil; + NSData *bookmark = [[panel directoryURL] bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error]; + if (!error) { + NSArray *new_bookmarks = [bookmarks arrayByAddingObject:bookmark]; + [[NSUserDefaults standardUserDefaults] setObject:new_bookmarks forKey:@"sec_bookmarks"]; + } + } + } + // Callback. + Vector<String> files; + String url; + url.parse_utf8([[[panel URL] path] UTF8String]); + files.push_back(url); + if (!callback.is_null()) { + callback.call(true, files, [handler getIndex]); + } + } else { + if (!callback.is_null()) { + callback.call(false, Vector<String>(), [handler getIndex]); + } + } + if (prev_focus != INVALID_WINDOW_ID) { + callable_mp(DisplayServer::get_singleton(), &DisplayServer::window_move_to_foreground).call_deferred(prev_focus); + } + }]; + } else { + NSOpenPanel *panel = [NSOpenPanel openPanel]; + + [panel setDirectoryURL:[NSURL fileURLWithPath:url]]; + handler = _make_accessory_view(panel, p_filters); + [panel setExtensionHidden:YES]; + [panel setCanSelectHiddenExtension:YES]; + [panel setCanCreateDirectories:YES]; + [panel setCanChooseFiles:(p_mode != FILE_DIALOG_MODE_OPEN_DIR)]; + [panel setCanChooseDirectories:(p_mode == FILE_DIALOG_MODE_OPEN_DIR || p_mode == FILE_DIALOG_MODE_OPEN_ANY)]; + [panel setShowsHiddenFiles:p_show_hidden]; + if (p_filename != "") { + NSString *fileurl = [NSString stringWithUTF8String:p_filename.utf8().get_data()]; + [panel setNameFieldStringValue:fileurl]; + } + [panel setAllowsMultipleSelection:(p_mode == FILE_DIALOG_MODE_OPEN_FILES)]; + + [panel beginSheetModalForWindow:[[NSApplication sharedApplication] mainWindow] + completionHandler:^(NSInteger ret) { + if (ret == NSModalResponseOK) { + // Save bookmark for folder. + NSArray *urls = [(NSOpenPanel *)panel URLs]; + if (OS::get_singleton()->is_sandboxed()) { + NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"]; + NSMutableArray *new_bookmarks = [bookmarks mutableCopy]; + for (NSUInteger i = 0; i != [urls count]; ++i) { bool skip = false; for (id bookmark in bookmarks) { NSError *error = nil; BOOL isStale = NO; NSURL *exurl = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error]; - if (!error && !isStale && ([[exurl path] compare:[[panel directoryURL] path]] == NSOrderedSame)) { + if (!error && !isStale && ([[exurl path] compare:[[urls objectAtIndex:i] path]] == NSOrderedSame)) { skip = true; break; } } if (!skip) { NSError *error = nil; - NSData *bookmark = [[panel directoryURL] bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error]; + NSData *bookmark = [[urls objectAtIndex:i] bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error]; if (!error) { - NSArray *new_bookmarks = [bookmarks arrayByAddingObject:bookmark]; - [[NSUserDefaults standardUserDefaults] setObject:new_bookmarks forKey:@"sec_bookmarks"]; + [new_bookmarks addObject:bookmark]; } } } - // Callback. - Vector<String> files; + [[NSUserDefaults standardUserDefaults] setObject:new_bookmarks forKey:@"sec_bookmarks"]; + } + // Callback. + Vector<String> files; + for (NSUInteger i = 0; i != [urls count]; ++i) { String url; - url.parse_utf8([[[panel URL] path] UTF8String]); + url.parse_utf8([[[urls objectAtIndex:i] path] UTF8String]); files.push_back(url); - if (!callback.is_null()) { - Variant v_status = true; - Variant v_files = files; - Variant *v_args[2] = { &v_status, &v_files }; - Variant ret; - Callable::CallError ce; - callback.callp((const Variant **)&v_args, 2, ret, ce); - } - } else { - if (!callback.is_null()) { - Variant v_status = false; - Variant v_files = Vector<String>(); - Variant *v_args[2] = { &v_status, &v_files }; - Variant ret; - Callable::CallError ce; - callback.callp((const Variant **)&v_args, 2, ret, ce); - } } - }]; - } break; - case FILE_DIALOG_MODE_OPEN_ANY: - case FILE_DIALOG_MODE_OPEN_FILE: - case FILE_DIALOG_MODE_OPEN_FILES: - case FILE_DIALOG_MODE_OPEN_DIR: { - NSOpenPanel *panel = [NSOpenPanel openPanel]; - - [panel setDirectoryURL:[NSURL fileURLWithPath:url]]; - if ([allowed_types count]) { - [panel setAllowedFileTypes:allowed_types]; - } - [panel setAllowsOtherFileTypes:allow_other]; - [panel setExtensionHidden:YES]; - [panel setCanSelectHiddenExtension:YES]; - [panel setCanCreateDirectories:YES]; - [panel setCanChooseFiles:(p_mode != FILE_DIALOG_MODE_OPEN_DIR)]; - [panel setCanChooseDirectories:(p_mode == FILE_DIALOG_MODE_OPEN_DIR || p_mode == FILE_DIALOG_MODE_OPEN_ANY)]; - [panel setShowsHiddenFiles:p_show_hidden]; - if (p_filename != "") { - NSString *fileurl = [NSString stringWithUTF8String:p_filename.utf8().get_data()]; - [panel setNameFieldStringValue:fileurl]; - } - [panel setAllowsMultipleSelection:(p_mode == FILE_DIALOG_MODE_OPEN_FILES)]; - - [panel beginSheetModalForWindow:[[NSApplication sharedApplication] mainWindow] - completionHandler:^(NSInteger ret) { - if (ret == NSModalResponseOK) { - // Save bookmark for folder. - NSArray *urls = [(NSOpenPanel *)panel URLs]; - if (OS::get_singleton()->is_sandboxed()) { - NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"]; - NSMutableArray *new_bookmarks = [bookmarks mutableCopy]; - for (NSUInteger i = 0; i != [urls count]; ++i) { - bool skip = false; - for (id bookmark in bookmarks) { - NSError *error = nil; - BOOL isStale = NO; - NSURL *exurl = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error]; - if (!error && !isStale && ([[exurl path] compare:[[urls objectAtIndex:i] path]] == NSOrderedSame)) { - skip = true; - break; - } - } - if (!skip) { - NSError *error = nil; - NSData *bookmark = [[urls objectAtIndex:i] bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error]; - if (!error) { - [new_bookmarks addObject:bookmark]; - } - } - } - [[NSUserDefaults standardUserDefaults] setObject:new_bookmarks forKey:@"sec_bookmarks"]; - } - // Callback. - Vector<String> files; - for (NSUInteger i = 0; i != [urls count]; ++i) { - String url; - url.parse_utf8([[[urls objectAtIndex:i] path] UTF8String]); - files.push_back(url); - } - if (!callback.is_null()) { - Variant v_status = true; - Variant v_files = files; - Variant *v_args[2] = { &v_status, &v_files }; - Variant ret; - Callable::CallError ce; - callback.callp((const Variant **)&v_args, 2, ret, ce); - } - } else { - if (!callback.is_null()) { - Variant v_status = false; - Variant v_files = Vector<String>(); - Variant *v_args[2] = { &v_status, &v_files }; - Variant ret; - Callable::CallError ce; - callback.callp((const Variant **)&v_args, 2, ret, ce); - } + if (!callback.is_null()) { + callback.call(true, files, [handler getIndex]); } - }]; - } break; + } else { + if (!callback.is_null()) { + callback.call(false, Vector<String>(), [handler getIndex]); + } + } + if (prev_focus != INVALID_WINDOW_ID) { + callable_mp(DisplayServer::get_singleton(), &DisplayServer::window_move_to_foreground).call_deferred(prev_focus); + } + }]; } return OK; @@ -2062,11 +2269,7 @@ Error DisplayServerMacOS::dialog_input_text(String p_title, String p_description ret.parse_utf8([[input stringValue] UTF8String]); if (!p_callback.is_null()) { - Variant text = ret; - Variant *textp = &text; - Variant fun_ret; - Callable::CallError ce; - p_callback.callp((const Variant **)&textp, 1, fun_ret, ce); + p_callback.call(ret); } return OK; @@ -2626,6 +2829,47 @@ void DisplayServerMacOS::window_set_title(const String &p_title, WindowID p_wind [wd.window_object setTitle:[NSString stringWithUTF8String:p_title.utf8().get_data()]]; } +Size2i DisplayServerMacOS::window_get_title_size(const String &p_title, WindowID p_window) const { + _THREAD_SAFE_METHOD_ + + Size2i size; + ERR_FAIL_COND_V(!windows.has(p_window), size); + + const WindowData &wd = windows[p_window]; + if (wd.fullscreen || wd.borderless) { + return size; + } + if ([wd.window_object respondsToSelector:@selector(isMiniaturized)]) { + if ([wd.window_object isMiniaturized]) { + return size; + } + } + + float scale = screen_get_max_scale(); + + if (wd.window_button_view) { + size.x = ([wd.window_button_view getOffset].x + [wd.window_button_view frame].size.width); + size.y = ([wd.window_button_view getOffset].y + [wd.window_button_view frame].size.height); + } else { + NSButton *cb = [wd.window_object standardWindowButton:NSWindowCloseButton]; + NSButton *mb = [wd.window_object standardWindowButton:NSWindowMiniaturizeButton]; + float cb_frame = NSMinX([cb frame]); + float mb_frame = NSMinX([mb frame]); + bool is_rtl = ([wd.window_object windowTitlebarLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft); + + float window_buttons_spacing = (is_rtl) ? (cb_frame - mb_frame) : (mb_frame - cb_frame); + size.x = window_buttons_spacing * 4; + size.y = [cb frame].origin.y + [cb frame].size.height; + } + + NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont titleBarFontOfSize:0], NSFontAttributeName, nil]; + NSSize text_size = [[[NSAttributedString alloc] initWithString:[NSString stringWithUTF8String:p_title.utf8().get_data()] attributes:attributes] size]; + size.x += text_size.width; + size.y = MAX(size.y, text_size.height); + + return size * scale; +} + void DisplayServerMacOS::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) { _THREAD_SAFE_METHOD_ @@ -2868,6 +3112,15 @@ Size2i DisplayServerMacOS::window_get_max_size(WindowID p_window) const { return wd.max_size; } +void DisplayServerMacOS::update_presentation_mode() { + for (const KeyValue<WindowID, WindowData> &wd : windows) { + if (wd.value.fullscreen && wd.value.exclusive_fullscreen) { + return; + } + } + [NSApp setPresentationOptions:NSApplicationPresentationDefault]; +} + void DisplayServerMacOS::window_set_min_size(const Size2i p_size, WindowID p_window) { _THREAD_SAFE_METHOD_ @@ -2978,7 +3231,7 @@ void DisplayServerMacOS::window_set_mode(WindowMode p_mode, WindowID p_window) { [wd.window_object toggleFullScreen:nil]; if (old_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) { - [NSApp setPresentationOptions:NSApplicationPresentationDefault]; + update_presentation_mode(); } wd.fullscreen = false; @@ -3176,7 +3429,9 @@ void DisplayServerMacOS::window_set_flag(WindowFlags p_flag, bool p_enabled, Win } break; case WINDOW_FLAG_BORDERLESS: { // OrderOut prevents a lose focus bug with the window. + bool was_visible = false; if ([wd.window_object isVisible]) { + was_visible = true; [wd.window_object orderOut:nil]; } wd.borderless = p_enabled; @@ -3191,7 +3446,7 @@ void DisplayServerMacOS::window_set_flag(WindowFlags p_flag, bool p_enabled, Win [wd.window_object setFrame:frameRect display:NO]; } _update_window_style(wd); - if ([wd.window_object isVisible]) { + if (was_visible || [wd.window_object isVisible]) { if ([wd.window_object isMiniaturized]) { return; } else if (wd.no_focus) { @@ -3307,14 +3562,14 @@ bool DisplayServerMacOS::window_is_focused(WindowID p_window) const { } bool DisplayServerMacOS::window_can_draw(WindowID p_window) const { - return (window_get_mode(p_window) != WINDOW_MODE_MINIMIZED) && [windows[p_window].window_object isOnActiveSpace]; + return windows[p_window].is_visible; } bool DisplayServerMacOS::can_any_window_draw() const { _THREAD_SAFE_METHOD_ for (const KeyValue<WindowID, WindowData> &E : windows) { - if ((window_get_mode(E.key) != WINDOW_MODE_MINIMIZED) && [E.value.window_object isOnActiveSpace]) { + if (E.value.is_visible) { return true; } } @@ -3603,7 +3858,7 @@ void DisplayServerMacOS::cursor_set_custom_image(const Ref<Resource> &p_cursor, bytesPerRow:int(texture_size.width) * 4 bitsPerPixel:32]; - ERR_FAIL_COND(imgrep == nil); + ERR_FAIL_NULL(imgrep); uint8_t *pixels = [imgrep bitmapData]; int len = int(texture_size.width * texture_size.height); @@ -3765,12 +4020,7 @@ void DisplayServerMacOS::process_events() { while (List<MenuCall>::Element *call_p = deferred_menu_calls.front()) { MenuCall call = call_p->get(); deferred_menu_calls.pop_front(); // Remove before call to avoid infinite loop in case callback is using `process_events` (e.g. EditorProgress). - - Variant tag = call.tag; - Variant *tagp = &tag; - Variant ret; - Callable::CallError ce; - call.callback.callp((const Variant **)&tagp, 1, ret, ce); + call.callback.call(call.tag); } if (!drop_events) { @@ -3874,7 +4124,7 @@ void DisplayServerMacOS::set_icon(const Ref<Image> &p_icon) { colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:img->get_width() * 4 bitsPerPixel:32]; - ERR_FAIL_COND(imgrep == nil); + ERR_FAIL_NULL(imgrep); uint8_t *pixels = [imgrep bitmapData]; int len = img->get_width() * img->get_height(); @@ -3890,7 +4140,7 @@ void DisplayServerMacOS::set_icon(const Ref<Image> &p_icon) { } NSImage *nsimg = [[NSImage alloc] initWithSize:NSMakeSize(img->get_width(), img->get_height())]; - ERR_FAIL_COND(nsimg == nil); + ERR_FAIL_NULL(nsimg); [nsimg addRepresentation:imgrep]; [NSApp setApplicationIconImage:nsimg]; @@ -4127,15 +4377,19 @@ DisplayServerMacOS::DisplayServerMacOS(const String &p_rendering_driver, WindowM nsappname = [[NSProcessInfo processInfo] processName]; } + menu_delegate = [[GodotMenuDelegate alloc] init]; + // Setup Dock menu. dock_menu = [[NSMenu alloc] initWithTitle:@"_dock"]; [dock_menu setAutoenablesItems:NO]; + [dock_menu setDelegate:menu_delegate]; // Setup Apple menu. apple_menu = [[NSMenu alloc] initWithTitle:@""]; title = [NSString stringWithFormat:NSLocalizedString(@"About %@", nil), nsappname]; [apple_menu addItemWithTitle:title action:@selector(showAbout:) keyEquivalent:@""]; [apple_menu setAutoenablesItems:NO]; + [apple_menu setDelegate:menu_delegate]; [apple_menu addItem:[NSMenuItem separatorItem]]; @@ -4165,8 +4419,6 @@ DisplayServerMacOS::DisplayServerMacOS(const String &p_rendering_driver, WindowM [main_menu setSubmenu:apple_menu forItem:menu_item]; [main_menu setAutoenablesItems:NO]; - menu_delegate = [[GodotMenuDelegate alloc] init]; - //!!!!!!!!!!!!!!!!!!!!!!!!!! //TODO - do Vulkan and OpenGL support checks, driver selection and fallback rendering_driver = p_rendering_driver; |