wails/v3/pkg/application/webview_window.go
Lea Anthony 5dc3e21699
feat(linux): GTK4 + WebKitGTK 6.0 support (opt-in via -tags gtk4) (#4958)
* chore: add WebKitGTK 6.0/GTK4 epic and beads issue tracking

Initialize beads (bd) issue tracker with comprehensive epic for
WebKitGTK 6.0 / GTK4 support as the new default for Wails v3 Linux.

Epic: wails-webview2gtk6-t4e (40 tasks)
- GTK4/WebKit6 as default (no build tag needed)
- GTK3/WebKit4.1 via -tags gtk3 for legacy
- Docker container with both library sets for cross-compilation
- Comprehensive test strategy including benchmarks
- task build:linux (GTK4) and task build:linux:gtk3 (legacy)

* feat(linux): add WebKitGTK 6.0 / GTK4 support infrastructure [WIP]

Architecture change for modern Linux desktop support:
- GTK4/WebKitGTK 6.0 is the new DEFAULT (no build tag)
- GTK3/WebKit2GTK 4.1 is LEGACY (requires -tags gtk3)

Changes:
- Add gtk3 build constraint to existing GTK3 CGO files
- Create GTK4 stub implementations (linux_cgo_gtk4.go, application_linux_gtk4.go)
- Create WebKitGTK 6.0 asset server stubs (webkit6.go, request/responsewriter)

Known limitations (documented):
- Window positioning is NO-OP on GTK4/Wayland (protocol limitation)
- Menu system needs GMenu/GAction rewrite (stub only)
- Some methods have TODO markers for full implementation

This establishes the build infrastructure for GTK4 support.
Full implementation requires GTK4 dev environment for testing.

* docs: add implementation tracker for WebKitGTK 6.0/GTK4 work

- Create IMPLEMENTATION.md to track progress, decisions, and API differences
- Update AGENTS.md with instructions to maintain IMPLEMENTATION.md
- Document Phase 1 completion and remaining phases

* feat(linux): update doctor and capabilities for GTK4/WebKitGTK 6.0 support

- Update all 7 package managers (apt, dnf, pacman, zypper, emerge, eopkg, nixpkgs)
  to check for GTK4/WebKitGTK 6.0 as primary dependencies
- Mark GTK3/WebKit2GTK packages as optional/legacy
- Add GTKVersion and WebKitVersion fields to Capabilities struct
- Create capabilities_linux_gtk3.go for legacy build path
- Update IMPLEMENTATION.md to mark Phase 2 complete

GTK4 packages are now checked by default. Legacy GTK3 packages
are marked optional and only needed when building with -tags gtk3.

* feat(linux): implement GTK4 window management and event handling

- Add GtkEventController-based event handling for GTK4:
  - GtkEventControllerFocus for focus in/out
  - GtkGestureClick for button press/release
  - GtkEventControllerKey for keyboard events
- Implement window drag/resize using GdkToplevel API
- Add complete drag-and-drop support with GtkDropTarget
- Fix window state detection (minimized, maximized, fullscreen)
- Fix size() to properly return window dimensions in GTK4
- Update IMPLEMENTATION.md to mark Phase 3 complete

GTK4 uses a fundamentally different event model with controllers
instead of direct signal handlers. This commit implements all the
necessary event handling for window management.

* feat(linux): implement GTK4 menu system with GMenu/GAction

Phase 4 of WebKitGTK 6.0/GTK4 implementation.

GTK4 completely replaces the menu system. GTK3's GtkMenu/GtkMenuItem
are replaced by:
- GMenu: Menu model (data structure, not a widget)
- GMenuItem: Individual menu item in the model
- GSimpleAction: Action triggered when menu item is activated
- GSimpleActionGroup: Container for actions, attached to widgets
- GtkPopoverMenuBar: Menu bar widget created from GMenu model

Key changes:
- linux_cgo_gtk4.go: Added C helpers and Go functions for GMenu/GAction
  - menuActionActivated() callback for action triggers
  - menuItemNewWithId/menuCheckItemNewWithId/menuRadioItemNewWithId
  - set_action_enabled/set_action_state for state management
- menu_linux_gtk4.go: GTK4 menu processing (processMenu, addMenuItem)
- menuitem_linux_gtk4.go: GTK4 menu item handling and role menus
- menu_linux.go: Added gtk3 build tag
- menuitem_linux.go: Added gtk3 build tag

Deferred to future work:
- Context menus with GtkPopoverMenu
- Keyboard accelerators with GtkShortcut

* feat(linux): add missing CGO exports for GTK4 asset server

Phase 5 of WebKitGTK 6.0/GTK4 implementation.

The GTK4 CGO file was missing two critical exports that existed in the
GTK3 version:

1. onProcessRequest - Handles WebKit URI scheme requests. This callback
   is registered with webkit_web_context_register_uri_scheme and routes
   asset requests to the webviewRequests channel for processing.

2. sendMessageToBackend - Handles JavaScript to Go communication. This
   is called when JavaScript sends messages via the webkit user content
   manager, enabling the IPC bridge.

The asset server files (webkit6.go, request_linux_gtk4.go,
responsewriter_linux_gtk4.go) were already complete from Phase 1.
WebKitGTK 6.0 uses the same URI scheme handler API as WebKitGTK 4.1.

* build(linux): add GTK4 support to Docker and Taskfile

Phase 6 of WebKitGTK 6.0/GTK4 implementation.

Docker containers (Ubuntu 24.04):
- Install both GTK4/WebKitGTK 6.0 (default) and GTK3/WebKit2GTK 4.1 (legacy)
- Build scripts support BUILD_TAGS environment variable
- Default build uses GTK4, BUILD_TAGS=gtk3 uses legacy GTK3

Taskfile targets:
- test:example:linux - Build with GTK4 (default)
- test:example:linux:gtk3 - Build with GTK3 (legacy)
- test:examples:linux:docker:x86_64 - Docker build with GTK4
- test:examples:linux:docker:x86_64:gtk3 - Docker build with GTK3
- test:examples:linux:docker:arm64 - Docker build with GTK4 (ARM64)
- test:examples:linux:docker:arm64:gtk3 - Docker build with GTK3 (ARM64)

This allows testing both the new GTK4 default and legacy GTK3 builds.

* feat(linux): implement GTK4 dialog system with GtkFileDialog and GtkAlertDialog

Phase 8 of WebKitGTK 6.0/GTK4 implementation.

GTK4 completely replaced the dialog APIs. GTK3's GtkFileChooserDialog
and gtk_dialog_run() are deprecated/removed in GTK4.

File Dialogs (GtkFileDialog):
- gtk_file_dialog_open() for single file selection
- gtk_file_dialog_open_multiple() for multiple files
- gtk_file_dialog_select_folder() for folder selection
- gtk_file_dialog_save() for save dialogs
- Filters use GListStore of GtkFileFilter objects
- All operations are async with GAsyncResult callbacks

Message Dialogs (GtkAlertDialog):
- gtk_alert_dialog_choose() with button array
- Configurable default and cancel button indices
- Async response via callback

Implementation:
- Request ID tracking for async callback matching
- fileDialogCallback/alertDialogCallback C exports
- runChooserDialog/runQuestionDialog Go wrappers
- runOpenFileDialog/runSaveFileDialog convenience functions

* feat(linux): implement GTK4 keyboard accelerators for menu items

Add keyboard accelerator support using gtk_application_set_accels_for_action():

- Add namedKeysToGTK map with GDK keysym values for special keys
- Add parseKeyGTK() to convert key names to GDK keysyms
- Add parseModifiersGTK() to convert Wails modifiers to GDK modifier masks
- Add acceleratorToGTK() for full accelerator conversion
- Add setMenuItemAccelerator() Go wrapper calling C helpers
- Integrate accelerator setting in newMenuItemImpl, newCheckMenuItemImpl,
  and newRadioMenuItemImpl during menu item creation
- Update setAccelerator() method on linuxMenuItem to use new function

Completes Phase 9 of GTK4 implementation.

* refactor(linux): extract GTK4 C code to separate files and fix WebKitGTK 6.0 API

Extract C code from linux_cgo_gtk4.go to dedicated C files for better
IDE support and maintainability:
- linux_cgo_gtk4.h: Function declarations and type definitions
- linux_cgo_gtk4.c: C implementations for GTK4/WebKitGTK 6.0

WebKitGTK 6.0 API fixes:
- webkit_web_view_new_with_user_content_manager() removed
  -> Use create_webview_with_user_content_manager() with g_object_new()
- WEBKIT_HARDWARE_ACCELERATION_POLICY_ON_DEMAND removed
  -> Default to ALWAYS (only ALWAYS/NEVER available in 6.0)
- WebKitJavascriptResult replaced with JSCValue in callbacks
  -> sendMessageToBackend now receives JSCValue* directly

Also:
- Remove duplicate show()/hide() methods (use shared file)
- Remove duplicate startResize() (wrong signature)
- Add set_app_menu_model() setter for C global variable access
- Fix webview.Scheme reference to use hardcoded 'wails' string

Note: Some pre-existing compilation errors remain in the codebase
that are unrelated to this refactoring.

* fix(linux): resolve GTK4 compilation errors and add missing platform methods

- Add missing App methods: logPlatformInfo, platformEnvironment, fatalHandler
- Add missing linuxApp methods: hide, show, on, isOnMainThread, getAccentColor
- Add missing CGO functions: getPrimaryScreen, openDevTools, enableDevTools, handleLoadChanged
- Fix options.Linux nil check (struct not pointer)
- Fix runSaveFileDialog return type to match interface
- Fix registerWindow signature to accept pointer type
- Fix GdkRGBA to use float instead of double
- Add webview import for asset request handling
- Add sanity check task to Taskfile for quick compilation verification

* fix(linux): resolve GTK3/GTK4 symbol conflict in operatingsystem package

- Add gtk3 build tag to webkit_linux.go to prevent GTK3 linking in GTK4 builds
- Create webkit_linux_gtk4.go with GTK4/WebKitGTK 6.0 pkg-config
- Move app initialization from init() to newPlatformApp() for cleaner setup
- Fixes runtime crash: 'GTK 2/3 symbols detected in GTK 4 process'

* docs: update implementation tracker for GTK3/GTK4 symbol conflict fix

* fix(linux): add GTK4 activation gate to prevent window creation before app activation

GTK4 requires the application to be 'activated' before gtk_application_window_new()
can be called. This adds a synchronization mechanism:

- Add activated channel and sync.Once to linuxApp struct
- Mark application as activated in activateLinux callback
- Wait for activation in WebviewWindow.Run() before creating windows

Fixes SIGSEGV crash when creating windows on GTK4.

* feat(linux): add primary menu style option and fix GTK4 menu issues

- Add LinuxMenuStyle option for MenuBar vs PrimaryMenu (hamburger) display
- Fix menu separators using GMenu sections instead of separator items
- Fix radio button styling with proper string-valued stateful actions
- Fix app not terminating when last window closed
- Fix Window→Zoom to toggle maximize instead of webview zoom
- Add build constraints to .c/.h files for GTK3 compatibility
- Document MenuStyle option in window reference docs
- Update implementation tracker with session changes

* chore(examples): use PrimaryMenu style in menu example

* feat(linux): implement Systray API v2 with smart defaults and window options

- Add smart defaults for systray click behavior:
  - Window only: left-click toggles window
  - Menu only: right-click shows menu
  - Window + Menu: left-click toggles, right-click shows menu

- Add HideOnEscape and HideOnFocusLost window options:
  - HideOnEscape: hides window when Escape key pressed
  - HideOnFocusLost: hides window on focus lost (auto-disabled on
    focus-follows-mouse WMs like Hyprland, Sway, i3)

- Add WebviewWindow.RegisterKeyBinding() public method

- Fix Linux systray handlers:
  - Activate() now calls clickHandler (was doubleClickHandler)
  - SecondaryActivate() calls rightClickHandler or opens menu
  - ItemIsMenu always false to let handlers control behavior

- Add environment_linux.go with compositor detection:
  - detectCompositor(), detectFocusFollowsMouse(), isTilingWM()
  - Cursor position detection for Hyprland/Sway

- Add comprehensive manual test suite in v3/test/manual/systray/
  - window-only, menu-only, window-menu, custom-handlers, hide-options
  - Builds for both GTK3 and GTK4
  - README with test matrix for different environments

- Update systray-basic example to use new options

* feat: add doctor-ng package with modern TUI for system diagnostics

Introduces a new pkg/doctor-ng package with a clean public API designed
for reuse by both CLI and future GUI tools. Features include:

- Public API types (Report, SystemInfo, Dependency, DiagnosticResult)
- Platform-specific dependency detection (Linux, macOS, Windows)
- Package manager support (apt, dnf, pacman, emerge, eopkg, nixpkgs, zypper)
- Modern TUI using bubbletea/lipgloss with:
  - Interactive dependency navigation (j/k keys)
  - Install missing dependencies prompt (i key)
  - Refresh/rescan capability (r key)
- Non-interactive mode for CI/scripts (-n flag)

The new command is available as 'wails3 doctor-ng' for testing while
the existing 'wails3 doctor' command remains unchanged.

* fix(doctor-ng): stabilize display order, conditional cursor, add copy to clipboard

- Sort platform extras alphabetically to prevent bouncing
- Only show dependency cursor when there are missing deps to act on
- Add 'c' key to copy sanitized report to clipboard
- Update help text to be contextual based on system state

* feat(doctor-ng): add package manager detection for macOS/Windows, remove unused code

- macOS: detect homebrew, macports, nix; show in platform extras
- Windows: detect winget, scoop, choco; show in platform extras
- Remove unused tui/install.go (replaced by tea.ExecProcess)
- Remove unused stateInstall/viewInstall from model.go
- Remove j/k navigation from help (cursor was already removed)

* feat(cli): add wails3 tool capabilities command

Checks system build capabilities via pkg-config:
- GTK4 and WebKitGTK 6.0 availability
- GTK3 and WebKit2GTK 4.1 availability
- Recommends gtk4 or gtk3 based on what's installed

Output is JSON for easy parsing by Taskfile/scripts.

* fix(linux/gtk4): avoid checkptr errors when building with -race

Go's race detector enables checkptr, which flags storing integers
as pointers (a common GLib/C pattern using GINT_TO_POINTER).

Changes:
- Change signal_connect to accept uintptr_t instead of void* for data
- Change enableDND/disableDND to accept uintptr_t instead of gpointer
- Replace unsafe.Pointer(uintptr(id)) with C.uintptr_t(id) in Go code
- Replace g_object_set/get_data for menu item IDs with Go-side map
- Pass 0 instead of nil for unused signal data parameters

This allows building with 'go build -race' for debugging without
triggering 'checkptr: pointer arithmetic computed bad pointer value'
fatal errors.

* fix(examples/dialogs): use window menu for GTK4 compatibility

GTK4 requires menus to be set on windows, not the application.
Use LinuxMenuStylePrimaryMenu to show menu in header bar.

* test(linux): add manual dialog test suite

Comprehensive test programs for GTK4 dialogs:
- message-info, message-question, message-warning, message-error
- file-open, file-open-multi, file-save, file-directory

Each test has multiple test cases accessible via menu.
Use 'go-task build:gtk4' or 'go-task build:gtk3' to build.

* fix(linux/gtk4): fix file dialog hang by not prematurely freeing dialog

GtkFileDialog is async - gtk_file_dialog_select_folder() returns
immediately and the callback fires later. The defer g_object_unref
was freeing the dialog before the user could interact with it.

GTK manages the dialog lifecycle internally for async operations.

* fix: add mutex to protect runtimeLoaded and pendingJS from races

Multiple goroutines access runtimeLoaded and pendingJS concurrently:
- ExecJS reads/writes from window event handlers
- HandleMessage writes when runtime becomes ready
- InitiateFrontendDropProcessing reads/writes during drag-drop

Added pendingJSMutex to synchronize access. Also changed HandleMessage
to copy pending slice before releasing lock to avoid holding it during
InvokeSync calls.

* fix(linux/gtk4): fix dialog deadlock and alert dialog lifecycle

- dialogs_linux.go: Change InvokeAsync to go func() to prevent deadlock
  when show() is called - runQuestionDialog uses InvokeAsync internally
  and blocks on channel, which deadlocks if caller is also using InvokeAsync
- linux_cgo_gtk4.c: Remove premature g_object_unref from show_alert_dialog
  as GtkAlertDialog is async and GTK manages the lifecycle
- linux_cgo_gtk4.c: Add DEBUG_LOG macro for compile-time debug output
  (CGO_CFLAGS="-DWAILS_GTK_DEBUG" go build ...)
- linux_cgo_gtk4.c: Handle cancelled-with-no-error case in file dialogs
- linux_cgo_gtk4.go: Fix runQuestionDialog to use options.Title as message
- linux_cgo_gtk4.go: Add default OK button when no buttons specified

* feat(linux/gtk4): implement custom message dialogs with proper styling

GTK4's GtkAlertDialog lacks icon support and visual differentiation.
This implements a custom GtkWindow-based dialog with:

- Escape key triggers cancel button via GtkEventControllerKey
- Enter key activates default button via gtk_window_set_default_widget
- Custom icons from bytes with gtk_image_set_pixel_size (64px max)
- Symbolic icons for info/warning/error/question dialogs
- 300px minimum width for better short message appearance
- Proper memory cleanup via message_dialog_cleanup()
- close-request returns cancel button index or -1

* fix(linux/gtk4): use native size for custom dialog icons

Custom icons now display at their native size.
Built-in symbolic icons remain at 32px as designed.

* fix(linux/gtk4): implement native file drag-and-drop

Use GtkDropControllerMotion and GtkDropTarget with GTK_PHASE_CAPTURE
to intercept file drops before WebKit's internal GtkDropTargetAsync
handler in the bubble phase.

- Add on_drop_accept to filter for GDK_TYPE_FILE_LIST
- Add motion controller for enter/leave/motion events
- Set capture phase so our handlers run before WebKit's
- Both controllers attached to WebKitWebView widget

* docs: update implementation tracker and dialog docs

- Update IMPLEMENTATION.md with GTK4 dialog progress
- Add GTK4 dialog documentation to reference docs
- Fix RLock -> Lock in cleanup to allow window modification
- Simplify manual dialog test menus (remove nested submenus)

* fix(linux/gtk4): parse runtime call params from query string

WebKitGTK 6.0 sends POST data as URL query parameters for custom URI
schemes instead of in the request body. Add fallback to parse object,
method, and args from query params when body is empty.

* fix(linux): fallback to application menu when no window menu set

Windows without an explicit Linux.Menu option now inherit the
application-level menu set via app.Menu.Set().

* fix(linux/gtk4): implement sync clipboard API

GTK4 uses async clipboard operations. Implement clipboard_get_text_sync
which iterates the GLib main context until the async read completes.
This avoids deadlock when called from the main thread (e.g., menu handlers).

* fix(linux/gtk4): DPI scaling and menu duplication fixes

- Implement proper DPI scaling using gdk_monitor_get_scale (GTK 4.14+)
  for fractional scaling support on Linux/GTK4
- Calculate PhysicalBounds correctly by multiplying logical coords by scale
- Fix menu items duplicating when creating new windows by adding
  processed flag to prevent re-processing menus
- Add safe type assertion helpers in screen example to prevent crashes
- Add CSS to prevent text selection during drag in screen example
- Document tiling WM limitations (Hyprland, Sway, i3) in official docs

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(tests): add GTK3 vs GTK4 benchmark suite

Add comprehensive benchmark suite for comparing GTK3 and GTK4 performance
in Wails applications. Benchmarks cover:

- Screen enumeration and primary screen query
- Window create/destroy, resize, show/hide operations
- Menu creation (simple, complex, with accelerators)
- Event emit and receive timing
- Dialog setup

Includes comparison tool for side-by-side analysis of results.

Usage:
  go build -tags gtk3 -o benchmark-gtk3 .
  go build -tags gtk4 -o benchmark-gtk4 .
  ./benchmark-gtk3 && ./benchmark-gtk4
  go run compare.go benchmark-GTK3-*.json benchmark-GTK4-*.json

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(examples): add WebView API compatibility checker

Cross-platform example that tests and reports which Web APIs are
available in the current WebView engine. Tests 200+ APIs across
categories:

- Storage (localStorage, IndexedDB, Cache API, File System)
- Network (Fetch, WebSocket, WebTransport, SSE)
- Media (Web Audio, MediaRecorder, Speech APIs)
- Graphics (Canvas, WebGL, WebGL2, WebGPU)
- Device (Geolocation, Sensors, Bluetooth, USB, Serial)
- Workers (Web Workers, Service Workers, Shared Workers)
- Performance (Observers, Timing APIs)
- Security (Web Crypto, WebAuthn, Credentials)
- UI/DOM (Custom Elements, Shadow DOM, Clipboard)
- CSS (CSSOM, Container Queries, Modern Selectors)
- JavaScript (ES Modules, BigInt, Private Fields)

Useful for understanding API availability differences between:
- WebKitGTK (Linux) vs WebView2 (Windows) vs WKWebView (macOS)
- GTK3/WebKit2GTK 4.1 vs GTK4/WebKitGTK 6.0

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(examples): add Web API examples demonstrating browser capabilities

Add 15 interactive Web API examples in v3/examples/web-apis/:
- Storage: localStorage, IndexedDB
- Network: Fetch API, WebSocket
- Media: Canvas 2D, WebGL, Web Audio
- Device: Geolocation, Clipboard, Fullscreen
- Security: WebCrypto
- Notifications API
- Workers: Web Workers
- Observers: Intersection Observer, Resize Observer

Each example includes an interactive demo with API documentation
and feature detection to help developers understand what's
available in WebView environments.

Also updates webview-api-check with autorun support for
automated API compatibility testing.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(examples): add 26 more Web API examples

Expand web-apis examples from 15 to 41 total, covering:

Storage: sessionStorage, Cache API, Page Visibility
Network: XMLHttpRequest, EventSource (SSE), Beacon API
Media: MediaDevices, MediaRecorder, Speech Synthesis
Device: Device Orientation, Vibration, Gamepad
Performance: Performance API, Mutation Observer
UI/DOM: Web Components, Pointer Events, Selection, Dialog
Messaging: Drag and Drop, Broadcast Channel, History API
Data: Streams, File API, Blob, Share, Permissions

Each example includes interactive demos, API detection,
and follows the consistent dark-themed styling pattern.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: update changelog with full web-api examples count

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(examples): simplify beacon demo with local server

Replace the complex beacon demo with a simpler version that includes:
- Local HTTP server on port 9999 that receives beacon data
- Go service to retrieve and display received beacons
- Quick buttons for common beacon types (pageview, click, error, timing)
- Live display of received beacon data with auto-refresh
- Clear explanation of how the demo works

This makes the demo more educational by showing both the sending
and receiving sides of the Beacon API.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(examples): streamline beacon demo UI

Revert to original standalone implementation with httpbin.org endpoint
but with a compact two-column layout that fits without scrolling:
- Left: endpoint config, data type selector, data input, example buttons
- Right: stats (sent/queued/failed/bytes), auto-unload option, event log

Features retained: String/JSON/FormData/Blob data types, analytics/error/
timing examples, auto-beacon on page unload.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(examples): streamline blob demo with tabbed layout

Redesign blob demo to fit without scrolling using:
- Three-column layout: Create | Stored Blobs | Output
- Tabbed interface for blob creation (Text/JSON/Binary/SVG)
- Compact blob list with download and delete actions
- Operations panel for conversions and slicing
- Feature badges showing API support status

Reduced from 846 lines to 349 lines while keeping core functionality.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(examples): fix dropdown styling in blob demo

Style select option elements with dark background to match theme.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(examples): add MDN links to demo titles

Link API names in titles to their MDN documentation pages.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(examples): streamline broadcast-channel with Wails windows

Redesign broadcast-channel demo for Wails environment:
- Replace browser tabs with Wails windows via WindowService
- Compact two-column layout: Channel/Send | Messages
- "Open New Window" button creates new Wails window
- Each window gets unique ID for message tracking
- Join/leave notifications when windows open/close
- Quick message buttons, ping all, stats display
- MDN link in title

Reduced from 737 lines to 245 lines.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(examples): simplify broadcast-channel to use multiple app instances

Remove WindowService that required generated bindings. Instead, instruct
users to run multiple instances of the app to test cross-window messaging.
BroadcastChannel API works across windows of the same origin.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(examples): add API feature badges to broadcast-channel demo

Show supported features: BroadcastChannel, postMessage, close,
onmessage, onmessageerror, MessageChannel - consistent with other demos.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(examples): add multi-window support to broadcast-channel demo

Use Wails runtime.js and WindowService to open new windows for
cross-window BroadcastChannel API testing. Streamlined UI with
feature detection badges and MDN link.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(linux): make GTK4 opt-in via -tags gtk4, keep GTK3 as default

This change inverts the build tag logic so that:
- GTK3/WebKit2GTK 4.1 is the stable default (no tag required)
- GTK4/WebKitGTK 6.0 is experimental opt-in via `-tags gtk4`

This allows the branch to be merged into v3-alpha without breaking
existing apps, while enabling early adopters to test GTK4 support.

Changes:
- Updated 20 Go files: `gtk3` → `!gtk4`, `!gtk3` → `gtk4`
- Updated IMPLEMENTATION.md to reflect new build strategy
- Updated benchmark README with correct build commands
- Added GTK4_FEEDBACK_ISSUE.md template for community testing
- Added Armaan's signing guide link to docs

Build commands after this change:
  go build ./v3/...            # GTK3 (default)
  go build -tags gtk4 ./v3/... # GTK4 (experimental)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(linux): rename capabilities files to follow naming convention

Renamed for consistency with other GTK3/GTK4 file pairs:
- capabilities_linux.go (default, GTK3)
- capabilities_linux_gtk4.go (opt-in, GTK4)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(linux/gtk4): add experimental notice with feedback issue link

When building with -tags gtk4, the app now displays a notice at startup
directing users to the feedback issue for reporting problems.

Issue: https://github.com/wailsapp/wails/issues/4957

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* ci(linux): add GTK4 testing for webkit-gtk6-support branch

- Fix box alignment in experimental notice
- Add GTK4 dependency installation for this branch only
- Run Go tests with both default (GTK3) and -tags gtk4
- Build examples with both GTK versions
- Build templates with both GTK versions

The GTK4 tests only run when PR source branch is feature/webkit-gtk6-support.
This ensures existing PRs are not affected while enabling full GTK4 CI coverage.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(doctor): make GTK3 primary, GTK4 experimental in package checks

Updated all 7 package managers to match new build tag strategy:
- GTK3/WebKit2GTK 4.1 → primary (required for default builds)
- GTK4/WebKitGTK 6.0 → optional/experimental (for -tags gtk4)

Affected: apt, dnf, pacman, zypper, emerge, eopkg, nixpkgs

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs(dialogs): fix GTK3/GTK4 documentation to reflect default behavior

GTK3 is the default, GTK4 is opt-in via -tags gtk4. Updated the dialogs
documentation to clarify this instead of suggesting GTK3 is opt-in.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(examples): escape HTML in web-apis examples to prevent DOM XSS

Add escapeHtml() helper function and escape all user-controlled or
dynamic values before inserting them into innerHTML to address CodeQL
security alerts.

Files fixed:
- beacon: escape log type, message, and class names
- eventsource: escape time and type in log entries
- file-api: escape file name, size, and type
- mediadevices: escape time, type, and message in log entries
- selection: escape text content before applying highlight regex
- share: escape file name, size, and type in file list
- speech-synthesis: escape time, type, and message in log entries
- web-components: escape title and color in shadow DOM template

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(linux): correct GTK4 build tags and Taskfile for GTK3 default

- Fix build tags in linux_cgo_gtk4.c and linux_cgo_gtk4.h from
  `!gtk3` to `gtk4` to match the Go file constraints
- Update Taskfile.yaml to reflect GTK3 as default, GTK4 as opt-in
- Rename test:example:linux:gtk3 to test:example:linux:gtk4
- Comment out GTK4 tests in test:examples since CI doesn't have GTK4 deps

This fixes the CI failure where GTK4 C files were being compiled
by default due to incorrect build constraints.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(systemtray): add missing defaultClickHandler method

Add the defaultClickHandler method that was in v3-alpha but not
properly merged. This method is called from systemtray_darwin.go
when handling tray icon clicks.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(tests): add linux build constraint to gtk4-benchmark

The gtk4-benchmark test is Linux-only but was missing a build
constraint on main.go, causing build failures on macOS/Windows.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* ci(linux): skip hanging GTK4 service tests in CI

The service startup/shutdown tests hang in GTK4 CI environment due to
display initialization issues with xvfb. Skip these specific tests for
now while keeping other GTK4 tests running.

Skipped tests:
- TestServiceStartup
- TestServiceShutdown
- TestServiceStartupShutdown

The *Error variants of these tests still run as they fail fast before
the hang occurs.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* ci(linux): skip all service tests for GTK4 in CI

All service tests hang in GTK4 CI because they require a fully
functional GTK4 display that xvfb cannot provide. Skip all tests
matching "TestService" pattern.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* ci(linux): remove unsupported GTK4 template build test

The wails build command doesn't support the -tags flag yet.
GTK4 compilation is already verified by Go tests, so this
additional template build step is not necessary.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix Copilot review feedback on PR #4958

- Use JSON.stringify() for onclick handlers in storage examples to safely
  handle keys with quotes (sessionstorage, localstorage)
- Guard DeviceOrientationEvent check to prevent ReferenceError on
  unsupported browsers (device-orientation)
- Add type assertion check for Bounds to prevent panic on malformed
  JSON (screens.go)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 21:55:45 +11:00

1587 lines
36 KiB
Go

package application
import (
"fmt"
"runtime"
"slices"
"strings"
"sync"
"sync/atomic"
"unsafe"
"encoding/json"
"github.com/leaanthony/u"
"github.com/wailsapp/wails/v3/internal/assetserver"
"github.com/wailsapp/wails/v3/pkg/events"
)
// Enabled means the feature should be enabled
var Enabled = u.True
// Disabled means the feature should be disabled
var Disabled = u.False
var shouldSkipHideOnFocusLost = func() bool { return false }
// LRTB is a struct that holds Left, Right, Top, Bottom values
type LRTB struct {
Left int
Right int
Top int
Bottom int
}
type (
webviewWindowImpl interface {
setTitle(title string)
setSize(width, height int)
setAlwaysOnTop(alwaysOnTop bool)
setURL(url string)
setResizable(resizable bool)
setMinSize(width, height int)
setMaxSize(width, height int)
execJS(js string)
setBackgroundColour(color RGBA)
run()
center()
size() (int, int)
width() int
height() int
destroy()
reload()
forceReload()
openDevTools()
zoomReset()
zoomIn()
zoomOut()
getZoom() float64
setZoom(zoom float64)
close()
zoom()
setHTML(html string)
on(eventID uint)
minimise()
unminimise()
maximise()
unmaximise()
fullscreen()
unfullscreen()
isMinimised() bool
isMaximised() bool
isFullscreen() bool
isNormal() bool
isVisible() bool
isFocused() bool
focus()
show()
hide()
getScreen() (*Screen, error)
setFrameless(bool)
openContextMenu(menu *Menu, data *ContextMenuData)
nativeWindow() unsafe.Pointer
startDrag() error
startResize(border string) error
print() error
setEnabled(enabled bool)
physicalBounds() Rect
setPhysicalBounds(physicalBounds Rect)
bounds() Rect
setBounds(bounds Rect)
position() (int, int)
setPosition(x int, y int)
relativePosition() (int, int)
setRelativePosition(x int, y int)
flash(enabled bool)
handleKeyEvent(acceleratorString string)
getBorderSizes() *LRTB
setMinimiseButtonState(state ButtonState)
setMaximiseButtonState(state ButtonState)
setCloseButtonState(state ButtonState)
isIgnoreMouseEvents() bool
setIgnoreMouseEvents(ignore bool)
cut()
copy()
paste()
undo()
delete()
selectAll()
redo()
showMenuBar()
hideMenuBar()
toggleMenuBar()
setMenu(menu *Menu)
snapAssist()
setContentProtection(enabled bool)
}
)
type WindowEvent struct {
ctx *WindowEventContext
cancelled atomic.Bool
}
func (w *WindowEvent) Context() *WindowEventContext {
return w.ctx
}
func NewWindowEvent() *WindowEvent {
return &WindowEvent{}
}
func (w *WindowEvent) IsCancelled() bool {
return w.cancelled.Load()
}
func (w *WindowEvent) Cancel() {
w.cancelled.Store(true)
}
type WindowEventListener struct {
callback func(event *WindowEvent)
}
type WebviewWindow struct {
options WebviewWindowOptions
impl webviewWindowImpl
id uint
eventListeners map[uint][]*WindowEventListener
eventListenersLock sync.RWMutex
eventHooks map[uint][]*WindowEventListener
eventHooksLock sync.RWMutex
// A map of listener cancellation functions
cancellersLock sync.RWMutex
cancellers []func()
// keyBindings holds the keybindings for the window
keyBindings map[string]func(Window)
keyBindingsLock sync.RWMutex
// menuBindings holds the menu bindings for the window
menuBindings map[string]*MenuItem
menuBindingsLock sync.RWMutex
// Indicates that the window is destroyed
destroyed bool
destroyedLock sync.RWMutex
runtimeLoaded bool
pendingJS []string
pendingJSMutex sync.Mutex
// unconditionallyClose marks the window to be unconditionally closed (atomic)
unconditionallyClose uint32
}
func (w *WebviewWindow) SetMenu(menu *Menu) {
switch runtime.GOOS {
case "darwin":
return
case "windows":
w.options.Windows.Menu = menu
case "linux":
w.options.Linux.Menu = menu
}
if w.impl != nil {
InvokeSync(func() {
w.impl.setMenu(menu)
})
}
}
// EmitEvent emits a custom event with the specified name and associated data.
// It returns a boolean indicating whether the event was cancelled by a hook.
// The [CustomEvent.Sender] field will be set to the window name.
//
// If the given event name is registered, EmitEvent validates the data parameter
// against the expected data type. In case of a mismatch, EmitEvent reports an error
// to the registered error handler for the application and cancels the event.
func (w *WebviewWindow) EmitEvent(name string, data ...any) bool {
event := &CustomEvent{
Name: name,
Sender: w.Name(),
}
if len(data) == 1 {
event.Data = data[0]
} else if len(data) > 1 {
event.Data = data
}
return globalApplication.Event.EmitEvent(event)
}
var windowID uint
var windowIDLock sync.RWMutex
func getWindowID() uint {
windowIDLock.Lock()
defer windowIDLock.Unlock()
windowID++
return windowID
}
// FIXME: This should like be an interface method (TDM)
// Use onApplicationEvent to register a callback for an application event from a window.
// This will handle tidying up the callback when the window is destroyed
func (w *WebviewWindow) onApplicationEvent(
eventType events.ApplicationEventType,
callback func(*ApplicationEvent),
) {
cancelFn := globalApplication.Event.OnApplicationEvent(eventType, callback)
w.addCancellationFunction(cancelFn)
}
func (w *WebviewWindow) markAsDestroyed() {
w.destroyedLock.Lock()
defer w.destroyedLock.Unlock()
w.destroyed = true
}
func (w *WebviewWindow) setupEventMapping() {
var mapping map[events.WindowEventType]events.WindowEventType
switch runtime.GOOS {
case "darwin":
mapping = w.options.Mac.EventMapping
case "windows":
mapping = w.options.Windows.EventMapping
case "linux":
// TBD
}
if mapping == nil {
mapping = events.DefaultWindowEventMapping()
}
for source, target := range mapping {
source := source
target := target
w.OnWindowEvent(source, func(event *WindowEvent) {
w.emit(target)
})
}
}
// NewWindow creates a new window with the given options
func NewWindow(options WebviewWindowOptions) *WebviewWindow {
thisWindowID := getWindowID()
if options.Width == 0 {
options.Width = 800
}
if options.Height == 0 {
options.Height = 600
}
if options.URL == "" {
options.URL = "/"
}
if options.Name == "" {
options.Name = fmt.Sprintf("window-%d", thisWindowID)
}
result := &WebviewWindow{
id: thisWindowID,
options: options,
eventListeners: make(map[uint][]*WindowEventListener),
eventHooks: make(map[uint][]*WindowEventListener),
menuBindings: make(map[string]*MenuItem),
}
result.setupEventMapping()
// Listen for window closing events and de
result.OnWindowEvent(events.Common.WindowClosing, func(event *WindowEvent) {
atomic.StoreUint32(&result.unconditionallyClose, 1)
InvokeSync(result.markAsDestroyed)
InvokeSync(result.impl.close)
globalApplication.Window.Remove(result.id)
})
// Process keybindings
if result.options.KeyBindings != nil {
result.keyBindings = processKeyBindingOptions(result.options.KeyBindings)
}
if result.options.HideOnEscape {
result.RegisterKeyBinding("escape", func(window Window) {
window.Hide()
})
}
if result.options.HideOnFocusLost {
result.setupHideOnFocusLost()
}
return result
}
func processKeyBindingOptions(
keyBindings map[string]func(window Window),
) map[string]func(window Window) {
result := make(map[string]func(window Window))
for key, callback := range keyBindings {
// Parse the key to an accelerator
acc, err := parseAccelerator(key)
if err != nil {
globalApplication.error("invalid keybinding: %w", err)
continue
}
result[acc.String()] = callback
globalApplication.debug("Added Keybinding", "accelerator", acc.String())
}
return result
}
func (w *WebviewWindow) setupHideOnFocusLost() {
if runtime.GOOS == "linux" && shouldSkipHideOnFocusLost() {
return
}
w.OnWindowEvent(events.Common.WindowLostFocus, func(event *WindowEvent) {
w.Hide()
})
}
func (w *WebviewWindow) addCancellationFunction(canceller func()) {
w.cancellersLock.Lock()
defer w.cancellersLock.Unlock()
w.cancellers = append(w.cancellers, canceller)
}
func (w *WebviewWindow) ID() uint {
return w.id
}
// SetTitle sets the title of the window
func (w *WebviewWindow) SetTitle(title string) Window {
w.options.Title = title
if w.impl != nil {
InvokeSync(func() {
w.impl.setTitle(title)
})
}
return w
}
// Name returns the name of the window
func (w *WebviewWindow) Name() string {
return w.options.Name
}
// SetSize sets the size of the window
func (w *WebviewWindow) SetSize(width, height int) Window {
// Don't set size if fullscreen
if w.IsFullscreen() {
return w
}
w.options.Width = width
w.options.Height = height
var newMaxWidth = w.options.MaxWidth
var newMaxHeight = w.options.MaxHeight
if width > w.options.MaxWidth && w.options.MaxWidth != 0 {
newMaxWidth = width
}
if height > w.options.MaxHeight && w.options.MaxHeight != 0 {
newMaxHeight = height
}
if newMaxWidth != 0 || newMaxHeight != 0 {
w.SetMaxSize(newMaxWidth, newMaxHeight)
}
var newMinWidth = w.options.MinWidth
var newMinHeight = w.options.MinHeight
if width < w.options.MinWidth && w.options.MinWidth != 0 {
newMinWidth = width
}
if height < w.options.MinHeight && w.options.MinHeight != 0 {
newMinHeight = height
}
if newMinWidth != 0 || newMinHeight != 0 {
w.SetMinSize(newMinWidth, newMinHeight)
}
if w.impl != nil {
InvokeSync(func() {
w.impl.setSize(width, height)
})
}
return w
}
func (w *WebviewWindow) Run() {
if w.impl != nil {
return
}
w.impl = newWindowImpl(w)
// On Linux GTK4, we must wait for the application to be activated
// before creating windows with gtk_application_window_new()
if nativeApp := globalApplication.impl; nativeApp != nil {
if waiter, ok := nativeApp.(interface{ waitForActivation() }); ok {
waiter.waitForActivation()
}
}
InvokeSync(w.impl.run)
}
// SetAlwaysOnTop sets the window to be always on top.
func (w *WebviewWindow) SetAlwaysOnTop(b bool) Window {
w.options.AlwaysOnTop = b
if w.impl != nil {
InvokeSync(func() {
w.impl.setAlwaysOnTop(b)
})
}
return w
}
// Show shows the window.
func (w *WebviewWindow) Show() Window {
if globalApplication.impl == nil {
return w
}
if w.impl == nil || w.isDestroyed() {
InvokeSync(w.Run)
return w
}
w.options.Hidden = false
InvokeSync(w.impl.show)
return w
}
// Hide hides the window.
func (w *WebviewWindow) Hide() Window {
w.options.Hidden = true
if w.impl != nil {
InvokeSync(w.impl.hide)
}
return w
}
func (w *WebviewWindow) SetURL(s string) Window {
url, _ := assetserver.GetStartURL(s)
w.options.URL = url
if w.impl != nil {
InvokeSync(func() {
w.impl.setURL(url)
})
}
return w
}
func (w *WebviewWindow) GetBorderSizes() *LRTB {
if w.impl != nil {
return InvokeSyncWithResult(w.impl.getBorderSizes)
}
return &LRTB{}
}
// SetZoom sets the zoom level of the window.
func (w *WebviewWindow) SetZoom(magnification float64) Window {
w.options.Zoom = magnification
if w.impl != nil {
InvokeSync(func() {
w.impl.setZoom(magnification)
})
}
return w
}
// GetZoom returns the current zoom level of the window.
func (w *WebviewWindow) GetZoom() float64 {
if w.impl != nil {
return InvokeSyncWithResult(w.impl.getZoom)
}
return 1
}
// SetResizable sets whether the window is resizable.
func (w *WebviewWindow) SetResizable(b bool) Window {
w.options.DisableResize = !b
if w.impl != nil {
InvokeSync(func() {
w.impl.setResizable(b)
})
}
return w
}
func (w *WebviewWindow) SetContentProtection(b bool) Window {
if w.impl == nil {
w.options.ContentProtectionEnabled = b
} else {
InvokeSync(func() {
w.impl.setContentProtection(b)
})
}
return w
}
// Resizable returns true if the window is resizable.
func (w *WebviewWindow) Resizable() bool {
return !w.options.DisableResize
}
// SetMinSize sets the minimum size of the window.
func (w *WebviewWindow) SetMinSize(minWidth, minHeight int) Window {
w.options.MinWidth = minWidth
w.options.MinHeight = minHeight
currentWidth, currentHeight := w.Size()
newWidth, newHeight := currentWidth, currentHeight
var newSize bool
if minHeight != 0 && currentHeight < minHeight {
newHeight = minHeight
w.options.Height = newHeight
newSize = true
}
if minWidth != 0 && currentWidth < minWidth {
newWidth = minWidth
w.options.Width = newWidth
newSize = true
}
if w.impl != nil {
if newSize {
InvokeSync(func() {
w.impl.setSize(newWidth, newHeight)
})
}
InvokeSync(func() {
w.impl.setMinSize(minWidth, minHeight)
})
}
return w
}
// SetMaxSize sets the maximum size of the window.
func (w *WebviewWindow) SetMaxSize(maxWidth, maxHeight int) Window {
w.options.MaxWidth = maxWidth
w.options.MaxHeight = maxHeight
currentWidth, currentHeight := w.Size()
newWidth, newHeight := currentWidth, currentHeight
var newSize bool
if maxHeight != 0 && currentHeight > maxHeight {
newHeight = maxHeight
w.options.Height = maxHeight
newSize = true
}
if maxWidth != 0 && currentWidth > maxWidth {
newWidth = maxWidth
w.options.Width = maxWidth
newSize = true
}
if w.impl != nil {
if newSize {
InvokeSync(func() {
w.impl.setSize(newWidth, newHeight)
})
}
InvokeSync(func() {
w.impl.setMaxSize(maxWidth, maxHeight)
})
}
return w
}
// ExecJS executes the given javascript in the context of the window.
func (w *WebviewWindow) ExecJS(js string) {
if w.impl == nil || w.isDestroyed() {
return
}
w.pendingJSMutex.Lock()
if w.runtimeLoaded {
w.pendingJSMutex.Unlock()
InvokeSync(func() {
w.impl.execJS(js)
})
} else {
w.pendingJS = append(w.pendingJS, js)
w.pendingJSMutex.Unlock()
}
}
// Fullscreen sets the window to fullscreen mode. Min/Max size constraints are disabled.
func (w *WebviewWindow) Fullscreen() Window {
if w.impl == nil || w.isDestroyed() {
w.options.StartState = WindowStateFullscreen
return w
}
if !w.IsFullscreen() {
w.DisableSizeConstraints()
InvokeSync(w.impl.fullscreen)
}
return w
}
func (w *WebviewWindow) SetMinimiseButtonState(state ButtonState) Window {
w.options.MinimiseButtonState = state
if w.impl != nil {
InvokeSync(func() {
w.impl.setMinimiseButtonState(state)
})
}
return w
}
func (w *WebviewWindow) SetMaximiseButtonState(state ButtonState) Window {
w.options.MaximiseButtonState = state
if w.impl != nil {
InvokeSync(func() {
w.impl.setMaximiseButtonState(state)
})
}
return w
}
func (w *WebviewWindow) SetCloseButtonState(state ButtonState) Window {
w.options.CloseButtonState = state
if w.impl != nil {
InvokeSync(func() {
w.impl.setCloseButtonState(state)
})
}
return w
}
// Flash flashes the window's taskbar button/icon.
// Useful to indicate that attention is required. Windows only.
func (w *WebviewWindow) Flash(enabled bool) {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
w.impl.flash(enabled)
})
}
// IsMinimised returns true if the window is minimised
func (w *WebviewWindow) IsMinimised() bool {
if w.impl == nil || w.isDestroyed() {
return false
}
return InvokeSyncWithResult(w.impl.isMinimised)
}
// IsVisible returns true if the window is visible
func (w *WebviewWindow) IsVisible() bool {
if w.impl == nil || w.isDestroyed() {
return false
}
return InvokeSyncWithResult(w.impl.isVisible)
}
// IsMaximised returns true if the window is maximised
func (w *WebviewWindow) IsMaximised() bool {
if w.impl == nil || w.isDestroyed() {
return false
}
return InvokeSyncWithResult(w.impl.isMaximised)
}
// Size returns the size of the window
func (w *WebviewWindow) Size() (int, int) {
if w.impl == nil || w.isDestroyed() {
return 0, 0
}
var width, height int
InvokeSync(func() {
width, height = w.impl.size()
})
return width, height
}
// IsFocused returns true if the window is currently focused
func (w *WebviewWindow) IsFocused() bool {
if w.impl == nil || w.isDestroyed() {
return false
}
return InvokeSyncWithResult(w.impl.isFocused)
}
// IsFullscreen returns true if the window is fullscreen
func (w *WebviewWindow) IsFullscreen() bool {
if w.impl == nil || w.isDestroyed() {
return false
}
return InvokeSyncWithResult(w.impl.isFullscreen)
}
// SetBackgroundColour sets the background colour of the window
func (w *WebviewWindow) SetBackgroundColour(colour RGBA) Window {
w.options.BackgroundColour = colour
if w.impl != nil {
InvokeSync(func() {
w.impl.setBackgroundColour(colour)
})
}
return w
}
func (w *WebviewWindow) HandleMessage(message string) {
// Check for special messages
switch true {
case message == "wails:drag":
if !w.IsFullscreen() {
InvokeSync(func() {
err := w.startDrag()
if err != nil {
w.Error("failed to start drag: %w", err)
}
})
}
case strings.HasPrefix(message, "wails:resize:"):
if !w.IsFullscreen() {
sl := strings.Split(message, ":")
if len(sl) != 3 {
w.Error("unknown message returned from dispatcher: %s", message)
return
}
err := w.startResize(sl[2])
if err != nil {
w.Error("%w", err)
}
}
case message == "wails:runtime:ready":
w.emit(events.Common.WindowRuntimeReady)
w.pendingJSMutex.Lock()
w.runtimeLoaded = true
pending := w.pendingJS
w.pendingJS = nil
w.pendingJSMutex.Unlock()
w.SetResizable(!w.options.DisableResize)
for _, js := range pending {
InvokeSync(func() {
w.impl.execJS(js)
})
}
default:
w.Error("unknown message sent via 'invoke' on frontend: %v", message)
}
}
func (w *WebviewWindow) startResize(border string) error {
if w.impl == nil || w.isDestroyed() {
return nil
}
return InvokeSyncWithResult(func() error {
return w.impl.startResize(border)
})
}
// Center centers the window on the screen
func (w *WebviewWindow) Center() {
if w.impl == nil || w.isDestroyed() {
w.options.InitialPosition = WindowCentered
return
}
InvokeSync(w.impl.center)
}
// OnWindowEvent registers a callback for the given window event
func (w *WebviewWindow) OnWindowEvent(
eventType events.WindowEventType,
callback func(event *WindowEvent),
) func() {
eventID := uint(eventType)
windowEventListener := &WindowEventListener{
callback: callback,
}
w.eventListenersLock.Lock()
w.eventListeners[eventID] = append(w.eventListeners[eventID], windowEventListener)
w.eventListenersLock.Unlock()
if w.impl != nil {
w.impl.on(eventID)
}
return func() {
// Check if eventListener is already locked
w.eventListenersLock.Lock()
w.eventListeners[eventID] = slices.DeleteFunc(w.eventListeners[eventID], func(l *WindowEventListener) bool {
return l == windowEventListener
})
w.eventListenersLock.Unlock()
}
}
// RegisterHook registers a hook for the given window event
func (w *WebviewWindow) RegisterHook(
eventType events.WindowEventType,
callback func(event *WindowEvent),
) func() {
eventID := uint(eventType)
w.eventHooksLock.Lock()
defer w.eventHooksLock.Unlock()
windowEventHook := &WindowEventListener{
callback: callback,
}
w.eventHooks[eventID] = append(w.eventHooks[eventID], windowEventHook)
return func() {
w.eventHooksLock.Lock()
defer w.eventHooksLock.Unlock()
w.eventHooks[eventID] = slices.DeleteFunc(w.eventHooks[eventID], func(l *WindowEventListener) bool {
return l == windowEventHook
})
}
}
func (w *WebviewWindow) HandleWindowEvent(id uint) {
// Get hooks
w.eventHooksLock.RLock()
hooks := w.eventHooks[id]
w.eventHooksLock.RUnlock()
// Create new WindowEvent
thisEvent := NewWindowEvent()
for _, thisHook := range hooks {
thisHook.callback(thisEvent)
if thisEvent.IsCancelled() {
return
}
}
// Copy the w.eventListeners
w.eventListenersLock.RLock()
var tempListeners = slices.Clone(w.eventListeners[id])
w.eventListenersLock.RUnlock()
for _, listener := range tempListeners {
go func() {
if thisEvent.IsCancelled() {
return
}
defer handlePanic()
listener.callback(thisEvent)
}()
}
w.dispatchWindowEvent(id)
}
// Width returns the width of the window
func (w *WebviewWindow) Width() int {
if w.impl == nil || w.isDestroyed() {
return 0
}
return InvokeSyncWithResult(w.impl.width)
}
// Height returns the height of the window
func (w *WebviewWindow) Height() int {
if w.impl == nil || w.isDestroyed() {
return 0
}
return InvokeSyncWithResult(w.impl.height)
}
// PhysicalBounds returns the physical bounds of the window
func (w *WebviewWindow) PhysicalBounds() Rect {
if w.impl == nil || w.isDestroyed() {
return Rect{}
}
var rect Rect
InvokeSync(func() {
rect = w.impl.physicalBounds()
})
return rect
}
// SetPhysicalBounds sets the physical bounds of the window
func (w *WebviewWindow) SetPhysicalBounds(physicalBounds Rect) {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
w.impl.setPhysicalBounds(physicalBounds)
})
}
// Bounds returns the DIP bounds of the window
func (w *WebviewWindow) Bounds() Rect {
if w.impl == nil || w.isDestroyed() {
return Rect{}
}
var rect Rect
InvokeSync(func() {
rect = w.impl.bounds()
})
return rect
}
// SetBounds sets the DIP bounds of the window
func (w *WebviewWindow) SetBounds(bounds Rect) {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
w.impl.setBounds(bounds)
})
}
// Position returns the absolute position of the window
func (w *WebviewWindow) Position() (int, int) {
if w.impl == nil || w.isDestroyed() {
return 0, 0
}
var x, y int
InvokeSync(func() {
x, y = w.impl.position()
})
return x, y
}
// SetPosition sets the absolute position of the window.
func (w *WebviewWindow) SetPosition(x int, y int) {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
w.impl.setPosition(x, y)
})
}
// RelativePosition returns the position of the window relative to the screen WorkArea on which it is
func (w *WebviewWindow) RelativePosition() (int, int) {
if w.impl == nil || w.isDestroyed() {
return 0, 0
}
var x, y int
InvokeSync(func() {
x, y = w.impl.relativePosition()
})
return x, y
}
// SetRelativePosition sets the position of the window relative to the screen WorkArea on which it is.
func (w *WebviewWindow) SetRelativePosition(x, y int) Window {
w.options.X = x
w.options.Y = y
if w.impl != nil {
InvokeSync(func() {
w.impl.setRelativePosition(x, y)
})
}
return w
}
func (w *WebviewWindow) destroy() {
if w.impl == nil || w.isDestroyed() {
return
}
// Cancel the callbacks
for _, cancelFunc := range w.cancellers {
cancelFunc()
}
InvokeSync(w.impl.destroy)
}
// Reload reloads the page assets
func (w *WebviewWindow) Reload() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(w.impl.reload)
}
// ForceReload forces the window to reload the page assets
func (w *WebviewWindow) ForceReload() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(w.impl.forceReload)
}
// ToggleFullscreen toggles the window between fullscreen and normal
func (w *WebviewWindow) ToggleFullscreen() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
if w.IsFullscreen() {
w.UnFullscreen()
} else {
w.Fullscreen()
}
})
}
// ToggleMaximise toggles the window between maximised and normal
func (w *WebviewWindow) ToggleMaximise() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
if w.IsMaximised() {
w.UnMaximise()
} else {
w.Maximise()
}
})
}
// ToggleFrameless toggles the window between frameless and normal
func (w *WebviewWindow) ToggleFrameless() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
w.SetFrameless(!w.options.Frameless)
})
}
func (w *WebviewWindow) OpenDevTools() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(w.impl.openDevTools)
}
// ZoomReset resets the zoom level of the webview content to 100%
func (w *WebviewWindow) ZoomReset() Window {
if w.impl != nil {
InvokeSync(w.impl.zoomReset)
}
return w
}
// ZoomIn increases the zoom level of the webview content
func (w *WebviewWindow) ZoomIn() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(w.impl.zoomIn)
}
// ZoomOut decreases the zoom level of the webview content
func (w *WebviewWindow) ZoomOut() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(w.impl.zoomOut)
}
// Close closes the window
func (w *WebviewWindow) Close() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
w.emit(events.Common.WindowClosing)
})
}
func (w *WebviewWindow) Zoom() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(w.impl.zoom)
}
// SetHTML sets the HTML of the window to the given html string.
func (w *WebviewWindow) SetHTML(html string) Window {
w.options.HTML = html
if w.impl != nil {
InvokeSync(func() {
w.impl.setHTML(html)
})
}
return w
}
// Minimise minimises the window.
func (w *WebviewWindow) Minimise() Window {
if w.impl == nil || w.isDestroyed() {
w.options.StartState = WindowStateMinimised
return w
}
if !w.IsMinimised() {
InvokeSync(w.impl.minimise)
}
return w
}
// Maximise maximises the window. Min/Max size constraints are disabled.
func (w *WebviewWindow) Maximise() Window {
if w.impl == nil || w.isDestroyed() {
w.options.StartState = WindowStateMaximised
return w
}
if !w.IsMaximised() {
w.DisableSizeConstraints()
InvokeSync(w.impl.maximise)
}
return w
}
// UnMinimise un-minimises the window. Min/Max size constraints are re-enabled.
func (w *WebviewWindow) UnMinimise() {
if w.impl == nil || w.isDestroyed() {
return
}
if w.IsMinimised() {
InvokeSync(w.impl.unminimise)
}
}
// UnMaximise un-maximises the window. Min/Max size constraints are re-enabled.
func (w *WebviewWindow) UnMaximise() {
if w.IsMaximised() {
w.EnableSizeConstraints()
InvokeSync(w.impl.unmaximise)
}
}
// UnFullscreen un-fullscreens the window. Min/Max size constraints are re-enabled.
func (w *WebviewWindow) UnFullscreen() {
if w.IsFullscreen() {
w.EnableSizeConstraints()
InvokeSync(w.impl.unfullscreen)
}
}
// Restore restores the window to its previous state if it was previously minimised, maximised or fullscreen.
func (w *WebviewWindow) Restore() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
if w.IsMinimised() {
w.UnMinimise()
} else if w.IsFullscreen() {
w.UnFullscreen()
} else if w.IsMaximised() {
w.UnMaximise()
}
})
}
func (w *WebviewWindow) DisableSizeConstraints() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
if w.options.MinWidth > 0 && w.options.MinHeight > 0 {
w.impl.setMinSize(0, 0)
}
if w.options.MaxWidth > 0 && w.options.MaxHeight > 0 {
w.impl.setMaxSize(0, 0)
}
})
}
func (w *WebviewWindow) EnableSizeConstraints() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
if w.options.MinWidth > 0 && w.options.MinHeight > 0 {
w.SetMinSize(w.options.MinWidth, w.options.MinHeight)
}
if w.options.MaxWidth > 0 && w.options.MaxHeight > 0 {
w.SetMaxSize(w.options.MaxWidth, w.options.MaxHeight)
}
})
}
// GetScreen returns the screen that the window is on
func (w *WebviewWindow) GetScreen() (*Screen, error) {
if w.impl == nil || w.isDestroyed() {
return nil, nil
}
return InvokeSyncWithResultAndError(w.impl.getScreen)
}
// SetFrameless removes the window frame and title bar
func (w *WebviewWindow) SetFrameless(frameless bool) Window {
w.options.Frameless = frameless
if w.impl != nil {
InvokeSync(func() {
w.impl.setFrameless(frameless)
})
}
return w
}
func (w *WebviewWindow) DispatchWailsEvent(event *CustomEvent) {
// Guard against race condition where event fires before runtime is initialized
// This can happen during page reload when WindowLoadFinished fires before
// the JavaScript runtime has mounted dispatchWailsEvent on window._wails
msg := fmt.Sprintf("if(window._wails&&window._wails.dispatchWailsEvent){window._wails.dispatchWailsEvent(%s);}", event.ToJSON())
w.ExecJS(msg)
}
func (w *WebviewWindow) dispatchWindowEvent(id uint) {
// TODO: Make this more efficient by keeping a list of which events have been registered
// and only dispatching those.
jsEvent := &CustomEvent{
Name: events.JSEvent(id),
}
w.DispatchWailsEvent(jsEvent)
}
func (w *WebviewWindow) Info(message string, args ...any) {
var messageArgs []interface{}
messageArgs = append(messageArgs, args...)
messageArgs = append(messageArgs, "sender", w.Name())
globalApplication.info(message, messageArgs...)
}
func (w *WebviewWindow) Error(message string, args ...any) {
args = append([]any{w.Name()}, args...)
globalApplication.error("in window '%s': "+message, args...)
}
func (w *WebviewWindow) handleDragAndDropMessage(filenames []string, dropTarget *DropTargetDetails) {
thisEvent := NewWindowEvent()
ctx := newWindowEventContext()
ctx.setDroppedFiles(filenames)
if dropTarget != nil {
ctx.setDropTargetDetails(dropTarget)
}
thisEvent.ctx = ctx
listeners := w.eventListeners[uint(events.Common.WindowFilesDropped)]
for _, listener := range listeners {
if listener == nil {
continue
}
listener.callback(thisEvent)
}
}
func (w *WebviewWindow) OpenContextMenu(data *ContextMenuData) {
// try application level context menu
menu, ok := globalApplication.ContextMenu.Get(data.Id)
if !ok {
w.Error("no context menu found for id: %s", data.Id)
return
}
menu.setContextData(data)
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
w.impl.openContextMenu(menu.Menu, data)
})
}
// NativeWindow returns the platform-specific native window handle
func (w *WebviewWindow) NativeWindow() unsafe.Pointer {
if w.impl == nil || w.isDestroyed() {
return nil
}
return w.impl.nativeWindow()
}
// shouldUnconditionallyClose returns whether the window should close unconditionally
func (w *WebviewWindow) shouldUnconditionallyClose() bool {
return atomic.LoadUint32(&w.unconditionallyClose) != 0
}
func (w *WebviewWindow) Focus() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(w.impl.focus)
}
func (w *WebviewWindow) emit(eventType events.WindowEventType) {
windowEvents <- &windowEvent{
WindowID: w.id,
EventID: uint(eventType),
}
}
func (w *WebviewWindow) startDrag() error {
if w.impl == nil || w.isDestroyed() {
return nil
}
return InvokeSyncWithError(w.impl.startDrag)
}
func (w *WebviewWindow) Print() error {
if w.impl == nil || w.isDestroyed() {
return nil
}
return InvokeSyncWithError(w.impl.print)
}
func (w *WebviewWindow) SetEnabled(enabled bool) {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
w.impl.setEnabled(enabled)
})
}
func (w *WebviewWindow) processKeyBinding(acceleratorString string) bool {
// Check menu bindings
if w.menuBindings != nil {
w.menuBindingsLock.RLock()
defer w.menuBindingsLock.RUnlock()
if menuItem := w.menuBindings[acceleratorString]; menuItem != nil {
menuItem.handleClick()
return true
}
}
// Check key bindings
if w.keyBindings != nil {
w.keyBindingsLock.RLock()
defer w.keyBindingsLock.RUnlock()
if callback := w.keyBindings[acceleratorString]; callback != nil {
// Execute callback
go func() {
defer handlePanic()
callback(w)
}()
return true
}
}
return globalApplication.KeyBinding.Process(acceleratorString, w)
}
func (w *WebviewWindow) HandleKeyEvent(acceleratorString string) {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(func() {
w.impl.handleKeyEvent(acceleratorString)
})
}
func (w *WebviewWindow) isDestroyed() bool {
w.destroyedLock.RLock()
defer w.destroyedLock.RUnlock()
return w.destroyed
}
func (w *WebviewWindow) RegisterKeyBinding(binding string, callback func(window Window)) *WebviewWindow {
acc, err := parseAccelerator(binding)
if err != nil {
globalApplication.error("invalid keybinding: %w", err)
return w
}
w.keyBindingsLock.Lock()
defer w.keyBindingsLock.Unlock()
if w.keyBindings == nil {
w.keyBindings = make(map[string]func(Window))
}
w.keyBindings[acc.String()] = callback
return w
}
func (w *WebviewWindow) removeMenuBinding(a *accelerator) {
w.menuBindingsLock.Lock()
defer w.menuBindingsLock.Unlock()
w.menuBindings[a.String()] = nil
}
func (w *WebviewWindow) addMenuBinding(a *accelerator, menuItem *MenuItem) {
w.menuBindingsLock.Lock()
defer w.menuBindingsLock.Unlock()
w.menuBindings[a.String()] = menuItem
}
func (w *WebviewWindow) IsIgnoreMouseEvents() bool {
if w.impl == nil || w.isDestroyed() {
return false
}
return InvokeSyncWithResult(w.impl.isIgnoreMouseEvents)
}
func (w *WebviewWindow) SetIgnoreMouseEvents(ignore bool) Window {
w.options.IgnoreMouseEvents = ignore
if w.impl == nil || w.isDestroyed() {
return w
}
InvokeSync(func() {
w.impl.setIgnoreMouseEvents(ignore)
})
return w
}
func (w *WebviewWindow) cut() {
if w.impl == nil || w.isDestroyed() {
return
}
w.impl.cut()
}
func (w *WebviewWindow) copy() {
if w.impl == nil || w.isDestroyed() {
return
}
w.impl.copy()
}
func (w *WebviewWindow) paste() {
if w.impl == nil || w.isDestroyed() {
return
}
w.impl.paste()
}
func (w *WebviewWindow) selectAll() {
if w.impl == nil || w.isDestroyed() {
return
}
w.impl.selectAll()
}
func (w *WebviewWindow) undo() {
if w.impl == nil || w.isDestroyed() {
return
}
w.impl.undo()
}
func (w *WebviewWindow) delete() {
if w.impl == nil || w.isDestroyed() {
return
}
w.impl.delete()
}
func (w *WebviewWindow) redo() {
if w.impl == nil || w.isDestroyed() {
return
}
w.impl.redo()
}
// ShowMenuBar shows the menu bar for the window.
func (w *WebviewWindow) ShowMenuBar() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(w.impl.showMenuBar)
}
// HideMenuBar hides the menu bar for the window.
func (w *WebviewWindow) HideMenuBar() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(w.impl.hideMenuBar)
}
// ToggleMenuBar toggles the menu bar for the window.
func (w *WebviewWindow) ToggleMenuBar() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(w.impl.toggleMenuBar)
}
func (w *WebviewWindow) InitiateFrontendDropProcessing(filenames []string, x int, y int) {
if w.impl == nil || w.isDestroyed() {
return
}
filenamesJSON, err := json.Marshal(filenames)
if err != nil {
w.Error("Error marshalling filenames for drop processing: %s", err)
return
}
jsCall := fmt.Sprintf(
"window._wails.handlePlatformFileDrop(%s, %d, %d);",
string(filenamesJSON),
x,
y,
)
w.pendingJSMutex.Lock()
if !w.runtimeLoaded {
w.pendingJS = append(w.pendingJS, jsCall)
w.pendingJSMutex.Unlock()
return
}
w.pendingJSMutex.Unlock()
InvokeSync(func() {
w.impl.execJS(jsCall)
})
}
// HandleDragEnter is called when drag enters the window (Linux only, since GTK intercepts drag events)
func (w *WebviewWindow) HandleDragEnter() {
if w.impl == nil || w.isDestroyed() || !w.runtimeLoaded {
return
}
// Reset drag hover state for new drag session
dragHover.lastSentX = 0
dragHover.lastSentY = 0
w.impl.execJS("window._wails.handleDragEnter();")
}
// Drag hover throttle state
var dragHover struct {
lastSentX int
lastSentY int
}
// HandleDragOver is called during drag-motion to update hover state in JS
// This is called from the GTK main thread, so we can call execJS directly
func (w *WebviewWindow) HandleDragOver(x int, y int) {
if w.impl == nil || w.isDestroyed() || !w.runtimeLoaded {
return
}
// Throttle: only send if moved at least 5 pixels
dx := x - dragHover.lastSentX
dy := y - dragHover.lastSentY
if dx < 0 {
dx = -dx
}
if dy < 0 {
dy = -dy
}
if dx < 5 && dy < 5 {
return
}
dragHover.lastSentX = x
dragHover.lastSentY = y
// Use platform-specific zero-alloc implementation if available
if impl, ok := w.impl.(interface{ execJSDragOver(x, y int) }); ok {
impl.execJSDragOver(x, y)
} else {
w.impl.execJS(fmt.Sprintf("window._wails.handleDragOver(%d,%d)", x, y))
}
}
// HandleDragLeave is called when drag leaves the window
func (w *WebviewWindow) HandleDragLeave() {
if w.impl == nil || w.isDestroyed() || !w.runtimeLoaded {
return
}
// Don't use InvokeSync - execJS already handles main thread dispatch internally
w.impl.execJS("window._wails.handleDragLeave();")
}
// SnapAssist triggers the Windows Snap Assist feature by simulating Win+Z key combination.
// On Windows, this opens the snap layout options. On Linux and macOS, this is a no-op.
func (w *WebviewWindow) SnapAssist() {
if w.impl == nil || w.isDestroyed() {
return
}
InvokeSync(w.impl.snapAssist)
}