diff options
Diffstat (limited to 'platform')
63 files changed, 1136 insertions, 338 deletions
diff --git a/platform/android/detect.py b/platform/android/detect.py index 1d9bcdd932..2ff9cd3dc5 100644 --- a/platform/android/detect.py +++ b/platform/android/detect.py @@ -47,9 +47,6 @@ def get_flags(): return [ ("arch", "arm64"), # Default for convenience. ("tools", False), - # Benefits of LTO for Android (size, performance) haven't been clearly established yet. - # So for now we override the default value which may be set when using `production=yes`. - ("lto", "none"), ] @@ -124,18 +121,18 @@ def configure(env): # `-O2` is more friendly to debuggers than `-O3`, leading to better crash backtraces # when using `target=release_debug`. opt = "-O3" if env["target"] == "release" else "-O2" - env.Append(CCFLAGS=[opt, "-fomit-frame-pointer"]) + env.Append(CCFLAGS=[opt]) elif env["optimize"] == "size": # optimize for size env.Append(CCFLAGS=["-Oz"]) - env.Append(CPPDEFINES=["NDEBUG"]) - env.Append(CCFLAGS=["-ftree-vectorize"]) elif env["target"] == "debug": env.Append(LINKFLAGS=["-O0"]) - env.Append(CCFLAGS=["-O0", "-g", "-fno-limit-debug-info"]) - env.Append(CPPDEFINES=["_DEBUG"]) - env.Append(CPPFLAGS=["-UNDEBUG"]) + env.Append(CCFLAGS=["-O0", "-g"]) # LTO + + if env["lto"] == "auto": # LTO benefits for Android (size, performance) haven't been clearly established yet. + env["lto"] = "none" + if env["lto"] != "none": if env["lto"] == "thin": env.Append(CCFLAGS=["-flto=thin"]) diff --git a/platform/android/export/export.cpp b/platform/android/export/export.cpp index 5bbe0ffab6..f4c4e985fe 100644 --- a/platform/android/export/export.cpp +++ b/platform/android/export/export.cpp @@ -36,6 +36,7 @@ #include "export_plugin.h" void register_android_exporter() { +#ifndef ANDROID_ENABLED EDITOR_DEF("export/android/android_sdk_path", ""); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/android_sdk_path", PROPERTY_HINT_GLOBAL_DIR)); EDITOR_DEF("export/android/debug_keystore", ""); @@ -47,6 +48,7 @@ void register_android_exporter() { EDITOR_DEF("export/android/shutdown_adb_on_exit", true); EDITOR_DEF("export/android/one_click_deploy_clear_previous_install", false); +#endif Ref<EditorExportPlatformAndroid> exporter = Ref<EditorExportPlatformAndroid>(memnew(EditorExportPlatformAndroid)); EditorExport::get_singleton()->add_export_platform(exporter); diff --git a/platform/android/export/export_plugin.cpp b/platform/android/export/export_plugin.cpp index 0f8ef3f7d6..366bd1c48c 100644 --- a/platform/android/export/export_plugin.cpp +++ b/platform/android/export/export_plugin.cpp @@ -569,16 +569,15 @@ bool EditorExportPlatformAndroid::_should_compress_asset(const String &p_path, c } zip_fileinfo EditorExportPlatformAndroid::get_zip_fileinfo() { - OS::Time time = OS::get_singleton()->get_time(); - OS::Date date = OS::get_singleton()->get_date(); + OS::DateTime dt = OS::get_singleton()->get_datetime(); zip_fileinfo zipfi; - zipfi.tmz_date.tm_hour = time.hour; - zipfi.tmz_date.tm_mday = date.day; - zipfi.tmz_date.tm_min = time.minute; - zipfi.tmz_date.tm_mon = date.month - 1; // tm_mon is zero indexed - zipfi.tmz_date.tm_sec = time.second; - zipfi.tmz_date.tm_year = date.year; + zipfi.tmz_date.tm_year = dt.year; + zipfi.tmz_date.tm_mon = dt.month - 1; // tm_mon is zero indexed + zipfi.tmz_date.tm_mday = dt.day; + zipfi.tmz_date.tm_hour = dt.hour; + zipfi.tmz_date.tm_min = dt.minute; + zipfi.tmz_date.tm_sec = dt.second; zipfi.dosDate = 0; zipfi.external_fa = 0; zipfi.internal_fa = 0; @@ -1670,14 +1669,7 @@ Vector<String> EditorExportPlatformAndroid::get_enabled_abis(const Ref<EditorExp } void EditorExportPlatformAndroid::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) const { - String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name"); - if (driver == "opengl3") { - r_features->push_back("etc"); - } - // FIXME: Review what texture formats are used for Vulkan. - if (driver == "vulkan") { - r_features->push_back("etc2"); - } + r_features->push_back("etc2"); Vector<String> abis = get_enabled_abis(p_preset); for (int i = 0; i < abis.size(); ++i) { diff --git a/platform/android/export/gradle_export_util.cpp b/platform/android/export/gradle_export_util.cpp index 8d370a31a4..2f53942f76 100644 --- a/platform/android/export/gradle_export_util.cpp +++ b/platform/android/export/gradle_export_util.cpp @@ -189,9 +189,7 @@ String bool_to_string(bool v) { } String _get_gles_tag() { - bool min_gles3 = ProjectSettings::get_singleton()->get("rendering/driver/driver_name") == "GLES3" && - !ProjectSettings::get_singleton()->get("rendering/driver/fallback_to_gles2"); - return min_gles3 ? " <uses-feature android:glEsVersion=\"0x00030000\" android:required=\"true\" />\n" : ""; + return " <uses-feature android:glEsVersion=\"0x00030000\" android:required=\"true\" />\n"; } String _get_screen_sizes_tag(const Ref<EditorExportPreset> &p_preset) { diff --git a/platform/android/file_access_android.cpp b/platform/android/file_access_android.cpp index ace7636e6c..d6cd62e9f5 100644 --- a/platform/android/file_access_android.cpp +++ b/platform/android/file_access_android.cpp @@ -42,7 +42,7 @@ String FileAccessAndroid::get_path_absolute() const { return absolute_path; } -Error FileAccessAndroid::_open(const String &p_path, int p_mode_flags) { +Error FileAccessAndroid::open_internal(const String &p_path, int p_mode_flags) { _close(); path_src = p_path; diff --git a/platform/android/file_access_android.h b/platform/android/file_access_android.h index 8d7ade8ead..55f8fbe0f4 100644 --- a/platform/android/file_access_android.h +++ b/platform/android/file_access_android.h @@ -49,7 +49,7 @@ class FileAccessAndroid : public FileAccess { public: static AAssetManager *asset_manager; - virtual Error _open(const String &p_path, int p_mode_flags) override; // open a file + virtual Error open_internal(const String &p_path, int p_mode_flags) override; // open a file virtual bool is_open() const override; // true when file is open /// returns the path for the current open file diff --git a/platform/android/file_access_filesystem_jandroid.cpp b/platform/android/file_access_filesystem_jandroid.cpp index 56561cb616..c2ee3389ae 100644 --- a/platform/android/file_access_filesystem_jandroid.cpp +++ b/platform/android/file_access_filesystem_jandroid.cpp @@ -61,7 +61,7 @@ String FileAccessFilesystemJAndroid::get_path_absolute() const { return absolute_path; } -Error FileAccessFilesystemJAndroid::_open(const String &p_path, int p_mode_flags) { +Error FileAccessFilesystemJAndroid::open_internal(const String &p_path, int p_mode_flags) { if (is_open()) { _close(); } diff --git a/platform/android/file_access_filesystem_jandroid.h b/platform/android/file_access_filesystem_jandroid.h index 76d7db6e3a..815ab36516 100644 --- a/platform/android/file_access_filesystem_jandroid.h +++ b/platform/android/file_access_filesystem_jandroid.h @@ -60,7 +60,7 @@ class FileAccessFilesystemJAndroid : public FileAccess { void _set_eof(bool eof); public: - virtual Error _open(const String &p_path, int p_mode_flags) override; ///< open a file + virtual Error open_internal(const String &p_path, int p_mode_flags) override; ///< open a file virtual bool is_open() const override; ///< true when file is open /// returns the path for the current open file diff --git a/platform/android/java/app/config.gradle b/platform/android/java/app/config.gradle index fbd97fae0b..0346625e4b 100644 --- a/platform/android/java/app/config.gradle +++ b/platform/android/java/app/config.gradle @@ -127,16 +127,36 @@ ext.generateGodotLibraryVersion = { List<String> requiredKeys -> if (requiredKeys.empty) { libraryVersionName = map.values().join(".") try { + if (map.containsKey("status")) { + int statusCode = 0 + String statusValue = map["status"] + if (statusValue == null) { + statusCode = 0 + } else if (statusValue.startsWith("alpha")) { + statusCode = 1 + } else if (statusValue.startsWith("beta")) { + statusCode = 2 + } else if (statusValue.startsWith("rc")) { + statusCode = 3 + } else if (statusValue.startsWith("stable")) { + statusCode = 4 + } else { + statusCode = 0 + } + + libraryVersionCode = statusCode + } + if (map.containsKey("patch")) { - libraryVersionCode = Integer.parseInt(map["patch"]) + libraryVersionCode += Integer.parseInt(map["patch"]) * 10 } if (map.containsKey("minor")) { - libraryVersionCode += (Integer.parseInt(map["minor"]) * 100) + libraryVersionCode += (Integer.parseInt(map["minor"]) * 1000) } if (map.containsKey("major")) { - libraryVersionCode += (Integer.parseInt(map["major"]) * 10000) + libraryVersionCode += (Integer.parseInt(map["major"]) * 100000) } } catch (NumberFormatException ignore) { libraryVersionCode = 1 diff --git a/platform/android/java/editor/build.gradle b/platform/android/java/editor/build.gradle index 729966ee69..9152492e9d 100644 --- a/platform/android/java/editor/build.gradle +++ b/platform/android/java/editor/build.gradle @@ -12,6 +12,25 @@ dependencies { implementation "androidx.window:window:1.0.0" } +ext { + // Build number added as a suffix to the version code, and incremented for each build/upload to + // the Google Play store. + // This should be reset on each stable release of Godot. + editorBuildNumber = 0 + // Value by which the Godot version code should be offset by to make room for the build number + editorBuildNumberOffset = 100 +} + +def generateVersionCode() { + int libraryVersionCode = getGodotLibraryVersionCode() + return (libraryVersionCode * editorBuildNumberOffset) + editorBuildNumber +} + +def generateVersionName() { + String libraryVersionName = getGodotLibraryVersionName() + return libraryVersionName + ".$editorBuildNumber" +} + android { compileSdkVersion versions.compileSdk buildToolsVersion versions.buildTools @@ -20,8 +39,8 @@ android { defaultConfig { // The 'applicationId' suffix allows to install Godot 3.x(v3) and 4.x(v4) on the same device applicationId "org.godotengine.editor.v4" - versionCode getGodotLibraryVersionCode() - versionName getGodotLibraryVersionName() + versionCode generateVersionCode() + versionName generateVersionName() minSdkVersion versions.minSdk targetSdkVersion versions.targetSdk diff --git a/platform/android/java/editor/src/main/AndroidManifest.xml b/platform/android/java/editor/src/main/AndroidManifest.xml index abf506a83c..6aa5f06f31 100644 --- a/platform/android/java/editor/src/main/AndroidManifest.xml +++ b/platform/android/java/editor/src/main/AndroidManifest.xml @@ -7,7 +7,7 @@ <supports-screens android:largeScreens="true" android:normalScreens="true" - android:smallScreens="true" + android:smallScreens="false" android:xlargeScreens="true" /> <uses-feature diff --git a/platform/android/java/lib/src/org/godotengine/godot/Godot.java b/platform/android/java/lib/src/org/godotengine/godot/Godot.java index a75c69484c..92e5e59496 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/Godot.java +++ b/platform/android/java/lib/src/org/godotengine/godot/Godot.java @@ -274,11 +274,11 @@ public class Godot extends Fragment implements SensorEventListener, IDownloaderC return false; } - final String videoDriver = GodotLib.getGlobal("rendering/driver/driver_name"); - if (videoDriver.equals("vulkan")) { - mRenderView = new GodotVulkanRenderView(activity, this); - } else { + final String renderer = GodotLib.getGlobal("rendering/renderer/rendering_method"); + if (renderer.equals("gl_compatibility")) { mRenderView = new GodotGLRenderView(activity, this, xrMode, use_debug_opengl); + } else { + mRenderView = new GodotVulkanRenderView(activity, this); } View view = mRenderView.getView(); diff --git a/platform/android/os_android.cpp b/platform/android/os_android.cpp index 142dc54c45..4469c7a0f7 100644 --- a/platform/android/os_android.cpp +++ b/platform/android/os_android.cpp @@ -44,6 +44,7 @@ #include "net_socket_android.h" #include <dlfcn.h> +#include <sys/system_properties.h> #include "java_godot_io_wrapper.h" #include "java_godot_wrapper.h" @@ -175,6 +176,79 @@ String OS_Android::get_name() const { return "Android"; } +String OS_Android::get_system_property(const char *key) const { + static String value; + char value_str[PROP_VALUE_MAX]; + if (__system_property_get(key, value_str)) { + value = String(value_str); + } + return value; +} + +String OS_Android::get_distribution_name() const { + if (!get_system_property("ro.havoc.version").is_empty()) { + return "Havoc OS"; + } else if (!get_system_property("org.pex.version").is_empty()) { // Putting before "Pixel Experience", because it's derivating from it. + return "Pixel Extended"; + } else if (!get_system_property("org.pixelexperience.version").is_empty()) { + return "Pixel Experience"; + } else if (!get_system_property("ro.potato.version").is_empty()) { + return "POSP"; + } else if (!get_system_property("ro.xtended.version").is_empty()) { + return "Project-Xtended"; + } else if (!get_system_property("org.evolution.version").is_empty()) { + return "Evolution X"; + } else if (!get_system_property("ro.corvus.version").is_empty()) { + return "Corvus-Q"; + } else if (!get_system_property("ro.pa.version").is_empty()) { + return "Paranoid Android"; + } else if (!get_system_property("ro.crdroid.version").is_empty()) { + return "crDroid Android"; + } else if (!get_system_property("ro.syberia.version").is_empty()) { + return "Syberia Project"; + } else if (!get_system_property("ro.arrow.version").is_empty()) { + return "ArrowOS"; + } else if (!get_system_property("ro.lineage.version").is_empty()) { // Putting LineageOS last, just in case any derivative writes to "ro.lineage.version". + return "LineageOS"; + } + + if (!get_system_property("ro.modversion").is_empty()) { // Handles other Android custom ROMs. + return vformat("%s %s", get_name(), "Custom ROM"); + } + + // Handles stock Android. + return get_name(); +} + +String OS_Android::get_version() const { + const Vector<const char *> roms = { "ro.havoc.version", "org.pex.version", "org.pixelexperience.version", + "ro.potato.version", "ro.xtended.version", "org.evolution.version", "ro.corvus.version", "ro.pa.version", + "ro.crdroid.version", "ro.syberia.version", "ro.arrow.version", "ro.lineage.version" }; + for (int i = 0; i < roms.size(); i++) { + static String rom_version = get_system_property(roms[i]); + if (!rom_version.is_empty()) { + return rom_version; + } + } + + static String mod_version = get_system_property("ro.modversion"); // Handles other Android custom ROMs. + if (!mod_version.is_empty()) { + return mod_version; + } + + // Handles stock Android. + static String sdk_version = get_system_property("ro.build.version.sdk_int"); + static String build = get_system_property("ro.build.version.incremental"); + if (!sdk_version.is_empty()) { + if (!build.is_empty()) { + return vformat("%s.%s", sdk_version, build); + } + return sdk_version; + } + + return ""; +} + MainLoop *OS_Android::get_main_loop() const { return main_loop; } diff --git a/platform/android/os_android.h b/platform/android/os_android.h index 96c06d715c..d6546a3507 100644 --- a/platform/android/os_android.h +++ b/platform/android/os_android.h @@ -65,6 +65,8 @@ private: GodotJavaWrapper *godot_java = nullptr; GodotIOJavaWrapper *godot_io_java = nullptr; + String get_system_property(const char *key) const; + public: static const char *ANDROID_EXEC_PATH; @@ -93,6 +95,8 @@ public: virtual Error open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path = false, String *r_resolved_path = nullptr) override; virtual String get_name() const override; + virtual String get_distribution_name() const override; + virtual String get_version() const override; virtual MainLoop *get_main_loop() const override; void main_loop_begin(); diff --git a/platform/ios/detect.py b/platform/ios/detect.py index 3cfb25cf61..0f277d6b3a 100644 --- a/platform/ios/detect.py +++ b/platform/ios/detect.py @@ -39,9 +39,6 @@ def get_flags(): ("arch", "arm64"), # Default for convenience. ("tools", False), ("use_volk", False), - # Disable by default even if production is set, as it makes linking in Xcode - # on exports very slow and that's not what most users expect. - ("lto", "none"), ] @@ -58,22 +55,25 @@ def configure(env): ## Build type if env["target"].startswith("release"): - env.Append(CPPDEFINES=["NDEBUG", ("NS_BLOCK_ASSERTIONS", 1)]) + env.Append(CPPDEFINES=[("NS_BLOCK_ASSERTIONS", 1)]) if env["optimize"] == "speed": # optimize for speed (default) # `-O2` is more friendly to debuggers than `-O3`, leading to better crash backtraces # when using `target=release_debug`. opt = "-O3" if env["target"] == "release" else "-O2" - env.Append(CCFLAGS=[opt, "-ftree-vectorize", "-fomit-frame-pointer"]) + env.Append(CCFLAGS=[opt]) env.Append(LINKFLAGS=[opt]) elif env["optimize"] == "size": # optimize for size - env.Append(CCFLAGS=["-Os", "-ftree-vectorize"]) + env.Append(CCFLAGS=["-Os"]) env.Append(LINKFLAGS=["-Os"]) elif env["target"] == "debug": - env.Append(CCFLAGS=["-gdwarf-2", "-O0"]) - env.Append(CPPDEFINES=["_DEBUG", ("DEBUG", 1)]) + env.Append(CCFLAGS=["-g", "-O0"]) + + ## LTO + + if env["lto"] == "auto": # Disable by default as it makes linking in Xcode very slow. + env["lto"] = "none" - # LTO if env["lto"] != "none": if env["lto"] == "thin": env.Append(CCFLAGS=["-flto=thin"]) @@ -120,6 +120,10 @@ def configure(env): env.Append(CCFLAGS=["-miphoneos-version-min=11.0"]) if env["arch"] == "x86_64": + if not env["ios_simulator"]: + print("ERROR: Building for iOS with 'arch=x86_64' requires 'ios_simulator=yes'.") + sys.exit(255) + env["ENV"]["MACOSX_DEPLOYMENT_TARGET"] = "10.9" env.Append( CCFLAGS=( diff --git a/platform/ios/display_layer.mm b/platform/ios/display_layer.mm index 7c83494768..74c760ae9a 100644 --- a/platform/ios/display_layer.mm +++ b/platform/ios/display_layer.mm @@ -89,12 +89,12 @@ // FIXME: Add Vulkan support via MoltenVK. Add fallback code back? - // Create GL ES 2 context - if (GLOBAL_GET("rendering/driver/driver_name") == "opengl3") { - context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; - NSLog(@"Setting up an OpenGL ES 2.0 context."); + // Create GL ES 3 context + if (GLOBAL_GET("rendering/renderer/rendering_method") == "gl_compatibility") { + context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3]; + NSLog(@"Setting up an OpenGL ES 3.0 context."); if (!context) { - NSLog(@"Failed to create OpenGL ES 2.0 context!"); + NSLog(@"Failed to create OpenGL ES 3.0 context!"); return; } } diff --git a/platform/ios/display_server_ios.mm b/platform/ios/display_server_ios.mm index 74d6bc2e97..d3a0f38463 100644 --- a/platform/ios/display_server_ios.mm +++ b/platform/ios/display_server_ios.mm @@ -62,7 +62,7 @@ DisplayServerIOS::DisplayServerIOS(const String &p_rendering_driver, WindowMode // Note that we should be checking "opengl3" as the driver, might never enable this seeing OpenGL is deprecated on iOS // We are hardcoding the rendering_driver to "vulkan" down below - if (rendering_driver == "opengl_es") { + if (rendering_driver == "opengl3") { bool gl_initialization_error = false; // FIXME: Add Vulkan support via MoltenVK. Add fallback code back? @@ -163,7 +163,7 @@ Vector<String> DisplayServerIOS::get_rendering_drivers_func() { drivers.push_back("vulkan"); #endif #if defined(GLES3_ENABLED) - drivers.push_back("opengl_es"); + drivers.push_back("opengl3"); #endif return drivers; diff --git a/platform/ios/export/export_plugin.cpp b/platform/ios/export/export_plugin.cpp index 7aacb2de85..74a57dc614 100644 --- a/platform/ios/export/export_plugin.cpp +++ b/platform/ios/export/export_plugin.cpp @@ -34,7 +34,6 @@ #include "editor/editor_node.h" void EditorExportPlatformIOS::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) const { - String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name"); // Vulkan and OpenGL ES 3.0 both mandate ETC2 support. r_features->push_back("etc2"); diff --git a/platform/ios/godot_view.mm b/platform/ios/godot_view.mm index 9ed219508c..ff90c05b1d 100644 --- a/platform/ios/godot_view.mm +++ b/platform/ios/godot_view.mm @@ -74,7 +74,7 @@ static const float earth_gravity = 9.80665; if ([driverName isEqualToString:@"vulkan"]) { layer = [GodotMetalLayer layer]; - } else if ([driverName isEqualToString:@"opengl_es"]) { + } else if ([driverName isEqualToString:@"opengl3"]) { if (@available(iOS 13, *)) { NSLog(@"OpenGL ES is deprecated on iOS 13"); } diff --git a/platform/ios/os_ios.h b/platform/ios/os_ios.h index 3b88f53b6a..00d91da771 100644 --- a/platform/ios/os_ios.h +++ b/platform/ios/os_ios.h @@ -100,6 +100,8 @@ public: virtual Error get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional = false) override; virtual String get_name() const override; + virtual String get_distribution_name() const override; + virtual String get_version() const override; virtual String get_model_name() const override; virtual Error shell_open(String p_uri) override; diff --git a/platform/ios/os_ios.mm b/platform/ios/os_ios.mm index b9d186f355..a674498620 100644 --- a/platform/ios/os_ios.mm +++ b/platform/ios/os_ios.mm @@ -240,6 +240,15 @@ String OS_IOS::get_name() const { return "iOS"; } +String OS_IOS::get_distribution_name() const { + return get_name(); +} + +String OS_IOS::get_version() const { + NSOperatingSystemVersion ver = [NSProcessInfo processInfo].operatingSystemVersion; + return vformat("%d.%d.%d", (int64_t)ver.majorVersion, (int64_t)ver.minorVersion, (int64_t)ver.patchVersion); +} + String OS_IOS::get_model_name() const { String model = ios->get_model(); if (model != "") { diff --git a/platform/linuxbsd/detect.py b/platform/linuxbsd/detect.py index 36644d5f29..12d2432eea 100644 --- a/platform/linuxbsd/detect.py +++ b/platform/linuxbsd/detect.py @@ -171,6 +171,10 @@ def configure(env): env.Append(LINKFLAGS=["-fsanitize=memory"]) # LTO + + if env["lto"] == "auto": # Full LTO for production. + env["lto"] = "full" + if env["lto"] != "none": if env["lto"] == "thin": if not env["use_llvm"]: diff --git a/platform/linuxbsd/display_server_x11.cpp b/platform/linuxbsd/display_server_x11.cpp index 0236e134fb..66dea6cf1b 100644 --- a/platform/linuxbsd/display_server_x11.cpp +++ b/platform/linuxbsd/display_server_x11.cpp @@ -397,7 +397,10 @@ void DisplayServerX11::mouse_set_mode(MouseMode p_mode) { if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) { //flush pending motion events _flush_mouse_motion(); - WindowID window_id = windows.has(last_focused_window) ? last_focused_window : MAIN_WINDOW_ID; + WindowID window_id = _get_focused_window_or_popup(); + if (!windows.has(window_id)) { + window_id = MAIN_WINDOW_ID; + } WindowData &window = windows[window_id]; if (XGrabPointer( @@ -433,7 +436,11 @@ void DisplayServerX11::warp_mouse(const Point2i &p_position) { if (mouse_mode == MOUSE_MODE_CAPTURED) { last_mouse_pos = p_position; } else { - WindowID window_id = windows.has(last_focused_window) ? last_focused_window : MAIN_WINDOW_ID; + WindowID window_id = _get_focused_window_or_popup(); + if (!windows.has(window_id)) { + window_id = MAIN_WINDOW_ID; + } + XWarpPointer(x11_display, None, windows[window_id].x11_window, 0, 0, 0, 0, (int)p_position.x, (int)p_position.y); } @@ -3181,6 +3188,15 @@ void DisplayServerX11::_window_changed(XEvent *event) { } } +DisplayServer::WindowID DisplayServerX11::_get_focused_window_or_popup() const { + const List<WindowID>::Element *E = popup_list.back(); + if (E) { + return E->get(); + } + + return last_focused_window; +} + void DisplayServerX11::_dispatch_input_events(const Ref<InputEvent> &p_event) { static_cast<DisplayServerX11 *>(get_singleton())->_dispatch_input_event(p_event); } @@ -3936,7 +3952,11 @@ void DisplayServerX11::process_events() { // The X11 API requires filtering one-by-one through the motion // notify events, in order to figure out which event is the one // generated by warping the mouse pointer. - WindowID focused_window_id = windows.has(last_focused_window) ? last_focused_window : MAIN_WINDOW_ID; + WindowID focused_window_id = _get_focused_window_or_popup(); + if (!windows.has(focused_window_id)) { + focused_window_id = MAIN_WINDOW_ID; + } + while (true) { if (mouse_mode == MOUSE_MODE_CAPTURED && event.xmotion.x == windows[focused_window_id].size.width / 2 && event.xmotion.y == windows[focused_window_id].size.height / 2) { //this is likely the warp event since it was warped here diff --git a/platform/linuxbsd/display_server_x11.h b/platform/linuxbsd/display_server_x11.h index ea03b2328c..a5fa7613bc 100644 --- a/platform/linuxbsd/display_server_x11.h +++ b/platform/linuxbsd/display_server_x11.h @@ -284,6 +284,8 @@ class DisplayServerX11 : public DisplayServer { Context context = CONTEXT_ENGINE; + WindowID _get_focused_window_or_popup() const; + void _send_window_event(const WindowData &wd, WindowEvent p_event); static void _dispatch_input_events(const Ref<InputEvent> &p_event); void _dispatch_input_event(const Ref<InputEvent> &p_event); diff --git a/platform/linuxbsd/gl_manager_x11.cpp b/platform/linuxbsd/gl_manager_x11.cpp index 04c1df71fb..838be2c042 100644 --- a/platform/linuxbsd/gl_manager_x11.cpp +++ b/platform/linuxbsd/gl_manager_x11.cpp @@ -256,7 +256,11 @@ void GLManager_X11::release_current() { if (!_current_window) { return; } - glXMakeCurrent(_x_windisp.x11_display, None, nullptr); + + if (!glXMakeCurrent(_x_windisp.x11_display, None, nullptr)) { + ERR_PRINT("glXMakeCurrent failed"); + } + _current_window = nullptr; } void GLManager_X11::window_make_current(DisplayServer::WindowID p_window_id) { @@ -276,7 +280,9 @@ void GLManager_X11::window_make_current(DisplayServer::WindowID p_window_id) { const GLDisplay &disp = get_display(win.gldisplay_id); - glXMakeCurrent(disp.x11_display, win.x11_window, disp.context->glx_context); + if (!glXMakeCurrent(disp.x11_display, win.x11_window, disp.context->glx_context)) { + ERR_PRINT("glXMakeCurrent failed"); + } _internal_set_current_window(&win); } @@ -290,13 +296,12 @@ void GLManager_X11::make_current() { return; } const GLDisplay &disp = get_current_display(); - glXMakeCurrent(_x_windisp.x11_display, _x_windisp.x11_window, disp.context->glx_context); + if (!glXMakeCurrent(_x_windisp.x11_display, _x_windisp.x11_window, disp.context->glx_context)) { + ERR_PRINT("glXMakeCurrent failed"); + } } void GLManager_X11::swap_buffers() { - // NO NEED TO CALL SWAP BUFFERS for each window... - // see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glXSwapBuffers.xml - if (!_current_window) { return; } @@ -315,13 +320,6 @@ void GLManager_X11::swap_buffers() { } } - // print_line("\tswap_buffers"); - - // only for debugging without drawing anything - // glClearColor(Math::randf(), 0, 1, 1); - //glClear(GL_COLOR_BUFFER_BIT); - - //const GLDisplay &disp = get_current_display(); glXSwapBuffers(_x_windisp.x11_display, _x_windisp.x11_window); } diff --git a/platform/linuxbsd/os_linuxbsd.cpp b/platform/linuxbsd/os_linuxbsd.cpp index 61faf3061c..f4e94f1a91 100644 --- a/platform/linuxbsd/os_linuxbsd.cpp +++ b/platform/linuxbsd/os_linuxbsd.cpp @@ -50,6 +50,7 @@ #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> +#include <sys/utsname.h> #include <unistd.h> #ifdef FONTCONFIG_ENABLED @@ -205,6 +206,42 @@ String OS_LinuxBSD::get_name() const { #endif } +String OS_LinuxBSD::get_systemd_os_release_info_value(const String &key) const { + static String info; + if (info.is_empty()) { + Ref<FileAccess> f = FileAccess::open("/etc/os-release", FileAccess::READ); + if (f.is_valid()) { + while (!f->eof_reached()) { + const String line = f->get_line(); + if (line.find(key) != -1) { + return line.split("=")[1].strip_edges(); + } + } + } + } + return info; +} + +String OS_LinuxBSD::get_distribution_name() const { + static String systemd_name = get_systemd_os_release_info_value("NAME"); // returns a value for systemd users, otherwise an empty string. + if (!systemd_name.is_empty()) { + return systemd_name; + } + struct utsname uts; // returns a decent value for BSD family. + uname(&uts); + return uts.sysname; +} + +String OS_LinuxBSD::get_version() const { + static String systemd_version = get_systemd_os_release_info_value("VERSION"); // returns a value for systemd users, otherwise an empty string. + if (!systemd_version.is_empty()) { + return systemd_version; + } + struct utsname uts; // returns a decent value for BSD family. + uname(&uts); + return uts.version; +} + Error OS_LinuxBSD::shell_open(String p_uri) { Error ok; int err_code; @@ -686,10 +723,9 @@ Error OS_LinuxBSD::move_to_trash(const String &p_path) { String renamed_path = path.get_base_dir() + "/" + file_name; // Generates the .trashinfo file - OS::Date date = OS::get_singleton()->get_date(false); - OS::Time time = OS::get_singleton()->get_time(false); - String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", date.year, (int)date.month, date.day, time.hour, time.minute); - timestamp = vformat("%s%02d", timestamp, time.second); // vformat only supports up to 6 arguments. + OS::DateTime dt = OS::get_singleton()->get_datetime(false); + String timestamp = vformat("%04d-%02d-%02dT%02d:%02d:", dt.year, (int)dt.month, dt.day, dt.hour, dt.minute); + timestamp = vformat("%s%02d", timestamp, dt.second); // vformat only supports up to 6 arguments. String trash_info = "[Trash Info]\nPath=" + path.uri_encode() + "\nDeletionDate=" + timestamp + "\n"; { Error err; diff --git a/platform/linuxbsd/os_linuxbsd.h b/platform/linuxbsd/os_linuxbsd.h index d5b2321316..722d83ba19 100644 --- a/platform/linuxbsd/os_linuxbsd.h +++ b/platform/linuxbsd/os_linuxbsd.h @@ -67,6 +67,8 @@ class OS_LinuxBSD : public OS_Unix { MainLoop *main_loop = nullptr; + String get_systemd_os_release_info_value(const String &key) const; + protected: virtual void initialize() override; virtual void finalize() override; @@ -77,6 +79,8 @@ protected: public: virtual String get_name() const override; + virtual String get_distribution_name() const override; + virtual String get_version() const override; virtual MainLoop *get_main_loop() const override; diff --git a/platform/macos/SCsub b/platform/macos/SCsub index bbd461fba9..7ffb80f70b 100644 --- a/platform/macos/SCsub +++ b/platform/macos/SCsub @@ -12,6 +12,7 @@ files = [ "crash_handler_macos.mm", "macos_terminal_logger.mm", "display_server_macos.mm", + "godot_button_view.mm", "godot_content_view.mm", "godot_window_delegate.mm", "godot_window.mm", diff --git a/platform/macos/detect.py b/platform/macos/detect.py index bcf4776609..58d9c0e99f 100644 --- a/platform/macos/detect.py +++ b/platform/macos/detect.py @@ -40,9 +40,6 @@ def get_flags(): return [ ("arch", detect_arch()), ("use_volk", False), - # Benefits of LTO for macOS (size, performance) haven't been clearly established yet. - # So for now we override the default value which may be set when using `production=yes`. - ("lto", "none"), ] @@ -91,9 +88,9 @@ def configure(env): if env["target"] == "release": if env["optimize"] == "speed": # optimize for speed (default) - env.Prepend(CCFLAGS=["-O3", "-fomit-frame-pointer", "-ftree-vectorize"]) + env.Prepend(CCFLAGS=["-O3"]) elif env["optimize"] == "size": # optimize for size - env.Prepend(CCFLAGS=["-Os", "-ftree-vectorize"]) + env.Prepend(CCFLAGS=["-Os"]) if env["arch"] != "arm64": env.Prepend(CCFLAGS=["-msse2"]) @@ -170,6 +167,10 @@ def configure(env): env["AS"] = basecmd + "as" # LTO + + if env["lto"] == "auto": # LTO benefits for macOS (size, performance) haven't been clearly established yet. + env["lto"] = "none" + if env["lto"] != "none": if env["lto"] == "thin": env.Append(CCFLAGS=["-flto=thin"]) @@ -178,6 +179,8 @@ def configure(env): env.Append(CCFLAGS=["-flto"]) env.Append(LINKFLAGS=["-flto"]) + # Sanitizers + if env["use_ubsan"] or env["use_asan"] or env["use_tsan"]: env.extra_suffix += ".san" env.Append(CCFLAGS=["-DSANITIZERS_ENABLED"]) diff --git a/platform/macos/display_server_macos.h b/platform/macos/display_server_macos.h index 769cba2de5..e72273a681 100644 --- a/platform/macos/display_server_macos.h +++ b/platform/macos/display_server_macos.h @@ -76,6 +76,7 @@ public: id window_delegate; id window_object; id window_view; + id window_button_view; Vector<Vector2> mpath; @@ -84,6 +85,9 @@ public: Size2i min_size; Size2i max_size; Size2i size; + Vector2i wb_offset = Vector2i(14, 14); + + NSRect last_frame_rect; bool im_active = false; Size2i im_position; @@ -175,6 +179,12 @@ private: IOPMAssertionID screen_keep_on_assertion = kIOPMNullAssertionID; + struct MenuCall { + Variant tag; + Callable callback; + }; + Vector<MenuCall> deferred_menu_calls; + const NSMenu *_get_menu_root(const String &p_menu_root) const; NSMenu *_get_menu_root(const String &p_menu_root); @@ -187,6 +197,8 @@ private: Point2i _get_native_screen_position(int p_screen) const; static void _displays_arrangement_changed(CGDirectDisplayID display_id, CGDisplayChangeSummaryFlags flags, void *user_info); + WindowID _get_focused_window_or_popup() const; + static void _dispatch_input_events(const Ref<InputEvent> &p_event); void _dispatch_input_event(const Ref<InputEvent> &p_event); void _push_input(const Ref<InputEvent> &p_event); @@ -224,6 +236,7 @@ public: void window_update(WindowID p_window); void window_destroy(WindowID p_window); void window_resize(WindowID p_window, int p_width, int p_height); + void window_set_custom_window_buttons(WindowData &p_wd, bool p_enabled); virtual bool has_feature(Feature p_feature) const override; virtual String get_name() const override; @@ -387,6 +400,7 @@ public: virtual bool window_maximize_on_title_dbl_click() const override; virtual bool window_minimize_on_title_dbl_click() const override; + virtual void window_set_window_buttons_offset(const Vector2i &p_offset, WindowID p_window = MAIN_WINDOW_ID) override; virtual Vector2i window_get_safe_title_margins(WindowID p_window = MAIN_WINDOW_ID) const override; virtual Point2i ime_get_selection() const override; diff --git a/platform/macos/display_server_macos.mm b/platform/macos/display_server_macos.mm index b009007d73..1914c5f35d 100644 --- a/platform/macos/display_server_macos.mm +++ b/platform/macos/display_server_macos.mm @@ -30,6 +30,7 @@ #include "display_server_macos.h" +#include "godot_button_view.h" #include "godot_content_view.h" #include "godot_menu_delegate.h" #include "godot_menu_item.h" @@ -166,6 +167,7 @@ DisplayServerMacOS::WindowID DisplayServerMacOS::_create_window(WindowMode p_mod ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create an OpenGL context"); } #endif + [wd.window_view updateLayerDelegate]; id = window_id_counter++; windows[id] = wd; } @@ -316,6 +318,15 @@ void DisplayServerMacOS::_displays_arrangement_changed(CGDirectDisplayID display } } +DisplayServer::WindowID DisplayServerMacOS::_get_focused_window_or_popup() const { + const List<WindowID>::Element *E = popup_list.back(); + if (E) { + return E->get(); + } + + return last_focused_window; +} + void DisplayServerMacOS::_dispatch_input_events(const Ref<InputEvent> &p_event) { ((DisplayServerMacOS *)(get_singleton()))->_dispatch_input_event(p_event); } @@ -554,11 +565,11 @@ void DisplayServerMacOS::menu_callback(id p_sender) { } if (value->callback != Callable()) { - Variant tag = value->meta; - Variant *tagp = &tag; - Variant ret; - Callable::CallError ce; - value->callback.callp((const Variant **)&tagp, 1, ret, ce); + MenuCall mc; + mc.tag = value->meta; + mc.callback = value->callback; + deferred_menu_calls.push_back(mc); + // Do not run callback from here! If it is opening a new window or calling process_events, it will corrupt OS event queue and crash. } } } @@ -1827,7 +1838,10 @@ void DisplayServerMacOS::mouse_set_mode(MouseMode p_mode) { return; } - WindowID window_id = windows.has(last_focused_window) ? last_focused_window : MAIN_WINDOW_ID; + WindowID window_id = _get_focused_window_or_popup(); + if (!windows.has(window_id)) { + window_id = MAIN_WINDOW_ID; + } WindowData &wd = windows[window_id]; if (p_mode == MOUSE_MODE_CAPTURED) { // Apple Docs state that the display parameter is not used. @@ -1942,7 +1956,10 @@ void DisplayServerMacOS::warp_mouse(const Point2i &p_position) { _THREAD_SAFE_METHOD_ if (mouse_mode != MOUSE_MODE_CAPTURED) { - WindowID window_id = windows.has(last_focused_window) ? last_focused_window : MAIN_WINDOW_ID; + WindowID window_id = _get_focused_window_or_popup(); + if (!windows.has(window_id)) { + window_id = MAIN_WINDOW_ID; + } WindowData &wd = windows[window_id]; // Local point in window coords. @@ -2196,7 +2213,9 @@ void DisplayServerMacOS::show_window(WindowID p_id) { WindowData &wd = windows[p_id]; popup_open(p_id); - if (wd.no_focus || wd.is_popup) { + if ([wd.window_object isMiniaturized]) { + return; + } else if (wd.no_focus || wd.is_popup) { [wd.window_object orderFront:nil]; } else { [wd.window_object makeKeyAndOrderFront:nil]; @@ -2353,6 +2372,10 @@ void DisplayServerMacOS::window_set_position(const Point2i &p_position, WindowID ERR_FAIL_COND(!windows.has(p_window)); WindowData &wd = windows[p_window]; + if ([wd.window_object isZoomed]) { + return; + } + Point2i position = p_position; // OS X native y-coordinate relative to _get_screens_origin() is negative, // Godot passes a positive value. @@ -2477,6 +2500,10 @@ void DisplayServerMacOS::window_set_size(const Size2i p_size, WindowID p_window) ERR_FAIL_COND(!windows.has(p_window)); WindowData &wd = windows[p_window]; + if ([wd.window_object isZoomed]) { + return; + } + Size2i size = p_size / screen_get_max_scale(); NSPoint top_left; @@ -2623,27 +2650,59 @@ bool DisplayServerMacOS::window_minimize_on_title_dbl_click() const { return false; } +void DisplayServerMacOS::window_set_window_buttons_offset(const Vector2i &p_offset, WindowID p_window) { + _THREAD_SAFE_METHOD_ + + ERR_FAIL_COND(!windows.has(p_window)); + WindowData &wd = windows[p_window]; + wd.wb_offset = p_offset; +} + Vector2i DisplayServerMacOS::window_get_safe_title_margins(WindowID p_window) const { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V(!windows.has(p_window), Vector2i()); const WindowData &wd = windows[p_window]; - float max_x = 0.f; - NSButton *cb = [wd.window_object standardWindowButton:NSWindowCloseButton]; - if (cb) { - max_x = MAX(max_x, [cb frame].origin.x + [cb frame].size.width); + if (!wd.window_button_view) { + return Vector2i(); } - NSButton *mb = [wd.window_object standardWindowButton:NSWindowMiniaturizeButton]; - if (mb) { - max_x = MAX(max_x, [mb frame].origin.x + [mb frame].size.width); + + float max_x = wd.wb_offset.x + [wd.window_button_view frame].size.width; + + if ([wd.window_object windowTitlebarLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft) { + return Vector2i(0, max_x * screen_get_max_scale()); + } else { + return Vector2i(max_x * screen_get_max_scale(), 0); } - NSButton *zb = [wd.window_object standardWindowButton:NSWindowZoomButton]; - if (zb) { - max_x = MAX(max_x, [zb frame].origin.x + [zb frame].size.width); +} + +void DisplayServerMacOS::window_set_custom_window_buttons(WindowData &p_wd, bool p_enabled) { + if (p_wd.window_button_view) { + [p_wd.window_button_view removeFromSuperview]; + p_wd.window_button_view = nil; } + if (p_enabled) { + float cb_frame = NSMinX([[p_wd.window_object standardWindowButton:NSWindowCloseButton] frame]); + float mb_frame = NSMinX([[p_wd.window_object standardWindowButton:NSWindowMiniaturizeButton] frame]); + bool is_rtl = ([p_wd.window_object windowTitlebarLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft); + + float window_buttons_spacing = (is_rtl) ? (cb_frame - mb_frame) : (mb_frame - cb_frame); + + [p_wd.window_object setTitleVisibility:NSWindowTitleHidden]; + [[p_wd.window_object standardWindowButton:NSWindowZoomButton] setHidden:YES]; + [[p_wd.window_object standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES]; + [[p_wd.window_object standardWindowButton:NSWindowCloseButton] setHidden:YES]; - return Vector2i(max_x * screen_get_max_scale(), 0); + p_wd.window_button_view = [[GodotButtonView alloc] initWithFrame:NSZeroRect]; + [p_wd.window_button_view initButtons:window_buttons_spacing offset:NSMakePoint(p_wd.wb_offset.x, p_wd.wb_offset.y) rtl:is_rtl]; + [p_wd.window_view addSubview:p_wd.window_button_view]; + } else { + [p_wd.window_object setTitleVisibility:NSWindowTitleVisible]; + [[p_wd.window_object standardWindowButton:NSWindowZoomButton] setHidden:NO]; + [[p_wd.window_object standardWindowButton:NSWindowMiniaturizeButton] setHidden:NO]; + [[p_wd.window_object standardWindowButton:NSWindowCloseButton] setHidden:NO]; + } } void DisplayServerMacOS::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) { @@ -2668,14 +2727,21 @@ void DisplayServerMacOS::window_set_flag(WindowFlags p_flag, bool p_enabled, Win NSRect rect = [wd.window_object frame]; if (p_enabled) { [wd.window_object setTitlebarAppearsTransparent:YES]; - [wd.window_object setTitleVisibility:NSWindowTitleHidden]; [wd.window_object setStyleMask:[wd.window_object styleMask] | NSWindowStyleMaskFullSizeContentView]; + + if (!wd.fullscreen) { + window_set_custom_window_buttons(wd, true); + } } else { [wd.window_object setTitlebarAppearsTransparent:NO]; - [wd.window_object setTitleVisibility:NSWindowTitleVisible]; [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskFullSizeContentView]; + + if (!wd.fullscreen) { + window_set_custom_window_buttons(wd, false); + } } [wd.window_object setFrame:rect display:YES]; + send_window_event(wd, DisplayServerMacOS::WINDOW_EVENT_TITLEBAR_CHANGE); } break; case WINDOW_FLAG_BORDERLESS: { // OrderOut prevents a lose focus bug with the window. @@ -2695,7 +2761,9 @@ void DisplayServerMacOS::window_set_flag(WindowFlags p_flag, bool p_enabled, Win } _update_window_style(wd); if ([wd.window_object isVisible]) { - if (wd.no_focus || wd.is_popup) { + if ([wd.window_object isMiniaturized]) { + return; + } else if (wd.no_focus || wd.is_popup) { [wd.window_object orderFront:nil]; } else { [wd.window_object makeKeyAndOrderFront:nil]; @@ -3212,6 +3280,16 @@ void DisplayServerMacOS::process_events() { [NSApp sendEvent:event]; } + // Process "menu_callback"s. + for (MenuCall &E : deferred_menu_calls) { + Variant tag = E.tag; + Variant *tagp = &tag; + Variant ret; + Callable::CallError ce; + E.callback.callp((const Variant **)&tagp, 1, ret, ce); + } + deferred_menu_calls.clear(); + if (!drop_events) { _process_key_events(); Input::get_singleton()->flush_buffered_events(); @@ -3536,7 +3614,7 @@ DisplayServerMacOS::DisplayServerMacOS(const String &p_rendering_driver, WindowM [apple_menu addItem:[NSMenuItem separatorItem]]; - title = [NSString stringWithFormat:NSLocalizedString(@"\t\tQuit %@", nil), nsappname]; + title = [NSString stringWithFormat:NSLocalizedString(@"Quit %@", nil), nsappname]; [apple_menu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; // Add items to the menu bar. diff --git a/platform/macos/export/export.cpp b/platform/macos/export/export.cpp index f219616df4..5f9cf22ccf 100644 --- a/platform/macos/export/export.cpp +++ b/platform/macos/export/export.cpp @@ -33,12 +33,14 @@ #include "export_plugin.h" void register_macos_exporter() { +#ifndef ANDROID_ENABLED EDITOR_DEF("export/macos/rcodesign", ""); #ifdef WINDOWS_ENABLED EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/macos/rcodesign", PROPERTY_HINT_GLOBAL_FILE, "*.exe")); #else EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/macos/rcodesign", PROPERTY_HINT_GLOBAL_FILE)); #endif +#endif Ref<EditorExportPlatformMacOS> platform; platform.instantiate(); diff --git a/platform/macos/export/export_plugin.cpp b/platform/macos/export/export_plugin.cpp index 50104aced5..070830c486 100644 --- a/platform/macos/export/export_plugin.cpp +++ b/platform/macos/export/export_plugin.cpp @@ -1641,16 +1641,15 @@ void EditorExportPlatformMacOS::_zip_folder_recursive(zipFile &p_zip, const Stri continue; } if (da->is_link(f)) { - OS::Time time = OS::get_singleton()->get_time(); - OS::Date date = OS::get_singleton()->get_date(); + OS::DateTime dt = OS::get_singleton()->get_datetime(); zip_fileinfo zipfi; - zipfi.tmz_date.tm_hour = time.hour; - zipfi.tmz_date.tm_mday = date.day; - zipfi.tmz_date.tm_min = time.minute; - zipfi.tmz_date.tm_mon = date.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, https://www.cplusplus.com/reference/ctime/tm/ - zipfi.tmz_date.tm_sec = time.second; - zipfi.tmz_date.tm_year = date.year; + zipfi.tmz_date.tm_year = dt.year; + zipfi.tmz_date.tm_mon = dt.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, https://www.cplusplus.com/reference/ctime/tm/ + zipfi.tmz_date.tm_mday = dt.day; + zipfi.tmz_date.tm_hour = dt.hour; + zipfi.tmz_date.tm_min = dt.minute; + zipfi.tmz_date.tm_sec = dt.second; zipfi.dosDate = 0; // 0120000: symbolic link type // 0000755: permissions rwxr-xr-x @@ -1686,16 +1685,15 @@ void EditorExportPlatformMacOS::_zip_folder_recursive(zipFile &p_zip, const Stri } else { bool is_executable = (p_folder.ends_with("MacOS") && (f == p_pkg_name)) || p_folder.ends_with("Helpers") || f.ends_with(".command"); - OS::Time time = OS::get_singleton()->get_time(); - OS::Date date = OS::get_singleton()->get_date(); + OS::DateTime dt = OS::get_singleton()->get_datetime(); zip_fileinfo zipfi; - zipfi.tmz_date.tm_hour = time.hour; - zipfi.tmz_date.tm_mday = date.day; - zipfi.tmz_date.tm_min = time.minute; - zipfi.tmz_date.tm_mon = date.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, https://www.cplusplus.com/reference/ctime/tm/ - zipfi.tmz_date.tm_sec = time.second; - zipfi.tmz_date.tm_year = date.year; + zipfi.tmz_date.tm_year = dt.year; + zipfi.tmz_date.tm_mon = dt.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, https://www.cplusplus.com/reference/ctime/tm/ + zipfi.tmz_date.tm_mday = dt.day; + zipfi.tmz_date.tm_hour = dt.hour; + zipfi.tmz_date.tm_min = dt.minute; + zipfi.tmz_date.tm_sec = dt.second; zipfi.dosDate = 0; // 0100000: regular file type // 0000755: permissions rwxr-xr-x diff --git a/platform/macos/gl_manager_macos_legacy.mm b/platform/macos/gl_manager_macos_legacy.mm index e6bb7aaa85..dec4821b86 100644 --- a/platform/macos/gl_manager_macos_legacy.mm +++ b/platform/macos/gl_manager_macos_legacy.mm @@ -167,9 +167,8 @@ void GLManager_MacOS::make_current() { } void GLManager_MacOS::swap_buffers() { - for (const KeyValue<DisplayServer::WindowID, GLWindow> &E : windows) { - [E.value.context flushBuffer]; - } + GLWindow &win = windows[current_window]; + [win.context flushBuffer]; } void GLManager_MacOS::window_update(DisplayServer::WindowID p_window_id) { diff --git a/platform/macos/godot_button_view.h b/platform/macos/godot_button_view.h new file mode 100644 index 0000000000..e7627a9e9b --- /dev/null +++ b/platform/macos/godot_button_view.h @@ -0,0 +1,52 @@ +/*************************************************************************/ +/* godot_button_view.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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. */ +/*************************************************************************/ + +#ifndef GODOT_BUTTON_VIEW_H +#define GODOT_BUTTON_VIEW_H + +#include "servers/display_server.h" + +#import <AppKit/AppKit.h> +#import <Foundation/Foundation.h> + +@interface GodotButtonView : NSView { + NSTrackingArea *tracking_area; + NSPoint offset; + CGFloat spacing; + bool mouse_in_group; + bool rtl; +} + +- (void)initButtons:(CGFloat)button_spacing offset:(NSPoint)button_offset rtl:(bool)is_rtl; +- (void)displayButtons; + +@end + +#endif // GODOT_BUTTON_VIEW_H diff --git a/platform/macos/godot_button_view.mm b/platform/macos/godot_button_view.mm new file mode 100644 index 0000000000..9106f0b0db --- /dev/null +++ b/platform/macos/godot_button_view.mm @@ -0,0 +1,123 @@ +/*************************************************************************/ +/* godot_button_view.mm */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "godot_button_view.h" + +@implementation GodotButtonView + +- (id)initWithFrame:(NSRect)frame { + self = [super initWithFrame:frame]; + + tracking_area = nil; + offset = NSMakePoint(8, 8); + spacing = 20; + mouse_in_group = false; + rtl = false; + + return self; +} + +- (void)initButtons:(CGFloat)button_spacing offset:(NSPoint)button_offset rtl:(bool)is_rtl { + spacing = button_spacing; + rtl = is_rtl; + + NSButton *close_button = [NSWindow standardWindowButton:NSWindowCloseButton forStyleMask:NSWindowStyleMaskTitled]; + [close_button setFrameOrigin:NSMakePoint(rtl ? spacing * 2 : 0, 0)]; + [self addSubview:close_button]; + + NSButton *miniaturize_button = [NSWindow standardWindowButton:NSWindowMiniaturizeButton forStyleMask:NSWindowStyleMaskTitled]; + [miniaturize_button setFrameOrigin:NSMakePoint(spacing, 0)]; + [self addSubview:miniaturize_button]; + + NSButton *zoom_button = [NSWindow standardWindowButton:NSWindowZoomButton forStyleMask:NSWindowStyleMaskTitled]; + [zoom_button setFrameOrigin:NSMakePoint(rtl ? 0 : spacing * 2, 0)]; + [self addSubview:zoom_button]; + + offset.y = button_offset.y - zoom_button.frame.size.height / 2; + offset.x = button_offset.x - zoom_button.frame.size.width / 2; + + if (rtl) { + [self setFrameSize:NSMakeSize(close_button.frame.origin.x + close_button.frame.size.width, close_button.frame.size.height)]; + } else { + [self setFrameSize:NSMakeSize(zoom_button.frame.origin.x + zoom_button.frame.size.width, zoom_button.frame.size.height)]; + } + [self displayButtons]; +} + +- (void)viewDidMoveToWindow { + if (!self.window) { + return; + } + + if (rtl) { + [self setAutoresizingMask:NSViewMinXMargin | NSViewMinYMargin]; + [self setFrameOrigin:NSMakePoint(self.window.frame.size.width - self.frame.size.width - offset.x, self.window.frame.size.height - self.frame.size.height - offset.y)]; + } else { + [self setAutoresizingMask:NSViewMaxXMargin | NSViewMinYMargin]; + [self setFrameOrigin:NSMakePoint(offset.x, self.window.frame.size.height - self.frame.size.height - offset.y)]; + } +} + +- (BOOL)_mouseInGroup:(NSButton *)button { + return mouse_in_group; +} + +- (void)updateTrackingAreas { + if (tracking_area != nil) { + [self removeTrackingArea:tracking_area]; + } + + NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingInVisibleRect; + tracking_area = [[NSTrackingArea alloc] initWithRect:NSZeroRect options:options owner:self userInfo:nil]; + + [self addTrackingArea:tracking_area]; +} + +- (void)mouseEntered:(NSEvent *)event { + [super mouseEntered:event]; + + mouse_in_group = true; + [self displayButtons]; +} + +- (void)mouseExited:(NSEvent *)event { + [super mouseExited:event]; + + mouse_in_group = false; + [self displayButtons]; +} + +- (void)displayButtons { + for (NSView *subview in self.subviews) { + [subview setNeedsDisplay:YES]; + } +} + +@end diff --git a/platform/macos/godot_content_view.h b/platform/macos/godot_content_view.h index 353305aec1..a6318ab903 100644 --- a/platform/macos/godot_content_view.h +++ b/platform/macos/godot_content_view.h @@ -45,6 +45,14 @@ #import <QuartzCore/CAMetalLayer.h> +@interface GodotContentLayerDelegate : NSObject <CALayerDelegate> { + DisplayServer::WindowID window_id; +} + +- (void)setWindowID:(DisplayServer::WindowID)wid; + +@end + @interface GodotContentView : RootView <NSTextInputClient> { DisplayServer::WindowID window_id; NSTrackingArea *tracking_area; @@ -53,12 +61,14 @@ bool mouse_down_control; bool ignore_momentum_scroll; bool last_pen_inverted; + id layer_delegate; } - (void)processScrollEvent:(NSEvent *)event button:(MouseButton)button factor:(double)factor; - (void)processPanEvent:(NSEvent *)event dx:(double)dx dy:(double)dy; - (void)processMouseEvent:(NSEvent *)event index:(MouseButton)index mask:(MouseButton)mask pressed:(bool)pressed; - (void)setWindowID:(DisplayServer::WindowID)wid; +- (void)updateLayerDelegate; - (void)cancelComposition; @end diff --git a/platform/macos/godot_content_view.mm b/platform/macos/godot_content_view.mm index dbed969901..cb70a5db86 100644 --- a/platform/macos/godot_content_view.mm +++ b/platform/macos/godot_content_view.mm @@ -32,11 +32,66 @@ #include "display_server_macos.h" #include "key_mapping_macos.h" +#include "main/main.h" + +@implementation GodotContentLayerDelegate + +- (id)init { + self = [super init]; + window_id = DisplayServer::INVALID_WINDOW_ID; + return self; +} + +- (void)setWindowID:(DisplayServerMacOS::WindowID)wid { + window_id = wid; +} + +- (void)displayLayer:(CALayer *)layer { + DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton(); + if (OS::get_singleton()->get_main_loop() && ds->get_is_resizing()) { + Main::force_redraw(); + if (!Main::is_iterating()) { // Avoid cyclic loop. + Main::iteration(); + } + } +} + +@end @implementation GodotContentView +- (void)setFrameSize:(NSSize)newSize { + DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton(); + if (ds && ds->has_window(window_id)) { + DisplayServerMacOS::WindowData &wd = ds->get_window(window_id); + NSRect frameRect = [wd.window_object frame]; + bool left = (wd.last_frame_rect.origin.x != frameRect.origin.x); + bool top = (wd.last_frame_rect.origin.y == frameRect.origin.y); + if (left && top) { + self.layerContentsPlacement = NSViewLayerContentsPlacementBottomRight; + } else if (left && !top) { + self.layerContentsPlacement = NSViewLayerContentsPlacementTopRight; + } else if (!left && top) { + self.layerContentsPlacement = NSViewLayerContentsPlacementBottomLeft; + } else { + self.layerContentsPlacement = NSViewLayerContentsPlacementTopLeft; + } + wd.last_frame_rect = frameRect; + } + + [super setFrameSize:newSize]; + [self.layer setNeedsDisplay]; // Force "drawRect" call. +} + +- (void)updateLayerDelegate { + self.layer.delegate = layer_delegate; + self.layer.autoresizingMask = kCALayerHeightSizable | kCALayerWidthSizable; + self.layer.needsDisplayOnBoundsChange = YES; +} + - (id)init { self = [super init]; + layer_delegate = [[GodotContentLayerDelegate alloc] init]; window_id = DisplayServer::INVALID_WINDOW_ID; tracking_area = nil; ime_input_event_in_progress = false; @@ -45,6 +100,9 @@ last_pen_inverted = false; [self updateTrackingAreas]; + self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawDuringViewResize; + self.layerContentsPlacement = NSViewLayerContentsPlacementTopLeft; + if (@available(macOS 10.13, *)) { [self registerForDraggedTypes:[NSArray arrayWithObject:NSPasteboardTypeFileURL]]; #if !defined(__aarch64__) // Do not build deprectead 10.13 code on ARM. @@ -58,6 +116,7 @@ - (void)setWindowID:(DisplayServerMacOS::WindowID)wid { window_id = wid; + [layer_delegate setWindowID:window_id]; } // MARK: Backing Layer diff --git a/platform/macos/godot_window.h b/platform/macos/godot_window.h index 9fc5599e86..d3653fda82 100644 --- a/platform/macos/godot_window.h +++ b/platform/macos/godot_window.h @@ -38,9 +38,11 @@ @interface GodotWindow : NSWindow { DisplayServer::WindowID window_id; + NSTimeInterval anim_duration; } - (void)setWindowID:(DisplayServer::WindowID)wid; +- (void)setAnimDuration:(NSTimeInterval)duration; @end diff --git a/platform/macos/godot_window.mm b/platform/macos/godot_window.mm index e205e7546d..bc51da4f72 100644 --- a/platform/macos/godot_window.mm +++ b/platform/macos/godot_window.mm @@ -37,9 +37,22 @@ - (id)init { self = [super init]; window_id = DisplayServer::INVALID_WINDOW_ID; + anim_duration = -1.0f; return self; } +- (void)setAnimDuration:(NSTimeInterval)duration { + anim_duration = duration; +} + +- (NSTimeInterval)animationResizeTime:(NSRect)newFrame { + if (anim_duration > 0) { + return anim_duration; + } else { + return [super animationResizeTime:newFrame]; + } +} + - (void)setWindowID:(DisplayServerMacOS::WindowID)wid { window_id = wid; } diff --git a/platform/macos/godot_window_delegate.h b/platform/macos/godot_window_delegate.h index 98c226aa2f..01cc13a016 100644 --- a/platform/macos/godot_window_delegate.h +++ b/platform/macos/godot_window_delegate.h @@ -38,6 +38,8 @@ @interface GodotWindowDelegate : NSObject <NSWindowDelegate> { DisplayServer::WindowID window_id; + NSRect old_frame; + NSWindowStyleMask old_style_mask; } - (void)setWindowID:(DisplayServer::WindowID)wid; diff --git a/platform/macos/godot_window_delegate.mm b/platform/macos/godot_window_delegate.mm index 2d9329ab3c..279fd2a359 100644 --- a/platform/macos/godot_window_delegate.mm +++ b/platform/macos/godot_window_delegate.mm @@ -31,6 +31,8 @@ #include "godot_window_delegate.h" #include "display_server_macos.h" +#include "godot_button_view.h" +#include "godot_window.h" @implementation GodotWindowDelegate @@ -68,6 +70,26 @@ ds->window_destroy(window_id); } +- (NSArray<NSWindow *> *)customWindowsToEnterFullScreenForWindow:(NSWindow *)window { + DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton(); + if (!ds || !ds->has_window(window_id)) { + return nullptr; + } + + old_frame = [window frame]; + old_style_mask = [window styleMask]; + + NSMutableArray<NSWindow *> *windows = [[NSMutableArray alloc] init]; + [windows addObject:window]; + + return windows; +} + +- (void)window:(NSWindow *)window startCustomAnimationToEnterFullScreenWithDuration:(NSTimeInterval)duration { + [(GodotWindow *)window setAnimDuration:duration]; + [window setFrame:[[window screen] frame] display:YES animate:YES]; +} + - (void)windowDidEnterFullScreen:(NSNotification *)notification { DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton(); if (!ds || !ds->has_window(window_id)) { @@ -76,12 +98,46 @@ DisplayServerMacOS::WindowData &wd = ds->get_window(window_id); wd.fullscreen = true; + // Reset window size limits. [wd.window_object setContentMinSize:NSMakeSize(0, 0)]; [wd.window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)]; + [(GodotWindow *)wd.window_object setAnimDuration:-1.0f]; + + // Reset custom window buttons. + if ([wd.window_object styleMask] & NSWindowStyleMaskFullSizeContentView) { + ds->window_set_custom_window_buttons(wd, false); + } // Force window resize event. [self windowDidResize:notification]; + ds->send_window_event(wd, DisplayServerMacOS::WINDOW_EVENT_TITLEBAR_CHANGE); +} + +- (NSArray<NSWindow *> *)customWindowsToExitFullScreenForWindow:(NSWindow *)window { + DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton(); + if (!ds || !ds->has_window(window_id)) { + return nullptr; + } + + DisplayServerMacOS::WindowData &wd = ds->get_window(window_id); + + // Restore custom window buttons. + if ([wd.window_object styleMask] & NSWindowStyleMaskFullSizeContentView) { + ds->window_set_custom_window_buttons(wd, true); + } + + ds->send_window_event(wd, DisplayServerMacOS::WINDOW_EVENT_TITLEBAR_CHANGE); + + NSMutableArray<NSWindow *> *windows = [[NSMutableArray alloc] init]; + [windows addObject:wd.window_object]; + return windows; +} + +- (void)window:(NSWindow *)window startCustomAnimationToExitFullScreenWithDuration:(NSTimeInterval)duration { + [(GodotWindow *)window setAnimDuration:duration]; + [window setStyleMask:old_style_mask]; + [window setFrame:old_frame display:YES animate:YES]; } - (void)windowDidExitFullScreen:(NSNotification *)notification { @@ -93,6 +149,8 @@ DisplayServerMacOS::WindowData &wd = ds->get_window(window_id); wd.fullscreen = false; + [(GodotWindow *)wd.window_object setAnimDuration:-1.0f]; + // Set window size limits. const float scale = ds->screen_get_max_scale(); if (wd.min_size != Size2i()) { @@ -151,7 +209,9 @@ - (void)windowWillStartLiveResize:(NSNotification *)notification { DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton(); - if (ds) { + if (ds && ds->has_window(window_id)) { + DisplayServerMacOS::WindowData &wd = ds->get_window(window_id); + wd.last_frame_rect = [wd.window_object frame]; ds->set_is_resizing(true); } } @@ -217,6 +277,10 @@ DisplayServerMacOS::WindowData &wd = ds->get_window(window_id); + if (wd.window_button_view) { + [(GodotButtonView *)wd.window_button_view displayButtons]; + } + if (ds->mouse_get_mode() == DisplayServer::MOUSE_MODE_CAPTURED) { const NSRect content_rect = [wd.window_view frame]; NSRect point_in_window_rect = NSMakeRect(content_rect.size.width / 2, content_rect.size.height / 2, 0, 0); @@ -239,6 +303,10 @@ DisplayServerMacOS::WindowData &wd = ds->get_window(window_id); + if (wd.window_button_view) { + [(GodotButtonView *)wd.window_button_view displayButtons]; + } + ds->release_pressed_events(); ds->send_window_event(wd, DisplayServerMacOS::WINDOW_EVENT_FOCUS_OUT); } diff --git a/platform/macos/os_macos.h b/platform/macos/os_macos.h index 61db99689c..46e7c17ebe 100644 --- a/platform/macos/os_macos.h +++ b/platform/macos/os_macos.h @@ -75,6 +75,8 @@ public: virtual List<String> get_cmdline_platform_args() const override; virtual String get_name() const override; + virtual String get_distribution_name() const override; + virtual String get_version() const override; virtual void alert(const String &p_alert, const String &p_title = "ALERT!") override; diff --git a/platform/macos/os_macos.mm b/platform/macos/os_macos.mm index 35c4e4b03d..ae8534f6ab 100644 --- a/platform/macos/os_macos.mm +++ b/platform/macos/os_macos.mm @@ -56,10 +56,11 @@ _FORCE_INLINE_ String OS_MacOS::get_framework_executable(const String &p_path) { } void OS_MacOS::pre_wait_observer_cb(CFRunLoopObserverRef p_observer, CFRunLoopActivity p_activiy, void *p_context) { - // Prevent main loop from sleeping and redraw window during resize / modal popups. + // Prevent main loop from sleeping and redraw window during modal popup display. + // Do not redraw when rendering is done from the separate thread, it will conflict with the OpenGL context updates. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton(); - if (get_singleton()->get_main_loop() && ds && (get_singleton()->get_render_thread_mode() != RENDER_SEPARATE_THREAD || !ds->get_is_resizing())) { + if (get_singleton()->get_main_loop() && ds && (get_singleton()->get_render_thread_mode() != RENDER_SEPARATE_THREAD) && !ds->get_is_resizing()) { Main::force_redraw(); if (!Main::is_iterating()) { // Avoid cyclic loop. Main::iteration(); @@ -133,6 +134,15 @@ String OS_MacOS::get_name() const { return "macOS"; } +String OS_MacOS::get_distribution_name() const { + return get_name(); +} + +String OS_MacOS::get_version() const { + NSOperatingSystemVersion ver = [NSProcessInfo processInfo].operatingSystemVersion; + return vformat("%d.%d.%d", (int64_t)ver.majorVersion, (int64_t)ver.minorVersion, (int64_t)ver.patchVersion); +} + void OS_MacOS::alert(const String &p_alert, const String &p_title) { NSAlert *window = [[NSAlert alloc] init]; NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()]; diff --git a/platform/uwp/os_uwp.cpp b/platform/uwp/os_uwp.cpp index 494f5ec4b9..8050d299f0 100644 --- a/platform/uwp/os_uwp.cpp +++ b/platform/uwp/os_uwp.cpp @@ -444,24 +444,17 @@ String OS_UWP::get_name() const { return "UWP"; } -OS::Date OS_UWP::get_date(bool p_utc) const { - SYSTEMTIME systemtime; - if (p_utc) { - GetSystemTime(&systemtime); - } else { - GetLocalTime(&systemtime); - } +String OS_UWP::get_distribution_name() const { + return get_name(); +} - Date date; - date.day = systemtime.wDay; - date.month = Month(systemtime.wMonth); - date.weekday = Weekday(systemtime.wDayOfWeek); - date.year = systemtime.wYear; - date.dst = false; - return date; +String OS_UWP::get_version() const { + winrt::hstring df_version = VersionInfo().DeviceFamilyVersion(); + static String version = String(winrt::to_string(df_version).c_str()); + return version; } -OS::Time OS_UWP::get_time(bool p_utc) const { +OS::DateTime OS_UWP::get_datetime(bool p_utc) const { SYSTEMTIME systemtime; if (p_utc) { GetSystemTime(&systemtime); @@ -469,11 +462,23 @@ OS::Time OS_UWP::get_time(bool p_utc) const { GetLocalTime(&systemtime); } - Time time; - time.hour = systemtime.wHour; - time.min = systemtime.wMinute; - time.sec = systemtime.wSecond; - return time; + //Get DST information from Windows, but only if p_utc is false. + TIME_ZONE_INFORMATION info; + bool daylight = false; + if (!p_utc && GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT) { + daylight = true; + } + + DateTime dt; + dt.year = systemtime.wYear; + dt.month = Month(systemtime.wMonth); + dt.day = systemtime.wDay; + dt.weekday = Weekday(systemtime.wDayOfWeek); + dt.hour = systemtime.wHour; + dt.minute = systemtime.wMinute; + dt.second = systemtime.wSecond; + dt.dst = daylight; + return dt; } OS::TimeZoneInfo OS_UWP::get_time_zone_info() const { diff --git a/platform/uwp/os_uwp.h b/platform/uwp/os_uwp.h index 5a58486ee7..0c1c4a793a 100644 --- a/platform/uwp/os_uwp.h +++ b/platform/uwp/os_uwp.h @@ -183,9 +183,10 @@ public: virtual MainLoop *get_main_loop() const; virtual String get_name() const; + virtual String get_distribution_name() const; + virtual String get_version() const; - virtual Date get_date(bool p_utc) const; - virtual Time get_time(bool p_utc) const; + virtual DateTime get_datetime(bool p_utc) const; virtual TimeZoneInfo get_time_zone_info() const; virtual uint64_t get_unix_time() const; diff --git a/platform/web/.eslintrc.engine.js b/platform/web/.eslintrc.engine.js index 78df6d41d9..a76bd46b9e 100644 --- a/platform/web/.eslintrc.engine.js +++ b/platform/web/.eslintrc.engine.js @@ -5,6 +5,7 @@ module.exports = { "globals": { "InternalConfig": true, "Godot": true, + "Features": true, "Preloader": true, }, }; diff --git a/platform/web/SCsub b/platform/web/SCsub index e8d0181ede..013b734be2 100644 --- a/platform/web/SCsub +++ b/platform/web/SCsub @@ -66,6 +66,7 @@ sys_env.Depends(build[0], sys_env["JS_PRE"]) sys_env.Depends(build[0], sys_env["JS_EXTERNS"]) engine = [ + "js/engine/features.js", "js/engine/preloader.js", "js/engine/config.js", "js/engine/engine.js", diff --git a/platform/web/detect.py b/platform/web/detect.py index 08f964db92..9cce73efc4 100644 --- a/platform/web/detect.py +++ b/platform/web/detect.py @@ -109,6 +109,10 @@ def configure(env): env["ENV"] = os.environ # LTO + + if env["lto"] == "auto": # Full LTO for production. + env["lto"] = "full" + if env["lto"] != "none": if env["lto"] == "thin": env.Append(CCFLAGS=["-flto=thin"]) diff --git a/platform/web/display_server_web.cpp b/platform/web/display_server_web.cpp index 38ac6b23f4..f6a61b18e4 100644 --- a/platform/web/display_server_web.cpp +++ b/platform/web/display_server_web.cpp @@ -997,7 +997,7 @@ void DisplayServerWeb::window_set_mode(WindowMode p_mode, WindowID p_window) { } break; case WINDOW_MODE_MAXIMIZED: case WINDOW_MODE_MINIMIZED: - WARN_PRINT("WindowMode MAXIMIZED and MINIMIZED are not supported in Web platform."); + // WindowMode MAXIMIZED and MINIMIZED are not supported in Web platform. break; default: break; diff --git a/platform/web/export/export.cpp b/platform/web/export/export.cpp index 7193bc6ac4..4b4e8b2705 100644 --- a/platform/web/export/export.cpp +++ b/platform/web/export/export.cpp @@ -34,6 +34,7 @@ #include "export_plugin.h" void register_web_exporter() { +#ifndef ANDROID_ENABLED EDITOR_DEF("export/web/http_host", "localhost"); EDITOR_DEF("export/web/http_port", 8060); EDITOR_DEF("export/web/use_tls", false); @@ -42,6 +43,7 @@ void register_web_exporter() { EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "export/web/http_port", PROPERTY_HINT_RANGE, "1,65535,1")); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/web/tls_key", PROPERTY_HINT_GLOBAL_FILE, "*.key")); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/web/tls_certificate", PROPERTY_HINT_GLOBAL_FILE, "*.crt,*.pem")); +#endif Ref<EditorExportPlatformWeb> platform; platform.instantiate(); diff --git a/platform/web/export/export_plugin.cpp b/platform/web/export/export_plugin.cpp index 306453c1eb..1c327fe4b2 100644 --- a/platform/web/export/export_plugin.cpp +++ b/platform/web/export/export_plugin.cpp @@ -307,13 +307,7 @@ void EditorExportPlatformWeb::get_preset_features(const Ref<EditorExportPreset> } if (p_preset->get("vram_texture_compression/for_mobile")) { - String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name"); - if (driver == "opengl3") { - r_features->push_back("etc"); - } else if (driver == "vulkan") { - // FIXME: Review if this is correct. - r_features->push_back("etc2"); - } + r_features->push_back("etc2"); } r_features->push_back("wasm32"); } diff --git a/platform/web/js/engine/engine.js b/platform/web/js/engine/engine.js index 6f0d51b2be..9227aa1f05 100644 --- a/platform/web/js/engine/engine.js +++ b/platform/web/js/engine/engine.js @@ -61,20 +61,6 @@ const Engine = (function () { }; /** - * Check whether WebGL is available. Optionally, specify a particular version of WebGL to check for. - * - * @param {number=} [majorVersion=1] The major WebGL version to check for. - * @returns {boolean} If the given major version of WebGL is available. - * @function Engine.isWebGLAvailable - */ - Engine.isWebGLAvailable = function (majorVersion = 1) { - try { - return !!document.createElement('canvas').getContext(['webgl', 'webgl2'][majorVersion - 1]); - } catch (e) { /* Not available */ } - return false; - }; - - /** * Safe Engine constructor, creates a new prototype for every new instance to avoid prototype pollution. * @ignore * @constructor @@ -265,14 +251,21 @@ const Engine = (function () { // Also expose static methods as instance methods Engine.prototype['load'] = Engine.load; Engine.prototype['unload'] = Engine.unload; - Engine.prototype['isWebGLAvailable'] = Engine.isWebGLAvailable; return new Engine(initConfig); } // Closure compiler exported static methods. SafeEngine['load'] = Engine.load; SafeEngine['unload'] = Engine.unload; - SafeEngine['isWebGLAvailable'] = Engine.isWebGLAvailable; + + // Feature-detection utilities. + SafeEngine['isWebGLAvailable'] = Features.isWebGLAvailable; + SafeEngine['isFetchAvailable'] = Features.isFetchAvailable; + SafeEngine['isSecureContext'] = Features.isSecureContext; + SafeEngine['isCrossOriginIsolated'] = Features.isCrossOriginIsolated; + SafeEngine['isSharedArrayBufferAvailable'] = Features.isSharedArrayBufferAvailable; + SafeEngine['isAudioWorkletAvailable'] = Features.isAudioWorkletAvailable; + SafeEngine['getMissingFeatures'] = Features.getMissingFeatures; return SafeEngine; }()); diff --git a/platform/web/js/engine/features.js b/platform/web/js/engine/features.js new file mode 100644 index 0000000000..f91a4eff81 --- /dev/null +++ b/platform/web/js/engine/features.js @@ -0,0 +1,96 @@ +const Features = { // eslint-disable-line no-unused-vars + /** + * Check whether WebGL is available. Optionally, specify a particular version of WebGL to check for. + * + * @param {number=} [majorVersion=1] The major WebGL version to check for. + * @returns {boolean} If the given major version of WebGL is available. + * @function Engine.isWebGLAvailable + */ + isWebGLAvailable: function (majorVersion = 1) { + try { + return !!document.createElement('canvas').getContext(['webgl', 'webgl2'][majorVersion - 1]); + } catch (e) { /* Not available */ } + return false; + }, + + /** + * Check whether the Fetch API available and supports streaming responses. + * + * @returns {boolean} If the Fetch API is available and supports streaming responses. + * @function Engine.isFetchAvailable + */ + isFetchAvailable: function () { + return 'fetch' in window && 'Response' in window && 'body' in window.Response.prototype; + }, + + /** + * Check whether the engine is running in a Secure Context. + * + * @returns {boolean} If the engine is running in a Secure Context. + * @function Engine.isSecureContext + */ + isSecureContext: function () { + return window['isSecureContext'] === true; + }, + + /** + * Check whether the engine is cross origin isolated. + * This value is dependent on Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers sent by the server. + * + * @returns {boolean} If the engine is running in a Secure Context. + * @function Engine.isSecureContext + */ + isCrossOriginIsolated: function () { + return window['crossOriginIsolated'] === true; + }, + + /** + * Check whether SharedBufferArray is available. + * + * Most browsers require the page to be running in a secure context, and the + * the server to provide specific CORS headers for SharedArrayBuffer to be available. + * + * @returns {boolean} If SharedArrayBuffer is available. + * @function Engine.isSharedArrayBufferAvailable + */ + isSharedArrayBufferAvailable: function () { + return 'SharedArrayBuffer' in window; + }, + + /** + * Check whether the AudioContext supports AudioWorkletNodes. + * + * @returns {boolean} If AudioWorkletNode is available. + * @function Engine.isAudioWorkletAvailable + */ + isAudioWorkletAvailable: function () { + return 'AudioContext' in window && 'audioWorklet' in AudioContext.prototype; + }, + + /** + * Return an array of missing required features (as string). + * + * @returns {Array<string>} A list of human-readable missing features. + * @function Engine.getMissingFeatures + */ + getMissingFeatures: function () { + const missing = []; + if (!Features.isWebGLAvailable(2)) { + missing.push('WebGL2'); + } + if (!Features.isFetchAvailable()) { + missing.push('Fetch'); + } + if (!Features.isSecureContext()) { + missing.push('Secure Context'); + } + if (!Features.isCrossOriginIsolated()) { + missing.push('Cross Origin Isolation'); + } + if (!Features.isSharedArrayBufferAvailable()) { + missing.push('SharedArrayBuffer'); + } + // Audio is normally optional since we have a dummy fallback. + return missing; + }, +}; diff --git a/platform/web/package.json b/platform/web/package.json index a57205415a..0a8d9e4334 100644 --- a/platform/web/package.json +++ b/platform/web/package.json @@ -4,7 +4,7 @@ "version": "1.0.0", "description": "Development and linting setup for Godot's Web platform code", "scripts": { - "docs": "jsdoc --template js/jsdoc2rst/ js/engine/engine.js js/engine/config.js --destination ''", + "docs": "jsdoc --template js/jsdoc2rst/ js/engine/engine.js js/engine/config.js js/engine/features.js --destination ''", "lint": "npm run lint:engine && npm run lint:libs && npm run lint:modules && npm run lint:tools", "lint:engine": "eslint \"js/engine/*.js\" --no-eslintrc -c .eslintrc.engine.js", "lint:libs": "eslint \"js/libs/*.js\" --no-eslintrc -c .eslintrc.libs.js", diff --git a/platform/windows/detect.py b/platform/windows/detect.py index e6e1874fc0..095d688213 100644 --- a/platform/windows/detect.py +++ b/platform/windows/detect.py @@ -350,7 +350,6 @@ def configure_msvc(env, vcvars_msvc_config): elif env["target"] == "debug": env.AppendUnique(CCFLAGS=["/Zi", "/FS", "/Od", "/EHsc"]) - # Allow big objects. Only needed for debug, see MinGW branch for rationale. env.Append(LINKFLAGS=["/DEBUG"]) if env["debug_symbols"]: @@ -448,6 +447,9 @@ def configure_msvc(env, vcvars_msvc_config): ## LTO + if env["lto"] == "auto": # No LTO by default for MSVC, doesn't help. + env["lto"] = "none" + if env["lto"] != "none": if env["lto"] == "thin": print("ThinLTO is only compatible with LLVM, use `use_llvm=yes` or `lto=full`.") @@ -564,6 +566,11 @@ def configure_mingw(env): if try_cmd("gcc-ranlib --version", env["mingw_prefix"], env["arch"]): env["RANLIB"] = mingw_bin_prefix + "gcc-ranlib" + ## LTO + + if env["lto"] == "auto": # Full LTO for production with MinGW. + env["lto"] = "full" + if env["lto"] != "none": if env["lto"] == "thin": if not env["use_llvm"]: diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp index b4949de3f7..b9e6f7b843 100644 --- a/platform/windows/display_server_windows.cpp +++ b/platform/windows/display_server_windows.cpp @@ -104,7 +104,10 @@ void DisplayServerWindows::_set_mouse_mode_impl(MouseMode p_mode) { if (windows.has(MAIN_WINDOW_ID) && (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_CONFINED || p_mode == MOUSE_MODE_CONFINED_HIDDEN)) { // Mouse is grabbed (captured or confined). - WindowID window_id = windows.has(last_focused_window) ? last_focused_window : MAIN_WINDOW_ID; + WindowID window_id = _get_focused_window_or_popup(); + if (!windows.has(window_id)) { + window_id = MAIN_WINDOW_ID; + } WindowData &wd = windows[window_id]; @@ -119,11 +122,15 @@ void DisplayServerWindows::_set_mouse_mode_impl(MouseMode p_mode) { ClientToScreen(wd.hWnd, &pos); SetCursorPos(pos.x, pos.y); SetCapture(wd.hWnd); + + _register_raw_input_devices(window_id); } } else { // Mouse is free to move around (not captured or confined). ReleaseCapture(); ClipCursor(nullptr); + + _register_raw_input_devices(INVALID_WINDOW_ID); } if (p_mode == MOUSE_MODE_HIDDEN || p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_CONFINED_HIDDEN) { @@ -139,6 +146,37 @@ void DisplayServerWindows::_set_mouse_mode_impl(MouseMode p_mode) { } } +DisplayServer::WindowID DisplayServerWindows::_get_focused_window_or_popup() const { + const List<WindowID>::Element *E = popup_list.back(); + if (E) { + return E->get(); + } + + return last_focused_window; +} + +void DisplayServerWindows::_register_raw_input_devices(WindowID p_target_window) { + use_raw_input = true; + + RAWINPUTDEVICE rid[1] = {}; + rid[0].usUsagePage = 0x01; + rid[0].usUsage = 0x02; + rid[0].dwFlags = 0; + + if (p_target_window != INVALID_WINDOW_ID && windows.has(p_target_window)) { + // Follow the defined window + rid[0].hwndTarget = windows[p_target_window].hWnd; + } else { + // Follow the keyboard focus + rid[0].hwndTarget = 0; + } + + if (RegisterRawInputDevices(rid, 1, sizeof(rid[0])) == FALSE) { + // Registration failed. + use_raw_input = false; + } +} + bool DisplayServerWindows::tts_is_speaking() const { ERR_FAIL_COND_V(!tts, false); return tts->is_speaking(); @@ -194,7 +232,9 @@ DisplayServer::MouseMode DisplayServerWindows::mouse_get_mode() const { void DisplayServerWindows::warp_mouse(const Point2i &p_position) { _THREAD_SAFE_METHOD_ - if (!windows.has(last_focused_window)) { + WindowID window_id = _get_focused_window_or_popup(); + + if (!windows.has(window_id)) { return; // No focused window? } @@ -205,7 +245,7 @@ void DisplayServerWindows::warp_mouse(const Point2i &p_position) { POINT p; p.x = p_position.x; p.y = p_position.y; - ClientToScreen(windows[last_focused_window].hWnd, &p); + ClientToScreen(windows[window_id].hWnd, &p); SetCursorPos(p.x, p.y); } @@ -645,7 +685,13 @@ void DisplayServerWindows::show_window(WindowID p_id) { _update_window_style(p_id); } - if (wd.no_focus || wd.is_popup) { + if (wd.maximized) { + ShowWindow(wd.hWnd, SW_SHOWMAXIMIZED); + SetForegroundWindow(wd.hWnd); // Slightly higher priority. + SetFocus(wd.hWnd); // Set keyboard focus. + } else if (wd.minimized) { + ShowWindow(wd.hWnd, SW_SHOWMINIMIZED); + } else if (wd.no_focus || wd.is_popup) { // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow ShowWindow(wd.hWnd, SW_SHOWNA); } else { @@ -886,7 +932,7 @@ void DisplayServerWindows::window_set_position(const Point2i &p_position, Window ERR_FAIL_COND(!windows.has(p_window)); WindowData &wd = windows[p_window]; - if (wd.fullscreen) { + if (wd.fullscreen || wd.maximized) { return; } @@ -1019,6 +1065,10 @@ void DisplayServerWindows::window_set_size(const Size2i p_size, WindowID p_windo ERR_FAIL_COND(!windows.has(p_window)); WindowData &wd = windows[p_window]; + if (wd.fullscreen || wd.maximized) { + return; + } + int w = p_size.width; int h = p_size.height; @@ -1036,10 +1086,6 @@ void DisplayServerWindows::window_set_size(const Size2i p_size, WindowID p_windo } #endif - if (wd.fullscreen) { - return; - } - RECT rect; GetWindowRect(wd.hWnd, &rect); @@ -1496,7 +1542,7 @@ void DisplayServerWindows::cursor_set_shape(CursorShape p_shape) { IDC_HELP }; - if (cursors[p_shape] != nullptr) { + if (cursors_cache.has(p_shape)) { SetCursor(cursors[p_shape]); } else { SetCursor(LoadCursor(hInstance, win_cursors[p_shape])); @@ -1509,55 +1555,6 @@ DisplayServer::CursorShape DisplayServerWindows::cursor_get_shape() const { return cursor_shape; } -void DisplayServerWindows::GetMaskBitmaps(HBITMAP hSourceBitmap, COLORREF clrTransparent, OUT HBITMAP &hAndMaskBitmap, OUT HBITMAP &hXorMaskBitmap) { - // Get the system display DC. - HDC hDC = GetDC(nullptr); - - // Create helper DC. - HDC hMainDC = CreateCompatibleDC(hDC); - HDC hAndMaskDC = CreateCompatibleDC(hDC); - HDC hXorMaskDC = CreateCompatibleDC(hDC); - - // Get the dimensions of the source bitmap. - BITMAP bm; - GetObject(hSourceBitmap, sizeof(BITMAP), &bm); - - // Create the mask bitmaps. - hAndMaskBitmap = CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); // Color. - hXorMaskBitmap = CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); // Color. - - // Release the system display DC. - ReleaseDC(nullptr, hDC); - - // Select the bitmaps to helper DC. - HBITMAP hOldMainBitmap = (HBITMAP)SelectObject(hMainDC, hSourceBitmap); - HBITMAP hOldAndMaskBitmap = (HBITMAP)SelectObject(hAndMaskDC, hAndMaskBitmap); - HBITMAP hOldXorMaskBitmap = (HBITMAP)SelectObject(hXorMaskDC, hXorMaskBitmap); - - // Assign the monochrome AND mask bitmap pixels so that the pixels of the source bitmap - // with 'clrTransparent' will be white pixels of the monochrome bitmap. - SetBkColor(hMainDC, clrTransparent); - BitBlt(hAndMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hMainDC, 0, 0, SRCCOPY); - - // Assign the color XOR mask bitmap pixels so that the pixels of the source bitmap - // with 'clrTransparent' will be black and rest the pixels same as corresponding - // pixels of the source bitmap. - SetBkColor(hXorMaskDC, RGB(0, 0, 0)); - SetTextColor(hXorMaskDC, RGB(255, 255, 255)); - BitBlt(hXorMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hAndMaskDC, 0, 0, SRCCOPY); - BitBlt(hXorMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hMainDC, 0, 0, SRCAND); - - // Deselect bitmaps from the helper DC. - SelectObject(hMainDC, hOldMainBitmap); - SelectObject(hAndMaskDC, hOldAndMaskBitmap); - SelectObject(hXorMaskDC, hOldXorMaskBitmap); - - // Delete the helper DC. - DeleteDC(hXorMaskDC); - DeleteDC(hAndMaskDC); - DeleteDC(hMainDC); -} - void DisplayServerWindows::cursor_set_custom_image(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) { _THREAD_SAFE_METHOD_ @@ -1610,8 +1607,26 @@ void DisplayServerWindows::cursor_set_custom_image(const Ref<Resource> &p_cursor UINT image_size = texture_size.width * texture_size.height; // Create the BITMAP with alpha channel. - COLORREF *buffer = (COLORREF *)memalloc(sizeof(COLORREF) * image_size); - + COLORREF *buffer = nullptr; + + BITMAPV5HEADER bi; + ZeroMemory(&bi, sizeof(bi)); + bi.bV5Size = sizeof(bi); + bi.bV5Width = texture_size.width; + bi.bV5Height = -texture_size.height; + bi.bV5Planes = 1; + bi.bV5BitCount = 32; + bi.bV5Compression = BI_BITFIELDS; + bi.bV5RedMask = 0x00ff0000; + bi.bV5GreenMask = 0x0000ff00; + bi.bV5BlueMask = 0x000000ff; + bi.bV5AlphaMask = 0xff000000; + + HDC dc = GetDC(nullptr); + HBITMAP bitmap = CreateDIBSection(dc, reinterpret_cast<BITMAPINFO *>(&bi), DIB_RGB_COLORS, reinterpret_cast<void **>(&buffer), nullptr, 0); + HBITMAP mask = CreateBitmap(texture_size.width, texture_size.height, 1, 1, nullptr); + + bool fully_transparent = true; for (UINT index = 0; index < image_size; index++) { int row_index = floor(index / texture_size.width) + atlas_rect.position.y; int column_index = (index % int(texture_size.width)) + atlas_rect.position.x; @@ -1620,39 +1635,28 @@ void DisplayServerWindows::cursor_set_custom_image(const Ref<Resource> &p_cursor column_index = MIN(column_index, atlas_rect.size.width - 1); row_index = MIN(row_index, atlas_rect.size.height - 1); } + const Color &c = image->get_pixel(column_index, row_index); + fully_transparent = fully_transparent && (c.a == 0.f); - *(buffer + index) = image->get_pixel(column_index, row_index).to_argb32(); - } - - // Using 4 channels, so 4 * 8 bits. - HBITMAP bitmap = CreateBitmap(texture_size.width, texture_size.height, 1, 4 * 8, buffer); - COLORREF clrTransparent = -1; - - // Create the AND and XOR masks for the bitmap. - HBITMAP hAndMask = nullptr; - HBITMAP hXorMask = nullptr; - - GetMaskBitmaps(bitmap, clrTransparent, hAndMask, hXorMask); - - if (nullptr == hAndMask || nullptr == hXorMask) { - memfree(buffer); - DeleteObject(bitmap); - return; + *(buffer + index) = c.to_argb32(); } // Finally, create the icon. - ICONINFO iconinfo; - iconinfo.fIcon = FALSE; - iconinfo.xHotspot = p_hotspot.x; - iconinfo.yHotspot = p_hotspot.y; - iconinfo.hbmMask = hAndMask; - iconinfo.hbmColor = hXorMask; - if (cursors[p_shape]) { DestroyIcon(cursors[p_shape]); } - cursors[p_shape] = CreateIconIndirect(&iconinfo); + if (fully_transparent) { + cursors[p_shape] = nullptr; + } else { + ICONINFO iconinfo; + iconinfo.fIcon = FALSE; + iconinfo.xHotspot = p_hotspot.x; + iconinfo.yHotspot = p_hotspot.y; + iconinfo.hbmMask = mask; + iconinfo.hbmColor = bitmap; + cursors[p_shape] = CreateIconIndirect(&iconinfo); + } Vector<Variant> params; params.push_back(p_cursor); @@ -1665,17 +1669,15 @@ void DisplayServerWindows::cursor_set_custom_image(const Ref<Resource> &p_cursor } } - DeleteObject(hAndMask); - DeleteObject(hXorMask); - - memfree(buffer); + DeleteObject(mask); DeleteObject(bitmap); + ReleaseDC(nullptr, dc); } else { // Reset to default system cursor. if (cursors[p_shape]) { DestroyIcon(cursors[p_shape]); - cursors[p_shape] = nullptr; } + cursors[p_shape] = nullptr; CursorShape c = cursor_shape; cursor_shape = CURSOR_MAX; @@ -2419,14 +2421,14 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA } break; case WM_SETTINGCHANGE: { if (lParam && CompareStringOrdinal(reinterpret_cast<LPCWCH>(lParam), -1, L"ImmersiveColorSet", -1, true) == CSTR_EQUAL) { - if (is_dark_mode_supported()) { + if (is_dark_mode_supported() && dark_title_available) { BOOL value = is_dark_mode(); ::DwmSetWindowAttribute(windows[window_id].hWnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &value, sizeof(value)); } } } break; case WM_THEMECHANGED: { - if (is_dark_mode_supported()) { + if (is_dark_mode_supported() && dark_title_available) { BOOL value = is_dark_mode(); ::DwmSetWindowAttribute(windows[window_id].hWnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &value, sizeof(value)); } @@ -2527,7 +2529,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA old_y = coords.y; } - if (windows[window_id].window_has_focus && mm->get_relative() != Vector2()) { + if ((windows[window_id].window_has_focus || windows[window_id].is_popup) && mm->get_relative() != Vector2()) { Input::get_singleton()->parse_input_event(mm); } } @@ -3350,7 +3352,7 @@ void DisplayServerWindows::_process_key_events() { k->set_ctrl_pressed(ke.control); k->set_meta_pressed(ke.meta); k->set_pressed(true); - k->set_keycode((Key)KeyMappingWindows::get_keysym(ke.wParam)); + k->set_keycode((Key)KeyMappingWindows::get_keysym(MapVirtualKey((ke.lParam >> 16) & 0xFF, MAPVK_VSC_TO_VK))); k->set_physical_keycode((Key)(KeyMappingWindows::get_scansym((ke.lParam >> 16) & 0xFF, ke.lParam & (1 << 24)))); k->set_unicode(unicode); if (k->get_unicode() && gr_mem) { @@ -3541,7 +3543,7 @@ DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode, wd.pre_fs_valid = true; } - if (is_dark_mode_supported()) { + if (is_dark_mode_supported() && dark_title_available) { BOOL value = is_dark_mode(); ::DwmSetWindowAttribute(wd.hWnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &value, sizeof(value)); } @@ -3603,6 +3605,16 @@ DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode, wd.wtctx = 0; } + if (p_mode == WINDOW_MODE_MAXIMIZED) { + wd.maximized = true; + wd.minimized = false; + } + + if (p_mode == WINDOW_MODE_MINIMIZED) { + wd.maximized = false; + wd.minimized = true; + } + wd.last_pressure = 0; wd.last_pressure_update = 0; wd.last_tilt = Vector2(); @@ -3633,6 +3645,7 @@ WTPacketPtr DisplayServerWindows::wintab_WTPacket = nullptr; WTEnablePtr DisplayServerWindows::wintab_WTEnable = nullptr; // UXTheme API. +bool DisplayServerWindows::dark_title_available = false; bool DisplayServerWindows::ux_theme_available = false; IsDarkModeAllowedForAppPtr DisplayServerWindows::IsDarkModeAllowedForApp = nullptr; ShouldAppsUseDarkModePtr DisplayServerWindows::ShouldAppsUseDarkMode = nullptr; @@ -3725,7 +3738,21 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win // Enforce default keep screen on value. screen_set_keep_on(GLOBAL_GET("display/window/energy_saving/keep_screen_on")); - // Load UXTheme + // Load Windows version info. + OSVERSIONINFOW os_ver; + ZeroMemory(&os_ver, sizeof(OSVERSIONINFOW)); + os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW); + + HMODULE nt_lib = LoadLibraryW(L"ntdll.dll"); + if (nt_lib) { + RtlGetVersionPtr RtlGetVersion = (RtlGetVersionPtr)GetProcAddress(nt_lib, "RtlGetVersion"); + if (RtlGetVersion) { + RtlGetVersion(&os_ver); + } + FreeLibrary(nt_lib); + } + + // Load UXTheme. HMODULE ux_theme_lib = LoadLibraryW(L"uxtheme.dll"); if (ux_theme_lib) { IsDarkModeAllowedForApp = (IsDarkModeAllowedForAppPtr)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(136)); @@ -3735,6 +3762,9 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win GetImmersiveUserColorSetPreference = (GetImmersiveUserColorSetPreferencePtr)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(98)); ux_theme_available = IsDarkModeAllowedForApp && ShouldAppsUseDarkMode && GetImmersiveColorFromColorSetEx && GetImmersiveColorTypeFromName && GetImmersiveUserColorSetPreference; + if (os_ver.dwBuildNumber >= 22000) { + dark_title_available = true; + } } // Note: Wacom WinTab driver API for pen input, for devices incompatible with Windows Ink. @@ -3799,19 +3829,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win return; } - use_raw_input = true; - - RAWINPUTDEVICE Rid[1]; - - Rid[0].usUsagePage = 0x01; - Rid[0].usUsage = 0x02; - Rid[0].dwFlags = 0; - Rid[0].hwndTarget = 0; - - if (RegisterRawInputDevices(Rid, 1, sizeof(Rid[0])) == FALSE) { - // Registration failed. - use_raw_input = false; - } + _register_raw_input_devices(INVALID_WINDOW_ID); #if defined(VULKAN_ENABLED) if (rendering_driver == "vulkan") { diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h index dbc9821970..d85d6364bd 100644 --- a/platform/windows/display_server_windows.h +++ b/platform/windows/display_server_windows.h @@ -157,6 +157,7 @@ typedef bool(WINAPI *ShouldAppsUseDarkModePtr)(); typedef DWORD(WINAPI *GetImmersiveColorFromColorSetExPtr)(UINT dwImmersiveColorSet, UINT dwImmersiveColorType, bool bIgnoreHighContrast, UINT dwHighContrastCacheMode); typedef int(WINAPI *GetImmersiveColorTypeFromNamePtr)(const WCHAR *name); typedef int(WINAPI *GetImmersiveUserColorSetPreferencePtr)(bool bForceCheckRegistry, bool bSkipCheckOnFail); +typedef HRESULT(WINAPI *RtlGetVersionPtr)(OSVERSIONINFOW *lpVersionInformation); // Windows Ink API #ifndef POINTER_STRUCTURES @@ -285,6 +286,7 @@ class DisplayServerWindows : public DisplayServer { _THREAD_SAFE_CLASS_ // UXTheme API + static bool dark_title_available; static bool ux_theme_available; static IsDarkModeAllowedForAppPtr IsDarkModeAllowedForApp; static ShouldAppsUseDarkModePtr ShouldAppsUseDarkMode; @@ -309,8 +311,6 @@ class DisplayServerWindows : public DisplayServer { String tablet_driver; Vector<String> tablet_drivers; - void GetMaskBitmaps(HBITMAP hSourceBitmap, COLORREF clrTransparent, OUT HBITMAP &hAndMaskBitmap, OUT HBITMAP &hXorMaskBitmap); - enum { KEY_EVENT_BUFFER_SIZE = 512 }; @@ -466,6 +466,8 @@ class DisplayServerWindows : public DisplayServer { void _update_real_mouse_position(WindowID p_window); void _set_mouse_mode_impl(MouseMode p_mode); + WindowID _get_focused_window_or_popup() const; + void _register_raw_input_devices(WindowID p_target_window); void _process_activate_event(WindowID p_window_id, WPARAM wParam, LPARAM lParam); void _process_key_events(); diff --git a/platform/windows/export/export.cpp b/platform/windows/export/export.cpp index 20320470b8..8f91756c02 100644 --- a/platform/windows/export/export.cpp +++ b/platform/windows/export/export.cpp @@ -34,6 +34,7 @@ #include "export_plugin.h" void register_windows_exporter() { +#ifndef ANDROID_ENABLED EDITOR_DEF("export/windows/rcedit", ""); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/windows/rcedit", PROPERTY_HINT_GLOBAL_FILE, "*.exe")); #ifdef WINDOWS_ENABLED @@ -46,6 +47,7 @@ void register_windows_exporter() { EDITOR_DEF("export/windows/wine", ""); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/windows/wine", PROPERTY_HINT_GLOBAL_FILE)); #endif +#endif Ref<EditorExportPlatformWindows> platform; platform.instantiate(); diff --git a/platform/windows/gl_manager_windows.cpp b/platform/windows/gl_manager_windows.cpp index d509ff8c51..7689751f1b 100644 --- a/platform/windows/gl_manager_windows.cpp +++ b/platform/windows/gl_manager_windows.cpp @@ -289,12 +289,7 @@ void GLManager_Windows::make_current() { } void GLManager_Windows::swap_buffers() { - // on other platforms, OpenGL swaps buffers for all windows (on all displays, really?) - // Windows swaps buffers on a per-window basis - // REVISIT: this could be structurally bad, should we have "dirty" flags then? - for (KeyValue<DisplayServer::WindowID, GLWindow> &entry : _windows) { - SwapBuffers(entry.value.hDC); - } + SwapBuffers(_current_window->hDC); } Error GLManager_Windows::initialize() { diff --git a/platform/windows/godot.natvis b/platform/windows/godot.natvis index cdd1c14978..36b0919185 100644 --- a/platform/windows/godot.natvis +++ b/platform/windows/godot.natvis @@ -32,6 +32,38 @@ </Expand> </Type> + <Type Name="HashMap<*,*>"> + <Expand> + <Item Name="[size]">num_elements</Item> + <LinkedListItems> + <Size>num_elements</Size> + <HeadPointer>head_element</HeadPointer> + <NextPointer>next</NextPointer> + <ValueNode>data</ValueNode> + </LinkedListItems> + </Expand> + </Type> + + <Type Name="VMap<*,*>"> + <Expand> + <Item Condition="_cowdata._ptr" Name="[size]">*(reinterpret_cast<int*>(_cowdata._ptr) - 1)</Item> + <ArrayItems Condition="_cowdata._ptr"> + <Size>*(reinterpret_cast<int*>(_cowdata._ptr) - 1)</Size> + <ValuePointer>reinterpret_cast<VMap<$T1,$T2>::Pair*>(_cowdata._ptr)</ValuePointer> + </ArrayItems> + </Expand> + </Type> + + <Type Name="VMap<Callable,*>::Pair"> + <DisplayString Condition="dynamic_cast<CallableCustomMethodPointerBase*>(key.custom)">{dynamic_cast<CallableCustomMethodPointerBase*>(key.custom)->text}</DisplayString> + </Type> + + <!-- requires PR 64364 + <Type Name="GDScriptThreadContext"> + <DisplayString Condition="_is_main == true">main thread {_debug_thread_id}</DisplayString> + </Type> + --> + <Type Name="Variant"> <DisplayString Condition="type == Variant::NIL">nil</DisplayString> <DisplayString Condition="type == Variant::BOOL">{_data._bool}</DisplayString> @@ -55,15 +87,17 @@ <DisplayString Condition="type == Variant::OBJECT">{*(Object *)_data._mem}</DisplayString> <DisplayString Condition="type == Variant::DICTIONARY">{*(Dictionary *)_data._mem}</DisplayString> <DisplayString Condition="type == Variant::ARRAY">{*(Array *)_data._mem}</DisplayString> - <DisplayString Condition="type == Variant::PACKED_BYTE_ARRAY">{*(PackedByteArray *)_data._mem}</DisplayString> - <DisplayString Condition="type == Variant::PACKED_INT32_ARRAY">{*(PackedInt32Array *)_data._mem}</DisplayString> + <DisplayString Condition="type == Variant::PACKED_BYTE_ARRAY">{reinterpret_cast<const Variant::PackedArrayRef<unsigned char>*>(_data.packed_array)->array}</DisplayString> + <DisplayString Condition="type == Variant::PACKED_INT32_ARRAY">{reinterpret_cast<const Variant::PackedArrayRef<int>*>(_data.packed_array)->array}</DisplayString> + <!-- broken, will show incorrect data <DisplayString Condition="type == Variant::PACKED_INT64_ARRAY">{*(PackedInt64Array *)_data._mem}</DisplayString> - <DisplayString Condition="type == Variant::PACKED_FLOAT32_ARRAY">{*(PackedFloat32Array *)_data._mem}</DisplayString> - <DisplayString Condition="type == Variant::PACKED_FLOAT64_ARRAY">{*(PackedFloat64Array *)_data._mem}</DisplayString> - <DisplayString Condition="type == Variant::PACKED_STRING_ARRAY">{*(PackedStringArray *)_data._mem}</DisplayString> - <DisplayString Condition="type == Variant::PACKED_VECTOR2_ARRAY">{*(PackedVector2Array *)_data._mem}</DisplayString> - <DisplayString Condition="type == Variant::PACKED_VECTOR3_ARRAY">{*(PackedVector3Array *)_data._mem}</DisplayString> - <DisplayString Condition="type == Variant::PACKED_COLOR_ARRAY">{*(PackedColorArray *)_data._mem}</DisplayString> + --> + <DisplayString Condition="type == Variant::PACKED_FLOAT32_ARRAY">{reinterpret_cast<const Variant::PackedArrayRef<float>*>(_data.packed_array)->array}</DisplayString> + <DisplayString Condition="type == Variant::PACKED_FLOAT64_ARRAY">{reinterpret_cast<const Variant::PackedArrayRef<double>*>(_data.packed_array)->array}</DisplayString> + <DisplayString Condition="type == Variant::PACKED_STRING_ARRAY">{reinterpret_cast<const Variant::PackedArrayRef<String>*>(_data.packed_array)->array}</DisplayString> + <DisplayString Condition="type == Variant::PACKED_VECTOR2_ARRAY">{reinterpret_cast<const Variant::PackedArrayRef<Vector2>*>(_data.packed_array)->array}</DisplayString> + <DisplayString Condition="type == Variant::PACKED_VECTOR3_ARRAY">{reinterpret_cast<const Variant::PackedArrayRef<Vector3>*>(_data.packed_array)->array}</DisplayString> + <DisplayString Condition="type == Variant::PACKED_COLOR_ARRAY">{reinterpret_cast<const Variant::PackedArrayRef<Color>*>(_data.packed_array)->array}</DisplayString> <StringView Condition="type == Variant::STRING && ((String *)(_data._mem))->_cowdata._ptr">((String *)(_data._mem))->_cowdata._ptr,s32</StringView> @@ -87,7 +121,7 @@ <Item Name="[value]" Condition="type == Variant::OBJECT">*(Object *)_data._mem</Item> <Item Name="[value]" Condition="type == Variant::DICTIONARY">*(Dictionary *)_data._mem</Item> <Item Name="[value]" Condition="type == Variant::ARRAY">*(Array *)_data._mem</Item> - <Item Name="[value]" Condition="type == Variant::PACKED_BYTE_ARRAY">*(PackedByteArray *)_data._mem</Item> + <Item Name="[value]" Condition="type == Variant::PACKED_BYTE_ARRAY">reinterpret_cast<const Variant::PackedArrayRef<unsigned char>*>(_data.packed_array)->array</Item> <Item Name="[value]" Condition="type == Variant::PACKED_INT32_ARRAY">*(PackedInt32Array *)_data._mem</Item> <Item Name="[value]" Condition="type == Variant::PACKED_INT64_ARRAY">*(PackedInt64Array *)_data._mem</Item> <Item Name="[value]" Condition="type == Variant::PACKED_FLOAT32_ARRAY">*(PackedFloat32Array *)_data._mem</Item> @@ -105,6 +139,14 @@ <StringView Condition="_cowdata._ptr != 0">_cowdata._ptr,s32</StringView> </Type> + <Type Name="godot::String"> + <DisplayString>{*reinterpret_cast<void**>(opaque),s32}</DisplayString> + <Expand> + <Item Name="opaque_ptr">*reinterpret_cast<void**>(opaque)</Item> + <Item Name="string">*reinterpret_cast<void**>(opaque),s32</Item> + </Expand> + </Type> + <Type Name="StringName"> <DisplayString Condition="_data && _data->cname">{_data->cname}</DisplayString> <DisplayString Condition="_data && !_data->cname">{_data->name,s32}</DisplayString> @@ -113,6 +155,22 @@ <StringView Condition="_data && !_data->cname">_data->name,s32</StringView> </Type> + <!-- can't cast the opaque to ::StringName because Natvis does not support global namespace specifier? --> + <Type Name="godot::StringName"> + <DisplayString Condition="(*reinterpret_cast<const char***>(opaque))[1]">{(*reinterpret_cast<const char***>(opaque))[1],s8}</DisplayString> + <DisplayString Condition="!(*reinterpret_cast<const char***>(opaque))[1]">{(*reinterpret_cast<const char***>(opaque))[2],s32}</DisplayString> + <Expand> + <Item Name="opaque_ptr">*reinterpret_cast<void**>(opaque)</Item> + <Item Name="&cname">(*reinterpret_cast<const char***>(opaque))+1</Item> + <Item Name="cname">(*reinterpret_cast<const char***>(opaque))[1],s8</Item> + </Expand> + </Type> + + <Type Name="Object::SignalData"> + <DisplayString Condition="user.name._cowdata._ptr">"{user.name}" {slot_map}</DisplayString> + <DisplayString Condition="!user.name._cowdata._ptr">"{slot_map}</DisplayString> + </Type> + <Type Name="Vector2"> <DisplayString>{{{x},{y}}}</DisplayString> <Expand> @@ -149,12 +207,4 @@ <Item Name="alpha">a</Item> </Expand> </Type> - - <Type Name="Node" Inheritable="false"> - <Expand> - <Item Name="Object">(Object*)this</Item> - <Item Name="class_name">(StringName*)(((char*)this) + sizeof(Object))</Item> - <Item Name="data">(Node::Data*)(((char*)this) + sizeof(Object) + sizeof(StringName))</Item> - </Expand> - </Type> </AutoVisualizer> diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp index b7794bbbf8..1978ec5ab6 100644 --- a/platform/windows/os_windows.cpp +++ b/platform/windows/os_windows.cpp @@ -290,7 +290,25 @@ String OS_Windows::get_name() const { return "Windows"; } -OS::Date OS_Windows::get_date(bool p_utc) const { +String OS_Windows::get_distribution_name() const { + return get_name(); +} + +String OS_Windows::get_version() const { + typedef LONG NTSTATUS, *PNTSTATUS; + typedef NTSTATUS(WINAPI * RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); + RtlGetVersionPtr version_ptr = (RtlGetVersionPtr)GetProcAddress(GetModuleHandle("ntdll.dll"), "RtlGetVersion"); + if (version_ptr != nullptr) { + RTL_OSVERSIONINFOW fow = { 0 }; + fow.dwOSVersionInfoSize = sizeof(fow); + if (version_ptr(&fow) == 0x00000000) { + return vformat("%d.%d.%d", (int64_t)fow.dwMajorVersion, (int64_t)fow.dwMinorVersion, (int64_t)fow.dwBuildNumber); + } + } + return ""; +} + +OS::DateTime OS_Windows::get_datetime(bool p_utc) const { SYSTEMTIME systemtime; if (p_utc) { GetSystemTime(&systemtime); @@ -305,28 +323,16 @@ OS::Date OS_Windows::get_date(bool p_utc) const { daylight = true; } - Date date; - date.day = systemtime.wDay; - date.month = Month(systemtime.wMonth); - date.weekday = Weekday(systemtime.wDayOfWeek); - date.year = systemtime.wYear; - date.dst = daylight; - return date; -} - -OS::Time OS_Windows::get_time(bool p_utc) const { - SYSTEMTIME systemtime; - if (p_utc) { - GetSystemTime(&systemtime); - } else { - GetLocalTime(&systemtime); - } - - Time time; - time.hour = systemtime.wHour; - time.minute = systemtime.wMinute; - time.second = systemtime.wSecond; - return time; + DateTime dt; + dt.year = systemtime.wYear; + dt.month = Month(systemtime.wMonth); + dt.day = systemtime.wDay; + dt.weekday = Weekday(systemtime.wDayOfWeek); + dt.hour = systemtime.wHour; + dt.minute = systemtime.wMinute; + dt.second = systemtime.wSecond; + dt.dst = daylight; + return dt; } OS::TimeZoneInfo OS_Windows::get_time_zone_info() const { diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h index 3e054c068c..491de2266f 100644 --- a/platform/windows/os_windows.h +++ b/platform/windows/os_windows.h @@ -143,11 +143,12 @@ public: virtual MainLoop *get_main_loop() const override; virtual String get_name() const override; + virtual String get_distribution_name() const override; + virtual String get_version() const override; virtual void initialize_joypads() override {} - virtual Date get_date(bool p_utc) const override; - virtual Time get_time(bool p_utc) const override; + virtual DateTime get_datetime(bool p_utc) const override; virtual TimeZoneInfo get_time_zone_info() const override; virtual double get_unix_time() const override; |