2014-02-10 02:10:30 +01:00
/*************************************************************************/
/* os_osx.mm */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
2017-08-27 14:16:55 +02:00
/* https://godotengine.org */
2014-02-10 02:10:30 +01:00
/*************************************************************************/
2020-01-01 11:16:22 +01:00
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
2014-02-10 02:10:30 +01:00
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
2018-01-05 00:50:27 +01:00
2017-04-09 14:18:49 +02:00
#include "os_osx.h"
2020-06-29 11:31:13 +02:00
#include "core/math/geometry.h"
2018-09-11 18:13:45 +02:00
#include "core/os/keyboard.h"
#include "core/print_string.h"
#include "core/version_generated.gen.h"
2017-04-09 14:18:49 +02:00
#include "dir_access_osx.h"
2018-03-02 11:38:44 +01:00
#include "drivers/gles2/rasterizer_gles2.h"
2017-04-09 14:18:49 +02:00
#include "drivers/gles3/rasterizer_gles3.h"
#include "main/main.h"
2019-02-12 15:43:54 +01:00
#include "semaphore_osx.h"
2017-04-09 14:18:49 +02:00
#include "servers/visual/visual_server_raster.h"
2015-01-08 08:26:27 +01:00
2018-01-04 20:36:44 +01:00
#include <mach-o/dyld.h>
2015-01-08 08:26:27 +01:00
#include <Carbon/Carbon.h>
2017-04-09 14:18:49 +02:00
#import <Cocoa/Cocoa.h>
2014-02-10 02:10:30 +01:00
#include <IOKit/IOCFPlugIn.h>
2017-04-09 14:18:49 +02:00
#include <IOKit/IOKitLib.h>
2014-02-10 02:10:30 +01:00
#include <IOKit/hid/IOHIDKeys.h>
2017-04-09 14:18:49 +02:00
#include <IOKit/hid/IOHIDLib.h>
2017-08-06 20:55:30 +02:00
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
#include <os/log.h>
#endif
2014-02-10 02:10:30 +01:00
2018-01-04 20:36:44 +01:00
#include <dlfcn.h>
2017-04-09 14:18:49 +02:00
#include <fcntl.h>
#include <libproc.h>
2014-02-10 02:10:30 +01:00
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
2017-04-09 14:18:49 +02:00
#include <sys/types.h>
2014-02-10 02:10:30 +01:00
#include <unistd.h>
2017-04-09 14:18:49 +02:00
2017-06-27 18:13:03 +02:00
#if MAC_OS_X_VERSION_MAX_ALLOWED < 101200
2018-01-06 14:39:44 +01:00
#define NSEventMaskAny NSAnyEventMask
#define NSEventTypeKeyDown NSKeyDown
#define NSEventTypeKeyUp NSKeyUp
#define NSEventModifierFlagShift NSShiftKeyMask
#define NSEventModifierFlagCommand NSCommandKeyMask
#define NSEventModifierFlagControl NSControlKeyMask
#define NSEventModifierFlagOption NSAlternateKeyMask
#define NSWindowStyleMaskTitled NSTitledWindowMask
#define NSWindowStyleMaskResizable NSResizableWindowMask
#define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
#define NSWindowStyleMaskClosable NSClosableWindowMask
2017-06-27 18:13:03 +02:00
#define NSWindowStyleMaskBorderless NSBorderlessWindowMask
#endif
2018-11-19 10:31:03 +01:00
#ifndef NSAppKitVersionNumber10_12
#define NSAppKitVersionNumber10_12 1504
#endif
#ifndef NSAppKitVersionNumber10_14
#define NSAppKitVersionNumber10_14 1671
#endif
2017-05-22 11:17:14 +02:00
static void get_key_modifier_state(unsigned int p_osx_state, Ref<InputEventWithModifiers> state) {
2018-01-06 14:39:44 +01:00
state->set_shift((p_osx_state & NSEventModifierFlagShift));
state->set_control((p_osx_state & NSEventModifierFlagControl));
state->set_alt((p_osx_state & NSEventModifierFlagOption));
state->set_metakey((p_osx_state & NSEventModifierFlagCommand));
2014-02-10 02:10:30 +01:00
}
2018-01-19 08:47:30 +01:00
static void push_to_key_event_buffer(const OS_OSX::KeyEvent &p_event) {
Vector<OS_OSX::KeyEvent> &buffer = OS_OSX::singleton->key_event_buffer;
if (OS_OSX::singleton->key_event_pos >= buffer.size()) {
buffer.resize(1 + OS_OSX::singleton->key_event_pos);
}
2018-07-25 03:11:03 +02:00
buffer.write[OS_OSX::singleton->key_event_pos++] = p_event;
2018-01-19 08:47:30 +01:00
}
2017-04-09 13:22:40 +02:00
static int mouse_x = 0;
static int mouse_y = 0;
static int button_mask = 0;
2017-07-23 17:45:59 +02:00
static bool mouse_down_control = false;
2014-02-10 02:10:30 +01:00
2020-07-07 20:37:05 +02:00
static Vector2 get_mouse_pos(NSPoint locationInWindow) {
2017-11-01 21:49:39 +01:00
const NSRect contentRect = [OS_OSX::singleton->window_view frame];
2018-10-23 18:17:27 +02:00
const NSPoint p = locationInWindow;
2020-07-07 20:37:05 +02:00
const float s = OS_OSX::singleton->get_screen_max_scale();
2018-10-23 18:17:27 +02:00
mouse_x = p.x * s;
mouse_y = (contentRect.size.height - p.y) * s;
2017-11-01 21:49:39 +01:00
return Vector2(mouse_x, mouse_y);
}
2020-01-31 05:40:13 +01:00
static NSCursor *cursorFromSelector(SEL selector, SEL fallback = nil) {
if ([NSCursor respondsToSelector:selector]) {
id object = [NSCursor performSelector:selector];
if ([object isKindOfClass:[NSCursor class]]) {
return object;
}
}
if (fallback) {
// Fallback should be a reasonable default, no need to check.
return [NSCursor performSelector:fallback];
}
return [NSCursor arrowCursor];
}
2014-02-10 02:10:30 +01:00
@interface GodotApplication : NSApplication
@end
@implementation GodotApplication
2017-04-09 13:22:40 +02:00
- (void)sendEvent:(NSEvent *)event {
2017-12-26 07:30:36 +01:00
// special case handling of command-period, which is traditionally a special
// shortcut in macOS and doesn't arrive at our regular keyDown handler.
2018-01-06 14:39:44 +01:00
if ([event type] == NSEventTypeKeyDown) {
2017-12-26 07:30:36 +01:00
if (([event modifierFlags] & NSEventModifierFlagCommand) && [event keyCode] == 0x2f) {
Ref<InputEventKey> k;
k.instance();
get_key_modifier_state([event modifierFlags], k);
k->set_pressed(true);
k->set_scancode(KEY_PERIOD);
k->set_echo([event isARepeat]);
OS_OSX::singleton->push_input(k);
}
}
// From http://cocoadev.com/index.pl?GameKeyboardHandlingAlmost
// This works around an AppKit bug, where key up events while holding
// down the command key don't get sent to the key window.
2018-01-06 14:39:44 +01:00
if ([event type] == NSEventTypeKeyUp && ([event modifierFlags] & NSEventModifierFlagCommand))
2017-04-09 13:22:40 +02:00
[[self keyWindow] sendEvent:event];
else
[super sendEvent:event];
2014-02-10 02:10:30 +01:00
}
@end
@interface GodotApplicationDelegate : NSObject
2018-03-02 17:38:42 +01:00
- (void)forceUnbundledWindowActivationHackStep1;
- (void)forceUnbundledWindowActivationHackStep2;
- (void)forceUnbundledWindowActivationHackStep3;
2014-02-10 02:10:30 +01:00
@end
@implementation GodotApplicationDelegate
2018-03-02 17:38:42 +01:00
- (void)forceUnbundledWindowActivationHackStep1 {
// Step1: Switch focus to macOS Dock.
// Required to perform step 2, TransformProcessType will fail if app is already the in focus.
for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.dock"]) {
[app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
break;
}
[self performSelector:@selector(forceUnbundledWindowActivationHackStep2) withObject:nil afterDelay:0.02];
}
- (void)forceUnbundledWindowActivationHackStep2 {
// Step 2: Register app as foreground process.
ProcessSerialNumber psn = { 0, kCurrentProcess };
(void)TransformProcessType(&psn, kProcessTransformToForegroundApplication);
[self performSelector:@selector(forceUnbundledWindowActivationHackStep3) withObject:nil afterDelay:0.02];
}
- (void)forceUnbundledWindowActivationHackStep3 {
// Step 3: Switch focus back to app window.
[[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateIgnoringOtherApps];
}
- (void)applicationDidFinishLaunching:(NSNotification *)notice {
NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
if (nsappname == nil) {
// If executable is not a bundled, macOS WindowServer won't register and activate app window correctly (menu and title bar are grayed out and input ignored).
[self performSelector:@selector(forceUnbundledWindowActivationHackStep1) withObject:nil afterDelay:0.02];
}
}
2019-02-06 14:57:06 +01:00
- (void)globalMenuCallback:(id)sender {
if (![sender representedObject])
return;
OS_OSX::GlobalMenuItem *item = (OS_OSX::GlobalMenuItem *)[[sender representedObject] pointerValue];
if (!item)
return;
OS_OSX::singleton->main_loop->global_menu_action(item->signal, item->meta);
}
- (NSMenu *)applicationDockMenu:(NSApplication *)sender {
NSMenu *menu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
Vector<OS_OSX::GlobalMenuItem> &E = OS_OSX::singleton->global_menus["_dock"];
for (int i = 0; i < E.size(); i++) {
if (E[i].label == String()) {
[menu addItem:[NSMenuItem separatorItem]];
} else {
NSMenuItem *menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:E[i].label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:@""];
[menu_item setRepresentedObject:[NSValue valueWithPointer:&(E[i])]];
}
}
return menu;
}
2018-01-12 15:38:19 +01:00
- (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename {
2019-02-06 14:57:06 +01:00
// Note: may be called called before main loop init!
2018-01-12 15:38:19 +01:00
char *utfs = strdup([filename UTF8String]);
OS_OSX::singleton->open_with_filename.parse_utf8(utfs);
2018-03-28 19:22:59 +02:00
free(utfs);
2019-02-06 14:57:06 +01:00
#ifdef TOOLS_ENABLED
// Open new instance
if (OS_OSX::singleton->get_main_loop()) {
List<String> args;
args.push_back(OS_OSX::singleton->open_with_filename);
String exec = OS::get_singleton()->get_executable_path();
OS::ProcessID pid = 0;
OS::get_singleton()->execute(exec, args, false, &pid);
}
#endif
2018-01-12 15:38:19 +01:00
return YES;
}
2017-04-09 13:22:40 +02:00
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
2016-06-04 17:35:00 +02:00
if (OS_OSX::singleton->get_main_loop())
OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
2014-02-10 02:10:30 +01:00
2016-06-04 17:35:00 +02:00
return NSTerminateCancel;
2014-02-10 02:10:30 +01:00
}
2017-04-09 14:18:49 +02:00
- (void)applicationDidHide:(NSNotification *)notification {
/*
2017-01-14 12:26:56 +01:00
_Godotwindow* window;
for (window = _Godot.windowListHead; window; window = window->next)
_GodotInputWindowVisibility(window, GL_FALSE);
2017-04-09 13:22:40 +02:00
*/
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)applicationDidUnhide:(NSNotification *)notification {
2017-04-09 14:18:49 +02:00
/*
2017-01-14 12:26:56 +01:00
_Godotwindow* window;
2014-02-10 02:10:30 +01:00
2017-04-09 13:22:40 +02:00
for (window = _Godot.windowListHead; window; window = window->next) {
if ([window_object isVisible])
_GodotInputWindowVisibility(window, GL_TRUE);
2017-01-14 12:26:56 +01:00
}
2017-04-09 13:22:40 +02:00
*/
2014-02-10 02:10:30 +01:00
}
2017-04-09 14:18:49 +02:00
- (void)applicationDidChangeScreenParameters:(NSNotification *)notification {
2017-01-14 12:26:56 +01:00
//_GodotInputMonitorChange();
2014-02-10 02:10:30 +01:00
}
2017-08-11 17:04:32 +02:00
- (void)showAbout:(id)sender {
if (OS_OSX::singleton->get_main_loop())
OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_ABOUT);
}
2014-02-10 02:10:30 +01:00
@end
2017-04-09 13:22:40 +02:00
@interface GodotWindowDelegate : NSObject {
2017-01-14 12:26:56 +01:00
//_Godotwindow* window;
2014-02-10 02:10:30 +01:00
}
@end
@implementation GodotWindowDelegate
2017-04-09 13:22:40 +02:00
- (BOOL)windowShouldClose:(id)sender {
2017-01-14 12:26:56 +01:00
//_GodotInputWindowCloseRequest(window);
2014-02-10 02:10:30 +01:00
if (OS_OSX::singleton->get_main_loop())
OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
2017-04-09 13:22:40 +02:00
return NO;
2014-02-10 02:10:30 +01:00
}
2017-07-26 15:16:10 +02:00
- (void)windowDidEnterFullScreen:(NSNotification *)notification {
OS_OSX::singleton->zoomed = true;
2019-06-13 14:31:08 +02:00
[OS_OSX::singleton->window_object setContentMinSize:NSMakeSize(0, 0)];
[OS_OSX::singleton->window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
2017-07-26 15:16:10 +02:00
}
- (void)windowDidExitFullScreen:(NSNotification *)notification {
OS_OSX::singleton->zoomed = false;
2019-06-13 14:31:08 +02:00
if (OS_OSX::singleton->min_size != Size2()) {
2020-07-07 20:37:05 +02:00
Size2 size = OS_OSX::singleton->min_size / OS_OSX::singleton->get_screen_max_scale();
2019-06-13 14:31:08 +02:00
[OS_OSX::singleton->window_object setContentMinSize:NSMakeSize(size.x, size.y)];
}
if (OS_OSX::singleton->max_size != Size2()) {
2020-07-07 20:37:05 +02:00
Size2 size = OS_OSX::singleton->max_size / OS_OSX::singleton->get_screen_max_scale();
2019-06-13 14:31:08 +02:00
[OS_OSX::singleton->window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
}
2019-03-28 14:36:51 +01:00
if (!OS_OSX::singleton->resizable)
[OS_OSX::singleton->window_object setStyleMask:[OS_OSX::singleton->window_object styleMask] & ~NSWindowStyleMaskResizable];
2017-07-26 15:16:10 +02:00
}
2017-07-28 18:06:48 +02:00
- (void)windowDidChangeBackingProperties:(NSNotification *)notification {
if (!OS_OSX::singleton)
return;
NSWindow *window = (NSWindow *)[notification object];
CGFloat newBackingScaleFactor = [window backingScaleFactor];
CGFloat oldBackingScaleFactor = [[[notification userInfo] objectForKey:@"NSBackingPropertyOldScaleFactorKey"] doubleValue];
2019-01-31 18:24:57 +01:00
if (OS_OSX::singleton->is_hidpi_allowed()) {
[OS_OSX::singleton->window_view setWantsBestResolutionOpenGLSurface:YES];
2019-10-13 22:15:20 +02:00
} else {
[OS_OSX::singleton->window_view setWantsBestResolutionOpenGLSurface:NO];
2019-01-31 18:24:57 +01:00
}
2017-07-28 18:06:48 +02:00
if (newBackingScaleFactor != oldBackingScaleFactor) {
//Set new display scale and window size
2020-07-07 20:37:05 +02:00
float newDisplayScale = OS_OSX::singleton->get_screen_max_scale();
2017-07-28 18:06:48 +02:00
const NSRect contentRect = [OS_OSX::singleton->window_view frame];
2018-10-04 11:09:55 +02:00
const NSRect fbRect = contentRect;
2017-07-28 18:06:48 +02:00
2017-09-30 12:50:30 +02:00
OS_OSX::singleton->window_size.width = fbRect.size.width * newDisplayScale;
OS_OSX::singleton->window_size.height = fbRect.size.height * newDisplayScale;
2017-07-28 18:06:48 +02:00
2020-07-07 20:37:05 +02:00
if (OS_OSX::singleton->context) {
GLint dim[2];
dim[0] = OS_OSX::singleton->window_size.width;
dim[1] = OS_OSX::singleton->window_size.height;
CGLSetParameter((CGLContextObj)[OS_OSX::singleton->context CGLContextObj], kCGLCPSurfaceBackingSize, &dim[0]);
CGLEnable((CGLContextObj)[OS_OSX::singleton->context CGLContextObj], kCGLCESurfaceBackingSize);
}
2017-07-28 18:06:48 +02:00
//Update context
if (OS_OSX::singleton->main_loop) {
2019-12-08 17:29:31 +01:00
//Force window resize event
[self windowDidResize:notification];
2017-07-28 18:06:48 +02:00
}
}
}
2017-04-09 13:22:40 +02:00
- (void)windowDidResize:(NSNotification *)notification {
[OS_OSX::singleton->context update];
2014-02-10 02:10:30 +01:00
2017-04-09 13:22:40 +02:00
const NSRect contentRect = [OS_OSX::singleton->window_view frame];
2018-10-04 11:09:55 +02:00
const NSRect fbRect = contentRect;
2014-02-10 02:10:30 +01:00
2020-07-07 20:37:05 +02:00
float displayScale = OS_OSX::singleton->get_screen_max_scale();
2017-09-30 12:50:30 +02:00
OS_OSX::singleton->window_size.width = fbRect.size.width * displayScale;
OS_OSX::singleton->window_size.height = fbRect.size.height * displayScale;
2014-02-10 02:10:30 +01:00
2020-07-07 20:37:05 +02:00
if (OS_OSX::singleton->context) {
GLint dim[2];
dim[0] = OS_OSX::singleton->window_size.width;
dim[1] = OS_OSX::singleton->window_size.height;
CGLSetParameter((CGLContextObj)[OS_OSX::singleton->context CGLContextObj], kCGLCPSurfaceBackingSize, &dim[0]);
CGLEnable((CGLContextObj)[OS_OSX::singleton->context CGLContextObj], kCGLCESurfaceBackingSize);
}
2017-07-26 15:29:48 +02:00
if (OS_OSX::singleton->main_loop) {
Main::force_redraw();
//Event retrieval blocks until resize is over. Call Main::iteration() directly.
2019-01-22 17:17:39 +01:00
if (!Main::is_iterating()) { //avoid cyclic loop
Main::iteration();
}
2017-07-26 15:29:48 +02:00
}
2017-04-09 14:18:49 +02:00
/*
2017-01-14 12:26:56 +01:00
_GodotInputFramebufferSize(window, fbRect.size.width, fbRect.size.height);
_GodotInputWindowSize(window, contentRect.size.width, contentRect.size.height);
_GodotInputWindowDamage(window);
2014-02-10 02:10:30 +01:00
2017-01-14 12:26:56 +01:00
if (window->cursorMode == Godot_CURSOR_DISABLED)
centerCursor(window);
2017-04-09 13:22:40 +02:00
*/
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)windowDidMove:(NSNotification *)notification {
2019-04-15 19:41:44 +02:00
if (OS_OSX::singleton->get_main_loop()) {
OS_OSX::singleton->input->release_pressed_events();
}
2017-04-09 14:18:49 +02:00
/*
2017-01-14 12:26:56 +01:00
[window->nsgl.context update];
2014-02-10 02:10:30 +01:00
2017-01-14 12:26:56 +01:00
int x, y;
_GodotPlatformGetWindowPos(window, &x, &y);
_GodotInputWindowPos(window, x, y);
2014-02-10 02:10:30 +01:00
2017-01-14 12:26:56 +01:00
if (window->cursorMode == Godot_CURSOR_DISABLED)
centerCursor(window);
2017-04-09 13:22:40 +02:00
*/
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)windowDidBecomeKey:(NSNotification *)notification {
2018-11-04 10:15:39 +01:00
if (OS_OSX::singleton->get_main_loop()) {
2020-07-07 20:37:05 +02:00
get_mouse_pos([OS_OSX::singleton->window_object mouseLocationOutsideOfEventStream]);
2018-10-30 01:50:41 +01:00
OS_OSX::singleton->input->set_mouse_position(Point2(mouse_x, mouse_y));
2018-10-23 18:17:27 +02:00
2014-02-10 02:10:30 +01:00
OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
2018-11-04 10:15:39 +01:00
}
2019-11-28 13:41:07 +01:00
OS_OSX::singleton->window_focused = true;
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)windowDidResignKey:(NSNotification *)notification {
2014-02-10 02:10:30 +01:00
if (OS_OSX::singleton->get_main_loop())
OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
2019-11-28 13:41:07 +01:00
OS_OSX::singleton->window_focused = false;
2014-02-10 02:10:30 +01:00
}
2017-04-09 14:18:49 +02:00
- (void)windowDidMiniaturize:(NSNotification *)notification {
2015-04-02 06:32:02 +02:00
OS_OSX::singleton->wm_minimized(true);
if (OS_OSX::singleton->get_main_loop())
OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
2019-11-28 13:41:07 +01:00
OS_OSX::singleton->window_focused = false;
2015-04-02 06:32:02 +02:00
};
2017-04-09 14:18:49 +02:00
- (void)windowDidDeminiaturize:(NSNotification *)notification {
2015-04-02 06:32:02 +02:00
OS_OSX::singleton->wm_minimized(false);
if (OS_OSX::singleton->get_main_loop())
OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
2019-11-28 13:41:07 +01:00
OS_OSX::singleton->window_focused = true;
2015-04-02 06:32:02 +02:00
};
2014-02-10 02:10:30 +01:00
@end
2020-06-29 13:24:56 +02:00
@interface GodotContentView : NSOpenGLView <NSTextInputClient> {
2017-04-09 14:18:49 +02:00
NSTrackingArea *trackingArea;
2017-08-07 13:09:56 +02:00
NSMutableAttributedString *markedText;
2019-06-04 09:30:59 +02:00
bool imeInputEventInProgress;
2014-02-10 02:10:30 +01:00
}
2017-08-07 13:09:56 +02:00
- (void)cancelComposition;
2018-11-04 10:16:58 +01:00
- (BOOL)wantsUpdateLayer;
- (void)updateLayer;
2014-02-10 02:10:30 +01:00
@end
@implementation GodotContentView
2017-04-09 13:22:40 +02:00
+ (void)initialize {
if (self == [GodotContentView class]) {
2017-05-20 01:30:31 +02:00
// nothing left to do here at the moment..
2017-01-14 12:26:56 +01:00
}
2014-02-10 02:10:30 +01:00
}
2018-11-04 10:16:58 +01:00
- (BOOL)wantsUpdateLayer {
return YES;
}
- (void)updateLayer {
[OS_OSX::singleton->context update];
}
2017-04-09 13:22:40 +02:00
- (id)init {
self = [super init];
trackingArea = nil;
2019-06-04 09:30:59 +02:00
imeInputEventInProgress = false;
2017-04-09 13:22:40 +02:00
[self updateTrackingAreas];
2020-06-29 13:24:56 +02:00
#if MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
[self registerForDraggedTypes:[NSArray arrayWithObject:NSPasteboardTypeFileURL]];
#else
2017-04-09 13:22:40 +02:00
[self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
2020-06-29 13:24:56 +02:00
#endif
2017-08-07 13:09:56 +02:00
markedText = [[NSMutableAttributedString alloc] init];
2017-04-09 13:22:40 +02:00
return self;
2014-02-10 02:10:30 +01:00
}
2017-04-09 14:18:49 +02:00
- (void)dealloc {
2017-04-09 13:22:40 +02:00
[trackingArea release];
2017-08-07 13:09:56 +02:00
[markedText release];
2017-04-09 13:22:40 +02:00
[super dealloc];
2014-02-10 02:10:30 +01:00
}
2017-08-07 13:09:56 +02:00
static const NSRange kEmptyRange = { NSNotFound, 0 };
- (BOOL)hasMarkedText {
return (markedText.length > 0);
}
- (NSRange)markedRange {
2020-01-14 12:07:55 +01:00
return NSMakeRange(0, markedText.length);
2017-08-07 13:09:56 +02:00
}
- (NSRange)selectedRange {
return kEmptyRange;
}
- (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange {
if ([aString isKindOfClass:[NSAttributedString class]]) {
[markedText initWithAttributedString:aString];
} else {
[markedText initWithString:aString];
}
2020-01-14 12:07:55 +01:00
if (markedText.length == 0) {
[self unmarkText];
return;
}
2018-11-23 13:07:48 +01:00
if (OS_OSX::singleton->im_active) {
2019-06-04 09:30:59 +02:00
imeInputEventInProgress = true;
2018-11-23 13:07:48 +01:00
OS_OSX::singleton->im_text.parse_utf8([[markedText mutableString] UTF8String]);
OS_OSX::singleton->im_selection = Point2(selectedRange.location, selectedRange.length);
if (OS_OSX::singleton->get_main_loop())
OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
2017-08-07 13:09:56 +02:00
}
}
- (void)doCommandBySelector:(SEL)aSelector {
if ([self respondsToSelector:aSelector])
[self performSelector:aSelector];
}
- (void)unmarkText {
2019-06-04 09:30:59 +02:00
imeInputEventInProgress = false;
2017-08-07 13:09:56 +02:00
[[markedText mutableString] setString:@""];
2018-11-23 13:07:48 +01:00
if (OS_OSX::singleton->im_active) {
OS_OSX::singleton->im_text = String();
OS_OSX::singleton->im_selection = Point2();
if (OS_OSX::singleton->get_main_loop())
OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
}
2017-08-07 13:09:56 +02:00
}
- (NSArray *)validAttributesForMarkedText {
return [NSArray array];
}
- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
return nil;
}
- (NSUInteger)characterIndexForPoint:(NSPoint)aPoint {
return 0;
}
- (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
const NSRect contentRect = [OS_OSX::singleton->window_view frame];
2020-07-07 20:37:05 +02:00
float displayScale = OS_OSX::singleton->get_screen_max_scale();
2017-09-30 12:50:30 +02:00
NSRect pointInWindowRect = NSMakeRect(OS_OSX::singleton->im_position.x / displayScale, contentRect.size.height - (OS_OSX::singleton->im_position.y / displayScale) - 1, 0, 0);
2017-08-07 13:09:56 +02:00
NSPoint pointOnScreen = [[OS_OSX::singleton->window_view window] convertRectToScreen:pointInWindowRect].origin;
return NSMakeRect(pointOnScreen.x, pointOnScreen.y, 0, 0);
}
- (void)cancelComposition {
[self unmarkText];
2018-01-06 14:39:44 +01:00
NSTextInputContext *currentInputContext = [NSTextInputContext currentInputContext];
[currentInputContext discardMarkedText];
2017-08-07 13:09:56 +02:00
}
- (void)insertText:(id)aString {
[self insertText:aString replacementRange:NSMakeRange(0, 0)];
}
- (void)insertText:(id)aString replacementRange:(NSRange)replacementRange {
NSEvent *event = [NSApp currentEvent];
NSString *characters;
if ([aString isKindOfClass:[NSAttributedString class]]) {
characters = [aString string];
} else {
characters = (NSString *)aString;
}
NSUInteger i, length = [characters length];
NSCharacterSet *ctrlChars = [NSCharacterSet controlCharacterSet];
NSCharacterSet *wsnlChars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
if ([characters rangeOfCharacterFromSet:ctrlChars].length && [characters rangeOfCharacterFromSet:wsnlChars].length == 0) {
2018-01-06 14:39:44 +01:00
NSTextInputContext *currentInputContext = [NSTextInputContext currentInputContext];
[currentInputContext discardMarkedText];
2017-08-07 13:09:56 +02:00
[self cancelComposition];
return;
}
for (i = 0; i < length; i++) {
const unichar codepoint = [characters characterAtIndex:i];
if ((codepoint & 0xFF00) == 0xF700)
continue;
2018-01-10 12:22:28 +01:00
OS_OSX::KeyEvent ke;
ke.osx_state = [event modifierFlags];
ke.pressed = true;
ke.echo = false;
2019-06-04 09:30:59 +02:00
ke.raw = false; // IME input event
2018-01-10 12:22:28 +01:00
ke.scancode = 0;
ke.unicode = codepoint;
2018-01-19 08:47:30 +01:00
push_to_key_event_buffer(ke);
2017-08-07 13:09:56 +02:00
}
[self cancelComposition];
}
2017-04-09 14:18:49 +02:00
- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
2017-04-09 13:22:40 +02:00
return NSDragOperationCopy;
2016-05-31 06:27:48 +02:00
}
- (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
2017-04-09 13:22:40 +02:00
return NSDragOperationCopy;
2016-05-31 06:27:48 +02:00
}
- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
2017-04-09 13:22:40 +02:00
NSPasteboard *pboard = [sender draggingPasteboard];
2020-06-29 13:24:56 +02:00
#if MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
NSArray<NSURL *> *filenames = [pboard propertyListForType:NSPasteboardTypeFileURL];
#else
2017-04-09 13:22:40 +02:00
NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType];
2020-06-29 13:24:56 +02:00
#endif
2016-05-31 06:27:48 +02:00
2017-04-09 13:22:40 +02:00
Vector<String> files;
2019-10-24 16:34:18 +02:00
for (NSUInteger i = 0; i < filenames.count; i++) {
2020-06-29 13:24:56 +02:00
#if MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
NSString *ns = [[filenames objectAtIndex:i] path];
#else
2017-04-09 13:22:40 +02:00
NSString *ns = [filenames objectAtIndex:i];
2020-06-29 13:24:56 +02:00
#endif
2017-04-09 13:22:40 +02:00
char *utfs = strdup([ns UTF8String]);
String ret;
ret.parse_utf8(utfs);
free(utfs);
files.push_back(ret);
}
2016-05-31 06:27:48 +02:00
2017-04-09 13:22:40 +02:00
if (files.size()) {
2017-04-09 14:18:49 +02:00
OS_OSX::singleton->main_loop->drop_files(files, 0);
2017-04-09 13:22:40 +02:00
OS_OSX::singleton->move_window_to_foreground();
}
2016-05-31 06:27:48 +02:00
2017-04-09 13:22:40 +02:00
return NO;
2016-05-31 06:27:48 +02:00
}
2017-04-09 13:22:40 +02:00
- (BOOL)isOpaque {
return YES;
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (BOOL)canBecomeKeyView {
return YES;
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (BOOL)acceptsFirstResponder {
return YES;
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)cursorUpdate:(NSEvent *)event {
2018-05-10 00:49:45 +02:00
OS::CursorShape p_shape = OS_OSX::singleton->cursor_shape;
OS_OSX::singleton->cursor_shape = OS::CURSOR_MAX;
OS_OSX::singleton->set_cursor_shape(p_shape);
2014-02-10 02:10:30 +01:00
}
2017-07-23 17:45:59 +02:00
static void _mouseDownEvent(NSEvent *event, int index, int mask, bool pressed) {
if (pressed) {
button_mask |= mask;
} else {
button_mask &= ~mask;
}
2017-05-22 04:02:35 +02:00
Ref<InputEventMouseButton> mb;
mb.instance();
2020-07-07 20:37:05 +02:00
const Vector2 pos = get_mouse_pos([event locationInWindow]);
2017-05-22 11:17:14 +02:00
get_key_modifier_state([event modifierFlags], mb);
2017-07-23 17:45:59 +02:00
mb->set_button_index(index);
mb->set_pressed(pressed);
2019-03-07 10:10:33 +01:00
mb->set_position(pos);
mb->set_global_position(pos);
2017-05-22 04:02:35 +02:00
mb->set_button_mask(button_mask);
2017-07-23 17:45:59 +02:00
if (index == BUTTON_LEFT && pressed) {
mb->set_doubleclick([event clickCount] == 2);
}
2017-05-22 04:02:35 +02:00
OS_OSX::singleton->push_input(mb);
2014-02-10 02:10:30 +01:00
}
2017-07-23 17:45:59 +02:00
- (void)mouseDown:(NSEvent *)event {
2018-01-06 14:39:44 +01:00
if (([event modifierFlags] & NSEventModifierFlagControl)) {
2017-07-23 17:45:59 +02:00
mouse_down_control = true;
_mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, true);
} else {
mouse_down_control = false;
_mouseDownEvent(event, BUTTON_LEFT, BUTTON_MASK_LEFT, true);
}
}
2017-04-09 13:22:40 +02:00
- (void)mouseDragged:(NSEvent *)event {
[self mouseMoved:event];
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)mouseUp:(NSEvent *)event {
2017-07-23 17:45:59 +02:00
if (mouse_down_control) {
_mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, false);
} else {
_mouseDownEvent(event, BUTTON_LEFT, BUTTON_MASK_LEFT, false);
}
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)mouseMoved:(NSEvent *)event {
2014-02-10 02:10:30 +01:00
2020-07-02 14:57:19 +02:00
NSPoint delta = NSMakePoint([event deltaX], [event deltaY]);
NSPoint mpos = [event locationInWindow];
if (OS_OSX::singleton->mouse_mode == OS::MOUSE_MODE_CONFINED) {
// Discard late events
if (([event timestamp]) < OS_OSX::singleton->last_warp) {
return;
}
// Warp affects next event delta, subtract previous warp deltas
List<OS_OSX::WarpEvent>::Element *F = OS_OSX::singleton->warp_events.front();
while (F) {
if (F->get().timestamp < [event timestamp]) {
List<OS_OSX::WarpEvent>::Element *E = F;
delta.x -= E->get().delta.x;
delta.y -= E->get().delta.y;
F = F->next();
OS_OSX::singleton->warp_events.erase(E);
} else {
F = F->next();
}
}
// Confine mouse position to the window, and update delta
NSRect frame = [OS_OSX::singleton->window_object frame];
NSPoint conf_pos = mpos;
conf_pos.x = CLAMP(conf_pos.x + delta.x, 0.f, frame.size.width);
conf_pos.y = CLAMP(conf_pos.y - delta.y, 0.f, frame.size.height);
delta.x = conf_pos.x - mpos.x;
delta.y = mpos.y - conf_pos.y;
mpos = conf_pos;
// Move mouse cursor
NSRect pointInWindowRect = NSMakeRect(conf_pos.x, conf_pos.y, 0, 0);
conf_pos = [[OS_OSX::singleton->window_view window] convertRectToScreen:pointInWindowRect].origin;
conf_pos.y = CGDisplayBounds(CGMainDisplayID()).size.height - conf_pos.y;
CGWarpMouseCursorPosition(conf_pos);
// Save warp data
OS_OSX::singleton->last_warp = [[NSProcessInfo processInfo] systemUptime];
OS_OSX::WarpEvent ev;
ev.timestamp = OS_OSX::singleton->last_warp;
ev.delta = delta;
OS_OSX::singleton->warp_events.push_back(ev);
}
2017-05-22 04:02:35 +02:00
Ref<InputEventMouseMotion> mm;
mm.instance();
2017-05-22 11:17:14 +02:00
2017-05-22 04:02:35 +02:00
mm->set_button_mask(button_mask);
2020-07-07 20:37:05 +02:00
const Vector2 pos = get_mouse_pos(mpos);
2017-11-01 21:49:39 +01:00
mm->set_position(pos);
2018-12-13 21:32:11 +01:00
mm->set_pressure([event pressure]);
2020-06-29 13:24:56 +02:00
if ([event subtype] == NSEventSubtypeTabletPoint) {
2018-12-13 21:32:11 +01:00
const NSPoint p = [event tilt];
mm->set_tilt(Vector2(p.x, p.y));
}
2017-11-01 21:49:39 +01:00
mm->set_global_position(pos);
2019-01-11 15:53:11 +01:00
mm->set_speed(OS_OSX::singleton->input->get_last_mouse_speed());
2020-07-07 20:37:05 +02:00
const Vector2 relativeMotion = Vector2(delta.x, delta.y) * OS_OSX::singleton->get_screen_max_scale();
2017-05-22 04:02:35 +02:00
mm->set_relative(relativeMotion);
2017-05-22 11:17:14 +02:00
get_key_modifier_state([event modifierFlags], mm);
2014-02-10 02:10:30 +01:00
2017-03-29 17:29:38 +02:00
OS_OSX::singleton->input->set_mouse_position(Point2(mouse_x, mouse_y));
2017-05-22 04:02:35 +02:00
OS_OSX::singleton->push_input(mm);
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)rightMouseDown:(NSEvent *)event {
2017-07-23 17:45:59 +02:00
_mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, true);
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)rightMouseDragged:(NSEvent *)event {
[self mouseMoved:event];
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)rightMouseUp:(NSEvent *)event {
2017-07-23 17:45:59 +02:00
_mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, false);
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)otherMouseDown:(NSEvent *)event {
2014-02-10 02:10:30 +01:00
2018-07-05 16:50:30 +02:00
if ((int)[event buttonNumber] == 2) {
_mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, true);
} else if ((int)[event buttonNumber] == 3) {
_mouseDownEvent(event, BUTTON_XBUTTON1, BUTTON_MASK_XBUTTON1, true);
} else if ((int)[event buttonNumber] == 4) {
_mouseDownEvent(event, BUTTON_XBUTTON2, BUTTON_MASK_XBUTTON2, true);
2014-02-10 02:10:30 +01:00
2018-07-05 16:50:30 +02:00
} else {
return;
}
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)otherMouseDragged:(NSEvent *)event {
[self mouseMoved:event];
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)otherMouseUp:(NSEvent *)event {
2014-02-10 02:10:30 +01:00
2018-07-05 16:50:30 +02:00
if ((int)[event buttonNumber] == 2) {
_mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, false);
} else if ((int)[event buttonNumber] == 3) {
_mouseDownEvent(event, BUTTON_XBUTTON1, BUTTON_MASK_XBUTTON1, false);
} else if ((int)[event buttonNumber] == 4) {
_mouseDownEvent(event, BUTTON_XBUTTON2, BUTTON_MASK_XBUTTON2, false);
2014-02-10 02:10:30 +01:00
2018-07-05 16:50:30 +02:00
} else {
return;
}
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)mouseExited:(NSEvent *)event {
2015-09-24 23:06:15 +02:00
if (!OS_OSX::singleton)
return;
2017-04-09 14:18:49 +02:00
if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode != OS::MOUSE_MODE_CAPTURED)
2015-09-24 23:06:15 +02:00
OS_OSX::singleton->main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)mouseEntered:(NSEvent *)event {
2015-09-24 23:06:15 +02:00
if (!OS_OSX::singleton)
return;
2017-04-09 14:18:49 +02:00
if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode != OS::MOUSE_MODE_CAPTURED)
2015-09-24 23:06:15 +02:00
OS_OSX::singleton->main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
2018-05-10 00:49:45 +02:00
OS::CursorShape p_shape = OS_OSX::singleton->cursor_shape;
OS_OSX::singleton->cursor_shape = OS::CURSOR_MAX;
OS_OSX::singleton->set_cursor_shape(p_shape);
2014-02-10 02:10:30 +01:00
}
2017-11-01 21:49:39 +01:00
- (void)magnifyWithEvent:(NSEvent *)event {
Ref<InputEventMagnifyGesture> ev;
ev.instance();
get_key_modifier_state([event modifierFlags], ev);
2020-07-07 20:37:05 +02:00
ev->set_position(get_mouse_pos([event locationInWindow]));
2017-11-01 21:49:39 +01:00
ev->set_factor([event magnification] + 1.0);
OS_OSX::singleton->push_input(ev);
}
2017-04-09 13:22:40 +02:00
- (void)viewDidChangeBackingProperties {
2017-05-20 01:30:31 +02:00
// nothing left to do here
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)updateTrackingAreas {
if (trackingArea != nil) {
[self removeTrackingArea:trackingArea];
[trackingArea release];
}
2014-02-10 02:10:30 +01:00
2017-04-09 14:18:49 +02:00
NSTrackingAreaOptions options =
NSTrackingMouseEnteredAndExited |
NSTrackingActiveInKeyWindow |
NSTrackingCursorUpdate |
NSTrackingInVisibleRect;
2014-02-10 02:10:30 +01:00
2017-04-09 14:18:49 +02:00
trackingArea = [[NSTrackingArea alloc]
initWithRect:[self bounds]
options:options
owner:self
userInfo:nil];
2014-02-10 02:10:30 +01:00
2017-04-09 13:22:40 +02:00
[self addTrackingArea:trackingArea];
[super updateTrackingAreas];
2014-02-10 02:10:30 +01:00
}
2019-03-06 21:03:15 +01:00
static bool isNumpadKey(unsigned int key) {
static const unsigned int table[] = {
0x41, /* kVK_ANSI_KeypadDecimal */
0x43, /* kVK_ANSI_KeypadMultiply */
0x45, /* kVK_ANSI_KeypadPlus */
0x47, /* kVK_ANSI_KeypadClear */
0x4b, /* kVK_ANSI_KeypadDivide */
0x4c, /* kVK_ANSI_KeypadEnter */
0x4e, /* kVK_ANSI_KeypadMinus */
0x51, /* kVK_ANSI_KeypadEquals */
0x52, /* kVK_ANSI_Keypad0 */
0x53, /* kVK_ANSI_Keypad1 */
0x54, /* kVK_ANSI_Keypad2 */
0x55, /* kVK_ANSI_Keypad3 */
0x56, /* kVK_ANSI_Keypad4 */
0x57, /* kVK_ANSI_Keypad5 */
0x58, /* kVK_ANSI_Keypad6 */
0x59, /* kVK_ANSI_Keypad7 */
0x5b, /* kVK_ANSI_Keypad8 */
0x5c, /* kVK_ANSI_Keypad9 */
0x5f, /* kVK_JIS_KeypadComma */
0x00
};
for (int i = 0; table[i] != 0; i++) {
if (key == table[i])
return true;
}
return false;
}
2014-02-10 02:10:30 +01:00
// Translates a OS X keycode to a Godot keycode
//
2017-04-09 13:22:40 +02:00
static int translateKey(unsigned int key) {
2019-03-06 21:03:15 +01:00
2017-04-09 13:22:40 +02:00
// Keyboard symbol translation table
static const unsigned int table[128] = {
/* 00 */ KEY_A,
/* 01 */ KEY_S,
/* 02 */ KEY_D,
/* 03 */ KEY_F,
/* 04 */ KEY_H,
/* 05 */ KEY_G,
/* 06 */ KEY_Z,
/* 07 */ KEY_X,
/* 08 */ KEY_C,
/* 09 */ KEY_V,
2019-03-06 21:03:15 +01:00
/* 0a */ KEY_SECTION, /* ISO Section */
2017-04-09 13:22:40 +02:00
/* 0b */ KEY_B,
/* 0c */ KEY_Q,
/* 0d */ KEY_W,
/* 0e */ KEY_E,
/* 0f */ KEY_R,
/* 10 */ KEY_Y,
/* 11 */ KEY_T,
/* 12 */ KEY_1,
/* 13 */ KEY_2,
/* 14 */ KEY_3,
/* 15 */ KEY_4,
/* 16 */ KEY_6,
/* 17 */ KEY_5,
/* 18 */ KEY_EQUAL,
/* 19 */ KEY_9,
/* 1a */ KEY_7,
/* 1b */ KEY_MINUS,
/* 1c */ KEY_8,
/* 1d */ KEY_0,
/* 1e */ KEY_BRACERIGHT,
/* 1f */ KEY_O,
/* 20 */ KEY_U,
/* 21 */ KEY_BRACELEFT,
/* 22 */ KEY_I,
/* 23 */ KEY_P,
2017-08-06 15:26:07 +02:00
/* 24 */ KEY_ENTER,
2017-04-09 13:22:40 +02:00
/* 25 */ KEY_L,
/* 26 */ KEY_J,
/* 27 */ KEY_APOSTROPHE,
/* 28 */ KEY_K,
/* 29 */ KEY_SEMICOLON,
/* 2a */ KEY_BACKSLASH,
/* 2b */ KEY_COMMA,
/* 2c */ KEY_SLASH,
/* 2d */ KEY_N,
/* 2e */ KEY_M,
/* 2f */ KEY_PERIOD,
/* 30 */ KEY_TAB,
/* 31 */ KEY_SPACE,
/* 32 */ KEY_QUOTELEFT,
/* 33 */ KEY_BACKSPACE,
/* 34 */ KEY_UNKNOWN,
/* 35 */ KEY_ESCAPE,
/* 36 */ KEY_META,
/* 37 */ KEY_META,
/* 38 */ KEY_SHIFT,
/* 39 */ KEY_CAPSLOCK,
/* 3a */ KEY_ALT,
/* 3b */ KEY_CONTROL,
/* 3c */ KEY_SHIFT,
/* 3d */ KEY_ALT,
/* 3e */ KEY_CONTROL,
/* 3f */ KEY_UNKNOWN, /* Function */
2019-03-06 21:03:15 +01:00
/* 40 */ KEY_UNKNOWN, /* F17 */
2017-04-09 13:22:40 +02:00
/* 41 */ KEY_KP_PERIOD,
/* 42 */ KEY_UNKNOWN,
/* 43 */ KEY_KP_MULTIPLY,
/* 44 */ KEY_UNKNOWN,
/* 45 */ KEY_KP_ADD,
/* 46 */ KEY_UNKNOWN,
/* 47 */ KEY_NUMLOCK, /* Really KeypadClear... */
2019-03-06 21:03:15 +01:00
/* 48 */ KEY_VOLUMEUP, /* VolumeUp */
/* 49 */ KEY_VOLUMEDOWN, /* VolumeDown */
/* 4a */ KEY_VOLUMEMUTE, /* Mute */
2017-04-09 13:22:40 +02:00
/* 4b */ KEY_KP_DIVIDE,
2017-08-06 15:26:07 +02:00
/* 4c */ KEY_KP_ENTER,
2017-04-09 13:22:40 +02:00
/* 4d */ KEY_UNKNOWN,
/* 4e */ KEY_KP_SUBTRACT,
2019-03-06 21:03:15 +01:00
/* 4f */ KEY_UNKNOWN, /* F18 */
/* 50 */ KEY_UNKNOWN, /* F19 */
/* 51 */ KEY_EQUAL, /* KeypadEqual */
2017-04-09 13:22:40 +02:00
/* 52 */ KEY_KP_0,
/* 53 */ KEY_KP_1,
/* 54 */ KEY_KP_2,
/* 55 */ KEY_KP_3,
/* 56 */ KEY_KP_4,
/* 57 */ KEY_KP_5,
/* 58 */ KEY_KP_6,
/* 59 */ KEY_KP_7,
2019-03-06 21:03:15 +01:00
/* 5a */ KEY_UNKNOWN, /* F20 */
2017-04-09 13:22:40 +02:00
/* 5b */ KEY_KP_8,
/* 5c */ KEY_KP_9,
2019-03-06 21:03:15 +01:00
/* 5d */ KEY_YEN, /* JIS Yen */
/* 5e */ KEY_UNDERSCORE, /* JIS Underscore */
/* 5f */ KEY_COMMA, /* JIS KeypadComma */
2017-04-09 13:22:40 +02:00
/* 60 */ KEY_F5,
/* 61 */ KEY_F6,
/* 62 */ KEY_F7,
/* 63 */ KEY_F3,
/* 64 */ KEY_F8,
/* 65 */ KEY_F9,
2019-03-06 21:03:15 +01:00
/* 66 */ KEY_UNKNOWN, /* JIS Eisu */
2017-04-09 13:22:40 +02:00
/* 67 */ KEY_F11,
2019-03-06 21:03:15 +01:00
/* 68 */ KEY_UNKNOWN, /* JIS Kana */
2017-04-09 13:22:40 +02:00
/* 69 */ KEY_F13,
/* 6a */ KEY_F16,
/* 6b */ KEY_F14,
/* 6c */ KEY_UNKNOWN,
/* 6d */ KEY_F10,
2019-03-06 21:03:15 +01:00
/* 6e */ KEY_MENU,
2017-04-09 13:22:40 +02:00
/* 6f */ KEY_F12,
/* 70 */ KEY_UNKNOWN,
/* 71 */ KEY_F15,
/* 72 */ KEY_INSERT, /* Really Help... */
/* 73 */ KEY_HOME,
/* 74 */ KEY_PAGEUP,
/* 75 */ KEY_DELETE,
/* 76 */ KEY_F4,
/* 77 */ KEY_END,
/* 78 */ KEY_F2,
/* 79 */ KEY_PAGEDOWN,
/* 7a */ KEY_F1,
/* 7b */ KEY_LEFT,
/* 7c */ KEY_RIGHT,
/* 7d */ KEY_DOWN,
/* 7e */ KEY_UP,
/* 7f */ KEY_UNKNOWN,
};
if (key >= 128)
return KEY_UNKNOWN;
return table[key];
}
2018-03-28 19:22:59 +02:00
struct _KeyCodeMap {
UniChar kchar;
int kcode;
};
static const _KeyCodeMap _keycodes[55] = {
{ '`', KEY_QUOTELEFT },
{ '~', KEY_ASCIITILDE },
2018-05-13 21:19:08 +02:00
{ '0', KEY_0 },
{ '1', KEY_1 },
{ '2', KEY_2 },
{ '3', KEY_3 },
{ '4', KEY_4 },
{ '5', KEY_5 },
{ '6', KEY_6 },
{ '7', KEY_7 },
{ '8', KEY_8 },
{ '9', KEY_9 },
2018-03-28 19:22:59 +02:00
{ '-', KEY_MINUS },
{ '_', KEY_UNDERSCORE },
{ '=', KEY_EQUAL },
{ '+', KEY_PLUS },
{ 'q', KEY_Q },
{ 'w', KEY_W },
{ 'e', KEY_E },
{ 'r', KEY_R },
{ 't', KEY_T },
{ 'y', KEY_Y },
{ 'u', KEY_U },
{ 'i', KEY_I },
{ 'o', KEY_O },
{ 'p', KEY_P },
2019-04-19 04:31:02 +02:00
{ '[', KEY_BRACELEFT },
{ ']', KEY_BRACERIGHT },
{ '{', KEY_BRACELEFT },
{ '}', KEY_BRACERIGHT },
2018-03-28 19:22:59 +02:00
{ 'a', KEY_A },
{ 's', KEY_S },
{ 'd', KEY_D },
{ 'f', KEY_F },
{ 'g', KEY_G },
{ 'h', KEY_H },
{ 'j', KEY_J },
{ 'k', KEY_K },
{ 'l', KEY_L },
{ ';', KEY_SEMICOLON },
{ ':', KEY_COLON },
{ '\'', KEY_APOSTROPHE },
{ '\"', KEY_QUOTEDBL },
{ '\\', KEY_BACKSLASH },
{ '#', KEY_NUMBERSIGN },
{ 'z', KEY_Z },
{ 'x', KEY_X },
{ 'c', KEY_C },
{ 'v', KEY_V },
{ 'b', KEY_B },
{ 'n', KEY_N },
{ 'm', KEY_M },
{ ',', KEY_COMMA },
{ '.', KEY_PERIOD },
{ '/', KEY_SLASH }
};
2019-06-04 18:45:49 +02:00
static int remapKey(unsigned int key, unsigned int state) {
2018-03-28 19:22:59 +02:00
2019-03-06 21:03:15 +01:00
if (isNumpadKey(key))
return translateKey(key);
2018-03-28 19:22:59 +02:00
TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
if (!currentKeyboard)
return translateKey(key);
CFDataRef layoutData = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
if (!layoutData)
2018-11-01 12:00:02 +01:00
return translateKey(key);
2018-03-28 19:22:59 +02:00
const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout *)CFDataGetBytePtr(layoutData);
UInt32 keysDown = 0;
UniChar chars[4];
UniCharCount realLength;
OSStatus err = UCKeyTranslate(keyboardLayout,
key,
kUCKeyActionDisplay,
2019-06-04 18:45:49 +02:00
(state >> 8) & 0xFF,
2018-03-28 19:22:59 +02:00
LMGetKbdType(),
kUCKeyTranslateNoDeadKeysBit,
&keysDown,
sizeof(chars) / sizeof(chars[0]),
&realLength,
chars);
if (err != noErr) {
return translateKey(key);
}
for (unsigned int i = 0; i < 55; i++) {
if (_keycodes[i].kchar == chars[0]) {
return _keycodes[i].kcode;
}
}
return translateKey(key);
}
2017-04-09 13:22:40 +02:00
- (void)keyDown:(NSEvent *)event {
2017-05-22 04:02:35 +02:00
2019-06-04 09:30:59 +02:00
// Ignore all input if IME input is in progress
if (!imeInputEventInProgress) {
NSString *characters = [event characters];
NSUInteger length = [characters length];
2017-04-09 13:22:40 +02:00
2019-06-04 18:45:49 +02:00
if (!OS_OSX::singleton->im_active && length > 0 && keycode_has_unicode(remapKey([event keyCode], [event modifierFlags]))) {
2019-06-04 09:30:59 +02:00
// Fallback unicode character handler used if IME is not active
for (NSUInteger i = 0; i < length; i++) {
OS_OSX::KeyEvent ke;
2017-04-09 13:22:40 +02:00
2019-06-04 09:30:59 +02:00
ke.osx_state = [event modifierFlags];
ke.pressed = true;
ke.echo = [event isARepeat];
2019-06-04 18:45:49 +02:00
ke.scancode = remapKey([event keyCode], [event modifierFlags]);
2019-06-04 09:30:59 +02:00
ke.raw = true;
ke.unicode = [characters characterAtIndex:i];
push_to_key_event_buffer(ke);
}
} else {
OS_OSX::KeyEvent ke;
ke.osx_state = [event modifierFlags];
ke.pressed = true;
ke.echo = [event isARepeat];
2019-06-04 18:45:49 +02:00
ke.scancode = remapKey([event keyCode], [event modifierFlags]);
2019-06-04 09:30:59 +02:00
ke.raw = false;
ke.unicode = 0;
push_to_key_event_buffer(ke);
}
2018-01-10 12:22:28 +01:00
}
2017-08-07 13:09:56 +02:00
2019-06-04 09:30:59 +02:00
// Pass events to IME handler
if (OS_OSX::singleton->im_active)
2017-08-07 13:09:56 +02:00
[self interpretKeyEvents:[NSArray arrayWithObject:event]];
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)flagsChanged:(NSEvent *)event {
2017-05-22 11:17:14 +02:00
2019-06-04 09:30:59 +02:00
// Ignore all input if IME input is in progress
if (!imeInputEventInProgress) {
2018-01-10 12:22:28 +01:00
OS_OSX::KeyEvent ke;
2014-02-10 02:10:30 +01:00
2018-01-10 12:22:28 +01:00
ke.echo = false;
2019-06-04 09:30:59 +02:00
ke.raw = true;
2018-01-10 12:22:28 +01:00
int key = [event keyCode];
int mod = [event modifierFlags];
if (key == 0x36 || key == 0x37) {
if (mod & NSEventModifierFlagCommand) {
mod &= ~NSEventModifierFlagCommand;
ke.pressed = true;
} else {
ke.pressed = false;
}
} else if (key == 0x38 || key == 0x3c) {
if (mod & NSEventModifierFlagShift) {
mod &= ~NSEventModifierFlagShift;
ke.pressed = true;
} else {
ke.pressed = false;
}
} else if (key == 0x3a || key == 0x3d) {
if (mod & NSEventModifierFlagOption) {
mod &= ~NSEventModifierFlagOption;
ke.pressed = true;
} else {
ke.pressed = false;
}
} else if (key == 0x3b || key == 0x3e) {
if (mod & NSEventModifierFlagControl) {
mod &= ~NSEventModifierFlagControl;
ke.pressed = true;
} else {
ke.pressed = false;
}
2016-05-31 05:02:14 +02:00
} else {
2018-01-10 12:22:28 +01:00
return;
2016-05-31 05:02:14 +02:00
}
2018-01-10 12:22:28 +01:00
ke.osx_state = mod;
2019-06-04 18:45:49 +02:00
ke.scancode = remapKey(key, mod);
2018-01-10 12:22:28 +01:00
ke.unicode = 0;
2014-02-10 02:10:30 +01:00
2018-01-19 08:47:30 +01:00
push_to_key_event_buffer(ke);
2018-01-10 12:22:28 +01:00
}
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
- (void)keyUp:(NSEvent *)event {
2014-02-10 02:10:30 +01:00
2019-06-04 09:30:59 +02:00
// Ignore all input if IME input is in progress
if (!imeInputEventInProgress) {
NSString *characters = [event characters];
NSUInteger length = [characters length];
2018-01-10 12:22:28 +01:00
2019-06-04 09:30:59 +02:00
// Fallback unicode character handler used if IME is not active
2019-06-04 18:45:49 +02:00
if (!OS_OSX::singleton->im_active && length > 0 && keycode_has_unicode(remapKey([event keyCode], [event modifierFlags]))) {
2019-06-04 09:30:59 +02:00
for (NSUInteger i = 0; i < length; i++) {
OS_OSX::KeyEvent ke;
2017-05-22 04:02:35 +02:00
2019-06-04 09:30:59 +02:00
ke.osx_state = [event modifierFlags];
ke.pressed = false;
ke.echo = [event isARepeat];
2019-06-04 18:45:49 +02:00
ke.scancode = remapKey([event keyCode], [event modifierFlags]);
2019-06-04 09:30:59 +02:00
ke.raw = true;
ke.unicode = [characters characterAtIndex:i];
2017-05-22 04:02:35 +02:00
2019-06-04 09:30:59 +02:00
push_to_key_event_buffer(ke);
}
} else {
OS_OSX::KeyEvent ke;
ke.osx_state = [event modifierFlags];
ke.pressed = false;
ke.echo = [event isARepeat];
2019-06-04 18:45:49 +02:00
ke.scancode = remapKey([event keyCode], [event modifierFlags]);
2019-06-04 09:30:59 +02:00
ke.raw = true;
ke.unicode = 0;
push_to_key_event_buffer(ke);
}
2018-01-10 12:22:28 +01:00
}
2014-02-10 02:10:30 +01:00
}
2017-05-22 11:17:14 +02:00
inline void sendScrollEvent(int button, double factor, int modifierFlags) {
2018-07-08 15:12:13 +02:00
unsigned int mask = 1 << (button - 1);
2019-03-06 14:34:52 +01:00
Vector2 mouse_pos = Vector2(mouse_x, mouse_y);
2018-07-08 15:12:13 +02:00
2017-05-22 04:02:35 +02:00
Ref<InputEventMouseButton> sc;
sc.instance();
2017-05-22 11:17:14 +02:00
get_key_modifier_state(modifierFlags, sc);
2017-05-22 04:02:35 +02:00
sc->set_button_index(button);
sc->set_factor(factor);
sc->set_pressed(true);
2017-06-03 10:54:24 +02:00
sc->set_position(mouse_pos);
sc->set_global_position(mouse_pos);
2018-07-08 15:12:13 +02:00
button_mask |= mask;
2017-05-22 04:02:35 +02:00
sc->set_button_mask(button_mask);
OS_OSX::singleton->push_input(sc);
2018-07-08 15:12:13 +02:00
2019-03-06 14:34:52 +01:00
sc.instance();
sc->set_button_index(button);
sc->set_factor(factor);
2017-05-22 04:02:35 +02:00
sc->set_pressed(false);
2019-03-06 14:34:52 +01:00
sc->set_position(mouse_pos);
sc->set_global_position(mouse_pos);
2018-07-08 15:12:13 +02:00
button_mask &= ~mask;
sc->set_button_mask(button_mask);
2017-05-22 04:02:35 +02:00
OS_OSX::singleton->push_input(sc);
2017-02-21 23:45:31 +01:00
}
2017-11-01 21:49:39 +01:00
inline void sendPanEvent(double dx, double dy, int modifierFlags) {
Ref<InputEventPanGesture> pg;
pg.instance();
get_key_modifier_state(modifierFlags, pg);
Vector2 mouse_pos = Vector2(mouse_x, mouse_y);
pg->set_position(mouse_pos);
pg->set_delta(Vector2(-dx, -dy));
OS_OSX::singleton->push_input(pg);
}
2017-04-09 13:22:40 +02:00
- (void)scrollWheel:(NSEvent *)event {
double deltaX, deltaY;
2014-02-10 02:10:30 +01:00
2020-07-07 20:37:05 +02:00
get_mouse_pos([event locationInWindow]);
2018-10-23 18:17:27 +02:00
2018-01-07 00:11:23 +01:00
deltaX = [event scrollingDeltaX];
deltaY = [event scrollingDeltaY];
2017-04-09 13:22:40 +02:00
2018-01-07 00:11:23 +01:00
if ([event hasPreciseScrollingDeltas]) {
deltaX *= 0.03;
deltaY *= 0.03;
2014-02-10 02:10:30 +01:00
}
2017-11-01 21:49:39 +01:00
if ([event phase] != NSEventPhaseNone || [event momentumPhase] != NSEventPhaseNone) {
sendPanEvent(deltaX, deltaY, [event modifierFlags]);
} else {
if (fabs(deltaX)) {
sendScrollEvent(0 > deltaX ? BUTTON_WHEEL_RIGHT : BUTTON_WHEEL_LEFT, fabs(deltaX * 0.3), [event modifierFlags]);
}
if (fabs(deltaY)) {
sendScrollEvent(0 < deltaY ? BUTTON_WHEEL_UP : BUTTON_WHEEL_DOWN, fabs(deltaY * 0.3), [event modifierFlags]);
}
2016-02-04 17:16:22 +01:00
}
2014-02-10 02:10:30 +01:00
}
@end
2017-04-09 14:18:49 +02:00
@interface GodotWindow : NSWindow {
}
2014-02-10 02:10:30 +01:00
@end
@implementation GodotWindow
2017-04-09 13:22:40 +02:00
- (BOOL)canBecomeKeyWindow {
// Required for NSBorderlessWindowMask windows
return YES;
2014-02-10 02:10:30 +01:00
}
@end
2019-02-06 14:57:06 +01:00
void OS_OSX::_update_global_menu() {
NSMenu *main_menu = [NSApp mainMenu];
2020-06-02 15:37:19 +02:00
for (int i = [main_menu numberOfItems] - 1; i > 0; i--) {
2019-02-06 14:57:06 +01:00
[main_menu removeItemAtIndex:i];
}
2020-06-02 15:37:19 +02:00
for (List<String>::Element *E = global_menus_order.front(); E; E = E->next()) {
Vector<GlobalMenuItem> &items = global_menus[E->get()];
NSMenu *menu = [[[NSMenu alloc] initWithTitle:[NSString stringWithUTF8String:E->get().utf8().get_data()]] autorelease];
for (int i = 0; i < items.size(); i++) {
if (items[i].label == String()) {
[menu addItem:[NSMenuItem separatorItem]];
} else {
NSMenuItem *menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:items[i].label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:@""];
[menu_item setRepresentedObject:[NSValue valueWithPointer:&(items[i])]];
2019-02-06 14:57:06 +01:00
}
}
2020-06-02 15:37:19 +02:00
NSMenuItem *menu_item = [main_menu addItemWithTitle:[NSString stringWithUTF8String:E->get().utf8().get_data()] action:nil keyEquivalent:@""];
[main_menu setSubmenu:menu forItem:menu_item];
2019-02-06 14:57:06 +01:00
}
}
void OS_OSX::global_menu_add_item(const String &p_menu, const String &p_label, const Variant &p_signal, const Variant &p_meta) {
2020-06-02 15:37:19 +02:00
if (!global_menus.has(p_menu) && (p_menu != "_dock")) {
global_menus_order.push_back(p_menu);
}
2019-02-06 14:57:06 +01:00
global_menus[p_menu].push_back(GlobalMenuItem(p_label, p_signal, p_meta));
_update_global_menu();
}
void OS_OSX::global_menu_add_separator(const String &p_menu) {
2020-06-02 15:37:19 +02:00
if (!global_menus.has(p_menu) && (p_menu != "_dock")) {
global_menus_order.push_back(p_menu);
}
2019-02-06 14:57:06 +01:00
global_menus[p_menu].push_back(GlobalMenuItem());
_update_global_menu();
}
void OS_OSX::global_menu_remove_item(const String &p_menu, int p_idx) {
ERR_FAIL_INDEX(p_idx, global_menus[p_menu].size());
global_menus[p_menu].remove(p_idx);
_update_global_menu();
}
void OS_OSX::global_menu_clear(const String &p_menu) {
2020-06-02 15:37:19 +02:00
if (global_menus.has(p_menu)) {
global_menus[p_menu].clear();
if (p_menu != "_dock") {
global_menus.erase(p_menu);
global_menus_order.erase(p_menu);
}
}
2019-02-06 14:57:06 +01:00
_update_global_menu();
}
2018-11-23 13:07:48 +01:00
Point2 OS_OSX::get_ime_selection() const {
return im_selection;
}
String OS_OSX::get_ime_text() const {
return im_text;
2017-08-07 13:09:56 +02:00
}
2018-01-20 16:17:39 +01:00
String OS_OSX::get_unique_id() const {
static String serial_number;
if (serial_number.empty()) {
io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"));
CFStringRef serialNumberAsCFString = NULL;
if (platformExpert) {
serialNumberAsCFString = (CFStringRef)IORegistryEntryCreateCFProperty(platformExpert, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0);
IOObjectRelease(platformExpert);
}
NSString *serialNumberAsNSString = nil;
if (serialNumberAsCFString) {
serialNumberAsNSString = [NSString stringWithString:(NSString *)serialNumberAsCFString];
CFRelease(serialNumberAsCFString);
}
serial_number = [serialNumberAsNSString UTF8String];
}
return serial_number;
}
2018-06-07 22:16:57 +02:00
void OS_OSX::set_ime_active(const bool p_active) {
2018-11-23 13:07:48 +01:00
2018-06-07 22:16:57 +02:00
im_active = p_active;
2018-11-23 13:07:48 +01:00
if (!im_active)
[window_view cancelComposition];
2018-06-07 22:16:57 +02:00
}
2017-08-07 13:09:56 +02:00
void OS_OSX::set_ime_position(const Point2 &p_pos) {
2018-11-23 13:07:48 +01:00
2017-08-07 13:09:56 +02:00
im_position = p_pos;
}
2014-02-10 02:10:30 +01:00
void OS_OSX::initialize_core() {
2017-09-08 03:01:49 +02:00
crash_handler.initialize();
2014-02-10 02:10:30 +01:00
OS_Unix::initialize_core();
2015-12-14 02:21:49 +01:00
DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_RESOURCES);
DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_USERDATA);
DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_FILESYSTEM);
2014-02-10 02:10:30 +01:00
SemaphoreOSX::make_default();
}
2020-06-12 14:51:51 +02:00
struct LayoutInfo {
String name;
String code;
};
static Vector<LayoutInfo> kbd_layouts;
static int current_layout = 0;
2015-01-08 08:26:27 +01:00
static bool keyboard_layout_dirty = true;
2020-06-12 14:51:51 +02:00
static OS::LatinKeyboardVariant latin_variant = OS::LATIN_KEYBOARD_QWERTY;
2017-11-03 11:00:29 +01:00
static void keyboard_layout_changed(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef user_info) {
2020-06-12 14:51:51 +02:00
kbd_layouts.clear();
current_layout = 0;
2015-01-08 08:26:27 +01:00
keyboard_layout_dirty = true;
}
2017-11-03 11:00:29 +01:00
static bool displays_arrangement_dirty = true;
2020-07-07 20:37:05 +02:00
static bool displays_scale_dirty = true;
2017-11-03 11:00:29 +01:00
static void displays_arrangement_changed(CGDirectDisplayID display_id, CGDisplayChangeSummaryFlags flags, void *user_info) {
displays_arrangement_dirty = true;
2020-07-07 20:37:05 +02:00
displays_scale_dirty = true;
2017-11-03 11:00:29 +01:00
}
2018-07-19 23:58:15 +02:00
int OS_OSX::get_current_video_driver() const {
return video_driver_index;
}
2018-01-03 18:26:44 +01:00
Error OS_OSX::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
2014-02-10 02:10:30 +01:00
/*** OSX INITIALIZATION ***/
/*** OSX INITIALIZATION ***/
/*** OSX INITIALIZATION ***/
2015-01-08 08:26:27 +01:00
keyboard_layout_dirty = true;
2017-11-03 11:00:29 +01:00
displays_arrangement_dirty = true;
2020-07-07 20:37:05 +02:00
displays_scale_dirty = true;
2015-01-08 08:26:27 +01:00
// Register to be notified on keyboard layout changes
CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
2017-11-03 11:00:29 +01:00
NULL, keyboard_layout_changed,
2017-04-09 14:18:49 +02:00
kTISNotifySelectedKeyboardInputSourceChanged, NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
2016-04-02 20:26:12 +02:00
2017-11-03 11:00:29 +01:00
// Register to be notified on displays arrangement changes
CGDisplayRegisterReconfigurationCallback(displays_arrangement_changed, NULL);
2014-02-10 02:10:30 +01:00
window_delegate = [[GodotWindowDelegate alloc] init];
2017-04-09 13:22:40 +02:00
// Don't use accumulation buffer support; it's not accelerated
// Aux buffers probably aren't accelerated either
2014-02-10 02:10:30 +01:00
2017-06-27 18:13:03 +02:00
unsigned int styleMask;
if (p_desired.borderless_window) {
styleMask = NSWindowStyleMaskBorderless;
} else {
2018-05-23 21:25:41 +02:00
resizable = p_desired.resizable;
2018-01-06 14:39:44 +01:00
styleMask = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (p_desired.resizable ? NSWindowStyleMaskResizable : 0);
2017-06-27 18:13:03 +02:00
}
2014-02-10 02:10:30 +01:00
2020-07-07 20:37:05 +02:00
float displayScale = get_screen_max_scale();
2014-02-10 02:10:30 +01:00
window_object = [[GodotWindow alloc]
2020-07-07 20:37:05 +02:00
initWithContentRect:NSMakeRect(0, 0, p_desired.width / displayScale, p_desired.height / displayScale)
2017-04-09 14:18:49 +02:00
styleMask:styleMask
backing:NSBackingStoreBuffered
defer:NO];
2014-02-10 02:10:30 +01:00
2018-01-04 17:32:33 +01:00
ERR_FAIL_COND_V(window_object == nil, ERR_UNAVAILABLE);
2014-02-10 02:10:30 +01:00
window_view = [[GodotContentView alloc] init];
2018-11-19 10:31:03 +01:00
if (NSAppKitVersionNumber >= NSAppKitVersionNumber10_14) {
2018-11-18 15:20:13 +01:00
[window_view setWantsLayer:TRUE];
}
2014-02-10 02:10:30 +01:00
2020-07-07 20:37:05 +02:00
window_size.width = p_desired.width;
window_size.height = p_desired.height;
2014-02-19 04:48:38 +01:00
2018-01-07 00:11:23 +01:00
if (displayScale > 1.0) {
2017-04-09 13:22:40 +02:00
[window_view setWantsBestResolutionOpenGLSurface:YES];
//if (current_videomode.resizable)
2014-02-10 02:10:30 +01:00
[window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
2019-10-13 22:15:20 +02:00
} else {
[window_view setWantsBestResolutionOpenGLSurface:NO];
2014-02-10 02:10:30 +01:00
}
2017-01-14 12:26:56 +01:00
//[window_object setTitle:[NSString stringWithUTF8String:"GodotEnginies"]];
2014-02-10 02:10:30 +01:00
[window_object setContentView:window_view];
[window_object setDelegate:window_delegate];
[window_object setAcceptsMouseMovedEvents:YES];
2019-10-24 16:34:18 +02:00
[(NSWindow *)window_object center];
2014-02-10 02:10:30 +01:00
2018-01-07 00:11:23 +01:00
[window_object setRestorable:NO];
2014-02-10 02:10:30 +01:00
unsigned int attributeCount = 0;
2018-02-21 17:30:55 +01:00
// OS X needs non-zero color size, so set reasonable values
2015-04-01 17:39:54 +02:00
int colorBits = 32;
2014-02-10 02:10:30 +01:00
2017-12-06 21:36:34 +01:00
// Fail if a robustness strategy was requested
2014-02-10 02:10:30 +01:00
2017-04-09 14:18:49 +02:00
#define ADD_ATTR(x) \
{ attributes[attributeCount++] = x; }
#define ADD_ATTR2(x, y) \
{ \
ADD_ATTR(x); \
ADD_ATTR(y); \
}
2014-02-10 02:10:30 +01:00
// Arbitrary array size here
NSOpenGLPixelFormatAttribute attributes[40];
ADD_ATTR(NSOpenGLPFADoubleBuffer);
ADD_ATTR(NSOpenGLPFAClosestPolicy);
2018-03-02 11:38:44 +01:00
if (p_video_driver == VIDEO_DRIVER_GLES2) {
ADD_ATTR2(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersionLegacy);
} else {
//we now need OpenGL 3 or better, maybe even change this to 3_3Core ?
ADD_ATTR2(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core);
}
2014-02-10 02:10:30 +01:00
ADD_ATTR2(NSOpenGLPFAColorSize, colorBits);
2017-04-09 14:18:49 +02:00
/*
2017-04-09 13:22:40 +02:00
if (fbconfig->alphaBits > 0)
ADD_ATTR2(NSOpenGLPFAAlphaSize, fbconfig->alphaBits);
*/
2014-02-10 02:10:30 +01:00
ADD_ATTR2(NSOpenGLPFADepthSize, 24);
ADD_ATTR2(NSOpenGLPFAStencilSize, 8);
2017-04-09 14:18:49 +02:00
/*
2017-04-09 13:22:40 +02:00
if (fbconfig->stereo)
ADD_ATTR(NSOpenGLPFAStereo);
*/
2014-02-10 02:10:30 +01:00
2017-04-09 14:18:49 +02:00
/*
2017-04-09 13:22:40 +02:00
if (fbconfig->samples > 0) {
ADD_ATTR2(NSOpenGLPFASampleBuffers, 1);
ADD_ATTR2(NSOpenGLPFASamples, fbconfig->samples);
}
*/
2014-02-10 02:10:30 +01:00
// NOTE: All NSOpenGLPixelFormats on the relevant cards support sRGB
2018-02-21 17:30:55 +01:00
// framebuffer, so there's no need (and no way) to request it
2014-02-10 02:10:30 +01:00
ADD_ATTR(0);
#undef ADD_ATTR
#undef ADD_ATTR2
pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes];
2018-01-04 17:32:33 +01:00
ERR_FAIL_COND_V(pixelFormat == nil, ERR_UNAVAILABLE);
2014-02-10 02:10:30 +01:00
2017-04-09 13:22:40 +02:00
context = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:nil];
2014-02-10 02:10:30 +01:00
2018-01-04 17:32:33 +01:00
ERR_FAIL_COND_V(context == nil, ERR_UNAVAILABLE);
2014-02-10 02:10:30 +01:00
2020-06-29 13:24:56 +02:00
[window_view setOpenGLContext:context];
2014-02-10 02:10:30 +01:00
[context makeCurrentContext];
2020-07-07 20:37:05 +02:00
GLint dim[2];
dim[0] = window_size.width;
dim[1] = window_size.height;
CGLSetParameter((CGLContextObj)[context CGLContextObj], kCGLCPSurfaceBackingSize, &dim[0]);
CGLEnable((CGLContextObj)[context CGLContextObj], kCGLCESurfaceBackingSize);
2017-12-08 17:58:28 +01:00
set_use_vsync(p_desired.use_vsync);
2014-02-10 02:10:30 +01:00
[NSApp activateIgnoringOtherApps:YES];
2017-07-03 03:44:42 +02:00
_update_window();
2015-05-05 12:02:47 +02:00
[window_object makeKeyAndOrderFront:nil];
2014-02-10 02:10:30 +01:00
2020-08-15 16:50:04 +02:00
on_top = p_desired.always_on_top;
if (p_desired.always_on_top) {
[window_object setLevel:NSFloatingWindowLevel];
}
2015-05-05 12:02:47 +02:00
if (p_desired.fullscreen)
2015-05-06 12:53:55 +02:00
zoomed = true;
2014-02-10 02:10:30 +01:00
/*** END OSX INITIALIZATION ***/
2018-08-25 00:04:25 +02:00
bool gles3 = true;
2018-03-02 11:38:44 +01:00
if (p_video_driver == VIDEO_DRIVER_GLES2) {
2018-08-25 00:04:25 +02:00
gles3 = false;
}
bool editor = Engine::get_singleton()->is_editor_hint();
bool gl_initialization_error = false;
while (true) {
if (gles3) {
if (RasterizerGLES3::is_viable() == OK) {
RasterizerGLES3::register_config();
RasterizerGLES3::make_current();
break;
} else {
2019-03-05 13:46:51 +01:00
if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) {
2018-08-25 00:04:25 +02:00
p_video_driver = VIDEO_DRIVER_GLES2;
gles3 = false;
continue;
} else {
gl_initialization_error = true;
break;
}
}
} else {
if (RasterizerGLES2::is_viable() == OK) {
RasterizerGLES2::register_config();
RasterizerGLES2::make_current();
break;
} else {
gl_initialization_error = true;
break;
}
}
}
if (gl_initialization_error) {
OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n"
"Please update your drivers or if you have a very old or integrated GPU upgrade it.",
"Unable to initialize Video driver");
return ERR_UNAVAILABLE;
2018-03-02 11:38:44 +01:00
}
2014-02-10 02:10:30 +01:00
2018-08-25 00:04:25 +02:00
video_driver_index = p_video_driver;
2018-11-01 19:22:15 +01:00
visual_server = memnew(VisualServerRaster);
2017-06-10 15:15:33 +02:00
if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
2017-01-14 12:26:56 +01:00
}
2014-02-10 02:10:30 +01:00
2018-08-25 00:04:25 +02:00
visual_server->init();
2017-09-13 18:34:22 +02:00
AudioDriverManager::initialize(p_audio_driver);
2014-02-10 02:10:30 +01:00
2017-04-09 14:18:49 +02:00
input = memnew(InputDefault);
joypad_osx = memnew(JoypadOSX);
2014-02-10 02:10:30 +01:00
2019-02-12 15:43:54 +01:00
power_manager = memnew(PowerOSX);
2016-07-23 13:15:55 +02:00
2017-11-17 15:25:22 +01:00
_ensure_user_data_dir();
2014-02-10 02:10:30 +01:00
2015-04-02 06:32:02 +02:00
restore_rect = Rect2(get_window_position(), get_window_size());
2018-01-03 18:26:44 +01:00
2019-06-04 10:21:29 +02:00
if (p_desired.layered) {
2017-12-10 19:38:26 +01:00
set_window_per_pixel_transparency_enabled(true);
}
2019-06-18 21:44:29 +02:00
update_real_mouse_position();
2018-01-03 18:26:44 +01:00
return OK;
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
2014-02-10 02:10:30 +01:00
void OS_OSX::finalize() {
2018-10-25 15:59:26 +02:00
#ifdef COREMIDI_ENABLED
2018-08-04 02:17:33 +02:00
midi_driver.close();
2018-10-25 15:59:26 +02:00
#endif
2018-08-04 02:17:33 +02:00
2015-01-08 08:26:27 +01:00
CFNotificationCenterRemoveObserver(CFNotificationCenterGetDistributedCenter(), NULL, kTISNotifySelectedKeyboardInputSourceChanged, NULL);
2017-11-03 11:00:29 +01:00
CGDisplayRemoveReconfigurationCallback(displays_arrangement_changed, NULL);
2015-12-31 14:25:21 +01:00
delete_main_loop();
2017-01-08 21:29:57 +01:00
memdelete(joypad_osx);
2015-12-31 14:25:21 +01:00
memdelete(input);
2019-07-24 19:57:59 +02:00
cursors_cache.clear();
2015-12-31 14:25:21 +01:00
visual_server->finish();
memdelete(visual_server);
2017-01-14 12:26:56 +01:00
//memdelete(rasterizer);
2014-02-10 02:10:30 +01:00
}
2017-04-09 14:18:49 +02:00
void OS_OSX::set_main_loop(MainLoop *p_main_loop) {
2014-02-10 02:10:30 +01:00
2017-04-09 14:18:49 +02:00
main_loop = p_main_loop;
2014-02-10 02:10:30 +01:00
input->set_main_loop(p_main_loop);
}
void OS_OSX::delete_main_loop() {
2015-12-31 14:25:21 +01:00
if (!main_loop)
return;
2014-02-10 02:10:30 +01:00
memdelete(main_loop);
2017-04-09 14:18:49 +02:00
main_loop = NULL;
2014-02-10 02:10:30 +01:00
}
2019-05-20 19:36:24 +02:00
String OS_OSX::get_name() const {
2014-02-10 02:10:30 +01:00
return "OSX";
}
2017-08-06 20:55:30 +02:00
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
2017-09-22 07:56:02 +02:00
class OSXTerminalLogger : public StdLogger {
public:
virtual void log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type = ERR_ERROR) {
if (!should_log(true)) {
return;
}
2017-08-06 20:55:30 +02:00
2017-09-22 07:56:02 +02:00
const char *err_details;
if (p_rationale && p_rationale[0])
err_details = p_rationale;
else
err_details = p_code;
switch (p_type) {
case ERR_WARNING:
2018-11-19 10:31:03 +01:00
if (NSAppKitVersionNumber >= NSAppKitVersionNumber10_12) {
2018-01-07 00:11:23 +01:00
os_log_info(OS_LOG_DEFAULT,
"WARNING: %{public}s: %{public}s\nAt: %{public}s:%i.",
p_function, err_details, p_file, p_line);
}
2017-09-22 07:56:02 +02:00
logf_error("\E[1;33mWARNING: %s: \E[0m\E[1m%s\n", p_function,
err_details);
logf_error("\E[0;33m At: %s:%i.\E[0m\n", p_file, p_line);
break;
case ERR_SCRIPT:
2018-11-19 10:31:03 +01:00
if (NSAppKitVersionNumber >= NSAppKitVersionNumber10_12) {
2018-01-07 00:11:23 +01:00
os_log_error(OS_LOG_DEFAULT,
"SCRIPT ERROR: %{public}s: %{public}s\nAt: %{public}s:%i.",
p_function, err_details, p_file, p_line);
}
2017-09-22 07:56:02 +02:00
logf_error("\E[1;35mSCRIPT ERROR: %s: \E[0m\E[1m%s\n", p_function,
err_details);
logf_error("\E[0;35m At: %s:%i.\E[0m\n", p_file, p_line);
break;
case ERR_SHADER:
2018-11-19 10:31:03 +01:00
if (NSAppKitVersionNumber >= NSAppKitVersionNumber10_12) {
2018-01-07 00:11:23 +01:00
os_log_error(OS_LOG_DEFAULT,
"SHADER ERROR: %{public}s: %{public}s\nAt: %{public}s:%i.",
p_function, err_details, p_file, p_line);
}
2017-09-22 07:56:02 +02:00
logf_error("\E[1;36mSHADER ERROR: %s: \E[0m\E[1m%s\n", p_function,
err_details);
logf_error("\E[0;36m At: %s:%i.\E[0m\n", p_file, p_line);
break;
case ERR_ERROR:
default:
2018-11-19 10:31:03 +01:00
if (NSAppKitVersionNumber >= NSAppKitVersionNumber10_12) {
2018-01-07 00:11:23 +01:00
os_log_error(OS_LOG_DEFAULT,
"ERROR: %{public}s: %{public}s\nAt: %{public}s:%i.",
p_function, err_details, p_file, p_line);
}
2017-09-22 07:56:02 +02:00
logf_error("\E[1;31mERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
logf_error("\E[0;31m At: %s:%i.\E[0m\n", p_file, p_line);
break;
}
2017-08-06 20:55:30 +02:00
}
2017-09-22 07:56:02 +02:00
};
2017-08-06 20:55:30 +02:00
#else
2017-09-22 07:56:02 +02:00
typedef UnixTerminalLogger OSXTerminalLogger;
2017-08-06 20:55:30 +02:00
#endif
2017-09-22 07:56:02 +02:00
2017-04-09 14:18:49 +02:00
void OS_OSX::alert(const String &p_alert, const String &p_title) {
2016-06-22 17:58:31 +02:00
// Set OS X-compliant variables
NSAlert *window = [[NSAlert alloc] init];
NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
NSString *ns_alert = [NSString stringWithUTF8String:p_alert.utf8().get_data()];
[window addButtonWithTitle:@"OK"];
[window setMessageText:ns_title];
[window setInformativeText:ns_alert];
2020-06-29 13:24:56 +02:00
[window setAlertStyle:NSAlertStyleWarning];
2016-06-22 17:58:31 +02:00
// Display it, then release
2020-07-26 22:00:30 +02:00
id key_window = [[NSApplication sharedApplication] keyWindow];
2016-06-22 17:58:31 +02:00
[window runModal];
[window release];
2020-07-26 22:00:30 +02:00
if (key_window) {
[key_window makeKeyAndOrderFront:nil];
}
2016-06-22 17:58:31 +02:00
}
2018-01-04 20:36:44 +01:00
Error OS_OSX::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
String path = p_path;
if (!FileAccess::exists(path)) {
//this code exists so gdnative can load .dylib files from within the executable path
path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
}
if (!FileAccess::exists(path)) {
//this code exists so gdnative can load .dylib files from a standard macOS location
path = get_executable_path().get_base_dir().plus_file("../Frameworks").plus_file(p_path.get_file());
}
p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
2019-08-09 06:49:33 +02:00
ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ", error: " + dlerror() + ".");
2018-01-04 20:36:44 +01:00
return OK;
}
2014-02-10 02:10:30 +01:00
void OS_OSX::set_cursor_shape(CursorShape p_shape) {
2017-04-09 14:18:49 +02:00
if (cursor_shape == p_shape)
2014-02-10 02:10:30 +01:00
return;
2018-05-21 00:07:25 +02:00
if (mouse_mode != MOUSE_MODE_VISIBLE && mouse_mode != MOUSE_MODE_CONFINED) {
2018-04-09 02:59:51 +02:00
cursor_shape = p_shape;
return;
}
2017-11-10 11:50:11 +01:00
if (cursors[p_shape] != NULL) {
[cursors[p_shape] set];
} else {
switch (p_shape) {
case CURSOR_ARROW: [[NSCursor arrowCursor] set]; break;
case CURSOR_IBEAM: [[NSCursor IBeamCursor] set]; break;
case CURSOR_POINTING_HAND: [[NSCursor pointingHandCursor] set]; break;
case CURSOR_CROSS: [[NSCursor crosshairCursor] set]; break;
case CURSOR_WAIT: [[NSCursor arrowCursor] set]; break;
case CURSOR_BUSY: [[NSCursor arrowCursor] set]; break;
case CURSOR_DRAG: [[NSCursor closedHandCursor] set]; break;
case CURSOR_CAN_DROP: [[NSCursor openHandCursor] set]; break;
2020-01-31 05:40:13 +01:00
case CURSOR_FORBIDDEN: [[NSCursor operationNotAllowedCursor] set]; break;
case CURSOR_VSIZE: [cursorFromSelector(@selector(_windowResizeNorthSouthCursor), @selector(resizeUpDownCursor)) set]; break;
case CURSOR_HSIZE: [cursorFromSelector(@selector(_windowResizeEastWestCursor), @selector(resizeLeftRightCursor)) set]; break;
case CURSOR_BDIAGSIZE: [cursorFromSelector(@selector(_windowResizeNorthEastSouthWestCursor)) set]; break;
case CURSOR_FDIAGSIZE: [cursorFromSelector(@selector(_windowResizeNorthWestSouthEastCursor)) set]; break;
2017-11-10 11:50:11 +01:00
case CURSOR_MOVE: [[NSCursor arrowCursor] set]; break;
case CURSOR_VSPLIT: [[NSCursor resizeUpDownCursor] set]; break;
case CURSOR_HSPLIT: [[NSCursor resizeLeftRightCursor] set]; break;
2020-01-31 05:40:13 +01:00
case CURSOR_HELP: [cursorFromSelector(@selector(_helpCursor)) set]; break;
2019-01-11 15:53:11 +01:00
default: {
};
2017-11-10 11:50:11 +01:00
}
2014-02-10 02:10:30 +01:00
}
2017-04-09 14:18:49 +02:00
cursor_shape = p_shape;
2014-02-10 02:10:30 +01:00
}
2019-04-15 17:30:20 +02:00
OS::CursorShape OS_OSX::get_cursor_shape() const {
return cursor_shape;
}
2017-11-10 11:50:11 +01:00
void OS_OSX::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
2019-07-08 22:37:18 +02:00
2017-11-10 11:50:11 +01:00
if (p_cursor.is_valid()) {
2019-07-08 22:37:18 +02:00
Map<CursorShape, Vector<Variant> >::Element *cursor_c = cursors_cache.find(p_shape);
if (cursor_c) {
if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) {
set_cursor_shape(p_shape);
return;
}
cursors_cache.erase(p_shape);
}
2017-11-10 11:50:11 +01:00
Ref<Texture> texture = p_cursor;
2018-05-08 16:07:43 +02:00
Ref<AtlasTexture> atlas_texture = p_cursor;
Ref<Image> image;
Size2 texture_size;
Rect2 atlas_rect;
2017-11-10 11:50:11 +01:00
2018-05-08 16:07:43 +02:00
if (texture.is_valid()) {
image = texture->get_data();
}
if (!image.is_valid() && atlas_texture.is_valid()) {
texture = atlas_texture->get_atlas();
atlas_rect.size.width = texture->get_width();
atlas_rect.size.height = texture->get_height();
atlas_rect.position.x = atlas_texture->get_region().position.x;
atlas_rect.position.y = atlas_texture->get_region().position.y;
texture_size.width = atlas_texture->get_region().size.x;
texture_size.height = atlas_texture->get_region().size.y;
} else if (image.is_valid()) {
texture_size.width = texture->get_width();
texture_size.height = texture->get_height();
}
ERR_FAIL_COND(!texture.is_valid());
2018-09-04 04:42:23 +02:00
ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
2018-05-08 16:07:43 +02:00
ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
2018-09-03 14:21:13 +02:00
ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
2018-05-08 16:07:43 +02:00
image = texture->get_data();
2017-11-10 11:50:11 +01:00
2018-05-28 14:36:30 +02:00
ERR_FAIL_COND(!image.is_valid());
2018-05-26 20:58:12 +02:00
NSBitmapImageRep *imgrep = [[NSBitmapImageRep alloc]
2017-11-10 11:50:11 +01:00
initWithBitmapDataPlanes:NULL
2018-05-08 16:07:43 +02:00
pixelsWide:int(texture_size.width)
pixelsHigh:int(texture_size.height)
2017-11-10 11:50:11 +01:00
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSDeviceRGBColorSpace
2018-05-08 16:07:43 +02:00
bytesPerRow:int(texture_size.width) * 4
2018-05-26 20:58:12 +02:00
bitsPerPixel:32];
2017-11-10 11:50:11 +01:00
ERR_FAIL_COND(imgrep == nil);
uint8_t *pixels = [imgrep bitmapData];
2018-05-08 16:07:43 +02:00
int len = int(texture_size.width * texture_size.height);
2017-11-10 11:50:11 +01:00
PoolVector<uint8_t> data = image->get_data();
PoolVector<uint8_t>::Read r = data.read();
2018-05-08 16:07:43 +02:00
image->lock();
2017-11-10 11:50:11 +01:00
/* Premultiply the alpha channel */
for (int i = 0; i < len; i++) {
2018-05-08 16:07:43 +02:00
int row_index = floor(i / texture_size.width) + atlas_rect.position.y;
int column_index = (i % int(texture_size.width)) + atlas_rect.position.x;
if (atlas_texture.is_valid()) {
column_index = MIN(column_index, atlas_rect.size.width - 1);
row_index = MIN(row_index, atlas_rect.size.height - 1);
}
uint32_t color = image->get_pixel(column_index, row_index).to_argb32();
uint8_t alpha = (color >> 24) & 0xFF;
pixels[i * 4 + 0] = ((color >> 16) & 0xFF) * alpha / 255;
pixels[i * 4 + 1] = ((color >> 8) & 0xFF) * alpha / 255;
pixels[i * 4 + 2] = ((color)&0xFF) * alpha / 255;
2017-11-10 11:50:11 +01:00
pixels[i * 4 + 3] = alpha;
}
2018-05-08 16:07:43 +02:00
image->unlock();
2018-05-26 20:58:12 +02:00
NSImage *nsimage = [[NSImage alloc] initWithSize:NSMakeSize(texture_size.width, texture_size.height)];
2017-11-10 11:50:11 +01:00
[nsimage addRepresentation:imgrep];
NSCursor *cursor = [[NSCursor alloc] initWithImage:nsimage hotSpot:NSMakePoint(p_hotspot.x, p_hotspot.y)];
2018-05-26 20:58:12 +02:00
[cursors[p_shape] release];
2017-11-10 11:50:11 +01:00
cursors[p_shape] = cursor;
2019-07-08 22:37:18 +02:00
Vector<Variant> params;
params.push_back(p_cursor);
params.push_back(p_hotspot);
cursors_cache.insert(p_shape, params);
2018-09-13 19:53:20 +02:00
if (p_shape == cursor_shape) {
2018-09-17 16:37:54 +02:00
if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
[cursor set];
}
2017-11-10 11:50:11 +01:00
}
2018-05-26 20:58:12 +02:00
[imgrep release];
[nsimage release];
2018-05-11 00:17:00 +02:00
} else {
// Reset to default system cursor
2019-10-03 13:02:11 +02:00
if (cursors[p_shape] != NULL) {
[cursors[p_shape] release];
cursors[p_shape] = NULL;
}
2018-09-13 19:53:20 +02:00
CursorShape c = cursor_shape;
2018-05-11 00:17:00 +02:00
cursor_shape = CURSOR_MAX;
2018-09-13 19:53:20 +02:00
set_cursor_shape(c);
2019-10-03 13:02:11 +02:00
cursors_cache.erase(p_shape);
2017-11-10 11:50:11 +01:00
}
}
2014-02-10 02:10:30 +01:00
void OS_OSX::set_mouse_show(bool p_show) {
}
2017-04-09 13:22:40 +02:00
2014-02-10 02:10:30 +01:00
void OS_OSX::set_mouse_grab(bool p_grab) {
}
2017-04-09 13:22:40 +02:00
2014-02-10 02:10:30 +01:00
bool OS_OSX::is_mouse_grab_enabled() const {
return mouse_grab;
}
2014-09-20 02:01:41 +02:00
2017-09-10 15:37:49 +02:00
void OS_OSX::warp_mouse_position(const Point2 &p_to) {
2014-09-20 02:01:41 +02:00
2017-04-09 13:22:40 +02:00
//copied from windows impl with osx native calls
2017-04-09 14:18:49 +02:00
if (mouse_mode == MOUSE_MODE_CAPTURED) {
2017-04-09 13:22:40 +02:00
mouse_x = p_to.x;
mouse_y = p_to.y;
} else { //set OS position
2016-04-02 20:26:12 +02:00
2017-04-09 13:22:40 +02:00
//local point in window coords
2017-08-04 22:40:03 +02:00
const NSRect contentRect = [window_view frame];
2020-07-07 20:37:05 +02:00
float displayScale = get_screen_max_scale();
2017-09-30 12:50:30 +02:00
NSRect pointInWindowRect = NSMakeRect(p_to.x / displayScale, contentRect.size.height - (p_to.y / displayScale) - 1, 0, 0);
2017-04-09 13:22:40 +02:00
NSPoint pointOnScreen = [[window_view window] convertRectToScreen:pointInWindowRect].origin;
2015-02-14 23:22:06 +01:00
2017-04-09 13:22:40 +02:00
//point in scren coords
2017-08-04 22:40:03 +02:00
CGPoint lMouseWarpPos = { pointOnScreen.x, CGDisplayBounds(CGMainDisplayID()).size.height - pointOnScreen.y };
2015-02-14 23:22:06 +01:00
2017-04-09 13:22:40 +02:00
//do the warping
CGEventSourceRef lEventRef = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventSourceSetLocalEventsSuppressionInterval(lEventRef, 0.0);
CGAssociateMouseAndMouseCursorPosition(false);
CGWarpMouseCursorPosition(lMouseWarpPos);
2020-07-02 14:57:19 +02:00
if (mouse_mode != MOUSE_MODE_CONFINED) {
CGAssociateMouseAndMouseCursorPosition(true);
}
2017-04-09 13:22:40 +02:00
}
2014-09-20 02:01:41 +02:00
}
2019-06-18 21:44:29 +02:00
void OS_OSX::update_real_mouse_position() {
2020-07-07 20:37:05 +02:00
get_mouse_pos([window_object mouseLocationOutsideOfEventStream]);
2019-06-18 21:44:29 +02:00
input->set_mouse_position(Point2(mouse_x, mouse_y));
}
2017-03-29 17:29:38 +02:00
Point2 OS_OSX::get_mouse_position() const {
2014-02-10 02:10:30 +01:00
2017-04-09 14:18:49 +02:00
return Vector2(mouse_x, mouse_y);
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
2014-02-10 02:10:30 +01:00
int OS_OSX::get_mouse_button_state() const {
return button_mask;
}
2017-04-09 13:22:40 +02:00
2017-04-09 14:18:49 +02:00
void OS_OSX::set_window_title(const String &p_title) {
2017-06-27 18:13:03 +02:00
title = p_title;
2014-02-10 02:10:30 +01:00
[window_object setTitle:[NSString stringWithUTF8String:p_title.utf8().get_data()]];
}
2020-06-29 11:31:13 +02:00
void OS_OSX::set_window_mouse_passthrough(const PoolVector2Array &p_region) {
mpath.clear();
for (int i = 0; i < p_region.size(); i++) {
mpath.push_back(p_region[i]);
}
}
2019-05-17 15:43:56 +02:00
void OS_OSX::set_native_icon(const String &p_filename) {
FileAccess *f = FileAccess::open(p_filename, FileAccess::READ);
ERR_FAIL_COND(!f);
Vector<uint8_t> data;
uint32_t len = f->get_len();
data.resize(len);
f->get_buffer((uint8_t *)&data.write[0], len);
memdelete(f);
NSData *icon_data = [[[NSData alloc] initWithBytes:&data.write[0] length:len] autorelease];
2019-08-09 06:49:33 +02:00
ERR_FAIL_COND_MSG(!icon_data, "Error reading icon data.");
2019-05-17 15:43:56 +02:00
NSImage *icon = [[[NSImage alloc] initWithData:icon_data] autorelease];
2019-08-09 06:49:33 +02:00
ERR_FAIL_COND_MSG(!icon, "Error loading icon.");
2019-05-17 15:43:56 +02:00
[NSApp setApplicationIconImage:icon];
}
2017-05-17 12:36:47 +02:00
void OS_OSX::set_icon(const Ref<Image> &p_icon) {
2014-02-10 02:10:30 +01:00
2017-05-17 12:36:47 +02:00
Ref<Image> img = p_icon;
img = img->duplicate();
img->convert(Image::FORMAT_RGBA8);
2017-04-09 14:18:49 +02:00
NSBitmapImageRep *imgrep = [[[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:NULL
2017-05-17 12:36:47 +02:00
pixelsWide:img->get_width()
pixelsHigh:img->get_height()
2017-04-09 14:18:49 +02:00
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSDeviceRGBColorSpace
2017-05-17 12:36:47 +02:00
bytesPerRow:img->get_width() * 4
2017-04-09 14:18:49 +02:00
bitsPerPixel:32] autorelease];
2017-04-09 13:22:40 +02:00
ERR_FAIL_COND(imgrep == nil);
2014-02-10 02:10:30 +01:00
uint8_t *pixels = [imgrep bitmapData];
2017-05-17 12:36:47 +02:00
int len = img->get_width() * img->get_height();
PoolVector<uint8_t> data = img->get_data();
2017-01-07 22:25:37 +01:00
PoolVector<uint8_t>::Read r = data.read();
2014-02-10 02:10:30 +01:00
/* Premultiply the alpha channel */
2017-04-09 14:18:49 +02:00
for (int i = 0; i < len; i++) {
uint8_t alpha = r[i * 4 + 3];
pixels[i * 4 + 0] = (uint8_t)(((uint16_t)r[i * 4 + 0] * alpha) / 255);
pixels[i * 4 + 1] = (uint8_t)(((uint16_t)r[i * 4 + 1] * alpha) / 255);
pixels[i * 4 + 2] = (uint8_t)(((uint16_t)r[i * 4 + 2] * alpha) / 255);
pixels[i * 4 + 3] = alpha;
2014-02-10 02:10:30 +01:00
}
2017-05-17 12:36:47 +02:00
NSImage *nsimg = [[[NSImage alloc] initWithSize:NSMakeSize(img->get_width(), img->get_height())] autorelease];
2014-02-10 02:10:30 +01:00
ERR_FAIL_COND(nsimg == nil);
2017-04-09 14:18:49 +02:00
[nsimg addRepresentation:imgrep];
2014-02-10 02:10:30 +01:00
[NSApp setApplicationIconImage:nsimg];
}
MainLoop *OS_OSX::get_main_loop() const {
return main_loop;
}
Add initial support for the XDG Base Directory spec
Spec version 0.7 from https://standards.freedesktop.org/basedir-spec/basedir-spec-0.7.html
(latest as of this commit).
Three virtual methods are added to OS for the various XDG paths we will use:
- OS::get_data_path gives XDG_DATA_HOME, or if missing:
~/.local/share on X11, ~/Library/Application Support/ on macOS and %APPDATA% on Windows
- OS::get_config_path gives XDG_CONFIG_HOME, or if missing:
~/.config on X11, ~/Library/Application Support/ on macOS and %APPDATA% on Windows
- OS::get_cache_path gives XDG_CACHE_HOME, or if missing:
~/.cache on X11, ~/Library/Caches on macOS and %APPDATA% on Windows
So for Windows there are no changes, for Linux we follow the full split spec
and for macOS stuff will move from ~/.godot to ~/Library/Application Support/Godot.
Support for system-wide installation of templates on Unix was removed for now,
as it's a bit hackish and I don't think anyone uses it.
user:// will still be OS::get_data_path() + "/godot/app_userdata/$name" by
default, but when using the application/config/use_shared_user_dir option
it will now use XDG_DATA_HOME/$name, e.g. ~/.local/share/MyGame.
For now everything still goes in EditorSettings::get_settings_dir(), but
this will be changed in a later commit to make use of the new splitting
where relevant.
Part of #3513.
2017-11-17 17:11:41 +01:00
String OS_OSX::get_config_path() const {
if (has_environment("XDG_CONFIG_HOME")) {
return get_environment("XDG_CONFIG_HOME");
} else if (has_environment("HOME")) {
return get_environment("HOME").plus_file("Library/Application Support");
} else {
return ".";
}
}
String OS_OSX::get_data_path() const {
if (has_environment("XDG_DATA_HOME")) {
return get_environment("XDG_DATA_HOME");
} else {
return get_config_path();
}
}
String OS_OSX::get_cache_path() const {
if (has_environment("XDG_CACHE_HOME")) {
return get_environment("XDG_CACHE_HOME");
} else if (has_environment("HOME")) {
return get_environment("HOME").plus_file("Library/Caches");
} else {
return get_config_path();
}
}
2020-01-10 17:02:29 +01:00
String OS_OSX::get_bundle_resource_dir() const {
NSBundle *main = [NSBundle mainBundle];
NSString *resourcePath = [main resourcePath];
char *utfs = strdup([resourcePath UTF8String]);
String ret;
ret.parse_utf8(utfs);
free(utfs);
return ret;
}
Add initial support for the XDG Base Directory spec
Spec version 0.7 from https://standards.freedesktop.org/basedir-spec/basedir-spec-0.7.html
(latest as of this commit).
Three virtual methods are added to OS for the various XDG paths we will use:
- OS::get_data_path gives XDG_DATA_HOME, or if missing:
~/.local/share on X11, ~/Library/Application Support/ on macOS and %APPDATA% on Windows
- OS::get_config_path gives XDG_CONFIG_HOME, or if missing:
~/.config on X11, ~/Library/Application Support/ on macOS and %APPDATA% on Windows
- OS::get_cache_path gives XDG_CACHE_HOME, or if missing:
~/.cache on X11, ~/Library/Caches on macOS and %APPDATA% on Windows
So for Windows there are no changes, for Linux we follow the full split spec
and for macOS stuff will move from ~/.godot to ~/Library/Application Support/Godot.
Support for system-wide installation of templates on Unix was removed for now,
as it's a bit hackish and I don't think anyone uses it.
user:// will still be OS::get_data_path() + "/godot/app_userdata/$name" by
default, but when using the application/config/use_shared_user_dir option
it will now use XDG_DATA_HOME/$name, e.g. ~/.local/share/MyGame.
For now everything still goes in EditorSettings::get_settings_dir(), but
this will be changed in a later commit to make use of the new splitting
where relevant.
Part of #3513.
2017-11-17 17:11:41 +01:00
// Get properly capitalized engine name for system paths
String OS_OSX::get_godot_dir_name() const {
2017-11-19 21:18:01 +01:00
return String(VERSION_SHORT_NAME).capitalize();
Add initial support for the XDG Base Directory spec
Spec version 0.7 from https://standards.freedesktop.org/basedir-spec/basedir-spec-0.7.html
(latest as of this commit).
Three virtual methods are added to OS for the various XDG paths we will use:
- OS::get_data_path gives XDG_DATA_HOME, or if missing:
~/.local/share on X11, ~/Library/Application Support/ on macOS and %APPDATA% on Windows
- OS::get_config_path gives XDG_CONFIG_HOME, or if missing:
~/.config on X11, ~/Library/Application Support/ on macOS and %APPDATA% on Windows
- OS::get_cache_path gives XDG_CACHE_HOME, or if missing:
~/.cache on X11, ~/Library/Caches on macOS and %APPDATA% on Windows
So for Windows there are no changes, for Linux we follow the full split spec
and for macOS stuff will move from ~/.godot to ~/Library/Application Support/Godot.
Support for system-wide installation of templates on Unix was removed for now,
as it's a bit hackish and I don't think anyone uses it.
user:// will still be OS::get_data_path() + "/godot/app_userdata/$name" by
default, but when using the application/config/use_shared_user_dir option
it will now use XDG_DATA_HOME/$name, e.g. ~/.local/share/MyGame.
For now everything still goes in EditorSettings::get_settings_dir(), but
this will be changed in a later commit to make use of the new splitting
where relevant.
Part of #3513.
2017-11-17 17:11:41 +01:00
}
2017-08-29 18:22:06 +02:00
String OS_OSX::get_system_dir(SystemDir p_dir) const {
2018-05-21 16:16:16 +02:00
NSSearchPathDirectory id;
bool found = true;
2017-08-29 18:22:06 +02:00
switch (p_dir) {
case SYSTEM_DIR_DESKTOP: {
id = NSDesktopDirectory;
} break;
case SYSTEM_DIR_DOCUMENTS: {
id = NSDocumentDirectory;
} break;
case SYSTEM_DIR_DOWNLOADS: {
id = NSDownloadsDirectory;
} break;
case SYSTEM_DIR_MOVIES: {
id = NSMoviesDirectory;
} break;
case SYSTEM_DIR_MUSIC: {
id = NSMusicDirectory;
} break;
case SYSTEM_DIR_PICTURES: {
id = NSPicturesDirectory;
} break;
2018-05-21 16:16:16 +02:00
default: {
found = false;
}
2017-08-29 18:22:06 +02:00
}
String ret;
2018-05-21 16:16:16 +02:00
if (found) {
2017-08-29 18:22:06 +02:00
NSArray *paths = NSSearchPathForDirectoriesInDomains(id, NSUserDomainMask, YES);
if (paths && [paths count] >= 1) {
char *utfs = strdup([[paths firstObject] UTF8String]);
ret.parse_utf8(utfs);
free(utfs);
}
}
return ret;
}
2014-02-10 02:10:30 +01:00
bool OS_OSX::can_draw() const {
return true;
}
2017-04-09 14:18:49 +02:00
void OS_OSX::set_clipboard(const String &p_text) {
2014-02-10 02:10:30 +01:00
2018-10-03 18:56:16 +02:00
NSString *copiedString = [NSString stringWithUTF8String:p_text.utf8().get_data()];
NSArray *copiedStringArray = [NSArray arrayWithObject:copiedString];
2014-02-10 02:10:30 +01:00
2017-04-09 14:18:49 +02:00
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
2018-10-03 18:56:16 +02:00
[pasteboard clearContents];
[pasteboard writeObjects:copiedStringArray];
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
2014-02-10 02:10:30 +01:00
String OS_OSX::get_clipboard() const {
2017-04-09 14:18:49 +02:00
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
2018-10-03 18:56:16 +02:00
NSArray *classArray = [NSArray arrayWithObject:[NSString class]];
NSDictionary *options = [NSDictionary dictionary];
2014-02-10 02:10:30 +01:00
2018-10-03 18:56:16 +02:00
BOOL ok = [pasteboard canReadObjectForClasses:classArray options:options];
2014-02-10 02:10:30 +01:00
2018-10-03 18:56:16 +02:00
if (!ok) {
2014-02-10 02:10:30 +01:00
return "";
}
2018-10-03 18:56:16 +02:00
NSArray *objectsToPaste = [pasteboard readObjectsForClasses:classArray options:options];
NSString *string = [objectsToPaste objectAtIndex:0];
char *utfs = strdup([string UTF8String]);
2014-02-10 02:10:30 +01:00
String ret;
ret.parse_utf8(utfs);
free(utfs);
return ret;
}
void OS_OSX::release_rendering_thread() {
[NSOpenGLContext clearCurrentContext];
}
2017-04-09 13:22:40 +02:00
2014-02-10 02:10:30 +01:00
void OS_OSX::make_rendering_thread() {
[context makeCurrentContext];
}
Error OS_OSX::shell_open(String p_uri) {
2020-07-04 06:00:48 +02:00
NSString *string = [NSString stringWithUTF8String:p_uri.utf8().get_data()];
NSURL *uri = [[NSURL alloc] initWithString:string];
// Escape special characters in filenames
if (!uri || !uri.scheme || [uri.scheme isEqual:@"file"]) {
uri = [[NSURL alloc] initWithString:[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
}
[[NSWorkspace sharedWorkspace] openURL:uri];
2014-02-10 02:10:30 +01:00
return OK;
}
2015-10-16 19:42:26 +02:00
String OS_OSX::get_locale() const {
2019-11-25 14:55:17 +01:00
NSString *locale_code = [[NSLocale preferredLanguages] objectAtIndex:0];
2017-05-26 20:50:22 +02:00
return [locale_code UTF8String];
2015-10-16 19:42:26 +02:00
}
2014-02-10 02:10:30 +01:00
void OS_OSX::swap_buffers() {
[context flushBuffer];
}
2015-04-02 06:32:02 +02:00
void OS_OSX::wm_minimized(bool p_minimized) {
2014-02-10 02:10:30 +01:00
2015-04-02 06:32:02 +02:00
minimized = p_minimized;
};
2014-02-10 02:10:30 +01:00
2017-04-09 14:18:49 +02:00
void OS_OSX::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
2014-02-10 02:10:30 +01:00
}
OS::VideoMode OS_OSX::get_video_mode(int p_screen) const {
2016-05-30 05:28:29 +02:00
VideoMode vm;
2017-04-09 14:18:49 +02:00
vm.width = window_size.width;
vm.height = window_size.height;
2016-05-30 05:28:29 +02:00
return vm;
2014-02-10 02:10:30 +01:00
}
2017-04-09 13:22:40 +02:00
2017-04-09 14:18:49 +02:00
void OS_OSX::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
2014-02-10 02:10:30 +01:00
}
2015-04-02 06:32:02 +02:00
int OS_OSX::get_screen_count() const {
2017-07-28 23:08:57 +02:00
NSArray *screenArray = [NSScreen screens];
return [screenArray count];
2015-04-02 06:32:02 +02:00
};
2017-11-03 11:00:29 +01:00
// Returns the native top-left screen coordinate of the smallest rectangle
// that encompasses all screens. Needed in get_screen_position(),
// get_window_position, and set_window_position()
// to convert between OS X native screen coordinates and the ones expected by Godot
Point2 OS_OSX::get_screens_origin() const {
static Point2 origin;
if (displays_arrangement_dirty) {
origin = Point2();
for (int i = 0; i < get_screen_count(); i++) {
Point2 position = get_native_screen_position(i);
if (position.x < origin.x) {
origin.x = position.x;
}
if (position.y > origin.y) {
origin.y = position.y;
}
}
displays_arrangement_dirty = false;
}
return origin;
}
2017-09-30 12:50:30 +02:00
static int get_screen_index(NSScreen *screen) {
const NSUInteger index = [[NSScreen screens] indexOfObject:screen];
return index == NSNotFound ? 0 : index;
}
2015-04-02 06:32:02 +02:00
int OS_OSX::get_current_screen() const {
2017-09-30 12:50:30 +02:00
if (window_object) {
return get_screen_index([window_object screen]);
} else {
return get_screen_index([NSScreen mainScreen]);
2017-07-26 15:16:10 +02:00
}
2015-04-02 06:32:02 +02:00
};
void OS_OSX::set_current_screen(int p_screen) {
2017-07-26 15:16:10 +02:00
Vector2 wpos = get_window_position() - get_screen_position(get_current_screen());
set_window_position(wpos + get_screen_position(p_screen));
2015-04-02 06:32:02 +02:00
};
2017-11-03 11:00:29 +01:00
Point2 OS_OSX::get_native_screen_position(int p_screen) const {
2019-10-24 16:34:18 +02:00
if (p_screen < 0) {
2017-08-20 21:12:29 +02:00
p_screen = get_current_screen();
}
2017-07-28 23:08:57 +02:00
NSArray *screenArray = [NSScreen screens];
2019-10-24 16:34:18 +02:00
if ((NSUInteger)p_screen < [screenArray count]) {
2020-07-07 20:37:05 +02:00
float display_scale = get_screen_max_scale();
2017-07-28 23:08:57 +02:00
NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
2017-11-03 11:00:29 +01:00
// Return the top-left corner of the screen, for OS X the y starts at the bottom
return Point2(nsrect.origin.x, nsrect.origin.y + nsrect.size.height) * display_scale;
2017-07-28 23:08:57 +02:00
}
return Point2();
}
2015-04-02 06:32:02 +02:00
2017-11-03 11:00:29 +01:00
Point2 OS_OSX::get_screen_position(int p_screen) const {
Point2 position = get_native_screen_position(p_screen) - get_screens_origin();
// OS X native y-coordinate relative to get_screens_origin() is negative,
// Godot expects a positive value
position.y *= -1;
return position;
}
2016-05-30 05:28:29 +02:00
int OS_OSX::get_screen_dpi(int p_screen) const {
2019-10-24 16:34:18 +02:00
if (p_screen < 0) {
2017-08-20 21:12:29 +02:00
p_screen = get_current_screen();
}
2017-07-28 23:08:57 +02:00
NSArray *screenArray = [NSScreen screens];
2019-10-24 16:34:18 +02:00
if ((NSUInteger)p_screen < [screenArray count]) {
2017-07-28 23:08:57 +02:00
NSDictionary *description = [[screenArray objectAtIndex:p_screen] deviceDescription];
2020-07-07 20:37:05 +02:00
NSSize displayDPI = [[description objectForKey:NSDeviceResolution] sizeValue];
return (displayDPI.width + displayDPI.height) / 2;
2017-07-28 23:08:57 +02:00
}
return 72;
2016-05-30 05:28:29 +02:00
}
2016-05-11 16:44:10 +02:00
Size2 OS_OSX::get_screen_size(int p_screen) const {
2019-10-24 16:34:18 +02:00
if (p_screen < 0) {
2017-08-20 21:12:29 +02:00
p_screen = get_current_screen();
}
2017-07-28 23:08:57 +02:00
NSArray *screenArray = [NSScreen screens];
2019-10-24 16:34:18 +02:00
if ((NSUInteger)p_screen < [screenArray count]) {
2020-07-07 20:37:05 +02:00
float displayScale = get_screen_max_scale();
2017-07-28 23:08:57 +02:00
// Note: Use frame to get the whole screen size
NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
return Size2(nsrect.size.width, nsrect.size.height) * displayScale;
}
return Size2();
}
2015-04-02 06:32:02 +02:00
2017-07-03 03:44:42 +02:00
void OS_OSX::_update_window() {
bool borderless_full = false;
if (get_borderless_window()) {
NSRect frameRect = [window_object frame];
NSRect screenRect = [[window_object screen] frame];
// Check if our window covers up the screen
if (frameRect.origin.x <= screenRect.origin.x && frameRect.origin.y <= frameRect.origin.y &&
frameRect.size.width >= screenRect.size.width && frameRect.size.height >= screenRect.size.height) {
borderless_full = true;
}
}
if (borderless_full) {
// If the window covers up the screen set the level to above the main menu and hide on deactivate
[window_object setLevel:NSMainMenuWindowLevel + 1];
[window_object setHidesOnDeactivate:YES];
} else {
// Reset these when our window is not a borderless window that covers up the screen
2020-08-15 16:50:04 +02:00
if (on_top) {
[window_object setLevel:NSFloatingWindowLevel];
} else {
[window_object setLevel:NSNormalWindowLevel];
}
2017-07-03 03:44:42 +02:00
[window_object setHidesOnDeactivate:NO];
}
}
2020-07-07 20:37:05 +02:00
float OS_OSX::get_screen_scale(int p_screen) const {
if (p_screen < 0) {
p_screen = get_current_screen();
2017-09-30 12:50:30 +02:00
}
if (is_hidpi_allowed()) {
2020-07-07 20:37:05 +02:00
NSArray *screenArray = [NSScreen screens];
if ((NSUInteger)p_screen < [screenArray count]) {
if ([[screenArray objectAtIndex:p_screen] respondsToSelector:@selector(backingScaleFactor)]) {
return fmax(1.0, [[screenArray objectAtIndex:p_screen] backingScaleFactor]);
}
2017-09-30 12:50:30 +02:00
}
}
2020-07-07 20:37:05 +02:00
return 1.f;
}
float OS_OSX::get_screen_max_scale() const {
static float scale = 1.f;
if (displays_scale_dirty) {
int screen_count = get_screen_count();
for (int i = 0; i < screen_count; i++) {
scale = fmax(scale, get_screen_scale(i));
}
displays_scale_dirty = false;
}
return scale;
2017-09-30 12:50:30 +02:00
}
2017-11-03 11:00:29 +01:00
Point2 OS_OSX::get_native_window_position() const {
2015-04-02 06:32:02 +02:00
2017-11-03 11:00:29 +01:00
NSRect nsrect = [window_object frame];
Point2 pos;
2020-07-07 20:37:05 +02:00
float display_scale = get_screen_max_scale();
2017-11-03 11:00:29 +01:00
// Return the position of the top-left corner, for OS X the y starts at the bottom
pos.x = nsrect.origin.x * display_scale;
pos.y = (nsrect.origin.y + nsrect.size.height) * display_scale;
return pos;
2015-04-02 06:32:02 +02:00
};
2017-11-03 11:00:29 +01:00
Point2 OS_OSX::get_window_position() const {
Point2 position = get_native_window_position() - get_screens_origin();
// OS X native y-coordinate relative to get_screens_origin() is negative,
// Godot expects a positive value
position.y *= -1;
return position;
}
void OS_OSX::set_native_window_position(const Point2 &p_position) {
2015-04-02 06:32:02 +02:00
2017-08-21 17:36:04 +02:00
NSPoint pos;
2020-07-07 20:37:05 +02:00
float displayScale = get_screen_max_scale();
2017-08-21 17:36:04 +02:00
2017-09-30 12:50:30 +02:00
pos.x = p_position.x / displayScale;
2017-11-03 11:00:29 +01:00
pos.y = p_position.y / displayScale;
2017-08-21 17:36:04 +02:00
[window_object setFrameTopLeftPoint:pos];
2017-07-03 03:44:42 +02:00
_update_window();
2015-04-02 06:32:02 +02:00
};
2017-11-03 11:00:29 +01:00
void OS_OSX::set_window_position(const Point2 &p_position) {
Point2 position = p_position;
// OS X native y-coordinate relative to get_screens_origin() is negative,
// Godot passes a positive value
position.y *= -1;
set_native_window_position(get_screens_origin() + position);
2019-06-18 21:44:29 +02:00
update_real_mouse_position();
2017-11-03 11:00:29 +01:00
};
2015-03-24 06:07:03 +01:00
Size2 OS_OSX::get_window_size() const {
2015-04-02 06:32:02 +02:00
2016-05-30 05:28:29 +02:00
return window_size;
2015-04-02 06:32:02 +02:00
};
2018-02-12 18:17:29 +01:00
Size2 OS_OSX::get_real_window_size() const {
NSRect frame = [window_object frame];
2020-07-07 20:37:05 +02:00
return Size2(frame.size.width, frame.size.height) * get_screen_max_scale();
2018-02-12 18:17:29 +01:00
}
2019-06-13 14:31:08 +02:00
Size2 OS_OSX::get_max_window_size() const {
return max_size;
}
Size2 OS_OSX::get_min_window_size() const {
return min_size;
}
void OS_OSX::set_min_window_size(const Size2 p_size) {
if ((p_size != Size2()) && (max_size != Size2()) && ((p_size.x > max_size.x) || (p_size.y > max_size.y))) {
2019-07-30 14:50:52 +02:00
ERR_PRINT("Minimum window size can't be larger than maximum window size!");
2019-06-13 14:31:08 +02:00
return;
}
min_size = p_size;
if ((min_size != Size2()) && !zoomed) {
2020-07-07 20:37:05 +02:00
Size2 size = min_size / get_screen_max_scale();
2019-06-13 14:31:08 +02:00
[window_object setContentMinSize:NSMakeSize(size.x, size.y)];
} else {
[window_object setContentMinSize:NSMakeSize(0, 0)];
}
}
void OS_OSX::set_max_window_size(const Size2 p_size) {
if ((p_size != Size2()) && ((p_size.x < min_size.x) || (p_size.y < min_size.y))) {
2019-07-30 14:50:52 +02:00
ERR_PRINT("Maximum window size can't be smaller than minimum window size!");
2019-06-13 14:31:08 +02:00
return;
}
max_size = p_size;
if ((max_size != Size2()) && !zoomed) {
2020-07-07 20:37:05 +02:00
Size2 size = max_size / get_screen_max_scale();
2019-06-13 14:31:08 +02:00
[window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
} else {
[window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
}
}
2015-04-02 06:32:02 +02:00
void OS_OSX::set_window_size(const Size2 p_size) {
2020-07-07 20:37:05 +02:00
Size2 size = p_size / get_screen_max_scale();
2016-08-03 03:30:19 +02:00
2020-07-14 16:38:16 +02:00
NSPoint top_left;
NSRect old_frame = [window_object frame];
top_left.x = old_frame.origin.x;
top_left.y = NSMaxY(old_frame);
2017-07-03 03:44:42 +02:00
2020-07-14 16:38:16 +02:00
NSRect new_frame = NSMakeRect(0, 0, size.x, size.y);
new_frame = [window_object frameRectForContentRect:new_frame];
new_frame.origin.x = top_left.x;
new_frame.origin.y = top_left.y - new_frame.size.height;
[window_object setFrame:new_frame display:YES];
2017-07-03 03:44:42 +02:00
_update_window();
2015-04-02 06:32:02 +02:00
};
void OS_OSX::set_window_fullscreen(bool p_enabled) {
2015-05-06 12:53:55 +02:00
if (zoomed != p_enabled) {
2017-12-10 19:38:26 +01:00
if (layered_window)
set_window_per_pixel_transparency_enabled(false);
2019-03-28 14:36:51 +01:00
if (!resizable)
[window_object setStyleMask:[window_object styleMask] | NSWindowStyleMaskResizable];
2019-06-13 14:31:08 +02:00
if (p_enabled) {
[window_object setContentMinSize:NSMakeSize(0, 0)];
[window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
} else {
if (min_size != Size2()) {
2020-07-07 20:37:05 +02:00
Size2 size = min_size / get_screen_max_scale();
2019-06-13 14:31:08 +02:00
[window_object setContentMinSize:NSMakeSize(size.x, size.y)];
}
if (max_size != Size2()) {
2020-07-07 20:37:05 +02:00
Size2 size = max_size / get_screen_max_scale();
2019-06-13 14:31:08 +02:00
[window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
}
}
2015-05-06 12:53:55 +02:00
[window_object toggleFullScreen:nil];
}
2015-04-02 06:32:02 +02:00
zoomed = p_enabled;
};
bool OS_OSX::is_window_fullscreen() const {
return zoomed;
};
void OS_OSX::set_window_resizable(bool p_enabled) {
if (p_enabled)
2018-01-06 14:39:44 +01:00
[window_object setStyleMask:[window_object styleMask] | NSWindowStyleMaskResizable];
2019-03-28 14:36:51 +01:00
else if (!zoomed)
2018-01-06 14:39:44 +01:00
[window_object setStyleMask:[window_object styleMask] & ~NSWindowStyleMaskResizable];
2018-05-23 21:25:41 +02:00
resizable = p_enabled;
2015-04-02 06:32:02 +02:00
};
bool OS_OSX::is_window_resizable() const {
2018-01-06 14:39:44 +01:00
return [window_object styleMask] & NSWindowStyleMaskResizable;
2015-04-02 06:32:02 +02:00
};
void OS_OSX::set_window_minimized(bool p_enabled) {
if (p_enabled)
[window_object performMiniaturize:nil];
else
[window_object deminiaturize:nil];
};
bool OS_OSX::is_window_minimized() const {
2017-04-09 14:18:49 +02:00
if ([window_object respondsToSelector:@selector(isMiniaturized)])
2015-04-02 06:32:02 +02:00
return [window_object isMiniaturized];
return minimized;
};
void OS_OSX::set_window_maximized(bool p_enabled) {
if (p_enabled) {
restore_rect = Rect2(get_window_position(), get_window_size());
2017-07-26 15:16:10 +02:00
[window_object setFrame:[[[NSScreen screens] objectAtIndex:get_current_screen()] visibleFrame] display:YES];
2015-04-02 06:32:02 +02:00
} else {
set_window_size(restore_rect.size);
2017-06-04 00:25:13 +02:00
set_window_position(restore_rect.position);
2015-04-02 06:32:02 +02:00
};
maximized = p_enabled;
};
bool OS_OSX::is_window_maximized() const {
// don't know
return maximized;
};
2014-02-10 02:10:30 +01:00
void OS_OSX::move_window_to_foreground() {
2019-02-23 19:06:33 +01:00
[[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
[window_object makeKeyAndOrderFront:nil];
2014-02-10 02:10:30 +01:00
}
2018-01-30 20:39:53 +01:00
void OS_OSX::set_window_always_on_top(bool p_enabled) {
2020-08-15 16:50:04 +02:00
on_top = p_enabled;
2018-01-30 20:39:53 +01:00
if (is_window_always_on_top() == p_enabled)
return;
if (p_enabled)
[window_object setLevel:NSFloatingWindowLevel];
else
[window_object setLevel:NSNormalWindowLevel];
}
bool OS_OSX::is_window_always_on_top() const {
return [window_object level] == NSFloatingWindowLevel;
}
2019-11-28 13:41:07 +01:00
bool OS_OSX::is_window_focused() const {
return window_focused;
}
2016-07-21 17:30:20 +02:00
void OS_OSX::request_attention() {
[NSApp requestUserAttention:NSCriticalRequest];
}
2017-12-10 19:38:26 +01:00
bool OS_OSX::get_window_per_pixel_transparency_enabled() const {
if (!is_layered_allowed()) return false;
return layered_window;
}
void OS_OSX::set_window_per_pixel_transparency_enabled(bool p_enabled) {
if (!is_layered_allowed()) return;
if (layered_window != p_enabled) {
if (p_enabled) {
GLint opacity = 0;
[window_object setBackgroundColor:[NSColor clearColor]];
[window_object setOpaque:NO];
[window_object setHasShadow:NO];
2020-06-29 13:24:56 +02:00
[context setValues:&opacity forParameter:NSOpenGLContextParameterSurfaceOpacity];
2017-12-10 19:38:26 +01:00
layered_window = true;
} else {
GLint opacity = 1;
[window_object setBackgroundColor:[NSColor colorWithCalibratedWhite:1 alpha:1]];
[window_object setOpaque:YES];
[window_object setHasShadow:YES];
2020-06-29 13:24:56 +02:00
[context setValues:&opacity forParameter:NSOpenGLContextParameterSurfaceOpacity];
2017-12-10 19:38:26 +01:00
layered_window = false;
}
[context update];
NSRect frame = [window_object frame];
[window_object setFrame:NSMakeRect(frame.origin.x, frame.origin.y, 1, 1) display:YES];
[window_object setFrame:frame display:YES];
}
}
2017-12-14 19:15:46 +01:00
void OS_OSX::set_borderless_window(bool p_borderless) {
2017-06-27 18:13:03 +02:00
2017-07-03 03:44:42 +02:00
// OrderOut prevents a lose focus bug with the window
[window_object orderOut:nil];
if (p_borderless) {
2017-06-27 18:13:03 +02:00
[window_object setStyleMask:NSWindowStyleMaskBorderless];
2017-07-03 03:44:42 +02:00
} else {
2018-05-23 21:25:41 +02:00
[window_object setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (resizable ? NSWindowStyleMaskResizable : 0)];
2017-06-27 18:13:03 +02:00
// Force update of the window styles
NSRect frameRect = [window_object frame];
[window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
[window_object setFrame:frameRect display:NO];
// Restore the window title
[window_object setTitle:[NSString stringWithUTF8String:title.utf8().get_data()]];
}
2017-07-03 03:44:42 +02:00
_update_window();
[window_object makeKeyAndOrderFront:nil];
2017-06-27 18:13:03 +02:00
}
bool OS_OSX::get_borderless_window() {
return [window_object styleMask] == NSWindowStyleMaskBorderless;
}
2014-02-10 02:10:30 +01:00
String OS_OSX::get_executable_path() const {
int ret;
pid_t pid;
char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
pid = getpid();
2017-04-09 14:18:49 +02:00
ret = proc_pidpath(pid, pathbuf, sizeof(pathbuf));
if (ret <= 0) {
2014-02-10 02:10:30 +01:00
return OS::get_executable_path();
} else {
String path;
path.parse_utf8(pathbuf);
return path;
}
}
2015-01-08 08:26:27 +01:00
// Returns string representation of keys, if they are printable.
//
static NSString *createStringForKeys(const CGKeyCode *keyCode, int length) {
TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
if (!currentKeyboard)
return nil;
CFDataRef layoutData = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
if (!layoutData)
return nil;
const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout *)CFDataGetBytePtr(layoutData);
OSStatus err;
CFMutableStringRef output = CFStringCreateMutable(NULL, 0);
2017-04-09 14:18:49 +02:00
for (int i = 0; i < length; ++i) {
2015-01-08 08:26:27 +01:00
UInt32 keysDown = 0;
UniChar chars[4];
UniCharCount realLength;
err = UCKeyTranslate(keyboardLayout,
2017-04-09 14:18:49 +02:00
keyCode[i],
kUCKeyActionDisplay,
0,
LMGetKbdType(),
kUCKeyTranslateNoDeadKeysBit,
&keysDown,
sizeof(chars) / sizeof(chars[0]),
&realLength,
chars);
2015-01-08 08:26:27 +01:00
if (err != noErr) {
CFRelease(output);
return nil;
}
2015-01-08 16:01:10 +01:00
CFStringAppendCharacters(output, chars, 1);
2015-01-08 08:26:27 +01:00
}
//CFStringUppercase(output, NULL);
return (NSString *)output;
}
2017-04-09 13:22:40 +02:00
2020-06-12 14:51:51 +02:00
void _update_keyboard_layouts() {
@autoreleasepool {
TISInputSourceRef cur_source = TISCopyCurrentKeyboardInputSource();
NSString *cur_name = (NSString *)TISGetInputSourceProperty(cur_source, kTISPropertyLocalizedName);
CFRelease(cur_source);
// Enum IME layouts
NSDictionary *filter_ime = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardInputMode };
NSArray *list_ime = (NSArray *)TISCreateInputSourceList((CFDictionaryRef)filter_ime, false);
for (NSUInteger i = 0; i < [list_ime count]; i++) {
LayoutInfo ly;
NSString *name = (NSString *)TISGetInputSourceProperty((TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyLocalizedName);
ly.name.parse_utf8([name UTF8String]);
NSArray *langs = (NSArray *)TISGetInputSourceProperty((TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyInputSourceLanguages);
ly.code.parse_utf8([(NSString *)[langs objectAtIndex:0] UTF8String]);
kbd_layouts.push_back(ly);
if ([name isEqualToString:cur_name]) {
current_layout = kbd_layouts.size() - 1;
}
}
[list_ime release];
// Enum plain keyboard layouts
NSDictionary *filter_kbd = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardLayout };
NSArray *list_kbd = (NSArray *)TISCreateInputSourceList((CFDictionaryRef)filter_kbd, false);
for (NSUInteger i = 0; i < [list_kbd count]; i++) {
LayoutInfo ly;
NSString *name = (NSString *)TISGetInputSourceProperty((TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyLocalizedName);
ly.name.parse_utf8([name UTF8String]);
NSArray *langs = (NSArray *)TISGetInputSourceProperty((TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyInputSourceLanguages);
ly.code.parse_utf8([(NSString *)[langs objectAtIndex:0] UTF8String]);
kbd_layouts.push_back(ly);
if ([name isEqualToString:cur_name]) {
current_layout = kbd_layouts.size() - 1;
}
}
[list_kbd release];
}
// Update latin variant
latin_variant = OS::LATIN_KEYBOARD_QWERTY;
CGKeyCode keys[] = { kVK_ANSI_Q, kVK_ANSI_W, kVK_ANSI_E, kVK_ANSI_R, kVK_ANSI_T, kVK_ANSI_Y };
NSString *test = createStringForKeys(keys, 6);
if ([test isEqualToString:@"qwertz"]) {
latin_variant = OS::LATIN_KEYBOARD_QWERTZ;
} else if ([test isEqualToString:@"azerty"]) {
latin_variant = OS::LATIN_KEYBOARD_AZERTY;
} else if ([test isEqualToString:@"qzerty"]) {
latin_variant = OS::LATIN_KEYBOARD_QZERTY;
} else if ([test isEqualToString:@"',.pyf"]) {
latin_variant = OS::LATIN_KEYBOARD_DVORAK;
} else if ([test isEqualToString:@"xvlcwk"]) {
latin_variant = OS::LATIN_KEYBOARD_NEO;
} else if ([test isEqualToString:@"qwfpgj"]) {
latin_variant = OS::LATIN_KEYBOARD_COLEMAK;
}
[test release];
keyboard_layout_dirty = false;
}
2015-01-08 08:26:27 +01:00
OS::LatinKeyboardVariant OS_OSX::get_latin_keyboard_variant() const {
2020-06-12 14:51:51 +02:00
if (keyboard_layout_dirty) {
_update_keyboard_layouts();
}
return latin_variant;
}
int OS_OSX::keyboard_get_layout_count() const {
if (keyboard_layout_dirty) {
_update_keyboard_layouts();
}
return kbd_layouts.size();
}
2015-01-08 08:26:27 +01:00
2020-06-12 14:51:51 +02:00
void OS_OSX::keyboard_set_current_layout(int p_index) {
2015-01-08 08:26:27 +01:00
if (keyboard_layout_dirty) {
2020-06-12 14:51:51 +02:00
_update_keyboard_layouts();
}
ERR_FAIL_INDEX(p_index, kbd_layouts.size());
2015-01-08 08:26:27 +01:00
2020-06-12 14:51:51 +02:00
NSString *cur_name = [NSString stringWithUTF8String:kbd_layouts[p_index].name.utf8().get_data()];
NSDictionary *filter_kbd = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardLayout };
NSArray *list_kbd = (NSArray *)TISCreateInputSourceList((CFDictionaryRef)filter_kbd, false);
for (NSUInteger i = 0; i < [list_kbd count]; i++) {
NSString *name = (NSString *)TISGetInputSourceProperty((TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyLocalizedName);
if ([name isEqualToString:cur_name]) {
TISSelectInputSource((TISInputSourceRef)[list_kbd objectAtIndex:i]);
break;
2015-01-08 08:26:27 +01:00
}
2020-06-12 14:51:51 +02:00
}
[list_kbd release];
NSDictionary *filter_ime = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardInputMode };
NSArray *list_ime = (NSArray *)TISCreateInputSourceList((CFDictionaryRef)filter_ime, false);
for (NSUInteger i = 0; i < [list_ime count]; i++) {
NSString *name = (NSString *)TISGetInputSourceProperty((TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyLocalizedName);
if ([name isEqualToString:cur_name]) {
TISSelectInputSource((TISInputSourceRef)[list_ime objectAtIndex:i]);
break;
}
}
[list_ime release];
}
int OS_OSX::keyboard_get_current_layout() const {
if (keyboard_layout_dirty) {
_update_keyboard_layouts();
}
2015-01-08 08:26:27 +01:00
2020-06-12 14:51:51 +02:00
return current_layout;
}
2015-01-08 08:26:27 +01:00
2020-06-12 14:51:51 +02:00
String OS_OSX::keyboard_get_layout_language(int p_index) const {
if (keyboard_layout_dirty) {
_update_keyboard_layouts();
}
ERR_FAIL_INDEX_V(p_index, kbd_layouts.size(), "");
return kbd_layouts[p_index].code;
}
String OS_OSX::keyboard_get_layout_name(int p_index) const {
if (keyboard_layout_dirty) {
_update_keyboard_layouts();
2015-01-08 08:26:27 +01:00
}
2020-06-12 14:51:51 +02:00
ERR_FAIL_INDEX_V(p_index, kbd_layouts.size(), "");
return kbd_layouts[p_index].name;
2015-01-08 08:26:27 +01:00
}
2014-02-10 02:10:30 +01:00
void OS_OSX::process_events() {
while (true) {
2017-04-09 14:18:49 +02:00
NSEvent *event = [NSApp
2018-01-06 14:39:44 +01:00
nextEventMatchingMask:NSEventMaskAny
2017-04-09 14:18:49 +02:00
untilDate:[NSDate distantPast]
inMode:NSDefaultRunLoopMode
dequeue:YES];
2014-02-10 02:10:30 +01:00
if (event == nil)
break;
[NSApp sendEvent:event];
}
2018-01-10 12:22:28 +01:00
process_key_events();
2014-02-10 02:10:30 +01:00
2020-06-29 11:31:13 +02:00
if (mpath.size() > 0) {
const Vector2 mpos = get_mouse_pos([window_object mouseLocationOutsideOfEventStream]);
if (Geometry::is_point_in_polygon(mpos, mpath)) {
if ([window_object ignoresMouseEvents]) {
[window_object setIgnoresMouseEvents:NO];
}
} else {
if (![window_object ignoresMouseEvents]) {
[window_object setIgnoresMouseEvents:YES];
}
}
} else {
if ([window_object ignoresMouseEvents]) {
[window_object setIgnoresMouseEvents:NO];
}
}
2014-02-10 02:10:30 +01:00
[autoreleasePool drain];
autoreleasePool = [[NSAutoreleasePool alloc] init];
2019-03-03 23:52:18 +01:00
input->flush_accumulated_events();
2014-02-10 02:10:30 +01:00
}
2018-01-10 12:22:28 +01:00
void OS_OSX::process_key_events() {
Ref<InputEventKey> k;
for (int i = 0; i < key_event_pos; i++) {
2018-07-25 03:11:03 +02:00
const KeyEvent &ke = key_event_buffer[i];
2018-01-10 12:22:28 +01:00
2019-06-04 09:30:59 +02:00
if (ke.raw) {
// Non IME input - no composite characters, pass events as is
2018-01-10 12:22:28 +01:00
k.instance();
get_key_modifier_state(ke.osx_state, k);
k->set_pressed(ke.pressed);
k->set_echo(ke.echo);
2019-06-04 09:30:59 +02:00
k->set_scancode(ke.scancode);
2018-01-10 12:22:28 +01:00
k->set_unicode(ke.unicode);
push_input(k);
2019-06-04 09:30:59 +02:00
} else {
// IME input
if ((i == 0 && ke.scancode == 0) || (i > 0 && key_event_buffer[i - 1].scancode == 0)) {
k.instance();
2018-01-10 12:22:28 +01:00
2019-06-04 09:30:59 +02:00
get_key_modifier_state(ke.osx_state, k);
k->set_pressed(ke.pressed);
k->set_echo(ke.echo);
k->set_scancode(0);
k->set_unicode(ke.unicode);
2018-01-10 12:22:28 +01:00
2019-06-04 09:30:59 +02:00
push_input(k);
2018-01-10 12:22:28 +01:00
}
2019-06-04 09:30:59 +02:00
if (ke.scancode != 0) {
k.instance();
2018-01-10 12:22:28 +01:00
2019-06-04 09:30:59 +02:00
get_key_modifier_state(ke.osx_state, k);
k->set_pressed(ke.pressed);
k->set_echo(ke.echo);
k->set_scancode(ke.scancode);
if (i + 1 < key_event_pos && key_event_buffer[i + 1].scancode == 0) {
k->set_unicode(key_event_buffer[i + 1].unicode);
}
push_input(k);
}
2018-01-10 12:22:28 +01:00
}
}
key_event_pos = 0;
}
2017-05-20 17:38:03 +02:00
void OS_OSX::push_input(const Ref<InputEvent> &p_event) {
2017-05-22 11:17:14 +02:00
2017-05-20 17:38:03 +02:00
Ref<InputEvent> ev = p_event;
2019-03-03 23:52:18 +01:00
input->accumulate_input_event(ev);
2014-02-10 02:10:30 +01:00
}
2017-12-14 12:59:46 +01:00
void OS_OSX::force_process_input() {
process_events(); // get rid of pending events
joypad_osx->process_joypads();
}
2014-02-10 02:10:30 +01:00
void OS_OSX::run() {
force_quit = false;
if (!main_loop)
return;
main_loop->init();
2015-05-06 12:53:55 +02:00
if (zoomed) {
zoomed = false;
set_window_fullscreen(true);
}
2017-01-14 12:26:56 +01:00
//uint64_t last_ticks=get_ticks_usec();
2014-02-10 02:10:30 +01:00
2017-01-14 12:26:56 +01:00
//int frames=0;
//uint64_t frame=0;
2014-02-10 02:10:30 +01:00
2018-01-15 09:20:45 +01:00
bool quit = false;
2014-02-10 02:10:30 +01:00
2018-01-15 09:20:45 +01:00
while (!force_quit && !quit) {
@try {
process_events(); // get rid of pending events
joypad_osx->process_joypads();
2020-07-24 10:26:41 +02:00
if (Main::iteration()) {
2018-01-15 09:20:45 +01:00
quit = true;
}
} @catch (NSException *exception) {
ERR_PRINTS("NSException: " + String([exception reason].UTF8String));
}
2014-02-10 02:10:30 +01:00
};
main_loop->finish();
}
2014-06-26 14:14:37 +02:00
void OS_OSX::set_mouse_mode(MouseMode p_mode) {
2017-04-09 14:18:49 +02:00
if (p_mode == mouse_mode)
return;
if (p_mode == MOUSE_MODE_CAPTURED) {
// Apple Docs state that the display parameter is not used.
// "This parameter is not used. By default, you may pass kCGDirectMainDisplay."
// https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/Quartz_Services_Ref/Reference/reference.html
2020-06-22 10:38:22 +02:00
if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
CGDisplayHideCursor(kCGDirectMainDisplay);
}
2017-04-09 14:18:49 +02:00
CGAssociateMouseAndMouseCursorPosition(false);
} else if (p_mode == MOUSE_MODE_HIDDEN) {
2020-06-22 10:38:22 +02:00
if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
CGDisplayHideCursor(kCGDirectMainDisplay);
}
2017-04-09 14:18:49 +02:00
CGAssociateMouseAndMouseCursorPosition(true);
2020-07-02 14:57:19 +02:00
} else if (p_mode == MOUSE_MODE_CONFINED) {
CGDisplayShowCursor(kCGDirectMainDisplay);
CGAssociateMouseAndMouseCursorPosition(false);
2017-04-09 14:18:49 +02:00
} else {
CGDisplayShowCursor(kCGDirectMainDisplay);
CGAssociateMouseAndMouseCursorPosition(true);
}
2014-06-26 14:14:37 +02:00
2020-07-02 14:57:19 +02:00
warp_events.clear();
2017-04-09 14:18:49 +02:00
mouse_mode = p_mode;
2014-06-26 14:14:37 +02:00
}
OS::MouseMode OS_OSX::get_mouse_mode() const {
2017-04-09 14:18:49 +02:00
return mouse_mode;
2014-06-26 14:14:37 +02:00
}
2014-02-10 02:10:30 +01:00
2016-09-06 00:47:54 +02:00
String OS_OSX::get_joy_guid(int p_device) const {
return input->get_joy_guid_remapped(p_device);
}
2017-09-12 21:09:06 +02:00
OS::PowerState OS_OSX::get_power_state() {
2016-07-23 13:15:55 +02:00
return power_manager->get_power_state();
}
int OS_OSX::get_power_seconds_left() {
return power_manager->get_power_seconds_left();
}
int OS_OSX::get_power_percent_left() {
return power_manager->get_power_percent_left();
}
2017-09-25 15:15:11 +02:00
Error OS_OSX::move_to_trash(const String &p_path) {
NSFileManager *fm = [NSFileManager defaultManager];
NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
NSError *err;
if (![fm trashItemAtURL:url resultingItemURL:nil error:&err]) {
ERR_PRINTS("trashItemAtURL error: " + String(err.localizedDescription.UTF8String));
return FAILED;
}
return OK;
}
2017-12-16 21:09:25 +01:00
void OS_OSX::_set_use_vsync(bool p_enable) {
2019-11-21 10:01:47 +01:00
CGLContextObj ctx = CGLGetCurrentContext();
2017-10-23 18:26:33 +02:00
if (ctx) {
GLint swapInterval = p_enable ? 1 : 0;
CGLSetParameter(ctx, kCGLCPSwapInterval, &swapInterval);
2019-11-21 10:01:47 +01:00
}
2017-10-23 18:26:33 +02:00
}
2019-01-27 12:39:32 +01:00
2017-04-09 14:18:49 +02:00
OS_OSX *OS_OSX::singleton = NULL;
2014-02-10 02:10:30 +01:00
OS_OSX::OS_OSX() {
2017-04-09 14:18:49 +02:00
2020-07-07 20:37:05 +02:00
context = nullptr;
2018-03-22 04:17:18 +01:00
memset(cursors, 0, sizeof(cursors));
2018-01-10 12:22:28 +01:00
key_event_pos = 0;
2017-04-09 14:18:49 +02:00
mouse_mode = OS::MOUSE_MODE_VISIBLE;
main_loop = NULL;
singleton = this;
2018-06-07 22:16:57 +02:00
im_active = false;
2017-08-07 13:09:56 +02:00
im_position = Point2();
2017-12-10 19:38:26 +01:00
layered_window = false;
2014-02-10 02:10:30 +01:00
autoreleasePool = [[NSAutoreleasePool alloc] init];
eventSource = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
ERR_FAIL_COND(!eventSource);
CGEventSourceSetLocalEventsSuppressionInterval(eventSource, 0.0);
2017-04-09 14:18:49 +02:00
/*
2017-04-09 13:22:40 +02:00
if (pthread_key_create(&_Godot.nsgl.current, NULL) != 0) {
_GodotInputError(Godot_PLATFORM_ERROR, "NSGL: Failed to create context TLS");
return GL_FALSE;
}
*/
2014-02-10 02:10:30 +01:00
framework = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl"));
ERR_FAIL_COND(!framework);
// Implicitly create shared NSApplication instance
[GodotApplication sharedApplication];
// In case we are unbundled, make us a proper UI application
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
// Menu bar setup must go between sharedApplication above and
// finishLaunching below, in order to properly emulate the behavior
// of NSApplicationMain
2017-07-26 15:05:26 +02:00
NSMenuItem *menu_item;
NSString *title;
2018-03-02 17:38:42 +01:00
NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
2017-07-26 15:05:26 +02:00
if (nsappname == nil)
nsappname = [[NSProcessInfo processInfo] processName];
// Setup Apple menu
NSMenu *apple_menu = [[NSMenu alloc] initWithTitle:@""];
title = [NSString stringWithFormat:NSLocalizedString(@"About %@", nil), nsappname];
2017-08-11 17:04:32 +02:00
[apple_menu addItemWithTitle:title action:@selector(showAbout:) keyEquivalent:@""];
2017-07-26 15:05:26 +02:00
[apple_menu addItem:[NSMenuItem separatorItem]];
NSMenu *services = [[NSMenu alloc] initWithTitle:@""];
menu_item = [apple_menu addItemWithTitle:NSLocalizedString(@"Services", nil) action:nil keyEquivalent:@""];
[apple_menu setSubmenu:services forItem:menu_item];
[NSApp setServicesMenu:services];
[services release];
[apple_menu addItem:[NSMenuItem separatorItem]];
title = [NSString stringWithFormat:NSLocalizedString(@"Hide %@", nil), nsappname];
[apple_menu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
menu_item = [apple_menu addItemWithTitle:NSLocalizedString(@"Hide Others", nil) action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
2018-01-06 14:39:44 +01:00
[menu_item setKeyEquivalentModifierMask:(NSEventModifierFlagOption | NSEventModifierFlagCommand)];
2017-07-26 15:05:26 +02:00
[apple_menu addItemWithTitle:NSLocalizedString(@"Show all", nil) action:@selector(unhideAllApplications:) keyEquivalent:@""];
[apple_menu addItem:[NSMenuItem separatorItem]];
title = [NSString stringWithFormat:NSLocalizedString(@"Quit %@", nil), nsappname];
[apple_menu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
// Setup menu bar
NSMenu *main_menu = [[NSMenu alloc] initWithTitle:@""];
menu_item = [main_menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
[main_menu setSubmenu:apple_menu forItem:menu_item];
[NSApp setMainMenu:main_menu];
[main_menu release];
[apple_menu release];
2014-02-10 02:10:30 +01:00
[NSApp finishLaunching];
delegate = [[GodotApplicationDelegate alloc] init];
ERR_FAIL_COND(!delegate);
[NSApp setDelegate:delegate];
2017-04-09 14:18:49 +02:00
cursor_shape = CURSOR_ARROW;
2014-02-10 02:10:30 +01:00
2015-04-02 06:32:02 +02:00
maximized = false;
minimized = false;
2017-04-09 14:18:49 +02:00
window_size = Vector2(1024, 600);
2015-04-02 06:32:02 +02:00
zoomed = false;
2018-05-23 21:25:41 +02:00
resizable = false;
2019-11-28 13:41:07 +01:00
window_focused = true;
2020-08-15 16:50:04 +02:00
on_top = false;
2017-09-22 07:56:02 +02:00
2017-11-21 10:35:01 +01:00
Vector<Logger *> loggers;
loggers.push_back(memnew(OSXTerminalLogger));
_set_logger(memnew(CompositeLogger(loggers)));
2018-01-12 15:38:19 +01:00
//process application:openFile: event
while (true) {
NSEvent *event = [NSApp
nextEventMatchingMask:NSEventMaskAny
untilDate:[NSDate distantPast]
inMode:NSDefaultRunLoopMode
dequeue:YES];
if (event == nil)
break;
[NSApp sendEvent:event];
}
2018-03-04 18:18:05 +01:00
2018-10-25 15:59:26 +02:00
#ifdef COREAUDIO_ENABLED
2018-03-04 18:18:05 +01:00
AudioDriverManager::add_driver(&audio_driver);
2018-10-25 15:59:26 +02:00
#endif
2014-02-10 02:10:30 +01:00
}
2017-07-19 22:00:46 +02:00
bool OS_OSX::_check_internal_feature_support(const String &p_feature) {
2019-02-26 15:58:47 +01:00
return p_feature == "pc";
2017-07-19 22:00:46 +02:00
}
2017-09-08 03:01:49 +02:00
void OS_OSX::disable_crash_handler() {
crash_handler.disable();
}
bool OS_OSX::is_disable_crash_handler() const {
return crash_handler.is_disabled();
}