wails/v3/pkg/application/linux_cgo.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

2296 lines
66 KiB
Go

//go:build linux && cgo && !gtk4 && !android && !server
package application
import (
"fmt"
"strings"
"sync"
"time"
"unsafe"
"github.com/wailsapp/wails/v3/internal/assetserver/webview"
"github.com/wailsapp/wails/v3/pkg/events"
)
/*
#cgo linux pkg-config: gtk+-3.0 webkit2gtk-4.1 gdk-3.0
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <webkit2/webkit2.h>
#include <stdio.h>
#include <limits.h>
#include <stdint.h>
// Use NON_UNIQUE to allow multiple instances of the application to run.
// This matches the behavior of gtk_init/gtk_main used in v2.
#define APPLICATION_DEFAULT_FLAGS G_APPLICATION_NON_UNIQUE
typedef struct CallbackID
{
unsigned int value;
} CallbackID;
extern void dispatchOnMainThreadCallback(unsigned int);
static gboolean dispatchCallback(gpointer data) {
struct CallbackID *args = data;
unsigned int cid = args->value;
dispatchOnMainThreadCallback(cid);
free(args);
return G_SOURCE_REMOVE;
};
static void dispatchOnMainThread(unsigned int id) {
CallbackID *args = malloc(sizeof(CallbackID));
args->value = id;
g_idle_add((GSourceFunc)dispatchCallback, (gpointer)args);
}
typedef struct WindowEvent {
uint id;
uint event;
} WindowEvent;
static void save_window_id(void *object, uint value)
{
g_object_set_data((GObject *)object, "windowid", GUINT_TO_POINTER((guint)value));
}
static void save_webview_to_content_manager(void *contentManager, void *webview)
{
g_object_set_data(G_OBJECT((WebKitUserContentManager *)contentManager), "webview", webview);
}
static WebKitWebView* get_webview_from_content_manager(void *contentManager)
{
return WEBKIT_WEB_VIEW(g_object_get_data(G_OBJECT(contentManager), "webview"));
}
static guint get_window_id(void *object)
{
return GPOINTER_TO_UINT(g_object_get_data((GObject *)object, "windowid"));
}
// exported below
void activateLinux(gpointer data);
extern void emit(WindowEvent* data);
extern gboolean handleConfigureEvent(GtkWidget*, GdkEventConfigure*, uintptr_t);
extern gboolean handleDeleteEvent(GtkWidget*, GdkEvent*, uintptr_t);
extern gboolean handleFocusEvent(GtkWidget*, GdkEvent*, uintptr_t);
extern void handleLoadChanged(WebKitWebView*, WebKitLoadEvent, uintptr_t);
void handleClick(void*);
extern gboolean onButtonEvent(GtkWidget *widget, GdkEventButton *event, uintptr_t user_data);
extern gboolean onMenuButtonEvent(GtkWidget *widget, GdkEventButton *event, uintptr_t user_data);
extern void onUriList(char **extracted, gint x, gint y, gpointer data);
extern void onDragEnter(gpointer data);
extern void onDragLeave(gpointer data);
extern void onDragOver(gint x, gint y, gpointer data);
extern gboolean onKeyPressEvent (GtkWidget *widget, GdkEventKey *event, uintptr_t user_data);
extern void onProcessRequest(WebKitURISchemeRequest *request, uintptr_t user_data);
extern void sendMessageToBackend(WebKitUserContentManager *contentManager, WebKitJavascriptResult *result, void *data);
// exported below (end)
static void signal_connect(void *widget, char *event, void *cb, void* data) {
// g_signal_connect is a macro and can't be called directly
g_signal_connect(widget, event, cb, data);
}
static WebKitWebView* webkit_web_view(GtkWidget *webview) {
return WEBKIT_WEB_VIEW(webview);
}
static void* new_message_dialog(GtkWindow *parent, const gchar *msg, int dialogType, bool hasButtons) {
// gtk_message_dialog_new is variadic! Can't call from cgo directly
GtkWidget *dialog;
int buttonMask;
// buttons will be added after creation
buttonMask = GTK_BUTTONS_OK;
if (hasButtons) {
buttonMask = GTK_BUTTONS_NONE;
}
dialog = gtk_message_dialog_new(
parent,
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
dialogType,
buttonMask,
"%s",
msg);
// g_signal_connect_swapped (dialog,
// "response",
// G_CALLBACK (callback),
// dialog);
return dialog;
};
extern void messageDialogCB(gint button);
static void* gtkFileChooserDialogNew(char* title, GtkWindow* window, GtkFileChooserAction action, char* cancelLabel, char* acceptLabel) {
// gtk_file_chooser_dialog_new is variadic! Can't call from cgo directly
return (GtkFileChooser*)gtk_file_chooser_dialog_new(
title,
window,
action,
cancelLabel,
GTK_RESPONSE_CANCEL,
acceptLabel,
GTK_RESPONSE_ACCEPT,
NULL);
}
typedef struct Screen {
const char* id;
const char* name;
int p_width;
int p_height;
int width;
int height;
int x;
int y;
int w_width;
int w_height;
int w_x;
int w_y;
float scaleFactor;
double rotation;
bool isPrimary;
} Screen;
// Signal handler fix for WebKit/GTK compatibility.
// CREDIT: https://github.com/rainycape/magick
//
// WebKit/GTK may install signal handlers without SA_ONSTACK, which causes
// Go to crash when handling signals (e.g., during panic recovery).
// This code adds SA_ONSTACK to signal handlers after WebKit initialization.
//
// Known limitation: Due to Go issue #7227 (golang/go#7227), signals may still
// be delivered on the wrong stack in some cases when C libraries are involved.
// This is a fundamental Go runtime limitation that cannot be fully resolved here.
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
static void fix_signal(int signum) {
struct sigaction st;
if (sigaction(signum, NULL, &st) < 0) {
goto fix_signal_error;
}
st.sa_flags |= SA_ONSTACK;
if (sigaction(signum, &st, NULL) < 0) {
goto fix_signal_error;
}
return;
fix_signal_error:
fprintf(stderr, "error fixing handler for signal %d, please "
"report this issue to "
"https://github.com/wailsapp/wails: %s\n",
signum, strerror(errno));
}
static void install_signal_handlers() {
#if defined(SIGCHLD)
fix_signal(SIGCHLD);
#endif
#if defined(SIGHUP)
fix_signal(SIGHUP);
#endif
#if defined(SIGINT)
fix_signal(SIGINT);
#endif
#if defined(SIGQUIT)
fix_signal(SIGQUIT);
#endif
#if defined(SIGABRT)
fix_signal(SIGABRT);
#endif
#if defined(SIGFPE)
fix_signal(SIGFPE);
#endif
#if defined(SIGTERM)
fix_signal(SIGTERM);
#endif
#if defined(SIGBUS)
fix_signal(SIGBUS);
#endif
#if defined(SIGSEGV)
fix_signal(SIGSEGV);
#endif
#if defined(SIGXCPU)
fix_signal(SIGXCPU);
#endif
#if defined(SIGXFSZ)
fix_signal(SIGXFSZ);
#endif
}
static int GetNumScreens(){
return 0;
}
// Handle file drops from the OS - called when drag data is received
static void on_drag_data_received(GtkWidget *widget, GdkDragContext *context, gint x, gint y,
GtkSelectionData *selection_data, guint target_type, guint time,
gpointer data)
{
// Only process target_type 2 which is our text/uri-list
// Other target types are from internal WebKit drags
if (target_type != 2) {
return; // Don't interfere with internal drags
}
// Check if we have valid data
if (selection_data == NULL || gtk_selection_data_get_length(selection_data) <= 0) {
gtk_drag_finish(context, FALSE, FALSE, time);
return;
}
const gchar *uri_data = (const gchar *)gtk_selection_data_get_data(selection_data);
gchar **filenames = g_uri_list_extract_uris(uri_data);
if (filenames == NULL || filenames[0] == NULL) {
if (filenames) g_strfreev(filenames);
gtk_drag_finish(context, FALSE, FALSE, time);
return;
}
// Build file array for Go
GPtrArray *file_array = g_ptr_array_new();
int iter = 0;
while (filenames[iter] != NULL) {
char *filename = g_filename_from_uri(filenames[iter], NULL, NULL);
if (filename != NULL) {
g_ptr_array_add(file_array, filename);
}
iter++;
}
g_strfreev(filenames);
if (file_array->len > 0) {
// Get stored drop coordinates and data pointer
gint drop_x = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "drop-x"));
gint drop_y = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "drop-y"));
gpointer drop_data = g_object_get_data(G_OBJECT(widget), "drop-data");
// Add NULL terminator and call Go
g_ptr_array_add(file_array, NULL);
onUriList((gchar **)file_array->pdata, drop_x, drop_y, drop_data);
}
// Cleanup
for (guint i = 0; i < file_array->len; i++) {
gpointer item = g_ptr_array_index(file_array, i);
if (item) g_free(item);
}
g_ptr_array_free(file_array, TRUE);
// Finish the drag successfully to prevent WebKit from opening the file
gtk_drag_finish(context, TRUE, FALSE, time);
}
// Track if we've notified about drag entering
static gboolean drag_entered = FALSE;
// Track if a drag started from within the webview (internal HTML5 drag)
static gboolean internal_drag_active = FALSE;
// Called when a drag starts FROM this widget (internal drag)
static void on_drag_begin(GtkWidget *widget, GdkDragContext *context, gpointer data)
{
internal_drag_active = TRUE;
}
// Called when a drag that started from this widget ends
static void on_drag_end(GtkWidget *widget, GdkDragContext *context, gpointer data)
{
internal_drag_active = FALSE;
}
// Check if a drag context contains file URIs (external drop)
// Returns TRUE only for external file manager drops, FALSE for internal HTML5 drags
static gboolean is_file_drag(GdkDragContext *context)
{
GList *targets = gdk_drag_context_list_targets(context);
// Internal HTML5 drags have WebKit-specific targets, external file drops have text/uri-list
for (GList *l = targets; l != NULL; l = l->next) {
GdkAtom atom = GDK_POINTER_TO_ATOM(l->data);
gchar *name = gdk_atom_name(atom);
if (name) {
gboolean is_uri = g_strcmp0(name, "text/uri-list") == 0;
g_free(name);
if (is_uri) {
return TRUE;
}
}
}
return FALSE;
}
// Handle the actual drop - called when user releases mouse button
static gboolean on_drag_drop(GtkWidget *widget, GdkDragContext *context, gint x, gint y,
guint time, gpointer data)
{
// Only handle external file drops, let WebKit handle internal HTML5 drags
if (!is_file_drag(context)) {
return FALSE;
}
// Reset drag entered state
drag_entered = FALSE;
// Store coordinates for use in drag-data-received
g_object_set_data(G_OBJECT(widget), "drop-x", GINT_TO_POINTER(x));
g_object_set_data(G_OBJECT(widget), "drop-y", GINT_TO_POINTER(y));
g_object_set_data(G_OBJECT(widget), "drop-data", data);
// Request the file data - this triggers drag-data-received
GdkAtom target = gdk_atom_intern("text/uri-list", FALSE);
gtk_drag_get_data(widget, context, target, time);
return TRUE;
}
// Handle drag-motion for hover effects on external file drags
static gboolean on_drag_motion(GtkWidget *widget, GdkDragContext *context, gint x, gint y, guint time, gpointer data)
{
// Don't handle internal HTML5 drags
if (internal_drag_active || !is_file_drag(context)) {
return FALSE;
}
gdk_drag_status(context, GDK_ACTION_COPY, time);
// Notify JS once when drag enters
if (!drag_entered) {
drag_entered = TRUE;
onDragEnter(data);
}
// Send position to JS for hover effects (Go side throttles this)
onDragOver(x, y, data);
return TRUE;
}
// Handle drag-leave - drag exited the window
static void on_drag_leave(GtkWidget *widget, GdkDragContext *context, guint time, gpointer data)
{
// Don't handle internal HTML5 drags
if (internal_drag_active || !is_file_drag(context)) {
return;
}
if (drag_entered) {
drag_entered = FALSE;
onDragLeave(data);
}
}
// Set up drag and drop handlers for external file drops with hover effects
static void enableDND(GtkWidget *widget, gpointer data)
{
// Core handlers for file drop
g_signal_connect(G_OBJECT(widget), "drag-data-received", G_CALLBACK(on_drag_data_received), data);
g_signal_connect(G_OBJECT(widget), "drag-drop", G_CALLBACK(on_drag_drop), data);
// Hover effect handlers - return FALSE for internal drags to let WebKit handle them
g_signal_connect(G_OBJECT(widget), "drag-motion", G_CALLBACK(on_drag_motion), data);
g_signal_connect(G_OBJECT(widget), "drag-leave", G_CALLBACK(on_drag_leave), data);
}
// Block external file drops - consume the events to prevent WebKit from navigating to files
// Returns TRUE for file drags to consume them, FALSE for internal HTML5 drags to let WebKit handle
static gboolean on_drag_drop_blocked(GtkWidget *widget, GdkDragContext *context, gint x, gint y,
guint time, gpointer data)
{
if (!is_file_drag(context)) {
return FALSE; // Let WebKit handle internal HTML5 drags
}
// Block external file drops by finishing with failure
gtk_drag_finish(context, FALSE, FALSE, time);
return TRUE;
}
static gboolean on_drag_motion_blocked(GtkWidget *widget, GdkDragContext *context, gint x, gint y, guint time, gpointer data)
{
if (internal_drag_active || !is_file_drag(context)) {
return FALSE; // Let WebKit handle internal HTML5 drags
}
// Show "no drop" cursor for external file drags
gdk_drag_status(context, 0, time);
return TRUE;
}
// Set up handlers that block external file drops while allowing internal HTML5 drag-and-drop
static void disableDND(GtkWidget *widget, gpointer data)
{
g_signal_connect(G_OBJECT(widget), "drag-drop", G_CALLBACK(on_drag_drop_blocked), data);
g_signal_connect(G_OBJECT(widget), "drag-motion", G_CALLBACK(on_drag_motion_blocked), data);
}
*/
import "C"
// Calloc handles alloc/dealloc of C data
type Calloc struct {
pool []unsafe.Pointer
}
// NewCalloc creates a new allocator
func NewCalloc() Calloc {
return Calloc{}
}
// String creates a new C string and retains a reference to it
func (c Calloc) String(in string) *C.char {
result := C.CString(in)
c.pool = append(c.pool, unsafe.Pointer(result))
return result
}
// Free frees all allocated C memory
func (c Calloc) Free() {
for _, str := range c.pool {
C.free(str)
}
c.pool = []unsafe.Pointer{}
}
type windowPointer *C.GtkWindow
type identifier C.uint
type pointer unsafe.Pointer
type GSList C.GSList
type GSListPointer *GSList
// getLinuxWebviewWindow safely extracts a linuxWebviewWindow from a Window interface
// Returns nil if the window is not a WebviewWindow or not a Linux implementation
func getLinuxWebviewWindow(window Window) *linuxWebviewWindow {
if window == nil {
return nil
}
webviewWindow, ok := window.(*WebviewWindow)
if !ok {
return nil
}
lw, ok := webviewWindow.impl.(*linuxWebviewWindow)
if !ok {
return nil
}
return lw
}
var (
nilPointer pointer = nil
nilRadioGroup GSListPointer = nil
)
var (
gtkSignalToMenuItem map[uint]*MenuItem
mainThreadId *C.GThread
)
var registerURIScheme sync.Once
var fixSignalHandlers sync.Once
func init() {
gtkSignalToMenuItem = map[uint]*MenuItem{}
mainThreadId = C.g_thread_self()
}
// mainthread stuff
func dispatchOnMainThread(id uint) {
C.dispatchOnMainThread(C.uint(id))
}
//export dispatchOnMainThreadCallback
func dispatchOnMainThreadCallback(callbackID C.uint) {
executeOnMainThread(uint(callbackID))
}
//export activateLinux
func activateLinux(data pointer) {
processApplicationEvent(C.uint(events.Linux.ApplicationStartup), data)
}
//export processApplicationEvent
func processApplicationEvent(eventID C.uint, data pointer) {
event := newApplicationEvent(events.ApplicationEventType(eventID))
//if data != nil {
// dataCStrJSON := C.serializationNSDictionary(data)
// if dataCStrJSON != nil {
// defer C.free(unsafe.Pointer(dataCStrJSON))
//
// dataJSON := C.GoString(dataCStrJSON)
// var result map[string]any
// err := json.Unmarshal([]byte(dataJSON), &result)
//
// if err != nil {
// panic(err)
// }
//
// event.Context().setData(result)
// }
//}
switch event.Id {
case uint(events.Linux.SystemThemeChanged):
isDark := globalApplication.Env.IsDarkMode()
event.Context().setIsDarkMode(isDark)
}
applicationEvents <- event
}
func isOnMainThread() bool {
threadId := C.g_thread_self()
return threadId == mainThreadId
}
// implementation below
func appName() string {
name := C.g_get_application_name()
defer C.free(unsafe.Pointer(name))
return C.GoString(name)
}
func appNew(name string) pointer {
// Name is already sanitized by sanitizeAppName() in application_linux.go
appId := fmt.Sprintf("org.wails.%s", name)
nameC := C.CString(appId)
defer C.free(unsafe.Pointer(nameC))
return pointer(C.gtk_application_new(nameC, C.APPLICATION_DEFAULT_FLAGS))
}
func setProgramName(prgName string) {
cPrgName := C.CString(prgName)
defer C.free(unsafe.Pointer(cPrgName))
C.g_set_prgname(cPrgName)
}
func appRun(app pointer) error {
application := (*C.GApplication)(app)
//TODO: Only set this if we configure it to do so
C.g_application_hold(application) // allows it to run without a window
signal := C.CString("activate")
defer C.free(unsafe.Pointer(signal))
C.signal_connect(unsafe.Pointer(application), signal, C.activateLinux, nil)
status := C.g_application_run(application, 0, nil)
C.g_application_release(application)
C.g_object_unref(C.gpointer(app))
var err error
if status != 0 {
err = fmt.Errorf("exit code: %d", status)
}
return err
}
func appDestroy(application pointer) {
C.g_application_quit((*C.GApplication)(application))
}
func (w *linuxWebviewWindow) contextMenuSignals(menu pointer) {
c := NewCalloc()
defer c.Free()
winID := unsafe.Pointer(uintptr(C.uint(w.parent.ID())))
C.signal_connect(unsafe.Pointer(menu), c.String("button-release-event"), C.onMenuButtonEvent, winID)
}
func (w *linuxWebviewWindow) contextMenuShow(menu pointer, data *ContextMenuData) {
geometry := C.GdkRectangle{
x: C.int(data.X),
y: C.int(data.Y),
}
event := C.GdkEvent{}
gdkWindow := C.gtk_widget_get_window(w.gtkWidget())
C.gtk_menu_popup_at_rect(
(*C.GtkMenu)(menu),
gdkWindow,
(*C.GdkRectangle)(&geometry),
C.GDK_GRAVITY_NORTH_WEST,
C.GDK_GRAVITY_NORTH_WEST,
(*C.GdkEvent)(&event),
)
w.ctxMenuOpened = true
}
func (a *linuxApp) getCurrentWindowID() uint {
// TODO: Add extra metadata to window and use it!
window := (*C.GtkWindow)(C.gtk_application_get_active_window((*C.GtkApplication)(a.application)))
if window == nil {
return uint(1)
}
identifier, ok := a.windowMap[window]
if ok {
return identifier
}
// FIXME: Should we panic here if not found?
return uint(1)
}
func (a *linuxApp) getWindows() []pointer {
result := []pointer{}
windows := C.gtk_application_get_windows((*C.GtkApplication)(a.application))
for {
result = append(result, pointer(windows.data))
windows = windows.next
if windows == nil {
return result
}
}
}
func (a *linuxApp) hideAllWindows() {
for _, window := range a.getWindows() {
C.gtk_widget_hide((*C.GtkWidget)(window))
}
}
func (a *linuxApp) showAllWindows() {
for _, window := range a.getWindows() {
C.gtk_window_present((*C.GtkWindow)(window))
}
}
func (a *linuxApp) setIcon(icon []byte) {
if len(icon) == 0 {
return
}
// Use g_bytes_new instead of g_bytes_new_static because Go memory can be
// moved or freed by the GC. g_bytes_new copies the data to C-owned memory.
gbytes := C.g_bytes_new(C.gconstpointer(unsafe.Pointer(&icon[0])), C.ulong(len(icon)))
defer C.g_bytes_unref(gbytes)
stream := C.g_memory_input_stream_new_from_bytes(gbytes)
defer C.g_object_unref(C.gpointer(stream))
var gerror *C.GError
pixbuf := C.gdk_pixbuf_new_from_stream(stream, nil, &gerror)
if gerror != nil {
a.parent.error("failed to load application icon: %s", C.GoString(gerror.message))
C.g_error_free(gerror)
return
}
a.icon = pointer(pixbuf)
}
// Clipboard
func clipboardGet() string {
clip := C.gtk_clipboard_get(C.GDK_SELECTION_CLIPBOARD)
text := C.gtk_clipboard_wait_for_text(clip)
return C.GoString(text)
}
func clipboardSet(text string) {
cText := C.CString(text)
clip := C.gtk_clipboard_get(C.GDK_SELECTION_CLIPBOARD)
C.gtk_clipboard_set_text(clip, cText, -1)
clip = C.gtk_clipboard_get(C.GDK_SELECTION_PRIMARY)
C.gtk_clipboard_set_text(clip, cText, -1)
C.free(unsafe.Pointer(cText))
}
// Menu
func menuAddSeparator(menu *Menu) {
C.gtk_menu_shell_append(
(*C.GtkMenuShell)((menu.impl).(*linuxMenu).native),
C.gtk_separator_menu_item_new())
}
func menuAppend(parent *Menu, menu *MenuItem) {
C.gtk_menu_shell_append(
(*C.GtkMenuShell)((parent.impl).(*linuxMenu).native),
(*C.GtkWidget)((menu.impl).(*linuxMenuItem).native),
)
/* gtk4
C.gtk_menu_item_set_submenu(
(*C.struct__GtkMenuItem)((menu.impl).(*linuxMenuItem).native),
(*C.struct__GtkWidget)((parent.impl).(*linuxMenu).native),
)
*/
}
func menuBarNew() pointer {
return pointer(C.gtk_menu_bar_new())
}
func menuNew() pointer {
return pointer(C.gtk_menu_new())
}
func menuSetSubmenu(item *MenuItem, menu *Menu) {
C.gtk_menu_item_set_submenu(
(*C.GtkMenuItem)((item.impl).(*linuxMenuItem).native),
(*C.GtkWidget)((menu.impl).(*linuxMenu).native))
}
func menuGetRadioGroup(item *linuxMenuItem) *GSList {
return (*GSList)(C.gtk_radio_menu_item_get_group((*C.GtkRadioMenuItem)(item.native)))
}
func menuClear(menu *Menu) {
menuShell := (*C.GtkMenuShell)((menu.impl).(*linuxMenu).native)
children := C.gtk_container_get_children((*C.GtkContainer)(unsafe.Pointer(menuShell)))
if children != nil {
// Save the original pointer to free later
originalList := children
// Iterate through all children and remove them
for children != nil {
child := (*C.GtkWidget)(children.data)
if child != nil {
C.gtk_container_remove((*C.GtkContainer)(unsafe.Pointer(menuShell)), child)
}
children = children.next
}
C.g_list_free(originalList)
}
}
//export handleClick
func handleClick(idPtr unsafe.Pointer) {
ident := C.CString("id")
defer C.free(unsafe.Pointer(ident))
value := C.g_object_get_data((*C.GObject)(idPtr), ident)
id := uint(*(*C.uint)(value))
item, ok := gtkSignalToMenuItem[id]
if !ok {
return
}
switch item.itemType {
case text, checkbox:
menuItemClicked <- item.id
case radio:
menuItem := (item.impl).(*linuxMenuItem)
if menuItem.isChecked() {
menuItemClicked <- item.id
}
}
}
func attachMenuHandler(item *MenuItem) uint {
signal := C.CString("activate")
defer C.free(unsafe.Pointer(signal))
impl := (item.impl).(*linuxMenuItem)
widget := impl.native
flags := C.GConnectFlags(0)
handlerId := C.g_signal_connect_object(
C.gpointer(widget),
signal,
C.GCallback(C.handleClick),
C.gpointer(widget),
flags)
id := C.uint(item.id)
ident := C.CString("id")
defer C.free(unsafe.Pointer(ident))
C.g_object_set_data(
(*C.GObject)(widget),
ident,
C.gpointer(&id),
)
gtkSignalToMenuItem[item.id] = item
return uint(handlerId)
}
// menuItem
func menuItemChecked(widget pointer) bool {
if C.gtk_check_menu_item_get_active((*C.GtkCheckMenuItem)(widget)) == C.int(1) {
return true
}
return false
}
func menuItemNew(label string, bitmap []byte) pointer {
return menuItemAddProperties(C.gtk_menu_item_new(), label, bitmap)
}
func menuItemDestroy(widget pointer) {
C.gtk_widget_destroy((*C.GtkWidget)(widget))
}
func menuItemAddProperties(menuItem *C.GtkWidget, label string, bitmap []byte) pointer {
/*
// FIXME: Support accelerator configuration
activate := C.CString("activate")
defer C.free(unsafe.Pointer(activate))
accelGroup := C.gtk_accel_group_new()
C.gtk_widget_add_accelerator(menuItem, activate, accelGroup,
C.GDK_KEY_m, C.GDK_CONTROL_MASK, C.GTK_ACCEL_VISIBLE)
*/
cLabel := C.CString(label)
defer C.free(unsafe.Pointer(cLabel))
lbl := unsafe.Pointer(C.gtk_accel_label_new(cLabel))
C.gtk_label_set_use_underline((*C.GtkLabel)(lbl), 1)
C.gtk_label_set_xalign((*C.GtkLabel)(lbl), 0.0)
C.gtk_accel_label_set_accel_widget(
(*C.GtkAccelLabel)(lbl),
(*C.GtkWidget)(unsafe.Pointer(menuItem)))
box := C.gtk_box_new(C.GTK_ORIENTATION_HORIZONTAL, 6)
if img, err := pngToImage(bitmap); err == nil && len(img.Pix) > 0 {
// Use g_bytes_new instead of g_bytes_new_static because Go memory can be
// moved or freed by the GC. g_bytes_new copies the data to C-owned memory.
gbytes := C.g_bytes_new(C.gconstpointer(unsafe.Pointer(&img.Pix[0])),
C.ulong(len(img.Pix)))
defer C.g_bytes_unref(gbytes)
pixBuf := C.gdk_pixbuf_new_from_bytes(
gbytes,
C.GDK_COLORSPACE_RGB,
1, // has_alpha
8,
C.int(img.Bounds().Dx()),
C.int(img.Bounds().Dy()),
C.int(img.Stride),
)
image := C.gtk_image_new_from_pixbuf(pixBuf)
C.gtk_widget_set_visible((*C.GtkWidget)(image), C.gboolean(1))
C.gtk_container_add(
(*C.GtkContainer)(unsafe.Pointer(box)),
(*C.GtkWidget)(unsafe.Pointer(image)))
}
C.gtk_box_pack_end(
(*C.GtkBox)(unsafe.Pointer(box)),
(*C.GtkWidget)(lbl), 1, 1, 0)
C.gtk_container_add(
(*C.GtkContainer)(unsafe.Pointer(menuItem)),
(*C.GtkWidget)(unsafe.Pointer(box)))
C.gtk_widget_show_all(menuItem)
return pointer(menuItem)
}
func menuCheckItemNew(label string, bitmap []byte) pointer {
return menuItemAddProperties(C.gtk_check_menu_item_new(), label, bitmap)
}
func menuItemSetChecked(widget pointer, checked bool) {
value := C.int(0)
if checked {
value = C.int(1)
}
C.gtk_check_menu_item_set_active(
(*C.GtkCheckMenuItem)(widget),
value)
}
func menuItemSetDisabled(widget pointer, disabled bool) {
value := C.int(1)
if disabled {
value = C.int(0)
}
C.gtk_widget_set_sensitive(
(*C.GtkWidget)(widget),
value)
}
func menuItemSetLabel(widget pointer, label string) {
value := C.CString(label)
C.gtk_menu_item_set_label(
(*C.GtkMenuItem)(widget),
value)
C.free(unsafe.Pointer(value))
}
func menuItemRemoveBitmap(widget pointer) {
box := C.gtk_bin_get_child((*C.GtkBin)(widget))
if box == nil {
return
}
children := C.gtk_container_get_children((*C.GtkContainer)(unsafe.Pointer(box)))
defer C.g_list_free(children)
count := int(C.g_list_length(children))
if count == 2 {
C.gtk_container_remove((*C.GtkContainer)(unsafe.Pointer(box)),
(*C.GtkWidget)(children.data))
}
}
func menuItemSetBitmap(widget pointer, bitmap []byte) {
menuItemRemoveBitmap(widget)
box := C.gtk_bin_get_child((*C.GtkBin)(widget))
if img, err := pngToImage(bitmap); err == nil && len(img.Pix) > 0 {
// Use g_bytes_new instead of g_bytes_new_static because Go memory can be
// moved or freed by the GC. g_bytes_new copies the data to C-owned memory.
gbytes := C.g_bytes_new(C.gconstpointer(unsafe.Pointer(&img.Pix[0])),
C.ulong(len(img.Pix)))
defer C.g_bytes_unref(gbytes)
pixBuf := C.gdk_pixbuf_new_from_bytes(
gbytes,
C.GDK_COLORSPACE_RGB,
1, // has_alpha
8,
C.int(img.Bounds().Dx()),
C.int(img.Bounds().Dy()),
C.int(img.Stride),
)
image := C.gtk_image_new_from_pixbuf(pixBuf)
C.gtk_widget_set_visible((*C.GtkWidget)(image), C.gboolean(1))
C.gtk_container_add(
(*C.GtkContainer)(unsafe.Pointer(box)),
(*C.GtkWidget)(unsafe.Pointer(image)))
}
}
func menuItemSetToolTip(widget pointer, tooltip string) {
value := C.CString(tooltip)
C.gtk_widget_set_tooltip_text(
(*C.GtkWidget)(widget),
value)
C.free(unsafe.Pointer(value))
}
func menuItemSignalBlock(widget pointer, handlerId uint, block bool) {
if block {
C.g_signal_handler_block(C.gpointer(widget), C.ulong(handlerId))
} else {
C.g_signal_handler_unblock(C.gpointer(widget), C.ulong(handlerId))
}
}
func menuRadioItemNew(group *GSList, label string) pointer {
cLabel := C.CString(label)
defer C.free(unsafe.Pointer(cLabel))
return pointer(C.gtk_radio_menu_item_new_with_label((*C.GSList)(group), cLabel))
}
// screen related
func getScreenByIndex(display *C.struct__GdkDisplay, index int) *Screen {
monitor := C.gdk_display_get_monitor(display, C.int(index))
// TODO: Do we need to update Screen to contain current info?
// currentMonitor := C.gdk_display_get_monitor_at_window(display, window)
var geometry C.GdkRectangle
C.gdk_monitor_get_geometry(monitor, &geometry)
primary := false
if C.gdk_monitor_is_primary(monitor) == 1 {
primary = true
}
name := C.gdk_monitor_get_model(monitor)
return &Screen{
ID: fmt.Sprintf("%d", index),
Name: C.GoString(name),
IsPrimary: primary,
ScaleFactor: float32(C.gdk_monitor_get_scale_factor(monitor)),
X: int(geometry.x),
Y: int(geometry.y),
Size: Size{
Height: int(geometry.height),
Width: int(geometry.width),
},
Bounds: Rect{
X: int(geometry.x),
Y: int(geometry.y),
Height: int(geometry.height),
Width: int(geometry.width),
},
PhysicalBounds: Rect{
X: int(geometry.x),
Y: int(geometry.y),
Height: int(geometry.height),
Width: int(geometry.width),
},
WorkArea: Rect{
X: int(geometry.x),
Y: int(geometry.y),
Height: int(geometry.height),
Width: int(geometry.width),
},
PhysicalWorkArea: Rect{
X: int(geometry.x),
Y: int(geometry.y),
Height: int(geometry.height),
Width: int(geometry.width),
},
Rotation: 0.0,
}
}
func getScreens(app pointer) ([]*Screen, error) {
var screens []*Screen
window := C.gtk_application_get_active_window((*C.GtkApplication)(app))
gdkWindow := C.gtk_widget_get_window((*C.GtkWidget)(unsafe.Pointer(window)))
display := C.gdk_window_get_display(gdkWindow)
count := C.gdk_display_get_n_monitors(display)
for i := 0; i < int(count); i++ {
screens = append(screens, getScreenByIndex(display, i))
}
return screens, nil
}
// widgets
func (w *linuxWebviewWindow) setEnabled(enabled bool) {
var value C.int
if enabled {
value = C.int(1)
}
C.gtk_widget_set_sensitive(w.gtkWidget(), value)
}
func widgetSetVisible(widget pointer, hidden bool) {
if hidden {
C.gtk_widget_hide((*C.GtkWidget)(widget))
} else {
C.gtk_widget_show((*C.GtkWidget)(widget))
}
}
func (w *linuxWebviewWindow) close() {
C.gtk_widget_destroy(w.gtkWidget())
getNativeApplication().unregisterWindow(windowPointer(w.window))
}
func (w *linuxWebviewWindow) enableDND() {
// Pass window ID as pointer value (not pointer to ID) - same pattern as other signal handlers
winID := unsafe.Pointer(uintptr(w.parent.id))
C.enableDND((*C.GtkWidget)(w.webview), C.gpointer(winID))
}
func (w *linuxWebviewWindow) disableDND() {
// Block external file drops while allowing internal HTML5 drag-and-drop
winID := unsafe.Pointer(uintptr(w.parent.id))
C.disableDND((*C.GtkWidget)(w.webview), C.gpointer(winID))
}
func (w *linuxWebviewWindow) execJS(js string) {
InvokeAsync(func() {
value := C.CString(js)
C.webkit_web_view_evaluate_javascript(w.webKitWebView(),
value,
C.long(len(js)),
nil,
C.CString(""),
nil,
nil,
nil)
C.free(unsafe.Pointer(value))
})
}
// Preallocated buffer for drag-over JS calls to avoid allocations
// "window._wails.handleDragOver(XXXXX,YYYYY)" is max ~45 chars
var dragOverJSBuffer = C.CString(strings.Repeat(" ", 64))
var emptyWorldName = C.CString("")
// execJSDragOver executes JS for drag-over events with zero Go allocations.
// It directly writes to a preallocated C buffer. Must be called from main thread.
func (w *linuxWebviewWindow) execJSDragOver(x, y int) {
// Format: "window._wails.handleDragOver(X,Y)"
// Write directly to C buffer
buf := (*[64]byte)(unsafe.Pointer(dragOverJSBuffer))
n := copy(buf[:], "window._wails.handleDragOver(")
n += writeInt(buf[n:], x)
buf[n] = ','
n++
n += writeInt(buf[n:], y)
buf[n] = ')'
n++
buf[n] = 0 // null terminate
C.webkit_web_view_evaluate_javascript(w.webKitWebView(),
dragOverJSBuffer,
C.long(n),
nil,
emptyWorldName,
nil,
nil,
nil)
}
// writeInt writes an integer to a byte slice and returns the number of bytes written
func writeInt(buf []byte, n int) int {
if n < 0 {
buf[0] = '-'
return 1 + writeInt(buf[1:], -n)
}
if n == 0 {
buf[0] = '0'
return 1
}
// Count digits
tmp := n
digits := 0
for tmp > 0 {
digits++
tmp /= 10
}
// Write digits in reverse
for i := digits - 1; i >= 0; i-- {
buf[i] = byte('0' + n%10)
n /= 10
}
return digits
}
func getMousePosition() (int, int, *Screen) {
var x, y C.gint
var screen *C.GdkScreen
defaultDisplay := C.gdk_display_get_default()
device := C.gdk_seat_get_pointer(C.gdk_display_get_default_seat(defaultDisplay))
C.gdk_device_get_position(device, &screen, &x, &y)
// Get Monitor for screen
monitor := C.gdk_display_get_monitor_at_point(defaultDisplay, x, y)
geometry := C.GdkRectangle{}
C.gdk_monitor_get_geometry(monitor, &geometry)
scaleFactor := int(C.gdk_monitor_get_scale_factor(monitor))
return int(x), int(y), &Screen{
ID: fmt.Sprintf("%d", 0), // A unique identifier for the display
Name: C.GoString(C.gdk_monitor_get_model(monitor)), // The name of the display
ScaleFactor: float32(scaleFactor), // The scale factor of the display
X: int(geometry.x), // The x-coordinate of the top-left corner of the rectangle
Y: int(geometry.y), // The y-coordinate of the top-left corner of the rectangle
Size: Size{
Height: int(geometry.height),
Width: int(geometry.width),
},
Bounds: Rect{
X: int(geometry.x),
Y: int(geometry.y),
Height: int(geometry.height),
Width: int(geometry.width),
},
WorkArea: Rect{
X: int(geometry.x),
Y: int(geometry.y),
Height: int(geometry.height),
Width: int(geometry.width),
},
IsPrimary: false,
Rotation: 0.0,
}
}
func (w *linuxWebviewWindow) destroy() {
w.parent.markAsDestroyed()
// Free menu
if w.gtkmenu != nil {
C.gtk_widget_destroy((*C.GtkWidget)(w.gtkmenu))
w.gtkmenu = nil
}
// Free window
C.gtk_widget_destroy(w.gtkWidget())
}
func (w *linuxWebviewWindow) fullscreen() {
w.maximise()
//w.lastWidth, w.lastHeight = w.size()
x, y, width, height, scaleFactor := w.getCurrentMonitorGeometry()
if x == -1 && y == -1 && width == -1 && height == -1 {
return
}
physicalWidth := int(float64(width) * scaleFactor)
physicalHeight := int(float64(height) * scaleFactor)
w.setMinMaxSize(0, 0, physicalWidth, physicalHeight)
w.setSize(physicalWidth, physicalHeight)
C.gtk_window_fullscreen(w.gtkWindow())
w.setRelativePosition(0, 0)
}
func (w *linuxWebviewWindow) getCurrentMonitor() *C.GdkMonitor {
display := C.gtk_widget_get_display(w.gtkWidget())
gdkWindow := C.gtk_widget_get_window(w.gtkWidget())
if gdkWindow != nil {
monitor := C.gdk_display_get_monitor_at_window(display, gdkWindow)
if monitor != nil {
return monitor
}
}
// Wayland fallback: find monitor containing the current window
n_monitors := C.gdk_display_get_n_monitors(display)
window_x, window_y := w.position()
for i := 0; i < int(n_monitors); i++ {
test_monitor := C.gdk_display_get_monitor(display, C.int(i))
if test_monitor != nil {
var rect C.GdkRectangle
C.gdk_monitor_get_geometry(test_monitor, &rect)
// Check if window is within this monitor's bounds
if window_x >= int(rect.x) && window_x < int(rect.x+rect.width) &&
window_y >= int(rect.y) && window_y < int(rect.y+rect.height) {
return test_monitor
}
}
}
return nil
}
func (w *linuxWebviewWindow) getScreen() (*Screen, error) {
// Get the current screen for the window
monitor := w.getCurrentMonitor()
name := C.gdk_monitor_get_model(monitor)
mx, my, width, height, scaleFactor := w.getCurrentMonitorGeometry()
return &Screen{
ID: fmt.Sprintf("%d", w.id), // A unique identifier for the display
Name: C.GoString(name), // The name of the display
ScaleFactor: float32(scaleFactor), // The scale factor of the display
X: mx, // The x-coordinate of the top-left corner of the rectangle
Y: my, // The y-coordinate of the top-left corner of the rectangle
Size: Size{
Height: int(height),
Width: int(width),
},
Bounds: Rect{
X: int(mx),
Y: int(my),
Height: int(height),
Width: int(width),
},
WorkArea: Rect{
X: int(mx),
Y: int(my),
Height: int(height),
Width: int(width),
},
PhysicalBounds: Rect{
X: int(mx),
Y: int(my),
Height: int(height),
Width: int(width),
},
PhysicalWorkArea: Rect{
X: int(mx),
Y: int(my),
Height: int(height),
Width: int(width),
},
IsPrimary: false,
Rotation: 0.0,
}, nil
}
func (w *linuxWebviewWindow) getCurrentMonitorGeometry() (x int, y int, width int, height int, scaleFactor float64) {
monitor := w.getCurrentMonitor()
if monitor == nil {
// Best effort to find screen resolution of default monitor
display := C.gdk_display_get_default()
monitor = C.gdk_display_get_primary_monitor(display)
if monitor == nil {
return -1, -1, -1, -1, 1
}
}
var result C.GdkRectangle
C.gdk_monitor_get_geometry(monitor, &result)
// GTK3 only supports integer scale factors
scaleFactor = float64(C.gdk_monitor_get_scale_factor(monitor))
return int(result.x), int(result.y), int(result.width), int(result.height), scaleFactor
}
func (w *linuxWebviewWindow) size() (int, int) {
var windowWidth C.int
var windowHeight C.int
C.gtk_window_get_size(w.gtkWindow(), &windowWidth, &windowHeight)
return int(windowWidth), int(windowHeight)
}
func (w *linuxWebviewWindow) relativePosition() (int, int) {
x, y := w.position()
// The position must be relative to the screen it is on
// We need to get the screen it is on
monitor := w.getCurrentMonitor()
geometry := C.GdkRectangle{}
C.gdk_monitor_get_geometry(monitor, &geometry)
x = x - int(geometry.x)
y = y - int(geometry.y)
// TODO: Scale based on DPI
return x, y
}
func (w *linuxWebviewWindow) gtkWidget() *C.GtkWidget {
return (*C.GtkWidget)(w.window)
}
func (w *linuxWebviewWindow) windowHide() {
C.gtk_widget_hide(w.gtkWidget())
}
func (w *linuxWebviewWindow) isFullscreen() bool {
gdkWindow := C.gtk_widget_get_window(w.gtkWidget())
state := C.gdk_window_get_state(gdkWindow)
return state&C.GDK_WINDOW_STATE_FULLSCREEN > 0
}
func (w *linuxWebviewWindow) isFocused() bool {
// returns true if window is focused
return C.gtk_window_has_toplevel_focus(w.gtkWindow()) == 1
}
func (w *linuxWebviewWindow) isMaximised() bool {
gdkwindow := C.gtk_widget_get_window(w.gtkWidget())
state := C.gdk_window_get_state(gdkwindow)
return state&C.GDK_WINDOW_STATE_MAXIMIZED > 0 && state&C.GDK_WINDOW_STATE_FULLSCREEN == 0
}
func (w *linuxWebviewWindow) isMinimised() bool {
gdkwindow := C.gtk_widget_get_window(w.gtkWidget())
state := C.gdk_window_get_state(gdkwindow)
return state&C.GDK_WINDOW_STATE_ICONIFIED > 0
}
func (w *linuxWebviewWindow) isVisible() bool {
if C.gtk_widget_is_visible(w.gtkWidget()) == 1 {
return true
}
return false
}
func (w *linuxWebviewWindow) maximise() {
C.gtk_window_maximize(w.gtkWindow())
}
func (w *linuxWebviewWindow) minimise() {
C.gtk_window_iconify(w.gtkWindow())
}
func windowNew(application pointer, menu pointer, _ LinuxMenuStyle, windowId uint, gpuPolicy WebviewGpuPolicy) (window, webview, vbox pointer) {
window = pointer(C.gtk_application_window_new((*C.GtkApplication)(application)))
C.g_object_ref_sink(C.gpointer(window))
webview = windowNewWebview(windowId, gpuPolicy)
vbox = pointer(C.gtk_box_new(C.GTK_ORIENTATION_VERTICAL, 0))
name := C.CString("webview-box")
defer C.free(unsafe.Pointer(name))
C.gtk_widget_set_name((*C.GtkWidget)(vbox), name)
C.gtk_container_add((*C.GtkContainer)(window), (*C.GtkWidget)(vbox))
if menu != nil {
C.gtk_box_pack_start((*C.GtkBox)(vbox), (*C.GtkWidget)(menu), 0, 0, 0)
}
C.gtk_box_pack_start((*C.GtkBox)(unsafe.Pointer(vbox)), (*C.GtkWidget)(webview), 1, 1, 0)
return
}
func windowNewWebview(parentId uint, gpuPolicy WebviewGpuPolicy) pointer {
c := NewCalloc()
defer c.Free()
manager := C.webkit_user_content_manager_new()
C.webkit_user_content_manager_register_script_message_handler(manager, c.String("external"))
webView := C.webkit_web_view_new_with_user_content_manager(manager)
fixSignalHandlers.Do(func() {
C.install_signal_handlers()
})
C.save_webview_to_content_manager(unsafe.Pointer(manager), unsafe.Pointer(webView))
// attach window id to both the webview and contentmanager
C.save_window_id(unsafe.Pointer(webView), C.uint(parentId))
C.save_window_id(unsafe.Pointer(manager), C.uint(parentId))
registerURIScheme.Do(func() {
context := C.webkit_web_view_get_context(C.webkit_web_view(webView))
C.webkit_web_context_register_uri_scheme(
context,
c.String("wails"),
C.WebKitURISchemeRequestCallback(C.onProcessRequest),
nil,
nil)
})
settings := C.webkit_web_view_get_settings((*C.WebKitWebView)(unsafe.Pointer(webView)))
C.webkit_settings_set_user_agent_with_application_details(settings, c.String("wails.io"), c.String(""))
switch gpuPolicy {
case WebviewGpuPolicyAlways:
C.webkit_settings_set_hardware_acceleration_policy(settings, C.WEBKIT_HARDWARE_ACCELERATION_POLICY_ALWAYS)
break
case WebviewGpuPolicyOnDemand:
C.webkit_settings_set_hardware_acceleration_policy(settings, C.WEBKIT_HARDWARE_ACCELERATION_POLICY_ON_DEMAND)
break
case WebviewGpuPolicyNever:
C.webkit_settings_set_hardware_acceleration_policy(settings, C.WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER)
break
default:
C.webkit_settings_set_hardware_acceleration_policy(settings, C.WEBKIT_HARDWARE_ACCELERATION_POLICY_ON_DEMAND)
}
return pointer(webView)
}
func (w *linuxWebviewWindow) present() {
C.gtk_window_present(w.gtkWindow())
// gtk_window_unminimize (w.gtkWindow()) /// gtk4
}
func (w *linuxWebviewWindow) setSize(width, height int) {
C.gtk_window_resize(
w.gtkWindow(),
C.gint(width),
C.gint(height))
}
func (w *linuxWebviewWindow) windowShow() {
if w.gtkWidget() == nil {
return
}
// Realize the window first to ensure it has a valid GdkWindow.
// This prevents crashes on Wayland when appmenu-gtk-module tries to
// set DBus properties for global menu integration before the window
// is fully realized. See: https://github.com/wailsapp/wails/issues/4769
C.gtk_widget_realize(w.gtkWidget())
C.gtk_widget_show_all(w.gtkWidget())
}
func windowIgnoreMouseEvents(window pointer, webview pointer, ignore bool) {
var enable C.int
if ignore {
enable = 1
}
gdkWindow := (*C.GdkWindow)(window)
C.gdk_window_set_pass_through(gdkWindow, enable)
C.webkit_web_view_set_editable((*C.WebKitWebView)(webview), C.gboolean(enable))
}
func (w *linuxWebviewWindow) webKitWebView() *C.WebKitWebView {
return (*C.WebKitWebView)(w.webview)
}
func (w *linuxWebviewWindow) setBorderless(borderless bool) {
C.gtk_window_set_decorated(w.gtkWindow(), gtkBool(!borderless))
}
func (w *linuxWebviewWindow) setResizable(resizable bool) {
C.gtk_window_set_resizable(w.gtkWindow(), gtkBool(resizable))
}
func (w *linuxWebviewWindow) setDefaultSize(width int, height int) {
C.gtk_window_set_default_size(w.gtkWindow(), C.gint(width), C.gint(height))
}
func (w *linuxWebviewWindow) setBackgroundColour(colour RGBA) {
rgba := C.GdkRGBA{C.double(colour.Red) / 255.0, C.double(colour.Green) / 255.0, C.double(colour.Blue) / 255.0, C.double(colour.Alpha) / 255.0}
C.webkit_web_view_set_background_color((*C.WebKitWebView)(w.webview), &rgba)
cssStr := C.CString(fmt.Sprintf("#webview-box {background-color: rgba(%d, %d, %d, %1.1f);}", colour.Red, colour.Green, colour.Blue, float32(colour.Alpha)/255.0))
provider := C.gtk_css_provider_new()
C.gtk_style_context_add_provider(
C.gtk_widget_get_style_context((*C.GtkWidget)(w.vbox)),
(*C.GtkStyleProvider)(unsafe.Pointer(provider)),
C.GTK_STYLE_PROVIDER_PRIORITY_USER)
C.g_object_unref(C.gpointer(provider))
C.gtk_css_provider_load_from_data(provider, cssStr, -1, nil)
C.free(unsafe.Pointer(cssStr))
}
func getPrimaryScreen() (*Screen, error) {
display := C.gdk_display_get_default()
monitor := C.gdk_display_get_primary_monitor(display)
geometry := C.GdkRectangle{}
C.gdk_monitor_get_geometry(monitor, &geometry)
scaleFactor := int(C.gdk_monitor_get_scale_factor(monitor))
// get the name for the screen
name := C.gdk_monitor_get_model(monitor)
return &Screen{
ID: "0",
Name: C.GoString(name),
IsPrimary: true,
X: int(geometry.x),
Y: int(geometry.y),
Size: Size{
Height: int(geometry.height),
Width: int(geometry.width),
},
Bounds: Rect{
X: int(geometry.x),
Y: int(geometry.y),
Height: int(geometry.height),
Width: int(geometry.width),
},
ScaleFactor: float32(scaleFactor),
}, nil
}
func windowSetGeometryHints(window pointer, minWidth, minHeight, maxWidth, maxHeight int) {
size := C.GdkGeometry{
min_width: C.int(minWidth),
min_height: C.int(minHeight),
max_width: C.int(maxWidth),
max_height: C.int(maxHeight),
}
C.gtk_window_set_geometry_hints((*C.GtkWindow)(window), nil, &size, C.GDK_HINT_MAX_SIZE|C.GDK_HINT_MIN_SIZE)
}
func (w *linuxWebviewWindow) setFrameless(frameless bool) {
C.gtk_window_set_decorated(w.gtkWindow(), gtkBool(!frameless))
// TODO: Deal with transparency for the titlebar if possible when !frameless
// Perhaps we just make it undecorated and add a menu bar inside?
}
// TODO: confirm this is working properly
func (w *linuxWebviewWindow) setHTML(html string) {
cHTML := C.CString(html)
uri := C.CString("wails://")
empty := C.CString("")
defer C.free(unsafe.Pointer(cHTML))
defer C.free(unsafe.Pointer(uri))
defer C.free(unsafe.Pointer(empty))
C.webkit_web_view_load_alternate_html(
w.webKitWebView(),
cHTML,
uri,
empty)
}
func (w *linuxWebviewWindow) setAlwaysOnTop(alwaysOnTop bool) {
C.gtk_window_set_keep_above(w.gtkWindow(), gtkBool(alwaysOnTop))
}
func (w *linuxWebviewWindow) flash(_ bool) {
}
func (w *linuxWebviewWindow) setOpacity(opacity float64) {
C.gtk_widget_set_opacity(w.gtkWidget(), C.double(opacity))
}
func (w *linuxWebviewWindow) setTitle(title string) {
if !w.parent.options.Frameless {
cTitle := C.CString(title)
C.gtk_window_set_title(w.gtkWindow(), cTitle)
C.free(unsafe.Pointer(cTitle))
}
}
func (w *linuxWebviewWindow) setIcon(icon pointer) {
if icon != nil {
C.gtk_window_set_icon(w.gtkWindow(), (*C.GdkPixbuf)(icon))
}
}
func (w *linuxWebviewWindow) gtkWindow() *C.GtkWindow {
return (*C.GtkWindow)(w.window)
}
func (w *linuxWebviewWindow) setTransparent() {
screen := C.gtk_widget_get_screen(w.gtkWidget())
visual := C.gdk_screen_get_rgba_visual(screen)
if visual != nil && C.gdk_screen_is_composited(screen) == C.int(1) {
C.gtk_widget_set_app_paintable(w.gtkWidget(), C.gboolean(1))
C.gtk_widget_set_visual(w.gtkWidget(), visual)
}
}
func (w *linuxWebviewWindow) setURL(uri string) {
target := C.CString(uri)
C.webkit_web_view_load_uri(w.webKitWebView(), target)
C.free(unsafe.Pointer(target))
}
//export emit
func emit(we *C.WindowEvent) {
window, _ := globalApplication.Window.GetByID(uint(we.id))
if window != nil {
windowEvents <- &windowEvent{
WindowID: window.ID(),
EventID: uint(events.WindowEventType(we.event)),
}
}
}
//export handleConfigureEvent
func handleConfigureEvent(widget *C.GtkWidget, event *C.GdkEventConfigure, data C.uintptr_t) C.gboolean {
window, _ := globalApplication.Window.GetByID(uint(data))
if window != nil {
lw := getLinuxWebviewWindow(window)
if lw == nil {
return C.gboolean(1)
}
if lw.lastX != int(event.x) || lw.lastY != int(event.y) {
lw.moveDebouncer(func() {
processWindowEvent(C.uint(data), C.uint(events.Linux.WindowDidMove))
})
}
if lw.lastWidth != int(event.width) || lw.lastHeight != int(event.height) {
lw.resizeDebouncer(func() {
processWindowEvent(C.uint(data), C.uint(events.Linux.WindowDidResize))
})
}
lw.lastX = int(event.x)
lw.lastY = int(event.y)
lw.lastWidth = int(event.width)
lw.lastHeight = int(event.height)
}
return C.gboolean(0)
}
//export handleDeleteEvent
func handleDeleteEvent(widget *C.GtkWidget, event *C.GdkEvent, data C.uintptr_t) C.gboolean {
processWindowEvent(C.uint(data), C.uint(events.Linux.WindowDeleteEvent))
return C.gboolean(1)
}
//export handleFocusEvent
func handleFocusEvent(widget *C.GtkWidget, event *C.GdkEvent, data C.uintptr_t) C.gboolean {
focusEvent := (*C.GdkEventFocus)(unsafe.Pointer(event))
if focusEvent._type == C.GDK_FOCUS_CHANGE {
if focusEvent.in == C.TRUE {
processWindowEvent(C.uint(data), C.uint(events.Linux.WindowFocusIn))
} else {
processWindowEvent(C.uint(data), C.uint(events.Linux.WindowFocusOut))
}
}
return C.gboolean(0)
}
//export handleLoadChanged
func handleLoadChanged(webview *C.WebKitWebView, event C.WebKitLoadEvent, data C.uintptr_t) {
switch event {
case C.WEBKIT_LOAD_STARTED:
processWindowEvent(C.uint(data), C.uint(events.Linux.WindowLoadStarted))
case C.WEBKIT_LOAD_REDIRECTED:
processWindowEvent(C.uint(data), C.uint(events.Linux.WindowLoadRedirected))
case C.WEBKIT_LOAD_COMMITTED:
processWindowEvent(C.uint(data), C.uint(events.Linux.WindowLoadCommitted))
case C.WEBKIT_LOAD_FINISHED:
processWindowEvent(C.uint(data), C.uint(events.Linux.WindowLoadFinished))
}
}
func (w *linuxWebviewWindow) setupSignalHandlers(emit func(e events.WindowEventType)) {
c := NewCalloc()
defer c.Free()
winID := unsafe.Pointer(uintptr(C.uint(w.parent.ID())))
// Set up the window close event
wv := unsafe.Pointer(w.webview)
C.signal_connect(unsafe.Pointer(w.window), c.String("delete-event"), C.handleDeleteEvent, winID)
C.signal_connect(unsafe.Pointer(w.window), c.String("focus-out-event"), C.handleFocusEvent, winID)
C.signal_connect(wv, c.String("load-changed"), C.handleLoadChanged, winID)
C.signal_connect(unsafe.Pointer(w.window), c.String("configure-event"), C.handleConfigureEvent, winID)
contentManager := C.webkit_web_view_get_user_content_manager(w.webKitWebView())
C.signal_connect(unsafe.Pointer(contentManager), c.String("script-message-received::external"), C.sendMessageToBackend, nil)
C.signal_connect(wv, c.String("button-press-event"), C.onButtonEvent, winID)
C.signal_connect(wv, c.String("button-release-event"), C.onButtonEvent, winID)
C.signal_connect(wv, c.String("key-press-event"), C.onKeyPressEvent, winID)
}
func getMouseButtons() (bool, bool, bool) {
var pointer *C.GdkDevice
var state C.GdkModifierType
pointer = C.gdk_seat_get_pointer(C.gdk_display_get_default_seat(C.gdk_display_get_default()))
C.gdk_device_get_state(pointer, nil, nil, &state)
return state&C.GDK_BUTTON1_MASK > 0, state&C.GDK_BUTTON2_MASK > 0, state&C.GDK_BUTTON3_MASK > 0
}
func openDevTools(webview pointer) {
inspector := C.webkit_web_view_get_inspector((*C.WebKitWebView)(webview))
C.webkit_web_inspector_show(inspector)
}
func (w *linuxWebviewWindow) startDrag() error {
C.gtk_window_begin_move_drag(
(*C.GtkWindow)(w.window),
C.int(w.drag.MouseButton),
C.int(w.drag.XRoot),
C.int(w.drag.YRoot),
C.uint32_t(w.drag.DragTime))
return nil
}
func enableDevTools(webview pointer) {
settings := C.webkit_web_view_get_settings((*C.WebKitWebView)(webview))
enabled := C.webkit_settings_get_enable_developer_extras(settings)
switch enabled {
case C.int(0):
enabled = C.int(1)
case C.int(1):
enabled = C.int(0)
}
C.webkit_settings_set_enable_developer_extras(settings, enabled)
}
func (w *linuxWebviewWindow) unfullscreen() {
C.gtk_window_unfullscreen((*C.GtkWindow)(w.window))
w.unmaximise()
}
func (w *linuxWebviewWindow) unmaximise() {
C.gtk_window_unmaximize((*C.GtkWindow)(w.window))
}
func (w *linuxWebviewWindow) getZoom() float64 {
return float64(C.webkit_web_view_get_zoom_level(w.webKitWebView()))
}
func (w *linuxWebviewWindow) zoomIn() {
// FIXME: ZoomIn/Out is assumed to be incorrect!
ZoomInFactor := 1.10
w.setZoom(w.getZoom() * ZoomInFactor)
}
func (w *linuxWebviewWindow) zoomOut() {
ZoomInFactor := -1.10
w.setZoom(w.getZoom() * ZoomInFactor)
}
func (w *linuxWebviewWindow) zoomReset() {
w.setZoom(1.0)
}
func (w *linuxWebviewWindow) reload() {
uri := C.CString("wails://")
C.webkit_web_view_load_uri(w.webKitWebView(), uri)
C.free(unsafe.Pointer(uri))
}
func (w *linuxWebviewWindow) setZoom(zoom float64) {
if zoom < 1 { // 1.0 is the smallest allowable
zoom = 1
}
C.webkit_web_view_set_zoom_level(w.webKitWebView(), C.double(zoom))
}
func (w *linuxWebviewWindow) move(x, y int) {
// Move the window to these coordinates
C.gtk_window_move(w.gtkWindow(), C.int(x), C.int(y))
}
func (w *linuxWebviewWindow) position() (int, int) {
var x C.int
var y C.int
C.gtk_window_get_position((*C.GtkWindow)(w.window), &x, &y)
return int(x), int(y)
}
func (w *linuxWebviewWindow) ignoreMouse(ignore bool) {
if ignore {
C.gtk_widget_set_events((*C.GtkWidget)(unsafe.Pointer(w.window)), C.GDK_ENTER_NOTIFY_MASK|C.GDK_LEAVE_NOTIFY_MASK)
} else {
C.gtk_widget_set_events((*C.GtkWidget)(unsafe.Pointer(w.window)), C.GDK_ALL_EVENTS_MASK)
}
}
// FIXME Change this to reflect mouse button!
//
//export onButtonEvent
func onButtonEvent(_ *C.GtkWidget, event *C.GdkEventButton, data C.uintptr_t) C.gboolean {
// Constants (defined here to be easier to use with purego)
GdkButtonPress := C.GDK_BUTTON_PRESS // 4
Gdk2ButtonPress := C.GDK_2BUTTON_PRESS // 5 for double-click
GdkButtonRelease := C.GDK_BUTTON_RELEASE // 7
windowId := uint(C.uint(data))
window, _ := globalApplication.Window.GetByID(windowId)
if window == nil {
return C.gboolean(0)
}
lw := getLinuxWebviewWindow(window)
if lw == nil {
return C.gboolean(0)
}
if event == nil {
return C.gboolean(0)
}
if event.button == 3 {
return C.gboolean(0)
}
switch int(event._type) {
case GdkButtonPress:
lw.drag.MouseButton = uint(event.button)
lw.drag.XRoot = int(event.x_root)
lw.drag.YRoot = int(event.y_root)
lw.drag.DragTime = uint32(event.time)
case Gdk2ButtonPress:
// do we need something here?
case GdkButtonRelease:
lw.endDrag(uint(event.button), int(event.x_root), int(event.y_root))
}
return C.gboolean(0)
}
//export onMenuButtonEvent
func onMenuButtonEvent(_ *C.GtkWidget, event *C.GdkEventButton, data C.uintptr_t) C.gboolean {
// Constants (defined here to be easier to use with purego)
GdkButtonRelease := C.GDK_BUTTON_RELEASE // 7
windowId := uint(C.uint(data))
window, _ := globalApplication.Window.GetByID(windowId)
if window == nil {
return C.gboolean(0)
}
lw := getLinuxWebviewWindow(window)
if lw == nil {
return C.gboolean(0)
}
// prevent custom context menu from closing immediately
if event.button == 3 && int(event._type) == GdkButtonRelease && lw.ctxMenuOpened {
lw.ctxMenuOpened = false
return C.gboolean(1)
}
return C.gboolean(0)
}
//export onDragEnter
func onDragEnter(data unsafe.Pointer) {
windowId := uint(uintptr(data))
targetWindow, ok := globalApplication.Window.GetByID(windowId)
if !ok || targetWindow == nil {
return
}
// HandleDragEnter is Linux-specific (GTK intercepts drag events)
if w, ok := targetWindow.(*WebviewWindow); ok {
w.HandleDragEnter()
}
}
//export onDragLeave
func onDragLeave(data unsafe.Pointer) {
windowId := uint(uintptr(data))
targetWindow, ok := globalApplication.Window.GetByID(windowId)
if !ok || targetWindow == nil {
return
}
// HandleDragLeave is Linux-specific (GTK intercepts drag events)
if w, ok := targetWindow.(*WebviewWindow); ok {
w.HandleDragLeave()
}
}
//export onDragOver
func onDragOver(x C.gint, y C.gint, data unsafe.Pointer) {
windowId := uint(uintptr(data))
targetWindow, ok := globalApplication.Window.GetByID(windowId)
if !ok || targetWindow == nil {
return
}
// HandleDragOver is Linux-specific (GTK intercepts drag events)
if w, ok := targetWindow.(*WebviewWindow); ok {
w.HandleDragOver(int(x), int(y))
}
}
//export onUriList
func onUriList(extracted **C.char, x C.gint, y C.gint, data unsafe.Pointer) {
// Credit: https://groups.google.com/g/golang-nuts/c/bI17Bpck8K4/m/DVDa7EMtDAAJ
offset := unsafe.Sizeof(uintptr(0))
filenames := []string{}
for *extracted != nil {
filenames = append(filenames, strings.TrimPrefix(C.GoString(*extracted), "file://"))
extracted = (**C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(extracted)) + offset))
}
// Window ID is stored as the pointer value itself (not pointing to memory)
// Same pattern as other signal handlers in this file
windowId := uint(uintptr(data))
targetWindow, ok := globalApplication.Window.GetByID(windowId)
if !ok || targetWindow == nil {
globalApplication.error("onUriList could not find window with ID: %d", windowId)
return
}
// Send to frontend for drop target detection and filtering
targetWindow.InitiateFrontendDropProcessing(filenames, int(x), int(y))
}
var debounceTimer *time.Timer
var isDebouncing bool = false
//export onKeyPressEvent
func onKeyPressEvent(_ *C.GtkWidget, event *C.GdkEventKey, userData C.uintptr_t) C.gboolean {
// Keypress re-emits if the key is pressed over a certain threshold so we need a debounce
if isDebouncing {
debounceTimer.Reset(50 * time.Millisecond)
return C.gboolean(0)
}
// Start the debounce
isDebouncing = true
debounceTimer = time.AfterFunc(50*time.Millisecond, func() {
isDebouncing = false
})
windowID := uint(C.uint(userData))
if accelerator, ok := getKeyboardState(event); ok {
windowKeyEvents <- &windowKeyEvent{
windowId: windowID,
acceleratorString: accelerator,
}
}
return C.gboolean(0)
}
func getKeyboardState(event *C.GdkEventKey) (string, bool) {
modifiers := uint(event.state) & C.GDK_MODIFIER_MASK
keyCode := uint(event.keyval)
var acc accelerator
// Check Accelerators
if modifiers&(C.GDK_SHIFT_MASK) != 0 {
acc.Modifiers = append(acc.Modifiers, ShiftKey)
}
if modifiers&(C.GDK_CONTROL_MASK) != 0 {
acc.Modifiers = append(acc.Modifiers, ControlKey)
}
if modifiers&(C.GDK_MOD1_MASK) != 0 {
acc.Modifiers = append(acc.Modifiers, OptionOrAltKey)
}
if modifiers&(C.GDK_SUPER_MASK) != 0 {
acc.Modifiers = append(acc.Modifiers, SuperKey)
}
keyString, ok := VirtualKeyCodes[keyCode]
if !ok {
return "", false
}
acc.Key = keyString
return acc.String(), true
}
//export onProcessRequest
func onProcessRequest(request *C.WebKitURISchemeRequest, data C.uintptr_t) {
webView := C.webkit_uri_scheme_request_get_web_view(request)
windowId := uint(C.get_window_id(unsafe.Pointer(webView)))
webviewRequests <- &webViewAssetRequest{
Request: webview.NewRequest(unsafe.Pointer(request)),
windowId: windowId,
windowName: func() string {
if window, ok := globalApplication.Window.GetByID(windowId); ok {
return window.Name()
}
return ""
}(),
}
}
//export sendMessageToBackend
func sendMessageToBackend(contentManager *C.WebKitUserContentManager, result *C.WebKitJavascriptResult,
data unsafe.Pointer) {
// Get the windowID from the contentManager
thisWindowID := uint(C.get_window_id(unsafe.Pointer(contentManager)))
webView := C.get_webview_from_content_manager(unsafe.Pointer(contentManager))
var origin string
if webView != nil {
currentUri := C.webkit_web_view_get_uri(webView)
if currentUri != nil {
uri := C.g_strdup(currentUri)
defer C.g_free(C.gpointer(uri))
origin = C.GoString(uri)
}
}
var msg string
value := C.webkit_javascript_result_get_js_value(result)
message := C.jsc_value_to_string(value)
msg = C.GoString(message)
defer C.g_free(C.gpointer(message))
windowMessageBuffer <- &windowMessage{
windowId: thisWindowID,
message: msg,
originInfo: &OriginInfo{
Origin: origin,
},
}
}
func gtkBool(input bool) C.gboolean {
if input {
return C.gboolean(1)
}
return C.gboolean(0)
}
// dialog related
func setWindowIcon(window pointer, icon []byte) {
loader := C.gdk_pixbuf_loader_new()
if loader == nil {
return
}
written := C.gdk_pixbuf_loader_write(
loader,
(*C.uchar)(&icon[0]),
C.ulong(len(icon)),
nil)
if written == 0 {
return
}
C.gdk_pixbuf_loader_close(loader, nil)
pixbuf := C.gdk_pixbuf_loader_get_pixbuf(loader)
if pixbuf != nil {
C.gtk_window_set_icon((*C.GtkWindow)(window), pixbuf)
}
C.g_object_unref(C.gpointer(loader))
}
//export messageDialogCB
func messageDialogCB(button C.int) {
fmt.Println("messageDialogCB", button)
}
func runChooserDialog(window pointer, allowMultiple, createFolders, showHidden bool, currentFolder, title string, action int, acceptLabel string, filters []FileFilter, currentName string) (chan string, error) {
titleStr := C.CString(title)
defer C.free(unsafe.Pointer(titleStr))
cancelStr := C.CString("_Cancel")
defer C.free(unsafe.Pointer(cancelStr))
acceptLabelStr := C.CString(acceptLabel)
defer C.free(unsafe.Pointer(acceptLabelStr))
fc := C.gtkFileChooserDialogNew(
titleStr,
(*C.GtkWindow)(window),
C.GtkFileChooserAction(action),
cancelStr,
acceptLabelStr)
C.gtk_file_chooser_set_action((*C.GtkFileChooser)(fc), C.GtkFileChooserAction(action))
gtkFilters := []*C.GtkFileFilter{}
for _, filter := range filters {
f := C.gtk_file_filter_new()
displayStr := C.CString(filter.DisplayName)
C.gtk_file_filter_set_name(f, displayStr)
C.free(unsafe.Pointer(displayStr))
patterns := strings.Split(filter.Pattern, ";")
for _, pattern := range patterns {
patternStr := C.CString(strings.TrimSpace(pattern))
C.gtk_file_filter_add_pattern(f, patternStr)
C.free(unsafe.Pointer(patternStr))
}
C.gtk_file_chooser_add_filter((*C.GtkFileChooser)(fc), f)
gtkFilters = append(gtkFilters, f)
}
C.gtk_file_chooser_set_select_multiple(
(*C.GtkFileChooser)(fc),
gtkBool(allowMultiple))
C.gtk_file_chooser_set_create_folders(
(*C.GtkFileChooser)(fc),
gtkBool(createFolders))
C.gtk_file_chooser_set_show_hidden(
(*C.GtkFileChooser)(fc),
gtkBool(showHidden))
if currentFolder != "" {
path := C.CString(currentFolder)
C.gtk_file_chooser_set_current_folder(
(*C.GtkFileChooser)(fc),
path)
C.free(unsafe.Pointer(path))
}
// Set the current name for save dialogs to pre-populate the filename
if currentName != "" && action == C.GTK_FILE_CHOOSER_ACTION_SAVE {
nameStr := C.CString(currentName)
C.gtk_file_chooser_set_current_name(
(*C.GtkFileChooser)(fc),
nameStr)
C.free(unsafe.Pointer(nameStr))
}
// FIXME: This should be consolidated - duplicate exists in linux_purego.go
buildStringAndFree := func(s C.gpointer) string {
bytes := []byte{}
p := unsafe.Pointer(s)
for {
val := *(*byte)(p)
if val == 0 { // this is the null terminator
break
}
bytes = append(bytes, val)
p = unsafe.Add(p, 1)
}
C.g_free(s) // so we don't have to iterate a second time
return string(bytes)
}
selections := make(chan string)
// run this on the gtk thread
InvokeAsync(func() {
response := C.gtk_dialog_run((*C.GtkDialog)(fc))
// Extract results on GTK thread BEFORE destroying widget
var results []string
if response == C.GTK_RESPONSE_ACCEPT {
// No artificial limit - consistent with Windows/macOS behavior
filenames := C.gtk_file_chooser_get_filenames((*C.GtkFileChooser)(fc))
for iter := filenames; iter != nil; iter = iter.next {
results = append(results, buildStringAndFree(C.gpointer(iter.data)))
}
C.g_slist_free(filenames)
}
// Destroy widget after extracting results (on GTK thread)
C.gtk_widget_destroy((*C.GtkWidget)(unsafe.Pointer(fc)))
// Send results from goroutine (safe - no GTK calls)
go func() {
defer handlePanic()
for _, result := range results {
selections <- result
}
close(selections)
}()
})
return selections, nil
}
func runOpenFileDialog(dialog *OpenFileDialogStruct) (chan string, error) {
var action int
if dialog.canChooseDirectories {
action = C.GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER
} else {
action = C.GTK_FILE_CHOOSER_ACTION_OPEN
}
window := nilPointer
if dialog.window != nil {
nativeWindow := dialog.window.NativeWindow()
if nativeWindow != nil {
window = pointer(nativeWindow)
}
}
buttonText := dialog.buttonText
if buttonText == "" {
buttonText = "_Open"
}
return runChooserDialog(
window,
dialog.allowsMultipleSelection,
dialog.canCreateDirectories,
dialog.showHiddenFiles,
dialog.directory,
dialog.title,
action,
buttonText,
dialog.filters,
"")
}
func runQuestionDialog(parent pointer, options *MessageDialog) int {
cMsg := C.CString(options.Message)
cTitle := C.CString(options.Title)
defer C.free(unsafe.Pointer(cMsg))
defer C.free(unsafe.Pointer(cTitle))
hasButtons := false
if len(options.Buttons) > 0 {
hasButtons = true
}
dType, ok := map[DialogType]C.int{
InfoDialogType: C.GTK_MESSAGE_INFO,
// ErrorDialogType:
QuestionDialogType: C.GTK_MESSAGE_QUESTION,
WarningDialogType: C.GTK_MESSAGE_WARNING,
}[options.DialogType]
if !ok {
// FIXME: Add logging here!
dType = C.GTK_MESSAGE_INFO
}
dialog := C.new_message_dialog((*C.GtkWindow)(parent), cMsg, dType, C.bool(hasButtons))
if options.Title != "" {
C.gtk_window_set_title(
(*C.GtkWindow)(unsafe.Pointer(dialog)),
cTitle)
}
if img, err := pngToImage(options.Icon); err == nil && len(img.Pix) > 0 {
// Use g_bytes_new instead of g_bytes_new_static because Go memory can be
// moved or freed by the GC. g_bytes_new copies the data to C-owned memory.
gbytes := C.g_bytes_new(
C.gconstpointer(unsafe.Pointer(&img.Pix[0])),
C.ulong(len(img.Pix)))
defer C.g_bytes_unref(gbytes)
pixBuf := C.gdk_pixbuf_new_from_bytes(
gbytes,
C.GDK_COLORSPACE_RGB,
1, // has_alpha
8,
C.int(img.Bounds().Dx()),
C.int(img.Bounds().Dy()),
C.int(img.Stride),
)
image := C.gtk_image_new_from_pixbuf(pixBuf)
C.gtk_widget_set_visible((*C.GtkWidget)(image), C.gboolean(1))
contentArea := C.gtk_dialog_get_content_area((*C.GtkDialog)(dialog))
C.gtk_container_add(
(*C.GtkContainer)(unsafe.Pointer(contentArea)),
(*C.GtkWidget)(image))
}
for i, button := range options.Buttons {
cLabel := C.CString(button.Label)
defer C.free(unsafe.Pointer(cLabel))
index := C.int(i)
C.gtk_dialog_add_button(
(*C.GtkDialog)(dialog), cLabel, index)
if button.IsDefault {
C.gtk_dialog_set_default_response((*C.GtkDialog)(dialog), index)
}
}
defer C.gtk_widget_destroy((*C.GtkWidget)(dialog))
return int(C.gtk_dialog_run((*C.GtkDialog)(unsafe.Pointer(dialog))))
}
func runSaveFileDialog(dialog *SaveFileDialogStruct) (chan string, error) {
window := nilPointer
buttonText := dialog.buttonText
if buttonText == "" {
buttonText = "_Save"
}
results, err := runChooserDialog(
window,
false, // multiple selection
dialog.canCreateDirectories,
dialog.showHiddenFiles,
dialog.directory,
dialog.title,
C.GTK_FILE_CHOOSER_ACTION_SAVE,
buttonText,
dialog.filters,
dialog.filename)
return results, err
}
func (w *linuxWebviewWindow) cut() {
//C.webkit_web_view_execute_editing_command(w.webview, C.WEBKIT_EDITING_COMMAND_CUT)
}
func (w *linuxWebviewWindow) paste() {
//C.webkit_web_view_execute_editing_command(w.webview, C.WEBKIT_EDITING_COMMAND_PASTE)
}
func (w *linuxWebviewWindow) copy() {
//C.webkit_web_view_execute_editing_command(w.webview, C.WEBKIT_EDITING_COMMAND_COPY)
}
func (w *linuxWebviewWindow) selectAll() {
//C.webkit_web_view_execute_editing_command(w.webview, C.WEBKIT_EDITING_COMMAND_SELECT_ALL)
}
func (w *linuxWebviewWindow) undo() {
//C.webkit_web_view_execute_editing_command(w.webview, C.WEBKIT_EDITING_COMMAND_UNDO)
}
func (w *linuxWebviewWindow) redo() {
}
func (w *linuxWebviewWindow) delete() {
}