summaryrefslogtreecommitdiffstats
path: root/platform
diff options
context:
space:
mode:
Diffstat (limited to 'platform')
-rw-r--r--platform/android/detect.py1
-rw-r--r--platform/android/doc_classes/EditorExportPlatformAndroid.xml30
-rw-r--r--platform/android/export/export_plugin.cpp52
-rw-r--r--platform/android/export/export_plugin.h3
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/gl/GLSurfaceView.java19
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularContextFactory.java10
-rw-r--r--platform/ios/app_delegate.mm12
-rw-r--r--platform/ios/detect.py1
-rw-r--r--platform/ios/export/export_plugin.cpp4
-rw-r--r--platform/linuxbsd/detect.py1
-rw-r--r--platform/linuxbsd/os_linuxbsd.cpp1
-rw-r--r--platform/linuxbsd/platform_linuxbsd_builders.py1
-rw-r--r--platform/linuxbsd/wayland/display_server_wayland.cpp50
-rw-r--r--platform/linuxbsd/wayland/display_server_wayland.h2
-rw-r--r--platform/linuxbsd/wayland/wayland_thread.cpp253
-rw-r--r--platform/linuxbsd/wayland/wayland_thread.h20
-rw-r--r--platform/linuxbsd/x11/display_server_x11.cpp40
-rw-r--r--platform/macos/SCsub2
-rw-r--r--platform/macos/detect.py5
-rw-r--r--platform/macos/dir_access_macos.mm7
-rw-r--r--platform/macos/display_server_macos.mm46
-rw-r--r--platform/macos/godot_application.mm2
-rw-r--r--platform/macos/godot_application_delegate.mm3
-rw-r--r--platform/macos/joypad_macos.cpp619
-rw-r--r--platform/macos/joypad_macos.h111
-rw-r--r--platform/macos/joypad_macos.mm612
-rw-r--r--platform/macos/os_macos.h2
-rw-r--r--platform/macos/os_macos.mm8
-rw-r--r--platform/macos/platform_config.h7
-rw-r--r--platform/macos/platform_macos_builders.py1
-rw-r--r--platform/web/detect.py6
-rw-r--r--platform/web/display_server_web.cpp40
-rw-r--r--platform/web/doc_classes/EditorExportPlatformWeb.xml7
-rw-r--r--platform/windows/detect.py30
-rw-r--r--platform/windows/display_server_windows.cpp413
-rw-r--r--platform/windows/display_server_windows.h5
-rw-r--r--platform/windows/godot_res.rc5
-rw-r--r--platform/windows/platform_windows_builders.py1
38 files changed, 1383 insertions, 1049 deletions
diff --git a/platform/android/detect.py b/platform/android/detect.py
index 98b3ecdeff..fea8ec3287 100644
--- a/platform/android/detect.py
+++ b/platform/android/detect.py
@@ -69,6 +69,7 @@ def get_flags():
return [
("arch", "arm64"), # Default for convenience.
("target", "template_debug"),
+ ("supported", ["mono"]),
]
diff --git a/platform/android/doc_classes/EditorExportPlatformAndroid.xml b/platform/android/doc_classes/EditorExportPlatformAndroid.xml
index 64485afeb0..7fce5359ae 100644
--- a/platform/android/doc_classes/EditorExportPlatformAndroid.xml
+++ b/platform/android/doc_classes/EditorExportPlatformAndroid.xml
@@ -274,8 +274,7 @@
<member name="permissions/custom_permissions" type="PackedStringArray" setter="" getter="">
Array of custom permission strings.
</member>
- <member name="permissions/delete_cache_files" type="bool" setter="" getter="">
- Deprecated.
+ <member name="permissions/delete_cache_files" type="bool" setter="" getter="" deprecated="">
</member>
<member name="permissions/delete_packages" type="bool" setter="" getter="">
Allows an application to delete packages. See [url=https://developer.android.com/reference/android/Manifest.permission#DELETE_PACKAGES]DELETE_PACKAGES[/url].
@@ -310,8 +309,7 @@
<member name="permissions/get_package_size" type="bool" setter="" getter="">
Allows an application to find out the space used by any package. See [url=https://developer.android.com/reference/android/Manifest.permission#GET_PACKAGE_SIZE]GET_PACKAGE_SIZE[/url].
</member>
- <member name="permissions/get_tasks" type="bool" setter="" getter="">
- Deprecated in API level 21.
+ <member name="permissions/get_tasks" type="bool" setter="" getter="" deprecated="Deprecated in API level 21.">
</member>
<member name="permissions/get_top_activity_info" type="bool" setter="" getter="">
Allows an application to retrieve private information about the current top activity.
@@ -379,13 +377,11 @@
<member name="permissions/nfc" type="bool" setter="" getter="">
Allows applications to perform I/O operations over NFC. See [url=https://developer.android.com/reference/android/Manifest.permission#NFC]NFC[/url].
</member>
- <member name="permissions/persistent_activity" type="bool" setter="" getter="">
+ <member name="permissions/persistent_activity" type="bool" setter="" getter="" deprecated="Deprecated in API level 15.">
Allow an application to make its activities persistent.
- Deprecated in API level 15.
</member>
- <member name="permissions/process_outgoing_calls" type="bool" setter="" getter="">
+ <member name="permissions/process_outgoing_calls" type="bool" setter="" getter="" deprecated="Deprecated in API level 29.">
Allows an application to see the number being dialed during an outgoing call with the option to redirect the call to a different number or abort the call altogether. See [url=https://developer.android.com/reference/android/Manifest.permission#PROCESS_OUTGOING_CALLS]PROCESS_OUTGOING_CALLS[/url].
- Deprecated in API level 29.
</member>
<member name="permissions/read_calendar" type="bool" setter="" getter="">
Allows an application to read the user's calendar data. See [url=https://developer.android.com/reference/android/Manifest.permission#READ_CALENDAR]READ_CALENDAR[/url].
@@ -396,9 +392,8 @@
<member name="permissions/read_contacts" type="bool" setter="" getter="">
Allows an application to read the user's contacts data. See [url=https://developer.android.com/reference/android/Manifest.permission#READ_CONTACTS]READ_CONTACTS[/url].
</member>
- <member name="permissions/read_external_storage" type="bool" setter="" getter="">
+ <member name="permissions/read_external_storage" type="bool" setter="" getter="" deprecated="Deprecated in API level 33.">
Allows an application to read from external storage. See [url=https://developer.android.com/reference/android/Manifest.permission#READ_EXTERNAL_STORAGE]READ_EXTERNAL_STORAGE[/url].
- Deprecated in API level 33.
</member>
<member name="permissions/read_frame_buffer" type="bool" setter="" getter="">
Allows an application to take screen shots and more generally get access to the frame buffer data.
@@ -406,8 +401,7 @@
<member name="permissions/read_history_bookmarks" type="bool" setter="" getter="">
Allows an application to read (but not write) the user's browsing history and bookmarks.
</member>
- <member name="permissions/read_input_state" type="bool" setter="" getter="">
- Deprecated in API level 16.
+ <member name="permissions/read_input_state" type="bool" setter="" getter="" deprecated="Deprecated in API level 16.">
</member>
<member name="permissions/read_logs" type="bool" setter="" getter="">
Allows an application to read the low-level system log files. See [url=https://developer.android.com/reference/android/Manifest.permission#READ_LOGS]READ_LOGS[/url].
@@ -454,8 +448,7 @@
<member name="permissions/reorder_tasks" type="bool" setter="" getter="">
Allows an application to change the Z-order of tasks. See [url=https://developer.android.com/reference/android/Manifest.permission#REORDER_TASKS]REORDER_TASKS[/url].
</member>
- <member name="permissions/restart_packages" type="bool" setter="" getter="">
- Deprecated in API level 15.
+ <member name="permissions/restart_packages" type="bool" setter="" getter="" deprecated="Deprecated in API level 15.">
</member>
<member name="permissions/send_respond_via_message" type="bool" setter="" getter="">
Allows an application (Phone) to send a request to other applications to handle the respond-via-message action during incoming calls. See [url=https://developer.android.com/reference/android/Manifest.permission#SEND_RESPOND_VIA_MESSAGE]SEND_RESPOND_VIA_MESSAGE[/url].
@@ -484,8 +477,7 @@
<member name="permissions/set_pointer_speed" type="bool" setter="" getter="">
Allows low-level access to setting the pointer speed.
</member>
- <member name="permissions/set_preferred_applications" type="bool" setter="" getter="">
- Deprecated in API level 15.
+ <member name="permissions/set_preferred_applications" type="bool" setter="" getter="" deprecated="Deprecated in API level 15.">
</member>
<member name="permissions/set_process_limit" type="bool" setter="" getter="">
Allows an application to set the maximum number of (not needed) application processes that can be running. See [url=https://developer.android.com/reference/android/Manifest.permission#SET_PROCESS_LIMIT]SET_PROCESS_LIMIT[/url].
@@ -511,8 +503,7 @@
<member name="permissions/subscribed_feeds_read" type="bool" setter="" getter="">
Allows an application to allow access the subscribed feeds ContentProvider.
</member>
- <member name="permissions/subscribed_feeds_write" type="bool" setter="" getter="">
- Deprecated.
+ <member name="permissions/subscribed_feeds_write" type="bool" setter="" getter="" deprecated="">
</member>
<member name="permissions/system_alert_window" type="bool" setter="" getter="">
Allows an app to create windows using the type WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, shown on top of all other apps. See [url=https://developer.android.com/reference/android/Manifest.permission#SYSTEM_ALERT_WINDOW]SYSTEM_ALERT_WINDOW[/url].
@@ -520,8 +511,7 @@
<member name="permissions/transmit_ir" type="bool" setter="" getter="">
Allows using the device's IR transmitter, if available. See [url=https://developer.android.com/reference/android/Manifest.permission#TRANSMIT_IR]TRANSMIT_IR[/url].
</member>
- <member name="permissions/uninstall_shortcut" type="bool" setter="" getter="">
- Deprecated.
+ <member name="permissions/uninstall_shortcut" type="bool" setter="" getter="" deprecated="">
</member>
<member name="permissions/update_device_stats" type="bool" setter="" getter="">
Allows an application to update device statistics. See [url=https://developer.android.com/reference/android/Manifest.permission#UPDATE_DEVICE_STATS]UPDATE_DEVICE_STATS[/url].
diff --git a/platform/android/export/export_plugin.cpp b/platform/android/export/export_plugin.cpp
index d0db7b2e6c..74d22bc44f 100644
--- a/platform/android/export/export_plugin.cpp
+++ b/platform/android/export/export_plugin.cpp
@@ -379,14 +379,15 @@ void EditorExportPlatformAndroid::_check_for_changes_poll_thread(void *ud) {
} else if (p.begins_with("ro.build.version.sdk=")) {
d.api_level = p.get_slice("=", 1).to_int();
} else if (p.begins_with("ro.product.cpu.abi=")) {
- d.description += "CPU: " + p.get_slice("=", 1).strip_edges() + "\n";
+ d.architecture = p.get_slice("=", 1).strip_edges();
+ d.description += "CPU: " + d.architecture + "\n";
} else if (p.begins_with("ro.product.manufacturer=")) {
d.description += "Manufacturer: " + p.get_slice("=", 1).strip_edges() + "\n";
} else if (p.begins_with("ro.board.platform=")) {
d.description += "Chipset: " + p.get_slice("=", 1).strip_edges() + "\n";
} else if (p.begins_with("ro.opengles.version=")) {
uint32_t opengl = p.get_slice("=", 1).to_int();
- d.description += "OpenGL: " + itos(opengl >> 16) + "." + itos((opengl >> 8) & 0xFF) + "." + itos((opengl)&0xFF) + "\n";
+ d.description += "OpenGL: " + itos(opengl >> 16) + "." + itos((opengl >> 8) & 0xFF) + "." + itos((opengl) & 0xFF) + "\n";
}
}
@@ -415,7 +416,7 @@ void EditorExportPlatformAndroid::_check_for_changes_poll_thread(void *ud) {
}
}
- if (EDITOR_GET("export/android/shutdown_adb_on_exit")) {
+ if (ea->has_runnable_preset.is_set() && EDITOR_GET("export/android/shutdown_adb_on_exit")) {
String adb = get_adb_path();
if (!FileAccess::exists(adb)) {
return; //adb not configured
@@ -830,8 +831,9 @@ bool EditorExportPlatformAndroid::_uses_vulkan() {
void EditorExportPlatformAndroid::_notification(int p_what) {
#ifndef ANDROID_ENABLED
if (p_what == NOTIFICATION_POSTINITIALIZE) {
- ERR_FAIL_NULL(EditorExport::get_singleton());
- EditorExport::get_singleton()->connect_presets_runnable_updated(callable_mp(this, &EditorExportPlatformAndroid::_update_preset_status));
+ if (EditorExport::get_singleton()) {
+ EditorExport::get_singleton()->connect_presets_runnable_updated(callable_mp(this, &EditorExportPlatformAndroid::_update_preset_status));
+ }
}
#endif
}
@@ -1911,13 +1913,22 @@ void EditorExportPlatformAndroid::get_export_options(List<ExportOption> *r_optio
}
bool EditorExportPlatformAndroid::get_export_option_visibility(const EditorExportPreset *p_preset, const String &p_option) const {
+ if (p_preset == nullptr) {
+ return true;
+ }
+
+ bool advanced_options_enabled = p_preset->are_advanced_options_enabled();
+ if (p_option == "graphics/opengl_debug" ||
+ p_option == "command_line/extra_args" ||
+ p_option == "permissions/custom_permissions") {
+ return advanced_options_enabled;
+ }
if (p_option == "gradle_build/gradle_build_directory" || p_option == "gradle_build/android_source_template") {
- // @todo These are experimental options - keep them hidden for now.
- //return (bool)p_preset->get("gradle_build/use_gradle_build");
- return false;
- } else if (p_option == "custom_template/debug" || p_option == "custom_template/release") {
+ return advanced_options_enabled && bool(p_preset->get("gradle_build/use_gradle_build"));
+ }
+ if (p_option == "custom_template/debug" || p_option == "custom_template/release") {
// The APK templates are ignored if Gradle build is enabled.
- return !p_preset->get("gradle_build/use_gradle_build");
+ return advanced_options_enabled && !bool(p_preset->get("gradle_build/use_gradle_build"));
}
return true;
}
@@ -1982,6 +1993,12 @@ String EditorExportPlatformAndroid::get_option_tooltip(int p_index) const {
return s;
}
+String EditorExportPlatformAndroid::get_device_architecture(int p_index) const {
+ ERR_FAIL_INDEX_V(p_index, devices.size(), "");
+ MutexLock lock(device_lock);
+ return devices[p_index].architecture;
+}
+
Error EditorExportPlatformAndroid::run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) {
ERR_FAIL_INDEX_V(p_device, devices.size(), ERR_INVALID_PARAMETER);
@@ -2391,9 +2408,22 @@ bool EditorExportPlatformAndroid::has_valid_export_configuration(const Ref<Edito
err += template_err;
}
} else {
+ // Validate the custom gradle android source template.
+ bool android_source_template_valid = false;
+ const String android_source_template = p_preset->get("gradle_build/android_source_template");
+ if (!android_source_template.is_empty()) {
+ android_source_template_valid = FileAccess::exists(android_source_template);
+ if (!android_source_template_valid) {
+ err += TTR("Custom Android source template not found.") + "\n";
+ }
+ }
+
+ // Validate the installed build template.
bool installed_android_build_template = FileAccess::exists(ExportTemplateManager::get_android_build_directory(p_preset).path_join("build.gradle"));
if (!installed_android_build_template) {
- r_missing_templates = !exists_export_template("android_source.zip", &err);
+ if (!android_source_template_valid) {
+ r_missing_templates = !exists_export_template("android_source.zip", &err);
+ }
err += TTR("Android build template not installed in the project. Install it from the Project menu.") + "\n";
} else {
r_missing_templates = false;
diff --git a/platform/android/export/export_plugin.h b/platform/android/export/export_plugin.h
index e25655c6cc..b968302449 100644
--- a/platform/android/export/export_plugin.h
+++ b/platform/android/export/export_plugin.h
@@ -76,6 +76,7 @@ class EditorExportPlatformAndroid : public EditorExportPlatform {
String name;
String description;
int api_level = 0;
+ String architecture;
};
struct APKExportData {
@@ -221,6 +222,8 @@ public:
virtual String get_option_tooltip(int p_index) const override;
+ virtual String get_device_architecture(int p_index) const override;
+
virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) override;
virtual Ref<Texture2D> get_run_icon() const override;
diff --git a/platform/android/java/lib/src/org/godotengine/godot/gl/GLSurfaceView.java b/platform/android/java/lib/src/org/godotengine/godot/gl/GLSurfaceView.java
index ef97aaeab9..bd8c58ad69 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/gl/GLSurfaceView.java
+++ b/platform/android/java/lib/src/org/godotengine/godot/gl/GLSurfaceView.java
@@ -1673,7 +1673,24 @@ public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback
mWantRenderNotification = true;
mRequestRender = true;
mRenderComplete = false;
- mFinishDrawingRunnable = finishDrawing;
+
+ // fix lost old callback when continuous call requestRenderAndNotify
+ //
+ // If continuous call requestRenderAndNotify before trigger old
+ // callback, old callback will lose, cause VRI will wait for SV's
+ // draw to finish forever not calling finishDraw.
+ // https://android.googlesource.com/platform/frameworks/base/+/044fce0b826f2da3a192aac56785b5089143e693%5E%21/
+ //+++++++++++++++++++++++++++++++++++++++++++++++++++
+ final Runnable oldCallback = mFinishDrawingRunnable;
+ mFinishDrawingRunnable = () -> {
+ if (oldCallback != null) {
+ oldCallback.run();
+ }
+ if (finishDrawing != null) {
+ finishDrawing.run();
+ }
+ };
+ //----------------------------------------------------
sGLThreadManager.notifyAll();
}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularContextFactory.java b/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularContextFactory.java
index 01ee41e30b..1f0d8592b3 100644
--- a/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularContextFactory.java
+++ b/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularContextFactory.java
@@ -66,11 +66,15 @@ public class RegularContextFactory implements GLSurfaceView.EGLContextFactory {
GLUtils.checkEglError(TAG, "Before eglCreateContext", egl);
EGLContext context;
+ int[] debug_attrib_list = { EGL_CONTEXT_CLIENT_VERSION, 3, _EGL_CONTEXT_FLAGS_KHR, _EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR, EGL10.EGL_NONE };
+ int[] attrib_list = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL10.EGL_NONE };
if (mUseDebugOpengl) {
- int[] attrib_list = { EGL_CONTEXT_CLIENT_VERSION, 3, _EGL_CONTEXT_FLAGS_KHR, _EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR, EGL10.EGL_NONE };
- context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list);
+ context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, debug_attrib_list);
+ if (context == null || context == EGL10.EGL_NO_CONTEXT) {
+ Log.w(TAG, "creating 'OpenGL Debug' context failed");
+ context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list);
+ }
} else {
- int[] attrib_list = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL10.EGL_NONE };
context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list);
}
GLUtils.checkEglError(TAG, "After eglCreateContext", egl);
diff --git a/platform/ios/app_delegate.mm b/platform/ios/app_delegate.mm
index 32ebf7be44..5a0c57be93 100644
--- a/platform/ios/app_delegate.mm
+++ b/platform/ios/app_delegate.mm
@@ -105,11 +105,17 @@ static ViewController *mainViewController = nil;
// Initialize with default Ambient category.
AVAudioSessionCategory category = AVAudioSessionCategoryAmbient;
+ AVAudioSessionCategoryOptions options = 0;
+
+ if (GLOBAL_GET("audio/general/ios/mix_with_others")) {
+ options |= AVAudioSessionCategoryOptionMixWithOthers;
+ }
if (sessionCategorySetting == SESSION_CATEGORY_MULTI_ROUTE) {
category = AVAudioSessionCategoryMultiRoute;
} else if (sessionCategorySetting == SESSION_CATEGORY_PLAY_AND_RECORD) {
category = AVAudioSessionCategoryPlayAndRecord;
+ options |= AVAudioSessionCategoryOptionDefaultToSpeaker;
} else if (sessionCategorySetting == SESSION_CATEGORY_PLAYBACK) {
category = AVAudioSessionCategoryPlayback;
} else if (sessionCategorySetting == SESSION_CATEGORY_RECORD) {
@@ -118,11 +124,7 @@ static ViewController *mainViewController = nil;
category = AVAudioSessionCategorySoloAmbient;
}
- if (GLOBAL_GET("audio/general/ios/mix_with_others")) {
- [[AVAudioSession sharedInstance] setCategory:category withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
- } else {
- [[AVAudioSession sharedInstance] setCategory:category error:nil];
- }
+ [[AVAudioSession sharedInstance] setCategory:category withOptions:options error:nil];
return YES;
}
diff --git a/platform/ios/detect.py b/platform/ios/detect.py
index 9f929ddf0a..4d6e3ae9ba 100644
--- a/platform/ios/detect.py
+++ b/platform/ios/detect.py
@@ -51,6 +51,7 @@ def get_flags():
("arch", "arm64"), # Default for convenience.
("target", "template_debug"),
("use_volk", False),
+ ("supported", ["mono"]),
]
diff --git a/platform/ios/export/export_plugin.cpp b/platform/ios/export/export_plugin.cpp
index ea2b23cfb9..91d75b0629 100644
--- a/platform/ios/export/export_plugin.cpp
+++ b/platform/ios/export/export_plugin.cpp
@@ -127,7 +127,9 @@ String EditorExportPlatformIOS::get_export_option_warning(const EditorExportPres
void EditorExportPlatformIOS::_notification(int p_what) {
#ifdef MACOS_ENABLED
if (p_what == NOTIFICATION_POSTINITIALIZE) {
- EditorExport::get_singleton()->connect_presets_runnable_updated(callable_mp(this, &EditorExportPlatformIOS::_update_preset_status));
+ if (EditorExport::get_singleton()) {
+ EditorExport::get_singleton()->connect_presets_runnable_updated(callable_mp(this, &EditorExportPlatformIOS::_update_preset_status));
+ }
}
#endif
}
diff --git a/platform/linuxbsd/detect.py b/platform/linuxbsd/detect.py
index 6cd5ea9f41..27dec73b65 100644
--- a/platform/linuxbsd/detect.py
+++ b/platform/linuxbsd/detect.py
@@ -67,6 +67,7 @@ def get_doc_path():
def get_flags():
return [
("arch", detect_arch()),
+ ("supported", ["mono"]),
]
diff --git a/platform/linuxbsd/os_linuxbsd.cpp b/platform/linuxbsd/os_linuxbsd.cpp
index 85846335f7..f29275c910 100644
--- a/platform/linuxbsd/os_linuxbsd.cpp
+++ b/platform/linuxbsd/os_linuxbsd.cpp
@@ -34,6 +34,7 @@
#include "core/io/dir_access.h"
#include "main/main.h"
#include "servers/display_server.h"
+#include "servers/rendering_server.h"
#ifdef X11_ENABLED
#include "x11/display_server_x11.h"
diff --git a/platform/linuxbsd/platform_linuxbsd_builders.py b/platform/linuxbsd/platform_linuxbsd_builders.py
index 58234f3748..85d55f0ac6 100644
--- a/platform/linuxbsd/platform_linuxbsd_builders.py
+++ b/platform/linuxbsd/platform_linuxbsd_builders.py
@@ -3,6 +3,7 @@
All such functions are invoked in a subprocess on Windows to prevent build flakiness.
"""
+
import os
from platform_methods import subprocess_main
diff --git a/platform/linuxbsd/wayland/display_server_wayland.cpp b/platform/linuxbsd/wayland/display_server_wayland.cpp
index c957dea32d..d552dd7b8a 100644
--- a/platform/linuxbsd/wayland/display_server_wayland.cpp
+++ b/platform/linuxbsd/wayland/display_server_wayland.cpp
@@ -193,18 +193,29 @@ void DisplayServerWayland::_show_window() {
bool DisplayServerWayland::has_feature(Feature p_feature) const {
switch (p_feature) {
case FEATURE_MOUSE:
+ case FEATURE_MOUSE_WARP:
case FEATURE_CLIPBOARD:
case FEATURE_CURSOR_SHAPE:
+ case FEATURE_CUSTOM_CURSOR_SHAPE:
case FEATURE_WINDOW_TRANSPARENCY:
+ case FEATURE_HIDPI:
case FEATURE_SWAP_BUFFERS:
case FEATURE_KEEP_SCREEN_ON:
- case FEATURE_CLIPBOARD_PRIMARY:
+ case FEATURE_CLIPBOARD_PRIMARY: {
+ return true;
+ } break;
+
#ifdef DBUS_ENABLED
- case FEATURE_NATIVE_DIALOG:
+ case FEATURE_NATIVE_DIALOG: {
+ return true;
+ } break;
#endif
- case FEATURE_HIDPI: {
+
+#ifdef SPEECHD_ENABLED
+ case FEATURE_TEXT_TO_SPEECH: {
return true;
} break;
+#endif
default: {
return false;
@@ -990,36 +1001,9 @@ void DisplayServerWayland::cursor_set_custom_image(const Ref<Resource> &p_cursor
wayland_thread.cursor_shape_clear_custom_image(p_shape);
}
- Ref<Texture2D> texture = p_cursor;
- ERR_FAIL_COND(!texture.is_valid());
- Size2i texture_size;
-
- Ref<AtlasTexture> atlas_texture = texture;
-
- if (atlas_texture.is_valid()) {
- texture_size.width = atlas_texture->get_region().size.x;
- texture_size.height = atlas_texture->get_region().size.y;
- } else {
- texture_size.width = texture->get_width();
- texture_size.height = texture->get_height();
- }
-
- ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
-
- // NOTE: The Wayland protocol says nothing about cursor size limits, yet if
- // the texture is larger than 256x256 it won't show at least on sway.
- ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
- ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
- ERR_FAIL_COND(texture_size.height == 0 || texture_size.width == 0);
-
- Ref<Image> image = texture->get_image();
- ERR_FAIL_COND(!image.is_valid());
-
- if (image->is_compressed()) {
- image = image->duplicate(true);
- Error err = image->decompress();
- ERR_FAIL_COND_MSG(err != OK, "Couldn't decompress VRAM-compressed custom mouse cursor image. Switch to a lossless compression mode in the Import dock.");
- }
+ Rect2 atlas_rect;
+ Ref<Image> image = _get_cursor_image_from_resource(p_cursor, p_hotspot, atlas_rect);
+ ERR_FAIL_COND(image.is_null());
CustomCursor &cursor = custom_cursors[p_shape];
diff --git a/platform/linuxbsd/wayland/display_server_wayland.h b/platform/linuxbsd/wayland/display_server_wayland.h
index e42967eb7b..5b8db1be47 100644
--- a/platform/linuxbsd/wayland/display_server_wayland.h
+++ b/platform/linuxbsd/wayland/display_server_wayland.h
@@ -59,8 +59,6 @@
#include "core/config/project_settings.h"
#include "core/input/input.h"
-#include "scene/resources/atlas_texture.h"
-#include "scene/resources/texture.h"
#include "servers/display_server.h"
#include <limits.h>
diff --git a/platform/linuxbsd/wayland/wayland_thread.cpp b/platform/linuxbsd/wayland/wayland_thread.cpp
index ebb21722e2..8167642345 100644
--- a/platform/linuxbsd/wayland/wayland_thread.cpp
+++ b/platform/linuxbsd/wayland/wayland_thread.cpp
@@ -448,14 +448,11 @@ void WaylandThread::_wl_registry_on_global(void *data, struct wl_registry *wl_re
zwp_primary_selection_device_v1_add_listener(ss->wp_primary_selection_device, &wp_primary_selection_device_listener, ss);
}
-#if 0
- // FIXME: Broken.
if (!ss->wp_tablet_seat && registry->wp_tablet_manager) {
// Tablet.
ss->wp_tablet_seat = zwp_tablet_manager_v2_get_tablet_seat(registry->wp_tablet_manager, wl_seat);
zwp_tablet_seat_v2_add_listener(ss->wp_tablet_seat, &wp_tablet_seat_listener, ss);
}
-#endif
registry->wl_seats.push_back(wl_seat);
@@ -541,13 +538,11 @@ void WaylandThread::_wl_registry_on_global(void *data, struct wl_registry *wl_re
return;
}
-#if 0
- // FIXME: Broken.
if (strcmp(interface, zwp_tablet_manager_v2_interface.name) == 0) {
registry->wp_tablet_manager = (struct zwp_tablet_manager_v2 *)wl_registry_bind(wl_registry, name, &zwp_tablet_manager_v2_interface, 1);
registry->wp_tablet_manager_name = name;
- // This global creates some seats data. Let's do that for the ones already available.
+ // This global creates some seat data. Let's do that for the ones already available.
for (struct wl_seat *wl_seat : registry->wl_seats) {
SeatState *ss = wl_seat_get_seat_state(wl_seat);
ERR_FAIL_NULL(ss);
@@ -558,7 +553,6 @@ void WaylandThread::_wl_registry_on_global(void *data, struct wl_registry *wl_re
return;
}
-#endif
}
void WaylandThread::_wl_registry_on_global_remove(void *data, struct wl_registry *wl_registry, uint32_t name) {
@@ -820,8 +814,6 @@ void WaylandThread::_wl_registry_on_global_remove(void *data, struct wl_registry
return;
}
-#if 0
- // FIXME: Broken.
if (name == registry->wp_tablet_manager_name) {
if (registry->wp_tablet_manager) {
zwp_tablet_manager_v2_destroy(registry->wp_tablet_manager);
@@ -835,25 +827,27 @@ void WaylandThread::_wl_registry_on_global_remove(void *data, struct wl_registry
SeatState *ss = wl_seat_get_seat_state(wl_seat);
ERR_FAIL_NULL(ss);
- List<struct zwp_tablet_tool_v2 *>::Element *it = ss->tablet_tools.front();
-
- while (it) {
- zwp_tablet_tool_v2_destroy(it->get());
- ss->tablet_tools.erase(it);
+ for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {
+ TabletToolState *state = wp_tablet_tool_get_state(tool);
+ if (state) {
+ memdelete(state);
+ }
- it = it->next();
+ zwp_tablet_tool_v2_destroy(tool);
}
+
+ ss->tablet_tools.clear();
}
return;
}
-#endif
{
// Iterate through all of the seats to find if any got removed.
- List<struct wl_seat *>::Element *it = registry->wl_seats.front();
- while (it) {
- struct wl_seat *wl_seat = it->get();
+ List<struct wl_seat *>::Element *E = registry->wl_seats.front();
+ while (E) {
+ struct wl_seat *wl_seat = E->get();
+ List<struct wl_seat *>::Element *N = E->next();
SeatState *ss = wl_seat_get_seat_state(wl_seat);
ERR_FAIL_NULL(ss);
@@ -867,28 +861,26 @@ void WaylandThread::_wl_registry_on_global_remove(void *data, struct wl_registry
wl_data_device_destroy(ss->wl_data_device);
}
-#if 0
- // FIXME: Broken.
if (ss->wp_tablet_seat) {
zwp_tablet_seat_v2_destroy(ss->wp_tablet_seat);
for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {
+ TabletToolState *state = wp_tablet_tool_get_state(tool);
+ if (state) {
+ memdelete(state);
+ }
+
zwp_tablet_tool_v2_destroy(tool);
}
}
- // Let's destroy all tools.
- for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {
- zwp_tablet_tool_v2_destroy(tool);
- }
-
memdelete(ss);
- registry->wl_seats.erase(it);
-#endif
+
+ registry->wl_seats.erase(E);
return;
}
- it = it->next();
+ E = N;
}
}
@@ -2160,82 +2152,80 @@ void WaylandThread::_wp_primary_selection_source_on_cancelled(void *data, struct
}
void WaylandThread::_wp_tablet_seat_on_tablet_added(void *data, struct zwp_tablet_seat_v2 *zwp_tablet_seat_v2, struct zwp_tablet_v2 *id) {
- DEBUG_LOG_WAYLAND_THREAD(vformat("wp tablet seat %x on tablet %x added", (size_t)zwp_tablet_seat_v2, (size_t)id));
}
void WaylandThread::_wp_tablet_seat_on_tool_added(void *data, struct zwp_tablet_seat_v2 *zwp_tablet_seat_v2, struct zwp_tablet_tool_v2 *id) {
SeatState *ss = (SeatState *)data;
ERR_FAIL_NULL(ss);
- ss->tablet_tools.push_back(id);
+ TabletToolState *state = memnew(TabletToolState);
+ state->wl_seat = ss->wl_seat;
- zwp_tablet_tool_v2_add_listener(id, &wp_tablet_tool_listener, ss);
+ wl_proxy_tag_godot((struct wl_proxy *)id);
+ zwp_tablet_tool_v2_add_listener(id, &wp_tablet_tool_listener, state);
- DEBUG_LOG_WAYLAND_THREAD(vformat("wp tablet seat %x on tool %x added", (size_t)zwp_tablet_seat_v2, (size_t)id));
+ ss->tablet_tools.push_back(id);
}
void WaylandThread::_wp_tablet_seat_on_pad_added(void *data, struct zwp_tablet_seat_v2 *zwp_tablet_seat_v2, struct zwp_tablet_pad_v2 *id) {
- DEBUG_LOG_WAYLAND_THREAD(vformat("wp tablet seat %x on pad %x added", (size_t)zwp_tablet_seat_v2, (size_t)id));
}
void WaylandThread::_wp_tablet_tool_on_type(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2, uint32_t tool_type) {
- DEBUG_LOG_WAYLAND_THREAD(vformat("wp tablet tool %x on type %d", (size_t)zwp_tablet_tool_v2, tool_type));
+ TabletToolState *state = wp_tablet_tool_get_state(zwp_tablet_tool_v2);
+
+ if (state && tool_type == ZWP_TABLET_TOOL_V2_TYPE_ERASER) {
+ state->is_eraser = true;
+ }
}
void WaylandThread::_wp_tablet_tool_on_hardware_serial(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2, uint32_t hardware_serial_hi, uint32_t hardware_serial_lo) {
- DEBUG_LOG_WAYLAND_THREAD(vformat("wp tablet tool %x on hardware serial %x%x", (size_t)zwp_tablet_tool_v2, hardware_serial_hi, hardware_serial_lo));
}
void WaylandThread::_wp_tablet_tool_on_hardware_id_wacom(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2, uint32_t hardware_id_hi, uint32_t hardware_id_lo) {
- DEBUG_LOG_WAYLAND_THREAD(vformat("wp tablet tool %x on hardware id wacom hardware id %x%x", (size_t)zwp_tablet_tool_v2, hardware_id_hi, hardware_id_lo));
}
void WaylandThread::_wp_tablet_tool_on_capability(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2, uint32_t capability) {
- SeatState *ss = (SeatState *)data;
- ERR_FAIL_NULL(ss);
-
- if (capability == ZWP_TABLET_TOOL_V2_TYPE_ERASER) {
- ss->tablet_tool_data_buffer.is_eraser = true;
- }
-
- DEBUG_LOG_WAYLAND_THREAD(vformat("wp tablet tool %x on capability %d", (size_t)zwp_tablet_tool_v2, capability));
}
void WaylandThread::_wp_tablet_tool_on_done(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2) {
- DEBUG_LOG_WAYLAND_THREAD(vformat("wp tablet tool %x on done", (size_t)zwp_tablet_tool_v2));
}
void WaylandThread::_wp_tablet_tool_on_removed(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2) {
- SeatState *ss = (SeatState *)data;
- ERR_FAIL_NULL(ss);
+ TabletToolState *ts = wp_tablet_tool_get_state(zwp_tablet_tool_v2);
+ SeatState *ss = wl_seat_get_seat_state(ts->wl_seat);
- List<struct zwp_tablet_tool_v2 *>::Element *it = ss->tablet_tools.front();
+ if (!ts || !ss) {
+ return;
+ }
- while (it) {
- struct zwp_tablet_tool_v2 *tool = it->get();
+ List<struct zwp_tablet_tool_v2 *>::Element *E = ss->tablet_tools.find(zwp_tablet_tool_v2);
- if (tool == zwp_tablet_tool_v2) {
- zwp_tablet_tool_v2_destroy(tool);
- ss->tablet_tools.erase(it);
- break;
+ if (E && E->get()) {
+ struct zwp_tablet_tool_v2 *tool = E->get();
+ TabletToolState *state = wp_tablet_tool_get_state(tool);
+ if (state) {
+ memdelete(state);
}
- }
- DEBUG_LOG_WAYLAND_THREAD(vformat("wp tablet tool %x on removed", (size_t)zwp_tablet_tool_v2));
+ zwp_tablet_tool_v2_destroy(tool);
+ ss->tablet_tools.erase(E);
+ }
}
void WaylandThread::_wp_tablet_tool_on_proximity_in(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2, uint32_t serial, struct zwp_tablet_v2 *tablet, struct wl_surface *surface) {
- SeatState *ss = (SeatState *)data;
- ERR_FAIL_NULL(ss);
+ TabletToolState *ts = wp_tablet_tool_get_state(zwp_tablet_tool_v2);
+ SeatState *ss = wl_seat_get_seat_state(ts->wl_seat);
+
+ if (!ts || !ss) {
+ return;
+ }
WaylandThread *wayland_thread = ss->wayland_thread;
ERR_FAIL_NULL(wayland_thread);
- ss->tablet_tool_data_buffer.in_proximity = true;
-
- ss->pointer_enter_serial = serial;
- ss->pointed_surface = surface;
- ss->last_pointed_surface = surface;
+ ts->data_pending.proximity_serial = serial;
+ ts->data_pending.proximal_surface = surface;
+ ts->last_surface = surface;
Ref<WindowEventMessage> msg;
msg.instantiate();
@@ -2243,21 +2233,20 @@ void WaylandThread::_wp_tablet_tool_on_proximity_in(void *data, struct zwp_table
wayland_thread->push_message(msg);
DEBUG_LOG_WAYLAND_THREAD("Tablet tool entered window.");
-
- DEBUG_LOG_WAYLAND_THREAD(vformat("wp tablet tool %x on proximity in serial %d tablet %x surface %x", (size_t)zwp_tablet_tool_v2, serial, (size_t)tablet, (size_t)surface));
}
void WaylandThread::_wp_tablet_tool_on_proximity_out(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2) {
- SeatState *ss = (SeatState *)data;
- ERR_FAIL_NULL(ss);
+ TabletToolState *ts = wp_tablet_tool_get_state(zwp_tablet_tool_v2);
+ SeatState *ss = wl_seat_get_seat_state(ts->wl_seat);
+
+ if (!ts || !ss) {
+ return;
+ }
WaylandThread *wayland_thread = ss->wayland_thread;
ERR_FAIL_NULL(wayland_thread);
- ss->pointed_surface = nullptr;
- ss->tablet_tool_data_buffer.in_proximity = false;
-
- DEBUG_LOG_WAYLAND_THREAD("Tablet tool left window.");
+ ts->data_pending.proximal_surface = nullptr;
Ref<WindowEventMessage> msg;
msg.instantiate();
@@ -2265,16 +2254,18 @@ void WaylandThread::_wp_tablet_tool_on_proximity_out(void *data, struct zwp_tabl
wayland_thread->push_message(msg);
- DEBUG_LOG_WAYLAND_THREAD(vformat("wp tablet tool %x on proximity out", (size_t)zwp_tablet_tool_v2));
+ DEBUG_LOG_WAYLAND_THREAD("Tablet tool left window.");
}
void WaylandThread::_wp_tablet_tool_on_down(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2, uint32_t serial) {
- SeatState *ss = (SeatState *)data;
- ERR_FAIL_NULL(ss);
+ TabletToolState *ts = wp_tablet_tool_get_state(zwp_tablet_tool_v2);
+
+ if (!ts) {
+ return;
+ }
- TabletToolData &td = ss->tablet_tool_data_buffer;
+ TabletToolData &td = ts->data_pending;
- td.touching = true;
td.pressed_button_mask.set_flag(mouse_button_to_mask(MouseButton::LEFT));
td.last_button_pressed = MouseButton::LEFT;
td.double_click_begun = true;
@@ -2282,45 +2273,53 @@ void WaylandThread::_wp_tablet_tool_on_down(void *data, struct zwp_tablet_tool_v
// The protocol doesn't cover this, but we can use this funky hack to make
// double clicking work.
td.button_time = OS::get_singleton()->get_ticks_msec();
-
- DEBUG_LOG_WAYLAND_THREAD(vformat("wp tablet tool %x on down serial %x", (size_t)zwp_tablet_tool_v2, serial));
}
void WaylandThread::_wp_tablet_tool_on_up(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2) {
- SeatState *ss = (SeatState *)data;
- ERR_FAIL_NULL(ss);
+ TabletToolState *ts = wp_tablet_tool_get_state(zwp_tablet_tool_v2);
- TabletToolData &td = ss->tablet_tool_data_buffer;
+ if (!ts) {
+ return;
+ }
+
+ TabletToolData &td = ts->data_pending;
- td.touching = false;
td.pressed_button_mask.clear_flag(mouse_button_to_mask(MouseButton::LEFT));
// The protocol doesn't cover this, but we can use this funky hack to make
// double clicking work.
td.button_time = OS::get_singleton()->get_ticks_msec();
-
- DEBUG_LOG_WAYLAND_THREAD(vformat("wp tablet tool %x on up", (size_t)zwp_tablet_tool_v2));
}
void WaylandThread::_wp_tablet_tool_on_motion(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2, wl_fixed_t x, wl_fixed_t y) {
- SeatState *ss = (SeatState *)data;
- ERR_FAIL_NULL(ss);
+ TabletToolState *ts = wp_tablet_tool_get_state(zwp_tablet_tool_v2);
- WindowState *ws = wl_surface_get_window_state(ss->pointed_surface);
+ if (!ts) {
+ return;
+ }
+
+ WindowState *ws = wl_surface_get_window_state(ts->data_pending.proximal_surface);
ERR_FAIL_NULL(ws);
- double scale_factor = window_state_get_scale_factor(ws);
+ TabletToolData &td = ts->data_pending;
- TabletToolData &td = ss->tablet_tool_data_buffer;
+ double scale_factor = window_state_get_scale_factor(ws);
+ td.position.x = wl_fixed_to_int(x);
+ td.position.y = wl_fixed_to_int(y);
td.position = scale_vector2i(td.position, scale_factor);
+
+ td.motion_time = OS::get_singleton()->get_ticks_msec();
}
void WaylandThread::_wp_tablet_tool_on_pressure(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2, uint32_t pressure) {
- SeatState *ss = (SeatState *)data;
- ERR_FAIL_NULL(ss);
+ TabletToolState *ts = wp_tablet_tool_get_state(zwp_tablet_tool_v2);
+
+ if (!ts) {
+ return;
+ }
- ss->tablet_tool_data_buffer.pressure = pressure;
+ ts->data_pending.pressure = pressure;
}
void WaylandThread::_wp_tablet_tool_on_distance(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2, uint32_t distance) {
@@ -2328,11 +2327,16 @@ void WaylandThread::_wp_tablet_tool_on_distance(void *data, struct zwp_tablet_to
}
void WaylandThread::_wp_tablet_tool_on_tilt(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2, wl_fixed_t tilt_x, wl_fixed_t tilt_y) {
- SeatState *ss = (SeatState *)data;
- ERR_FAIL_NULL(ss);
+ TabletToolState *ts = wp_tablet_tool_get_state(zwp_tablet_tool_v2);
+
+ if (!ts) {
+ return;
+ }
- ss->tablet_tool_data_buffer.tilt.x = wl_fixed_to_double(tilt_x);
- ss->tablet_tool_data_buffer.tilt.y = wl_fixed_to_double(tilt_y);
+ TabletToolData &td = ts->data_pending;
+
+ td.tilt.x = wl_fixed_to_double(tilt_x);
+ td.tilt.y = wl_fixed_to_double(tilt_y);
}
void WaylandThread::_wp_tablet_tool_on_rotation(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2, wl_fixed_t degrees) {
@@ -2348,10 +2352,13 @@ void WaylandThread::_wp_tablet_tool_on_wheel(void *data, struct zwp_tablet_tool_
}
void WaylandThread::_wp_tablet_tool_on_button(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2, uint32_t serial, uint32_t button, uint32_t state) {
- SeatState *ss = (SeatState *)data;
- ERR_FAIL_NULL(ss);
+ TabletToolState *ts = wp_tablet_tool_get_state(zwp_tablet_tool_v2);
- TabletToolData &td = ss->tablet_tool_data_buffer;
+ if (!ts) {
+ return;
+ }
+
+ TabletToolData &td = ts->data_pending;
MouseButton mouse_button = MouseButton::NONE;
@@ -2381,14 +2388,18 @@ void WaylandThread::_wp_tablet_tool_on_button(void *data, struct zwp_tablet_tool
}
void WaylandThread::_wp_tablet_tool_on_frame(void *data, struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2, uint32_t time) {
- SeatState *ss = (SeatState *)data;
- ERR_FAIL_NULL(ss);
+ TabletToolState *ts = wp_tablet_tool_get_state(zwp_tablet_tool_v2);
+ SeatState *ss = wl_seat_get_seat_state(ts->wl_seat);
+
+ if (!ts || !ss) {
+ return;
+ }
WaylandThread *wayland_thread = ss->wayland_thread;
ERR_FAIL_NULL(wayland_thread);
- TabletToolData &old_td = ss->tablet_tool_data;
- TabletToolData &td = ss->tablet_tool_data_buffer;
+ TabletToolData &old_td = ts->data;
+ TabletToolData &td = ts->data_pending;
if (old_td.position != td.position || old_td.tilt != td.tilt || old_td.pressure != td.pressure) {
Ref<InputEventMouseMotion> mm;
@@ -2411,25 +2422,24 @@ void WaylandThread::_wp_tablet_tool_on_frame(void *data, struct zwp_tablet_tool_
// straight from the compositor, so we have to normalize them here.
// According to the tablet proto spec, tilt is expressed in degrees relative
- // to the Z axis of the tablet, so it shouldn't go over 90 degrees, I think.
- // TODO: Investigate whether the tilt can go over 90 degrees (it shouldn't).
+ // to the Z axis of the tablet, so it shouldn't go over 90 degrees either way,
+ // I think. We'll clamp it just in case.
+ td.tilt = td.tilt.clamp(Vector2(-90, -90), Vector2(90, 90));
+
mm->set_tilt(td.tilt / 90);
// The tablet proto spec explicitly says that pressure is defined as a value
// between 0 to 65535.
mm->set_pressure(td.pressure / (float)65535);
- // FIXME: Tool handling is broken.
- mm->set_pen_inverted(td.is_eraser);
+ mm->set_pen_inverted(ts->is_eraser);
mm->set_relative(td.position - old_td.position);
mm->set_relative_screen_position(mm->get_relative());
- // FIXME: Stop doing this to calculate speed.
- // FIXME2: It has been done, port this from the pointer logic once this works again.
- Input::get_singleton()->set_mouse_position(td.position);
- mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
- mm->set_screen_velocity(mm->get_velocity());
+ Vector2i pos_delta = td.position - old_td.position;
+ uint32_t time_delta = td.motion_time - td.motion_time;
+ mm->set_velocity((Vector2)pos_delta / time_delta);
Ref<InputEventMessage> inputev_msg;
inputev_msg.instantiate();
@@ -2618,6 +2628,15 @@ WaylandThread::SeatState *WaylandThread::wl_seat_get_seat_state(struct wl_seat *
return nullptr;
}
+// Returns the wp_tablet_tool's `TabletToolState`, otherwise `nullptr`.
+// NOTE: This will fail if the output isn't tagged as ours.
+WaylandThread::TabletToolState *WaylandThread::wp_tablet_tool_get_state(struct zwp_tablet_tool_v2 *p_tool) {
+ if (p_tool && wl_proxy_is_godot((wl_proxy *)p_tool)) {
+ return (TabletToolState *)zwp_tablet_tool_v2_get_user_data(p_tool);
+ }
+
+ return nullptr;
+}
// Returns the wl_data_offer's `OfferState`, otherwise `nullptr`.
// NOTE: This will fail if the output isn't tagged as ours.
WaylandThread::OfferState *WaylandThread::wl_data_offer_get_offer_state(struct wl_data_offer *p_offer) {
@@ -4070,14 +4089,16 @@ void WaylandThread::destroy() {
zwp_confined_pointer_v1_destroy(ss->wp_confined_pointer);
}
-#if 0
- // FIXME: Broken.
if (ss->wp_tablet_seat) {
zwp_tablet_seat_v2_destroy(ss->wp_tablet_seat);
}
-#endif
for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {
+ TabletToolState *state = wp_tablet_tool_get_state(tool);
+ if (state) {
+ memdelete(state);
+ }
+
zwp_tablet_tool_v2_destroy(tool);
}
diff --git a/platform/linuxbsd/wayland/wayland_thread.h b/platform/linuxbsd/wayland/wayland_thread.h
index f3e3c3a2ac..d49f0c9d34 100644
--- a/platform/linuxbsd/wayland/wayland_thread.h
+++ b/platform/linuxbsd/wayland/wayland_thread.h
@@ -308,7 +308,7 @@ public:
struct TabletToolData {
Point2i position;
- Vector2i tilt;
+ Vector2 tilt;
uint32_t pressure = 0;
BitField<MouseButtonMask> pressed_button_mask;
@@ -322,10 +322,20 @@ public:
// be used as a mouse...), but we'll hack one in with the current ticks.
uint64_t button_time = 0;
+ uint64_t motion_time = 0;
+
+ uint32_t proximity_serial = 0;
+ struct wl_surface *proximal_surface = nullptr;
+ };
+
+ struct TabletToolState {
+ struct wl_seat *wl_seat = nullptr;
+
+ struct wl_surface *last_surface = nullptr;
bool is_eraser = false;
- bool in_proximity = false;
- bool touching = false;
+ TabletToolData data_pending;
+ TabletToolData data;
};
struct OfferState {
@@ -425,9 +435,6 @@ public:
struct zwp_tablet_seat_v2 *wp_tablet_seat = nullptr;
List<struct zwp_tablet_tool_v2 *> tablet_tools;
-
- TabletToolData tablet_tool_data_buffer;
- TabletToolData tablet_tool_data;
};
struct CustomCursor {
@@ -855,6 +862,7 @@ public:
static WindowState *wl_surface_get_window_state(struct wl_surface *p_surface);
static ScreenState *wl_output_get_screen_state(struct wl_output *p_output);
static SeatState *wl_seat_get_seat_state(struct wl_seat *p_seat);
+ static TabletToolState *wp_tablet_tool_get_state(struct zwp_tablet_tool_v2 *p_tool);
static OfferState *wl_data_offer_get_offer_state(struct wl_data_offer *p_offer);
static OfferState *wp_primary_selection_offer_get_offer_state(struct zwp_primary_selection_offer_v1 *p_offer);
diff --git a/platform/linuxbsd/x11/display_server_x11.cpp b/platform/linuxbsd/x11/display_server_x11.cpp
index 35bfe81827..d58b5b93d7 100644
--- a/platform/linuxbsd/x11/display_server_x11.cpp
+++ b/platform/linuxbsd/x11/display_server_x11.cpp
@@ -41,7 +41,6 @@
#include "core/string/ustring.h"
#include "drivers/png/png_driver_common.h"
#include "main/main.h"
-#include "scene/resources/atlas_texture.h"
#if defined(VULKAN_ENABLED)
#include "servers/rendering/renderer_rd/renderer_compositor_rd.h"
@@ -3064,39 +3063,10 @@ void DisplayServerX11::cursor_set_custom_image(const Ref<Resource> &p_cursor, Cu
cursors_cache.erase(p_shape);
}
- Ref<Texture2D> texture = p_cursor;
- ERR_FAIL_COND(!texture.is_valid());
- Ref<AtlasTexture> atlas_texture = p_cursor;
- Size2i texture_size;
- Rect2i atlas_rect;
-
- if (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 {
- texture_size.width = texture->get_width();
- texture_size.height = texture->get_height();
- }
-
- ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
- ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
- ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
-
- Ref<Image> image = texture->get_image();
-
- ERR_FAIL_COND(!image.is_valid());
- if (image->is_compressed()) {
- image = image->duplicate(true);
- Error err = image->decompress();
- ERR_FAIL_COND_MSG(err != OK, "Couldn't decompress VRAM-compressed custom mouse cursor image. Switch to a lossless compression mode in the Import dock.");
- }
+ Rect2 atlas_rect;
+ Ref<Image> image = _get_cursor_image_from_resource(p_cursor, p_hotspot, atlas_rect);
+ ERR_FAIL_COND(image.is_null());
+ Vector2i texture_size = image->get_size();
// Create the cursor structure
XcursorImage *cursor_image = XcursorImageCreate(texture_size.width, texture_size.height);
@@ -3115,7 +3085,7 @@ void DisplayServerX11::cursor_set_custom_image(const Ref<Resource> &p_cursor, Cu
int row_index = floor(index / texture_size.width) + atlas_rect.position.y;
int column_index = (index % int(texture_size.width)) + atlas_rect.position.x;
- if (atlas_texture.is_valid()) {
+ if (atlas_rect.has_area()) {
column_index = MIN(column_index, atlas_rect.size.width - 1);
row_index = MIN(row_index, atlas_rect.size.height - 1);
}
diff --git a/platform/macos/SCsub b/platform/macos/SCsub
index 08783ee14a..355772fcd2 100644
--- a/platform/macos/SCsub
+++ b/platform/macos/SCsub
@@ -115,7 +115,7 @@ files = [
"godot_open_save_delegate.mm",
"dir_access_macos.mm",
"tts_macos.mm",
- "joypad_macos.cpp",
+ "joypad_macos.mm",
"rendering_context_driver_vulkan_macos.mm",
"gl_manager_macos_angle.mm",
"gl_manager_macos_legacy.mm",
diff --git a/platform/macos/detect.py b/platform/macos/detect.py
index cfbe9a8ee7..ed9e59ae05 100644
--- a/platform/macos/detect.py
+++ b/platform/macos/detect.py
@@ -56,6 +56,7 @@ def get_flags():
return [
("arch", detect_arch()),
("use_volk", False),
+ ("supported", ["mono"]),
]
@@ -207,7 +208,9 @@ def configure(env: "SConsEnvironment"):
"-framework",
"IOKit",
"-framework",
- "ForceFeedback",
+ "GameController",
+ "-framework",
+ "CoreHaptics",
"-framework",
"CoreVideo",
"-framework",
diff --git a/platform/macos/dir_access_macos.mm b/platform/macos/dir_access_macos.mm
index 66d81f2687..37f717c9de 100644
--- a/platform/macos/dir_access_macos.mm
+++ b/platform/macos/dir_access_macos.mm
@@ -41,9 +41,10 @@
String DirAccessMacOS::fix_unicode_name(const char *p_name) const {
String fname;
- NSString *nsstr = [[NSString stringWithUTF8String:p_name] precomposedStringWithCanonicalMapping];
-
- fname.parse_utf8([nsstr UTF8String]);
+ if (p_name != nullptr) {
+ NSString *nsstr = [[NSString stringWithUTF8String:p_name] precomposedStringWithCanonicalMapping];
+ fname.parse_utf8([nsstr UTF8String]);
+ }
return fname;
}
diff --git a/platform/macos/display_server_macos.mm b/platform/macos/display_server_macos.mm
index ce4c7b2e05..2d6e614a05 100644
--- a/platform/macos/display_server_macos.mm
+++ b/platform/macos/display_server_macos.mm
@@ -48,7 +48,6 @@
#include "core/os/keyboard.h"
#include "drivers/png/png_driver_common.h"
#include "main/main.h"
-#include "scene/resources/atlas_texture.h"
#include "scene/resources/image_texture.h"
#if defined(GLES3_ENABLED)
@@ -2559,7 +2558,7 @@ bool DisplayServerMacOS::update_mouse_wrap(WindowData &p_wd, NSPoint &r_delta, N
}
// Confine mouse position to the window, and update delta.
- NSRect frame = [p_wd.window_object frame];
+ NSRect frame = [p_wd.window_view frame];
NSPoint conf_pos = r_mpos;
conf_pos.x = CLAMP(conf_pos.x + r_delta.x, 0.f, frame.size.width);
conf_pos.y = CLAMP(conf_pos.y - r_delta.y, 0.f, frame.size.height);
@@ -2686,7 +2685,7 @@ Ref<Image> DisplayServerMacOS::clipboard_get_image() const {
return image;
}
NSBitmapImageRep *bitmap = [NSBitmapImageRep imageRepWithData:data];
- NSData *pngData = [bitmap representationUsingType:NSPNGFileType properties:@{}];
+ NSData *pngData = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
image.instantiate();
PNGDriverCommon::png_to_image((const uint8_t *)pngData.bytes, pngData.length, false, image);
return image;
@@ -4037,39 +4036,10 @@ void DisplayServerMacOS::cursor_set_custom_image(const Ref<Resource> &p_cursor,
cursors_cache.erase(p_shape);
}
- Ref<Texture2D> texture = p_cursor;
- ERR_FAIL_COND(!texture.is_valid());
- Ref<AtlasTexture> atlas_texture = p_cursor;
- Size2 texture_size;
Rect2 atlas_rect;
-
- if (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 {
- texture_size.width = texture->get_width();
- texture_size.height = texture->get_height();
- }
-
- ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
- ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
- ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
-
- Ref<Image> image = texture->get_image();
-
- ERR_FAIL_COND(!image.is_valid());
- if (image->is_compressed()) {
- image = image->duplicate(true);
- Error err = image->decompress();
- ERR_FAIL_COND_MSG(err != OK, "Couldn't decompress VRAM-compressed custom mouse cursor image. Switch to a lossless compression mode in the Import dock.");
- }
+ Ref<Image> image = _get_cursor_image_from_resource(p_cursor, p_hotspot, atlas_rect);
+ ERR_FAIL_COND(image.is_null());
+ Vector2i texture_size = image->get_size();
NSBitmapImageRep *imgrep = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:nullptr
@@ -4092,7 +4062,7 @@ void DisplayServerMacOS::cursor_set_custom_image(const Ref<Resource> &p_cursor,
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()) {
+ if (atlas_rect.has_area()) {
column_index = MIN(column_index, atlas_rect.size.width - 1);
row_index = MIN(row_index, atlas_rect.size.height - 1);
}
@@ -4102,7 +4072,7 @@ void DisplayServerMacOS::cursor_set_custom_image(const Ref<Resource> &p_cursor,
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;
+ pixels[i * 4 + 2] = ((color) & 0xFF) * alpha / 255;
pixels[i * 4 + 3] = alpha;
}
@@ -4905,7 +4875,7 @@ DisplayServerMacOS::~DisplayServerMacOS() {
}
// Destroy all status indicators.
- for (HashMap<IndicatorID, IndicatorData>::Iterator E = indicators.begin(); E;) {
+ for (HashMap<IndicatorID, IndicatorData>::Iterator E = indicators.begin(); E; ++E) {
[[NSStatusBar systemStatusBar] removeStatusItem:E->value.item];
}
diff --git a/platform/macos/godot_application.mm b/platform/macos/godot_application.mm
index e3a744caa2..f5e1bb43bf 100644
--- a/platform/macos/godot_application.mm
+++ b/platform/macos/godot_application.mm
@@ -100,7 +100,7 @@
}
- (void)sendEvent:(NSEvent *)event {
- if ([event type] == NSSystemDefined && [event subtype] == 8) {
+ if ([event type] == NSEventTypeSystemDefined && [event subtype] == 8) {
int keyCode = (([event data1] & 0xFFFF0000) >> 16);
int keyFlags = ([event data1] & 0x0000FFFF);
int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
diff --git a/platform/macos/godot_application_delegate.mm b/platform/macos/godot_application_delegate.mm
index 2e76d4aa97..b3759e66f5 100644
--- a/platform/macos/godot_application_delegate.mm
+++ b/platform/macos/godot_application_delegate.mm
@@ -125,7 +125,8 @@
- (void)applicationDidFinishLaunching:(NSNotification *)notice {
NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
- NSString *nsbundleid_env = [NSString stringWithUTF8String:getenv("__CFBundleIdentifier")];
+ const char *bundled_id = getenv("__CFBundleIdentifier");
+ NSString *nsbundleid_env = [NSString stringWithUTF8String:(bundled_id != nullptr) ? bundled_id : ""];
NSString *nsbundleid = [[NSBundle mainBundle] bundleIdentifier];
if (nsappname == nil || isatty(STDOUT_FILENO) || isatty(STDIN_FILENO) || isatty(STDERR_FILENO) || ![nsbundleid isEqualToString:nsbundleid_env]) {
// If the executable is started from terminal or is not bundled, macOS WindowServer won't register and activate app window correctly (menu and title bar are grayed out and input ignored).
diff --git a/platform/macos/joypad_macos.cpp b/platform/macos/joypad_macos.cpp
deleted file mode 100644
index 1fcd636a4b..0000000000
--- a/platform/macos/joypad_macos.cpp
+++ /dev/null
@@ -1,619 +0,0 @@
-/**************************************************************************/
-/* joypad_macos.cpp */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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. */
-/**************************************************************************/
-
-#include "joypad_macos.h"
-
-#include <machine/endian.h>
-
-#define GODOT_JOY_LOOP_RUN_MODE CFSTR("GodotJoypad")
-
-static JoypadMacOS *self = nullptr;
-
-joypad::joypad() {
- ff_constant_force.lMagnitude = 10000;
- ff_effect.dwDuration = 0;
- ff_effect.dwSamplePeriod = 0;
- ff_effect.dwGain = 10000;
- ff_effect.dwFlags = FFEFF_OBJECTOFFSETS;
- ff_effect.dwTriggerButton = FFEB_NOTRIGGER;
- ff_effect.dwStartDelay = 0;
- ff_effect.dwTriggerRepeatInterval = 0;
- ff_effect.lpEnvelope = nullptr;
- ff_effect.cbTypeSpecificParams = sizeof(FFCONSTANTFORCE);
- ff_effect.lpvTypeSpecificParams = &ff_constant_force;
- ff_effect.dwSize = sizeof(ff_effect);
-}
-
-void joypad::free() {
- if (device_ref) {
- IOHIDDeviceUnscheduleFromRunLoop(device_ref, CFRunLoopGetCurrent(), GODOT_JOY_LOOP_RUN_MODE);
- }
- if (ff_device) {
- FFDeviceReleaseEffect(ff_device, ff_object);
- FFReleaseDevice(ff_device);
- ff_device = nullptr;
- memfree(ff_axes);
- memfree(ff_directions);
- }
-}
-
-bool joypad::has_element(IOHIDElementCookie p_cookie, Vector<rec_element> *p_list) const {
- for (int i = 0; i < p_list->size(); i++) {
- if (p_cookie == p_list->get(i).cookie) {
- return true;
- }
- }
- return false;
-}
-
-int joypad::get_hid_element_state(rec_element *p_element) const {
- int value = 0;
- if (p_element && p_element->ref) {
- IOHIDValueRef valueRef;
- if (IOHIDDeviceGetValue(device_ref, p_element->ref, &valueRef) == kIOReturnSuccess) {
- value = (SInt32)IOHIDValueGetIntegerValue(valueRef);
-
- // Record min and max for auto calibration.
- if (value < p_element->min) {
- p_element->min = value;
- }
- if (value > p_element->max) {
- p_element->max = value;
- }
- }
- }
- return value;
-}
-
-void joypad::add_hid_element(IOHIDElementRef p_element) {
- const CFTypeID elementTypeID = p_element ? CFGetTypeID(p_element) : 0;
-
- if (p_element && (elementTypeID == IOHIDElementGetTypeID())) {
- const IOHIDElementCookie cookie = IOHIDElementGetCookie(p_element);
- const uint32_t usagePage = IOHIDElementGetUsagePage(p_element);
- const uint32_t usage = IOHIDElementGetUsage(p_element);
- Vector<rec_element> *list = nullptr;
-
- switch (IOHIDElementGetType(p_element)) {
- case kIOHIDElementTypeInput_Misc:
- case kIOHIDElementTypeInput_Button:
- case kIOHIDElementTypeInput_Axis: {
- switch (usagePage) {
- case kHIDPage_GenericDesktop:
- switch (usage) {
- case kHIDUsage_GD_X:
- case kHIDUsage_GD_Y:
- case kHIDUsage_GD_Z:
- case kHIDUsage_GD_Rx:
- case kHIDUsage_GD_Ry:
- case kHIDUsage_GD_Rz:
- case kHIDUsage_GD_Slider:
- case kHIDUsage_GD_Dial:
- case kHIDUsage_GD_Wheel:
- if (!has_element(cookie, &axis_elements)) {
- list = &axis_elements;
- }
- break;
-
- case kHIDUsage_GD_Hatswitch:
- if (!has_element(cookie, &hat_elements)) {
- list = &hat_elements;
- }
- break;
- case kHIDUsage_GD_DPadUp:
- case kHIDUsage_GD_DPadDown:
- case kHIDUsage_GD_DPadRight:
- case kHIDUsage_GD_DPadLeft:
- case kHIDUsage_GD_Start:
- case kHIDUsage_GD_Select:
- if (!has_element(cookie, &button_elements)) {
- list = &button_elements;
- }
- break;
- }
- break;
-
- case kHIDPage_Simulation:
- switch (usage) {
- case kHIDUsage_Sim_Rudder:
- case kHIDUsage_Sim_Throttle:
- case kHIDUsage_Sim_Accelerator:
- case kHIDUsage_Sim_Brake:
- if (!has_element(cookie, &axis_elements)) {
- list = &axis_elements;
- }
- break;
-
- default:
- break;
- }
- break;
-
- case kHIDPage_Button:
- case kHIDPage_Consumer:
- if (!has_element(cookie, &button_elements)) {
- list = &button_elements;
- }
- break;
-
- default:
- break;
- }
- } break;
-
- case kIOHIDElementTypeCollection: {
- CFArrayRef array = IOHIDElementGetChildren(p_element);
- if (array) {
- add_hid_elements(array);
- }
- } break;
-
- default:
- break;
- }
-
- if (list) { // Add to list.
- rec_element element;
-
- element.ref = p_element;
- element.usage = usage;
-
- element.min = (SInt32)IOHIDElementGetLogicalMin(p_element);
- element.max = (SInt32)IOHIDElementGetLogicalMax(p_element);
- element.cookie = IOHIDElementGetCookie(p_element);
- list->push_back(element);
- list->sort_custom<rec_element::Comparator>();
- }
- }
-}
-
-static void hid_element_added(const void *p_value, void *p_parameter) {
- joypad *joy = static_cast<joypad *>(p_parameter);
- joy->add_hid_element((IOHIDElementRef)p_value);
-}
-
-void joypad::add_hid_elements(CFArrayRef p_array) {
- CFRange range = { 0, CFArrayGetCount(p_array) };
- CFArrayApplyFunction(p_array, range, hid_element_added, this);
-}
-
-static void joypad_removed_callback(void *ctx, IOReturn res, void *sender, IOHIDDeviceRef ioHIDDeviceObject) {
- self->_device_removed(res, ioHIDDeviceObject);
-}
-
-static void joypad_added_callback(void *ctx, IOReturn res, void *sender, IOHIDDeviceRef ioHIDDeviceObject) {
- self->_device_added(res, ioHIDDeviceObject);
-}
-
-static bool is_joypad(IOHIDDeviceRef p_device_ref) {
- int usage_page = 0;
- int usage = 0;
- CFTypeRef refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDPrimaryUsagePageKey));
- if (refCF) {
- CFNumberGetValue((CFNumberRef)refCF, kCFNumberSInt32Type, &usage_page);
- }
- if (usage_page != kHIDPage_GenericDesktop) {
- return false;
- }
-
- refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDPrimaryUsageKey));
- if (refCF) {
- CFNumberGetValue((CFNumberRef)refCF, kCFNumberSInt32Type, &usage);
- }
- if ((usage != kHIDUsage_GD_Joystick &&
- usage != kHIDUsage_GD_GamePad &&
- usage != kHIDUsage_GD_MultiAxisController)) {
- return false;
- }
- return true;
-}
-
-void JoypadMacOS::_device_added(IOReturn p_res, IOHIDDeviceRef p_device) {
- if (p_res != kIOReturnSuccess || have_device(p_device)) {
- return;
- }
-
- joypad new_joypad;
- if (is_joypad(p_device)) {
- configure_joypad(p_device, &new_joypad);
-#if MAC_OS_X_VERSION_MIN_REQUIRED < 1060
- if (IOHIDDeviceGetService) {
-#endif
- const io_service_t ioservice = IOHIDDeviceGetService(p_device);
- if ((ioservice) && (FFIsForceFeedback(ioservice) == FF_OK) && new_joypad.config_force_feedback(ioservice)) {
- new_joypad.ffservice = ioservice;
- }
-#if MAC_OS_X_VERSION_MIN_REQUIRED < 1060
- }
-#endif
- device_list.push_back(new_joypad);
- }
- IOHIDDeviceScheduleWithRunLoop(p_device, CFRunLoopGetCurrent(), GODOT_JOY_LOOP_RUN_MODE);
-}
-
-void JoypadMacOS::_device_removed(IOReturn p_res, IOHIDDeviceRef p_device) {
- int device = get_joy_ref(p_device);
- ERR_FAIL_COND(device == -1);
-
- input->joy_connection_changed(device_list[device].id, false, "");
- device_list.write[device].free();
- device_list.remove_at(device);
-}
-
-static String _hex_str(uint8_t p_byte) {
- static const char *dict = "0123456789abcdef";
- char ret[3];
- ret[2] = 0;
-
- ret[0] = dict[p_byte >> 4];
- ret[1] = dict[p_byte & 0xF];
-
- return ret;
-}
-
-bool JoypadMacOS::configure_joypad(IOHIDDeviceRef p_device_ref, joypad *p_joy) {
- p_joy->device_ref = p_device_ref;
- // Get device name.
- String name;
- char c_name[256];
- CFTypeRef refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDProductKey));
- if (!refCF) {
- refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDManufacturerKey));
- }
- if ((!refCF) || (!CFStringGetCString((CFStringRef)refCF, c_name, sizeof(c_name), kCFStringEncodingUTF8))) {
- name = "Unidentified Joypad";
- } else {
- name = c_name;
- }
-
- int id = input->get_unused_joy_id();
- ERR_FAIL_COND_V(id == -1, false);
- p_joy->id = id;
- int vendor = 0;
- refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDVendorIDKey));
- if (refCF) {
- CFNumberGetValue((CFNumberRef)refCF, kCFNumberSInt32Type, &vendor);
- }
-
- int product_id = 0;
- refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDProductIDKey));
- if (refCF) {
- CFNumberGetValue((CFNumberRef)refCF, kCFNumberSInt32Type, &product_id);
- }
-
- int version = 0;
- refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDVersionNumberKey));
- if (refCF) {
- CFNumberGetValue((CFNumberRef)refCF, kCFNumberSInt32Type, &version);
- }
-
- if (vendor && product_id) {
- char uid[128];
- snprintf(uid, 128, "%08x%08x%08x%08x", OSSwapHostToBigInt32(3), OSSwapHostToBigInt32(vendor), OSSwapHostToBigInt32(product_id), OSSwapHostToBigInt32(version));
- input->joy_connection_changed(id, true, name, uid);
- } else {
- // Bluetooth device.
- String guid = "05000000";
- for (int i = 0; i < 12; i++) {
- if (i < name.size()) {
- guid += _hex_str(name[i]);
- } else {
- guid += "00";
- }
- }
- input->joy_connection_changed(id, true, name, guid);
- }
-
- CFArrayRef array = IOHIDDeviceCopyMatchingElements(p_device_ref, nullptr, kIOHIDOptionsTypeNone);
- if (array) {
- p_joy->add_hid_elements(array);
- CFRelease(array);
- }
- // Xbox controller hat values start at 1 rather than 0.
- p_joy->offset_hat = vendor == 0x45e &&
- (product_id == 0x0b05 ||
- product_id == 0x02e0 ||
- product_id == 0x02fd ||
- product_id == 0x0b13);
-
- return true;
-}
-
-#define FF_ERR() \
- { \
- if (ret != FF_OK) { \
- FFReleaseDevice(ff_device); \
- ff_device = nullptr; \
- return false; \
- } \
- }
-bool joypad::config_force_feedback(io_service_t p_service) {
- HRESULT ret = FFCreateDevice(p_service, &ff_device);
- ERR_FAIL_COND_V(ret != FF_OK, false);
-
- ret = FFDeviceSendForceFeedbackCommand(ff_device, FFSFFC_RESET);
- FF_ERR();
-
- ret = FFDeviceSendForceFeedbackCommand(ff_device, FFSFFC_SETACTUATORSON);
- FF_ERR();
-
- if (check_ff_features()) {
- ret = FFDeviceCreateEffect(ff_device, kFFEffectType_ConstantForce_ID, &ff_effect, &ff_object);
- FF_ERR();
- return true;
- }
- FFReleaseDevice(ff_device);
- ff_device = nullptr;
- return false;
-}
-#undef FF_ERR
-
-#define TEST_FF(ff) (features.supportedEffects & (ff))
-bool joypad::check_ff_features() {
- FFCAPABILITIES features;
- HRESULT ret = FFDeviceGetForceFeedbackCapabilities(ff_device, &features);
- if (ret == FF_OK && (features.supportedEffects & FFCAP_ET_CONSTANTFORCE)) {
- uint32_t val;
- ret = FFDeviceGetForceFeedbackProperty(ff_device, FFPROP_FFGAIN, &val, sizeof(val));
- if (ret != FF_OK) {
- return false;
- }
- int num_axes = features.numFfAxes;
- ff_axes = (DWORD *)memalloc(sizeof(DWORD) * num_axes);
- ff_directions = (LONG *)memalloc(sizeof(LONG) * num_axes);
-
- for (int i = 0; i < num_axes; i++) {
- ff_axes[i] = features.ffAxes[i];
- ff_directions[i] = 0;
- }
-
- ff_effect.cAxes = num_axes;
- ff_effect.rgdwAxes = ff_axes;
- ff_effect.rglDirection = ff_directions;
- return true;
- }
- return false;
-}
-
-static BitField<HatMask> process_hat_value(int p_min, int p_max, int p_value, bool p_offset_hat) {
- int range = (p_max - p_min + 1);
- int value = p_value - p_min;
- BitField<HatMask> hat_value;
- if (range == 4) {
- value *= 2;
- }
- if (p_offset_hat) {
- value -= 1;
- }
-
- switch (value) {
- case 0:
- hat_value.set_flag(HatMask::UP);
- break;
- case 1:
- hat_value.set_flag(HatMask::UP);
- hat_value.set_flag(HatMask::RIGHT);
- break;
- case 2:
- hat_value.set_flag(HatMask::RIGHT);
- break;
- case 3:
- hat_value.set_flag(HatMask::DOWN);
- hat_value.set_flag(HatMask::RIGHT);
- break;
- case 4:
- hat_value.set_flag(HatMask::DOWN);
- break;
- case 5:
- hat_value.set_flag(HatMask::DOWN);
- hat_value.set_flag(HatMask::LEFT);
- break;
- case 6:
- hat_value.set_flag(HatMask::LEFT);
- break;
- case 7:
- hat_value.set_flag(HatMask::UP);
- hat_value.set_flag(HatMask::LEFT);
- break;
- default:
- break;
- }
- return hat_value;
-}
-
-void JoypadMacOS::poll_joypads() const {
- while (CFRunLoopRunInMode(GODOT_JOY_LOOP_RUN_MODE, 0, TRUE) == kCFRunLoopRunHandledSource) {
- // No-op. Pending callbacks will fire.
- }
-}
-
-static float axis_correct(int p_value, int p_min, int p_max) {
- // Convert to a value between -1.0f and 1.0f.
- return 2.0f * (p_value - p_min) / (p_max - p_min) - 1.0f;
-}
-
-void JoypadMacOS::process_joypads() {
- poll_joypads();
-
- for (int i = 0; i < device_list.size(); i++) {
- joypad &joy = device_list.write[i];
-
- for (int j = 0; j < joy.axis_elements.size(); j++) {
- rec_element &elem = joy.axis_elements.write[j];
- int value = joy.get_hid_element_state(&elem);
- input->joy_axis(joy.id, (JoyAxis)j, axis_correct(value, elem.min, elem.max));
- }
- for (int j = 0; j < joy.button_elements.size(); j++) {
- int value = joy.get_hid_element_state(&joy.button_elements.write[j]);
- input->joy_button(joy.id, (JoyButton)j, (value >= 1));
- }
- for (int j = 0; j < joy.hat_elements.size(); j++) {
- rec_element &elem = joy.hat_elements.write[j];
- int value = joy.get_hid_element_state(&elem);
- BitField<HatMask> hat_value = process_hat_value(elem.min, elem.max, value, joy.offset_hat);
- input->joy_hat(joy.id, hat_value);
- }
-
- if (joy.ffservice) {
- uint64_t timestamp = input->get_joy_vibration_timestamp(joy.id);
- if (timestamp > joy.ff_timestamp) {
- Vector2 strength = input->get_joy_vibration_strength(joy.id);
- float duration = input->get_joy_vibration_duration(joy.id);
- if (strength.x == 0 && strength.y == 0) {
- joypad_vibration_stop(joy.id, timestamp);
- } else {
- float gain = MAX(strength.x, strength.y);
- joypad_vibration_start(joy.id, gain, duration, timestamp);
- }
- }
- }
- }
-}
-
-void JoypadMacOS::joypad_vibration_start(int p_id, float p_magnitude, float p_duration, uint64_t p_timestamp) {
- joypad *joy = &device_list.write[get_joy_index(p_id)];
- joy->ff_timestamp = p_timestamp;
- joy->ff_effect.dwDuration = p_duration * FF_SECONDS;
- joy->ff_effect.dwGain = p_magnitude * FF_FFNOMINALMAX;
- FFEffectSetParameters(joy->ff_object, &joy->ff_effect, FFEP_DURATION | FFEP_GAIN);
- FFEffectStart(joy->ff_object, 1, 0);
-}
-
-void JoypadMacOS::joypad_vibration_stop(int p_id, uint64_t p_timestamp) {
- joypad *joy = &device_list.write[get_joy_index(p_id)];
- joy->ff_timestamp = p_timestamp;
- FFEffectStop(joy->ff_object);
-}
-
-int JoypadMacOS::get_joy_index(int p_id) const {
- for (int i = 0; i < device_list.size(); i++) {
- if (device_list[i].id == p_id) {
- return i;
- }
- }
- return -1;
-}
-
-int JoypadMacOS::get_joy_ref(IOHIDDeviceRef p_device) const {
- for (int i = 0; i < device_list.size(); i++) {
- if (device_list[i].device_ref == p_device) {
- return i;
- }
- }
- return -1;
-}
-
-bool JoypadMacOS::have_device(IOHIDDeviceRef p_device) const {
- for (int i = 0; i < device_list.size(); i++) {
- if (device_list[i].device_ref == p_device) {
- return true;
- }
- }
- return false;
-}
-
-static CFDictionaryRef create_match_dictionary(const UInt32 page, const UInt32 usage, int *okay) {
- CFDictionaryRef retval = nullptr;
- CFNumberRef pageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &page);
- CFNumberRef usageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage);
-
- if (pageNumRef && usageNumRef) {
- const void *keys[2] = { (void *)CFSTR(kIOHIDDeviceUsagePageKey), (void *)CFSTR(kIOHIDDeviceUsageKey) };
- const void *vals[2] = { (void *)pageNumRef, (void *)usageNumRef };
- retval = CFDictionaryCreate(kCFAllocatorDefault, keys, vals, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
- }
-
- if (pageNumRef) {
- CFRelease(pageNumRef);
- }
- if (usageNumRef) {
- CFRelease(usageNumRef);
- }
-
- if (!retval) {
- *okay = 0;
- }
-
- return retval;
-}
-
-void JoypadMacOS::config_hid_manager(CFArrayRef p_matching_array) const {
- CFRunLoopRef runloop = CFRunLoopGetCurrent();
- IOReturn ret = IOHIDManagerOpen(hid_manager, kIOHIDOptionsTypeNone);
- ERR_FAIL_COND(ret != kIOReturnSuccess);
-
- IOHIDManagerSetDeviceMatchingMultiple(hid_manager, p_matching_array);
- IOHIDManagerRegisterDeviceMatchingCallback(hid_manager, joypad_added_callback, nullptr);
- IOHIDManagerRegisterDeviceRemovalCallback(hid_manager, joypad_removed_callback, nullptr);
- IOHIDManagerScheduleWithRunLoop(hid_manager, runloop, GODOT_JOY_LOOP_RUN_MODE);
-
- while (CFRunLoopRunInMode(GODOT_JOY_LOOP_RUN_MODE, 0, TRUE) == kCFRunLoopRunHandledSource) {
- // No-op. Callback fires once per existing device.
- }
-}
-
-JoypadMacOS::JoypadMacOS(Input *in) {
- self = this;
- input = in;
-
- int okay = 1;
- const void *vals[] = {
- (void *)create_match_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_Joystick, &okay),
- (void *)create_match_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_GamePad, &okay),
- (void *)create_match_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_MultiAxisController, &okay),
- };
- const size_t n_elements = sizeof(vals) / sizeof(vals[0]);
- CFArrayRef array = okay ? CFArrayCreate(kCFAllocatorDefault, vals, n_elements, &kCFTypeArrayCallBacks) : nullptr;
-
- for (size_t i = 0; i < n_elements; i++) {
- if (vals[i]) {
- CFRelease((CFTypeRef)vals[i]);
- }
- }
-
- if (array) {
- hid_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
- if (hid_manager) {
- config_hid_manager(array);
- }
- CFRelease(array);
- }
-}
-
-JoypadMacOS::~JoypadMacOS() {
- for (int i = 0; i < device_list.size(); i++) {
- device_list.write[i].free();
- }
-
- IOHIDManagerUnscheduleFromRunLoop(hid_manager, CFRunLoopGetCurrent(), GODOT_JOY_LOOP_RUN_MODE);
- IOHIDManagerClose(hid_manager, kIOHIDOptionsTypeNone);
- CFRelease(hid_manager);
- hid_manager = nullptr;
-}
diff --git a/platform/macos/joypad_macos.h b/platform/macos/joypad_macos.h
index 6a2af11b51..b37a1b24f3 100644
--- a/platform/macos/joypad_macos.h
+++ b/platform/macos/joypad_macos.h
@@ -28,93 +28,62 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
-#ifndef JOYPAD_MACOS_H
-#define JOYPAD_MACOS_H
-
#include "core/input/input.h"
-#import <ForceFeedback/ForceFeedback.h>
-#import <ForceFeedback/ForceFeedbackConstants.h>
-#import <IOKit/hid/IOHIDLib.h>
-#import <Kernel/IOKit/hidsystem/IOHIDUsageTables.h>
-
-struct rec_element {
- IOHIDElementRef ref;
- IOHIDElementCookie cookie;
+#define Key _QKey
+#import <CoreHaptics/CoreHaptics.h>
+#import <GameController/GameController.h>
+#undef Key
- uint32_t usage = 0;
+@interface JoypadMacOSObserver : NSObject
- int min = 0;
- int max = 0;
+- (void)startObserving;
+- (void)startProcessing;
+- (void)finishObserving;
- struct Comparator {
- bool operator()(const rec_element p_a, const rec_element p_b) const { return p_a.usage < p_b.usage; }
- };
-};
+@end
-struct joypad {
- IOHIDDeviceRef device_ref = nullptr;
+API_AVAILABLE(macosx(11))
+@interface RumbleMotor : NSObject
+@property(strong, nonatomic) CHHapticEngine *engine;
+@property(strong, nonatomic) id<CHHapticPatternPlayer> player;
+@end
- Vector<rec_element> axis_elements;
- Vector<rec_element> button_elements;
- Vector<rec_element> hat_elements;
+API_AVAILABLE(macosx(11))
+@interface RumbleContext : NSObject
+// High frequency motor, it's usually the right engine.
+@property(strong, nonatomic) RumbleMotor *weak_motor;
+// Low frequency motor, it's usually the left engine.
+@property(strong, nonatomic) RumbleMotor *strong_motor;
+@end
- int id = 0;
- bool offset_hat = false;
+// Controller support for macOS begins with macOS 10.9+,
+// however haptics (vibrations) are only supported in macOS 11+.
+@interface Joypad : NSObject
- io_service_t ffservice = 0; // Interface for force feedback, 0 = no ff.
- FFCONSTANTFORCE ff_constant_force;
- FFDeviceObjectReference ff_device = nullptr;
- FFEffectObjectReference ff_object = nullptr;
- uint64_t ff_timestamp = 0;
- LONG *ff_directions = nullptr;
- FFEFFECT ff_effect;
- DWORD *ff_axes = nullptr;
+@property(assign, nonatomic) BOOL force_feedback;
+@property(assign, nonatomic) NSInteger ff_effect_timestamp;
+@property(strong, nonatomic) GCController *controller;
+@property(strong, nonatomic) RumbleContext *rumble_context API_AVAILABLE(macosx(11));
- void add_hid_elements(CFArrayRef p_array);
- void add_hid_element(IOHIDElementRef p_element);
+- (instancetype)init;
+- (instancetype)init:(GCController *)controller;
- bool has_element(IOHIDElementCookie p_cookie, Vector<rec_element> *p_list) const;
- bool config_force_feedback(io_service_t p_service);
- bool check_ff_features();
-
- int get_hid_element_state(rec_element *p_element) const;
-
- void free();
- joypad();
-};
+@end
class JoypadMacOS {
- enum {
- JOYPADS_MAX = 16,
- };
-
private:
- Input *input = nullptr;
- IOHIDManagerRef hid_manager;
-
- Vector<joypad> device_list;
-
- bool have_device(IOHIDDeviceRef p_device) const;
- bool configure_joypad(IOHIDDeviceRef p_device_ref, joypad *p_joy);
-
- int get_joy_index(int p_id) const;
- int get_joy_ref(IOHIDDeviceRef p_device) const;
-
- void poll_joypads() const;
- void config_hid_manager(CFArrayRef p_matching_array) const;
-
- void joypad_vibration_start(int p_id, float p_magnitude, float p_duration, uint64_t p_timestamp);
- void joypad_vibration_stop(int p_id, uint64_t p_timestamp);
+ JoypadMacOSObserver *observer;
public:
- void process_joypads();
+ JoypadMacOS();
+ ~JoypadMacOS();
- void _device_added(IOReturn p_res, IOHIDDeviceRef p_device);
- void _device_removed(IOReturn p_res, IOHIDDeviceRef p_device);
+ API_AVAILABLE(macosx(11))
+ void joypad_vibration_start(Joypad *p_joypad, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp);
+ API_AVAILABLE(macosx(11))
+ void joypad_vibration_stop(Joypad *p_joypad, uint64_t p_timestamp);
- JoypadMacOS(Input *in);
- ~JoypadMacOS();
+ void start_processing();
+ void process_joypads();
};
-
-#endif // JOYPAD_MACOS_H
diff --git a/platform/macos/joypad_macos.mm b/platform/macos/joypad_macos.mm
new file mode 100644
index 0000000000..8cd5cdd9f2
--- /dev/null
+++ b/platform/macos/joypad_macos.mm
@@ -0,0 +1,612 @@
+/**************************************************************************/
+/* joypad_macos.mm */
+/**************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/**************************************************************************/
+/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* 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. */
+/**************************************************************************/
+
+#import "joypad_macos.h"
+
+#include <Foundation/Foundation.h>
+
+#import "os_macos.h"
+
+#include "core/config/project_settings.h"
+#include "core/os/keyboard.h"
+#include "core/string/ustring.h"
+#include "main/main.h"
+
+@implementation RumbleMotor
+
+- (instancetype)initWithController:(GCController *)controller locality:(GCHapticsLocality)locality {
+ self = [super init];
+ self.engine = [controller.haptics createEngineWithLocality:locality];
+ self.player = nil;
+ return self;
+}
+
+- (void)execute_pattern:(CHHapticPattern *)pattern {
+ NSError *error;
+ id<CHHapticPatternPlayer> player = [self.engine createPlayerWithPattern:pattern error:&error];
+
+ // When all players have stopped for an engine, stop the engine.
+ [self.engine notifyWhenPlayersFinished:^CHHapticEngineFinishedAction(NSError *_Nullable error) {
+ return CHHapticEngineFinishedActionStopEngine;
+ }];
+
+ self.player = player;
+
+ // Starts the engine and returns if an error was encountered.
+ if (![self.engine startAndReturnError:&error]) {
+ print_verbose("Couldn't start controller haptic engine");
+ return;
+ }
+ if (![self.player startAtTime:0 error:&error]) {
+ print_verbose("Couldn't execute controller haptic pattern");
+ }
+}
+
+- (void)stop {
+ NSError *error;
+ [self.player stopAtTime:0 error:&error];
+ self.player = nil;
+}
+
+@end
+
+@implementation RumbleContext
+
+- (instancetype)init {
+ self = [super init];
+ self.weak_motor = nil;
+ self.strong_motor = nil;
+ return self;
+}
+
+- (bool)hasMotors {
+ return self.weak_motor != nil && self.strong_motor != nil;
+}
+- (bool)hasActivePlayers {
+ if (![self hasMotors]) {
+ return NO;
+ }
+ return self.weak_motor.player != nil && self.strong_motor.player != nil;
+}
+
+@end
+
+@implementation Joypad
+
+- (instancetype)init {
+ self = [super init];
+ return self;
+}
+- (instancetype)init:(GCController *)controller {
+ self = [super init];
+ self.controller = controller;
+
+ if (@available(macOS 11, *)) {
+ // Haptics within the controller is only available in macOS 11+.
+ self.rumble_context = [[RumbleContext alloc] init];
+
+ // Create Weak and Strong motors for controller.
+ self.rumble_context.weak_motor = [[RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityRightHandle];
+ self.rumble_context.strong_motor = [[RumbleMotor alloc] initWithController:controller locality:GCHapticsLocalityLeftHandle];
+
+ // If the rumble motors aren't available, disable force feedback.
+ if (![self.rumble_context hasMotors]) {
+ self.force_feedback = NO;
+ } else {
+ self.force_feedback = YES;
+ }
+ } else {
+ self.force_feedback = NO;
+ }
+
+ self.ff_effect_timestamp = 0;
+
+ return self;
+}
+
+@end
+
+JoypadMacOS::JoypadMacOS() {
+ observer = [[JoypadMacOSObserver alloc] init];
+ [observer startObserving];
+
+ if (@available(macOS 11.3, *)) {
+ GCController.shouldMonitorBackgroundEvents = YES;
+ }
+}
+
+JoypadMacOS::~JoypadMacOS() {
+ if (observer) {
+ [observer finishObserving];
+ observer = nil;
+ }
+}
+
+void JoypadMacOS::start_processing() {
+ if (observer) {
+ [observer startProcessing];
+ }
+ process_joypads();
+}
+
+API_AVAILABLE(macosx(10.15))
+CHHapticPattern *get_vibration_pattern(float p_magnitude, float p_duration) {
+ // Creates a vibration pattern with an intensity and duration.
+ NSDictionary *hapticDict = @{
+ CHHapticPatternKeyPattern : @[
+ @{
+ CHHapticPatternKeyEvent : @{
+ CHHapticPatternKeyEventType : CHHapticEventTypeHapticContinuous,
+ CHHapticPatternKeyTime : @(CHHapticTimeImmediate),
+ CHHapticPatternKeyEventDuration : [NSNumber numberWithFloat:p_duration],
+
+ CHHapticPatternKeyEventParameters : @[
+ @{
+ CHHapticPatternKeyParameterID : CHHapticEventParameterIDHapticIntensity,
+ CHHapticPatternKeyParameterValue : [NSNumber numberWithFloat:p_magnitude]
+ },
+ ],
+ },
+ },
+ ],
+ };
+ NSError *error;
+ CHHapticPattern *pattern = [[CHHapticPattern alloc] initWithDictionary:hapticDict error:&error];
+ return pattern;
+}
+
+void JoypadMacOS::joypad_vibration_start(Joypad *p_joypad, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp) {
+ if (!p_joypad.force_feedback || p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
+ return;
+ }
+
+ // If there is active vibration players, stop them.
+ if ([p_joypad.rumble_context hasActivePlayers]) {
+ joypad_vibration_stop(p_joypad, p_timestamp);
+ }
+
+ // Gets the default vibration pattern and creates a player for each motor.
+ CHHapticPattern *weak_pattern = get_vibration_pattern(p_weak_magnitude, p_duration);
+ CHHapticPattern *strong_pattern = get_vibration_pattern(p_strong_magnitude, p_duration);
+
+ RumbleMotor *weak_motor = p_joypad.rumble_context.weak_motor;
+ RumbleMotor *strong_motor = p_joypad.rumble_context.strong_motor;
+
+ [weak_motor execute_pattern:weak_pattern];
+ [strong_motor execute_pattern:strong_pattern];
+
+ p_joypad.ff_effect_timestamp = p_timestamp;
+}
+
+void JoypadMacOS::joypad_vibration_stop(Joypad *p_joypad, uint64_t p_timestamp) {
+ if (!p_joypad.force_feedback) {
+ return;
+ }
+ // If there is no active vibration players, exit.
+ if (![p_joypad.rumble_context hasActivePlayers]) {
+ return;
+ }
+
+ RumbleMotor *weak_motor = p_joypad.rumble_context.weak_motor;
+ RumbleMotor *strong_motor = p_joypad.rumble_context.strong_motor;
+
+ [weak_motor stop];
+ [strong_motor stop];
+
+ p_joypad.ff_effect_timestamp = p_timestamp;
+}
+
+@interface JoypadMacOSObserver ()
+
+@property(assign, nonatomic) BOOL isObserving;
+@property(assign, nonatomic) BOOL isProcessing;
+@property(strong, nonatomic) NSMutableDictionary<NSNumber *, Joypad *> *connectedJoypads;
+@property(strong, nonatomic) NSMutableArray<Joypad *> *joypadsQueue;
+
+@end
+
+@implementation JoypadMacOSObserver
+
+- (instancetype)init {
+ self = [super init];
+
+ if (self) {
+ [self godot_commonInit];
+ }
+
+ return self;
+}
+
+- (void)godot_commonInit {
+ self.isObserving = NO;
+ self.isProcessing = NO;
+}
+
+- (void)startProcessing {
+ self.isProcessing = YES;
+
+ for (GCController *controller in self.joypadsQueue) {
+ [self addMacOSJoypad:controller];
+ }
+
+ [self.joypadsQueue removeAllObjects];
+}
+
+- (void)startObserving {
+ if (self.isObserving) {
+ return;
+ }
+
+ self.isObserving = YES;
+
+ self.connectedJoypads = [NSMutableDictionary dictionary];
+ self.joypadsQueue = [NSMutableArray array];
+
+ // Get told when controllers connect, this will be called right away for
+ // already connected controllers.
+ [[NSNotificationCenter defaultCenter]
+ addObserver:self
+ selector:@selector(controllerWasConnected:)
+ name:GCControllerDidConnectNotification
+ object:nil];
+
+ // Get told when controllers disconnect.
+ [[NSNotificationCenter defaultCenter]
+ addObserver:self
+ selector:@selector(controllerWasDisconnected:)
+ name:GCControllerDidDisconnectNotification
+ object:nil];
+}
+
+- (void)finishObserving {
+ if (self.isObserving) {
+ [[NSNotificationCenter defaultCenter] removeObserver:self];
+ }
+
+ self.isObserving = NO;
+ self.isProcessing = NO;
+
+ self.connectedJoypads = nil;
+ self.joypadsQueue = nil;
+}
+
+- (void)dealloc {
+ [self finishObserving];
+}
+
+- (NSArray<NSNumber *> *)getAllKeysForController:(GCController *)controller {
+ NSArray *keys = [self.connectedJoypads allKeys];
+ NSMutableArray *final_keys = [NSMutableArray array];
+
+ for (NSNumber *key in keys) {
+ Joypad *joypad = [self.connectedJoypads objectForKey:key];
+ if (joypad.controller == controller) {
+ [final_keys addObject:key];
+ }
+ }
+
+ return final_keys;
+}
+
+- (int)getJoyIdForController:(GCController *)controller {
+ NSArray *keys = [self getAllKeysForController:controller];
+
+ for (NSNumber *key in keys) {
+ int joy_id = [key intValue];
+ return joy_id;
+ }
+
+ return -1;
+}
+
+- (void)addMacOSJoypad:(GCController *)controller {
+ // Get a new id for our controller.
+ int joy_id = Input::get_singleton()->get_unused_joy_id();
+
+ if (joy_id == -1) {
+ print_verbose("Couldn't retrieve new joy ID.");
+ return;
+ }
+
+ // Assign our player index.
+ if (controller.playerIndex == GCControllerPlayerIndexUnset) {
+ controller.playerIndex = [self getFreePlayerIndex];
+ }
+
+ // Tell Godot about our new controller.
+ Input::get_singleton()->joy_connection_changed(joy_id, true, String::utf8([controller.vendorName UTF8String]));
+
+ Joypad *joypad = [[Joypad alloc] init:controller];
+
+ // Add it to our dictionary, this will retain our controllers.
+ [self.connectedJoypads setObject:joypad forKey:[NSNumber numberWithInt:joy_id]];
+
+ // Set our input handler.
+ [self setControllerInputHandler:controller];
+}
+
+- (void)controllerWasConnected:(NSNotification *)notification {
+ // Get our controller.
+ GCController *controller = (GCController *)notification.object;
+
+ if (!controller) {
+ print_verbose("Couldn't retrieve new controller.");
+ return;
+ }
+
+ if ([[self getAllKeysForController:controller] count] > 0) {
+ print_verbose("Controller is already registered.");
+ } else if (!self.isProcessing) {
+ Joypad *joypad = [[Joypad alloc] init:controller];
+ [self.joypadsQueue addObject:joypad];
+ } else {
+ [self addMacOSJoypad:controller];
+ }
+}
+
+- (void)controllerWasDisconnected:(NSNotification *)notification {
+ // Find our joystick, there should be only one in our dictionary.
+ GCController *controller = (GCController *)notification.object;
+
+ if (!controller) {
+ return;
+ }
+
+ NSArray *keys = [self getAllKeysForController:controller];
+ for (NSNumber *key in keys) {
+ // Tell Godot this joystick is no longer there.
+ int joy_id = [key intValue];
+ Input::get_singleton()->joy_connection_changed(joy_id, false, "");
+
+ // And remove it from our dictionary.
+ [self.connectedJoypads removeObjectForKey:key];
+ }
+}
+
+- (GCControllerPlayerIndex)getFreePlayerIndex {
+ bool have_player_1 = false;
+ bool have_player_2 = false;
+ bool have_player_3 = false;
+ bool have_player_4 = false;
+
+ if (self.connectedJoypads == nil) {
+ NSArray *keys = [self.connectedJoypads allKeys];
+ for (NSNumber *key in keys) {
+ Joypad *joypad = [self.connectedJoypads objectForKey:key];
+ GCController *controller = joypad.controller;
+ if (controller.playerIndex == GCControllerPlayerIndex1) {
+ have_player_1 = true;
+ } else if (controller.playerIndex == GCControllerPlayerIndex2) {
+ have_player_2 = true;
+ } else if (controller.playerIndex == GCControllerPlayerIndex3) {
+ have_player_3 = true;
+ } else if (controller.playerIndex == GCControllerPlayerIndex4) {
+ have_player_4 = true;
+ }
+ }
+ }
+
+ if (!have_player_1) {
+ return GCControllerPlayerIndex1;
+ } else if (!have_player_2) {
+ return GCControllerPlayerIndex2;
+ } else if (!have_player_3) {
+ return GCControllerPlayerIndex3;
+ } else if (!have_player_4) {
+ return GCControllerPlayerIndex4;
+ } else {
+ return GCControllerPlayerIndexUnset;
+ }
+}
+
+- (void)setControllerInputHandler:(GCController *)controller {
+ // Hook in the callback handler for the correct gamepad profile.
+ // This is a bit of a weird design choice on Apples part.
+ // You need to select the most capable gamepad profile for the
+ // gamepad attached.
+ if (controller.extendedGamepad != nil) {
+ // The extended gamepad profile has all the input you could possibly find on
+ // a gamepad but will only be active if your gamepad actually has all of
+ // these...
+ _weakify(self);
+ _weakify(controller);
+
+ controller.extendedGamepad.valueChangedHandler = ^(GCExtendedGamepad *gamepad, GCControllerElement *element) {
+ _strongify(self);
+ _strongify(controller);
+
+ int joy_id = [self getJoyIdForController:controller];
+
+ if (element == gamepad.buttonA) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::A,
+ gamepad.buttonA.isPressed);
+ } else if (element == gamepad.buttonB) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::B,
+ gamepad.buttonB.isPressed);
+ } else if (element == gamepad.buttonX) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::X,
+ gamepad.buttonX.isPressed);
+ } else if (element == gamepad.buttonY) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::Y,
+ gamepad.buttonY.isPressed);
+ } else if (element == gamepad.leftShoulder) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::LEFT_SHOULDER,
+ gamepad.leftShoulder.isPressed);
+ } else if (element == gamepad.rightShoulder) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::RIGHT_SHOULDER,
+ gamepad.rightShoulder.isPressed);
+ } else if (element == gamepad.dpad) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::DPAD_UP,
+ gamepad.dpad.up.isPressed);
+ Input::get_singleton()->joy_button(joy_id, JoyButton::DPAD_DOWN,
+ gamepad.dpad.down.isPressed);
+ Input::get_singleton()->joy_button(joy_id, JoyButton::DPAD_LEFT,
+ gamepad.dpad.left.isPressed);
+ Input::get_singleton()->joy_button(joy_id, JoyButton::DPAD_RIGHT,
+ gamepad.dpad.right.isPressed);
+ }
+
+ if (element == gamepad.leftThumbstick) {
+ float value = gamepad.leftThumbstick.xAxis.value;
+ Input::get_singleton()->joy_axis(joy_id, JoyAxis::LEFT_X, value);
+ value = -gamepad.leftThumbstick.yAxis.value;
+ Input::get_singleton()->joy_axis(joy_id, JoyAxis::LEFT_Y, value);
+ } else if (element == gamepad.rightThumbstick) {
+ float value = gamepad.rightThumbstick.xAxis.value;
+ Input::get_singleton()->joy_axis(joy_id, JoyAxis::RIGHT_X, value);
+ value = -gamepad.rightThumbstick.yAxis.value;
+ Input::get_singleton()->joy_axis(joy_id, JoyAxis::RIGHT_Y, value);
+ } else if (element == gamepad.leftTrigger) {
+ float value = gamepad.leftTrigger.value;
+ Input::get_singleton()->joy_axis(joy_id, JoyAxis::TRIGGER_LEFT, value);
+ } else if (element == gamepad.rightTrigger) {
+ float value = gamepad.rightTrigger.value;
+ Input::get_singleton()->joy_axis(joy_id, JoyAxis::TRIGGER_RIGHT, value);
+ }
+
+ if (@available(macOS 10.14.1, *)) {
+ if (element == gamepad.leftThumbstickButton) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::LEFT_STICK,
+ gamepad.leftThumbstickButton.isPressed);
+ } else if (element == gamepad.rightThumbstickButton) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::RIGHT_STICK,
+ gamepad.rightThumbstickButton.isPressed);
+ }
+ }
+
+ if (@available(macOS 10.15, *)) {
+ if (element == gamepad.buttonOptions) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::BACK,
+ gamepad.buttonOptions.isPressed);
+ } else if (element == gamepad.buttonMenu) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::START,
+ gamepad.buttonMenu.isPressed);
+ }
+ }
+
+ if (@available(macOS 11, *)) {
+ if (element == gamepad.buttonHome) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::GUIDE,
+ gamepad.buttonHome.isPressed);
+ }
+ if ([gamepad isKindOfClass:[GCXboxGamepad class]]) {
+ GCXboxGamepad *xboxGamepad = (GCXboxGamepad *)gamepad;
+ if (element == xboxGamepad.paddleButton1) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::PADDLE1,
+ xboxGamepad.paddleButton1.isPressed);
+ } else if (element == xboxGamepad.paddleButton2) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::PADDLE2,
+ xboxGamepad.paddleButton2.isPressed);
+ } else if (element == xboxGamepad.paddleButton3) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::PADDLE3,
+ xboxGamepad.paddleButton3.isPressed);
+ } else if (element == xboxGamepad.paddleButton4) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::PADDLE4,
+ xboxGamepad.paddleButton4.isPressed);
+ }
+ }
+ }
+
+ if (@available(macOS 12, *)) {
+ if ([gamepad isKindOfClass:[GCXboxGamepad class]]) {
+ GCXboxGamepad *xboxGamepad = (GCXboxGamepad *)gamepad;
+ if (element == xboxGamepad.buttonShare) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::MISC1,
+ xboxGamepad.buttonShare.isPressed);
+ }
+ }
+ }
+ };
+ } else if (controller.microGamepad != nil) {
+ // Micro gamepads were added in macOS 10.11 and feature just 2 buttons and a d-pad.
+ _weakify(self);
+ _weakify(controller);
+
+ controller.microGamepad.valueChangedHandler = ^(GCMicroGamepad *gamepad, GCControllerElement *element) {
+ _strongify(self);
+ _strongify(controller);
+
+ int joy_id = [self getJoyIdForController:controller];
+
+ if (element == gamepad.buttonA) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::A,
+ gamepad.buttonA.isPressed);
+ } else if (element == gamepad.buttonX) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::X,
+ gamepad.buttonX.isPressed);
+ } else if (element == gamepad.dpad) {
+ Input::get_singleton()->joy_button(joy_id, JoyButton::DPAD_UP,
+ gamepad.dpad.up.isPressed);
+ Input::get_singleton()->joy_button(joy_id, JoyButton::DPAD_DOWN,
+ gamepad.dpad.down.isPressed);
+ Input::get_singleton()->joy_button(joy_id, JoyButton::DPAD_LEFT,
+ gamepad.dpad.left.isPressed);
+ Input::get_singleton()->joy_button(joy_id, JoyButton::DPAD_RIGHT,
+ gamepad.dpad.right.isPressed);
+ }
+ };
+ }
+
+ // TODO: Need to add support for controller.motion which gives us access to
+ // the orientation of the device (if supported).
+}
+
+@end
+
+void JoypadMacOS::process_joypads() {
+ if (@available(macOS 11, *)) {
+ // Process vibrations in macOS 11+.
+ NSArray *keys = [observer.connectedJoypads allKeys];
+
+ for (NSNumber *key in keys) {
+ int id = key.intValue;
+ Joypad *joypad = [observer.connectedJoypads objectForKey:key];
+
+ if (joypad.force_feedback) {
+ Input *input = Input::get_singleton();
+ uint64_t timestamp = input->get_joy_vibration_timestamp(id);
+
+ if (timestamp > (unsigned)joypad.ff_effect_timestamp) {
+ Vector2 strength = input->get_joy_vibration_strength(id);
+ float duration = input->get_joy_vibration_duration(id);
+ if (duration == 0) {
+ duration = GCHapticDurationInfinite;
+ }
+
+ if (strength.x == 0 && strength.y == 0) {
+ joypad_vibration_stop(joypad, timestamp);
+ } else {
+ joypad_vibration_start(joypad, strength.x, strength.y, duration, timestamp);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/platform/macos/os_macos.h b/platform/macos/os_macos.h
index 9b20e51f47..8088c3431c 100644
--- a/platform/macos/os_macos.h
+++ b/platform/macos/os_macos.h
@@ -32,7 +32,7 @@
#define OS_MACOS_H
#include "crash_handler_macos.h"
-#include "joypad_macos.h"
+#import "joypad_macos.h"
#include "core/input/input.h"
#import "drivers/coreaudio/audio_driver_coreaudio.h"
diff --git a/platform/macos/os_macos.mm b/platform/macos/os_macos.mm
index 934767db74..c5c95c9a70 100644
--- a/platform/macos/os_macos.mm
+++ b/platform/macos/os_macos.mm
@@ -139,7 +139,7 @@ void OS_MacOS::finalize() {
}
void OS_MacOS::initialize_joypads() {
- joypad_macos = memnew(JoypadMacOS(Input::get_singleton()));
+ joypad_macos = memnew(JoypadMacOS());
}
void OS_MacOS::set_main_loop(MainLoop *p_main_loop) {
@@ -601,7 +601,9 @@ Error OS_MacOS::create_process(const String &p_path, const List<String> &p_argum
for (const String &arg : p_arguments) {
[arguments addObject:[NSString stringWithUTF8String:arg.utf8().get_data()]];
}
+#if defined(__x86_64__)
if (@available(macOS 10.15, *)) {
+#endif
NSWorkspaceOpenConfiguration *configuration = [[NSWorkspaceOpenConfiguration alloc] init];
[configuration setArguments:arguments];
[configuration setCreatesNewApplicationInstance:YES];
@@ -630,6 +632,7 @@ Error OS_MacOS::create_process(const String &p_path, const List<String> &p_argum
}
return err;
+#if defined(__x86_64__)
} else {
Error err = ERR_TIMEOUT;
NSError *error = nullptr;
@@ -645,6 +648,7 @@ Error OS_MacOS::create_process(const String &p_path, const List<String> &p_argum
}
return err;
}
+#endif
} else {
return OS_Unix::create_process(p_path, p_arguments, r_child_id, p_open_console);
}
@@ -769,7 +773,7 @@ void OS_MacOS::run() {
if (DisplayServer::get_singleton()) {
DisplayServer::get_singleton()->process_events(); // Get rid of pending events.
}
- joypad_macos->process_joypads();
+ joypad_macos->start_processing();
if (Main::iteration()) {
quit = true;
diff --git a/platform/macos/platform_config.h b/platform/macos/platform_config.h
index 1a571b689a..01b0a12b5d 100644
--- a/platform/macos/platform_config.h
+++ b/platform/macos/platform_config.h
@@ -31,3 +31,10 @@
#include <alloca.h>
#define PTHREAD_RENAME_SELF
+
+#define _weakify(var) __weak typeof(var) GDWeak_##var = var;
+#define _strongify(var) \
+ _Pragma("clang diagnostic push") \
+ _Pragma("clang diagnostic ignored \"-Wshadow\"") \
+ __strong typeof(var) var = GDWeak_##var; \
+ _Pragma("clang diagnostic pop")
diff --git a/platform/macos/platform_macos_builders.py b/platform/macos/platform_macos_builders.py
index 3a1cc92bd2..a1228b96eb 100644
--- a/platform/macos/platform_macos_builders.py
+++ b/platform/macos/platform_macos_builders.py
@@ -3,6 +3,7 @@
All such functions are invoked in a subprocess on Windows to prevent build flakiness.
"""
+
import os
from platform_methods import subprocess_main
diff --git a/platform/web/detect.py b/platform/web/detect.py
index 7d9b1de6b7..e692c79a20 100644
--- a/platform/web/detect.py
+++ b/platform/web/detect.py
@@ -253,6 +253,9 @@ def configure(env: "SConsEnvironment"):
env.Append(LINKFLAGS=["-fvisibility=hidden"])
env.extra_suffix = ".dlink" + env.extra_suffix
+ # WASM_BIGINT is needed since emscripten ≥ 3.1.41
+ needs_wasm_bigint = cc_semver >= (3, 1, 41)
+
# Run the main application in a web worker
if env["proxy_to_pthread"]:
env.Append(LINKFLAGS=["-s", "PROXY_TO_PTHREAD=1"])
@@ -261,6 +264,9 @@ def configure(env: "SConsEnvironment"):
# https://github.com/emscripten-core/emscripten/issues/18034#issuecomment-1277561925
env.Append(LINKFLAGS=["-s", "TEXTDECODER=0"])
# BigInt support to pass object pointers between contexts
+ needs_wasm_bigint = True
+
+ if needs_wasm_bigint:
env.Append(LINKFLAGS=["-s", "WASM_BIGINT"])
# Reduce code size by generating less support code (e.g. skip NodeJS support).
diff --git a/platform/web/display_server_web.cpp b/platform/web/display_server_web.cpp
index bc4c0d22f0..2e3afc49ca 100644
--- a/platform/web/display_server_web.cpp
+++ b/platform/web/display_server_web.cpp
@@ -36,7 +36,6 @@
#include "core/config/project_settings.h"
#include "core/object/callable_method_pointer.h"
-#include "scene/resources/atlas_texture.h"
#include "servers/rendering/dummy/rasterizer_dummy.h"
#ifdef GLES3_ENABLED
@@ -511,43 +510,12 @@ DisplayServer::CursorShape DisplayServerWeb::cursor_get_shape() const {
void DisplayServerWeb::cursor_set_custom_image(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
if (p_cursor.is_valid()) {
- Ref<Texture2D> texture = p_cursor;
- ERR_FAIL_COND(!texture.is_valid());
- Ref<AtlasTexture> atlas_texture = p_cursor;
- Size2 texture_size;
Rect2 atlas_rect;
+ Ref<Image> image = _get_cursor_image_from_resource(p_cursor, p_hotspot, atlas_rect);
+ ERR_FAIL_COND(image.is_null());
+ Vector2i texture_size = image->get_size();
- if (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 {
- texture_size.width = texture->get_width();
- texture_size.height = texture->get_height();
- }
-
- ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
- ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
- ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
-
- Ref<Image> image = texture->get_image();
-
- ERR_FAIL_COND(!image.is_valid());
-
- image = image->duplicate(true);
-
- if (image->is_compressed()) {
- Error err = image->decompress();
- ERR_FAIL_COND_MSG(err != OK, "Couldn't decompress VRAM-compressed custom mouse cursor image. Switch to a lossless compression mode in the Import dock.");
- }
-
- if (atlas_texture.is_valid()) {
+ if (atlas_rect.has_area()) {
image->crop_from_point(
atlas_rect.position.x,
atlas_rect.position.y,
diff --git a/platform/web/doc_classes/EditorExportPlatformWeb.xml b/platform/web/doc_classes/EditorExportPlatformWeb.xml
index 75125e2708..c759701d2f 100644
--- a/platform/web/doc_classes/EditorExportPlatformWeb.xml
+++ b/platform/web/doc_classes/EditorExportPlatformWeb.xml
@@ -28,9 +28,8 @@
The custom HTML page that wraps the exported web build. If left empty, the default HTML shell is used.
For more information, see the [url=$DOCS_URL/tutorials/platform/web/customizing_html5_shell.html]Customizing HTML5 Shell[/url] tutorial.
</member>
- <member name="html/experimental_virtual_keyboard" type="bool" setter="" getter="">
+ <member name="html/experimental_virtual_keyboard" type="bool" setter="" getter="" experimental="">
If [code]true[/code], embeds support for a virtual keyboard into the web page, which is shown when necessary on touchscreen devices.
- [b]Warning:[/b] This feature is experimental and may be changed in a future release.
</member>
<member name="html/export_icon" type="bool" setter="" getter="">
If [code]true[/code], the project icon will be used as the favicon for this application's web page.
@@ -84,8 +83,8 @@
If [code]true[/code] enables [GDExtension] support for this web build.
</member>
<member name="variant/thread_support" type="bool" setter="" getter="">
- If enabled, the exported game will support threads. It requires [url=https://web.dev/articles/coop-coep]a "cross-origin isolated" website[/url], which can be difficult to setup and brings some limitations (e.g. not being able to communicate with third-party websites).
- If disabled, the exported game will not support threads. As a result, it is more prone to performance and audio issues, but will only require to be run on a HTTPS website.
+ If [code]true[/code], the exported game will support threads. It requires [url=https://web.dev/articles/coop-coep]a "cross-origin isolated" website[/url], which may be difficult to set up and is limited for security reasons (such as not being able to communicate with third-party websites).
+ If [code]false[/code], the exported game will not support threads. As a result, it is more prone to performance and audio issues, but will only require to be run on a HTTPS website.
</member>
<member name="vram_texture_compression/for_desktop" type="bool" setter="" getter="">
If [code]true[/code], allows textures to be optimized for desktop through the S3TC algorithm.
diff --git a/platform/windows/detect.py b/platform/windows/detect.py
index f536c1ac27..196beb423f 100644
--- a/platform/windows/detect.py
+++ b/platform/windows/detect.py
@@ -202,6 +202,9 @@ def get_opts():
BoolVariable("use_asan", "Use address sanitizer (ASAN)", False),
BoolVariable("debug_crt", "Compile with MSVC's debug CRT (/MDd)", False),
BoolVariable("incremental_link", "Use MSVC incremental linking. May increase or decrease build times.", False),
+ BoolVariable(
+ "silence_msvc", "Silence MSVC's stdout to decrease output log bloat. May hide error messages.", False
+ ),
("angle_libs", "Path to the ANGLE static libraries", ""),
# Direct3D 12 support.
(
@@ -248,6 +251,7 @@ def get_flags():
return [
("arch", arch),
+ ("supported", ["mono"]),
]
@@ -391,6 +395,20 @@ def configure_msvc(env: "SConsEnvironment", vcvars_msvc_config):
## Compile/link flags
+ env["MAXLINELENGTH"] = 8192 # Windows Vista and beyond, so always applicable.
+
+ if env["silence_msvc"]:
+ env.Prepend(CCFLAGS=[">", "NUL"])
+ env.Prepend(LINKFLAGS=[">", "NUL"])
+
+ # "> NUL" fails if using a tempfile, circumvent by removing the argument altogether.
+ old_esc_func = env["TEMPFILEARGESCFUNC"]
+
+ def trim_nul(arg):
+ return "" if arg in [">", "NUL"] else old_esc_func(arg)
+
+ env["TEMPFILEARGESCFUNC"] = trim_nul
+
if env["debug_crt"]:
# Always use dynamic runtime, static debug CRT breaks thread_local.
env.AppendUnique(CCFLAGS=["/MDd"])
@@ -421,6 +439,10 @@ def configure_msvc(env: "SConsEnvironment", vcvars_msvc_config):
else:
print("Missing environment variable: WindowsSdkDir")
+ if int(env["target_win_version"], 16) < 0x0601:
+ print("`target_win_version` should be 0x0601 or higher (Windows 7).")
+ sys.exit(255)
+
env.AppendUnique(
CPPDEFINES=[
"WINDOWS_ENABLED",
@@ -485,7 +507,7 @@ def configure_msvc(env: "SConsEnvironment", vcvars_msvc_config):
sys.exit(255)
env.AppendUnique(CPPDEFINES=["D3D12_ENABLED", "RD_ENABLED"])
- LIBS += ["d3d12", "dxgi", "dxguid"]
+ LIBS += ["dxgi", "dxguid"]
LIBS += ["version"] # Mesa dependency.
# Needed for avoiding C1128.
@@ -650,6 +672,10 @@ def configure_mingw(env: "SConsEnvironment"):
## Compile flags
+ if int(env["target_win_version"], 16) < 0x0601:
+ print("`target_win_version` should be 0x0601 or higher (Windows 7).")
+ sys.exit(255)
+
if not env["use_llvm"]:
env.Append(CCFLAGS=["-mwindows"])
@@ -710,7 +736,7 @@ def configure_mingw(env: "SConsEnvironment"):
sys.exit(255)
env.AppendUnique(CPPDEFINES=["D3D12_ENABLED", "RD_ENABLED"])
- env.Append(LIBS=["d3d12", "dxgi", "dxguid"])
+ env.Append(LIBS=["dxgi", "dxguid"])
# PIX
if not env["arch"] in ["x86_64", "arm64"] or env["pix_path"] == "" or not os.path.exists(env["pix_path"]):
diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp
index 16eabf6855..ada9202207 100644
--- a/platform/windows/display_server_windows.cpp
+++ b/platform/windows/display_server_windows.cpp
@@ -35,9 +35,9 @@
#include "core/config/project_settings.h"
#include "core/io/marshalls.h"
+#include "core/version.h"
#include "drivers/png/png_driver_common.h"
#include "main/main.h"
-#include "scene/resources/atlas_texture.h"
#if defined(VULKAN_ENABLED)
#include "rendering_context_driver_vulkan_windows.h"
@@ -51,6 +51,9 @@
#include <avrt.h>
#include <dwmapi.h>
+#include <propkey.h>
+#include <propvarutil.h>
+#include <shellapi.h>
#include <shlwapi.h>
#include <shobjidl.h>
#include <wbemcli.h>
@@ -1375,6 +1378,15 @@ void DisplayServerWindows::delete_sub_window(WindowID p_window) {
WindowData &wd = windows[p_window];
+ IPropertyStore *prop_store;
+ HRESULT hr = SHGetPropertyStoreForWindow(wd.hWnd, IID_IPropertyStore, (void **)&prop_store);
+ if (hr == S_OK) {
+ PROPVARIANT val;
+ PropVariantInit(&val);
+ prop_store->SetValue(PKEY_AppUserModel_ID, val);
+ prop_store->Release();
+ }
+
while (wd.transient_children.size()) {
window_set_transient(*wd.transient_children.begin(), INVALID_WINDOW_ID);
}
@@ -2380,38 +2392,10 @@ void DisplayServerWindows::cursor_set_custom_image(const Ref<Resource> &p_cursor
cursors_cache.erase(p_shape);
}
- Ref<Texture2D> texture = p_cursor;
- ERR_FAIL_COND(!texture.is_valid());
- Ref<AtlasTexture> atlas_texture = p_cursor;
- Size2 texture_size;
Rect2 atlas_rect;
-
- if (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 {
- texture_size.width = texture->get_width();
- texture_size.height = texture->get_height();
- }
-
- ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
- ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
- ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
-
- Ref<Image> image = texture->get_image();
-
- ERR_FAIL_COND(!image.is_valid());
- if (image->is_compressed()) {
- image = image->duplicate(true);
- Error err = image->decompress();
- ERR_FAIL_COND_MSG(err != OK, "Couldn't decompress VRAM-compressed custom mouse cursor image. Switch to a lossless compression mode in the Import dock.");
- }
+ Ref<Image> image = _get_cursor_image_from_resource(p_cursor, p_hotspot, atlas_rect);
+ ERR_FAIL_COND(image.is_null());
+ Vector2i texture_size = image->get_size();
UINT image_size = texture_size.width * texture_size.height;
@@ -2440,7 +2424,7 @@ void DisplayServerWindows::cursor_set_custom_image(const Ref<Resource> &p_cursor
int row_index = floor(index / texture_size.width) + atlas_rect.position.y;
int column_index = (index % int(texture_size.width)) + atlas_rect.position.x;
- if (atlas_texture.is_valid()) {
+ if (atlas_rect.has_area()) {
column_index = MIN(column_index, atlas_rect.size.width - 1);
row_index = MIN(row_index, atlas_rect.size.height - 1);
}
@@ -2506,6 +2490,299 @@ void DisplayServerWindows::enable_for_stealing_focus(OS::ProcessID pid) {
AllowSetForegroundWindow(pid);
}
+static HRESULT CALLBACK win32_task_dialog_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, LONG_PTR lpRefData) {
+ if (msg == TDN_CREATED) {
+ // To match the input text dialog.
+ SendMessageW(hwnd, WM_SETICON, ICON_BIG, 0);
+ SendMessageW(hwnd, WM_SETICON, ICON_SMALL, 0);
+ }
+
+ return 0;
+}
+
+Error DisplayServerWindows::dialog_show(String p_title, String p_description, Vector<String> p_buttons, const Callable &p_callback) {
+ _THREAD_SAFE_METHOD_
+
+ TASKDIALOGCONFIG config;
+ ZeroMemory(&config, sizeof(TASKDIALOGCONFIG));
+ config.cbSize = sizeof(TASKDIALOGCONFIG);
+
+ Char16String title = p_title.utf16();
+ Char16String message = p_description.utf16();
+ List<Char16String> buttons;
+ for (String s : p_buttons) {
+ buttons.push_back(s.utf16());
+ }
+
+ config.pszWindowTitle = (LPCWSTR)(title.get_data());
+ config.pszContent = (LPCWSTR)(message.get_data());
+
+ const int button_count = MIN(buttons.size(), 8);
+ config.cButtons = button_count;
+
+ // No dynamic stack array size :(
+ TASKDIALOG_BUTTON *tbuttons = button_count != 0 ? (TASKDIALOG_BUTTON *)alloca(sizeof(TASKDIALOG_BUTTON) * button_count) : nullptr;
+ if (tbuttons) {
+ for (int i = 0; i < button_count; i++) {
+ tbuttons[i].nButtonID = i;
+ tbuttons[i].pszButtonText = (LPCWSTR)(buttons[i].get_data());
+ }
+ }
+ config.pButtons = tbuttons;
+ config.pfCallback = win32_task_dialog_callback;
+
+ HMODULE comctl = LoadLibraryW(L"comctl32.dll");
+ if (comctl) {
+ typedef HRESULT(WINAPI * TaskDialogIndirectPtr)(const TASKDIALOGCONFIG *pTaskConfig, int *pnButton, int *pnRadioButton, BOOL *pfVerificationFlagChecked);
+
+ TaskDialogIndirectPtr task_dialog_indirect = (TaskDialogIndirectPtr)GetProcAddress(comctl, "TaskDialogIndirect");
+ if (task_dialog_indirect) {
+ int button_pressed;
+ if (FAILED(task_dialog_indirect(&config, &button_pressed, nullptr, nullptr))) {
+ return FAILED;
+ }
+
+ if (!p_callback.is_null()) {
+ Variant button = button_pressed;
+ const Variant *args[1] = { &button };
+ Variant ret;
+ Callable::CallError ce;
+ p_callback.callp(args, 1, ret, ce);
+ if (ce.error != Callable::CallError::CALL_OK) {
+ ERR_PRINT(vformat("Failed to execute dialog callback: %s.", Variant::get_callable_error_text(p_callback, args, 1, ce)));
+ }
+ }
+
+ return OK;
+ }
+ FreeLibrary(comctl);
+ }
+
+ ERR_PRINT("Unable to create native dialog.");
+ return FAILED;
+}
+
+struct Win32InputTextDialogInit {
+ const char16_t *title;
+ const char16_t *description;
+ const char16_t *partial;
+ const Callable &callback;
+};
+
+static constexpr int scale_with_dpi(int p_pos, int p_dpi) {
+ return IsProcessDPIAware() ? (p_pos * p_dpi / 96) : p_pos;
+}
+
+static INT_PTR input_text_dialog_init(HWND hWnd, UINT code, WPARAM wParam, LPARAM lParam) {
+ Win32InputTextDialogInit init = *(Win32InputTextDialogInit *)lParam;
+ SetWindowLongPtrW(hWnd, GWLP_USERDATA, (LONG_PTR)&init.callback); // Set dialog callback.
+
+ SetWindowTextW(hWnd, (LPCWSTR)init.title);
+
+ const int dpi = DisplayServerWindows::get_singleton()->screen_get_dpi();
+
+ const int margin = scale_with_dpi(7, dpi);
+ const SIZE dlg_size = { scale_with_dpi(300, dpi), scale_with_dpi(50, dpi) };
+
+ int str_len = lstrlenW((LPCWSTR)init.description);
+ SIZE str_size = { dlg_size.cx, 0 };
+ if (str_len > 0) {
+ HDC hdc = GetDC(nullptr);
+ RECT trect = { margin, margin, margin + dlg_size.cx, margin + dlg_size.cy };
+ SelectObject(hdc, (HFONT)SendMessageW(hWnd, WM_GETFONT, 0, 0));
+
+ // `+ margin` adds some space between the static text and the edit field.
+ // Don't scale this with DPI because DPI is already handled by DrawText.
+ str_size.cy = DrawTextW(hdc, (LPCWSTR)init.description, str_len, &trect, DT_LEFT | DT_WORDBREAK | DT_CALCRECT) + margin;
+
+ ReleaseDC(nullptr, hdc);
+ }
+
+ RECT crect, wrect;
+ GetClientRect(hWnd, &crect);
+ GetWindowRect(hWnd, &wrect);
+ int sw = GetSystemMetrics(SM_CXSCREEN);
+ int sh = GetSystemMetrics(SM_CYSCREEN);
+ int new_width = dlg_size.cx + margin * 2 + wrect.right - wrect.left - crect.right;
+ int new_height = dlg_size.cy + margin * 2 + wrect.bottom - wrect.top - crect.bottom + str_size.cy;
+
+ MoveWindow(hWnd, (sw - new_width) / 2, (sh - new_height) / 2, new_width, new_height, true);
+
+ HWND ok_button = GetDlgItem(hWnd, 1);
+ MoveWindow(ok_button,
+ dlg_size.cx + margin - scale_with_dpi(65, dpi),
+ dlg_size.cy + str_size.cy + margin - scale_with_dpi(20, dpi),
+ scale_with_dpi(65, dpi), scale_with_dpi(20, dpi), true);
+
+ HWND description = GetDlgItem(hWnd, 3);
+ MoveWindow(description, margin, margin, dlg_size.cx, str_size.cy, true);
+ SetWindowTextW(description, (LPCWSTR)init.description);
+
+ HWND text_edit = GetDlgItem(hWnd, 2);
+ MoveWindow(text_edit, margin, str_size.cy + margin, dlg_size.cx, scale_with_dpi(20, dpi), true);
+ SetWindowTextW(text_edit, (LPCWSTR)init.partial);
+
+ return TRUE;
+}
+
+static INT_PTR input_text_dialog_cmd_proc(HWND hWnd, UINT code, WPARAM wParam, LPARAM lParam) {
+ if (LOWORD(wParam) == 1) {
+ HWND text_edit = GetDlgItem(hWnd, 2);
+ ERR_FAIL_NULL_V(text_edit, false);
+
+ Char16String text;
+ text.resize(GetWindowTextLengthW(text_edit) + 1);
+ GetWindowTextW(text_edit, (LPWSTR)text.get_data(), text.size());
+
+ const Callable *callback = (const Callable *)GetWindowLongPtrW(hWnd, GWLP_USERDATA);
+ if (callback && callback->is_valid()) {
+ Variant v_result = String((const wchar_t *)text.get_data());
+ Variant ret;
+ Callable::CallError ce;
+ const Variant *args[1] = { &v_result };
+
+ callback->callp(args, 1, ret, ce);
+ if (ce.error != Callable::CallError::CALL_OK) {
+ ERR_PRINT(vformat("Failed to execute input dialog callback: %s.", Variant::get_callable_error_text(*callback, args, 1, ce)));
+ }
+ }
+
+ return EndDialog(hWnd, 0);
+ }
+
+ return false;
+}
+
+static INT_PTR CALLBACK input_text_dialog_proc(HWND hWnd, UINT code, WPARAM wParam, LPARAM lParam) {
+ switch (code) {
+ case WM_INITDIALOG:
+ return input_text_dialog_init(hWnd, code, wParam, lParam);
+
+ case WM_COMMAND:
+ return input_text_dialog_cmd_proc(hWnd, code, wParam, lParam);
+
+ default:
+ return FALSE;
+ }
+}
+
+Error DisplayServerWindows::dialog_input_text(String p_title, String p_description, String p_partial, const Callable &p_callback) {
+#pragma pack(push, 1)
+
+ // NOTE: Use default/placeholder coordinates here. Windows uses its own coordinate system
+ // specifically for dialogs which relies on font sizes instead of pixels.
+ const struct {
+ WORD dlgVer; // must be 1
+ WORD signature; // must be 0xFFFF
+ DWORD helpID;
+ DWORD exStyle;
+ DWORD style;
+ WORD cDlgItems;
+ short x;
+ short y;
+ short cx;
+ short cy;
+ WCHAR menu[1]; // must be 0
+ WCHAR windowClass[7]; // must be "#32770" -- the default window class for dialogs
+ WCHAR title[1]; // must be 0
+ WORD pointsize;
+ WORD weight;
+ BYTE italic;
+ BYTE charset;
+ WCHAR font[13]; // must be "MS Shell Dlg"
+ } template_base = {
+ 1, 0xFFFF, 0, 0,
+ DS_SYSMODAL | DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU,
+ 3, 0, 0, 20, 20, L"", L"#32770", L"", 8, FW_NORMAL, 0, DEFAULT_CHARSET, L"MS Shell Dlg"
+ };
+
+ const struct {
+ DWORD helpID;
+ DWORD exStyle;
+ DWORD style;
+ short x;
+ short y;
+ short cx;
+ short cy;
+ DWORD id;
+ WCHAR windowClass[7]; // must be "Button"
+ WCHAR title[3]; // must be "OK"
+ WORD extraCount;
+ } ok_button = {
+ 0, 0, WS_VISIBLE | BS_DEFPUSHBUTTON, 0, 0, 50, 14, 1, WC_BUTTONW, L"OK", 0
+ };
+ const struct {
+ DWORD helpID;
+ DWORD exStyle;
+ DWORD style;
+ short x;
+ short y;
+ short cx;
+ short cy;
+ DWORD id;
+ WCHAR windowClass[5]; // must be "Edit"
+ WCHAR title[1]; // must be 0
+ WORD extraCount;
+ } text_field = {
+ 0, 0, WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL, 0, 0, 250, 14, 2, WC_EDITW, L"", 0
+ };
+ const struct {
+ DWORD helpID;
+ DWORD exStyle;
+ DWORD style;
+ short x;
+ short y;
+ short cx;
+ short cy;
+ DWORD id;
+ WCHAR windowClass[7]; // must be "Static"
+ WCHAR title[1]; // must be 0
+ WORD extraCount;
+ } static_text = {
+ 0, 0, WS_VISIBLE, 0, 0, 250, 14, 3, WC_STATICW, L"", 0
+ };
+
+#pragma pack(pop)
+
+ // Dialog template
+ const size_t data_size = sizeof(template_base) + (sizeof(template_base) % 4) +
+ sizeof(ok_button) + (sizeof(ok_button) % 4) +
+ sizeof(text_field) + (sizeof(text_field) % 4) +
+ sizeof(static_text) + (sizeof(static_text) % 4);
+
+ void *data_template = memalloc(data_size);
+ ERR_FAIL_NULL_V_MSG(data_template, FAILED, "Unable to allocate memory for the dialog template.");
+ ZeroMemory(data_template, data_size);
+
+ char *current_block = (char *)data_template;
+ CopyMemory(current_block, &template_base, sizeof(template_base));
+ current_block += sizeof(template_base) + (sizeof(template_base) % 4);
+ CopyMemory(current_block, &ok_button, sizeof(ok_button));
+ current_block += sizeof(ok_button) + (sizeof(ok_button) % 4);
+ CopyMemory(current_block, &text_field, sizeof(text_field));
+ current_block += sizeof(text_field) + (sizeof(text_field) % 4);
+ CopyMemory(current_block, &static_text, sizeof(static_text));
+
+ Char16String title16 = p_title.utf16();
+ Char16String description16 = p_description.utf16();
+ Char16String partial16 = p_partial.utf16();
+
+ Win32InputTextDialogInit init = {
+ title16.get_data(), description16.get_data(), partial16.get_data(), p_callback
+ };
+
+ // No modal dialogs for specific windows? Assume main window here.
+ INT_PTR ret = DialogBoxIndirectParamW(hInstance, (LPDLGTEMPLATEW)data_template, nullptr, (DLGPROC)input_text_dialog_proc, (LPARAM)(&init));
+
+ Error result = ret != -1 ? OK : FAILED;
+ memfree(data_template);
+
+ if (result == FAILED) {
+ ERR_PRINT("Unable to create native dialog.");
+ }
+ return result;
+}
+
int DisplayServerWindows::keyboard_get_layout_count() const {
return GetKeyboardLayoutList(0, nullptr);
}
@@ -3081,9 +3358,9 @@ void DisplayServerWindows::set_context(Context p_context) {
#define SIGNATURE_MASK 0xFFFFFF00
// Keeping the name suggested by Microsoft, but this macro really answers:
// Is this mouse event emulated from touch or pen input?
-#define IsPenEvent(dw) (((dw)&SIGNATURE_MASK) == MI_WP_SIGNATURE)
+#define IsPenEvent(dw) (((dw) & SIGNATURE_MASK) == MI_WP_SIGNATURE)
// This one tells whether the event comes from touchscreen (and not from pen).
-#define IsTouchEvent(dw) (IsPenEvent(dw) && ((dw)&0x80))
+#define IsTouchEvent(dw) (IsPenEvent(dw) && ((dw) & 0x80))
void DisplayServerWindows::_touch_event(WindowID p_window, bool p_pressed, float p_x, float p_y, int idx) {
if (touch_state.has(idx) == p_pressed) {
@@ -4956,6 +5233,33 @@ DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode,
wd.last_pressure_update = 0;
wd.last_tilt = Vector2();
+ IPropertyStore *prop_store;
+ HRESULT hr = SHGetPropertyStoreForWindow(wd.hWnd, IID_IPropertyStore, (void **)&prop_store);
+ if (hr == S_OK) {
+ PROPVARIANT val;
+ String appname;
+ if (Engine::get_singleton()->is_editor_hint()) {
+ appname = "Godot.GodotEditor." + String(VERSION_BRANCH);
+ } else {
+ String name = GLOBAL_GET("application/config/name");
+ String version = GLOBAL_GET("application/config/version");
+ if (version.is_empty()) {
+ version = "0";
+ }
+ String clean_app_name = name.to_pascal_case();
+ for (int i = 0; i < clean_app_name.length(); i++) {
+ if (!is_ascii_alphanumeric_char(clean_app_name[i]) && clean_app_name[i] != '_' && clean_app_name[i] != '.') {
+ clean_app_name[i] = '_';
+ }
+ }
+ clean_app_name = clean_app_name.substr(0, 120 - version.length()).trim_suffix(".");
+ appname = "Godot." + clean_app_name + "." + version;
+ }
+ InitPropVariantFromString((PCWSTR)appname.utf16().get_data(), &val);
+ prop_store->SetValue(PKEY_AppUserModel_ID, val);
+ prop_store->Release();
+ }
+
// IME.
wd.im_himc = ImmGetContext(wd.hWnd);
ImmAssociateContext(wd.hWnd, (HIMC)0);
@@ -5245,6 +5549,23 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win
}
}
+ HMODULE comctl32 = LoadLibraryW(L"comctl32.dll");
+ if (comctl32) {
+ typedef BOOL(WINAPI * InitCommonControlsExPtr)(_In_ const INITCOMMONCONTROLSEX *picce);
+ InitCommonControlsExPtr init_common_controls_ex = (InitCommonControlsExPtr)GetProcAddress(comctl32, "InitCommonControlsEx");
+
+ // Fails if the incorrect version was loaded. Probably not a big enough deal to print an error about.
+ if (init_common_controls_ex) {
+ INITCOMMONCONTROLSEX icc = {};
+ icc.dwICC = ICC_STANDARD_CLASSES;
+ icc.dwSize = sizeof(INITCOMMONCONTROLSEX);
+ if (!init_common_controls_ex(&icc)) {
+ WARN_PRINT("Unable to initialize Windows common controls. Native dialogs may not work properly.");
+ }
+ }
+ FreeLibrary(comctl32);
+ }
+
memset(&wc, 0, sizeof(WNDCLASSEXW));
wc.cbSize = sizeof(WNDCLASSEXW);
wc.style = CS_OWNDC | CS_DBLCLKS;
@@ -5354,6 +5675,26 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win
}
#endif
+ String appname;
+ if (Engine::get_singleton()->is_editor_hint()) {
+ appname = "Godot.GodotEditor." + String(VERSION_BRANCH);
+ } else {
+ String name = GLOBAL_GET("application/config/name");
+ String version = GLOBAL_GET("application/config/version");
+ if (version.is_empty()) {
+ version = "0";
+ }
+ String clean_app_name = name.to_pascal_case();
+ for (int i = 0; i < clean_app_name.length(); i++) {
+ if (!is_ascii_alphanumeric_char(clean_app_name[i]) && clean_app_name[i] != '_' && clean_app_name[i] != '.') {
+ clean_app_name[i] = '_';
+ }
+ }
+ clean_app_name = clean_app_name.substr(0, 120 - version.length()).trim_suffix(".");
+ appname = "Godot." + clean_app_name + "." + version;
+ }
+ SetCurrentProcessExplicitAppUserModelID((PCWSTR)appname.utf16().get_data());
+
mouse_monitor = SetWindowsHookEx(WH_MOUSE, ::MouseProc, nullptr, GetCurrentThreadId());
Point2i window_position;
@@ -5479,7 +5820,7 @@ DisplayServerWindows::~DisplayServerWindows() {
cursors_cache.clear();
// Destroy all status indicators.
- for (HashMap<IndicatorID, IndicatorData>::Iterator E = indicators.begin(); E;) {
+ for (HashMap<IndicatorID, IndicatorData>::Iterator E = indicators.begin(); E; ++E) {
NOTIFYICONDATAW ndat;
ZeroMemory(&ndat, sizeof(NOTIFYICONDATAW));
ndat.cbSize = sizeof(NOTIFYICONDATAW);
diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h
index 81cddec49f..f749185080 100644
--- a/platform/windows/display_server_windows.h
+++ b/platform/windows/display_server_windows.h
@@ -192,6 +192,7 @@ typedef UINT32 PEN_MASK;
#define POINTER_MESSAGE_FLAG_FIRSTBUTTON 0x00000010
#endif
+#if WINVER < 0x0602
enum tagPOINTER_INPUT_TYPE {
PT_POINTER = 0x00000001,
PT_TOUCH = 0x00000002,
@@ -242,6 +243,7 @@ typedef struct tagPOINTER_PEN_INFO {
INT32 tiltX;
INT32 tiltY;
} POINTER_PEN_INFO;
+#endif
#endif //POINTER_STRUCTURES
@@ -642,6 +644,9 @@ public:
virtual void enable_for_stealing_focus(OS::ProcessID pid) override;
+ virtual Error dialog_show(String p_title, String p_description, Vector<String> p_buttons, const Callable &p_callback) override;
+ virtual Error dialog_input_text(String p_title, String p_description, String p_partial, const Callable &p_callback) override;
+
virtual int keyboard_get_layout_count() const override;
virtual int keyboard_get_current_layout() const override;
virtual void keyboard_set_current_layout(int p_index) override;
diff --git a/platform/windows/godot_res.rc b/platform/windows/godot_res.rc
index 8187c0c936..86191ad9d9 100644
--- a/platform/windows/godot_res.rc
+++ b/platform/windows/godot_res.rc
@@ -1,6 +1,11 @@
#include "core/version.h"
+#ifndef RT_MANIFEST
+#define RT_MANIFEST 24
+#endif
+
GODOT_ICON ICON platform/windows/godot.ico
+1 RT_MANIFEST "godot.manifest"
1 VERSIONINFO
FILEVERSION VERSION_MAJOR,VERSION_MINOR,VERSION_PATCH,0
diff --git a/platform/windows/platform_windows_builders.py b/platform/windows/platform_windows_builders.py
index 652dc06acf..99e9633800 100644
--- a/platform/windows/platform_windows_builders.py
+++ b/platform/windows/platform_windows_builders.py
@@ -3,6 +3,7 @@
All such functions are invoked in a subprocess on Windows to prevent build flakiness.
"""
+
import os
from detect import get_mingw_bin_prefix
from detect import try_cmd