From 1e750ec7c3174a719bad8672106b6a92821a4ff9 Mon Sep 17 00:00:00 2001 From: LiJianying Date: Tue, 1 Dec 2026 07:34:46 +0800 Subject: [PATCH 1/2] feat(linux): support both GTK 4 (default) and GTK 3 backends --- .github/workflows/build.yml | 33 +- README.md | 2 +- docs/linux-gtk.md | 58 + examples/menu_c_example/CMakeLists.txt | 5 +- examples/menu_example/CMakeLists.txt | 5 +- examples/tray_color_example/main.cpp | 21 +- examples/tray_stats_example/CMakeLists.txt | 5 +- examples/tray_view_example/CMakeLists.txt | 5 +- examples/view_example/CMakeLists.txt | 5 +- examples/window_lifecycle_example/main.cpp | 4 + src/CMakeLists.txt | 16 +- .../linux/accessibility_manager_linux.cpp | 4 +- src/platform/linux/application_linux.cpp | 10 +- src/platform/linux/clipboard_linux.cpp | 461 ++++++- src/platform/linux/display_linux.cpp | 23 +- src/platform/linux/display_manager_linux.cpp | 80 +- src/platform/linux/drag_source_linux.cpp | 186 ++- src/platform/linux/drop_target_linux.cpp | 199 ++- src/platform/linux/file_dialog_linux.cpp | 154 ++- src/platform/linux/gtk_compat_linux.h | 75 ++ src/platform/linux/gtk_x11_compat_linux.h | 17 + src/platform/linux/menu_linux.cpp | 538 +++++++- src/platform/linux/message_dialog_linux.cpp | 193 ++- src/platform/linux/shortcut_manager_linux.cpp | 5 +- src/platform/linux/tray_icon_linux.cpp | 174 ++- src/platform/linux/view_controls_linux.cpp | 56 +- src/platform/linux/view_internal_linux.h | 13 +- src/platform/linux/view_linux.cpp | 251 +++- src/platform/linux/window_close_linux.cpp | 65 +- .../linux/window_drag_session_linux.cpp | 62 +- src/platform/linux/window_linux.cpp | 1102 ++++++++++++++++- src/platform/linux/window_manager_linux.cpp | 601 ++++++++- src/platform/linux/window_shadow_linux.h | 145 ++- tests/CMakeLists.txt | 34 +- tests/gtk_test_compat.h | 35 + tests/tray_context_menu_linux_test.cpp | 12 +- tests/view_api_test.cpp | 4 +- tests/window_close_linux_test.cpp | 34 +- .../window_close_manager_first_linux_test.cpp | 10 +- tests/window_content_protection_test.cpp | 4 +- ...dow_corner_preference_unsupported_test.cpp | 4 +- tests/window_manager_hooks_linux_test.cpp | 26 +- tests/window_occlusion_test.cpp | 6 +- tests/window_property_changed_test.cpp | 10 +- 44 files changed, 4594 insertions(+), 158 deletions(-) create mode 100644 docs/linux-gtk.md create mode 100644 src/platform/linux/gtk_compat_linux.h create mode 100644 src/platform/linux/gtk_x11_compat_linux.h create mode 100644 tests/gtk_test_compat.h diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f5cd6678..79703e7f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -96,10 +96,22 @@ jobs: cd build-ios-${{ matrix.target }} cmake --build . --config Release - # Linux build + # Linux builds (GTK 4 default and GTK 3) build-linux: + strategy: + matrix: + include: + - backend: GTK4 + gtk_pkg: libgtk-4-dev + forbidden_lib: libgtk-3 + cmake_args: "" + - backend: GTK3 + gtk_pkg: libgtk-3-dev + forbidden_lib: libgtk-4 + cmake_args: "-DNATIVEAPI_LINUX_BACKEND=GTK3" + runs-on: ubuntu-latest - name: Build Linux + name: Build Linux (${{ matrix.backend }}) steps: - uses: actions/checkout@v4 @@ -109,21 +121,32 @@ jobs: run: | cmake --version sudo apt-get update - sudo apt-get install -y ninja-build libgtk-3-dev libx11-dev libxi-dev + sudo apt-get install -y ninja-build ${{ matrix.gtk_pkg }} libx11-dev libxi-dev xvfb - name: Configure CMake shell: bash run: | mkdir build cd build - cmake .. -DCMAKE_BUILD_TYPE=Release + cmake .. -G Ninja -DCMAKE_BUILD_TYPE=Release ${{ matrix.cmake_args }} - - name: Build Examples + - name: Build Examples and Tests shell: bash run: | cd build cmake --build . --config Release + - name: Verify GTK Linkage + shell: bash + run: | + ldd build/examples/window_example/window_example | grep -E "gtk|gdk" + ! ldd build/examples/window_example/window_example | grep -q "${{ matrix.forbidden_lib }}" + + - name: Run Tests + shell: bash + run: | + xvfb-run -a ctest --test-dir build --output-on-failure + # macOS build build-macos: runs-on: macos-latest diff --git a/README.md b/README.md index ac6871fd..3c2b7bf3 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Language bindings: [Flutter](https://github.com/libnativeapi/nativeapi-flutter) ## Installation -Requires CMake 3.10+ and a C++17 compiler. On Linux, install the GTK 3 headers (`sudo apt install libgtk-3-dev`). +Requires CMake 3.10+ and a C++17 compiler. On Linux, install the GTK 4 headers (`sudo apt install libgtk-4-dev`; or `libgtk-3-dev` when configuring with `-DNATIVEAPI_LINUX_BACKEND=GTK3` — see [docs/linux-gtk.md](docs/linux-gtk.md)). Add the repository to your project and link the `nativeapi` target: diff --git a/docs/linux-gtk.md b/docs/linux-gtk.md new file mode 100644 index 00000000..d33d451b --- /dev/null +++ b/docs/linux-gtk.md @@ -0,0 +1,58 @@ +# Linux GTK Backends (GTK 4 & GTK 3) + +`nativeapi-core` supports both **GTK 4** (default) and **GTK 3** on Linux. + +GTK 4 aborts at runtime if GTK 3 symbols are loaded into the same process, while +embedders such as Flutter Linux still run on GTK 3. Supporting both backends at +build time lets standalone and GTK 4 apps use GTK 4 out of the box without +breaking GTK 3 hosts. + +## CMake Configuration + +Select the Linux backend with `NATIVEAPI_LINUX_BACKEND` (case-insensitive): + +| Value | Default | `pkg-config` module | Compile definition | +| --- | --- | --- | --- | +| `GTK4` | Yes | `gtk4` | `NATIVEAPI_LINUX_GTK4` | +| `GTK3` | No | `gtk+-3.0` | `NATIVEAPI_LINUX_GTK3` | + +```bash +# Default (GTK 4) +cmake -S . -B build +cmake --build build + +# Explicit GTK 3 (e.g. for GTK 3 hosts such as Flutter Linux) +cmake -S . -B build-gtk3 -DNATIVEAPI_LINUX_BACKEND=GTK3 +cmake --build build-gtk3 +``` + +`NATIVEAPI_LINUX_GTK4` / `NATIVEAPI_LINUX_GTK3` is exported as a `PUBLIC` +compile definition on the `nativeapi` target. Public C++ (`src/*.h`) and C ABI +(`src/capi/*.h`) headers remain completely backend-agnostic. + +## Source-Selection Contract for Downstream Bindings + +All Linux platform sources live directly in `src/platform/linux/*.cpp` and +compile cleanly under **both** GTK 4 and GTK 3 — non-CMake build systems do not +need to maintain separate per-GTK file lists: + +1. Compile every `src/platform/linux/*.cpp`. +2. Link against either `gtk4` (with `-DNATIVEAPI_LINUX_GTK4`) or `gtk+-3.0` + (with `-DNATIVEAPI_LINUX_GTK3`), plus `x11`, `xi`, and `pthread`. +3. `src/platform/linux/gtk_compat_linux.h` validates that the compile definition + matches `GTK_MAJOR_VERSION` from `` and fails compilation if they + disagree. + +## Downstream Binding Defaults + +- **C++, Rust, Swift, Go, Python, JS, C#**: follow core's default (**GTK 4**). + - CMake-based bindings (Go, Python, JS, C#): pass `-DNATIVEAPI_LINUX_BACKEND=GTK3` + to build against GTK 3. + - Rust (`cnativeapi` / `nativeapi`): enable the `gtk3` Cargo feature or set + `NATIVEAPI_LINUX_BACKEND=GTK3`. + - Swift (`Package.swift`): set `NATIVEAPI_LINUX_BACKEND=GTK3` to use `CGTK3` + instead of `CGTK4`. +- **Dart / Flutter (`cnativeapi` / `nativeapi_flutter`)**: defaults to **GTK 3** + to match Flutter's Linux embedder. Opt into GTK 4 via + `hooks.user_defines.cnativeapi.linux_backend: gtk4` in `pubspec.yaml` or + `NATIVEAPI_LINUX_BACKEND=GTK4`. diff --git a/examples/menu_c_example/CMakeLists.txt b/examples/menu_c_example/CMakeLists.txt index 68e6c505..8270bc1e 100644 --- a/examples/menu_c_example/CMakeLists.txt +++ b/examples/menu_c_example/CMakeLists.txt @@ -21,10 +21,7 @@ elseif(APPLE) elseif(WIN32) target_link_libraries(menu_c_example user32 kernel32) elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - find_package(PkgConfig REQUIRED) - pkg_check_modules(GTK3 REQUIRED gtk+-3.0) - target_include_directories(menu_c_example PRIVATE ${GTK3_INCLUDE_DIRS}) - target_link_libraries(menu_c_example ${GTK3_LIBRARIES}) + # GTK, X11 and Xi are already linked publicly by nativeapi. elseif(ANDROID) target_link_libraries(menu_c_example log android) endif() diff --git a/examples/menu_example/CMakeLists.txt b/examples/menu_example/CMakeLists.txt index a65d2758..c897bfba 100644 --- a/examples/menu_example/CMakeLists.txt +++ b/examples/menu_example/CMakeLists.txt @@ -25,10 +25,7 @@ elseif(APPLE) elseif(WIN32) target_link_libraries(menu_example user32 kernel32) elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - find_package(PkgConfig REQUIRED) - pkg_check_modules(GTK3 REQUIRED gtk+-3.0) - target_include_directories(menu_example PRIVATE ${GTK3_INCLUDE_DIRS}) - target_link_libraries(menu_example ${GTK3_LIBRARIES}) + # GTK, X11 and Xi are already linked publicly by nativeapi. elseif(ANDROID) target_link_libraries(menu_example log android) endif() diff --git a/examples/tray_color_example/main.cpp b/examples/tray_color_example/main.cpp index dfd54b5a..b04b274e 100644 --- a/examples/tray_color_example/main.cpp +++ b/examples/tray_color_example/main.cpp @@ -42,11 +42,18 @@ class SystemColourSwitch { g_object_ref_sink(widget_); view = std::make_shared(widget_); g_object_unref(widget_); // The View wrapper retains it from here. - gtk_widget_show(widget_); + gtk_widget_set_visible(widget_, TRUE); +#if GTK_MAJOR_VERSION >= 4 + signal_ = g_signal_connect(widget_, "toggled", G_CALLBACK(+[](GtkCheckButton*, gpointer data) { + static_cast(data)->Changed(); + }), + this); +#else signal_ = g_signal_connect(widget_, "toggled", G_CALLBACK(+[](GtkToggleButton*, gpointer data) { static_cast(data)->Changed(); }), this); +#endif #endif view->SetPreferredSize(nativeapi::Size{0, 32}); SetChecked(true); @@ -67,7 +74,11 @@ class SystemColourSwitch { return SendMessageW(static_cast(button_->GetNativeObject()), BM_GETCHECK, 0, 0) == BST_CHECKED; #elif defined(__linux__) +#if GTK_MAJOR_VERSION >= 4 + return gtk_check_button_get_active(GTK_CHECK_BUTTON(widget_)); +#else return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget_)); +#endif #endif } @@ -80,7 +91,11 @@ class SystemColourSwitch { SendMessageW(static_cast(button_->GetNativeObject()), BM_SETCHECK, value ? BST_CHECKED : BST_UNCHECKED, 0); #elif defined(__linux__) +#if GTK_MAJOR_VERSION >= 4 + gtk_check_button_set_active(GTK_CHECK_BUTTON(widget_), value); +#else gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget_), value); +#endif #endif suppress_ = false; } @@ -92,7 +107,11 @@ class SystemColourSwitch { #elif defined(_WIN32) SendMessageW(static_cast(button_->GetNativeObject()), BM_CLICK, 0, 0); #elif defined(__linux__) +#if GTK_MAJOR_VERSION >= 4 + gtk_check_button_set_active(GTK_CHECK_BUTTON(widget_), !IsChecked()); +#else gtk_button_clicked(GTK_BUTTON(widget_)); +#endif #endif } diff --git a/examples/tray_stats_example/CMakeLists.txt b/examples/tray_stats_example/CMakeLists.txt index 3501a860..489fb6ad 100644 --- a/examples/tray_stats_example/CMakeLists.txt +++ b/examples/tray_stats_example/CMakeLists.txt @@ -25,10 +25,7 @@ elseif(APPLE) elseif(WIN32) target_link_libraries(tray_stats_example user32 kernel32) elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - find_package(PkgConfig REQUIRED) - pkg_check_modules(GTK3 REQUIRED gtk+-3.0) - target_include_directories(tray_stats_example PRIVATE ${GTK3_INCLUDE_DIRS}) - target_link_libraries(tray_stats_example ${GTK3_LIBRARIES}) + # GTK, X11 and Xi are already linked publicly by nativeapi. elseif(ANDROID) target_link_libraries(tray_stats_example log android) endif() diff --git a/examples/tray_view_example/CMakeLists.txt b/examples/tray_view_example/CMakeLists.txt index 5078d531..cb6976ac 100644 --- a/examples/tray_view_example/CMakeLists.txt +++ b/examples/tray_view_example/CMakeLists.txt @@ -25,10 +25,7 @@ elseif(APPLE) elseif(WIN32) target_link_libraries(tray_view_example user32 kernel32) elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - find_package(PkgConfig REQUIRED) - pkg_check_modules(GTK3 REQUIRED gtk+-3.0) - target_include_directories(tray_view_example PRIVATE ${GTK3_INCLUDE_DIRS}) - target_link_libraries(tray_view_example ${GTK3_LIBRARIES}) + # GTK, X11 and Xi are already linked publicly by nativeapi. elseif(ANDROID) target_link_libraries(tray_view_example log android) endif() diff --git a/examples/view_example/CMakeLists.txt b/examples/view_example/CMakeLists.txt index 6055f3f6..40c0d58b 100644 --- a/examples/view_example/CMakeLists.txt +++ b/examples/view_example/CMakeLists.txt @@ -25,10 +25,7 @@ elseif(APPLE) elseif(WIN32) target_link_libraries(view_example user32 kernel32) elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - find_package(PkgConfig REQUIRED) - pkg_check_modules(GTK3 REQUIRED gtk+-3.0) - target_include_directories(view_example PRIVATE ${GTK3_INCLUDE_DIRS}) - target_link_libraries(view_example ${GTK3_LIBRARIES}) + # GTK, X11 and Xi are already linked publicly by nativeapi. elseif(ANDROID) target_link_libraries(view_example log android) endif() diff --git a/examples/window_lifecycle_example/main.cpp b/examples/window_lifecycle_example/main.cpp index d1724b81..43530048 100644 --- a/examples/window_lifecycle_example/main.cpp +++ b/examples/window_lifecycle_example/main.cpp @@ -40,7 +40,11 @@ static void CloseNatively(const std::shared_ptr& window) { #elif defined(_WIN32) DestroyWindow(static_cast(native)); #elif defined(NATIVEAPI_EXAMPLE_GTK) +#if GTK_MAJOR_VERSION >= 4 + gtk_window_destroy(GTK_WINDOW(native)); +#else gtk_widget_destroy(GTK_WIDGET(native)); +#endif #else (void)native; #endif diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index e3f55ccb..96a16ed5 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -6,6 +6,8 @@ cmake_minimum_required(VERSION 3.10) project(nativeapi VERSION 0.0.1 LANGUAGES CXX) option(NATIVEAPI_ENABLE_WINUI3 "Use WinUI 3 for Windows UI components (MSVC only)" OFF) +set(NATIVEAPI_LINUX_BACKEND "GTK4" CACHE STRING "Linux GTK backend (GTK4 or GTK3)") +set_property(CACHE NATIVEAPI_LINUX_BACKEND PROPERTY STRINGS GTK4 GTK3) # Enable Objective-C++ if(APPLE) @@ -31,10 +33,21 @@ elseif(ANDROID) elseif(CMAKE_SYSTEM_NAME STREQUAL "iOS") file(GLOB PLATFORM_SOURCES "platform/ios/*.mm") elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") + string(TOUPPER "${NATIVEAPI_LINUX_BACKEND}" _NATIVEAPI_LINUX_BACKEND_UPPER) + if(_NATIVEAPI_LINUX_BACKEND_UPPER STREQUAL "GTK4") + set(NATIVEAPI_LINUX_GTK_PACKAGE "gtk4") + set(NATIVEAPI_LINUX_GTK_DEFINE "NATIVEAPI_LINUX_GTK4") + elseif(_NATIVEAPI_LINUX_BACKEND_UPPER STREQUAL "GTK3") + set(NATIVEAPI_LINUX_GTK_PACKAGE "gtk+-3.0") + set(NATIVEAPI_LINUX_GTK_DEFINE "NATIVEAPI_LINUX_GTK3") + else() + message(FATAL_ERROR + "Invalid NATIVEAPI_LINUX_BACKEND='${NATIVEAPI_LINUX_BACKEND}'. Expected GTK4 or GTK3.") + endif() file(GLOB PLATFORM_SOURCES "platform/linux/*.cpp") # Find packages for Linux find_package(PkgConfig REQUIRED) - pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + pkg_check_modules(GTK REQUIRED IMPORTED_TARGET ${NATIVEAPI_LINUX_GTK_PACKAGE}) pkg_check_modules(X11 REQUIRED IMPORTED_TARGET x11) pkg_check_modules(XI REQUIRED IMPORTED_TARGET xi) elseif(APPLE) @@ -90,6 +103,7 @@ target_include_directories(nativeapi PUBLIC ) if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + target_compile_definitions(nativeapi PUBLIC ${NATIVEAPI_LINUX_GTK_DEFINE}) target_include_directories(nativeapi PUBLIC ${GTK_INCLUDE_DIRS}) endif () diff --git a/src/platform/linux/accessibility_manager_linux.cpp b/src/platform/linux/accessibility_manager_linux.cpp index 865ebb0e..4e0638d3 100644 --- a/src/platform/linux/accessibility_manager_linux.cpp +++ b/src/platform/linux/accessibility_manager_linux.cpp @@ -5,7 +5,7 @@ // Import GTK headers for accessibility support #include -#include +#include "gtk_compat_linux.h" namespace nativeapi { @@ -18,7 +18,7 @@ void AccessibilityManager::Enable() { // Initialize GTK if not already initialized (for accessibility bridge) if (!gdk_display_get_default()) { // Try to initialize GTK silently if not already done - gtk_init_check(nullptr, nullptr); + linux_gtk::InitCheck(); } // The accessibility bridge in GTK is automatically enabled when accessibility diff --git a/src/platform/linux/application_linux.cpp b/src/platform/linux/application_linux.cpp index 17852a2c..6104ddfd 100644 --- a/src/platform/linux/application_linux.cpp +++ b/src/platform/linux/application_linux.cpp @@ -1,7 +1,7 @@ #include #include #include -#include +#include "gtk_compat_linux.h" #include #include #include @@ -24,7 +24,11 @@ class Application::Impl { bool Initialize() { // Initialize GTK +#if NATIVEAPI_GTK4 + linux_gtk::InitCheck(); +#else gtk_init(nullptr, nullptr); +#endif // Create GTK application with default ID. G_APPLICATION_DEFAULT_FLAGS is // GLib 2.74+; older distributions (and manylinux wheels) spell it _NONE. @@ -133,8 +137,10 @@ class Application::Impl { return false; } - // Set application icon +#if !NATIVEAPI_GTK4 + // Set application icon (GTK 4 uses icon themes / .desktop icons instead). gtk_window_set_default_icon(pixbuf); +#endif g_object_unref(pixbuf); return true; diff --git a/src/platform/linux/clipboard_linux.cpp b/src/platform/linux/clipboard_linux.cpp index aa893023..35fd9597 100644 --- a/src/platform/linux/clipboard_linux.cpp +++ b/src/platform/linux/clipboard_linux.cpp @@ -1,4 +1,4 @@ -#include +#include "gtk_compat_linux.h" #include #include @@ -10,6 +10,272 @@ namespace { constexpr unsigned Bit(ClipboardReadFormat format) { return 1u << static_cast(format); } + +#if NATIVEAPI_GTK4 +GdkClipboard* Board() { + GdkDisplay* display = gdk_display_get_default(); + if (!display && linux_gtk::InitCheck()) + display = gdk_display_get_default(); + return display ? gdk_display_get_clipboard(display) : nullptr; +} + +std::vector ReadAllBytes(GInputStream* stream) { + std::vector out; + if (!stream) + return out; + unsigned char chunk[4096]; + for (;;) { + GError* err = nullptr; + gssize n = g_input_stream_read(stream, chunk, sizeof(chunk), nullptr, &err); + if (err) { + g_error_free(err); + return {}; + } + if (n <= 0) + break; + out.insert(out.end(), chunk, chunk + n); + } + return out; +} + +struct ReadState : std::enable_shared_from_this { + GdkClipboard* board; + unsigned mask; + std::function callback; + ClipboardData data; + std::vector formats; + size_t next = 0; + gulong changed_signal = 0; + guint timeout = 0; + bool changed = false; + bool done = false; + + explicit ReadState(GdkClipboard* board, unsigned mask) : board(board), mask(mask) { + g_object_ref(board); + } + ~ReadState() { g_object_unref(board); } + using Ref = std::shared_ptr; + gpointer Retain() { return new Ref(shared_from_this()); } + static Ref Take(gpointer value) { + std::unique_ptr ref(static_cast(value)); + return *ref; + } + void Finish(bool ok) { + if (done) + return; + done = true; + if (changed_signal) { + g_signal_handler_disconnect(board, changed_signal); + changed_signal = 0; + } + if (timeout) { + g_source_remove(timeout); + timeout = 0; + } + ok = ok && !changed && clipboard_internal::ValidData(data); + if (callback) { + auto complete = std::move(callback); + complete(ok, ok ? std::move(data) : ClipboardData{}); + } + } + void Watch() { + changed_signal = g_signal_connect( + board, "changed", + G_CALLBACK(+[](GdkClipboard*, gpointer ptr) { + static_cast(ptr)->changed = true; + }), + this); + } + void Start() { + timeout = g_timeout_add_full( + G_PRIORITY_DEFAULT, 5000, + +[](gpointer value) -> gboolean { + auto self = *static_cast(value); + self->timeout = 0; + self->Finish(false); + return G_SOURCE_REMOVE; + }, + Retain(), +[](gpointer value) { delete static_cast(value); }); + + GdkContentFormats* avail = gdk_clipboard_get_formats(board); + if (avail) { + if (gdk_content_formats_contain_gtype(avail, G_TYPE_STRING) || + gdk_content_formats_contain_mime_type(avail, "text/plain;charset=utf-8") || + gdk_content_formats_contain_mime_type(avail, "text/plain") || + gdk_content_formats_contain_mime_type(avail, "UTF8_STRING")) { + formats.push_back(ClipboardReadFormat::Text); + } + if (gdk_content_formats_contain_mime_type(avail, "text/html") || + gdk_content_formats_contain_mime_type(avail, "text/html;charset=utf-8")) { + formats.push_back(ClipboardReadFormat::Html); + } + if (gdk_content_formats_contain_mime_type(avail, "text/rtf")) { + formats.push_back(ClipboardReadFormat::Rtf); + } + if (gdk_content_formats_contain_gtype(avail, GDK_TYPE_TEXTURE) || + gdk_content_formats_contain_mime_type(avail, "image/png")) { + formats.push_back(ClipboardReadFormat::Image); + } + if (gdk_content_formats_contain_gtype(avail, GDK_TYPE_FILE_LIST) || + gdk_content_formats_contain_mime_type(avail, "text/uri-list")) { + formats.push_back(ClipboardReadFormat::FilePaths); + } + } + Next(); + } + void Next() { + if (done) + return; + if (changed) { + Finish(false); + return; + } + while (next < formats.size() && !(mask & Bit(formats[next]))) + ++next; + if (next == formats.size()) { + Finish(true); + return; + } + const auto format = formats[next++]; + if (format == ClipboardReadFormat::Text) { + gdk_clipboard_read_text_async( + board, nullptr, + +[](GObject* source, GAsyncResult* res, gpointer ptr) { + auto self = Take(ptr); + if (self->done) + return; + GError* err = nullptr; + char* text = gdk_clipboard_read_text_finish(GDK_CLIPBOARD(source), res, &err); + g_clear_error(&err); + if (!text) { + self->Finish(false); + return; + } + self->data.text = text; + g_free(text); + self->Next(); + }, + Retain()); + } else if (format == ClipboardReadFormat::Html) { + const char* mimes[] = {"text/html", "text/html;charset=utf-8", nullptr}; + gdk_clipboard_read_async( + board, mimes, G_PRIORITY_DEFAULT, nullptr, + +[](GObject* source, GAsyncResult* res, gpointer ptr) { + auto self = Take(ptr); + if (self->done) + return; + GError* err = nullptr; + const char* out_mime = nullptr; + GInputStream* stream = + gdk_clipboard_read_finish(GDK_CLIPBOARD(source), res, &out_mime, &err); + g_clear_error(&err); + if (!stream) { + self->Finish(false); + return; + } + auto bytes = ReadAllBytes(stream); + g_object_unref(stream); + if (!bytes.empty() && bytes.back() == 0) + bytes.pop_back(); + self->data.html = std::string(reinterpret_cast(bytes.data()), bytes.size()); + self->Next(); + }, + Retain()); + } else if (format == ClipboardReadFormat::Rtf) { + const char* mimes[] = {"text/rtf", nullptr}; + gdk_clipboard_read_async( + board, mimes, G_PRIORITY_DEFAULT, nullptr, + +[](GObject* source, GAsyncResult* res, gpointer ptr) { + auto self = Take(ptr); + if (self->done) + return; + GError* err = nullptr; + const char* out_mime = nullptr; + GInputStream* stream = + gdk_clipboard_read_finish(GDK_CLIPBOARD(source), res, &out_mime, &err); + g_clear_error(&err); + if (!stream) { + self->Finish(false); + return; + } + auto bytes = ReadAllBytes(stream); + g_object_unref(stream); + if (!bytes.empty() && bytes.back() == 0) + bytes.pop_back(); + self->data.rtf = std::string(reinterpret_cast(bytes.data()), bytes.size()); + self->Next(); + }, + Retain()); + } else if (format == ClipboardReadFormat::Image) { + gdk_clipboard_read_texture_async( + board, nullptr, + +[](GObject* source, GAsyncResult* res, gpointer ptr) { + auto self = Take(ptr); + if (self->done) + return; + GError* err = nullptr; + GdkTexture* texture = gdk_clipboard_read_texture_finish(GDK_CLIPBOARD(source), res, &err); + g_clear_error(&err); + if (!texture) { + self->Finish(false); + return; + } + GBytes* png = gdk_texture_save_to_png_bytes(texture); + g_object_unref(texture); + if (!png) { + self->Finish(false); + return; + } + gsize size = 0; + const auto* raw = static_cast(g_bytes_get_data(png, &size)); + self->data.image = Image::FromBase64(clipboard_internal::Base64(raw, size)); + g_bytes_unref(png); + if (!self->data.image) { + self->Finish(false); + return; + } + self->Next(); + }, + Retain()); + } else { + const char* mimes[] = {"text/uri-list", nullptr}; + gdk_clipboard_read_async( + board, mimes, G_PRIORITY_DEFAULT, nullptr, + +[](GObject* source, GAsyncResult* res, gpointer ptr) { + auto self = Take(ptr); + if (self->done) + return; + GError* err = nullptr; + const char* out_mime = nullptr; + GInputStream* stream = + gdk_clipboard_read_finish(GDK_CLIPBOARD(source), res, &out_mime, &err); + g_clear_error(&err); + if (!stream) { + self->Finish(false); + return; + } + auto bytes = ReadAllBytes(stream); + g_object_unref(stream); + std::string raw(reinterpret_cast(bytes.data()), bytes.size()); + gchar** uris = g_uri_list_extract_uris(raw.c_str()); + if (uris) { + for (gchar** uri = uris; *uri; ++uri) { + gchar* host = nullptr; + gchar* path = g_filename_from_uri(*uri, &host, nullptr); + if (path && (!host || !*host || g_ascii_strcasecmp(host, "localhost") == 0)) + self->data.file_paths.emplace_back(path); + g_free(host); + g_free(path); + } + g_strfreev(uris); + } + self->Next(); + }, + Retain()); + } + } +}; +#else GtkClipboard* Board() { GdkDisplay* display = gdk_display_get_default(); if (!display && gtk_init_check(nullptr, nullptr)) @@ -268,10 +534,15 @@ struct PublishedData { gtk_selection_data_set(selection, gtk_selection_data_get_target(selection), 8, nullptr, 0); } }; +#endif } // namespace struct Clipboard::Impl::Platform { +#if NATIVEAPI_GTK4 + GdkClipboard* board = nullptr; +#else GtkClipboard* board = nullptr; +#endif gulong signal = 0; }; Clipboard::Impl::Impl(Clipboard* owner) : owner(owner), platform(std::make_unique()) {} @@ -283,7 +554,11 @@ bool Clipboard::IsSupported() { } bool Clipboard::IsChangeMonitoringSupported() { auto* board = Board(); +#if NATIVEAPI_GTK4 + return board != nullptr; +#else return board && gdk_display_supports_selection_notification(gtk_clipboard_get_display(board)); +#endif } void Clipboard::Impl::Read(unsigned mask, std::function callback) { auto* board = Board(); @@ -296,6 +571,172 @@ void Clipboard::Impl::Read(unsigned mask, std::functionWatch(); RunOnMainThread([state] { state->Start(); }); } + +#if NATIVEAPI_GTK4 +bool Clipboard::Impl::Write(const ClipboardData& data) { + auto* board = Board(); + if (!board) + return false; + if ((data.text && data.text->size() > G_MAXINT) || (data.html && data.html->size() > G_MAXINT) || + (data.rtf && data.rtf->size() > G_MAXINT)) + return false; + + std::vector providers; + auto add_bytes = [&](const char* mime, const void* ptr, size_t len) { + GBytes* bytes = g_bytes_new(ptr, len); + providers.push_back(gdk_content_provider_new_for_bytes(mime, bytes)); + g_bytes_unref(bytes); + }; + + if (data.text) { + providers.push_back(gdk_content_provider_new_typed(G_TYPE_STRING, data.text->c_str())); + add_bytes("text/plain;charset=utf-8", data.text->data(), data.text->size()); + add_bytes("text/plain", data.text->data(), data.text->size()); + } + if (data.html) { + add_bytes("text/html", data.html->data(), data.html->size()); + } + if (data.rtf) { + add_bytes("text/rtf", data.rtf->data(), data.rtf->size()); + } + if (data.image) { + auto png = clipboard_internal::DecodeBase64(data.image->ToBase64()); + if (png.empty() || png.size() > G_MAXINT) { + for (auto* p : providers) + g_object_unref(p); + return false; + } + add_bytes("image/png", png.data(), png.size()); + } + if (!data.file_paths.empty()) { + std::string uri_list; + std::string gnome_copied = "copy"; + for (const auto& path : data.file_paths) { + gchar* uri = g_filename_to_uri(path.c_str(), nullptr, nullptr); + if (!uri) { + for (auto* p : providers) + g_object_unref(p); + return false; + } + uri_list += uri; + uri_list += "\r\n"; + gnome_copied += "\n"; + gnome_copied += uri; + g_free(uri); + } + add_bytes("text/uri-list", uri_list.data(), uri_list.size()); + add_bytes("x-special/gnome-copied-files", gnome_copied.data(), gnome_copied.size()); + } + + if (providers.empty()) { + return gdk_clipboard_set_content(board, nullptr) != FALSE; + } + GdkContentProvider* content = + providers.size() == 1 ? providers[0] + : gdk_content_provider_new_union(providers.data(), providers.size()); + const gboolean ok = gdk_clipboard_set_content(board, content); + g_object_unref(content); + return ok != FALSE; +} + +void Clipboard::Impl::ReadCustomFormatBase64( + const std::string& format, + std::function)> callback) { + auto* board = Board(); + if (!board) { + RunOnMainThread([callback = std::move(callback)] { callback(false, std::nullopt); }); + return; + } + struct CustomRead { + std::function)> callback; + }; + auto* ctx = new CustomRead{std::move(callback)}; + const char* mimes[] = {format.c_str(), nullptr}; + gdk_clipboard_read_async( + board, mimes, G_PRIORITY_DEFAULT, nullptr, + +[](GObject* source, GAsyncResult* res, gpointer ptr) { + std::unique_ptr holder(static_cast(ptr)); + GError* err = nullptr; + const char* out_mime = nullptr; + GInputStream* stream = + gdk_clipboard_read_finish(GDK_CLIPBOARD(source), res, &out_mime, &err); + g_clear_error(&err); + if (!stream) { + holder->callback(true, std::nullopt); + return; + } + auto bytes = ReadAllBytes(stream); + g_object_unref(stream); + holder->callback(true, clipboard_internal::Base64(bytes.data(), bytes.size())); + }, + ctx); +} + +bool Clipboard::Impl::WriteCustomFormatBase64(const std::string& format, + const std::string& base64_data) { + auto* board = Board(); + if (!board) + return false; + auto bytes = clipboard_internal::DecodeBase64(base64_data); + if ((bytes.empty() && !base64_data.empty()) || bytes.size() > G_MAXINT) + return false; + GBytes* gbytes = g_bytes_new(bytes.data(), bytes.size()); + GdkContentProvider* provider = gdk_content_provider_new_for_bytes(format.c_str(), gbytes); + g_bytes_unref(gbytes); + const gboolean ok = gdk_clipboard_set_content(board, provider); + g_object_unref(provider); + return ok != FALSE; +} + +bool Clipboard::Impl::HasFormat(ClipboardReadFormat format) const { + auto* board = Board(); + if (!board) + return false; + GdkContentFormats* formats = gdk_clipboard_get_formats(board); + if (!formats) + return false; + switch (format) { + case ClipboardReadFormat::Text: + return gdk_content_formats_contain_gtype(formats, G_TYPE_STRING) || + gdk_content_formats_contain_mime_type(formats, "text/plain;charset=utf-8") || + gdk_content_formats_contain_mime_type(formats, "text/plain"); + case ClipboardReadFormat::Html: + return gdk_content_formats_contain_mime_type(formats, "text/html") || + gdk_content_formats_contain_mime_type(formats, "text/html;charset=utf-8"); + case ClipboardReadFormat::Rtf: + return gdk_content_formats_contain_mime_type(formats, "text/rtf"); + case ClipboardReadFormat::Image: + return gdk_content_formats_contain_gtype(formats, GDK_TYPE_TEXTURE) || + gdk_content_formats_contain_mime_type(formats, "image/png"); + case ClipboardReadFormat::FilePaths: + return gdk_content_formats_contain_gtype(formats, GDK_TYPE_FILE_LIST) || + gdk_content_formats_contain_mime_type(formats, "text/uri-list"); + default: + return false; + } +} + +bool Clipboard::Impl::HasCustomFormat(const std::string& format) const { + auto* board = Board(); + if (!board) + return false; + GdkContentFormats* formats = gdk_clipboard_get_formats(board); + return formats && gdk_content_formats_contain_mime_type(formats, format.c_str()) != FALSE; +} + +bool Clipboard::Impl::Start() { + if (!Clipboard::IsChangeMonitoringSupported()) + return false; + platform->board = Board(); + if (!platform->board) + return false; + g_object_ref(platform->board); + platform->signal = g_signal_connect( + platform->board, "changed", + G_CALLBACK(+[](GdkClipboard*, gpointer ptr) { static_cast(ptr)->Changed(); }), this); + return platform->signal != 0; +} +#else bool Clipboard::Impl::Write(const ClipboardData& data) { auto* board = Board(); if (!board) @@ -422,14 +863,6 @@ bool Clipboard::Impl::WriteCustomFormatBase64(const std::string& format, return true; } -int64_t Clipboard::Impl::GetChangeCount() const { - return 0; -} - -bool Clipboard::Impl::IsConcealed() const { - return false; -} - bool Clipboard::Impl::HasFormat(ClipboardReadFormat format) const { auto* board = Board(); if (!board) @@ -475,6 +908,16 @@ bool Clipboard::Impl::Start() { this); return platform->signal != 0; } +#endif + +int64_t Clipboard::Impl::GetChangeCount() const { + return 0; +} + +bool Clipboard::Impl::IsConcealed() const { + return false; +} + void Clipboard::Impl::Stop() { if (platform->board) { if (platform->signal) diff --git a/src/platform/linux/display_linux.cpp b/src/platform/linux/display_linux.cpp index 1bd75545..8f169794 100644 --- a/src/platform/linux/display_linux.cpp +++ b/src/platform/linux/display_linux.cpp @@ -1,7 +1,6 @@ #include "../../display.h" -#include -#include +#include "gtk_compat_linux.h" namespace nativeapi { @@ -74,8 +73,13 @@ Size Display::GetSize() const { Rectangle Display::GetWorkArea() const { if (!pimpl_->gdk_monitor_) return {0.0, 0.0, 0.0, 0.0}; - GdkRectangle workarea; + GdkRectangle workarea{}; +#if NATIVEAPI_GTK4 + // GTK 4 removed gdk_monitor_get_workarea(); fall back to monitor geometry. + gdk_monitor_get_geometry(pimpl_->gdk_monitor_, &workarea); +#else gdk_monitor_get_workarea(pimpl_->gdk_monitor_, &workarea); +#endif return {static_cast(workarea.x), static_cast(workarea.y), static_cast(workarea.width), static_cast(workarea.height)}; } @@ -90,6 +94,18 @@ bool Display::IsPrimary() const { if (!pimpl_->gdk_monitor_) return false; GdkDisplay* display = gdk_monitor_get_display(pimpl_->gdk_monitor_); + if (!display) + return false; +#if NATIVEAPI_GTK4 + GListModel* monitors = gdk_display_get_monitors(display); + if (!monitors || g_list_model_get_n_items(monitors) == 0) + return false; + GdkMonitor* first = GDK_MONITOR(g_list_model_get_item(monitors, 0)); + const bool primary = (first == pimpl_->gdk_monitor_); + if (first) + g_object_unref(first); + return primary; +#else GdkMonitor* primary = gdk_display_get_primary_monitor(display); if (!primary) { // Wayland has no notion of a primary monitor; match the first-monitor @@ -97,6 +113,7 @@ bool Display::IsPrimary() const { primary = gdk_display_get_monitor(display, 0); } return primary == pimpl_->gdk_monitor_; +#endif } DisplayOrientation Display::GetOrientation() const { diff --git a/src/platform/linux/display_manager_linux.cpp b/src/platform/linux/display_manager_linux.cpp index ff03f19c..03072005 100644 --- a/src/platform/linux/display_manager_linux.cpp +++ b/src/platform/linux/display_manager_linux.cpp @@ -1,13 +1,17 @@ -#include #include #include #include "../../display_manager.h" +#include "gtk_x11_compat_linux.h" namespace nativeapi { DisplayManager::DisplayManager() { +#if NATIVEAPI_GTK4 + linux_gtk::InitCheck(); +#else gtk_init(nullptr, nullptr); +#endif // Prime the instance cache so the first change notification diffs against // the displays present at startup. GetAll(); @@ -26,6 +30,25 @@ bool DisplayManager::EnumerateNativeDisplays(std::vector& nat return false; } +#if NATIVEAPI_GTK4 + GListModel* monitors = gdk_display_get_monitors(display); + if (!monitors) { + return false; + } + const guint monitor_count = g_list_model_get_n_items(monitors); + for (guint i = 0; i < monitor_count; ++i) { + GdkMonitor* monitor = GDK_MONITOR(g_list_model_get_item(monitors, i)); + if (!monitor) { + continue; + } + // GListModel holds its own reference while the monitor stays connected. + // Drop the extra ref returned by g_list_model_get_item(). + natives.push_back( + {std::to_string(reinterpret_cast(monitor)), monitor, i == 0}); + g_object_unref(monitor); + } + return true; +#else GdkMonitor* primary = gdk_display_get_primary_monitor(display); int monitor_count = gdk_display_get_n_monitors(display); for (int i = 0; i < monitor_count; ++i) { @@ -40,12 +63,64 @@ bool DisplayManager::EnumerateNativeDisplays(std::vector& nat {std::to_string(reinterpret_cast(monitor)), monitor, is_primary}); } return true; +#endif } Point DisplayManager::GetCursorPosition() { GdkDisplay* display = gdk_display_get_default(); + if (!display) { + return {0.0, 0.0}; + } +#if NATIVEAPI_GTK4 +#ifdef GDK_WINDOWING_X11 + if (GDK_IS_X11_DISPLAY(display)) { + ::Display* xdisplay = gdk_x11_display_get_xdisplay(display); + if (xdisplay) { + ::Window root = DefaultRootWindow(xdisplay); + ::Window root_ret = 0; + ::Window child_ret = 0; + int root_x = 0; + int root_y = 0; + int win_x = 0; + int win_y = 0; + unsigned int mask = 0; + if (XQueryPointer(xdisplay, root, &root_ret, &child_ret, &root_x, &root_y, &win_x, &win_y, + &mask)) { + int scale = 1; + if (GListModel* monitors = gdk_display_get_monitors(display)) { + const guint count = g_list_model_get_n_items(monitors); + for (guint i = 0; i < count; ++i) { + GdkMonitor* monitor = GDK_MONITOR(g_list_model_get_item(monitors, i)); + if (!monitor) { + continue; + } + GdkRectangle geom{}; + gdk_monitor_get_geometry(monitor, &geom); + const int s = gdk_monitor_get_scale_factor(monitor); + const int eff_s = s > 0 ? s : 1; + const int lx = root_x / eff_s; + const int ly = root_y / eff_s; + if (lx >= geom.x && lx < geom.x + geom.width && ly >= geom.y && + ly < geom.y + geom.height) { + scale = eff_s; + g_object_unref(monitor); + break; + } + g_object_unref(monitor); + } + } + return {static_cast(root_x) / scale, static_cast(root_y) / scale}; + } + } + } +#endif + return {0.0, 0.0}; +#else GdkSeat* seat = gdk_display_get_default_seat(display); - GdkDevice* pointer = gdk_seat_get_pointer(seat); + GdkDevice* pointer = seat ? gdk_seat_get_pointer(seat) : nullptr; + if (!pointer) { + return {0.0, 0.0}; + } int x, y; gdk_device_get_position(pointer, NULL, &x, &y); @@ -54,6 +129,7 @@ Point DisplayManager::GetCursorPosition() { point.x = x; point.y = y; return point; +#endif } void DisplayManager::StartEventListening() {} diff --git a/src/platform/linux/drag_source_linux.cpp b/src/platform/linux/drag_source_linux.cpp index bbe7910e..d87da23c 100644 --- a/src/platform/linux/drag_source_linux.cpp +++ b/src/platform/linux/drag_source_linux.cpp @@ -1,11 +1,9 @@ -#include -#include - #include #include #include "../../drag_source_impl.h" #include "../../image.h" +#include "gtk_x11_compat_linux.h" namespace nativeapi { @@ -14,8 +12,6 @@ bool DragSource::IsOperationSelectionSupported() { return true; } bool DragSource::IsPositionSupported() { return true; } namespace { -enum TargetInfo : guint { kUriList = 0, kText = 1 }; - GdkDragAction ToGdkAction(DragOperation operation) { switch (operation) { case DragOperation::Copy: @@ -37,6 +33,75 @@ DragOperation FromGdkAction(GdkDragAction action) { return DragOperation::None; } +#if NATIVEAPI_GTK4 +bool QueryPointer(Point& position, bool& primary_button_down) { + GdkDisplay* display = gdk_display_get_default(); + if (!display) { + return false; + } +#ifdef GDK_WINDOWING_X11 + if (GDK_IS_X11_DISPLAY(display)) { + ::Display* xdisplay = gdk_x11_display_get_xdisplay(display); + if (!xdisplay) { + return false; + } + ::Window root = DefaultRootWindow(xdisplay); + ::Window root_ret = 0; + ::Window child_ret = 0; + int root_x = 0; + int root_y = 0; + int win_x = 0; + int win_y = 0; + unsigned int mask = 0; + if (!XQueryPointer(xdisplay, root, &root_ret, &child_ret, &root_x, &root_y, &win_x, &win_y, + &mask)) { + return false; + } + position = {static_cast(root_x), static_cast(root_y)}; + primary_button_down = (mask & Button1Mask) != 0; + return true; + } +#endif + // Wayland does not expose global pointer state outside a surface event; + // allow programmatic drag attempts when called from a pointer handler. + position = {0.0, 0.0}; + primary_button_down = true; + return true; +} + +GdkContentProvider* BuildContentProvider(const std::vector& file_paths, + const std::optional& text) { + std::vector providers; + if (!file_paths.empty()) { + std::string uri_list; + for (const auto& path : file_paths) { + if (gchar* uri = g_filename_to_uri(path.c_str(), nullptr, nullptr)) { + uri_list += uri; + uri_list += "\r\n"; + g_free(uri); + } + } + if (!uri_list.empty()) { + GBytes* bytes = g_bytes_new(uri_list.data(), uri_list.size()); + providers.push_back(gdk_content_provider_new_for_bytes("text/uri-list", bytes)); + g_bytes_unref(bytes); + } + } + if (text.has_value()) { + providers.push_back(gdk_content_provider_new_typed(G_TYPE_STRING, text->c_str())); + } + if (providers.empty()) { + return nullptr; + } + if (providers.size() == 1) { + return providers[0]; + } + // gdk_content_provider_new_union takes ownership of the elements. + return gdk_content_provider_new_union(providers.data(), providers.size()); +} +#else +enum TargetInfo : guint { kUriList = 0, kText = 1 }; + GdkDevice* Pointer() { GdkDisplay* display = gdk_display_get_default(); GdkSeat* seat = display ? gdk_display_get_default_seat(display) : nullptr; @@ -57,9 +122,119 @@ bool QueryPointer(Point& position, bool& primary_button_down) { primary_button_down = (mask & GDK_BUTTON1_MASK) != 0; return true; } +#endif } // namespace +#if NATIVEAPI_GTK4 +struct DragSource::Impl::Platform { + explicit Platform(Impl* impl) : impl(impl) {} + ~Platform() { Disconnect(); } + + void Disconnect() { + if (!drag) { + return; + } + for (gulong id : handler_ids) { + g_signal_handler_disconnect(drag, id); + } + handler_ids.clear(); + g_object_unref(drag); + drag = nullptr; + } + + static void OnCancel(GdkDrag* drag, GdkDragCancelReason, gpointer user_data) { + auto* self = static_cast(user_data); + if (drag != self->drag) { + return; + } + self->Disconnect(); + Point position{0, 0}; + bool button_down = false; + QueryPointer(position, button_down); + self->impl->Finish(position, DragOperation::None); + } + + static void OnDndFinished(GdkDrag* drag, gpointer user_data) { + auto* self = static_cast(user_data); + if (drag != self->drag) { + return; + } + const DragOperation operation = FromGdkAction(gdk_drag_get_selected_action(drag)); + self->Disconnect(); + Point position{0, 0}; + bool button_down = false; + QueryPointer(position, button_down); + self->impl->Finish(position, operation); + } + + Impl* impl; + GdkDrag* drag = nullptr; + std::vector handler_ids; +}; + +bool DragSource::IsSupported() { return true; } + +DragSource::Impl::Impl(DragSource* owner) + : owner(owner), platform(std::make_unique(this)) {} + +DragSource::Impl::~Impl() = default; + +bool DragSource::Impl::Start() { + GtkWidget* widget = static_cast(window->GetNativeObject()); + if (!widget || !GTK_IS_WIDGET(widget) || !gtk_widget_get_realized(widget)) { + return false; + } + Point position{0, 0}; + bool button_down = false; + if (!QueryPointer(position, button_down) || !button_down) { + return false; + } + + GtkNative* native = gtk_widget_get_native(widget); + GdkSurface* surface = native ? gtk_native_get_surface(native) : nullptr; + GdkDisplay* display = gtk_widget_get_display(widget); + GdkSeat* seat = display ? gdk_display_get_default_seat(display) : nullptr; + GdkDevice* pointer = seat ? gdk_seat_get_pointer(seat) : nullptr; + if (!surface || !pointer) { + return false; + } + + GdkContentProvider* content = BuildContentProvider(file_paths, text); + if (!content) { + return false; + } + + auto* p = platform.get(); + p->Disconnect(); + + GdkDrag* drag = gdk_drag_begin(surface, pointer, content, ToGdkAction(operation), 0.0, 0.0); + g_object_unref(content); + if (!drag) { + return false; + } + + p->drag = drag; + p->handler_ids = { + g_signal_connect(drag, "cancel", G_CALLBACK(&Platform::OnCancel), p), + g_signal_connect(drag, "dnd-finished", G_CALLBACK(&Platform::OnDndFinished), p), + }; + + GdkPixbuf* pixbuf = image ? static_cast(image->GetNativeObject()) : nullptr; + if (pixbuf) { + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + GdkTexture* texture = gdk_texture_new_for_pixbuf(pixbuf); + G_GNUC_END_IGNORE_DEPRECATIONS + if (texture) { + gtk_drag_icon_set_from_paintable(drag, GDK_PAINTABLE(texture), + gdk_pixbuf_get_width(pixbuf) / 2, + gdk_pixbuf_get_height(pixbuf) / 2); + g_object_unref(texture); + } + } + return true; +} +#else struct DragSource::Impl::Platform { explicit Platform(Impl* impl) : impl(impl) {} ~Platform() { Disconnect(); } @@ -202,5 +377,6 @@ bool DragSource::Impl::Start() { } return true; } +#endif } // namespace nativeapi diff --git a/src/platform/linux/drop_target_linux.cpp b/src/platform/linux/drop_target_linux.cpp index 4bee8e73..8aadd5df 100644 --- a/src/platform/linux/drop_target_linux.cpp +++ b/src/platform/linux/drop_target_linux.cpp @@ -1,5 +1,4 @@ -#include -#include +#include "gtk_compat_linux.h" #include #include @@ -9,8 +8,6 @@ namespace nativeapi { namespace { -enum TargetInfo : guint { kUriList = 0, kText = 1 }; - GdkDragAction ToGdkAction(DragOperation operation) { switch (operation) { case DragOperation::Copy: @@ -27,6 +24,199 @@ GdkDragAction ToGdkAction(DragOperation operation) { } // namespace +#if NATIVEAPI_GTK4 +struct DropTarget::Impl::Platform { + explicit Platform(Impl* impl) : impl(impl) {} + + static unsigned SourceOperations(GdkDrop* drop) { + const GdkDragAction actions = gdk_drop_get_actions(drop); + unsigned result = 0; + for (DragOperation operation : + {DragOperation::Copy, DragOperation::Move, DragOperation::Link}) { + if (actions & ToGdkAction(operation)) { + result |= OperationBit(operation); + } + } + return result; + } + + static bool HasFiles(GdkDrop* drop) { + GdkContentFormats* formats = gdk_drop_get_formats(drop); + return formats && (gdk_content_formats_contain_gtype(formats, GDK_TYPE_FILE_LIST) || + gdk_content_formats_contain_mime_type(formats, "text/uri-list")); + } + + static bool HasText(GdkDrop* drop) { + GdkContentFormats* formats = gdk_drop_get_formats(drop); + return formats && (gdk_content_formats_contain_gtype(formats, G_TYPE_STRING) || + gdk_content_formats_contain_mime_type(formats, "text/plain;charset=utf-8") || + gdk_content_formats_contain_mime_type(formats, "text/plain")); + } + + static GdkDragAction OnEnter(GtkDropTargetAsync*, + GdkDrop* drop, + double x, + double y, + gpointer user_data) { + auto* self = static_cast(user_data); + self->inside = true; + const bool has_data = HasFiles(drop) || HasText(drop); + const DragOperation operation = + self->impl->Entered({x, y}, SourceOperations(drop), has_data); + return ToGdkAction(operation); + } + + static GdkDragAction OnMotion(GtkDropTargetAsync*, + GdkDrop* drop, + double x, + double y, + gpointer user_data) { + auto* self = static_cast(user_data); + const DragOperation operation = self->impl->Moved({x, y}, SourceOperations(drop)); + return ToGdkAction(operation); + } + + static void OnLeave(GtkDropTargetAsync*, GdkDrop*, gpointer user_data) { + auto* self = static_cast(user_data); + if (self->inside) { + self->inside = false; + self->impl->Exited(self->impl->last_position); + } + } + + struct DropReadCtx { + Platform* platform; + Point position; + DragOperation operation; + GType gtype; + }; + + static void OnValueRead(GObject* source, GAsyncResult* res, gpointer user_data) { + std::unique_ptr ctx(static_cast(user_data)); + GdkDrop* drop = GDK_DROP(source); + GError* err = nullptr; + const GValue* value = gdk_drop_read_value_finish(drop, res, &err); + std::vector file_paths; + std::string text; + if (value) { + if (ctx->gtype == GDK_TYPE_FILE_LIST && G_VALUE_HOLDS(value, GDK_TYPE_FILE_LIST)) { + auto* list = static_cast(g_value_get_boxed(value)); + if (list) { + GSList* files = gdk_file_list_get_files(list); + for (GSList* item = files; item; item = item->next) { + if (auto* file = G_FILE(item->data)) { + if (char* p = g_file_get_path(file)) { + file_paths.emplace_back(p); + g_free(p); + } + } + } + g_slist_free(files); + } + } else if (ctx->gtype == G_TYPE_STRING && G_VALUE_HOLDS_STRING(value)) { + if (const char* s = g_value_get_string(value)) { + text = s; + } + } + } + g_clear_error(&err); + const bool ok = !file_paths.empty() || !text.empty(); + gdk_drop_finish(drop, ok ? ToGdkAction(ctx->operation) : static_cast(0)); + if (ok) { + ctx->platform->impl->Dropped(ctx->position, std::move(file_paths), std::move(text)); + } else { + ctx->platform->impl->Exited(ctx->position); + } + } + + static gboolean OnDrop(GtkDropTargetAsync*, + GdkDrop* drop, + double x, + double y, + gpointer user_data) { + auto* self = static_cast(user_data); + self->inside = false; + const Point pos{x, y}; + const bool has_files = HasFiles(drop); + const bool has_text = HasText(drop); + if (!self->impl->accepted || (!has_files && !has_text)) { + self->impl->Exited(pos); + gdk_drop_finish(drop, static_cast(0)); + return FALSE; + } + const GType type = has_files ? GDK_TYPE_FILE_LIST : G_TYPE_STRING; + auto* ctx = new DropReadCtx{self, pos, self->impl->operation, type}; + gdk_drop_read_value_async(drop, type, G_PRIORITY_DEFAULT, nullptr, &Platform::OnValueRead, ctx); + return TRUE; + } + + Impl* impl; + GtkWidget* widget = nullptr; + GtkDropTargetAsync* controller = nullptr; + bool inside = false; +}; + +bool DropTarget::IsSupported() { return true; } + +DropTarget::Impl::Impl(DropTarget* owner, std::shared_ptr window) + : owner(owner), + window(std::move(window)), + window_id(this->window ? this->window->GetId() : 0), + platform(std::make_unique(this)) {} + +DropTarget::Impl::~Impl() = default; + +bool DropTarget::Impl::Register() { + GtkWidget* widget = static_cast(window->GetNativeObject()); + if (!widget || !GTK_IS_WIDGET(widget)) { + return false; + } + + GdkContentFormatsBuilder* builder = gdk_content_formats_builder_new(); + gdk_content_formats_builder_add_gtype(builder, GDK_TYPE_FILE_LIST); + gdk_content_formats_builder_add_gtype(builder, G_TYPE_STRING); + gdk_content_formats_builder_add_mime_type(builder, "text/uri-list"); + gdk_content_formats_builder_add_mime_type(builder, "text/plain;charset=utf-8"); + gdk_content_formats_builder_add_mime_type(builder, "text/plain"); + GdkContentFormats* formats = gdk_content_formats_builder_free_to_formats(builder); + + GtkDropTargetAsync* target = gtk_drop_target_async_new( + formats, + static_cast(GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_LINK)); + gdk_content_formats_unref(formats); + + auto* p = platform.get(); + g_signal_connect(target, "drag-enter", G_CALLBACK(&Platform::OnEnter), p); + g_signal_connect(target, "drag-motion", G_CALLBACK(&Platform::OnMotion), p); + g_signal_connect(target, "drag-leave", G_CALLBACK(&Platform::OnLeave), p); + g_signal_connect(target, "drop", G_CALLBACK(&Platform::OnDrop), p); + + g_object_ref(widget); + p->widget = widget; + p->controller = target; + gtk_widget_add_controller(widget, GTK_EVENT_CONTROLLER(target)); + return true; +} + +void DropTarget::Impl::Unregister() { + platform->inside = false; + GtkWidget* widget = platform->widget; + GtkDropTargetAsync* controller = platform->controller; + platform->widget = nullptr; + platform->controller = nullptr; + if (!widget) { + return; + } + if (controller) { + gtk_widget_remove_controller(widget, GTK_EVENT_CONTROLLER(controller)); + } + g_object_unref(widget); +} +#else +namespace { +enum TargetInfo : guint { kUriList = 0, kText = 1 }; +} // namespace + struct DropTarget::Impl::Platform { explicit Platform(Impl* impl) : impl(impl) {} @@ -214,5 +404,6 @@ void DropTarget::Impl::Unregister() { gtk_drag_dest_unset(widget); g_object_unref(widget); } +#endif } // namespace nativeapi diff --git a/src/platform/linux/file_dialog_linux.cpp b/src/platform/linux/file_dialog_linux.cpp index 3c0f8223..7739a882 100644 --- a/src/platform/linux/file_dialog_linux.cpp +++ b/src/platform/linux/file_dialog_linux.cpp @@ -1,4 +1,4 @@ -#include +#include "gtk_compat_linux.h" #include #include "../../file_dialog_impl.h" @@ -23,9 +23,16 @@ std::string CaseInsensitiveGlob(const std::string& extension) { GtkWindow* ParentToplevel(const std::shared_ptr& parent) { auto* widget = parent ? static_cast(parent->GetNativeObject()) : nullptr; if (!widget || !GTK_IS_WIDGET(widget)) return nullptr; +#if NATIVEAPI_GTK4 + GtkRoot* root = gtk_widget_get_root(widget); + return root && GTK_IS_WINDOW(root) ? GTK_WINDOW(root) : nullptr; +#else GtkWidget* toplevel = gtk_widget_get_toplevel(widget); return GTK_IS_WINDOW(toplevel) ? GTK_WINDOW(toplevel) : nullptr; +#endif } + +#if !NATIVEAPI_GTK4 struct Session { GMainLoop* loop = nullptr; gint response = GTK_RESPONSE_NONE; @@ -37,17 +44,153 @@ void OnResponse(GtkNativeDialog*, gint response, gpointer data) { session->done = true; g_main_loop_quit(session->loop); } +#endif } // namespace -// GtkFileChooserNative goes through xdg-desktop-portal when GTK picks it -// (Flatpak, GTK_USE_PORTAL=1) and exports the parent's Wayland/X11 handle for -// it; otherwise it shows an in-process GtkFileChooserDialog transient for the -// parent toplevel. bool FileDialog::IsSupported() { return true; } FileDialog::Impl::~Impl() = default; bool FileDialog::Impl::Close() { return open && cancel && cancel(); } +#if NATIVEAPI_GTK4 +bool FileDialog::Impl::Open() { + if (!gdk_display_get_default() && !linux_gtk::InitCheck()) { + error = "Cannot open a GTK display"; + result = FileDialogResult::Failed; + return false; + } + if (parent && !ParentToplevel(parent)) { + error = "Invalid picker parent"; + result = FileDialogResult::Failed; + return false; + } + + GtkWindow* owner = ParentToplevel(parent); + GtkFileDialog* dialog = gtk_file_dialog_new(); + gtk_file_dialog_set_modal(dialog, TRUE); + + const char* title = mode == FileDialogMode::OpenFiles ? "Open Files" : "Open File"; + if (mode == FileDialogMode::SaveFile) { + title = "Save File"; + } else if (mode == FileDialogMode::SelectFolder) { + title = "Select Folder"; + } + gtk_file_dialog_set_title(dialog, title); + + if (mode == FileDialogMode::SaveFile) { + std::string name = suggested_name; + // Mirror IFileDialog::SetDefaultExtension: a bare name gets the first type. + if (!extensions.empty() && extensions.front() != "*" && name.find('.') == std::string::npos) + name = (name.empty() ? "Untitled" : name) + extensions.front(); + if (!name.empty()) gtk_file_dialog_set_initial_name(dialog, name.c_str()); + } + + if (!extensions.empty() && mode != FileDialogMode::SelectFolder) { + GtkFileFilter* filter = gtk_file_filter_new(); + std::string label; + for (const auto& ext : extensions) { + gtk_file_filter_add_pattern(filter, CaseInsensitiveGlob(ext).c_str()); + label += (label.empty() ? "" : ", ") + (ext == "*" ? std::string("*") : "*" + ext); + } + gtk_file_filter_set_name(filter, label.c_str()); + GListStore* filters = g_list_store_new(GTK_TYPE_FILE_FILTER); + g_list_store_append(filters, filter); + gtk_file_dialog_set_filters(dialog, G_LIST_MODEL(filters)); + gtk_file_dialog_set_default_filter(dialog, filter); + g_object_unref(filters); + g_object_unref(filter); + } + + struct Gtk4Session { + GMainLoop* loop = nullptr; + GCancellable* cancellable = nullptr; + FileDialogMode mode = FileDialogMode::OpenFile; + std::vector paths; + bool done = false; + }; + Gtk4Session session; + session.loop = g_main_loop_new(nullptr, FALSE); + session.cancellable = g_cancellable_new(); + session.mode = mode; + + auto on_finish = +[](GObject* source, GAsyncResult* res, gpointer data) { + auto* s = static_cast(data); + auto* dlg = GTK_FILE_DIALOG(source); + GError* err = nullptr; + if (s->mode == FileDialogMode::OpenFiles) { + GListModel* files = gtk_file_dialog_open_multiple_finish(dlg, res, &err); + if (files) { + const guint n = g_list_model_get_n_items(files); + for (guint i = 0; i < n; ++i) { + GFile* file = G_FILE(g_list_model_get_item(files, i)); + if (file) { + if (char* p = g_file_get_path(file)) { + s->paths.emplace_back(p); + g_free(p); + } + g_object_unref(file); + } + } + g_object_unref(files); + } + } else { + GFile* file = nullptr; + if (s->mode == FileDialogMode::SaveFile) { + file = gtk_file_dialog_save_finish(dlg, res, &err); + } else if (s->mode == FileDialogMode::SelectFolder) { + file = gtk_file_dialog_select_folder_finish(dlg, res, &err); + } else { + file = gtk_file_dialog_open_finish(dlg, res, &err); + } + if (file) { + if (char* p = g_file_get_path(file)) { + s->paths.emplace_back(p); + g_free(p); + } + g_object_unref(file); + } + } + g_clear_error(&err); + s->done = true; + g_main_loop_quit(s->loop); + }; + + GMainContext* context = g_main_context_default(); + open = true; + cancel = [&session, context] { + if (!g_main_context_is_owner(context) || session.done) return false; + g_cancellable_cancel(session.cancellable); + session.done = true; + g_main_loop_quit(session.loop); + return true; + }; + + if (mode == FileDialogMode::OpenFiles) { + gtk_file_dialog_open_multiple(dialog, owner, session.cancellable, on_finish, &session); + } else if (mode == FileDialogMode::SaveFile) { + gtk_file_dialog_save(dialog, owner, session.cancellable, on_finish, &session); + } else if (mode == FileDialogMode::SelectFolder) { + gtk_file_dialog_select_folder(dialog, owner, session.cancellable, on_finish, &session); + } else { + gtk_file_dialog_open(dialog, owner, session.cancellable, on_finish, &session); + } + + if (!session.done) g_main_loop_run(session.loop); + cancel = {}; + open = false; + + paths = std::move(session.paths); + g_object_unref(session.cancellable); + g_object_unref(dialog); + g_main_loop_unref(session.loop); + result = paths.empty() ? FileDialogResult::Cancelled : FileDialogResult::Accepted; + return true; +} +#else +// GtkFileChooserNative goes through xdg-desktop-portal when GTK picks it +// (Flatpak, GTK_USE_PORTAL=1) and exports the parent's Wayland/X11 handle for +// it; otherwise it shows an in-process GtkFileChooserDialog transient for the +// parent toplevel. bool FileDialog::Impl::Open() { if (!gdk_display_get_default() && !gtk_init_check(nullptr, nullptr)) { error = "Cannot open a GTK display"; @@ -132,4 +275,5 @@ bool FileDialog::Impl::Open() { result = paths.empty() ? FileDialogResult::Cancelled : FileDialogResult::Accepted; return true; } +#endif } // namespace nativeapi diff --git a/src/platform/linux/gtk_compat_linux.h b/src/platform/linux/gtk_compat_linux.h new file mode 100644 index 00000000..4c28e5d1 --- /dev/null +++ b/src/platform/linux/gtk_compat_linux.h @@ -0,0 +1,75 @@ +#pragma once + +#include + +#if defined(NATIVEAPI_LINUX_GTK4) && defined(NATIVEAPI_LINUX_GTK3) +#error "NATIVEAPI_LINUX_GTK4 and NATIVEAPI_LINUX_GTK3 cannot both be defined" +#endif + +#if defined(NATIVEAPI_LINUX_GTK4) && (GTK_MAJOR_VERSION != 4) +#error "NATIVEAPI_LINUX_GTK4 is defined, but GTK headers are not GTK 4" +#endif + +#if defined(NATIVEAPI_LINUX_GTK3) && (GTK_MAJOR_VERSION != 3) +#error "NATIVEAPI_LINUX_GTK3 is defined, but GTK headers are not GTK 3" +#endif + +#if GTK_MAJOR_VERSION >= 4 +#define NATIVEAPI_GTK4 1 +#else +#define NATIVEAPI_GTK4 0 +#endif + +#if NATIVEAPI_GTK4 +#ifdef GDK_WINDOWING_WAYLAND +#include +#endif +#else +#ifdef GDK_WINDOWING_WAYLAND +#include +#endif +#endif + +namespace nativeapi::linux_gtk { + +inline bool InitCheck() { +#if NATIVEAPI_GTK4 + return gtk_init_check() != FALSE; +#else + return gtk_init_check(nullptr, nullptr) != FALSE; +#endif +} + +inline void PumpMainContext() { +#if NATIVEAPI_GTK4 + GMainContext* ctx = g_main_context_default(); + while (g_main_context_pending(ctx)) { + g_main_context_iteration(ctx, FALSE); + } +#else + while (gtk_events_pending()) { + gtk_main_iteration(); + } +#endif +} + +inline bool IsX11Display(GdkDisplay* display) { + if (!display) { + return false; + } + const GType x11_type = g_type_from_name("GdkX11Display"); + return x11_type != 0 && G_TYPE_CHECK_INSTANCE_TYPE(display, x11_type); +} + +inline bool IsWaylandDisplay(GdkDisplay* display) { + if (!display) { + return false; + } +#ifdef GDK_WINDOWING_WAYLAND + return GDK_IS_WAYLAND_DISPLAY(display) != FALSE; +#else + return false; +#endif +} + +} // namespace nativeapi::linux_gtk diff --git a/src/platform/linux/gtk_x11_compat_linux.h b/src/platform/linux/gtk_x11_compat_linux.h new file mode 100644 index 00000000..b269ded1 --- /dev/null +++ b/src/platform/linux/gtk_x11_compat_linux.h @@ -0,0 +1,17 @@ +#pragma once + +// Include this AFTER all nativeapi C++ headers: X11 headers define macros +// (None, Bool, Status, ...) that collide with C++ enum identifiers. +#include "gtk_compat_linux.h" + +#ifdef GDK_WINDOWING_X11 +#if NATIVEAPI_GTK4 +#include +#else +#include +#endif +#include +#include +#include +#undef None +#endif diff --git a/src/platform/linux/menu_linux.cpp b/src/platform/linux/menu_linux.cpp index a66fe4fa..13f1af47 100644 --- a/src/platform/linux/menu_linux.cpp +++ b/src/platform/linux/menu_linux.cpp @@ -1,4 +1,4 @@ -#include +#include "gtk_compat_linux.h" #include #include #include @@ -15,6 +15,540 @@ namespace nativeapi { +#if NATIVEAPI_GTK4 + +class MenuItem::Impl { + public: + Impl(MenuItemId id, MenuItemType type) + : id_(id), + type_(type), + state_(MenuItemState::Unchecked), + enabled_(true), + radio_group_(-1), + accelerator_("", ModifierKey::None) {} + + MenuItemId id_; + std::optional title_; + std::shared_ptr image_; + std::optional tooltip_; + MenuItemType type_; + MenuItemState state_; + bool enabled_; + int radio_group_; + KeyboardAccelerator accelerator_; + std::shared_ptr submenu_; + GMenuItem* gmenu_item_ = nullptr; + + ~Impl() { + if (gmenu_item_) { + g_object_unref(gmenu_item_); + gmenu_item_ = nullptr; + } + } +}; + +MenuItem::MenuItem(const std::string& label, MenuItemType type) { + MenuItemId id = IdAllocator::Allocate(); + pimpl_ = std::unique_ptr(new Impl(id, type)); + if (!label.empty()) { + pimpl_->title_ = label; + } + if (type != MenuItemType::Separator) { + pimpl_->gmenu_item_ = g_menu_item_new(label.c_str(), nullptr); + } +} + +MenuItem::MenuItem(void* menu_item) { + MenuItemId id = IdAllocator::Allocate(); + pimpl_ = std::unique_ptr(new Impl(id, MenuItemType::Normal)); + if (menu_item && G_IS_MENU_ITEM(menu_item)) { + pimpl_->gmenu_item_ = G_MENU_ITEM(g_object_ref(menu_item)); + const gchar* label = nullptr; + if (g_menu_item_get_attribute(pimpl_->gmenu_item_, G_MENU_ATTRIBUTE_LABEL, "&s", &label) && + label && label[0] != '\0') { + pimpl_->title_ = std::string(label); + } + } +} + +MenuItem::~MenuItem() = default; + +MenuItemId MenuItem::GetId() const { return pimpl_->id_; } +MenuItemType MenuItem::GetType() const { return pimpl_->type_; } + +void MenuItem::SetLabel(const std::optional& label) { + pimpl_->title_ = label; + if (pimpl_->gmenu_item_) { + g_menu_item_set_label(pimpl_->gmenu_item_, label.has_value() ? label->c_str() : ""); + } +} + +std::optional MenuItem::GetLabel() const { return pimpl_->title_; } + +void MenuItem::SetIcon(std::shared_ptr image) { pimpl_->image_ = std::move(image); } +std::shared_ptr MenuItem::GetIcon() const { return pimpl_->image_; } + +void MenuItem::SetTooltip(const std::optional& tooltip) { pimpl_->tooltip_ = tooltip; } +std::optional MenuItem::GetTooltip() const { return pimpl_->tooltip_; } + +void MenuItem::SetAccelerator(const std::optional& accelerator) { + if (accelerator.has_value()) { + pimpl_->accelerator_ = *accelerator; + } else { + pimpl_->accelerator_ = KeyboardAccelerator("", ModifierKey::None); + } +} + +KeyboardAccelerator MenuItem::GetAccelerator() const { return pimpl_->accelerator_; } + +void MenuItem::SetEnabled(bool enabled) { pimpl_->enabled_ = enabled; } +bool MenuItem::IsEnabled() const { return pimpl_->enabled_; } + +void MenuItem::SetState(MenuItemState state) { pimpl_->state_ = state; } +MenuItemState MenuItem::GetState() const { return pimpl_->state_; } + +void MenuItem::SetRadioGroup(int group_id) { pimpl_->radio_group_ = group_id; } +int MenuItem::GetRadioGroup() const { return pimpl_->radio_group_; } + +void MenuItem::SetSubmenu(std::shared_ptr submenu) { pimpl_->submenu_ = std::move(submenu); } +std::shared_ptr MenuItem::GetSubmenu() const { return pimpl_->submenu_; } + +void* MenuItem::GetNativeObjectInternal() const { return pimpl_->gmenu_item_; } + +class Menu::Impl { + public: + explicit Impl(MenuId id, GMenu* gmenu) + : id_(id), gmenu_(gmenu ? G_MENU(g_object_ref(gmenu)) : g_menu_new()) {} + + ~Impl() { + if (pending_close_idle_id_ != 0) { + g_source_remove(pending_close_idle_id_); + pending_close_idle_id_ = 0; + } + DetachPopover(); + if (gmenu_) { + g_object_unref(gmenu_); + gmenu_ = nullptr; + } + } + + void DetachPopover() { + if (popover_) { + if (map_handler_id_) { + g_signal_handler_disconnect(popover_, map_handler_id_); + map_handler_id_ = 0; + } + if (closed_handler_id_) { + g_signal_handler_disconnect(popover_, closed_handler_id_); + closed_handler_id_ = 0; + } + gtk_widget_unparent(popover_); + popover_ = nullptr; + } + if (action_group_) { + g_object_unref(action_group_); + action_group_ = nullptr; + } + action_items_.clear(); + } + + void PopulateGMenu(GMenu* target, + const std::vector>& items, + GSimpleActionGroup* group, + int& action_index) { + g_menu_remove_all(target); + GMenu* section = g_menu_new(); + auto flush_section = [&]() { + if (g_menu_model_get_n_items(G_MENU_MODEL(section)) > 0) { + g_menu_append_section(target, nullptr, G_MENU_MODEL(section)); + g_object_unref(section); + section = g_menu_new(); + } + }; + + for (const auto& item : items) { + if (!item) { + continue; + } + if (item->GetType() == MenuItemType::Separator) { + flush_section(); + continue; + } + const std::string label = item->GetLabel().value_or(""); + if (auto sub = item->GetSubmenu()) { + GMenu* sub_model = g_menu_new(); + PopulateGMenu(sub_model, sub->GetAllItems(), group, action_index); + g_menu_append_submenu(section, label.c_str(), G_MENU_MODEL(sub_model)); + g_object_unref(sub_model); + continue; + } + const std::string action_name = "item" + std::to_string(action_index++); + const std::string full_action = "menu." + action_name; + + GSimpleAction* action = nullptr; + if (item->GetType() == MenuItemType::Checkbox || item->GetType() == MenuItemType::Radio) { + const gboolean active = item->GetState() == MenuItemState::Checked ? TRUE : FALSE; + action = g_simple_action_new_stateful(action_name.c_str(), nullptr, + g_variant_new_boolean(active)); + } else { + action = g_simple_action_new(action_name.c_str(), nullptr); + } + g_simple_action_set_enabled(action, item->IsEnabled() ? TRUE : FALSE); + + struct ActionCtx { + Menu::Impl* menu_impl; + std::weak_ptr item; + }; + auto* ctx = new ActionCtx{this, item}; + g_signal_connect_data( + action, "activate", + G_CALLBACK(+[](GSimpleAction* act, GVariant*, gpointer data) { + auto* c = static_cast(data); + auto mi = c->item.lock(); + if (!mi) { + return; + } + if (mi->GetType() == MenuItemType::Checkbox) { + const bool now_checked = mi->GetState() != MenuItemState::Checked; + mi->SetState(now_checked ? MenuItemState::Checked : MenuItemState::Unchecked); + g_simple_action_set_state(act, g_variant_new_boolean(now_checked ? TRUE : FALSE)); + mi->Emit(MenuItemClickedEvent(mi->GetId())); + } else if (mi->GetType() == MenuItemType::Radio) { + const int group_id = mi->GetRadioGroup(); + if (group_id >= 0) { + for (const auto& sibling_weak : c->menu_impl->action_items_) { + if (auto sibling = sibling_weak.lock()) { + if (sibling.get() != mi.get() && sibling->GetType() == MenuItemType::Radio && + sibling->GetRadioGroup() == group_id) { + sibling->SetState(MenuItemState::Unchecked); + } + } + } + } + mi->SetState(MenuItemState::Checked); + g_simple_action_set_state(act, g_variant_new_boolean(TRUE)); + mi->Emit(MenuItemClickedEvent(mi->GetId())); + } else { + mi->Emit(MenuItemClickedEvent(mi->GetId())); + } + }), + ctx, +[](gpointer data, GClosure*) { delete static_cast(data); }, + static_cast(0)); + + g_action_map_add_action(G_ACTION_MAP(group), G_ACTION(action)); + g_object_unref(action); + action_items_.push_back(item); + + GMenuItem* gitem = g_menu_item_new(label.c_str(), full_action.c_str()); + g_menu_append_item(section, gitem); + g_object_unref(gitem); + } + + if (g_menu_model_get_n_items(G_MENU_MODEL(section)) > 0) { + if (g_menu_model_get_n_items(G_MENU_MODEL(target)) == 0) { + // Avoid an unnecessary section wrapper when there are no separators. + GMenuModel* src = G_MENU_MODEL(section); + const gint n = g_menu_model_get_n_items(src); + for (gint i = 0; i < n; ++i) { + GMenuItem* copy = g_menu_item_new_from_model(src, i); + g_menu_append_item(target, copy); + g_object_unref(copy); + } + } else { + g_menu_append_section(target, nullptr, G_MENU_MODEL(section)); + } + } + g_object_unref(section); + } + + static void OnMap(GtkWidget*, gpointer user_data) { + auto* menu_obj = static_cast(user_data); + if (menu_obj) { + menu_obj->Emit(MenuOpenedEvent(menu_obj->GetId())); + } + } + + static void OnClosed(GtkPopover*, gpointer user_data) { + auto* menu_obj = static_cast(user_data); + if (!menu_obj || menu_obj->pimpl_->pending_close_idle_id_ != 0) { + return; + } + menu_obj->pimpl_->pending_close_idle_id_ = g_idle_add_full( + G_PRIORITY_HIGH, + [](gpointer data) -> gboolean { + Menu* self = static_cast(data); + self->pimpl_->pending_close_idle_id_ = 0; + self->Emit(MenuClosedEvent(self->GetId())); + return G_SOURCE_REMOVE; + }, + menu_obj, nullptr); + } + + MenuId id_; + GMenu* gmenu_ = nullptr; + GtkWidget* popover_ = nullptr; + GSimpleActionGroup* action_group_ = nullptr; + std::vector> items_; + std::vector> action_items_; + gulong map_handler_id_ = 0; + gulong closed_handler_id_ = 0; + guint pending_close_idle_id_ = 0; +}; + +Menu::Menu() { + MenuId id = IdAllocator::Allocate(); + pimpl_ = std::unique_ptr(new Impl(id, nullptr)); +} + +Menu::Menu(void* menu) { + MenuId id = IdAllocator::Allocate(); + GMenu* gmenu = (menu && G_IS_MENU(menu)) ? G_MENU(menu) : nullptr; + pimpl_ = std::unique_ptr(new Impl(id, gmenu)); +} + +Menu::~Menu() = default; + +MenuId Menu::GetId() const { return pimpl_->id_; } + +void Menu::AddItem(std::shared_ptr item) { + if (item) { + pimpl_->items_.push_back(std::move(item)); + } +} + +void Menu::InsertItem(size_t index, std::shared_ptr item) { + if (!item) return; + if (index >= pimpl_->items_.size()) { + AddItem(std::move(item)); + return; + } + pimpl_->items_.insert(pimpl_->items_.begin() + index, std::move(item)); +} + +bool Menu::RemoveItem(std::shared_ptr item) { + if (!item) return false; + auto it = std::find(pimpl_->items_.begin(), pimpl_->items_.end(), item); + if (it != pimpl_->items_.end()) { + pimpl_->items_.erase(it); + return true; + } + return false; +} + +bool Menu::RemoveItemById(MenuItemId item_id) { + for (auto& item : pimpl_->items_) { + if (item->GetId() == item_id) { + return RemoveItem(item); + } + } + return false; +} + +bool Menu::RemoveItemAt(size_t index) { + if (index < pimpl_->items_.size()) { + return RemoveItem(pimpl_->items_[index]); + } + return false; +} + +void Menu::Clear() { pimpl_->items_.clear(); } + +void Menu::AddSeparator() { AddItem(std::make_shared("", MenuItemType::Separator)); } +void Menu::InsertSeparator(size_t index) { + InsertItem(index, std::make_shared("", MenuItemType::Separator)); +} + +size_t Menu::GetItemCount() const { return pimpl_->items_.size(); } + +std::shared_ptr Menu::GetItemAt(size_t index) const { + return index < pimpl_->items_.size() ? pimpl_->items_[index] : nullptr; +} + +std::shared_ptr Menu::GetItemById(MenuItemId item_id) const { + for (const auto& item : pimpl_->items_) { + if (item->GetId() == item_id) { + return item; + } + } + return nullptr; +} + +std::vector> Menu::GetAllItems() const { return pimpl_->items_; } + +bool Menu::Open(const PositioningStrategy& strategy, Placement placement) { + if (!g_main_context_is_owner(g_main_context_default())) { + struct OpenInvokeData { + Menu* self; + PositioningStrategy strategy; + Placement placement; + bool result; + GMutex mutex; + GCond cond; + bool done; + } data{this, strategy, placement, false}; + + g_mutex_init(&data.mutex); + g_cond_init(&data.cond); + data.done = false; + g_mutex_lock(&data.mutex); + g_main_context_invoke( + nullptr, + [](gpointer user_data) -> gboolean { + auto* d = static_cast(user_data); + bool r = d->self->Open(d->strategy, d->placement); + g_mutex_lock(&d->mutex); + d->result = r; + d->done = true; + g_cond_signal(&d->cond); + g_mutex_unlock(&d->mutex); + return G_SOURCE_REMOVE; + }, + &data); + while (!data.done) { + g_cond_wait(&data.cond, &data.mutex); + } + g_mutex_unlock(&data.mutex); + g_cond_clear(&data.cond); + g_mutex_clear(&data.mutex); + return data.result; + } + + if (strategy.GetType() == PositioningStrategy::Type::Absolute) { + std::cerr << "Warning: Absolute positioning strategy is not supported on Linux" << std::endl; + return false; + } + + GtkWidget* parent_widget = nullptr; + if (auto relative_window = strategy.GetRelativeWindow()) { + GtkWidget* w = static_cast(relative_window->GetNativeObject()); + if (w && GTK_IS_WIDGET(w)) { + parent_widget = w; + } + } + if (!parent_widget) { + GListModel* toplevels = gtk_window_get_toplevels(); + if (toplevels && g_list_model_get_n_items(toplevels) > 0) { + GtkWidget* fallback = nullptr; + const guint n = g_list_model_get_n_items(toplevels); + for (guint i = 0; i < n; ++i) { + GtkWindow* win = GTK_WINDOW(g_list_model_get_item(toplevels, i)); + if (!win) continue; + if (!fallback && gtk_widget_get_visible(GTK_WIDGET(win))) { + fallback = GTK_WIDGET(win); + } + if (gtk_window_is_active(win)) { + parent_widget = GTK_WIDGET(win); + g_object_unref(win); + break; + } + g_object_unref(win); + } + if (!parent_widget) { + parent_widget = fallback; + } + } + } + if (!parent_widget) { + return false; + } + + pimpl_->DetachPopover(); + pimpl_->action_group_ = g_simple_action_group_new(); + int action_index = 0; + pimpl_->PopulateGMenu(pimpl_->gmenu_, pimpl_->items_, pimpl_->action_group_, action_index); + + pimpl_->popover_ = gtk_popover_menu_new_from_model(G_MENU_MODEL(pimpl_->gmenu_)); + gtk_popover_set_has_arrow(GTK_POPOVER(pimpl_->popover_), FALSE); + gtk_widget_insert_action_group(pimpl_->popover_, "menu", G_ACTION_GROUP(pimpl_->action_group_)); + gtk_widget_set_parent(pimpl_->popover_, parent_widget); + + GdkRectangle rect{0, 0, 1, 1}; + if (strategy.GetType() == PositioningStrategy::Type::Relative) { + Rectangle r = strategy.GetRelativeRectangle(); + Point off = strategy.GetRelativeOffset(); + rect.x = static_cast(r.x + off.x); + rect.y = static_cast(r.y + off.y); + } + gtk_popover_set_pointing_to(GTK_POPOVER(pimpl_->popover_), &rect); + + GtkPositionType pos = GTK_POS_BOTTOM; + switch (placement) { + case Placement::TopStart: + case Placement::Top: + case Placement::TopEnd: + pos = GTK_POS_TOP; + break; + case Placement::LeftStart: + case Placement::Left: + case Placement::LeftEnd: + pos = GTK_POS_LEFT; + break; + case Placement::RightStart: + case Placement::Right: + case Placement::RightEnd: + pos = GTK_POS_RIGHT; + break; + default: + pos = GTK_POS_BOTTOM; + break; + } + gtk_popover_set_position(GTK_POPOVER(pimpl_->popover_), pos); + + pimpl_->map_handler_id_ = + g_signal_connect(pimpl_->popover_, "map", G_CALLBACK(Impl::OnMap), this); + pimpl_->closed_handler_id_ = + g_signal_connect(pimpl_->popover_, "closed", G_CALLBACK(Impl::OnClosed), this); + + gtk_popover_popup(GTK_POPOVER(pimpl_->popover_)); + return true; +} + +bool Menu::Close() { + if (!g_main_context_is_owner(g_main_context_default())) { + struct CloseInvokeData { + Menu* self; + bool result; + GMutex mutex; + GCond cond; + bool done; + } data{this, false}; + g_mutex_init(&data.mutex); + g_cond_init(&data.cond); + data.done = false; + g_mutex_lock(&data.mutex); + g_main_context_invoke( + nullptr, + [](gpointer user_data) -> gboolean { + auto* d = static_cast(user_data); + bool r = d->self->Close(); + g_mutex_lock(&d->mutex); + d->result = r; + d->done = true; + g_cond_signal(&d->cond); + g_mutex_unlock(&d->mutex); + return G_SOURCE_REMOVE; + }, + &data); + while (!data.done) { + g_cond_wait(&data.cond, &data.mutex); + } + g_mutex_unlock(&data.mutex); + g_cond_clear(&data.cond); + g_mutex_clear(&data.mutex); + return data.result; + } + + if (pimpl_->popover_) { + gtk_popover_popdown(GTK_POPOVER(pimpl_->popover_)); + return true; + } + return false; +} + +void* Menu::GetNativeObjectInternal() const { return pimpl_->gmenu_; } + +#else + // GTK signal handlers → Event emission static void OnGtkMenuItemActivate(GtkMenuItem* /*item*/, gpointer user_data) { MenuItem* menu_item = static_cast(user_data); @@ -891,4 +1425,6 @@ void* Menu::GetNativeObjectInternal() const { return (void*)pimpl_->gtk_menu_; } +#endif + } // namespace nativeapi diff --git a/src/platform/linux/message_dialog_linux.cpp b/src/platform/linux/message_dialog_linux.cpp index 5275b60d..be6e2963 100644 --- a/src/platform/linux/message_dialog_linux.cpp +++ b/src/platform/linux/message_dialog_linux.cpp @@ -1,10 +1,11 @@ #include "../message_dialog_state.h" #include #include +#include #include "../../dialog.h" #include "../../message_dialog.h" -#include +#include "gtk_compat_linux.h" namespace nativeapi { @@ -25,6 +26,195 @@ GtkWindow* ResolveParentWindow(const std::shared_ptr& parent, bool* vali } // namespace +#if NATIVEAPI_GTK4 +class MessageDialog::Impl { + public: + MessageDialogState state_; + void RefreshExtended() {} + + Impl(const std::string& title, const std::string& message) + : title_(title), + message_(message), + cancellable_(nullptr), + modal_loop_(nullptr), + alive_(std::make_shared(true)) { + if (!gdk_display_get_default()) { + linux_gtk::InitCheck(); + } + } + + ~Impl() { + *alive_ = false; + Close(); + } + + void SetTitle(const std::string& title) { title_ = title; } + std::string GetTitle() const { return title_; } + void SetMessage(const std::string& message) { message_ = message; } + std::string GetMessage() const { return message_; } + + bool Open(DialogModality modality) { + if (state_.open) { + return false; + } + if (!gdk_display_get_default() && !linux_gtk::InitCheck()) { + return false; + } + + bool parent_valid = true; + GtkWindow* parent = ResolveParentWindow(state_.parent, &parent_valid); + if (!parent_valid) { + return false; + } + + const char* primary = !title_.empty() ? title_.c_str() : message_.c_str(); + GtkAlertDialog* dialog = gtk_alert_dialog_new("%s", primary); + if (!dialog) { + return false; + } + if (!title_.empty() && !message_.empty()) { + gtk_alert_dialog_set_detail(dialog, message_.c_str()); + } + + std::vector buttons; + button_results_.clear(); + int default_idx = -1; + int cancel_idx = -1; + auto add_button = [&](const std::string& label, MessageDialogResult res) { + if (label.empty()) { + return; + } + const int idx = static_cast(button_results_.size()); + buttons.push_back(label.c_str()); + button_results_.push_back(res); + if (res == state_.default_button) { + default_idx = idx; + } + if (res == MessageDialogResult::Close) { + cancel_idx = idx; + } + }; + add_button(state_.close, MessageDialogResult::Close); + add_button(state_.secondary, MessageDialogResult::Secondary); + add_button(state_.primary, MessageDialogResult::Primary); + if (button_results_.empty()) { + buttons.push_back("OK"); + button_results_.push_back(MessageDialogResult::Close); + default_idx = 0; + cancel_idx = 0; + } + buttons.push_back(nullptr); + + gtk_alert_dialog_set_buttons(dialog, buttons.data()); + gtk_alert_dialog_set_default_button(dialog, default_idx); + gtk_alert_dialog_set_cancel_button(dialog, cancel_idx); + + const bool modal = modality != DialogModality::None; + gtk_alert_dialog_set_modal(dialog, modal ? TRUE : FALSE); + + state_.result = MessageDialogResult::None; + cancellable_ = g_cancellable_new(); + state_.open = true; + + if (!modal) { + struct AsyncCtx { + Impl* impl; + std::shared_ptr alive; + }; + auto* ctx = new AsyncCtx{this, alive_}; + gtk_alert_dialog_choose( + dialog, parent, cancellable_, + +[](GObject* source, GAsyncResult* res, gpointer data) { + std::unique_ptr ctx(static_cast(data)); + GError* err = nullptr; + const int chosen = + gtk_alert_dialog_choose_finish(GTK_ALERT_DIALOG(source), res, &err); + const bool has_err = (err != nullptr); + g_clear_error(&err); + if (!*ctx->alive) { + return; + } + Impl* impl = ctx->impl; + impl->state_.result = (!has_err && chosen >= 0 && + static_cast(chosen) < impl->button_results_.size()) + ? impl->button_results_[static_cast(chosen)] + : MessageDialogResult::Close; + impl->state_.open = false; + if (impl->cancellable_) { + g_object_unref(impl->cancellable_); + impl->cancellable_ = nullptr; + } + }, + ctx); + g_object_unref(dialog); + return true; + } + + GMainLoop* loop = g_main_loop_new(nullptr, FALSE); + modal_loop_ = loop; + struct ModalState { + Impl* impl; + GMainLoop* loop; + bool done = false; + }; + ModalState modal_state{this, loop, false}; + + gtk_alert_dialog_choose( + dialog, parent, cancellable_, + +[](GObject* source, GAsyncResult* res, gpointer data) { + auto* s = static_cast(data); + GError* err = nullptr; + const int chosen = gtk_alert_dialog_choose_finish(GTK_ALERT_DIALOG(source), res, &err); + const bool has_err = (err != nullptr); + g_clear_error(&err); + s->impl->state_.result = + (!has_err && chosen >= 0 && + static_cast(chosen) < s->impl->button_results_.size()) + ? s->impl->button_results_[static_cast(chosen)] + : MessageDialogResult::Close; + s->done = true; + g_main_loop_quit(s->loop); + }, + &modal_state); + + if (!modal_state.done) { + g_main_loop_run(loop); + } + + modal_loop_ = nullptr; + state_.open = false; + if (cancellable_) { + g_object_unref(cancellable_); + cancellable_ = nullptr; + } + g_main_loop_unref(loop); + g_object_unref(dialog); + return true; + } + + bool Close() { + if (!state_.open) { + return false; + } + state_.open = false; + if (cancellable_) { + g_cancellable_cancel(cancellable_); + } + if (modal_loop_) { + g_main_loop_quit(modal_loop_); + } + return true; + } + + private: + std::string title_; + std::string message_; + GCancellable* cancellable_; + GMainLoop* modal_loop_; + std::vector button_results_; + std::shared_ptr alive_; +}; +#else // Private implementation class for MessageDialog (GTK 3) class MessageDialog::Impl { public: @@ -291,6 +481,7 @@ class MessageDialog::Impl { GtkWidget* checkbox_; GtkWidget* progress_bar_; }; +#endif // MessageDialog implementation MessageDialog::MessageDialog(const std::string& title, const std::string& message) diff --git a/src/platform/linux/shortcut_manager_linux.cpp b/src/platform/linux/shortcut_manager_linux.cpp index 3de5a6ad..d88a9f75 100644 --- a/src/platform/linux/shortcut_manager_linux.cpp +++ b/src/platform/linux/shortcut_manager_linux.cpp @@ -10,7 +10,8 @@ #include #include -#include + +#include "gtk_compat_linux.h" #include "../../shortcut_manager.h" #include "../shared/shortcut_native_key.h" @@ -345,7 +346,7 @@ class ShortcutManagerImpl final : public ShortcutManager::Impl { // A Wayland desktop can still run an explicitly X11 application. Preserve // its existing X11 registration path instead of inferring its backend only // from the inherited session environment. - if (auto* display = gdk_display_get_default(); display && GDK_IS_X11_DISPLAY(display)) return false; + if (auto* display = gdk_display_get_default(); linux_gtk::IsX11Display(display)) return false; const char* backend = std::getenv("GDK_BACKEND"); if (backend && std::string(backend) == "x11") return false; const char* display = std::getenv("WAYLAND_DISPLAY"); diff --git a/src/platform/linux/tray_icon_linux.cpp b/src/platform/linux/tray_icon_linux.cpp index 41a33719..203a0179 100644 --- a/src/platform/linux/tray_icon_linux.cpp +++ b/src/platform/linux/tray_icon_linux.cpp @@ -7,7 +7,7 @@ #include #include #include -#include +#include "gtk_compat_linux.h" #include #include #include @@ -26,7 +26,6 @@ #include "../../menu.h" #include "../../tray_icon.h" #include "../../view.h" -#include #undef None namespace nativeapi { @@ -290,7 +289,11 @@ class TrayIcon::Impl { bool name_acquired_ = false; std::string registered_watcher_owner_; std::string service_name_; +#if NATIVEAPI_GTK4 + std::unordered_map> dbusmenu_items_; +#else std::unordered_map dbusmenu_items_; +#endif // dbusmenu ids the host reported open (0 is the root menu), so that a repeated // "opened" or a missing "closed" still yields one event of each. std::unordered_set open_dbusmenus_; @@ -359,6 +362,13 @@ class TrayIcon::Impl { return GdkRGBA{1, 1, 1, 1}; if (color_scheme_ == 2) return GdkRGBA{0, 0, 0, 1}; +#if NATIVEAPI_GTK4 + if (GtkSettings* settings = gtk_settings_get_default()) { + gboolean prefer_dark = FALSE; + g_object_get(settings, "gtk-application-prefer-dark-theme", &prefer_dark, nullptr); + return prefer_dark ? GdkRGBA{1, 1, 1, 1} : GdkRGBA{0, 0, 0, 1}; + } +#else // No portal preference: use a fresh context without application CSS. if (gdk_screen_get_default()) { GtkWidgetPath* path = gtk_widget_path_new(); @@ -371,6 +381,7 @@ class TrayIcon::Impl { gtk_widget_path_unref(path); return color; } +#endif return GdkRGBA{1, 1, 1, 1}; } @@ -572,7 +583,11 @@ class TrayIcon::Impl { auto popup = local_popup_.lock(); local_popup_.reset(); if (popup) { +#if NATIVEAPI_GTK4 + popup->Close(); +#else gtk_menu_popdown(GTK_MENU(popup->GetNativeObject())); +#endif } StopWatchingAppearance(); @@ -877,6 +892,115 @@ class TrayIcon::Impl { return nullptr; } +#if NATIVEAPI_GTK4 + int RegisterDbusMenuItem(const std::shared_ptr& item) { + int id = static_cast(item->GetId() & 0x7fffffff); + if (id == 0) { + id = 1; + } + dbusmenu_items_[id] = item; + return id; + } + + void AppendMenuItemProperties(GVariantBuilder* props, const std::shared_ptr& item) { + const bool is_separator = item && item->GetType() == MenuItemType::Separator; + const bool enabled = item ? item->IsEnabled() : true; + const bool visible = true; + + g_variant_builder_add(props, "{sv}", "enabled", g_variant_new_boolean(enabled)); + g_variant_builder_add(props, "{sv}", "visible", g_variant_new_boolean(visible)); + + if (is_separator) { + g_variant_builder_add(props, "{sv}", "type", g_variant_new_string("separator")); + return; + } + + if (item) { + if (auto label = item->GetLabel(); label && !label->empty()) { + g_variant_builder_add(props, "{sv}", "label", g_variant_new_string(label->c_str())); + } + if (item->GetType() == MenuItemType::Checkbox || item->GetType() == MenuItemType::Radio) { + const bool is_radio = item->GetType() == MenuItemType::Radio; + g_variant_builder_add(props, "{sv}", "toggle-type", + g_variant_new_string(is_radio ? "radio" : "checkmark")); + g_variant_builder_add( + props, "{sv}", "toggle-state", + g_variant_new_int32(item->GetState() == MenuItemState::Checked ? 1 : 0)); + } + if (item->GetSubmenu()) { + g_variant_builder_add(props, "{sv}", "children-display", g_variant_new_string("submenu")); + } + } + } + + GVariant* BuildDbusMenuLayoutItem(const std::shared_ptr& item, int item_id) { + GVariantBuilder props; + GVariantBuilder children; + g_variant_builder_init(&props, G_VARIANT_TYPE("a{sv}")); + g_variant_builder_init(&children, G_VARIANT_TYPE("av")); + + if (item) { + AppendMenuItemProperties(&props, item); + if (auto sub = item->GetSubmenu()) { + for (const auto& child : sub->GetAllItems()) { + if (!child) continue; + int child_id = RegisterDbusMenuItem(child); + g_variant_builder_add(&children, "v", BuildDbusMenuLayoutItem(child, child_id)); + } + } + } + return g_variant_new("(i@a{sv}@av)", item_id, g_variant_builder_end(&props), + g_variant_builder_end(&children)); + } + + GVariant* BuildDbusMenuLayoutRoot(const std::shared_ptr& menu) { + GVariantBuilder props; + GVariantBuilder children; + g_variant_builder_init(&props, G_VARIANT_TYPE("a{sv}")); + g_variant_builder_init(&children, G_VARIANT_TYPE("av")); + + dbusmenu_items_.clear(); + if (menu) { + for (const auto& child : menu->GetAllItems()) { + if (!child) continue; + int child_id = RegisterDbusMenuItem(child); + g_variant_builder_add(&children, "v", BuildDbusMenuLayoutItem(child, child_id)); + } + } + return g_variant_new("(i@a{sv}@av)", 0, g_variant_builder_end(&props), + g_variant_builder_end(&children)); + } + + GVariant* BuildDbusMenuProperties(int id) { + GVariantBuilder props; + g_variant_builder_init(&props, G_VARIANT_TYPE("a{sv}")); + auto it = dbusmenu_items_.find(id); + if (it != dbusmenu_items_.end()) { + if (auto item = it->second.lock()) { + AppendMenuItemProperties(&props, item); + } + } + return g_variant_new("(i@a{sv})", id, g_variant_builder_end(&props)); + } + + void ActivateDbusMenuItem(int id) { + auto it = dbusmenu_items_.find(id); + if (it == dbusmenu_items_.end()) { + return; + } + auto item = it->second.lock(); + if (!item || !item->IsEnabled() || item->GetType() == MenuItemType::Separator) { + return; + } + if (item->GetType() == MenuItemType::Checkbox) { + item->SetState(item->GetState() == MenuItemState::Checked ? MenuItemState::Unchecked + : MenuItemState::Checked); + } else if (item->GetType() == MenuItemType::Radio) { + item->SetState(MenuItemState::Checked); + } + item->Emit(MenuItemClickedEvent(item->GetId())); + } +#else static std::string GtkMenuItemLabel(GtkWidget* item) { if (!item || !GTK_IS_MENU_ITEM(item) || GTK_IS_SEPARATOR_MENU_ITEM(item)) { return ""; @@ -1016,6 +1140,7 @@ class TrayIcon::Impl { } return nullptr; } +#endif // The host shows the exported menu itself and reports it through dbusmenu // events: "clicked" on an item, "opened" / "closed" on the root (id 0) or on the @@ -1044,7 +1169,11 @@ class TrayIcon::Impl { } auto it = dbusmenu_items_.find(id); if (it == dbusmenu_items_.end()) return; +#if NATIVEAPI_GTK4 + std::shared_ptr item = it->second.lock(); +#else std::shared_ptr item = FindMenuItem(context_menu_, it->second); +#endif if (!item) return; if (opened) { item->Emit(MenuItemSubmenuOpenedEvent(item->GetId())); @@ -1074,6 +1203,19 @@ class TrayIcon::Impl { } } +#if NATIVEAPI_GTK4 + GVariant* layout = nullptr; + if (parent_id == 0) { + layout = self->BuildDbusMenuLayoutRoot(self->context_menu_); + } else { + auto it = self->dbusmenu_items_.find(parent_id); + std::shared_ptr item = + it != self->dbusmenu_items_.end() ? it->second.lock() : nullptr; + layout = self->BuildDbusMenuLayoutItem(item, parent_id); + } + g_dbus_method_invocation_return_value( + invocation, g_variant_new("(u@(ia{sv}av))", self->menu_revision_, layout)); +#else GtkWidget* menu = self->context_menu_ ? static_cast(self->context_menu_->GetNativeObject()) : nullptr; @@ -1085,6 +1227,7 @@ class TrayIcon::Impl { invocation, g_variant_new("(u@(ia{sv}av))", self->menu_revision_, self->BuildDbusMenuLayout(menu, parent_id))); +#endif return; } @@ -1124,7 +1267,13 @@ class TrayIcon::Impl { g_variant_builder_init(&props, G_VARIANT_TYPE("a{sv}")); auto it = self->dbusmenu_items_.find(item_id); if (it != self->dbusmenu_items_.end()) { +#if NATIVEAPI_GTK4 + if (auto item = it->second.lock()) { + self->AppendMenuItemProperties(&props, item); + } +#else self->AppendMenuItemProperties(&props, it->second); +#endif } GVariant* props_variant = g_variant_builder_end(&props); GVariant* value = g_variant_lookup_value(props_variant, name ? name : "", nullptr); @@ -1338,7 +1487,11 @@ void TrayIcon::SetContextMenu(std::shared_ptr menu) { "com.canonical.dbusmenu", "LayoutUpdated", g_variant_new("(ui)", pimpl_->menu_revision_, 0), nullptr); } +#if NATIVEAPI_GTK4 + if (popup) popup->Close(); +#else if (popup) gtk_menu_popdown(GTK_MENU(popup->GetNativeObject())); +#endif } std::shared_ptr TrayIcon::GetContextMenu() { @@ -1365,8 +1518,18 @@ bool TrayIcon::OpenContextMenu() { // GTK operations, like the other tray setters, belong on the UI thread. auto menu = pimpl_->context_menu_; if (!menu) return false; +#if NATIVEAPI_GTK4 + GdkDisplay* display = gdk_display_get_default(); + if (!linux_gtk::IsX11Display(display)) { + g_warning("TrayIcon::OpenContextMenu requires X11; on Wayland use " + "ContextMenuTrigger::Clicked or RightClicked so the tray host displays the menu"); + return false; + } + pimpl_->local_popup_ = menu; + return menu->Open(PositioningStrategy::CursorPosition(), Placement::BottomStart); +#else GdkDisplay* display = gdk_display_get_default(); - if (!display || !GDK_IS_X11_DISPLAY(display)) { + if (!linux_gtk::IsX11Display(display)) { g_warning("TrayIcon::OpenContextMenu requires X11; on Wayland use " "ContextMenuTrigger::Clicked or RightClicked so the tray host displays the menu"); return false; @@ -1387,15 +1550,20 @@ bool TrayIcon::OpenContextMenu() { G_GNUC_END_IGNORE_DEPRECATIONS // Menu's existing map/unmap handlers deliver opened/closed exactly once. return gtk_widget_get_mapped(widget); +#endif } bool TrayIcon::CloseContextMenu() { auto popup = pimpl_->local_popup_.lock(); pimpl_->local_popup_.reset(); if (popup) { +#if NATIVEAPI_GTK4 + return popup->Close(); +#else auto* widget = static_cast(popup->GetNativeObject()); gtk_menu_popdown(GTK_MENU(widget)); return !gtk_widget_get_mapped(widget); +#endif } // Host-rendered dbusmenus have no SNI close operation. return pimpl_->open_dbusmenus_.empty(); diff --git a/src/platform/linux/view_controls_linux.cpp b/src/platform/linux/view_controls_linux.cpp index 06db15c5..774f5fd1 100644 --- a/src/platform/linux/view_controls_linux.cpp +++ b/src/platform/linux/view_controls_linux.cpp @@ -21,7 +21,7 @@ using Platform = ViewInternal::Impl::Platform; ViewInternal::NativeControl Adopt(GtkWidget* widget) { if (widget) { g_object_ref_sink(widget); - gtk_widget_show(widget); + gtk_widget_set_visible(widget, TRUE); } return ViewInternal::NativeControl{widget}; } @@ -31,8 +31,13 @@ GtkWidget* MakeLabel(const std::string& text) { if (!label) { return nullptr; } +#if NATIVEAPI_GTK4 + gtk_label_set_wrap(GTK_LABEL(label), TRUE); + gtk_label_set_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR); +#else gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR); +#endif gtk_label_set_xalign(GTK_LABEL(label), 0.0f); gtk_label_set_yalign(GTK_LABEL(label), 0.0f); return label; @@ -44,7 +49,11 @@ GtkWidget* MakeEntry(const std::string& text, const Platform* platform) { if (!entry) { return nullptr; } +#if NATIVEAPI_GTK4 + gtk_editable_set_text(GTK_EDITABLE(entry), text.c_str()); +#else gtk_entry_set_text(GTK_ENTRY(entry), text.c_str()); +#endif gtk_entry_set_has_frame(GTK_ENTRY(entry), (!platform || platform->bordered) ? TRUE : FALSE); if (platform) { gtk_entry_set_visibility(GTK_ENTRY(entry), platform->secure ? FALSE : TRUE); @@ -67,7 +76,11 @@ GtkWidget* MakeTextView(const std::string& text, *text_view = nullptr; *placeholder_label = nullptr; GtkWidget* overlay = gtk_overlay_new(); +#if NATIVEAPI_GTK4 + GtkWidget* scrolled = gtk_scrolled_window_new(); +#else GtkWidget* scrolled = gtk_scrolled_window_new(nullptr, nullptr); +#endif GtkWidget* view = gtk_text_view_new(); GtkWidget* label = gtk_label_new(platform.placeholder ? platform.placeholder->c_str() : ""); if (!overlay || !scrolled || !view || !label) { @@ -81,8 +94,13 @@ GtkWidget* MakeTextView(const std::string& text, } gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); +#if NATIVEAPI_GTK4 + gtk_scrolled_window_set_has_frame(GTK_SCROLLED_WINDOW(scrolled), + platform.bordered ? TRUE : FALSE); +#else gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolled), platform.bordered ? GTK_SHADOW_IN : GTK_SHADOW_NONE); +#endif gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(view), GTK_WRAP_WORD_CHAR); gtk_text_view_set_editable(GTK_TEXT_VIEW(view), platform.editable ? TRUE : FALSE); gtk_text_view_set_justification(GTK_TEXT_VIEW(view), ToGtkJustification(platform.text_alignment)); @@ -90,9 +108,13 @@ GtkWidget* MakeTextView(const std::string& text, if (buffer) { gtk_text_buffer_set_text(buffer, text.c_str(), -1); } +#if NATIVEAPI_GTK4 + gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(scrolled), view); +#else gtk_container_add(GTK_CONTAINER(scrolled), view); gtk_widget_show(view); gtk_widget_show(scrolled); +#endif gtk_label_set_xalign(GTK_LABEL(label), ToGtkXAlign(platform.text_alignment)); gtk_widget_set_halign(label, GTK_ALIGN_FILL); @@ -100,11 +122,17 @@ GtkWidget* MakeTextView(const std::string& text, gtk_widget_set_margin_start(label, platform.bordered ? 6 : 0); gtk_widget_set_margin_end(label, platform.bordered ? 6 : 0); gtk_widget_set_margin_top(label, platform.bordered ? 4 : 0); +#if NATIVEAPI_GTK4 + gtk_widget_add_css_class(label, "dim-label"); + gtk_overlay_set_child(GTK_OVERLAY(overlay), scrolled); + gtk_overlay_add_overlay(GTK_OVERLAY(overlay), label); + gtk_widget_set_can_target(label, FALSE); +#else gtk_style_context_add_class(gtk_widget_get_style_context(label), "dim-label"); - gtk_container_add(GTK_CONTAINER(overlay), scrolled); gtk_overlay_add_overlay(GTK_OVERLAY(overlay), label); gtk_overlay_set_overlay_pass_through(GTK_OVERLAY(overlay), label, TRUE); +#endif *text_view = GTK_TEXT_VIEW(view); *placeholder_label = GTK_LABEL(label); @@ -291,7 +319,11 @@ void TextField::SetText(const std::string& text) { gtk_text_buffer_set_text(buffer, text.c_str(), -1); } } else if (GTK_IS_ENTRY(platform.widget)) { +#if NATIVEAPI_GTK4 + gtk_editable_set_text(GTK_EDITABLE(platform.widget), text.c_str()); +#else gtk_entry_set_text(GTK_ENTRY(platform.widget), text.c_str()); +#endif } --platform.suppress_changed; } @@ -434,6 +466,23 @@ void TextField::SetBordered(bool is_bordered) { return; } platform.bordered = is_bordered; +#if NATIVEAPI_GTK4 + if (platform.text_view && platform.widget && GTK_IS_OVERLAY(platform.widget)) { + GtkWidget* scrolled = gtk_overlay_get_child(GTK_OVERLAY(platform.widget)); + if (scrolled && GTK_IS_SCROLLED_WINDOW(scrolled)) { + gtk_scrolled_window_set_has_frame(GTK_SCROLLED_WINDOW(scrolled), + is_bordered ? TRUE : FALSE); + } + if (platform.placeholder_label) { + GtkWidget* lbl = GTK_WIDGET(platform.placeholder_label); + gtk_widget_set_margin_start(lbl, is_bordered ? 6 : 0); + gtk_widget_set_margin_end(lbl, is_bordered ? 6 : 0); + gtk_widget_set_margin_top(lbl, is_bordered ? 4 : 0); + } + } else if (platform.widget && GTK_IS_ENTRY(platform.widget)) { + gtk_entry_set_has_frame(GTK_ENTRY(platform.widget), is_bordered ? TRUE : FALSE); + } +#else if (platform.text_view && platform.widget && GTK_IS_BIN(platform.widget)) { GtkWidget* scrolled = gtk_bin_get_child(GTK_BIN(platform.widget)); if (scrolled && GTK_IS_SCROLLED_WINDOW(scrolled)) { @@ -449,6 +498,7 @@ void TextField::SetBordered(bool is_bordered) { } else if (platform.widget && GTK_IS_ENTRY(platform.widget)) { gtk_entry_set_has_frame(GTK_ENTRY(platform.widget), is_bordered ? TRUE : FALSE); } +#endif platform.ApplyCss(); pimpl_->InvalidateIntrinsicSize(); } @@ -548,6 +598,7 @@ TextRange TextField::GetSelection() const { } bool TextField::IsComposing() const { +#if !NATIVEAPI_GTK4 auto& platform = *pimpl_->platform; if (platform.widget && GTK_IS_ENTRY(platform.widget)) { PangoLayout* layout = gtk_entry_get_layout(GTK_ENTRY(platform.widget)); @@ -559,6 +610,7 @@ bool TextField::IsComposing() const { } } } +#endif return false; } diff --git a/src/platform/linux/view_internal_linux.h b/src/platform/linux/view_internal_linux.h index 1cb35c74..52d3160f 100644 --- a/src/platform/linux/view_internal_linux.h +++ b/src/platform/linux/view_internal_linux.h @@ -1,9 +1,9 @@ #pragma once // Shared between view_linux.cpp and view_controls_linux.cpp: the platform half -// of View::Impl on GTK 3 and the helpers that turn widget signals into events. +// of View::Impl on GTK 3 / GTK 4 and the helpers that turn widget signals into events. -#include +#include "gtk_compat_linux.h" #include #include @@ -49,6 +49,11 @@ struct View::Impl::Platform { GtkTextBuffer* hooked_buffer = nullptr; gulong focus_in_id = 0; gulong focus_out_id = 0; +#if NATIVEAPI_GTK4 + GtkEventController* focus_controller = nullptr; + GtkWidget* focus_controller_widget = nullptr; + guint resize_tick_id = 0; +#endif gulong size_allocate_id = 0; /// Idle source of a relayout the root's size-allocate asked for; 0 if none. guint relayout_source_id = 0; @@ -137,7 +142,11 @@ inline std::string ReadWidgetText(GtkWidget* widget, GtkTextView* text_view) { return result; } if (widget && GTK_IS_ENTRY(widget)) { +#if NATIVEAPI_GTK4 + const gchar* text = gtk_editable_get_text(GTK_EDITABLE(widget)); +#else const gchar* text = gtk_entry_get_text(GTK_ENTRY(widget)); +#endif return text ? text : ""; } return ""; diff --git a/src/platform/linux/view_linux.cpp b/src/platform/linux/view_linux.cpp index 2480893e..f3523010 100644 --- a/src/platform/linux/view_linux.cpp +++ b/src/platform/linux/view_linux.cpp @@ -23,12 +23,16 @@ namespace { using Impl = ViewInternal::Impl; /// Whether GTK has allocated `widget` yet: a fresh widget carries the -/// placeholder allocation {-1, -1, 1, 1}. +/// placeholder allocation {-1, -1, 1, 1} on GTK 3, or 0x0 on GTK 4. bool IsAllocated(GtkWidget* widget) { +#if NATIVEAPI_GTK4 + return gtk_widget_get_width(widget) > 0 || gtk_widget_get_height(widget) > 0; +#else GtkAllocation allocation; gtk_widget_get_allocation(widget, &allocation); return !(allocation.x == -1 && allocation.y == -1 && allocation.width == 1 && allocation.height == 1); +#endif } /// The position of `child` inside its GtkFixed parent; (0, 0) elsewhere. @@ -37,10 +41,41 @@ void GetFixedPosition(GtkWidget* child, int* x, int* y) { *y = 0; GtkWidget* parent = child ? gtk_widget_get_parent(child) : nullptr; if (parent && GTK_IS_FIXED(parent)) { +#if NATIVEAPI_GTK4 + double dx = 0.0; + double dy = 0.0; + gtk_fixed_get_child_position(GTK_FIXED(parent), child, &dx, &dy); + *x = static_cast(std::lround(dx)); + *y = static_cast(std::lround(dy)); +#else gtk_container_child_get(GTK_CONTAINER(parent), child, "x", x, "y", y, nullptr); +#endif } } +void RemoveFromParent(GtkWidget* parent, GtkWidget* child) { + if (!parent || !child) { + return; + } +#if NATIVEAPI_GTK4 + if (GTK_IS_FIXED(parent)) { + gtk_fixed_remove(GTK_FIXED(parent), child); + } else if (GTK_IS_WINDOW(parent)) { + gtk_window_set_child(GTK_WINDOW(parent), nullptr); + } else if (GTK_IS_OVERLAY(parent)) { + if (gtk_overlay_get_child(GTK_OVERLAY(parent)) == child) { + gtk_overlay_set_child(GTK_OVERLAY(parent), nullptr); + } else { + gtk_overlay_remove_overlay(GTK_OVERLAY(parent), child); + } + } else { + gtk_widget_unparent(child); + } +#else + gtk_container_remove(GTK_CONTAINER(parent), child); +#endif +} + /// Re-appends `child` to `fixed` so it draws above every other child. GtkFixed /// paints its children in insertion order and offers no reorder call, so this /// (remove + put at the same position) is how the z-order is arranged. @@ -52,7 +87,7 @@ void MoveToEnd(GtkWidget* fixed, GtkWidget* child) { int y = 0; GetFixedPosition(child, &x, &y); g_object_ref(child); - gtk_container_remove(GTK_CONTAINER(fixed), child); + RemoveFromParent(fixed, child); gtk_fixed_put(GTK_FIXED(fixed), child, x, y); g_object_unref(child); } @@ -125,6 +160,19 @@ void OnPlaceholderBufferChanged(GtkTextBuffer*, gpointer data) { static_cast(data)->SyncPlaceholderVisibility(); } +#if NATIVEAPI_GTK4 +void OnFocusEnter(GtkEventControllerFocus*, gpointer data) { + auto* impl = static_cast(data); + std::shared_ptr keep_alive = impl->owner ? impl->owner->shared_from_this() : nullptr; + impl->Emit(ViewFocusedEvent(impl->id)); +} + +void OnFocusLeave(GtkEventControllerFocus*, gpointer data) { + auto* impl = static_cast(data); + std::shared_ptr keep_alive = impl->owner ? impl->owner->shared_from_this() : nullptr; + impl->Emit(ViewBlurredEvent(impl->id)); +} +#else gboolean OnFocusIn(GtkWidget*, GdkEventFocus*, gpointer data) { auto* impl = static_cast(data); std::shared_ptr keep_alive = impl->owner ? impl->owner->shared_from_this() : nullptr; @@ -138,6 +186,7 @@ gboolean OnFocusOut(GtkWidget*, GdkEventFocus*, gpointer data) { impl->Emit(ViewBlurredEvent(impl->id)); return FALSE; } +#endif gboolean RelayoutRootWhenIdle(gpointer data) { auto* impl = static_cast(data); @@ -146,6 +195,23 @@ gboolean RelayoutRootWhenIdle(gpointer data) { return G_SOURCE_REMOVE; } +#if NATIVEAPI_GTK4 +gboolean OnRootResizeTick(GtkWidget* widget, GdkFrameClock*, gpointer data) { + auto* impl = static_cast(data); + auto& platform = *impl->platform; + const int width = gtk_widget_get_width(widget); + const int height = gtk_widget_get_height(widget); + if ((width > 0 || height > 0) && (width != platform.last_width || height != platform.last_height)) { + platform.last_width = width; + platform.last_height = height; + if (platform.relayout_source_id == 0) { + platform.relayout_source_id = + g_idle_add_full(G_PRIORITY_HIGH_IDLE, RelayoutRootWhenIdle, impl, nullptr); + } + } + return G_SOURCE_CONTINUE; +} +#else /// A root's "size-allocate": lays the tree out again when the size changed. /// /// Not from inside the handler: GTK is in the middle of an allocation pass @@ -177,6 +243,7 @@ gboolean OnDrawContainerBackground(GtkWidget* widget, cairo_t* cr, gpointer) { gtk_widget_get_allocated_height(widget)); return FALSE; // the default handler draws the children } +#endif } // namespace @@ -202,9 +269,11 @@ View::Impl::Platform::Platform(Impl* impl, GtkWidget* widget, bool owned) gtk_widget_set_name(widget, name); g_free(name); } +#if !NATIVEAPI_GTK4 if (GTK_IS_FIXED(widget)) { draw_id = g_signal_connect(widget, "draw", G_CALLBACK(OnDrawContainerBackground), this); } +#endif } View::Impl::Platform::~Platform() { @@ -219,10 +288,18 @@ View::Impl::Platform::~Platform() { placeholder_label = nullptr; UnhookControl(); if (widget) { +#if NATIVEAPI_GTK4 + if (resize_tick_id) { + gtk_widget_remove_tick_callback(widget, resize_tick_id); + resize_tick_id = 0; + } +#else DisconnectSignal(widget, size_allocate_id); DisconnectSignal(widget, draw_id); +#endif } if (css_provider) { + G_GNUC_BEGIN_IGNORE_DEPRECATIONS if (placeholder_css_widget) { gtk_style_context_remove_provider(gtk_widget_get_style_context(placeholder_css_widget), GTK_STYLE_PROVIDER(css_provider)); @@ -233,6 +310,7 @@ View::Impl::Platform::~Platform() { GTK_STYLE_PROVIDER(css_provider)); css_widget = nullptr; } + G_GNUC_END_IGNORE_DEPRECATIONS g_object_unref(css_provider); css_provider = nullptr; } @@ -275,8 +353,16 @@ void View::Impl::Platform::HookControl() { } GtkWidget* focusable = FocusWidget(); if (focusable && gtk_widget_get_can_focus(focusable)) { +#if NATIVEAPI_GTK4 + focus_controller = gtk_event_controller_focus_new(); + focus_in_id = g_signal_connect(focus_controller, "enter", G_CALLBACK(OnFocusEnter), impl); + focus_out_id = g_signal_connect(focus_controller, "leave", G_CALLBACK(OnFocusLeave), impl); + focus_controller_widget = focusable; + gtk_widget_add_controller(focusable, focus_controller); +#else focus_in_id = g_signal_connect(focusable, "focus-in-event", G_CALLBACK(OnFocusIn), impl); focus_out_id = g_signal_connect(focusable, "focus-out-event", G_CALLBACK(OnFocusOut), impl); +#endif } } @@ -294,6 +380,19 @@ void View::Impl::Platform::UnhookControl() { } else { buffer_changed_id = 0; } +#if NATIVEAPI_GTK4 + if (focus_controller) { + DisconnectSignal(focus_controller, focus_in_id); + DisconnectSignal(focus_controller, focus_out_id); + if (focus_controller_widget) { + gtk_widget_remove_controller(focus_controller_widget, focus_controller); + } + focus_controller = nullptr; + focus_controller_widget = nullptr; + } else { + focus_in_id = focus_out_id = 0; + } +#else GtkWidget* focusable = FocusWidget(); if (focusable) { DisconnectSignal(focusable, focus_in_id); @@ -301,6 +400,7 @@ void View::Impl::Platform::UnhookControl() { } else { focus_in_id = focus_out_id = 0; } +#endif } void View::Impl::Platform::ApplyCss() { @@ -311,6 +411,7 @@ void View::Impl::Platform::ApplyCss() { if (!css_provider) { css_provider = gtk_css_provider_new(); } + G_GNUC_BEGIN_IGNORE_DEPRECATIONS if (css_widget != target) { if (css_widget) { gtk_style_context_remove_provider(gtk_widget_get_style_context(css_widget), @@ -339,6 +440,7 @@ void View::Impl::Platform::ApplyCss() { } placeholder_css_widget = ph_target; } + G_GNUC_END_IGNORE_DEPRECATIONS std::string font_declarations; if (font_size > 0.0) { @@ -391,7 +493,13 @@ void View::Impl::Platform::ApplyCss() { css += "label.dim-label { " + font_declarations + "background-color: transparent; background-image: none; }"; } +#if NATIVEAPI_GTK4 + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gtk_css_provider_load_from_data(css_provider, css.c_str(), -1); + G_GNUC_END_IGNORE_DEPRECATIONS +#else gtk_css_provider_load_from_data(css_provider, css.c_str(), -1, nullptr); +#endif gtk_widget_queue_resize(target); } @@ -415,6 +523,31 @@ void View::Impl::Platform::ScaleImage(int width, int height) { target_width = std::max(1, static_cast(std::lround(source_width * scale))); target_height = std::max(1, static_cast(std::lround(source_height * scale))); } +#if NATIVEAPI_GTK4 + if (target_width == scaled_width && target_height == scaled_height && + gtk_image_get_paintable(GTK_IMAGE(widget)) != nullptr) { + return; + } + GdkPixbuf* src = pixbuf; + GdkPixbuf* scaled = nullptr; + if (target_width != source_width || target_height != source_height) { + scaled = gdk_pixbuf_scale_simple(pixbuf, target_width, target_height, GDK_INTERP_BILINEAR); + if (!scaled) { + return; + } + src = scaled; + } + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + GdkTexture* texture = gdk_texture_new_for_pixbuf(src); + G_GNUC_END_IGNORE_DEPRECATIONS + if (texture) { + gtk_image_set_from_paintable(GTK_IMAGE(widget), GDK_PAINTABLE(texture)); + g_object_unref(texture); + } + if (scaled) { + g_object_unref(scaled); + } +#else if (target_width == scaled_width && target_height == scaled_height && gtk_image_get_pixbuf(GTK_IMAGE(widget)) != nullptr) { return; @@ -430,6 +563,7 @@ void View::Impl::Platform::ScaleImage(int width, int height) { gtk_image_set_from_pixbuf(GTK_IMAGE(widget), scaled); g_object_unref(scaled); } +#endif scaled_width = target_width; scaled_height = target_height; } @@ -453,10 +587,18 @@ void View::Impl::Platform::ReplaceWidget(GtkWidget* replacement, } GtkWidget* old = widget; const bool had_focus = old && FocusWidget() && gtk_widget_is_focus(FocusWidget()); +#if NATIVEAPI_GTK4 + const bool had_size_allocate = resize_tick_id != 0; + if (old && resize_tick_id) { + gtk_widget_remove_tick_callback(old, resize_tick_id); + resize_tick_id = 0; + } +#else const bool had_size_allocate = size_allocate_id != 0; if (old) { DisconnectSignal(old, size_allocate_id); } +#endif if (relayout_source_id) { g_source_remove(relayout_source_id); relayout_source_id = 0; @@ -468,6 +610,7 @@ void View::Impl::Platform::ReplaceWidget(GtkWidget* replacement, placeholder_label = nullptr; UnhookControl(); if (css_provider) { + G_GNUC_BEGIN_IGNORE_DEPRECATIONS if (placeholder_css_widget) { gtk_style_context_remove_provider(gtk_widget_get_style_context(placeholder_css_widget), GTK_STYLE_PROVIDER(css_provider)); @@ -478,6 +621,7 @@ void View::Impl::Platform::ReplaceWidget(GtkWidget* replacement, GTK_STYLE_PROVIDER(css_provider)); css_widget = nullptr; } + G_GNUC_END_IGNORE_DEPRECATIONS } g_object_ref_sink(replacement); @@ -489,9 +633,14 @@ void View::Impl::Platform::ReplaceWidget(GtkWidget* replacement, gtk_widget_set_size_request(replacement, request_width, request_height); gtk_widget_set_sensitive(replacement, gtk_widget_get_sensitive(old)); gtk_widget_set_visible(replacement, gtk_widget_get_visible(old)); +#if NATIVEAPI_GTK4 + const char* tooltip = gtk_widget_get_tooltip_text(old); + gtk_widget_set_tooltip_text(replacement, tooltip); +#else gchar* tooltip = gtk_widget_get_tooltip_text(old); gtk_widget_set_tooltip_text(replacement, tooltip); g_free(tooltip); +#endif const gchar* name = gtk_widget_get_name(old); gtk_widget_set_name(replacement, name); if (replacement_text_view) { @@ -506,6 +655,22 @@ void View::Impl::Platform::ReplaceWidget(GtkWidget* replacement, gtk_fixed_put(GTK_FIXED(parent), replacement, x, y); // Keep the z-order: whatever drew above the old widget goes back above // the replacement, which gtk_fixed_put has just appended. +#if NATIVEAPI_GTK4 + std::vector after; + bool after_old = false; + for (GtkWidget* s = gtk_widget_get_first_child(parent); s; + s = gtk_widget_get_next_sibling(s)) { + if (s == old) { + after_old = true; + } else if (after_old && s != replacement) { + after.push_back(s); + } + } + for (GtkWidget* sibling : after) { + MoveToEnd(parent, sibling); + } + RemoveFromParent(parent, old); +#else GList* children = gtk_container_get_children(GTK_CONTAINER(parent)); bool after_old = false; for (GList* it = children; it; it = it->next) { @@ -518,6 +683,7 @@ void View::Impl::Platform::ReplaceWidget(GtkWidget* replacement, } g_list_free(children); gtk_container_remove(GTK_CONTAINER(parent), old); +#endif } } @@ -584,7 +750,7 @@ View::Impl::~Impl() { } GtkWidget* parent = gtk_widget_get_parent(platform->widget); if (parent) { - gtk_container_remove(GTK_CONTAINER(parent), platform->widget); + RemoveFromParent(parent, platform->widget); } } platform.reset(); @@ -597,7 +763,7 @@ void* View::Impl::CreateNativeContainer() { return nullptr; } g_object_ref_sink(fixed); - gtk_widget_show(fixed); + gtk_widget_set_visible(fixed, TRUE); return fixed; } @@ -627,6 +793,18 @@ Rectangle View::Impl::GetNativeFrame() const { return Rectangle{0, 0, 0, 0}; } if (is_root) { +#if NATIVEAPI_GTK4 + int width = gtk_widget_get_width(widget); + int height = gtk_widget_get_height(widget); + if (!IsAllocated(widget)) { + width = 0; + height = 0; + GtkRoot* root = gtk_widget_get_root(widget); + if (root && GTK_IS_WINDOW(root)) { + gtk_window_get_default_size(GTK_WINDOW(root), &width, &height); + } + } +#else GtkAllocation allocation; gtk_widget_get_allocation(widget, &allocation); int width = allocation.width; @@ -640,6 +818,7 @@ Rectangle View::Impl::GetNativeFrame() const { gtk_window_get_size(GTK_WINDOW(toplevel), &width, &height); } } +#endif return Rectangle{0, 0, static_cast(width), static_cast(height)}; } int x = 0; @@ -649,6 +828,15 @@ Rectangle View::Impl::GetNativeFrame() const { int height = -1; gtk_widget_get_size_request(widget, &width, &height); if (width < 0 || height < 0) { +#if NATIVEAPI_GTK4 + const bool allocated = IsAllocated(widget); + if (width < 0) { + width = allocated ? gtk_widget_get_width(widget) : 0; + } + if (height < 0) { + height = allocated ? gtk_widget_get_height(widget) : 0; + } +#else GtkAllocation allocation; gtk_widget_get_allocation(widget, &allocation); const bool allocated = IsAllocated(widget); @@ -658,6 +846,7 @@ Rectangle View::Impl::GetNativeFrame() const { if (height < 0) { height = allocated ? allocation.height : 0; } +#endif } return Rectangle{static_cast(x), static_cast(y), static_cast(width), static_cast(height)}; @@ -706,7 +895,7 @@ void View::Impl::AddNativeSubview(Impl& child, size_t index) { if (old_parent && old_parent != widget) { // The child's Platform holds its own reference, so the removal cannot // finalize it. - gtk_container_remove(GTK_CONTAINER(old_parent), child_widget); + RemoveFromParent(old_parent, child_widget); } if (gtk_widget_get_parent(child_widget) != widget) { // Position and size follow in the relayout the shared half runs next. @@ -729,7 +918,7 @@ void View::Impl::RemoveNativeSubview(Impl& child) { return; } // The child's Platform keeps its reference: the widget survives for reuse. - gtk_container_remove(GTK_CONTAINER(widget), child_widget); + RemoveFromParent(widget, child_widget); } void View::Impl::SetNativeVisible(bool is_visible) { @@ -771,9 +960,14 @@ void View::Impl::SetNativeAccessibilityLabel(const std::optional& l if (!target) { return; } +#if NATIVEAPI_GTK4 + gtk_accessible_update_property(GTK_ACCESSIBLE(target), GTK_ACCESSIBLE_PROPERTY_LABEL, + label ? label->c_str() : "", -1); +#else if (AtkObject* accessible = gtk_widget_get_accessible(target)) { atk_object_set_name(accessible, label ? label->c_str() : ""); } +#endif } void View::Impl::NativeFocus() { @@ -788,10 +982,17 @@ void View::Impl::NativeBlur() { if (!focusable || !IsNativeFocused()) { return; } +#if NATIVEAPI_GTK4 + GtkRoot* root = gtk_widget_get_root(focusable); + if (root && GTK_IS_WINDOW(root)) { + gtk_window_set_focus(GTK_WINDOW(root), nullptr); + } +#else GtkWidget* toplevel = gtk_widget_get_toplevel(focusable); if (toplevel && GTK_IS_WINDOW(toplevel)) { gtk_window_set_focus(GTK_WINDOW(toplevel), nullptr); } +#endif } bool View::Impl::IsNativeFocused() const { @@ -816,6 +1017,23 @@ void View::Impl::ObserveNativeResize(bool observe) { if (!widget) { return; } +#if NATIVEAPI_GTK4 + if (observe && platform->resize_tick_id == 0) { + platform->last_width = -1; + platform->last_height = -1; + platform->resize_tick_id = + gtk_widget_add_tick_callback(widget, OnRootResizeTick, this, nullptr); + } else if (!observe) { + if (platform->resize_tick_id) { + gtk_widget_remove_tick_callback(widget, platform->resize_tick_id); + platform->resize_tick_id = 0; + } + if (platform->relayout_source_id) { + g_source_remove(platform->relayout_source_id); + platform->relayout_source_id = 0; + } + } +#else if (observe && platform->size_allocate_id == 0) { platform->last_width = -1; platform->last_height = -1; @@ -830,6 +1048,7 @@ void View::Impl::ObserveNativeResize(bool observe) { platform->relayout_source_id = 0; } } +#endif } bool View::IsSupported() { @@ -879,15 +1098,23 @@ std::shared_ptr Window::GetContentView() const { return nullptr; } GtkWidget* window = GTK_WIDGET(native); +#if NATIVEAPI_GTK4 + GtkWidget* child = gtk_window_get_child(GTK_WINDOW(window)); +#else GtkWidget* child = gtk_bin_get_child(GTK_BIN(window)); +#endif GtkWidget* fixed = nullptr; if (!child) { fixed = gtk_fixed_new(); if (!fixed) { return nullptr; } +#if NATIVEAPI_GTK4 + gtk_window_set_child(GTK_WINDOW(window), fixed); +#else gtk_container_add(GTK_CONTAINER(window), fixed); gtk_widget_show(fixed); +#endif } else if (GTK_IS_FIXED(child)) { fixed = child; } else if (gpointer marked = g_object_get_data(G_OBJECT(child), kContentFixedKey)) { @@ -899,6 +1126,17 @@ std::shared_ptr Window::GetContentView() const { return nullptr; } g_object_ref(child); +#if NATIVEAPI_GTK4 + gtk_window_set_child(GTK_WINDOW(window), nullptr); + gtk_overlay_set_child(GTK_OVERLAY(overlay), child); + g_object_unref(child); + gtk_widget_set_halign(fixed, GTK_ALIGN_FILL); + gtk_widget_set_valign(fixed, GTK_ALIGN_FILL); + gtk_overlay_add_overlay(GTK_OVERLAY(overlay), fixed); + gtk_widget_set_can_target(fixed, FALSE); + g_object_set_data(G_OBJECT(overlay), kContentFixedKey, fixed); + gtk_window_set_child(GTK_WINDOW(window), overlay); +#else gtk_container_remove(GTK_CONTAINER(window), child); gtk_container_add(GTK_CONTAINER(overlay), child); g_object_unref(child); @@ -910,6 +1148,7 @@ std::shared_ptr Window::GetContentView() const { gtk_widget_show(fixed); gtk_widget_show(overlay); gtk_container_add(GTK_CONTAINER(window), overlay); +#endif } return ContentViewFor(fixed); } diff --git a/src/platform/linux/window_close_linux.cpp b/src/platform/linux/window_close_linux.cpp index 33216f08..94185bbf 100644 --- a/src/platform/linux/window_close_linux.cpp +++ b/src/platform/linux/window_close_linux.cpp @@ -1,4 +1,4 @@ -#include +#include "gtk_compat_linux.h" #include #include "../../window_close_dispatch.h" @@ -15,10 +15,22 @@ struct Policy : std::enable_shared_from_this { bool bypass = false; GSList* blocked = nullptr; bool Valid() const { - return !destroyed.load() && widget && state->IsAlive() && !gtk_widget_in_destruction(widget) && - gtk_widget_get_realized(widget) && gtk_widget_get_window(widget) && - !gdk_window_is_destroyed(gtk_widget_get_window(widget)) && - reinterpret_cast(g_object_get_data(G_OBJECT(widget), kId)) == id; + if (destroyed.load() || !widget || !state->IsAlive() || gtk_widget_in_destruction(widget) || + !gtk_widget_get_realized(widget)) { + return false; + } +#if NATIVEAPI_GTK4 + GdkSurface* surface = gtk_native_get_surface(GTK_NATIVE(widget)); + if (!surface || gdk_surface_is_destroyed(surface)) { + return false; + } +#else + GdkWindow* window = gtk_widget_get_window(widget); + if (!window || gdk_window_is_destroyed(window)) { + return false; + } +#endif + return reinterpret_cast(g_object_get_data(G_OBJECT(widget), kId)) == id; } void Restore(GArray* frame) { if (widget) @@ -67,6 +79,39 @@ std::shared_ptr Lookup(GtkWidget* widget) { auto* box = static_cast(g_object_get_data(G_OBJECT(widget), kPolicy)); return box ? *box : nullptr; } +#if NATIVEAPI_GTK4 +gboolean Gate(GtkWindow* /*window*/, gpointer data) { + auto policy = static_cast(data)->shared_from_this(); + if (policy->bypass) + return FALSE; + if (!policy->blocked) + return FALSE; + auto* frame = static_cast(policy->blocked->data); + policy->blocked = g_slist_delete_link(policy->blocked, policy->blocked); + policy->Restore(frame); + if (!policy->Valid()) + return TRUE; + try { + std::weak_ptr weak = policy; + (void)policy->state->Request([weak] { + auto policy = weak.lock(); + if (!policy || !policy->Valid()) + return; + auto keep = std::shared_ptr(GTK_WIDGET(g_object_ref(policy->widget)), + [](GtkWidget* target) { g_object_unref(target); }); + const bool previous = policy->bypass; + policy->bypass = true; + gboolean handled = FALSE; + g_signal_emit_by_name(keep.get(), "close-request", &handled); + policy->bypass = previous; + if (!handled && policy->Valid()) + gtk_window_destroy(GTK_WINDOW(keep.get())); + }); + } catch (...) { + } // A failed request is swallowed, never silently approved. + return TRUE; +} +#else gboolean Gate(GtkWidget* widget, GdkEvent* event, gpointer data) { auto policy = static_cast(data)->shared_from_this(); if (policy->bypass) @@ -99,6 +144,7 @@ gboolean Gate(GtkWidget* widget, GdkEvent* event, gpointer data) { } // A failed request is swallowed, never silently approved. return TRUE; } +#endif gboolean BeforeDelete(GSignalInvocationHint* hint, guint count, const GValue* values, gpointer) { if (!count) return TRUE; @@ -169,8 +215,13 @@ std::shared_ptr GetPolicy(void* native, WindowId id) { return nullptr; if (auto policy = Lookup(widget)) return policy->Valid() ? policy : nullptr; +#if NATIVEAPI_GTK4 + static gulong hook = g_signal_add_emission_hook(g_signal_lookup("close-request", GTK_TYPE_WINDOW), + 0, BeforeDelete, nullptr, nullptr); +#else static gulong hook = g_signal_add_emission_hook(g_signal_lookup("delete-event", GTK_TYPE_WIDGET), 0, BeforeDelete, nullptr, nullptr); +#endif if (!hook) return nullptr; auto policy = std::make_shared(); @@ -191,7 +242,11 @@ std::shared_ptr GetPolicy(void* native, WindowId id) { }); g_object_set_data_full(G_OBJECT(widget), kPolicy, new Box(policy), [](gpointer data) { delete static_cast(data); }); +#if NATIVEAPI_GTK4 + policy->gate = g_signal_connect(widget, "close-request", G_CALLBACK(Gate), policy.get()); +#else policy->gate = g_signal_connect(widget, "delete-event", G_CALLBACK(Gate), policy.get()); +#endif g_signal_connect(widget, "destroy", G_CALLBACK(Destroyed), policy.get()); return policy; } diff --git a/src/platform/linux/window_drag_session_linux.cpp b/src/platform/linux/window_drag_session_linux.cpp index dbf73146..88f781a4 100644 --- a/src/platform/linux/window_drag_session_linux.cpp +++ b/src/platform/linux/window_drag_session_linux.cpp @@ -1,11 +1,6 @@ #include "../../window_drag_session.h" -#include -#include - -#ifdef GDK_WINDOWING_WAYLAND -#include -#endif +#include "gtk_x11_compat_linux.h" namespace nativeapi { @@ -69,6 +64,56 @@ bool WindowDragSession::QueryPointer(Point& position, bool& primary_button_down) return false; } #endif +#if NATIVEAPI_GTK4 + bool button_down = false; +#ifdef GDK_WINDOWING_X11 + if (!GDK_IS_X11_DISPLAY(display)) { + return false; + } + ::Display* xdisplay = gdk_x11_display_get_xdisplay(display); + if (!xdisplay) { + return false; + } + ::Window root = DefaultRootWindow(xdisplay); + ::Window root_ret = 0; + ::Window child_ret = 0; + int root_x = 0; + int root_y = 0; + int win_x = 0; + int win_y = 0; + unsigned int mask = 0; + if (!XQueryPointer(xdisplay, root, &root_ret, &child_ret, &root_x, &root_y, &win_x, &win_y, + &mask)) { + return false; + } + int scale = 1; + if (GListModel* monitors = gdk_display_get_monitors(display)) { + const guint count = g_list_model_get_n_items(monitors); + for (guint i = 0; i < count; ++i) { + GdkMonitor* monitor = GDK_MONITOR(g_list_model_get_item(monitors, i)); + if (!monitor) { + continue; + } + GdkRectangle geom{}; + gdk_monitor_get_geometry(monitor, &geom); + const int s = gdk_monitor_get_scale_factor(monitor); + const int eff_s = s > 0 ? s : 1; + const int lx = root_x / eff_s; + const int ly = root_y / eff_s; + if (lx >= geom.x && lx < geom.x + geom.width && ly >= geom.y && ly < geom.y + geom.height) { + scale = eff_s; + g_object_unref(monitor); + break; + } + g_object_unref(monitor); + } + } + position = {static_cast(root_x) / scale, static_cast(root_y) / scale}; + button_down = (mask & Button1Mask) != 0; +#else + return false; +#endif +#else GdkSeat* seat = gdk_display_get_default_seat(display); GdkDevice* pointer = seat ? gdk_seat_get_pointer(seat) : nullptr; GdkWindow* root = gdk_get_default_root_window(); @@ -84,6 +129,7 @@ bool WindowDragSession::QueryPointer(Point& position, bool& primary_button_down) position = {static_cast(x), static_cast(y)}; bool button_down = (mask & GDK_BUTTON1_MASK) != 0; +#endif if (button_down) { pimpl_->seen_button_down_ = true; } else if (!pimpl_->seen_button_down_ && pimpl_->ticking_since_us_ != 0 && @@ -97,6 +143,9 @@ bool WindowDragSession::QueryPointer(Point& position, bool& primary_button_down) void WindowDragSession::MoveWindow(Window& window, Point cursor_position) const { const gint x = static_cast(cursor_position.x - anchor_.x); const gint y = static_cast(cursor_position.y - anchor_.y); +#if NATIVEAPI_GTK4 + window.SetPosition({static_cast(x), static_cast(y)}); +#else GtkWidget* widget = static_cast(window.GetNativeObject()); if (widget && GTK_IS_WINDOW(widget)) { // gtk_window_move() positions the frame, including decorations, which is @@ -105,6 +154,7 @@ void WindowDragSession::MoveWindow(Window& window, Point cursor_position) const return; } window.SetPosition({static_cast(x), static_cast(y)}); +#endif } } // namespace nativeapi diff --git a/src/platform/linux/window_linux.cpp b/src/platform/linux/window_linux.cpp index 7cd2f5a5..c021a172 100644 --- a/src/platform/linux/window_linux.cpp +++ b/src/platform/linux/window_linux.cpp @@ -13,28 +13,1104 @@ #include "../../window_property_dispatch.h" // Import GTK headers -#include #include #include -#include +#include "gtk_x11_compat_linux.h" +// Native shadow rendering is independent of Flutter and other content renderers. +#include "window_shadow_linux.h" + +namespace nativeapi { + +// Key to store/retrieve WindowId on GObjects +static const char* kWindowIdKey = "NativeAPIWindowId"; + +#if NATIVEAPI_GTK4 + +static void RefreshShadowInput(GtkWidget*) {} +static void ClearShadowInput(GtkWidget*) {} + +namespace { + +#ifdef GDK_WINDOWING_X11 +void SendNetWmState(GdkSurface* surface, bool add, const char* atom_name) { + if (!surface || !GDK_IS_X11_SURFACE(surface)) { + return; + } + GdkDisplay* display = gdk_surface_get_display(surface); + if (!display || !GDK_IS_X11_DISPLAY(display)) { + return; + } + ::Display* xdisplay = gdk_x11_display_get_xdisplay(display); + ::Window xid = gdk_x11_surface_get_xid(surface); + if (!xdisplay || !xid) { + return; + } + Atom wm_state = XInternAtom(xdisplay, "_NET_WM_STATE", False); + Atom prop = XInternAtom(xdisplay, atom_name, False); + XEvent xev{}; + xev.xclient.type = ClientMessage; + xev.xclient.window = xid; + xev.xclient.message_type = wm_state; + xev.xclient.format = 32; + xev.xclient.data.l[0] = add ? 1 : 0; // _NET_WM_STATE_ADD / _NET_WM_STATE_REMOVE + xev.xclient.data.l[1] = static_cast(prop); + xev.xclient.data.l[2] = 0; + xev.xclient.data.l[3] = 1; // normal application + XSendEvent(xdisplay, DefaultRootWindow(xdisplay), False, + SubstructureRedirectMask | SubstructureNotifyMask, &xev); + XFlush(xdisplay); +} + +bool HasX11NetWmState(GdkSurface* surface, const char* atom_name) { + if (!surface || !GDK_IS_X11_SURFACE(surface)) { + return false; + } + GdkDisplay* display = gdk_surface_get_display(surface); + if (!display || !GDK_IS_X11_DISPLAY(display)) { + return false; + } + ::Display* xdisplay = gdk_x11_display_get_xdisplay(display); + ::Window xid = gdk_x11_surface_get_xid(surface); + if (!xdisplay || !xid) { + return false; + } + Atom wm_state = XInternAtom(xdisplay, "_NET_WM_STATE", False); + Atom target = XInternAtom(xdisplay, atom_name, False); + Atom actual_type = 0; + int actual_format = 0; + unsigned long nitems = 0; + unsigned long bytes_after = 0; + unsigned char* data = nullptr; + bool found = false; + if (XGetWindowProperty(xdisplay, xid, wm_state, 0, 64, False, XA_ATOM, &actual_type, + &actual_format, &nitems, &bytes_after, &data) == Success && + data) { + auto* atoms = reinterpret_cast(data); + for (unsigned long i = 0; i < nitems; ++i) { + if (atoms[i] == target) { + found = true; + break; + } + } + XFree(data); + } + return found; +} + +void ApplyX11SizeHints(GtkWidget* widget, Size max_size, double aspect_ratio) { + if (!widget || !gtk_widget_get_realized(widget)) { + return; + } + GdkSurface* surface = gtk_native_get_surface(GTK_NATIVE(widget)); + if (!surface || !GDK_IS_X11_SURFACE(surface)) { + return; + } + GdkDisplay* display = gdk_surface_get_display(surface); + ::Display* xdisplay = gdk_x11_display_get_xdisplay(display); + ::Window xid = gdk_x11_surface_get_xid(surface); + if (!xdisplay || !xid) { + return; + } + XSizeHints* hints = XAllocSizeHints(); + if (!hints) { + return; + } + long supplied = 0; + XGetWMNormalHints(xdisplay, xid, hints, &supplied); + const int scale = std::max(1, gtk_widget_get_scale_factor(widget)); + if (max_size.width > 0 && max_size.height > 0) { + hints->flags |= PMaxSize; + hints->max_width = static_cast(std::lround(max_size.width * scale)); + hints->max_height = static_cast(std::lround(max_size.height * scale)); + } else { + hints->flags &= ~PMaxSize; + } + if (aspect_ratio > 0.0) { + hints->flags |= PAspect; + hints->min_aspect.x = static_cast(std::lround(aspect_ratio * 10000.0)); + hints->min_aspect.y = 10000; + hints->max_aspect.x = hints->min_aspect.x; + hints->max_aspect.y = 10000; + } else { + hints->flags &= ~PAspect; + } + XSetWMNormalHints(xdisplay, xid, hints); + XFree(hints); + XFlush(xdisplay); +} +#endif + +cairo_region_t* BuildPolygonRegion(const std::shared_ptr& shape) { + if (!shape || shape->GetPointCount() < 3) { + return nullptr; + } + double min_x = shape->GetPointAt(0).x; + double max_x = min_x; + double min_y = shape->GetPointAt(0).y; + double max_y = min_y; + for (size_t i = 1; i < shape->GetPointCount(); ++i) { + auto pt = shape->GetPointAt(i); + min_x = std::min(min_x, pt.x); + max_x = std::max(max_x, pt.x); + min_y = std::min(min_y, pt.y); + max_y = std::max(max_y, pt.y); + } + cairo_rectangle_int_t rect{ + static_cast(std::floor(min_x)), + static_cast(std::floor(min_y)), + std::max(1, static_cast(std::ceil(max_x - min_x))), + std::max(1, static_cast(std::ceil(max_y - min_y))), + }; + return cairo_region_create_rectangle(&rect); +} + +} // namespace + +class Window::Impl { + public: + explicit Impl(GtkWidget* widget) : widget_(widget) { + if (widget_) { + g_object_add_weak_pointer(G_OBJECT(widget_), reinterpret_cast(&widget_)); + map_handler_id_ = g_signal_connect(widget_, "map", G_CALLBACK(OnMap), this); + } + } + + ~Impl() { + if (bg_css_provider_) { + if (widget_ && GTK_IS_WIDGET(widget_)) { + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gtk_style_context_remove_provider(gtk_widget_get_style_context(widget_), + GTK_STYLE_PROVIDER(bg_css_provider_)); + G_GNUC_END_IGNORE_DEPRECATIONS + } + g_object_unref(bg_css_provider_); + bg_css_provider_ = nullptr; + } + if (widget_) { + if (map_handler_id_ && g_signal_handler_is_connected(widget_, map_handler_id_)) { + g_signal_handler_disconnect(widget_, map_handler_id_); + } + g_object_remove_weak_pointer(G_OBJECT(widget_), reinterpret_cast(&widget_)); + } + } + + GdkSurface* Surface() const { + if (!widget_ || !gtk_widget_get_realized(widget_)) { + return nullptr; + } + return gtk_native_get_surface(GTK_NATIVE(widget_)); + } + + void ApplyPendingOnMap() { + GdkSurface* surface = Surface(); + if (!surface) { + return; + } +#ifdef GDK_WINDOWING_X11 + if (has_pending_position_ && GDK_IS_X11_SURFACE(surface)) { + GdkDisplay* display = gdk_surface_get_display(surface); + ::Display* xdisplay = gdk_x11_display_get_xdisplay(display); + ::Window xid = gdk_x11_surface_get_xid(surface); + const int scale = std::max(1, gtk_widget_get_scale_factor(widget_)); + if (xdisplay && xid) { + XMoveWindow(xdisplay, xid, static_cast(std::lround(pending_position_.x * scale)), + static_cast(std::lround(pending_position_.y * scale))); + XFlush(xdisplay); + } + has_pending_position_ = false; + } + if (always_on_top_) SendNetWmState(surface, true, "_NET_WM_STATE_ABOVE"); + if (always_on_bottom_) SendNetWmState(surface, true, "_NET_WM_STATE_BELOW"); + if (visible_on_all_workspaces_) SendNetWmState(surface, true, "_NET_WM_STATE_STICKY"); + if (!visible_in_taskbar_) SendNetWmState(surface, true, "_NET_WM_STATE_SKIP_TASKBAR"); + if (max_size_.width > 0 || aspect_ratio_ > 0.0) { + ApplyX11SizeHints(widget_, max_size_, aspect_ratio_); + } +#endif + ApplyInputRegion(); + } + + void ApplyInputRegion() { + GdkSurface* surface = Surface(); + if (!surface) { + return; + } + if (ignore_mouse_events_) { + cairo_region_t* empty = cairo_region_create(); + gdk_surface_set_input_region(surface, empty); + cairo_region_destroy(empty); + } else if (input_shape_) { + if (cairo_region_t* region = BuildPolygonRegion(input_shape_)) { + gdk_surface_set_input_region(surface, region); + cairo_region_destroy(region); + } + } else { + gdk_surface_set_input_region(surface, nullptr); + } + } + + static void OnMap(GtkWidget*, gpointer data) { + static_cast(data)->ApplyPendingOnMap(); + } + + GtkWidget* widget_ = nullptr; + gulong map_handler_id_ = 0; + GtkCssProvider* bg_css_provider_ = nullptr; + + Size min_size_{0, 0}; + Size max_size_{0, 0}; + double aspect_ratio_ = 0.0; + Point pending_position_{0, 0}; + bool has_pending_position_ = false; + + bool movable_ = true; + bool minimizable_ = true; + bool maximizable_ = true; + bool full_screenable_ = true; + bool control_buttons_visible_ = true; + bool always_on_top_ = false; + bool always_on_bottom_ = false; + bool non_activating_ = false; + bool focusable_ = true; + bool visible_on_all_workspaces_ = false; + bool visible_in_taskbar_ = true; + bool ignore_mouse_events_ = false; + bool forward_mouse_events_ = false; + bool has_shadow_ = true; + bool keyboard_grabbed_ = false; + TitleBarStyle title_bar_style_ = TitleBarStyle::Normal; + Color background_color_{0, 0, 0, 0}; + std::shared_ptr shape_; + std::shared_ptr input_shape_; +}; + +static void RefreshGtk4Properties(GtkWidget* widget, GParamSpec*, gpointer) { + if (!widget || !GTK_IS_WINDOW(widget) || gtk_widget_in_destruction(widget)) { + return; + } + Window wrapper(static_cast(widget)); + detail::WindowPropertyDispatch::Refresh(wrapper); + detail::WindowPropertyDispatch::RefreshOcclusion(wrapper); +} + +static void ObserveGtk4WindowProperties(GtkWidget* widget) { + static const char* kObservedKey = "NativeAPIGtk4PropertiesObserved"; + if (!widget || !GTK_IS_WINDOW(widget) || g_object_get_data(G_OBJECT(widget), kObservedKey)) { + return; + } + g_object_set_data(G_OBJECT(widget), kObservedKey, GINT_TO_POINTER(1)); + for (const char* prop : {"notify::title", "notify::resizable", "notify::decorated", + "notify::deletable", "notify::visible", "notify::maximized", + "notify::fullscreened", "notify::transient-for", "notify::opacity"}) { + g_signal_connect(widget, prop, G_CALLBACK(RefreshGtk4Properties), nullptr); + } +} + +Window::Window() : Window(nullptr) {} + +Window::Window(void* native_window) { + if (!gdk_display_get_default()) { + linux_gtk::InitCheck(); + } + GtkWidget* widget = nullptr; + if (native_window && GTK_IS_WINDOW(native_window)) { + widget = GTK_WIDGET(native_window); + } else if (gdk_display_get_default()) { + widget = gtk_window_new(); + if (widget) { + gtk_window_set_default_size(GTK_WINDOW(widget), 800, 600); + } + } + + if (widget) { + gpointer existing_id = g_object_get_data(G_OBJECT(widget), kWindowIdKey); + if (!existing_id) { + WindowId id = IdAllocator::Allocate(); + if (id != IdAllocator::kInvalidId) { + g_object_set_data(G_OBJECT(widget), kWindowIdKey, + reinterpret_cast(static_cast(id))); + } + } + } + + pimpl_ = std::make_unique(widget); + ObserveGtk4WindowProperties(widget); + detail::WindowPropertyDispatch::Refresh(*this); + detail::WindowPropertyDispatch::RefreshOcclusion(*this); +} + +Window::~Window() { ShutdownEmitter(); } + +WindowNumber Window::GetNativeNumber() const { return 0; } + +WindowId Window::GetId() const { + if (pimpl_->widget_) { + gpointer data = g_object_get_data(G_OBJECT(pimpl_->widget_), kWindowIdKey); + if (data) { + return static_cast(reinterpret_cast(data)); + } + } + return IdAllocator::kInvalidId; +} + +void Window::Focus() { + if (pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_)) { + gtk_window_present(GTK_WINDOW(pimpl_->widget_)); + } +} + +void Window::Blur() { + // GTK 4 / Wayland does not provide a direct window blur operation. +} + +bool Window::IsFocused() const { + return pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_) && + gtk_window_is_active(GTK_WINDOW(pimpl_->widget_)) != FALSE; +} + +void Window::Show() { + if (!pimpl_->widget_) return; + if (pimpl_->non_activating_ || !pimpl_->focusable_) { + gtk_widget_set_visible(pimpl_->widget_, TRUE); + } else { + gtk_window_present(GTK_WINDOW(pimpl_->widget_)); + } +} + +void Window::ShowInactive() { + if (pimpl_->widget_) { + gtk_widget_set_visible(pimpl_->widget_, TRUE); + } +} + +void Window::Hide() { + if (pimpl_->widget_) { + gtk_widget_set_visible(pimpl_->widget_, FALSE); + } +} + +bool Window::IsVisible() const { + return pimpl_->widget_ && gtk_widget_get_visible(pimpl_->widget_) != FALSE; +} + +WindowOcclusionState Window::GetOcclusionState() const { + if (!IsVisible() || IsMinimized()) { + return WindowOcclusionState::Occluded; + } + return WindowOcclusionState::Visible; +} + +bool Window::IsOcclusionStateSupported() { return false; } + +void Window::Maximize() { + if (pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_) && pimpl_->maximizable_) { + gtk_window_maximize(GTK_WINDOW(pimpl_->widget_)); + } +} + +void Window::Unmaximize() { + if (pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_)) { + gtk_window_unmaximize(GTK_WINDOW(pimpl_->widget_)); + } +} + +bool Window::IsMaximized() const { + return pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_) && + gtk_window_is_maximized(GTK_WINDOW(pimpl_->widget_)) != FALSE; +} + +void Window::Minimize() { + if (pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_) && pimpl_->minimizable_) { + gtk_window_minimize(GTK_WINDOW(pimpl_->widget_)); + } +} + +void Window::Restore() { + if (!pimpl_->widget_ || !GTK_IS_WINDOW(pimpl_->widget_)) return; + if (IsFullScreen()) { + gtk_window_unfullscreen(GTK_WINDOW(pimpl_->widget_)); + } + if (IsMaximized()) { + gtk_window_unmaximize(GTK_WINDOW(pimpl_->widget_)); + } + gtk_window_present(GTK_WINDOW(pimpl_->widget_)); +} + +bool Window::IsMinimized() const { + GdkSurface* surface = pimpl_->Surface(); + if (!surface || !GDK_IS_TOPLEVEL(surface)) { + return false; + } + return (gdk_toplevel_get_state(GDK_TOPLEVEL(surface)) & GDK_TOPLEVEL_STATE_MINIMIZED) != 0; +} + +void Window::SetFullScreen(bool is_full_screen) { + if (!pimpl_->widget_ || !GTK_IS_WINDOW(pimpl_->widget_)) return; + if (is_full_screen) { + if (pimpl_->full_screenable_) { + gtk_window_fullscreen(GTK_WINDOW(pimpl_->widget_)); + } + } else { + gtk_window_unfullscreen(GTK_WINDOW(pimpl_->widget_)); + } +} + +bool Window::IsFullScreen() const { + return pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_) && + gtk_window_is_fullscreen(GTK_WINDOW(pimpl_->widget_)) != FALSE; +} + +void Window::SetBounds(Rectangle bounds) { + SetPosition({bounds.x, bounds.y}); + SetSize({bounds.width, bounds.height}, false); +} + +Rectangle Window::GetBounds() const { + Point pos = GetPosition(); + Size size = GetSize(); + return {pos.x, pos.y, size.width, size.height}; +} + +void Window::SetSize(Size size, bool /*animate*/) { + if (!pimpl_->widget_ || !GTK_IS_WINDOW(pimpl_->widget_)) return; + const int w = std::max(1, static_cast(std::lround(size.width))); + const int h = std::max(1, static_cast(std::lround(size.height))); + linux_shadow::NoteRequestedSize(pimpl_->widget_, w, h); + gtk_window_set_default_size(GTK_WINDOW(pimpl_->widget_), w, h); +} + +Size Window::GetSize() const { + if (!pimpl_->widget_ || !GTK_IS_WINDOW(pimpl_->widget_)) { + return {0, 0}; + } + int w = gtk_widget_get_width(pimpl_->widget_); + int h = gtk_widget_get_height(pimpl_->widget_); + if (w <= 0 || h <= 0) { + gtk_window_get_default_size(GTK_WINDOW(pimpl_->widget_), &w, &h); + } + return {static_cast(std::max(0, w)), static_cast(std::max(0, h))}; +} + +void Window::SetContentSize(Size size) { SetSize(size, false); } + +Size Window::GetContentSize() const { return GetSize(); } + +void Window::SetContentBounds(Rectangle bounds) { SetBounds(bounds); } + +Rectangle Window::GetContentBounds() const { return GetBounds(); } + +void Window::SetMinimumSize(Size size) { + pimpl_->min_size_ = size; + if (pimpl_->widget_) { + const int w = size.width > 0 ? static_cast(std::lround(size.width)) : -1; + const int h = size.height > 0 ? static_cast(std::lround(size.height)) : -1; + gtk_widget_set_size_request(pimpl_->widget_, w, h); + } +} + +Size Window::GetMinimumSize() const { return pimpl_->min_size_; } + +void Window::SetMaximumSize(Size size) { + pimpl_->max_size_ = size; +#ifdef GDK_WINDOWING_X11 + ApplyX11SizeHints(pimpl_->widget_, pimpl_->max_size_, pimpl_->aspect_ratio_); +#endif +} + +Size Window::GetMaximumSize() const { return pimpl_->max_size_; } + +void Window::SetAspectRatio(double aspect_ratio) { + pimpl_->aspect_ratio_ = aspect_ratio > 0.0 ? aspect_ratio : 0.0; +#ifdef GDK_WINDOWING_X11 + ApplyX11SizeHints(pimpl_->widget_, pimpl_->max_size_, pimpl_->aspect_ratio_); +#endif +} + +double Window::GetAspectRatio() const { return pimpl_->aspect_ratio_; } + +void Window::SetResizable(bool is_resizable) { + if (pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_)) { + gtk_window_set_resizable(GTK_WINDOW(pimpl_->widget_), is_resizable ? TRUE : FALSE); + } +} + +bool Window::IsResizable() const { + return pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_) && + gtk_window_get_resizable(GTK_WINDOW(pimpl_->widget_)) != FALSE; +} + +void Window::SetMovable(bool is_movable) { pimpl_->movable_ = is_movable; } +bool Window::IsMovable() const { return pimpl_->movable_; } + +void Window::SetMinimizable(bool is_minimizable) { + pimpl_->minimizable_ = is_minimizable; + if (pimpl_->widget_) { + g_object_set_data(G_OBJECT(pimpl_->widget_), "NativeAPIGtk4Minimizable", + GINT_TO_POINTER(is_minimizable ? 1 : 2)); + } + detail::WindowPropertyDispatch::Refresh(*this); +} +bool Window::IsMinimizable() const { + if (pimpl_->widget_) { + int v = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(pimpl_->widget_), "NativeAPIGtk4Minimizable")); + if (v != 0) return v == 1; + } + return pimpl_->minimizable_; +} + +void Window::SetMaximizable(bool is_maximizable) { + pimpl_->maximizable_ = is_maximizable; + if (pimpl_->widget_) { + g_object_set_data(G_OBJECT(pimpl_->widget_), "NativeAPIGtk4Maximizable", + GINT_TO_POINTER(is_maximizable ? 1 : 2)); + } + detail::WindowPropertyDispatch::Refresh(*this); +} +bool Window::IsMaximizable() const { + if (pimpl_->widget_) { + int v = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(pimpl_->widget_), "NativeAPIGtk4Maximizable")); + if (v != 0) return v == 1; + } + return pimpl_->maximizable_; +} + +void Window::SetFullScreenable(bool is_full_screenable) { + pimpl_->full_screenable_ = is_full_screenable; +} +bool Window::IsFullScreenable() const { return pimpl_->full_screenable_; } + +void Window::SetClosable(bool is_closable) { + if (pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_)) { + gtk_window_set_deletable(GTK_WINDOW(pimpl_->widget_), is_closable ? TRUE : FALSE); + } +} + +bool Window::IsClosable() const { + return pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_) && + gtk_window_get_deletable(GTK_WINDOW(pimpl_->widget_)) != FALSE; +} + +void Window::SetWindowControlButtonsVisible(bool is_visible) { + pimpl_->control_buttons_visible_ = is_visible; + if (pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_)) { + GtkWidget* titlebar = gtk_window_get_titlebar(GTK_WINDOW(pimpl_->widget_)); + if (titlebar && GTK_IS_HEADER_BAR(titlebar)) { + gtk_header_bar_set_show_title_buttons(GTK_HEADER_BAR(titlebar), is_visible ? TRUE : FALSE); + } + } +} + +bool Window::IsWindowControlButtonsVisible() const { return pimpl_->control_buttons_visible_; } + +void Window::SetAlwaysOnTop(bool is_always_on_top) { + pimpl_->always_on_top_ = is_always_on_top; + if (is_always_on_top) { + pimpl_->always_on_bottom_ = false; + } + if (pimpl_->widget_) { + g_object_set_data(G_OBJECT(pimpl_->widget_), "NativeAPIGtk4AlwaysOnTop", + GINT_TO_POINTER(is_always_on_top ? 1 : 2)); + if (is_always_on_top) { + g_object_set_data(G_OBJECT(pimpl_->widget_), "NativeAPIGtk4AlwaysOnBottom", + GINT_TO_POINTER(2)); + } + } #ifdef GDK_WINDOWING_X11 -#include -#include -#undef None // Xlib macro conflicts with VisualEffect::None. + if (GdkSurface* surface = pimpl_->Surface()) { + SendNetWmState(surface, is_always_on_top, "_NET_WM_STATE_ABOVE"); + if (is_always_on_top) { + SendNetWmState(surface, false, "_NET_WM_STATE_BELOW"); + } + } #endif + detail::WindowPropertyDispatch::Refresh(*this); +} -#ifdef GDK_WINDOWING_WAYLAND -#include +bool Window::IsAlwaysOnTop() const { +#ifdef GDK_WINDOWING_X11 + if (GdkSurface* surface = pimpl_->Surface(); surface && GDK_IS_X11_SURFACE(surface)) { + return HasX11NetWmState(surface, "_NET_WM_STATE_ABOVE"); + } #endif + if (pimpl_->widget_) { + int v = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(pimpl_->widget_), "NativeAPIGtk4AlwaysOnTop")); + if (v != 0) return v == 1; + } + return pimpl_->always_on_top_; +} -// Native shadow rendering is independent of Flutter and other content renderers. -#include "window_shadow_linux.h" +void Window::SetAlwaysOnBottom(bool is_always_on_bottom) { + pimpl_->always_on_bottom_ = is_always_on_bottom; + if (is_always_on_bottom) { + pimpl_->always_on_top_ = false; + } + if (pimpl_->widget_) { + g_object_set_data(G_OBJECT(pimpl_->widget_), "NativeAPIGtk4AlwaysOnBottom", + GINT_TO_POINTER(is_always_on_bottom ? 1 : 2)); + if (is_always_on_bottom) { + g_object_set_data(G_OBJECT(pimpl_->widget_), "NativeAPIGtk4AlwaysOnTop", + GINT_TO_POINTER(2)); + } + } +#ifdef GDK_WINDOWING_X11 + if (GdkSurface* surface = pimpl_->Surface()) { + SendNetWmState(surface, is_always_on_bottom, "_NET_WM_STATE_BELOW"); + if (is_always_on_bottom) { + SendNetWmState(surface, false, "_NET_WM_STATE_ABOVE"); + } + } +#endif + detail::WindowPropertyDispatch::Refresh(*this); +} -namespace nativeapi { +bool Window::IsAlwaysOnBottom() const { +#ifdef GDK_WINDOWING_X11 + if (GdkSurface* surface = pimpl_->Surface(); surface && GDK_IS_X11_SURFACE(surface)) { + return HasX11NetWmState(surface, "_NET_WM_STATE_BELOW"); + } +#endif + if (pimpl_->widget_) { + int v = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(pimpl_->widget_), "NativeAPIGtk4AlwaysOnBottom")); + if (v != 0) return v == 1; + } + return pimpl_->always_on_bottom_; +} + +bool Window::SetParentWindow(std::shared_ptr parent) { + if (!pimpl_->widget_ || !GTK_IS_WINDOW(pimpl_->widget_)) { + return false; + } + if (!parent) { + gtk_window_set_transient_for(GTK_WINDOW(pimpl_->widget_), nullptr); + return true; + } + GtkWidget* parent_widget = static_cast(parent->GetNativeObject()); + if (!parent_widget || !GTK_IS_WINDOW(parent_widget) || parent_widget == pimpl_->widget_) { + return false; + } + gtk_window_set_transient_for(GTK_WINDOW(pimpl_->widget_), GTK_WINDOW(parent_widget)); + return true; +} + +std::shared_ptr Window::GetParentWindow() const { + if (!pimpl_->widget_ || !GTK_IS_WINDOW(pimpl_->widget_)) { + return nullptr; + } + GtkWindow* parent = gtk_window_get_transient_for(GTK_WINDOW(pimpl_->widget_)); + if (!parent) { + return nullptr; + } + gpointer data = g_object_get_data(G_OBJECT(parent), kWindowIdKey); + if (data) { + WindowId id = static_cast(reinterpret_cast(data)); + if (auto found = WindowManager::GetInstance().Get(id)) { + return found; + } + } + return std::make_shared(static_cast(parent)); +} + +void Window::SetNonActivating(bool is_non_activating) { + pimpl_->non_activating_ = is_non_activating; +} +bool Window::IsNonActivating() const { return pimpl_->non_activating_; } + +void Window::SetPosition(Point point) { + pimpl_->pending_position_ = point; + pimpl_->has_pending_position_ = true; +#ifdef GDK_WINDOWING_X11 + if (GdkSurface* surface = pimpl_->Surface(); surface && GDK_IS_X11_SURFACE(surface)) { + GdkDisplay* display = gdk_surface_get_display(surface); + ::Display* xdisplay = gdk_x11_display_get_xdisplay(display); + ::Window xid = gdk_x11_surface_get_xid(surface); + const int scale = std::max(1, gtk_widget_get_scale_factor(pimpl_->widget_)); + if (xdisplay && xid) { + XMoveWindow(xdisplay, xid, static_cast(std::lround(point.x * scale)), + static_cast(std::lround(point.y * scale))); + XFlush(xdisplay); + pimpl_->has_pending_position_ = false; + } + } +#endif +} + +Point Window::GetPosition() const { +#ifdef GDK_WINDOWING_X11 + if (GdkSurface* surface = pimpl_->Surface(); surface && GDK_IS_X11_SURFACE(surface)) { + GdkDisplay* display = gdk_surface_get_display(surface); + ::Display* xdisplay = gdk_x11_display_get_xdisplay(display); + ::Window xid = gdk_x11_surface_get_xid(surface); + if (xdisplay && xid) { + int rx = 0; + int ry = 0; + ::Window child = 0; + if (XTranslateCoordinates(xdisplay, xid, DefaultRootWindow(xdisplay), 0, 0, &rx, &ry, + &child)) { + const int scale = std::max(1, gtk_widget_get_scale_factor(pimpl_->widget_)); + return {static_cast(rx) / scale, static_cast(ry) / scale}; + } + } + } +#endif + return pimpl_->has_pending_position_ ? pimpl_->pending_position_ : Point{0.0, 0.0}; +} + +void Window::Center() { + GdkDisplay* display = gdk_display_get_default(); + if (!display) return; + GListModel* monitors = gdk_display_get_monitors(display); + if (!monitors || g_list_model_get_n_items(monitors) == 0) return; + GdkMonitor* monitor = GDK_MONITOR(g_list_model_get_item(monitors, 0)); + if (!monitor) return; + GdkRectangle geom{}; + gdk_monitor_get_geometry(monitor, &geom); + g_object_unref(monitor); + Size sz = GetSize(); + SetPosition({geom.x + (geom.width - sz.width) / 2.0, geom.y + (geom.height - sz.height) / 2.0}); +} + +void Window::SetTitle(std::string title) { + if (pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_)) { + gtk_window_set_title(GTK_WINDOW(pimpl_->widget_), title.c_str()); + } +} + +std::string Window::GetTitle() const { + if (pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_)) { + const char* title = gtk_window_get_title(GTK_WINDOW(pimpl_->widget_)); + return title ? title : ""; + } + return ""; +} + +bool Window::SetFrameless(bool is_frameless) { + if (!pimpl_->widget_ || !GTK_IS_WINDOW(pimpl_->widget_)) { + return false; + } + gtk_window_set_decorated(GTK_WINDOW(pimpl_->widget_), is_frameless ? FALSE : TRUE); + return true; +} + +bool Window::IsFrameless() const { + return pimpl_->widget_ && GTK_IS_WINDOW(pimpl_->widget_) && + gtk_window_get_decorated(GTK_WINDOW(pimpl_->widget_)) == FALSE; +} + +void Window::SetTitleBarStyle(TitleBarStyle style) { + pimpl_->title_bar_style_ = style; + if (!pimpl_->widget_ || !GTK_IS_WINDOW(pimpl_->widget_)) return; + g_object_set_data(G_OBJECT(pimpl_->widget_), "NativeAPIGtk4TitleBarStyle", + GINT_TO_POINTER(static_cast(style) + 1)); + if (style == TitleBarStyle::Hidden) { + gtk_window_set_decorated(GTK_WINDOW(pimpl_->widget_), FALSE); + } else { + gtk_window_set_decorated(GTK_WINDOW(pimpl_->widget_), TRUE); + } + detail::WindowPropertyDispatch::Refresh(*this); +} + +TitleBarStyle Window::GetTitleBarStyle() const { + if (pimpl_->widget_) { + int v = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(pimpl_->widget_), "NativeAPIGtk4TitleBarStyle")); + if (v != 0) return static_cast(v - 1); + } + return pimpl_->title_bar_style_; +} + +bool Window::SetContentUnderTitleBar(bool) { return false; } +bool Window::IsContentUnderTitleBar() const { return false; } +bool Window::SetContentProtection(bool) { return false; } +bool Window::IsContentProtected() const { return false; } +bool Window::IsContentProtectionSupported() { return false; } +bool Window::SetCornerPreference(WindowCornerPreference) { return false; } +WindowCornerPreference Window::GetCornerPreference() const { + return WindowCornerPreference::Default; +} +bool Window::IsCornerPreferenceSupported() { return false; } +bool Window::IsContentUnderTitleBarSupported() { return false; } + +void Window::SetHasShadow(bool has_shadow) { + pimpl_->has_shadow_ = has_shadow; + if (!pimpl_->widget_) return; + auto* state = linux_shadow::Ensure(pimpl_->widget_); + if (state) { + state->enabled = has_shadow; + linux_shadow::ApplyCss(pimpl_->widget_, state); + } +} + +bool Window::SetCustomShadow(std::shared_ptr shadow) { + if (!pimpl_->widget_) return false; + if (shadow) { + linux_shadow::Configure(pimpl_->widget_, shadow); + } else if (auto* state = linux_shadow::Get(pimpl_->widget_)) { + state->custom.reset(); + linux_shadow::ApplyCss(pimpl_->widget_, state); + } + return true; +} + +std::shared_ptr Window::GetCustomShadow() const { + auto* state = linux_shadow::Get(pimpl_->widget_); + return state ? state->custom : nullptr; +} + +bool Window::HasShadow() const { return pimpl_->has_shadow_; } + +void Window::SetOpacity(float opacity) { + if (pimpl_->widget_) { + gtk_widget_set_opacity(pimpl_->widget_, std::clamp(static_cast(opacity), 0.0, 1.0)); + } +} + +float Window::GetOpacity() const { + return pimpl_->widget_ ? static_cast(gtk_widget_get_opacity(pimpl_->widget_)) : 1.0f; +} + +bool Window::SetVisualEffect(VisualEffect effect) { return effect == VisualEffect::None; } +VisualEffect Window::GetVisualEffect() const { return VisualEffect::None; } +bool Window::IsVisualEffectSupported(VisualEffect effect) { return effect == VisualEffect::None; } + +void Window::SetBackgroundColor(const Color& color) { + pimpl_->background_color_ = color; + if (!pimpl_->widget_) return; + if (!pimpl_->bg_css_provider_) { + pimpl_->bg_css_provider_ = gtk_css_provider_new(); + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gtk_style_context_add_provider(gtk_widget_get_style_context(pimpl_->widget_), + GTK_STYLE_PROVIDER(pimpl_->bg_css_provider_), + GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); + G_GNUC_END_IGNORE_DEPRECATIONS + } + gchar alpha_buf[G_ASCII_DTOSTR_BUF_SIZE]; + g_ascii_formatd(alpha_buf, sizeof(alpha_buf), "%.3f", color.a / 255.0); + std::string css = "window { background-color: rgba(" + std::to_string(color.r) + "," + + std::to_string(color.g) + "," + std::to_string(color.b) + "," + alpha_buf + + "); background-image: none; }"; + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gtk_css_provider_load_from_data(pimpl_->bg_css_provider_, css.c_str(), -1); + G_GNUC_END_IGNORE_DEPRECATIONS +} + +Color Window::GetBackgroundColor() const { return pimpl_->background_color_; } + +void Window::SetVisibleOnAllWorkspaces(bool is_visible_on_all_workspaces) { + pimpl_->visible_on_all_workspaces_ = is_visible_on_all_workspaces; +#ifdef GDK_WINDOWING_X11 + if (GdkSurface* surface = pimpl_->Surface()) { + SendNetWmState(surface, is_visible_on_all_workspaces, "_NET_WM_STATE_STICKY"); + } +#endif +} + +bool Window::IsVisibleOnAllWorkspaces() const { +#ifdef GDK_WINDOWING_X11 + if (GdkSurface* surface = pimpl_->Surface(); surface && GDK_IS_X11_SURFACE(surface)) { + return HasX11NetWmState(surface, "_NET_WM_STATE_STICKY"); + } +#endif + return pimpl_->visible_on_all_workspaces_; +} + +void Window::SetVisibleInTaskbar(bool is_visible_in_taskbar) { + pimpl_->visible_in_taskbar_ = is_visible_in_taskbar; +#ifdef GDK_WINDOWING_X11 + if (GdkSurface* surface = pimpl_->Surface()) { + SendNetWmState(surface, !is_visible_in_taskbar, "_NET_WM_STATE_SKIP_TASKBAR"); + } +#endif +} + +bool Window::IsVisibleInTaskbar() const { +#ifdef GDK_WINDOWING_X11 + if (GdkSurface* surface = pimpl_->Surface(); surface && GDK_IS_X11_SURFACE(surface)) { + return !HasX11NetWmState(surface, "_NET_WM_STATE_SKIP_TASKBAR"); + } +#endif + return pimpl_->visible_in_taskbar_; +} + +bool Window::SetIgnoreMouseEvents(bool is_ignore_mouse_events, bool forward) { + pimpl_->ignore_mouse_events_ = is_ignore_mouse_events; + pimpl_->forward_mouse_events_ = is_ignore_mouse_events && forward; + pimpl_->ApplyInputRegion(); + return true; +} + +bool Window::IsIgnoreMouseEvents() const { return pimpl_->ignore_mouse_events_; } +bool Window::IsMouseMoveForwardingEnabled() const { return pimpl_->forward_mouse_events_; } +bool Window::IsMouseMoveForwardingSupported() { return false; } + +void Window::SetFocusable(bool is_focusable) { pimpl_->focusable_ = is_focusable; } +bool Window::IsFocusable() const { return pimpl_->focusable_; } + +bool Window::ShowSystemMenu(Point position) { + GdkSurface* surface = pimpl_->Surface(); + if (!surface || !GDK_IS_TOPLEVEL(surface)) { + return false; + } +#ifdef GDK_WINDOWING_X11 + if (GDK_IS_X11_SURFACE(surface)) { + GdkDisplay* display = gdk_surface_get_display(surface); + ::Display* xdisplay = gdk_x11_display_get_xdisplay(display); + ::Window xid = gdk_x11_surface_get_xid(surface); + if (xdisplay && xid) { + Atom atom = XInternAtom(xdisplay, "_GTK_SHOW_WINDOW_MENU", False); + const int scale = std::max(1, gtk_widget_get_scale_factor(pimpl_->widget_)); + Point origin = GetPosition(); + XEvent xev{}; + xev.xclient.type = ClientMessage; + xev.xclient.window = xid; + xev.xclient.message_type = atom; + xev.xclient.format = 32; + xev.xclient.data.l[0] = 0; + xev.xclient.data.l[1] = static_cast(std::lround((origin.x + position.x) * scale)); + xev.xclient.data.l[2] = static_cast(std::lround((origin.y + position.y) * scale)); + XSendEvent(xdisplay, DefaultRootWindow(xdisplay), False, + SubstructureRedirectMask | SubstructureNotifyMask, &xev); + XFlush(xdisplay); + return true; + } + } +#endif + return false; +} + +bool Window::IsSystemMenuSupported() { + return linux_gtk::IsX11Display(gdk_display_get_default()); +} + +bool Window::SetMaximizeButtonBounds(Rectangle) { return false; } +Rectangle Window::GetMaximizeButtonBounds() const { return {0, 0, 0, 0}; } +bool Window::IsMaximizeButtonBoundsSupported() { return false; } + +bool Window::PerformTitleBarDoubleClick() { + if (!pimpl_->widget_ || !GTK_IS_WINDOW(pimpl_->widget_) || !pimpl_->maximizable_) { + return false; + } + if (IsMaximized()) { + Unmaximize(); + } else { + Maximize(); + } + return true; +} + +void Window::StartDragging() { + GdkSurface* surface = pimpl_->Surface(); + if (!surface || !GDK_IS_TOPLEVEL(surface) || !pimpl_->movable_) return; + GdkDisplay* display = gdk_surface_get_display(surface); + GdkSeat* seat = display ? gdk_display_get_default_seat(display) : nullptr; + GdkDevice* pointer = seat ? gdk_seat_get_pointer(seat) : nullptr; + if (!pointer) return; + double x = 0.0; + double y = 0.0; + gdk_surface_get_device_position(surface, pointer, &x, &y, nullptr); + gdk_toplevel_begin_move(GDK_TOPLEVEL(surface), pointer, 1, x, y, GDK_CURRENT_TIME); +} + +void Window::StartResizing(ResizeEdge edge) { + GdkSurface* surface = pimpl_->Surface(); + if (!surface || !GDK_IS_TOPLEVEL(surface) || !IsResizable()) return; + GdkDisplay* display = gdk_surface_get_display(surface); + GdkSeat* seat = display ? gdk_display_get_default_seat(display) : nullptr; + GdkDevice* pointer = seat ? gdk_seat_get_pointer(seat) : nullptr; + if (!pointer) return; + GdkSurfaceEdge gdk_edge = GDK_SURFACE_EDGE_SOUTH_EAST; + switch (edge) { + case ResizeEdge::Top: gdk_edge = GDK_SURFACE_EDGE_NORTH; break; + case ResizeEdge::Bottom: gdk_edge = GDK_SURFACE_EDGE_SOUTH; break; + case ResizeEdge::Left: gdk_edge = GDK_SURFACE_EDGE_WEST; break; + case ResizeEdge::Right: gdk_edge = GDK_SURFACE_EDGE_EAST; break; + case ResizeEdge::TopLeft: gdk_edge = GDK_SURFACE_EDGE_NORTH_WEST; break; + case ResizeEdge::TopRight: gdk_edge = GDK_SURFACE_EDGE_NORTH_EAST; break; + case ResizeEdge::BottomLeft: gdk_edge = GDK_SURFACE_EDGE_SOUTH_WEST; break; + case ResizeEdge::BottomRight: gdk_edge = GDK_SURFACE_EDGE_SOUTH_EAST; break; + } + double x = 0.0; + double y = 0.0; + gdk_surface_get_device_position(surface, pointer, &x, &y, nullptr); + gdk_toplevel_begin_resize(GDK_TOPLEVEL(surface), gdk_edge, pointer, 1, x, y, GDK_CURRENT_TIME); +} + +void* Window::GetNativeObjectInternal() const { return pimpl_->widget_; } + +bool Window::IsShapeSupported() { return false; } + +bool Window::SetShape(std::shared_ptr shape) { + pimpl_->shape_ = std::move(shape); + if (pimpl_->widget_) { + linux_shadow::SetPolygon(pimpl_->widget_, pimpl_->shape_); + } + return false; +} + +bool Window::IsInputShapeSupported() { return true; } + +bool Window::SetInputShape(std::shared_ptr shape) { + pimpl_->input_shape_ = std::move(shape); + pimpl_->ApplyInputRegion(); + return true; +} + +bool Window::IsInputShaped() const { return pimpl_->input_shape_ != nullptr; } +bool Window::IsShaped() const { return pimpl_->shape_ != nullptr; } + +bool Window::SetMaximizedVertically(bool) { return false; } +bool Window::IsMaximizedVertically() const { return false; } +bool Window::IsVerticalMaximizeSupported() { return false; } +bool Window::Dock(WindowDockSide, double) { return false; } +bool Window::Undock() { return false; } +WindowDockSide Window::GetDockSide() const { return WindowDockSide::None; } +bool Window::IsDockingSupported() { return false; } +bool Window::AnimateBounds(Rectangle) { return false; } +bool Window::IsBoundsAnimationSupported() { return false; } +bool Window::SetVisibleOnFullScreen(bool) { return false; } +bool Window::IsVisibleOnFullScreen() const { return false; } +bool Window::IsVisibleOnFullScreenSupported() { return false; } + +bool Window::IsKeyboardGrabSupported() { + return linux_gtk::IsX11Display(gdk_display_get_default()); +} + +bool Window::GrabKeyboard() { +#ifdef GDK_WINDOWING_X11 + GdkSurface* surface = pimpl_->Surface(); + if (!surface || !GDK_IS_X11_SURFACE(surface)) return false; + GdkDisplay* display = gdk_surface_get_display(surface); + ::Display* xdisplay = gdk_x11_display_get_xdisplay(display); + ::Window xid = gdk_x11_surface_get_xid(surface); + if (!xdisplay || !xid) return false; + const int res = XGrabKeyboard(xdisplay, xid, False, GrabModeAsync, GrabModeAsync, CurrentTime); + XFlush(xdisplay); + pimpl_->keyboard_grabbed_ = (res == GrabSuccess); + return pimpl_->keyboard_grabbed_; +#else + return false; +#endif +} + +bool Window::UngrabKeyboard() { +#ifdef GDK_WINDOWING_X11 + GdkSurface* surface = pimpl_->Surface(); + if (!surface || !GDK_IS_X11_SURFACE(surface)) return false; + GdkDisplay* display = gdk_surface_get_display(surface); + ::Display* xdisplay = gdk_x11_display_get_xdisplay(display); + if (!xdisplay) return false; + XUngrabKeyboard(xdisplay, CurrentTime); + XFlush(xdisplay); + pimpl_->keyboard_grabbed_ = false; + return true; +#else + return false; +#endif +} + +bool Window::IsKeyboardGrabbed() const { return pimpl_->keyboard_grabbed_; } + +#else -// Key to store/retrieve WindowId on GObjects -static const char* kWindowIdKey = "NativeAPIWindowId"; static const char* kInputShapeKey = "NativeAPIInputShape"; static const char* kMouseInputPolicyKey = "NativeAPIMouseInputPolicy"; struct MouseInputPolicy { @@ -2988,6 +4064,8 @@ bool Window::IsKeyboardGrabbed() const { gdk_display_get_default_seat(gdk_window_get_display(surface)), surface); } +#endif + } // namespace nativeapi namespace nativeapi { diff --git a/src/platform/linux/window_manager_linux.cpp b/src/platform/linux/window_manager_linux.cpp index 48ae9cfa..aa0916c0 100644 --- a/src/platform/linux/window_manager_linux.cpp +++ b/src/platform/linux/window_manager_linux.cpp @@ -14,13 +14,608 @@ #include "../../window_registry.h" // Import GTK headers -#include -#include +#include "gtk_compat_linux.h" namespace nativeapi { // Key to store/retrieve WindowId on GObjects (must match window_linux.cpp) static const char* kWindowIdKey = "NativeAPIWindowId"; + +#if NATIVEAPI_GTK4 + +static std::unordered_map g_window_id_map; +static std::mutex g_map_mutex; + +static WindowId GetOrCreateWindowId(GtkWindow* gtk_window) { + if (!gtk_window || !GTK_IS_WINDOW(gtk_window)) { + return IdAllocator::kInvalidId; + } + gpointer data = g_object_get_data(G_OBJECT(gtk_window), kWindowIdKey); + if (data) { + WindowId id = static_cast(reinterpret_cast(data)); + std::lock_guard lock(g_map_mutex); + g_window_id_map[gtk_window] = id; + return id; + } + { + std::lock_guard lock(g_map_mutex); + auto it = g_window_id_map.find(gtk_window); + if (it != g_window_id_map.end()) { + return it->second; + } + } + WindowId new_id = IdAllocator::Allocate(); + if (new_id != IdAllocator::kInvalidId) { + g_object_set_data(G_OBJECT(gtk_window), kWindowIdKey, + reinterpret_cast(static_cast(new_id))); + std::lock_guard lock(g_map_mutex); + g_window_id_map[gtk_window] = new_id; + } + return new_id; +} + +static GtkWindow* FindGtkWindowById(WindowId id) { + std::lock_guard lock(g_map_mutex); + for (const auto& pair : g_window_id_map) { + if (pair.second == id) { + return pair.first; + } + } + return nullptr; +} + +struct TrackedWindow { + WindowId id = IdAllocator::kInvalidId; + bool active = false; + bool maximized = false; + bool fullscreened = false; + bool minimized = false; + bool shown = false; + int width = 0; + int height = 0; + int scale = 1; + GdkSurface* surface = nullptr; + std::vector window_handlers; + std::vector surface_handlers; +}; + +static std::map g_tracked_windows; +static gulong g_show_hook_id = 0; +static gulong g_hide_hook_id = 0; +static gulong g_toplevels_changed_id = 0; +static bool g_swizzle_installed = false; + +using WindowSignalFn = void (*)(void* impl, WindowId id, const char* event_type); +static WindowSignalFn g_window_signal_fn = nullptr; +static void* g_window_signal_context = nullptr; + +using WindowFocusChangedFn = void (*)(void* impl, WindowId id, bool focused); +static WindowFocusChangedFn g_focus_changed_fn = nullptr; +static void* g_focus_changed_context = nullptr; + +static void OnTrackedWindowDestroyed(gpointer, GObject* where_the_object_was) { + auto* win = reinterpret_cast(where_the_object_was); + WindowId closed_id = IdAllocator::kInvalidId; + bool was_shown = false; + auto it = g_tracked_windows.find(win); + if (it != g_tracked_windows.end()) { + closed_id = it->second.id; + was_shown = it->second.shown; + g_tracked_windows.erase(it); + } + { + std::lock_guard lock(g_map_mutex); + g_window_id_map.erase(win); + } + if (was_shown && closed_id != IdAllocator::kInvalidId && g_window_signal_fn && + g_window_signal_context) { + g_window_signal_fn(g_window_signal_context, closed_id, "closed"); + } +} + +static void OnGtk4WindowActiveChanged(GtkWindow* win, GParamSpec*, gpointer) { + auto it = g_tracked_windows.find(win); + if (it == g_tracked_windows.end()) return; + const bool active = gtk_window_is_active(win) != FALSE; + if (active == it->second.active) return; + it->second.active = active; + if (g_focus_changed_fn && g_focus_changed_context) { + g_focus_changed_fn(g_focus_changed_context, it->second.id, active); + } +} + +static void OnGtk4WindowMaximizedChanged(GtkWindow* win, GParamSpec*, gpointer) { + auto it = g_tracked_windows.find(win); + if (it == g_tracked_windows.end()) return; + const bool maximized = gtk_window_is_maximized(win) != FALSE; + if (maximized == it->second.maximized) return; + it->second.maximized = maximized; + if (g_window_signal_fn && g_window_signal_context) { + g_window_signal_fn(g_window_signal_context, it->second.id, maximized ? "maximized" : "restored"); + } +} + +static void OnGtk4WindowFullscreenedChanged(GtkWindow* win, GParamSpec*, gpointer) { + auto it = g_tracked_windows.find(win); + if (it == g_tracked_windows.end()) return; + const bool fs = gtk_window_is_fullscreen(win) != FALSE; + if (fs == it->second.fullscreened) return; + it->second.fullscreened = fs; + if (g_window_signal_fn && g_window_signal_context) { + g_window_signal_fn(g_window_signal_context, it->second.id, + fs ? "entered_full_screen" : "exited_full_screen"); + } +} + +static void OnGtk4WindowScaleChanged(GtkWidget* widget, GParamSpec*, gpointer) { + auto* win = GTK_WINDOW(widget); + auto it = g_tracked_windows.find(win); + if (it == g_tracked_windows.end()) return; + const int scale = gtk_widget_get_scale_factor(widget); + if (scale == it->second.scale) return; + it->second.scale = scale; + if (g_window_signal_fn && g_window_signal_context) { + g_window_signal_fn(g_window_signal_context, it->second.id, "scale_factor_changed"); + } +} + +static void OnGtk4SurfaceStateChanged(GdkToplevel* toplevel, GParamSpec*, gpointer data) { + auto* win = static_cast(data); + auto it = g_tracked_windows.find(win); + if (it == g_tracked_windows.end()) return; + const GdkToplevelState state = gdk_toplevel_get_state(toplevel); + const bool minimized = (state & GDK_TOPLEVEL_STATE_MINIMIZED) != 0; + if (minimized == it->second.minimized) return; + it->second.minimized = minimized; + if (g_window_signal_fn && g_window_signal_context) { + g_window_signal_fn(g_window_signal_context, it->second.id, minimized ? "minimized" : "restored"); + } +} + +static void OnGtk4SurfaceSizeChanged(GdkSurface* surface, GParamSpec*, gpointer data) { + auto* win = static_cast(data); + auto it = g_tracked_windows.find(win); + if (it == g_tracked_windows.end()) return; + const int w = gdk_surface_get_width(surface); + const int h = gdk_surface_get_height(surface); + if (w == it->second.width && h == it->second.height) return; + it->second.width = w; + it->second.height = h; + if (g_window_signal_fn && g_window_signal_context) { + g_window_signal_fn(g_window_signal_context, it->second.id, "resized"); + } +} + +static void AttachSurfaceHandlers(GtkWindow* win, TrackedWindow& info) { + GdkSurface* surface = gtk_native_get_surface(GTK_NATIVE(win)); + if (!surface || surface == info.surface) return; + info.surface = surface; + info.width = gdk_surface_get_width(surface); + info.height = gdk_surface_get_height(surface); + if (GDK_IS_TOPLEVEL(surface)) { + info.minimized = (gdk_toplevel_get_state(GDK_TOPLEVEL(surface)) & GDK_TOPLEVEL_STATE_MINIMIZED) != 0; + info.surface_handlers.push_back( + g_signal_connect(surface, "notify::state", G_CALLBACK(OnGtk4SurfaceStateChanged), win)); + } + info.surface_handlers.push_back( + g_signal_connect(surface, "notify::width", G_CALLBACK(OnGtk4SurfaceSizeChanged), win)); + info.surface_handlers.push_back( + g_signal_connect(surface, "notify::height", G_CALLBACK(OnGtk4SurfaceSizeChanged), win)); +} + +static void OnGtk4WindowMap(GtkWidget* widget, gpointer) { + auto* win = GTK_WINDOW(widget); + auto it = g_tracked_windows.find(win); + if (it == g_tracked_windows.end()) return; + AttachSurfaceHandlers(win, it->second); + if (!it->second.shown) { + it->second.shown = true; + if (g_window_signal_fn && g_window_signal_context) { + g_window_signal_fn(g_window_signal_context, it->second.id, "created"); + } + } +} + +static void TrackGtk4Window(GtkWindow* win, bool seed_existing) { + if (!win || !GTK_IS_WINDOW(win) || g_tracked_windows.count(win)) { + return; + } + TrackedWindow info; + info.id = GetOrCreateWindowId(win); + info.active = gtk_window_is_active(win) != FALSE; + info.maximized = gtk_window_is_maximized(win) != FALSE; + info.fullscreened = gtk_window_is_fullscreen(win) != FALSE; + info.scale = gtk_widget_get_scale_factor(GTK_WIDGET(win)); + info.shown = seed_existing && gtk_widget_get_mapped(GTK_WIDGET(win)) != FALSE; + info.window_handlers.push_back( + g_signal_connect(win, "notify::is-active", G_CALLBACK(OnGtk4WindowActiveChanged), nullptr)); + info.window_handlers.push_back( + g_signal_connect(win, "notify::maximized", G_CALLBACK(OnGtk4WindowMaximizedChanged), nullptr)); + info.window_handlers.push_back( + g_signal_connect(win, "notify::fullscreened", G_CALLBACK(OnGtk4WindowFullscreenedChanged), nullptr)); + info.window_handlers.push_back( + g_signal_connect(win, "notify::scale-factor", G_CALLBACK(OnGtk4WindowScaleChanged), nullptr)); + info.window_handlers.push_back( + g_signal_connect(win, "map", G_CALLBACK(OnGtk4WindowMap), nullptr)); + if (gtk_widget_get_realized(GTK_WIDGET(win))) { + AttachSurfaceHandlers(win, info); + } + g_tracked_windows.emplace(win, std::move(info)); + g_object_weak_ref(G_OBJECT(win), OnTrackedWindowDestroyed, nullptr); +} + +static void OnToplevelsChanged(GListModel* model, guint position, guint /*removed*/, guint added, + gpointer) { + for (guint i = 0; i < added; ++i) { + GtkWindow* win = GTK_WINDOW(g_list_model_get_item(model, position + i)); + if (win) { + TrackGtk4Window(win, false); + g_object_unref(win); + } + } +} + +static gboolean on_show_emission_hook(GSignalInvocationHint*, guint, const GValue* param_values, + gpointer) { + GtkWidget* widget = GTK_WIDGET(g_value_get_object(¶m_values[0])); + if (widget && GTK_IS_WINDOW(widget)) { + WindowId id = GetOrCreateWindowId(GTK_WINDOW(widget)); + if (id != IdAllocator::kInvalidId) { + WindowManager::GetInstance().HandleWillShow(id); + } + } + return TRUE; +} + +static gboolean on_hide_emission_hook(GSignalInvocationHint*, guint, const GValue* param_values, + gpointer) { + GtkWidget* widget = GTK_WIDGET(g_value_get_object(¶m_values[0])); + if (widget && GTK_IS_WINDOW(widget)) { + WindowId id = GetOrCreateWindowId(GTK_WINDOW(widget)); + if (id != IdAllocator::kInvalidId) { + WindowManager::GetInstance().HandleWillHide(id); + } + } + return TRUE; +} + +static void InstallGlobalSwizzling() { + if (g_swizzle_installed) return; + guint show_id = g_signal_lookup("show", GTK_TYPE_WIDGET); + guint hide_id = g_signal_lookup("hide", GTK_TYPE_WIDGET); + if (show_id && !g_show_hook_id) { + g_show_hook_id = g_signal_add_emission_hook(show_id, 0, on_show_emission_hook, nullptr, nullptr); + } + if (hide_id && !g_hide_hook_id) { + g_hide_hook_id = g_signal_add_emission_hook(hide_id, 0, on_hide_emission_hook, nullptr, nullptr); + } + g_swizzle_installed = true; +} + +static void RemoveShowHideHooks() { + guint show_id = g_signal_lookup("show", GTK_TYPE_WIDGET); + guint hide_id = g_signal_lookup("hide", GTK_TYPE_WIDGET); + if (g_show_hook_id && show_id) g_signal_remove_emission_hook(show_id, g_show_hook_id); + if (g_hide_hook_id && hide_id) g_signal_remove_emission_hook(hide_id, g_hide_hook_id); + g_show_hook_id = 0; + g_hide_hook_id = 0; + g_swizzle_installed = false; +} + +class WindowManager::Impl { + public: + Impl(WindowManager* manager) : manager_(manager) {} + ~Impl() = default; + + void StartEventListening() { + InstallGlobalSwizzling(); + g_focus_changed_context = this; + g_focus_changed_fn = [](void* impl, WindowId id, bool focused) { + static_cast(impl)->OnWindowFocusChanged(id, focused); + }; + g_window_signal_context = this; + g_window_signal_fn = [](void* impl, WindowId id, const char* event_type) { + static_cast(impl)->OnWindowSignal(id, event_type); + }; + + if (gdk_display_get_default()) { + GListModel* toplevels = gtk_window_get_toplevels(); + if (toplevels) { + if (!g_toplevels_changed_id) { + g_toplevels_changed_id = + g_signal_connect(toplevels, "items-changed", G_CALLBACK(OnToplevelsChanged), nullptr); + } + const guint n = g_list_model_get_n_items(toplevels); + for (guint i = 0; i < n; ++i) { + GtkWindow* win = GTK_WINDOW(g_list_model_get_item(toplevels, i)); + if (win) { + TrackGtk4Window(win, true); + g_object_unref(win); + } + } + } + } + } + + void StopEventListening() { + if (!will_show_hook_ && !will_hide_hook_) { + RemoveShowHideHooks(); + } + if (g_toplevels_changed_id) { + if (GListModel* toplevels = gtk_window_get_toplevels()) { + g_signal_handler_disconnect(toplevels, g_toplevels_changed_id); + } + g_toplevels_changed_id = 0; + } + g_focus_changed_fn = nullptr; + g_focus_changed_context = nullptr; + g_window_signal_fn = nullptr; + g_window_signal_context = nullptr; + for (auto& entry : g_tracked_windows) { + GtkWindow* win = entry.first; + if (G_IS_OBJECT(win)) { + for (gulong h : entry.second.window_handlers) { + if (g_signal_handler_is_connected(win, h)) g_signal_handler_disconnect(win, h); + } + g_object_weak_unref(G_OBJECT(win), OnTrackedWindowDestroyed, nullptr); + } + if (entry.second.surface && G_IS_OBJECT(entry.second.surface)) { + for (gulong h : entry.second.surface_handlers) { + if (g_signal_handler_is_connected(entry.second.surface, h)) { + g_signal_handler_disconnect(entry.second.surface, h); + } + } + } + } + g_tracked_windows.clear(); + } + + void OnWindowSignal(WindowId window_id, const std::string& event_type) { + if (event_type == "created") { + WindowCreatedEvent event(window_id); + manager_->DispatchWindowEvent(event); + } else if (event_type == "closed") { + WindowClosedEvent event(window_id); + manager_->DispatchWindowEvent(event); + } else if (event_type == "minimized") { + WindowMinimizedEvent event(window_id); + manager_->DispatchWindowEvent(event); + } else if (event_type == "maximized") { + WindowMaximizedEvent event(window_id); + manager_->DispatchWindowEvent(event); + } else if (event_type == "restored") { + WindowRestoredEvent event(window_id); + manager_->DispatchWindowEvent(event); + } else if (event_type == "entered_full_screen") { + WindowEnteredFullScreenEvent event(window_id); + manager_->DispatchWindowEvent(event); + } else if (event_type == "exited_full_screen") { + WindowExitedFullScreenEvent event(window_id); + manager_->DispatchWindowEvent(event); + } else if (event_type == "moved" || event_type == "resized") { + auto window = manager_->Get(window_id); + if (!window) return; + if (event_type == "moved") { + WindowMovedEvent event(window_id, window->GetPosition()); + manager_->DispatchWindowEvent(event); + } else { + WindowResizedEvent event(window_id, window->GetSize()); + manager_->DispatchWindowEvent(event); + } + } else if (event_type == "scale_factor_changed") { + GtkWindow* win = FindGtkWindowById(window_id); + const int raw_scale = win ? gtk_widget_get_scale_factor(GTK_WIDGET(win)) : 1; + WindowScaleFactorChangedEvent event(window_id, + raw_scale > 0 ? static_cast(raw_scale) : 1.0); + manager_->DispatchWindowEvent(event); + } + } + + void OnWindowFocusChanged(WindowId window_id, bool focused) { + if (focused) { + WindowFocusedEvent event(window_id); + manager_->DispatchWindowEvent(event); + } else { + WindowBlurredEvent event(window_id); + manager_->DispatchWindowEvent(event); + } + } + + private: + WindowManager* manager_; + std::shared_ptr will_show_hook_; + std::shared_ptr will_hide_hook_; + friend class WindowManager; +}; + +WindowManager::WindowManager() : pimpl_(std::make_unique(this)) { + if (!gdk_display_get_default()) { + fflush(stderr); + int saved_stderr = dup(STDERR_FILENO); + int devnull = open("/dev/null", O_WRONLY | O_CLOEXEC); + if (devnull != -1) { + dup2(devnull, STDERR_FILENO); + close(devnull); + } + linux_gtk::InitCheck(); + fflush(stderr); + if (saved_stderr != -1) { + dup2(saved_stderr, STDERR_FILENO); + close(saved_stderr); + } + } + StartEventListening(); +} + +WindowManager::~WindowManager() { + ShutdownEmitter(); + StopEventListening(); + RemoveShowHideHooks(); +} + +std::shared_ptr WindowManager::Get(WindowId id) { + auto cached = WindowRegistry::GetInstance().Get(id); + if (cached) { + return cached; + } + if (!gdk_display_get_default()) { + return nullptr; + } + GListModel* toplevels = gtk_window_get_toplevels(); + if (!toplevels) { + return nullptr; + } + const guint n = g_list_model_get_n_items(toplevels); + for (guint i = 0; i < n; ++i) { + GtkWindow* win = GTK_WINDOW(g_list_model_get_item(toplevels, i)); + if (!win) continue; + if (GetOrCreateWindowId(win) == id) { + auto window = std::make_shared(static_cast(win)); + WindowRegistry::GetInstance().Add(id, window); + g_object_unref(win); + return window; + } + g_object_unref(win); + } + return nullptr; +} + +std::vector> WindowManager::GetAll() { + if (!gdk_display_get_default()) { + return {}; + } + GListModel* toplevels = gtk_window_get_toplevels(); + if (toplevels) { + const guint n = g_list_model_get_n_items(toplevels); + for (guint i = 0; i < n; ++i) { + GtkWindow* win = GTK_WINDOW(g_list_model_get_item(toplevels, i)); + if (!win) continue; + WindowId window_id = GetOrCreateWindowId(win); + if (!WindowRegistry::GetInstance().Get(window_id)) { + auto window = std::make_shared(static_cast(win)); + WindowRegistry::GetInstance().Add(window_id, window); + } + g_object_unref(win); + } + } + return WindowRegistry::GetInstance().GetAll(); +} + +std::shared_ptr WindowManager::GetWindowAtPoint(Point point, WindowId excluded_window_id) { + if (!gdk_display_get_default()) { + return nullptr; + } + GtkWindow* excluded = excluded_window_id != 0 ? FindGtkWindowById(excluded_window_id) : nullptr; + GListModel* toplevels = gtk_window_get_toplevels(); + if (!toplevels) { + return nullptr; + } + GtkWindow* found = nullptr; + const guint n = g_list_model_get_n_items(toplevels); + for (guint i = 0; i < n; ++i) { + GtkWindow* win = GTK_WINDOW(g_list_model_get_item(toplevels, i)); + if (!win) continue; + if (win != excluded && gtk_widget_get_visible(GTK_WIDGET(win))) { + auto wrapped = Get(GetOrCreateWindowId(win)); + if (wrapped) { + Rectangle bounds = wrapped->GetBounds(); + if (point.x >= bounds.x && point.y >= bounds.y && point.x < bounds.x + bounds.width && + point.y < bounds.y + bounds.height) { + if (!found || gtk_window_is_active(win)) { + found = win; + } + } + } + } + g_object_unref(win); + } + return found ? Get(GetOrCreateWindowId(found)) : nullptr; +} + +std::shared_ptr WindowManager::GetCurrent() { + if (!gdk_display_get_default()) { + return nullptr; + } + GListModel* toplevels = gtk_window_get_toplevels(); + if (!toplevels) { + return nullptr; + } + GtkWindow* first_visible = nullptr; + GtkWindow* first_hidden = nullptr; + const guint n = g_list_model_get_n_items(toplevels); + for (guint i = 0; i < n; ++i) { + GtkWindow* win = GTK_WINDOW(g_list_model_get_item(toplevels, i)); + if (!win) continue; + if (!gtk_widget_get_visible(GTK_WIDGET(win))) { + if (!first_hidden) first_hidden = win; + g_object_unref(win); + continue; + } + if (gtk_window_is_active(win)) { + WindowId id = GetOrCreateWindowId(win); + g_object_unref(win); + return Get(id); + } + if (!first_visible) first_visible = win; + g_object_unref(win); + } + GtkWindow* fallback = first_visible ? first_visible : first_hidden; + return fallback ? Get(GetOrCreateWindowId(fallback)) : nullptr; +} + +void WindowManager::SetWillShowHook(std::optional hook) { + pimpl_->will_show_hook_ = + hook && *hook ? std::make_shared(std::move(*hook)) : nullptr; + if (pimpl_->will_show_hook_) { + InstallGlobalSwizzling(); + } +} + +void WindowManager::SetWillHideHook(std::optional hook) { + pimpl_->will_hide_hook_ = + hook && *hook ? std::make_shared(std::move(*hook)) : nullptr; + if (pimpl_->will_hide_hook_) { + InstallGlobalSwizzling(); + } +} + +bool WindowManager::HasWillShowHook() const { return pimpl_->will_show_hook_ != nullptr; } +bool WindowManager::HasWillHideHook() const { return pimpl_->will_hide_hook_ != nullptr; } + +void WindowManager::HandleWillShow(WindowId id) { + auto hook = pimpl_->will_show_hook_; + if (hook) (*hook)(id); +} + +void WindowManager::HandleWillHide(WindowId id) { + auto hook = pimpl_->will_hide_hook_; + if (hook) (*hook)(id); +} + +bool WindowManager::CallOriginalShow(WindowId id) { + GtkWindow* win = FindGtkWindowById(id); + if (!win) return false; + gtk_widget_set_visible(GTK_WIDGET(win), TRUE); + return true; +} + +bool WindowManager::CallOriginalHide(WindowId id) { + GtkWindow* win = FindGtkWindowById(id); + if (!win) return false; + gtk_widget_set_visible(GTK_WIDGET(win), FALSE); + return true; +} + +void WindowManager::StartEventListening() { pimpl_->StartEventListening(); } +void WindowManager::StopEventListening() { pimpl_->StopEventListening(); } + +void WindowManager::DispatchWindowEvent(const WindowEvent& event) { + detail::EmitObservedWindowEvent(event); + Emit(event); +} + +#else + static const char* kObservedIconifiedKey = "NativeAPIObservedIconified"; // Shared static variables for window ID mapping @@ -1066,4 +1661,6 @@ void WindowManager::DispatchWindowEvent(const WindowEvent& event) { Emit(event); } +#endif + } // namespace nativeapi diff --git a/src/platform/linux/window_shadow_linux.h b/src/platform/linux/window_shadow_linux.h index 0688ed95..6582e35c 100644 --- a/src/platform/linux/window_shadow_linux.h +++ b/src/platform/linux/window_shadow_linux.h @@ -1,9 +1,6 @@ #pragma once -#include -#ifdef GDK_WINDOWING_WAYLAND -#include -#endif +#include "gtk_compat_linux.h" #include #include @@ -18,17 +15,8 @@ namespace nativeapi::linux_shadow { constexpr char kConfig[] = "NativeAPICustomShadow"; constexpr char kState[] = "NativeAPICoreShadow"; constexpr char kReservedGutterStyleClass[] = "nativeapi-shadow-reserved"; +constexpr char kGutterStyleClass[] = "nativeapi-shadow-gutter"; -// GTK rewrites a CSD window's shadow widths during every allocation. Keep its -// decoration margin as the only source of geometry rather than competing with -// that declaration from an allocation handler. -inline bool GtkOwnsGutter(GtkWidget* widget) { - return gtk_style_context_has_class(gtk_widget_get_style_context(widget), "csd"); -} - -// Reserve the complete supported blur/offset envelope once. Wayland cannot -// compensate for changing surface gutters with gtk_window_move(), and doing so -// also races asynchronous GTK allocations on X11. Raster only the actual shadow. inline int ReservedMargin() { WindowShadow maximum; maximum.SetBlurRadius(64); @@ -36,6 +24,133 @@ inline int ReservedMargin() { return window_shadow::Margin(maximum); } +#if NATIVEAPI_GTK4 +struct State { + GtkWidget* target = nullptr; + int margin = 0; + std::shared_ptr custom; + bool enabled = true; + bool translucent = true; + bool fitted = false; + bool gutter = false; + bool gtk_gutter = true; + int surface_width = 0; + int surface_height = 0; + bool decided = true; + bool dirty = false; + WindowShape polygon; + GtkCssProvider* css_provider = nullptr; + ~State() { + if (css_provider) { + if (target && GTK_IS_WIDGET(target)) { + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gtk_style_context_remove_provider(gtk_widget_get_style_context(target), + GTK_STYLE_PROVIDER(css_provider)); + G_GNUC_END_IGNORE_DEPRECATIONS + } + g_object_unref(css_provider); + css_provider = nullptr; + } + } +}; + +inline State* Get(GtkWidget* widget) { + return widget ? static_cast(g_object_get_data(G_OBJECT(widget), kState)) : nullptr; +} +inline int Gutter(GtkWidget*) { return 0; } +inline void NoteRequestedSize(GtkWidget* widget, int width, int height) { + if (auto* state = Get(widget)) { + state->surface_width = width; + state->surface_height = height; + } +} +inline void ApplyCss(GtkWidget* widget, State* state) { + if (!widget || !state) { + return; + } + if (!state->css_provider) { + state->css_provider = gtk_css_provider_new(); + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gtk_style_context_add_provider(gtk_widget_get_style_context(widget), + GTK_STYLE_PROVIDER(state->css_provider), + GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); + G_GNUC_END_IGNORE_DEPRECATIONS + } + std::string css; + if (!state->enabled) { + css = "window { box-shadow: none; }"; + } else if (state->custom) { + const auto& s = *state->custom; + const auto c = s.GetColor(); + const auto off = s.GetOffset(); + const double blur = s.GetBlurRadius(); + const double alpha = c.a / 255.0; + gchar alpha_buf[G_ASCII_DTOSTR_BUF_SIZE]; + g_ascii_formatd(alpha_buf, sizeof(alpha_buf), "%.3f", alpha); + css = "window { box-shadow: " + std::to_string(static_cast(off.x)) + "px " + + std::to_string(static_cast(off.y)) + "px " + + std::to_string(static_cast(blur)) + "px rgba(" + std::to_string(c.r) + "," + + std::to_string(c.g) + "," + std::to_string(c.b) + "," + alpha_buf + "); }"; + } + G_GNUC_BEGIN_IGNORE_DEPRECATIONS + gtk_css_provider_load_from_data(state->css_provider, css.c_str(), -1); + G_GNUC_END_IGNORE_DEPRECATIONS +} +inline void Remove(GtkWidget* widget) { + if (!Get(widget)) { + return; + } + ClearShadowInput(widget); + g_object_set_data(G_OBJECT(widget), kState, nullptr); + gtk_widget_queue_draw(widget); +} +inline State* Ensure(GtkWidget* widget) { + if (auto* state = Get(widget)) { + return state; + } + if (!widget || !GTK_IS_WINDOW(widget)) { + return nullptr; + } + auto* state = new State; + state->target = widget; + if (auto* config = static_cast(g_object_get_data(G_OBJECT(widget), kConfig))) { + state->custom = std::make_shared(*config); + } + g_object_set_data_full(G_OBJECT(widget), kState, state, + [](gpointer p) { delete static_cast(p); }); + ApplyCss(widget, state); + return state; +} +inline void Configure(GtkWidget* widget, std::shared_ptr custom) { + auto* state = Ensure(widget); + if (!state) { + return; + } + state->custom = std::move(custom); + ApplyCss(widget, state); + gtk_widget_queue_draw(widget); +} +inline void SetPolygon(GtkWidget* widget, const std::shared_ptr& polygon) { + auto* state = Get(widget); + if (!state) { + return; + } + state->polygon.Clear(); + if (polygon) { + for (size_t i = 0; i < polygon->GetPointCount(); ++i) { + state->polygon.AddPoint(polygon->GetPointAt(i)); + } + } + gtk_widget_queue_draw(widget); +} +#else +// GTK rewrites a CSD window's shadow widths during every allocation. Keep its +// decoration margin as the only source of geometry rather than competing with +// that declaration from an allocation handler. +inline bool GtkOwnsGutter(GtkWidget* widget) { + return gtk_style_context_has_class(gtk_widget_get_style_context(widget), "csd"); +} + // States in which the window manager fits the whole surface to the space it gives the // window - a tiling window manager's tiles, maximized, full screen. The gutter is then // no shadow, only a band of empty window around the content, so it is taken away @@ -277,7 +392,6 @@ inline void Allocated(GtkWidget* widget, GtkAllocation*, gpointer data) { // which would hide the shadow behind an opaque band. A window that can be // translucent gets this class, and one rule for the screen clears its background; // the content paints its own. -constexpr char kGutterStyleClass[] = "nativeapi-shadow-gutter"; inline bool CanBeTranslucent(GtkWidget* widget) { auto* screen = gtk_widget_get_screen(widget); auto* rgba = gdk_screen_get_rgba_visual(screen); @@ -564,4 +678,5 @@ inline void SetPolygon(GtkWidget* widget, const std::shared_ptr& po state->dirty = true; gtk_widget_queue_draw(widget); } +#endif } // namespace nativeapi::linux_shadow diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index b6babd2e..76dd405b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -368,8 +368,19 @@ if(WIN32) target_link_libraries(menu_theme_test PRIVATE nativeapi) endif() -# Explicit desktop integration test; requires a running window manager. if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + string(TOUPPER "${NATIVEAPI_LINUX_BACKEND}" _NATIVEAPI_TEST_LINUX_BACKEND) + if(_NATIVEAPI_TEST_LINUX_BACKEND STREQUAL "GTK3") + set(_NATIVEAPI_LINUX_GTK3 TRUE) + else() + set(_NATIVEAPI_LINUX_GTK3 FALSE) + endif() +else() + set(_NATIVEAPI_LINUX_GTK3 FALSE) +endif() + +# Explicit desktop integration test; requires a running window manager. +if(_NATIVEAPI_LINUX_GTK3) # Inspect real server input regions without injecting input into the desktop. add_executable(window_title_bar_double_click_linux_test window_title_bar_double_click_linux_test.cpp) target_link_libraries(window_title_bar_double_click_linux_test PRIVATE nativeapi) @@ -396,7 +407,7 @@ if(WIN32) endif() # Explicit desktop integration test; requires a running window manager. -if(CMAKE_SYSTEM_NAME STREQUAL "Linux") +if(_NATIVEAPI_LINUX_GTK3) add_executable(window_resizable_linux_test window_resizable_linux_test.cpp) target_link_libraries(window_resizable_linux_test PRIVATE nativeapi) endif() @@ -410,19 +421,19 @@ if(WIN32 OR (APPLE AND NOT CMAKE_SYSTEM_NAME STREQUAL "iOS")) target_link_libraries(window_resizable_desktop_test PRIVATE nativeapi) endif() -if(CMAKE_SYSTEM_NAME STREQUAL "Linux") +if(_NATIVEAPI_LINUX_GTK3) add_executable(window_controls_linux_test window_controls_linux_test.cpp) target_link_libraries(window_controls_linux_test PRIVATE nativeapi) endif() -if(CMAKE_SYSTEM_NAME STREQUAL "Linux") +if(_NATIVEAPI_LINUX_GTK3) add_executable(window_restore_linux_test window_restore_linux_test.cpp) target_link_libraries(window_restore_linux_test PRIVATE nativeapi) endif() # Explicit desktop integration test; requires a running compositor (meant for one that # sends tiled states to floating windows, such as Hyprland). -if(CMAKE_SYSTEM_NAME STREQUAL "Linux") +if(_NATIVEAPI_LINUX_GTK3) add_executable(window_shadow_remap_linux_test window_shadow_remap_linux_test.cpp) target_link_libraries(window_shadow_remap_linux_test PRIVATE nativeapi) add_executable(window_shadow_visual_linux_test window_shadow_visual_linux_test.cpp) @@ -435,6 +446,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux") add_executable(window_shadow_gutter_linux_test window_shadow_gutter_linux_test.cpp ../src/window_shape.cpp ../src/window_shadow.cpp) target_compile_features(window_shadow_gutter_linux_test PRIVATE cxx_std_17) + target_compile_definitions(window_shadow_gutter_linux_test PRIVATE NATIVEAPI_LINUX_GTK3) target_link_libraries(window_shadow_gutter_linux_test PRIVATE PkgConfig::SHADOW_GTK) add_test(NAME window_shadow_gutter_linux_test COMMAND window_shadow_gutter_linux_test) set_tests_properties(window_shadow_gutter_linux_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 10) @@ -449,7 +461,7 @@ if(WIN32 OR (APPLE AND NOT CMAKE_SYSTEM_NAME STREQUAL "iOS")) target_link_libraries(window_aspect_ratio_desktop_test PRIVATE nativeapi) endif() -if(CMAKE_SYSTEM_NAME STREQUAL "Linux") +if(_NATIVEAPI_LINUX_GTK3) add_executable(window_aspect_ratio_linux_test window_aspect_ratio_linux_test.cpp) target_link_libraries(window_aspect_ratio_linux_test PRIVATE nativeapi) endif() @@ -476,7 +488,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux") endif() # Explicit desktop regression; --clicks is driven by the guarded GUI harness. -if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Linux") +if(WIN32 OR _NATIVEAPI_LINUX_GTK3) add_executable(window_focus_policy_test window_focus_policy_test.cpp) target_link_libraries(window_focus_policy_test PRIVATE nativeapi) # Focus()/Blur() across processes; changes the foreground window, run by hand. @@ -578,7 +590,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "iOS") MACOSX_BUNDLE_BUNDLE_VERSION 1) endif() -if(CMAKE_SYSTEM_NAME STREQUAL "Linux") +if(_NATIVEAPI_LINUX_GTK3) # Explicit private Xvfb integration; changes that display's clipboard. add_executable(clipboard_linux_test clipboard_linux_test.cpp) target_link_libraries(clipboard_linux_test PRIVATE nativeapi) @@ -632,7 +644,7 @@ add_test(NAME ohos_shadow_raster_test COMMAND ohos_shadow_raster_test) # Migrated appbar, keyboard-grab and macOS frame/space capabilities. Manual: # creates windows and briefly reserves desktop space; sends no synthetic input. -if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Linux" OR (APPLE AND NOT CMAKE_SYSTEM_NAME STREQUAL "iOS")) +if(WIN32 OR _NATIVEAPI_LINUX_GTK3 OR (APPLE AND NOT CMAKE_SYSTEM_NAME STREQUAL "iOS")) if(APPLE) set_source_files_properties(window_migration_test.cpp PROPERTIES LANGUAGE OBJCXX) endif() @@ -655,7 +667,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux") endif() # Manual no-input caption group/policy checks; requires a desktop compositor. -if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Linux" OR (APPLE AND NOT CMAKE_SYSTEM_NAME STREQUAL "iOS")) +if(WIN32 OR _NATIVEAPI_LINUX_GTK3 OR (APPLE AND NOT CMAKE_SYSTEM_NAME STREQUAL "iOS")) if(APPLE) set_source_files_properties(window_controls_test.cpp PROPERTIES LANGUAGE OBJCXX) endif() @@ -663,7 +675,7 @@ if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Linux" OR (APPLE AND NOT CMAKE_SYSTEM_NA target_link_libraries(window_controls_test PRIVATE nativeapi) endif() -if(CMAKE_SYSTEM_NAME STREQUAL "Linux") +if(_NATIVEAPI_LINUX_GTK3) add_executable(window_startup_state_linux_test window_startup_state_linux_test.cpp) target_link_libraries(window_startup_state_linux_test PRIVATE nativeapi) add_executable(window_controls_x11_test window_controls_x11_test.cpp) diff --git a/tests/gtk_test_compat.h b/tests/gtk_test_compat.h new file mode 100644 index 00000000..08e0f067 --- /dev/null +++ b/tests/gtk_test_compat.h @@ -0,0 +1,35 @@ +#pragma once + +#include + +inline bool GtkTestInit(int* argc = nullptr, char*** argv = nullptr) { +#if GTK_MAJOR_VERSION >= 4 + (void)argc; + (void)argv; + return gtk_init_check() != FALSE; +#else + return gtk_init_check(argc, argv) != FALSE; +#endif +} + +inline void GtkTestPump() { +#if GTK_MAJOR_VERSION >= 4 + GMainContext* ctx = g_main_context_default(); + while (g_main_context_pending(ctx)) { + g_main_context_iteration(ctx, FALSE); + } +#else + while (gtk_events_pending()) { + gtk_main_iteration(); + } +#endif +} + +inline void GtkTestDestroyWindow(GtkWidget* widget) { + if (!widget) return; +#if GTK_MAJOR_VERSION >= 4 + gtk_window_destroy(GTK_WINDOW(widget)); +#else + gtk_widget_destroy(widget); +#endif +} diff --git a/tests/tray_context_menu_linux_test.cpp b/tests/tray_context_menu_linux_test.cpp index 137b46c7..13f97172 100644 --- a/tests/tray_context_menu_linux_test.cpp +++ b/tests/tray_context_menu_linux_test.cpp @@ -1,8 +1,10 @@ // Run in a private X11/Wayland display; no synthetic input is sent. #include "nativeapi.h" -#include +#include "gtk_test_compat.h" +#if GTK_MAJOR_VERSION < 4 #include #undef None +#endif #include #include #include @@ -51,13 +53,15 @@ static void CheckExport(TrayIcon& tray, ContextMenuTrigger trigger, bool exposed } int main(int argc, char** argv) { if (!g_getenv("NATIVEAPI_TEST_PRIVATE_DISPLAY")) return 77; - if (!gtk_init_check(&argc, &argv)) return 77; + if (!GtkTestInit(&argc, &argv)) return 77; auto tray = std::make_unique(); Check(!tray->OpenContextMenu(), "no menu returns false"); auto menu = std::make_shared(); auto item = std::make_shared("Item", MenuItemType::Normal); menu->AddItem(item); +#if GTK_MAJOR_VERSION < 4 auto* widget = static_cast(menu->GetNativeObject()); +#endif int opened = 0, closed = 0, clicked = 0; menu->AddListener([&](const auto&) { ++opened; }); menu->AddListener([&](const auto&) { ++closed; }); @@ -78,6 +82,9 @@ int main(int argc, char** argv) { Check(closed == 1 && tray->CloseContextMenu(), "host menu closed event retained"); opened = closed = 0; tray->SetContextMenuTrigger(ContextMenuTrigger::None); +#if GTK_MAJOR_VERSION >= 4 + return 0; +#else if (!GDK_IS_X11_DISPLAY(gdk_display_get_default())) { Check(!tray->OpenContextMenu(), "Wayland reports unsupported"); Check(!gtk_widget_get_mapped(widget) && opened == 0, "Wayland has no phantom popup/event"); @@ -124,4 +131,5 @@ int main(int argc, char** argv) { } Check(!tray && !gtk_widget_get_mapped(widget), "double-click listener can destroy tray safely"); return 0; +#endif } diff --git a/tests/view_api_test.cpp b/tests/view_api_test.cpp index 6b462acf..6e819405 100644 --- a/tests/view_api_test.cpp +++ b/tests/view_api_test.cpp @@ -7,7 +7,7 @@ #endif #if defined(__linux__) && !defined(__ANDROID__) -#include +#include "gtk_test_compat.h" #endif #include @@ -45,7 +45,7 @@ int main(int argc, char** argv) { "ViewResizedEvent payload"); #if defined(__linux__) && !defined(__ANDROID__) - if (!gtk_init_check(&argc, &argv)) { + if (!GtkTestInit(&argc, &argv)) { return failures == 0 ? 77 : 1; } #else diff --git a/tests/window_close_linux_test.cpp b/tests/window_close_linux_test.cpp index 00d4a883..efb99bfd 100644 --- a/tests/window_close_linux_test.cpp +++ b/tests/window_close_linux_test.cpp @@ -1,5 +1,5 @@ -// GTK delete-event with existing host handlers, in a private display session. -#include +// GTK close-request / delete-event with existing host handlers, in a private display session. +#include "gtk_test_compat.h" #include #include #include "nativeapi.h" @@ -10,6 +10,16 @@ void Check(bool ok, const char* label) { std::cout << (ok ? "PASS " : "FAIL ") << label << std::endl; failures += !ok; } +#if GTK_MAJOR_VERSION >= 4 +gboolean Host(GtkWindow*, gpointer) { + ++host_close; + return refuse; +} +gboolean Preblocked(GtkWindow*, gpointer) { + ++preblocked_calls; + return FALSE; +} +#else gboolean Host(GtkWidget*, GdkEvent*, gpointer) { ++host_close; return refuse; @@ -18,20 +28,30 @@ gboolean Preblocked(GtkWidget*, GdkEvent*, gpointer) { ++preblocked_calls; return FALSE; } +#endif void Drain() { while (g_main_context_pending(nullptr)) g_main_context_iteration(nullptr, FALSE); } } // namespace int main() { - if (!gtk_init_check(nullptr, nullptr)) + if (!GtkTestInit()) return 77; +#if GTK_MAJOR_VERSION >= 4 + auto* widget = gtk_window_new(); +#else auto* widget = gtk_window_new(GTK_WINDOW_TOPLEVEL); +#endif g_object_ref_sink(widget); - // Realize without showing: this is still a real GdkWindow for either backend. + // Realize without showing: this is still a real native surface for either backend. gtk_widget_realize(widget); +#if GTK_MAJOR_VERSION >= 4 + g_signal_connect(widget, "close-request", G_CALLBACK(Host), nullptr); + auto blocked = g_signal_connect(widget, "close-request", G_CALLBACK(Preblocked), nullptr); +#else g_signal_connect(widget, "delete-event", G_CALLBACK(Host), nullptr); auto blocked = g_signal_connect(widget, "delete-event", G_CALLBACK(Preblocked), nullptr); +#endif g_signal_handler_block(widget, blocked); nativeapi::Window first(widget), alias(widget); auto ui = std::this_thread::get_id(); @@ -81,7 +101,13 @@ int main() { close_worker.join(); Drain(); auto late_a = a, late_b = b; +#if GTK_MAJOR_VERSION >= 4 + // In GTK 4, gtk_window_destroy() only drops GTK's own ref; with our extra ref + // held to inspect state afterwards, run_dispose mirrors GTK 3's gtk_widget_destroy. + g_object_run_dispose(G_OBJECT(widget)); +#else gtk_widget_destroy(widget); +#endif late_a->Accept(); late_b->Accept(); Drain(); diff --git a/tests/window_close_manager_first_linux_test.cpp b/tests/window_close_manager_first_linux_test.cpp index dd48a7a9..6e2ac2a8 100644 --- a/tests/window_close_manager_first_linux_test.cpp +++ b/tests/window_close_manager_first_linux_test.cpp @@ -3,7 +3,7 @@ // events and cancellable close requests. WindowManager keys windows by their // GdkWindow; the close gate checks the ID on the GtkWindow, so the two must // carry the same one. Private display, no input. -#include +#include "gtk_test_compat.h" #include #include "nativeapi.h" namespace { @@ -18,9 +18,13 @@ void Drain() { } } // namespace int main() { - if (!gtk_init_check(nullptr, nullptr)) + if (!GtkTestInit()) return 77; +#if GTK_MAJOR_VERSION >= 4 + auto* widget = gtk_window_new(); +#else auto* widget = gtk_window_new(GTK_WINDOW_TOPLEVEL); +#endif g_object_ref_sink(widget); gtk_widget_realize(widget); // A real GdkWindow, not shown yet (as a Flutter runner's at start). @@ -50,7 +54,7 @@ int main() { Drain(); Check(titles == 1, "its own property events arrive too"); - gtk_widget_destroy(widget); + GtkTestDestroyWindow(widget); g_object_unref(widget); std::cout << (failures ? "FAILED" : "OK") << std::endl; return failures ? 1 : 0; diff --git a/tests/window_content_protection_test.cpp b/tests/window_content_protection_test.cpp index 5101066e..51826a28 100644 --- a/tests/window_content_protection_test.cpp +++ b/tests/window_content_protection_test.cpp @@ -4,12 +4,12 @@ #ifdef __APPLE__ #import #else -#include +#include "gtk_test_compat.h" #endif int main(int argc, char** argv) { #ifndef __APPLE__ - if (!gtk_init_check(&argc, &argv)) return 77; + if (!GtkTestInit(&argc, &argv)) return 77; #endif using namespace nativeapi; Application::GetInstance(); diff --git a/tests/window_corner_preference_unsupported_test.cpp b/tests/window_corner_preference_unsupported_test.cpp index 5f377f7f..b9d7e55d 100644 --- a/tests/window_corner_preference_unsupported_test.cpp +++ b/tests/window_corner_preference_unsupported_test.cpp @@ -2,12 +2,12 @@ #include "nativeapi.h" #include #ifdef __linux__ -#include +#include "gtk_test_compat.h" #endif int main(int argc, char** argv) { #ifdef __linux__ - if (!gtk_init_check(&argc, &argv)) return 77; + if (!GtkTestInit(&argc, &argv)) return 77; #endif using namespace nativeapi; Application::GetInstance(); diff --git a/tests/window_manager_hooks_linux_test.cpp b/tests/window_manager_hooks_linux_test.cpp index 169b2c40..091bcafd 100644 --- a/tests/window_manager_hooks_linux_test.cpp +++ b/tests/window_manager_hooks_linux_test.cpp @@ -1,6 +1,6 @@ // GTK integration regression: windows may outlive the manager at process exit. #include "nativeapi.h" -#include +#include "gtk_test_compat.h" #include #include @@ -12,15 +12,17 @@ void AfterManagerShutdown() { const int before = calls; // These signals must no longer reach the already-destroyed singleton. Exercise // both the global show/hide hooks and the per-widget map/unmap fallback. - gtk_widget_show(surviving_widget); - gtk_widget_hide(surviving_widget); + gtk_widget_set_visible(surviving_widget, TRUE); + gtk_widget_set_visible(surviving_widget, FALSE); +#if GTK_MAJOR_VERSION < 4 GdkEvent* event = gdk_event_new(GDK_MAP); gboolean handled = FALSE; g_signal_emit_by_name(surviving_widget, "map-event", event, &handled); event->type = GDK_UNMAP; g_signal_emit_by_name(surviving_widget, "unmap-event", event, &handled); gdk_event_free(event); - gtk_widget_destroy(surviving_widget); +#endif + GtkTestDestroyWindow(surviving_widget); g_object_unref(surviving_widget); if (calls != before) { std::cerr << "FAIL GTK callbacks survived manager shutdown\n"; @@ -31,8 +33,12 @@ void AfterManagerShutdown() { } // namespace int main(int argc, char** argv) { - if (!gtk_init_check(&argc, &argv)) return 77; + if (!GtkTestInit(&argc, &argv)) return 77; +#if GTK_MAJOR_VERSION >= 4 + surviving_widget = gtk_window_new(); +#else surviving_widget = gtk_window_new(GTK_WINDOW_TOPLEVEL); +#endif g_object_ref_sink(surviving_widget); gtk_widget_realize(surviving_widget); // Registered first, so this runs after the singleton's destructor. @@ -43,17 +49,21 @@ int main(int argc, char** argv) { const auto listener = manager.AddListener([](const auto&) {}); manager.RemoveListener(listener); // Removing the last event listener must keep explicit will-show/hide hooks. - gtk_widget_show(surviving_widget); - gtk_widget_hide(surviving_widget); + gtk_widget_set_visible(surviving_widget, TRUE); + gtk_widget_set_visible(surviving_widget, FALSE); if (calls < 2) { std::cerr << "FAIL will-show/hide hooks lost when event listening stopped\n"; return 1; } std::cout << "PASS will-show/hide hooks independent of event listeners\n"; // Include windows destroyed before the manager, then reinstall event hooks. +#if GTK_MAJOR_VERSION >= 4 + auto* temporary = gtk_window_new(); +#else auto* temporary = gtk_window_new(GTK_WINDOW_TOPLEVEL); +#endif const auto other_listener = manager.AddListener([](const auto&) {}); - gtk_widget_destroy(temporary); + GtkTestDestroyWindow(temporary); manager.RemoveListener(other_listener); return 0; } diff --git a/tests/window_occlusion_test.cpp b/tests/window_occlusion_test.cpp index 58071c98..873f0c04 100644 --- a/tests/window_occlusion_test.cpp +++ b/tests/window_occlusion_test.cpp @@ -16,7 +16,7 @@ #elif defined(_WIN32) #include #else -#include +#include "gtk_test_compat.h" #endif using namespace nativeapi; @@ -41,7 +41,7 @@ void PumpOnce() { DispatchMessageW(&message); } #else - while (gtk_events_pending()) gtk_main_iteration(); + GtkTestPump(); #endif } // The system can take seconds to recompute occlusion (macOS after a window @@ -65,7 +65,7 @@ const char* Name(WindowOcclusionState state) { int main(int argc, char** argv) { #if !defined(__APPLE__) && !defined(_WIN32) - if (!gtk_init_check(&argc, &argv)) return 77; + if (!GtkTestInit(&argc, &argv)) return 77; #endif #ifdef _WIN32 SetProcessDPIAware(); diff --git a/tests/window_property_changed_test.cpp b/tests/window_property_changed_test.cpp index 5570bc0c..8470b176 100644 --- a/tests/window_property_changed_test.cpp +++ b/tests/window_property_changed_test.cpp @@ -15,7 +15,7 @@ #elif defined(_WIN32) #include #else -#include +#include "gtk_test_compat.h" #endif using namespace nativeapi; @@ -28,7 +28,7 @@ void Check(bool ok, const std::string& label) { } void PumpOnce() { #if !defined(__APPLE__) && !defined(_WIN32) - while (gtk_events_pending()) gtk_main_iteration(); + GtkTestPump(); #elif defined(_WIN32) MSG message; while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) DispatchMessageW(&message); @@ -54,7 +54,7 @@ int Count(const std::vector& events, WindowProperty property) { int main(int argc, char** argv) { #if !defined(__APPLE__) && !defined(_WIN32) - if (!gtk_init_check(&argc, &argv)) return 77; + if (!GtkTestInit(&argc, &argv)) return 77; #endif Application::GetInstance(); Window window; @@ -85,7 +85,7 @@ int main(int argc, char** argv) { probe.SetAlwaysOnTop(true); Pump([&] { return probe.IsAlwaysOnTop(); }); keep_above_confirmed = probe.IsAlwaysOnTop(); - gtk_widget_destroy(GTK_WIDGET(probe.GetNativeObject())); + GtkTestDestroyWindow(GTK_WIDGET(probe.GetNativeObject())); Pump([] { return false; }, 100); if (!keep_above_confirmed) std::cout << "SKIP always-on-top: the window manager does not confirm keep-above" << std::endl; @@ -164,6 +164,7 @@ int main(int argc, char** argv) { #endif }); Check(window.IsResizable(), "the getter returns the native resizable state"); +#if !defined(__linux__) || GTK_MAJOR_VERSION < 4 if (keep_above_confirmed) expect("a direct native always-on-top change is reported", WindowProperty::AlwaysOnTop, [&] { #ifdef __APPLE__ static_cast(window.GetNativeObject()).level = NSFloatingWindowLevel; @@ -174,6 +175,7 @@ int main(int argc, char** argv) { gtk_window_set_keep_above(GTK_WINDOW(window.GetNativeObject()), TRUE); #endif }); +#endif std::cout << (failures ? "FAILED" : "OK") << std::endl; return failures ? 1 : 0; From 217d7364bab4326598cc41a4a785dacfa8d81729 Mon Sep 17 00:00:00 2001 From: LiJianying Date: Tue, 1 Dec 2026 08:04:10 +0800 Subject: [PATCH 2/2] fix(examples): inherit GTK linkage from nativeapi in window_taskbar_example --- examples/window_taskbar_example/CMakeLists.txt | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/examples/window_taskbar_example/CMakeLists.txt b/examples/window_taskbar_example/CMakeLists.txt index 05257f34..994f92b4 100644 --- a/examples/window_taskbar_example/CMakeLists.txt +++ b/examples/window_taskbar_example/CMakeLists.txt @@ -15,10 +15,7 @@ elseif(APPLE) elseif(WIN32) target_link_libraries(window_taskbar_example user32 kernel32) elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - find_package(PkgConfig REQUIRED) - pkg_check_modules(GTK3 REQUIRED gtk+-3.0) - target_include_directories(window_taskbar_example PRIVATE ${GTK3_INCLUDE_DIRS}) - target_link_libraries(window_taskbar_example ${GTK3_LIBRARIES}) + # GTK, X11 and Xi are already linked publicly by nativeapi. elseif(ANDROID) target_link_libraries(window_taskbar_example log android) endif()