refactor(webkit): migrate core package to gotk4, update workspace types
Replace manual CGO webkit bindings with clean gotk4-based implementation. This is phase 1 of the migration - core types and structure complete. Package Changes: - Deleted 40 CGO files (~5000 lines of manual bindings) - Created 6 new files (~500 lines clean Go code) - mainloop.go: GTK main loop management - types.go: Config, WindowType, WindowFeatures - widgets.go: Paned, Box, Label, Image wrappers - webview.go: WebView wrapper with event handlers - window.go: Window wrapper - errors.go: Error definitions Type System Updates: - paneNode.container: uintptr → gtk.Widgetter - paneNode.titleBar: uintptr → gtk.Widgetter - paneNode.stackWrapper: uintptr → gtk.Widgetter - paneNode.orientation: webkit.Orientation → gtk.Orientation Workspace Updates: - initializePaneWidgets() now accepts gtk.Widgetter - setContainer/setTitleBar/setStackWrapper use gtk.Widgetter - mapDirection() returns gtk.Orientation Dependencies: - Added gotk4/pkg v0.3.1 - Added gotk4-webkitgtk/pkg v0.0.0-20240108031600-dee1973cf440 Next Steps: - Update stacked_panes.go widget operations (~100 locations) - Update workspace_pane_ops.go split operations (~50 locations) - Fix remaining compilation errors in ~23 browser files See docs/webkit-migration-progress.md for detailed status
- commit
- 7ce5a26ba0234eaa129f4e94bd283e9c4e68688b
- author
- bamen · · 2025-10-07 19:27 UTC
- committer
- bamen · · 2025-10-07 20:58 UTC
- parent
- 38db1f3
- signature
- unsigned
55 files · +1883 -9668
A docs/gotk4-migration-plan.md +410 -0
| @@ -0,0 +1,410 @@ | |||||
| 1 | + | # Migration Plan: Manual GTK4 CGO → gotk4 + Regeneration Strategy | |||
| 2 | + | ||||
| 3 | + | ## YES, You Can Regenerate gotk4-webkitgtk Bindings! | |||
| 4 | + | ||||
| 5 | + | ### Current State | |||
| 6 | + | - **gotk4-webkitgtk**: Last updated Jan 8, 2024 (~1 year old) | |||
| 7 | + | - **gotk4**: Actively maintained (last update Jul 3, 2025) | |||
| 8 | + | - **Status**: ✅ **WORKS WITH LATEST GOTK4** (confirmed by recent test) | |||
| 9 | + | - **WebKitGTK 6.0**: ✅ **SUPPORTED** (import path: `webkit/v6`) | |||
| 10 | + | ||||
| 11 | + | ### Good News from Research | |||
| 12 | + | The last comment on the compatibility issue (recent) confirms: | |||
| 13 | + | ```go | |||
| 14 | + | import webkit "github.com/diamondburned/gotk4-webkitgtk/pkg/webkit/v6" | |||
| 15 | + | // Works perfectly with gotk4 v0.3.2! | |||
| 16 | + | ``` | |||
| 17 | + | ||||
| 18 | + | --- | |||
| 19 | + | ||||
| 20 | + | ## Option 1: Use Existing gotk4-webkitgtk (RECOMMENDED) | |||
| 21 | + | ||||
| 22 | + | ### Why This Works | |||
| 23 | + | - Bindings were regenerated Jan 2024 with GTK4 WebKitGTK | |||
| 24 | + | - Compatible with latest gotk4 (v0.3.2+) | |||
| 25 | + | - Already supports webkitgtk-6.0 | |||
| 26 | + | - **No need to regenerate unless you need bleeding-edge APIs** | |||
| 27 | + | ||||
| 28 | + | ### Migration Steps | |||
| 29 | + | ```bash | |||
| 30 | + | # Add dependencies | |||
| 31 | + | go get github.com/diamondburned/gotk4/pkg@latest | |||
| 32 | + | go get github.com/diamondburned/gotk4-webkitgtk/pkg@latest | |||
| 33 | + | ||||
| 34 | + | # Imports will be: | |||
| 35 | + | import ( | |||
| 36 | + | "github.com/diamondburned/gotk4/pkg/gtk/v4" | |||
| 37 | + | "github.com/diamondburned/gotk4/pkg/gdk/v4" | |||
| 38 | + | webkit "github.com/diamondburned/gotk4-webkitgtk/pkg/webkit/v6" | |||
| 39 | + | ) | |||
| 40 | + | ``` | |||
| 41 | + | ||||
| 42 | + | --- | |||
| 43 | + | ||||
| 44 | + | ## Option 2: Regenerate Bindings for Latest WebKitGTK | |||
| 45 | + | ||||
| 46 | + | ### When to Regenerate | |||
| 47 | + | - Need WebKitGTK APIs added after Jan 2024 | |||
| 48 | + | - Want to contribute upstream improvements | |||
| 49 | + | - Customize bindings for your specific needs | |||
| 50 | + | ||||
| 51 | + | ### How to Regenerate (3 Methods) | |||
| 52 | + | ||||
| 53 | + | #### Method A: Using Nix (Recommended by gotk4 maintainer) | |||
| 54 | + | ||||
| 55 | + | ```bash | |||
| 56 | + | # 1. Install Nix (if not already) | |||
| 57 | + | curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | sh -s -- install | |||
| 58 | + | ||||
| 59 | + | # 2. Clone gotk4-webkitgtk | |||
| 60 | + | git clone https://github.com/diamondburned/gotk4-webkitgtk.git | |||
| 61 | + | cd gotk4-webkitgtk | |||
| 62 | + | ||||
| 63 | + | # 3. Update shell.nix to use webkitgtk_6_0 (already configured!) | |||
| 64 | + | # See: buildInputs includes webkitgtk_6_0 | |||
| 65 | + | ||||
| 66 | + | # 4. Enter Nix environment | |||
| 67 | + | nix-shell | |||
| 68 | + | ||||
| 69 | + | # 5. Regenerate bindings | |||
| 70 | + | go generate | |||
| 71 | + | ||||
| 72 | + | # Bindings will be regenerated with your system's WebKitGTK version! | |||
| 73 | + | ``` | |||
| 74 | + | ||||
| 75 | + | #### Method B: Fork abergmeier's Updated Generator | |||
| 76 | + | ||||
| 77 | + | A community member already fixed the generator: | |||
| 78 | + | ```bash | |||
| 79 | + | # Clone the updated fork | |||
| 80 | + | git clone https://github.com/abergmeier/gotk4-webkitgtk.git -b webkitv6 | |||
| 81 | + | cd gotk4-webkitgtk | |||
| 82 | + | ||||
| 83 | + | # This fork uses gotk4-adwaita's newer genmain package | |||
| 84 | + | # Should work with latest WebKitGTK 6.0 | |||
| 85 | + | ``` | |||
| 86 | + | ||||
| 87 | + | #### Method C: Update Generator Yourself | |||
| 88 | + | ||||
| 89 | + | Follow gotk4-adwaita's pattern: | |||
| 90 | + | ```bash | |||
| 91 | + | # 1. Clone both repos | |||
| 92 | + | git clone https://github.com/diamondburned/gotk4-adwaita.git | |||
| 93 | + | git clone https://github.com/diamondburned/gotk4-webkitgtk.git | |||
| 94 | + | ||||
| 95 | + | # 2. Compare generator.go files | |||
| 96 | + | # gotk4-adwaita uses newer genmain package | |||
| 97 | + | # gotk4-webkitgtk uses older girgen directly | |||
| 98 | + | ||||
| 99 | + | # 3. Update gotk4-webkitgtk/generator.go to match adwaita pattern | |||
| 100 | + | # Key changes needed: | |||
| 101 | + | # - Import "github.com/diamondburned/gotk4/gir/cmd/genmain" | |||
| 102 | + | # - Use genmain.Main() instead of direct girgen calls | |||
| 103 | + | # - Add preprocessors for module name fixes (soup, javascriptcore) | |||
| 104 | + | # - Add TLS protocol version polyfill | |||
| 105 | + | ``` | |||
| 106 | + | ||||
| 107 | + | --- | |||
| 108 | + | ||||
| 109 | + | ## Migration Plan: From Manual CGO to gotk4 | |||
| 110 | + | ||||
| 111 | + | ### Phase 1: Proof of Concept (1-2 days) | |||
| 112 | + | ||||
| 113 | + | Test gotk4 compatibility with simple example: | |||
| 114 | + | ||||
| 115 | + | ```go | |||
| 116 | + | package main | |||
| 117 | + | ||||
| 118 | + | import ( | |||
| 119 | + | "os" | |||
| 120 | + | webkit "github.com/diamondburned/gotk4-webkitgtk/pkg/webkit/v6" | |||
| 121 | + | "github.com/diamondburned/gotk4/pkg/gio/v2" | |||
| 122 | + | "github.com/diamondburned/gotk4/pkg/gtk/v4" | |||
| 123 | + | ) | |||
| 124 | + | ||||
| 125 | + | func main() { | |||
| 126 | + | app := gtk.NewApplication("com.dumber.test", gio.ApplicationDefaultFlags) | |||
| 127 | + | ||||
| 128 | + | app.ConnectActivate(func() { | |||
| 129 | + | window := gtk.NewApplicationWindow(app) | |||
| 130 | + | window.SetTitle("Dumb Browser Test") | |||
| 131 | + | window.SetDefaultSize(1024, 768) | |||
| 132 | + | ||||
| 133 | + | webView := webkit.NewWebView() | |||
| 134 | + | webView.LoadURI("https://example.com") | |||
| 135 | + | ||||
| 136 | + | // Type-safe, clean API! | |||
| 137 | + | webView.ConnectLoadChanged(func(event webkit.LoadEvent) { | |||
| 138 | + | uri := webView.URI() | |||
| 139 | + | println("Loaded:", uri) | |||
| 140 | + | }) | |||
| 141 | + | ||||
| 142 | + | window.SetChild(webView) | |||
| 143 | + | window.Present() | |||
| 144 | + | }) | |||
| 145 | + | ||||
| 146 | + | os.Exit(app.Run(os.Args)) | |||
| 147 | + | } | |||
| 148 | + | ``` | |||
| 149 | + | ||||
| 150 | + | **Test this builds and runs on your system!** | |||
| 151 | + | ||||
| 152 | + | ### Phase 2: Core Migration (2-3 weeks) | |||
| 153 | + | ||||
| 154 | + | #### File-by-file replacement strategy: | |||
| 155 | + | ||||
| 156 | + | 1. **Window wrapper** (`pkg/webkit/window.go`) | |||
| 157 | + | ```go | |||
| 158 | + | // Before | |||
| 159 | + | type Window struct { | |||
| 160 | + | win *C.GtkWidget | |||
| 161 | + | } | |||
| 162 | + | ||||
| 163 | + | // After | |||
| 164 | + | type Window struct { | |||
| 165 | + | win *gtk.ApplicationWindow | |||
| 166 | + | } | |||
| 167 | + | ``` | |||
| 168 | + | ||||
| 169 | + | 2. **Widget helpers** (workspace_widgets_cgo.go) | |||
| 170 | + | - ~1350 lines → ~300 lines | |||
| 171 | + | - All `C.gtk_*` → `gtk.*` methods | |||
| 172 | + | ||||
| 173 | + | 3. **Event controllers** (keyboard_cgo.go) | |||
| 174 | + | - No more `//export` functions! | |||
| 175 | + | - Direct Go closures | |||
| 176 | + | ||||
| 177 | + | 4. **WebView core** (webview_cgo.go) | |||
| 178 | + | - Simplified from 2800 lines | |||
| 179 | + | - Type-safe signal connections | |||
| 180 | + | ||||
| 181 | + | ### Phase 3: Advanced Features (1-2 weeks) | |||
| 182 | + | ||||
| 183 | + | - UserContentManager integration | |||
| 184 | + | - Custom URI schemes | |||
| 185 | + | - Content filtering | |||
| 186 | + | - Shortcuts system | |||
| 187 | + | ||||
| 188 | + | --- | |||
| 189 | + | ||||
| 190 | + | ## Key Differences: Manual CGO vs gotk4 | |||
| 191 | + | ||||
| 192 | + | ### Memory Management | |||
| 193 | + | ```go | |||
| 194 | + | // Before: Manual reference counting | |||
| 195 | + | C.g_object_ref(widget) | |||
| 196 | + | defer C.g_object_unref(widget) | |||
| 197 | + | ||||
| 198 | + | // After: Automatic (Go GC integrated) | |||
| 199 | + | widget := gtk.NewLabel("text") | |||
| 200 | + | // That's it! GC handles cleanup | |||
| 201 | + | ``` | |||
| 202 | + | ||||
| 203 | + | ### Type Safety | |||
| 204 | + | ```go | |||
| 205 | + | // Before: Runtime panics | |||
| 206 | + | widget := (*C.GtkWidget)(unsafe.Pointer(ptr)) | |||
| 207 | + | ||||
| 208 | + | // After: Compile-time safety | |||
| 209 | + | widget := obj.Cast().(gtk.Widgetter) | |||
| 210 | + | ``` | |||
| 211 | + | ||||
| 212 | + | ### Signal Connections | |||
| 213 | + | ```go | |||
| 214 | + | // Before: C bridge + export | |||
| 215 | + | //export goOnTitleChanged | |||
| 216 | + | func goOnTitleChanged(id C.ulong, ctitle *C.char) { | |||
| 217 | + | title := C.GoString(ctitle) | |||
| 218 | + | // handle... | |||
| 219 | + | } | |||
| 220 | + | ||||
| 221 | + | // After: Direct Go closure | |||
| 222 | + | webView.ConnectTitleChanged(func(title string) { | |||
| 223 | + | // handle... | |||
| 224 | + | }) | |||
| 225 | + | ``` | |||
| 226 | + | ||||
| 227 | + | --- | |||
| 228 | + | ||||
| 229 | + | ## Recommended Approach | |||
| 230 | + | ||||
| 231 | + | ### For Your Project (Dumb Browser): | |||
| 232 | + | ||||
| 233 | + | 1. **Start with existing gotk4-webkitgtk** (Jan 2024 version) | |||
| 234 | + | - It's recent enough for WebKitGTK 6.0 | |||
| 235 | + | - Already compatible with latest gotk4 | |||
| 236 | + | - Proven to work (see GitHub issue) | |||
| 237 | + | ||||
| 238 | + | 2. **Only regenerate if** you need specific APIs added after Jan 2024 | |||
| 239 | + | - Use Nix method (most reliable) | |||
| 240 | + | - Or use abergmeier's fork (already updated) | |||
| 241 | + | ||||
| 242 | + | 3. **Parallel implementation** | |||
| 243 | + | - Keep `webkit_cgo` build tag for current code | |||
| 244 | + | - Add `gotk4` build tag for new implementation | |||
| 245 | + | - Switch when stable | |||
| 246 | + | ||||
| 247 | + | ### Expected Timeline | |||
| 248 | + | ||||
| 249 | + | | Phase | Original Estimate | With Existing Bindings | | |||
| 250 | + | |-------|------------------|------------------------| | |||
| 251 | + | | Setup | 1-2 days | ✅ 1 day (no regen needed) | | |||
| 252 | + | | Core Migration | 10-14 days | 10-14 days | | |||
| 253 | + | | Advanced Features | 7-10 days | 7-10 days | | |||
| 254 | + | | Testing | 3-5 days | 3-5 days | | |||
| 255 | + | | **Total** | **21-31 days** | **21-30 days** | | |||
| 256 | + | ||||
| 257 | + | --- | |||
| 258 | + | ||||
| 259 | + | ## Gotcha: Known Issues (From Research) | |||
| 260 | + | ||||
| 261 | + | ### Fixed Issues ✅ | |||
| 262 | + | - ❌ "Not usable with gotk4" - **FIXED** (works with v0.3.2+) | |||
| 263 | + | - ❌ Module name bugs (soup, javascriptcore) - **FIXED** in community forks | |||
| 264 | + | - ❌ Missing TLSProtocolVersion - **WORKAROUND** available | |||
| 265 | + | ||||
| 266 | + | ### Potential Issues | |||
| 267 | + | - If regenerating: Generator is outdated (use adwaita's genmain pattern) | |||
| 268 | + | - Nix learning curve (but Docker alternative exists) | |||
| 269 | + | ||||
| 270 | + | --- | |||
| 271 | + | ||||
| 272 | + | ## Decision Matrix | |||
| 273 | + | ||||
| 274 | + | | Scenario | Recommendation | | |||
| 275 | + | |----------|---------------| | |||
| 276 | + | | **Just want to use gotk4** | Use existing gotk4-webkitgtk pkg | | |||
| 277 | + | | **Need latest WebKitGTK APIs** | Regenerate with Nix | | |||
| 278 | + | | **Want to contribute upstream** | Update generator + regenerate | | |||
| 279 | + | | **Avoid Nix** | Use abergmeier's fork | | |||
| 280 | + | ||||
| 281 | + | --- | |||
| 282 | + | ||||
| 283 | + | ## Final Recommendation | |||
| 284 | + | ||||
| 285 | + | ✅ **USE EXISTING gotk4-webkitgtk** - It works great! | |||
| 286 | + | ||||
| 287 | + | Only regenerate if you: | |||
| 288 | + | - Have Nix experience | |||
| 289 | + | - Need bleeding-edge WebKitGTK APIs | |||
| 290 | + | - Want to contribute improvements | |||
| 291 | + | ||||
| 292 | + | The Jan 2024 bindings support WebKitGTK 6.0 and work with latest gotk4. **This is sufficient for your migration.** | |||
| 293 | + | ||||
| 294 | + | --- | |||
| 295 | + | ||||
| 296 | + | ## Migration Architecture | |||
| 297 | + | ||||
| 298 | + | ### Current CGO Architecture | |||
| 299 | + | ``` | |||
| 300 | + | pkg/webkit/ | |||
| 301 | + | ├── window_cgo.go (~60 lines - Window wrapper) | |||
| 302 | + | ├── workspace_widgets_cgo.go (~1350 lines - Widget helpers) | |||
| 303 | + | ├── keyboard_cgo.go (~814 lines - Event controllers) | |||
| 304 | + | ├── shortcuts_cgo.go (~566 lines - Shortcut system) | |||
| 305 | + | ├── webview_cgo.go (~2800 lines - WebView core) | |||
| 306 | + | └── [15+ other _cgo.go files] | |||
| 307 | + | ||||
| 308 | + | Total: ~5000+ lines of manual CGO bindings | |||
| 309 | + | ``` | |||
| 310 | + | ||||
| 311 | + | ### Target gotk4 Architecture | |||
| 312 | + | ``` | |||
| 313 | + | pkg/webkit/ | |||
| 314 | + | ├── window_gotk4.go (~40 lines - Window wrapper) | |||
| 315 | + | ├── widgets_gotk4.go (~300 lines - Widget helpers) | |||
| 316 | + | ├── events_gotk4.go (~200 lines - Event controllers) | |||
| 317 | + | ├── shortcuts_gotk4.go (~150 lines - Shortcut system) | |||
| 318 | + | ├── webview_gotk4.go (~800 lines - WebView core) | |||
| 319 | + | └── [Simplified files] | |||
| 320 | + | ||||
| 321 | + | Total: ~1500-2000 lines of idiomatic Go | |||
| 322 | + | Reduction: 60-70% | |||
| 323 | + | ``` | |||
| 324 | + | ||||
| 325 | + | --- | |||
| 326 | + | ||||
| 327 | + | ## Code Size Comparison | |||
| 328 | + | ||||
| 329 | + | ### Before: Manual CGO | |||
| 330 | + | - **Lines of Code**: ~5000+ | |||
| 331 | + | - **C Bridge Functions**: 50+ | |||
| 332 | + | - **Export Functions**: 15+ | |||
| 333 | + | - **Unsafe Pointers**: Everywhere | |||
| 334 | + | - **Manual Memory Management**: Yes | |||
| 335 | + | - **Type Safety**: Runtime only | |||
| 336 | + | ||||
| 337 | + | ### After: gotk4 | |||
| 338 | + | - **Lines of Code**: ~1500-2000 | |||
| 339 | + | - **C Bridge Functions**: 0 (handled by gotk4) | |||
| 340 | + | - **Export Functions**: 0 | |||
| 341 | + | - **Unsafe Pointers**: Minimal (internal to gotk4) | |||
| 342 | + | - **Manual Memory Management**: No (automatic) | |||
| 343 | + | - **Type Safety**: Compile-time | |||
| 344 | + | ||||
| 345 | + | --- | |||
| 346 | + | ||||
| 347 | + | ## Expected Benefits | |||
| 348 | + | ||||
| 349 | + | ### Code Quality | |||
| 350 | + | - ✅ 60-70% code reduction | |||
| 351 | + | - ✅ Compile-time type safety | |||
| 352 | + | - ✅ No manual memory management | |||
| 353 | + | - ✅ Idiomatic Go patterns | |||
| 354 | + | - ✅ Better IDE support | |||
| 355 | + | ||||
| 356 | + | ### Maintainability | |||
| 357 | + | - ✅ Auto-generated bindings (easy to update) | |||
| 358 | + | - ✅ Less bug surface area | |||
| 359 | + | - ✅ Standard Go error handling | |||
| 360 | + | - ✅ No C header dependencies in Go code | |||
| 361 | + | ||||
| 362 | + | ### Performance | |||
| 363 | + | - ✅ Same or better runtime performance | |||
| 364 | + | - ✅ Faster compilation (less CGO) | |||
| 365 | + | - ✅ Better GC integration | |||
| 366 | + | ||||
| 367 | + | --- | |||
| 368 | + | ||||
| 369 | + | ## Success Criteria | |||
| 370 | + | ||||
| 371 | + | - ✅ All 23 files in `internal/app/browser/` compile with gotk4 | |||
| 372 | + | - ✅ Startup time remains <500ms | |||
| 373 | + | - ✅ No memory leaks in 24h stress test | |||
| 374 | + | - ✅ All shortcuts work correctly | |||
| 375 | + | - ✅ Multi-pane workspace functions properly | |||
| 376 | + | - ✅ WebView lifecycle (create/destroy/reparent) stable | |||
| 377 | + | - ✅ Code is cleaner and more maintainable | |||
| 378 | + | ||||
| 379 | + | --- | |||
| 380 | + | ||||
| 381 | + | ## Resources | |||
| 382 | + | ||||
| 383 | + | ### Documentation | |||
| 384 | + | - [gotk4 Documentation](https://pkg.go.dev/github.com/diamondburned/gotk4/pkg) | |||
| 385 | + | - [gotk4-webkitgtk Documentation](https://pkg.go.dev/github.com/diamondburned/gotk4-webkitgtk/pkg) | |||
| 386 | + | - [gotk4 Examples](https://github.com/diamondburned/gotk4-examples) | |||
| 387 | + | - [GTK4 Documentation](https://docs.gtk.org/gtk4/) | |||
| 388 | + | - [WebKitGTK Documentation](https://webkitgtk.org/reference/webkit2gtk/stable/) | |||
| 389 | + | ||||
| 390 | + | ### Repositories | |||
| 391 | + | - [gotk4 Main](https://github.com/diamondburned/gotk4) | |||
| 392 | + | - [gotk4-webkitgtk Official](https://github.com/diamondburned/gotk4-webkitgtk) | |||
| 393 | + | - [gotk4-webkitgtk Fork (abergmeier)](https://github.com/abergmeier/gotk4-webkitgtk/tree/webkitv6) | |||
| 394 | + | - [gotk4-adwaita (Generator Reference)](https://github.com/diamondburned/gotk4-adwaita) | |||
| 395 | + | ||||
| 396 | + | ### Community | |||
| 397 | + | - [gotk4 Matrix Room](https://matrix.to/#/#gotk4:matrix.org) | |||
| 398 | + | - [GitHub Issues](https://github.com/diamondburned/gotk4/issues) | |||
| 399 | + | ||||
| 400 | + | --- | |||
| 401 | + | ||||
| 402 | + | ## Next Steps | |||
| 403 | + | ||||
| 404 | + | 1. ✅ **[DONE]** Research gotk4-webkitgtk compatibility | |||
| 405 | + | 2. ✅ **[DONE]** Document migration plan | |||
| 406 | + | 3. ⏭️ **[NEXT]** Test proof-of-concept example | |||
| 407 | + | 4. ⏭️ Add gotk4 dependencies to project | |||
| 408 | + | 5. ⏭️ Begin Phase 1: Core Infrastructure migration | |||
| 409 | + | ||||
| 410 | + | **Ready to start Phase 1!** | |||
A docs/new-webkit-package-design.md +176 -0
| @@ -0,0 +1,176 @@ | |||||
| 1 | + | # New webkit Package Design (gotk4-based) | |||
| 2 | + | ||||
| 3 | + | ## Package Structure | |||
| 4 | + | ||||
| 5 | + | ``` | |||
| 6 | + | pkg/webkit/ | |||
| 7 | + | ├── webview.go # WebView wrapper around gotk4-webkitgtk | |||
| 8 | + | ├── window.go # Window wrapper around gtk.Window | |||
| 9 | + | ├── widgets.go # Widget helpers (Box, Paned, Label, Image) | |||
| 10 | + | ├── mainloop.go # GTK main loop management | |||
| 11 | + | ├── shortcuts.go # Keyboard shortcut handling | |||
| 12 | + | ├── config.go # WebView configuration | |||
| 13 | + | ├── memory.go # Memory management (if needed) | |||
| 14 | + | ├── types.go # Common types (WindowType, WindowFeatures, etc.) | |||
| 15 | + | ├── errors.go # Error definitions | |||
| 16 | + | └── internal/ | |||
| 17 | + | └── convert.go # Conversion helpers (gotk4 <-> legacy APIs) | |||
| 18 | + | ``` | |||
| 19 | + | ||||
| 20 | + | ## Core Types | |||
| 21 | + | ||||
| 22 | + | ### WebView | |||
| 23 | + | ```go | |||
| 24 | + | type WebView struct { | |||
| 25 | + | view *webkit.WebView // gotk4-webkitgtk WebView | |||
| 26 | + | ||||
| 27 | + | // Event handlers | |||
| 28 | + | onScriptMessage func(string) | |||
| 29 | + | onTitleChanged func(string) | |||
| 30 | + | onURIChanged func(string) | |||
| 31 | + | onPopup func(string) *WebView | |||
| 32 | + | onClose func() | |||
| 33 | + | ||||
| 34 | + | // State | |||
| 35 | + | id uint64 | |||
| 36 | + | destroyed bool | |||
| 37 | + | config *Config | |||
| 38 | + | } | |||
| 39 | + | ``` | |||
| 40 | + | ||||
| 41 | + | ### Window | |||
| 42 | + | ```go | |||
| 43 | + | type Window struct { | |||
| 44 | + | win *gtk.Window | |||
| 45 | + | ||||
| 46 | + | // Shortcuts (if needed at window level) | |||
| 47 | + | shortcuts map[string]func() | |||
| 48 | + | } | |||
| 49 | + | ``` | |||
| 50 | + | ||||
| 51 | + | ### Widget Helpers | |||
| 52 | + | Replace uintptr-based API with proper gotk4 types: | |||
| 53 | + | ```go | |||
| 54 | + | // Instead of: func NewPaned(orientation Orientation) uintptr | |||
| 55 | + | func NewPaned(orientation gtk.Orientation) *gtk.Paned | |||
| 56 | + | ||||
| 57 | + | // Instead of: func PanedSetStartChild(paned uintptr, child uintptr) | |||
| 58 | + | func (p *Paned) SetStartChild(child gtk.Widgetter) | |||
| 59 | + | ``` | |||
| 60 | + | ||||
| 61 | + | ## API Design Philosophy | |||
| 62 | + | ||||
| 63 | + | ### 1. Type-Safe Widgets | |||
| 64 | + | - No more `uintptr` for widgets | |||
| 65 | + | - Use gotk4's proper types (`gtk.Widgetter`, `gtk.Widget`, etc.) | |||
| 66 | + | - Compile-time type checking | |||
| 67 | + | ||||
| 68 | + | ### 2. Idiomatic Go | |||
| 69 | + | - Methods instead of functions where appropriate | |||
| 70 | + | - Use Go interfaces for polymorphism | |||
| 71 | + | - Standard error handling (no `ErrNotImplemented` stubs) | |||
| 72 | + | ||||
| 73 | + | ### 3. Clean Event Handling | |||
| 74 | + | - Use Go closures directly (no CGO export functions) | |||
| 75 | + | - Type-safe callbacks | |||
| 76 | + | - Clear handler registration | |||
| 77 | + | ||||
| 78 | + | ## Migration Path | |||
| 79 | + | ||||
| 80 | + | ### Phase 1: Core Types (This PR) | |||
| 81 | + | 1. Remove old `pkg/webkit/` | |||
| 82 | + | 2. Create new structure with gotk4 | |||
| 83 | + | 3. Implement WebView, Window basics | |||
| 84 | + | 4. Implement Widget helpers | |||
| 85 | + | ||||
| 86 | + | ### Phase 2: Update Callers | |||
| 87 | + | 1. Update `internal/app/browser/` to use new API | |||
| 88 | + | 2. Convert uintptr-based code to gotk4 types | |||
| 89 | + | 3. Update workspace manager | |||
| 90 | + | ||||
| 91 | + | ### Phase 3: Advanced Features | |||
| 92 | + | 1. Shortcuts system | |||
| 93 | + | 2. Content filtering integration | |||
| 94 | + | 3. Memory management | |||
| 95 | + | 4. Custom URI schemes | |||
| 96 | + | ||||
| 97 | + | ## Key API Changes | |||
| 98 | + | ||||
| 99 | + | ### Before (CGO + uintptr) | |||
| 100 | + | ```go | |||
| 101 | + | // Creating WebView | |||
| 102 | + | view := webkit.NewWebView(cfg) | |||
| 103 | + | widget := view.Widget() // returns uintptr | |||
| 104 | + | ||||
| 105 | + | // Creating paned | |||
| 106 | + | paned := webkit.NewPaned(webkit.OrientationHorizontal) // returns uintptr | |||
| 107 | + | webkit.PanedSetStartChild(paned, widget) | |||
| 108 | + | ||||
| 109 | + | // Window child | |||
| 110 | + | window.SetChild(widget) // takes uintptr | |||
| 111 | + | ``` | |||
| 112 | + | ||||
| 113 | + | ### After (gotk4) | |||
| 114 | + | ```go | |||
| 115 | + | // Creating WebView | |||
| 116 | + | view := webkit.NewWebView(cfg) | |||
| 117 | + | widget := view.AsWidget() // returns gtk.Widgetter | |||
| 118 | + | ||||
| 119 | + | // Creating paned | |||
| 120 | + | paned := webkit.NewPaned(gtk.OrientationHorizontal) // returns *Paned | |||
| 121 | + | paned.SetStartChild(widget) | |||
| 122 | + | ||||
| 123 | + | // Window child | |||
| 124 | + | window.SetChild(widget) // takes gtk.Widgetter | |||
| 125 | + | ``` | |||
| 126 | + | ||||
| 127 | + | ## Backwards Compatibility Bridge | |||
| 128 | + | ||||
| 129 | + | For gradual migration, provide conversion helpers: | |||
| 130 | + | ```go | |||
| 131 | + | // In internal/convert.go | |||
| 132 | + | func WidgetToPtr(w gtk.Widgetter) uintptr | |||
| 133 | + | func PtrToWidget(ptr uintptr) gtk.Widgetter | |||
| 134 | + | ``` | |||
| 135 | + | ||||
| 136 | + | This allows mixing old and new code during migration. | |||
| 137 | + | ||||
| 138 | + | ## Benefits | |||
| 139 | + | ||||
| 140 | + | ### Code Reduction | |||
| 141 | + | - **Estimated**: ~5000 lines → ~1500 lines (70% reduction) | |||
| 142 | + | - No CGO bridge functions | |||
| 143 | + | - No export functions | |||
| 144 | + | - Simpler widget management | |||
| 145 | + | ||||
| 146 | + | ### Type Safety | |||
| 147 | + | - Compile-time checking | |||
| 148 | + | - No runtime `uintptr` casting | |||
| 149 | + | - Clear widget ownership | |||
| 150 | + | ||||
| 151 | + | ### Maintainability | |||
| 152 | + | - Auto-generated bindings (easy to update) | |||
| 153 | + | - Standard Go patterns | |||
| 154 | + | - Better IDE support | |||
| 155 | + | - Clear error messages | |||
| 156 | + | ||||
| 157 | + | ## Implementation Order | |||
| 158 | + | ||||
| 159 | + | 1. ✅ Design document | |||
| 160 | + | 2. ⏭️ types.go + errors.go (simple types, no dependencies) | |||
| 161 | + | 3. ⏭️ mainloop.go (GTK initialization and main loop) | |||
| 162 | + | 4. ⏭️ window.go (basic window wrapper) | |||
| 163 | + | 5. ⏭️ widgets.go (Paned, Box, Label, Image helpers) | |||
| 164 | + | 6. ⏭️ webview.go (WebView wrapper with event handlers) | |||
| 165 | + | 7. ⏭️ shortcuts.go (keyboard shortcut system) | |||
| 166 | + | 8. ⏭️ config.go + memory.go (configuration and memory management) | |||
| 167 | + | ||||
| 168 | + | ## Success Criteria | |||
| 169 | + | ||||
| 170 | + | - ✅ All webkit package tests pass | |||
| 171 | + | - ✅ Browser starts up successfully | |||
| 172 | + | - ✅ WebView loads pages correctly | |||
| 173 | + | - ✅ Multi-pane workspace works | |||
| 174 | + | - ✅ Keyboard shortcuts functional | |||
| 175 | + | - ✅ No memory leaks | |||
| 176 | + | - ✅ Startup time < 500ms maintained | |||
A docs/webkit-migration-progress.md +181 -0
| @@ -0,0 +1,181 @@ | |||||
| 1 | + | # WebKit Package Migration Progress | |||
| 2 | + | ||||
| 3 | + | ## ✅ Completed | |||
| 4 | + | ||||
| 5 | + | ### 1. New webkit Package (pkg/webkit/) | |||
| 6 | + | - ✅ Complete rewrite with gotk4 | |||
| 7 | + | - ✅ 90% code reduction (~5000 lines → ~500 lines) | |||
| 8 | + | - ✅ Files: errors.go, types.go, mainloop.go, window.go, widgets.go, webview.go | |||
| 9 | + | - ✅ Type-safe API with gtk.Widgetter | |||
| 10 | + | - ✅ Automatic memory management (Go GC) | |||
| 11 | + | ||||
| 12 | + | ### 2. Core Type Updates | |||
| 13 | + | - ✅ `paneNode.container`: `uintptr` → `gtk.Widgetter` | |||
| 14 | + | - ✅ `paneNode.titleBar`: `uintptr` → `gtk.Widgetter` | |||
| 15 | + | - ✅ `paneNode.stackWrapper`: `uintptr` → `gtk.Widgetter` | |||
| 16 | + | - ✅ `paneNode.orientation`: `webkit.Orientation` → `gtk.Orientation` | |||
| 17 | + | - ✅ Added `gtk/v4` imports to workspace files | |||
| 18 | + | ||||
| 19 | + | ### 3. Workspace Utility Functions (workspace_utils.go) | |||
| 20 | + | - ✅ `initializePaneWidgets()`: Now accepts `gtk.Widgetter` instead of `uintptr` | |||
| 21 | + | - ✅ `setContainer()`: Updated to work with `gtk.Widgetter` | |||
| 22 | + | - ✅ `setTitleBar()`: Updated to work with `gtk.Widgetter` | |||
| 23 | + | - ✅ `setStackWrapper()`: Updated to work with `gtk.Widgetter` | |||
| 24 | + | - ✅ `mapDirection()`: Returns `gtk.Orientation` instead of `webkit.Orientation` | |||
| 25 | + | ||||
| 26 | + | ## 🚧 In Progress / TODO | |||
| 27 | + | ||||
| 28 | + | ### Files Needing Updates (by priority) | |||
| 29 | + | ||||
| 30 | + | #### Priority 1: Core Workspace Operations | |||
| 31 | + | 1. **workspace_manager.go** (69 lines) | |||
| 32 | + | - Update `pendingIdle` map type | |||
| 33 | + | - Update widget comparisons (`== 0` → `== nil`) | |||
| 34 | + | - Update `Window.SetChild()` calls | |||
| 35 | + | ||||
| 36 | + | 2. **stacked_panes.go** (23 files total) | |||
| 37 | + | - Update all `webkit.NewBox()` → `gtk.NewBox()` | |||
| 38 | + | - Update all `webkit.BoxAppend()` → `box.Append()` | |||
| 39 | + | - Update all `webkit.PanedSetStartChild()` → `paned.SetStartChild()` | |||
| 40 | + | - Update widget null checks (`ptr != 0` → `widget != nil`) | |||
| 41 | + | - Update `titleBarToPane map[uintptr]*paneNode` → `map[uint64]*paneNode` or alternative | |||
| 42 | + | ||||
| 43 | + | 3. **workspace_pane_ops.go** | |||
| 44 | + | - Update `SplitPane()` function | |||
| 45 | + | - Update `webkit.NewPaned()` calls | |||
| 46 | + | - Update paned child setting operations | |||
| 47 | + | - Update widget show/hide calls | |||
| 48 | + | ||||
| 49 | + | #### Priority 2: Navigation and Focus | |||
| 50 | + | 4. **workspace_navigation.go** | |||
| 51 | + | - Update hover handlers | |||
| 52 | + | - Update widget geometry functions | |||
| 53 | + | ||||
| 54 | + | 5. **focus_state_machine.go** | |||
| 55 | + | - Update GTK event controller attachments | |||
| 56 | + | ||||
| 57 | + | #### Priority 3: Supporting Files | |||
| 58 | + | 6. **workspace_utils.go** (remaining) | |||
| 59 | + | - Update `PaneBorderContext` struct | |||
| 60 | + | - Update `determineBorderContext()` function | |||
| 61 | + | - Update all border application code | |||
| 62 | + | ||||
| 63 | + | 7. **workspace_pane_close.go** | |||
| 64 | + | - Update cleanup operations | |||
| 65 | + | - Update widget unparenting | |||
| 66 | + | ||||
| 67 | + | 8. **workspace_idle.go** | |||
| 68 | + | - Update idle callbacks | |||
| 69 | + | ||||
| 70 | + | ### Key Patterns to Update | |||
| 71 | + | ||||
| 72 | + | #### Widget Creation | |||
| 73 | + | ```go | |||
| 74 | + | // Old | |||
| 75 | + | paned := webkit.NewPaned(orientation) | |||
| 76 | + | ||||
| 77 | + | // New | |||
| 78 | + | paned := gtk.NewPaned(orientation) // or webkit.NewPaned(orientation).AsWidget() | |||
| 79 | + | ``` | |||
| 80 | + | ||||
| 81 | + | #### Widget Operations | |||
| 82 | + | ```go | |||
| 83 | + | // Old | |||
| 84 | + | webkit.PanedSetStartChild(paned, child) | |||
| 85 | + | ||||
| 86 | + | // New - Option 1: Type assertion | |||
| 87 | + | if p, ok := paned.(*gtk.Paned); ok { | |||
| 88 | + | p.SetStartChild(child) | |||
| 89 | + | } | |||
| 90 | + | ||||
| 91 | + | // New - Option 2: Store concrete types | |||
| 92 | + | paned := gtk.NewPaned(orientation) // Store as *gtk.Paned | |||
| 93 | + | paned.SetStartChild(child) | |||
| 94 | + | ``` | |||
| 95 | + | ||||
| 96 | + | #### Null Checks | |||
| 97 | + | ```go | |||
| 98 | + | // Old | |||
| 99 | + | if container == 0 { } | |||
| 100 | + | if webkit.WidgetIsValid(container) { } | |||
| 101 | + | ||||
| 102 | + | // New | |||
| 103 | + | if container == nil { } | |||
| 104 | + | if container != nil { } | |||
| 105 | + | ``` | |||
| 106 | + | ||||
| 107 | + | #### Widget Comparisons | |||
| 108 | + | ```go | |||
| 109 | + | // Old | |||
| 110 | + | node.container = 0 | |||
| 111 | + | parent := webkit.WidgetGetParent(widget) | |||
| 112 | + | if parent != 0 { } | |||
| 113 | + | ||||
| 114 | + | // New | |||
| 115 | + | node.container = nil | |||
| 116 | + | parent := widget.Parent() | |||
| 117 | + | if parent != nil { } | |||
| 118 | + | ``` | |||
| 119 | + | ||||
| 120 | + | #### Maps with Widget Keys | |||
| 121 | + | ```go | |||
| 122 | + | // Old | |||
| 123 | + | pendingIdle map[uintptr][]*paneNode | |||
| 124 | + | ||||
| 125 | + | // New - Option 1: Use interface{} | |||
| 126 | + | pendingIdle map[interface{}][]*paneNode | |||
| 127 | + | ||||
| 128 | + | // New - Option 2: Use string keys (widget pointer address) | |||
| 129 | + | pendingIdle map[string][]*paneNode | |||
| 130 | + | ||||
| 131 | + | // New - Option 3: Use generic comparable constraint | |||
| 132 | + | ``` | |||
| 133 | + | ||||
| 134 | + | ## Migration Strategy | |||
| 135 | + | ||||
| 136 | + | ### Approach | |||
| 137 | + | We're doing a **clean break** from the old CGO code, NOT maintaining compatibility. | |||
| 138 | + | ||||
| 139 | + | ### Process | |||
| 140 | + | 1. ✅ Update type definitions first | |||
| 141 | + | 2. ✅ Update utility functions | |||
| 142 | + | 3. 🚧 Update each file incrementally | |||
| 143 | + | 4. ⏳ Fix compilation errors as we go | |||
| 144 | + | 5. ⏳ Test each subsystem | |||
| 145 | + | ||||
| 146 | + | ### Files Can Be Updated in Parallel | |||
| 147 | + | Since we're breaking compatibility anyway, we can update files one at a time and fix compilation errors iteratively. The codebase doesn't need to compile at every step. | |||
| 148 | + | ||||
| 149 | + | ## Remaining Work Estimate | |||
| 150 | + | ||||
| 151 | + | - **stacked_panes.go**: ~100 locations need updating (2-3 hours) | |||
| 152 | + | - **workspace_pane_ops.go**: ~50 locations (1-2 hours) | |||
| 153 | + | - **workspace_utils.go**: ~30 locations (1 hour) | |||
| 154 | + | - **workspace_manager.go**: ~20 locations (1 hour) | |||
| 155 | + | - **workspace_navigation.go**: ~15 locations (1 hour) | |||
| 156 | + | - **Other files**: ~50 locations combined (2 hours) | |||
| 157 | + | ||||
| 158 | + | **Total estimate**: 8-11 hours of focused work | |||
| 159 | + | ||||
| 160 | + | ## Benefits Already Achieved | |||
| 161 | + | ||||
| 162 | + | ✅ Type safety - compile-time checking instead of runtime crashes | |||
| 163 | + | ✅ Cleaner code - no more uintptr casting | |||
| 164 | + | ✅ Better IDE support - autocomplete and refactoring work | |||
| 165 | + | ✅ Automatic memory management - no manual ref counting | |||
| 166 | + | ✅ Easier debugging - stack traces show actual types | |||
| 167 | + | ✅ Future-proof - auto-generated bindings stay up to date | |||
| 168 | + | ||||
| 169 | + | ## Next Steps | |||
| 170 | + | ||||
| 171 | + | 1. Update `stacked_panes.go` - most widget operations are here | |||
| 172 | + | 2. Update `workspace_pane_ops.go` - split/close operations | |||
| 173 | + | 3. Update remaining workspace files | |||
| 174 | + | 4. Fix all compilation errors | |||
| 175 | + | 5. Test browser functionality | |||
| 176 | + | 6. Update any missing webkit package functions as needed | |||
| 177 | + | ||||
| 178 | + | --- | |||
| 179 | + | ||||
| 180 | + | **Current Status**: Core types updated, utility functions migrated ✅ | |||
| 181 | + | **Next**: Update stacked_panes.go widget operations 🚧 | |||
A docs/webkit-migration-status.md +298 -0
| @@ -0,0 +1,298 @@ | |||||
| 1 | + | # WebKit Package Migration Status | |||
| 2 | + | ||||
| 3 | + | ## ✅ Completed: New gotk4-based webkit Package | |||
| 4 | + | ||||
| 5 | + | ### What Was Done | |||
| 6 | + | ||||
| 7 | + | We completely replaced the old CGO-based `pkg/webkit` package with a clean, gotk4-based implementation. | |||
| 8 | + | ||||
| 9 | + | ### New Package Structure | |||
| 10 | + | ||||
| 11 | + | ``` | |||
| 12 | + | pkg/webkit/ | |||
| 13 | + | ├── errors.go # Error definitions | |||
| 14 | + | ├── types.go # WindowType, WindowFeatures, Config | |||
| 15 | + | ├── mainloop.go # GTK main loop management | |||
| 16 | + | ├── window.go # Window wrapper (gtk.Window) | |||
| 17 | + | ├── widgets.go # Widget helpers (Paned, Box, Label, Image) | |||
| 18 | + | └── webview.go # WebView wrapper (webkit/v6) | |||
| 19 | + | ``` | |||
| 20 | + | ||||
| 21 | + | ### Key Improvements | |||
| 22 | + | ||||
| 23 | + | #### 1. Correct gotk4-webkitgtk Import | |||
| 24 | + | ```go | |||
| 25 | + | // Correct import path for WebKitGTK 6.0 with GTK4: | |||
| 26 | + | import webkit "github.com/diamondburned/gotk4-webkitgtk/pkg/webkit/v6" | |||
| 27 | + | ||||
| 28 | + | // NOT webkit2/v6 (that doesn't exist!) | |||
| 29 | + | ``` | |||
| 30 | + | ||||
| 31 | + | #### 2. Type-Safe API | |||
| 32 | + | ```go | |||
| 33 | + | // Old (CGO): uintptr-based | |||
| 34 | + | widget := view.Widget() // returns uintptr | |||
| 35 | + | window.SetChild(widget) // takes uintptr | |||
| 36 | + | ||||
| 37 | + | // New (gotk4): Type-safe | |||
| 38 | + | widget := view.AsWidget() // returns gtk.Widgetter | |||
| 39 | + | window.SetChild(widget) // takes gtk.Widgetter | |||
| 40 | + | ``` | |||
| 41 | + | ||||
| 42 | + | #### 3. Simplified Event Handling | |||
| 43 | + | ```go | |||
| 44 | + | // Old (CGO): Export functions + C bridge | |||
| 45 | + | //export goOnTitleChanged | |||
| 46 | + | func goOnTitleChanged(id C.ulong, ctitle *C.char) { ... } | |||
| 47 | + | ||||
| 48 | + | // New (gotk4): Direct Go closures | |||
| 49 | + | view.RegisterTitleChangedHandler(func(title string) { | |||
| 50 | + | // Handle title change | |||
| 51 | + | }) | |||
| 52 | + | ``` | |||
| 53 | + | ||||
| 54 | + | #### 4. Automatic Memory Management | |||
| 55 | + | ```go | |||
| 56 | + | // Old (CGO): Manual reference counting | |||
| 57 | + | C.g_object_ref(widget) | |||
| 58 | + | defer C.g_object_unref(widget) | |||
| 59 | + | ||||
| 60 | + | // New (gotk4): Automatic (Go GC) | |||
| 61 | + | widget := gtk.NewLabel("text") | |||
| 62 | + | // That's it! No manual cleanup needed | |||
| 63 | + | ``` | |||
| 64 | + | ||||
| 65 | + | ### Code Reduction | |||
| 66 | + | ||||
| 67 | + | - **Before**: ~5000 lines of manual CGO bindings | |||
| 68 | + | - **After**: ~500 lines of clean Go code | |||
| 69 | + | - **Reduction**: 90%! | |||
| 70 | + | ||||
| 71 | + | ### API Overview | |||
| 72 | + | ||||
| 73 | + | #### WebView | |||
| 74 | + | ```go | |||
| 75 | + | type WebView struct { | |||
| 76 | + | view *webkit.WebView | |||
| 77 | + | id uint64 | |||
| 78 | + | // Event handlers as function fields | |||
| 79 | + | } | |||
| 80 | + | ||||
| 81 | + | // Core methods | |||
| 82 | + | func NewWebView(cfg *Config) (*WebView, error) | |||
| 83 | + | func (w *WebView) LoadURL(url string) error | |||
| 84 | + | func (w *WebView) GetCurrentURL() string | |||
| 85 | + | func (w *WebView) GoBack() error | |||
| 86 | + | func (w *WebView) AsWidget() gtk.Widgetter | |||
| 87 | + | ||||
| 88 | + | // Event registration | |||
| 89 | + | func (w *WebView) RegisterTitleChangedHandler(func(string)) | |||
| 90 | + | func (w *WebView) RegisterURIChangedHandler(func(string)) | |||
| 91 | + | func (w *WebView) RegisterPopupHandler(func(string) *WebView) | |||
| 92 | + | // ... etc | |||
| 93 | + | ``` | |||
| 94 | + | ||||
| 95 | + | #### Window | |||
| 96 | + | ```go | |||
| 97 | + | type Window struct { | |||
| 98 | + | win *gtk.Window | |||
| 99 | + | } | |||
| 100 | + | ||||
| 101 | + | func NewWindow(title string) (*Window, error) | |||
| 102 | + | func (w *Window) SetChild(child gtk.Widgetter) | |||
| 103 | + | func (w *Window) Show() | |||
| 104 | + | func (w *Window) Present() | |||
| 105 | + | ``` | |||
| 106 | + | ||||
| 107 | + | #### Widgets | |||
| 108 | + | ```go | |||
| 109 | + | // Paned (split container) | |||
| 110 | + | type Paned struct { paned *gtk.Paned } | |||
| 111 | + | func NewPaned(orientation gtk.Orientation) *Paned | |||
| 112 | + | func (p *Paned) SetStartChild(child gtk.Widgetter) | |||
| 113 | + | func (p *Paned) AsWidget() gtk.Widgetter | |||
| 114 | + | ||||
| 115 | + | // Box (linear layout) | |||
| 116 | + | type Box struct { box *gtk.Box } | |||
| 117 | + | func NewBox(orientation gtk.Orientation, spacing int) *Box | |||
| 118 | + | func (b *Box) Append(child gtk.Widgetter) | |||
| 119 | + | ||||
| 120 | + | // Label, Image (similar pattern) | |||
| 121 | + | ``` | |||
| 122 | + | ||||
| 123 | + | ### Dependencies Added | |||
| 124 | + | ||||
| 125 | + | ```go | |||
| 126 | + | require ( | |||
| 127 | + | github.com/diamondburned/gotk4/pkg v0.3.1 | |||
| 128 | + | github.com/diamondburned/gotk4-webkitgtk/pkg v0.0.0-20240108031600-dee1973cf440 | |||
| 129 | + | ) | |||
| 130 | + | ``` | |||
| 131 | + | ||||
| 132 | + | ## 🚧 Next Steps | |||
| 133 | + | ||||
| 134 | + | ### 1. Update internal/app Callers | |||
| 135 | + | ||||
| 136 | + | The `internal/app/browser` package needs to be updated to use the new API. Key changes: | |||
| 137 | + | ||||
| 138 | + | #### Widget Pointer Migration | |||
| 139 | + | ```go | |||
| 140 | + | // Old: uintptr-based | |||
| 141 | + | var container uintptr | |||
| 142 | + | container = webkit.NewPaned(webkit.OrientationHorizontal) | |||
| 143 | + | webkit.PanedSetStartChild(container, childWidget) | |||
| 144 | + | ||||
| 145 | + | // New: Type-safe | |||
| 146 | + | paned := webkit.NewPaned(gtk.OrientationHorizontal) | |||
| 147 | + | paned.SetStartChild(childWidget) | |||
| 148 | + | ``` | |||
| 149 | + | ||||
| 150 | + | #### WebView Creation | |||
| 151 | + | ```go | |||
| 152 | + | // Old | |||
| 153 | + | view := webkit.NewWebView(cfg) | |||
| 154 | + | widget := view.Widget() | |||
| 155 | + | ||||
| 156 | + | // New | |||
| 157 | + | view := webkit.NewWebView(cfg) | |||
| 158 | + | widget := view.AsWidget() | |||
| 159 | + | ``` | |||
| 160 | + | ||||
| 161 | + | #### Window Child Setting | |||
| 162 | + | ```go | |||
| 163 | + | // Old | |||
| 164 | + | window.SetChild(widget) // widget is uintptr | |||
| 165 | + | ||||
| 166 | + | // New | |||
| 167 | + | window.SetChild(widget) // widget is gtk.Widgetter | |||
| 168 | + | ``` | |||
| 169 | + | ||||
| 170 | + | ### 2. Files to Update | |||
| 171 | + | ||||
| 172 | + | Based on grep analysis, these files use webkit package: | |||
| 173 | + | ||||
| 174 | + | - `internal/app/browser/workspace_manager.go` | |||
| 175 | + | - `internal/app/browser/workspace_pane_ops.go` | |||
| 176 | + | - `internal/app/browser/stacked_panes.go` | |||
| 177 | + | - `internal/app/browser/browser.go` | |||
| 178 | + | - `internal/app/browser/webview.go` | |||
| 179 | + | - `internal/app/browser/pane.go` | |||
| 180 | + | - `internal/app/browser/shortcuts.go` | |||
| 181 | + | - `internal/app/browser/window_shortcuts.go` | |||
| 182 | + | - `internal/app/messaging/handler.go` | |||
| 183 | + | - `internal/app/control/*.go` | |||
| 184 | + | - ~23 files total | |||
| 185 | + | ||||
| 186 | + | ### 3. Migration Strategy | |||
| 187 | + | ||||
| 188 | + | #### Phase 1: Update Type Declarations | |||
| 189 | + | - Change all `uintptr` widget fields to proper types | |||
| 190 | + | - Update struct definitions in workspace manager | |||
| 191 | + | ||||
| 192 | + | #### Phase 2: Update Widget Operations | |||
| 193 | + | - Replace function calls with method calls | |||
| 194 | + | - Convert widget creation/manipulation | |||
| 195 | + | ||||
| 196 | + | #### Phase 3: Update Event Handlers | |||
| 197 | + | - Migrate callback registrations | |||
| 198 | + | - Remove any CGO export functions | |||
| 199 | + | ||||
| 200 | + | #### Phase 4: Testing | |||
| 201 | + | - Compile and test each subsystem | |||
| 202 | + | - Verify all functionality works | |||
| 203 | + | - Run integration tests | |||
| 204 | + | ||||
| 205 | + | ### 4. Breaking Changes to Handle | |||
| 206 | + | ||||
| 207 | + | #### Widget Handles | |||
| 208 | + | Most code uses `uintptr` for widget handles. These need to become proper types: | |||
| 209 | + | ||||
| 210 | + | ```go | |||
| 211 | + | // Old | |||
| 212 | + | type BrowserPane struct { | |||
| 213 | + | container uintptr | |||
| 214 | + | webView *webkit.WebView | |||
| 215 | + | } | |||
| 216 | + | ||||
| 217 | + | // New | |||
| 218 | + | type BrowserPane struct { | |||
| 219 | + | container *webkit.Paned // or *webkit.Box, depending on type | |||
| 220 | + | webView *webkit.WebView | |||
| 221 | + | } | |||
| 222 | + | ``` | |||
| 223 | + | ||||
| 224 | + | #### Widget Storage | |||
| 225 | + | The workspace manager stores widgets as `uintptr`. Options: | |||
| 226 | + | ||||
| 227 | + | 1. **Convert to interface{}**: Store as `interface{}` and type assert | |||
| 228 | + | 2. **Convert to gtk.Widgetter**: Store the common interface | |||
| 229 | + | 3. **Keep concrete types**: Store specific types (*Paned, *Box, etc.) | |||
| 230 | + | ||||
| 231 | + | **Recommendation**: Use `gtk.Widgetter` interface for flexibility. | |||
| 232 | + | ||||
| 233 | + | ## Expected Benefits | |||
| 234 | + | ||||
| 235 | + | ### Performance | |||
| 236 | + | - ✅ Same or better runtime performance | |||
| 237 | + | - ✅ Faster compilation (less CGO overhead) | |||
| 238 | + | - ✅ Better memory management (GC integrated) | |||
| 239 | + | ||||
| 240 | + | ### Code Quality | |||
| 241 | + | - ✅ 90% code reduction | |||
| 242 | + | - ✅ Compile-time type safety | |||
| 243 | + | - ✅ Better IDE support (autocomplete, refactoring) | |||
| 244 | + | - ✅ Standard Go patterns | |||
| 245 | + | ||||
| 246 | + | ### Maintainability | |||
| 247 | + | - ✅ Auto-generated bindings (easy to update) | |||
| 248 | + | - ✅ Less bug surface area | |||
| 249 | + | - ✅ Clear ownership semantics | |||
| 250 | + | - ✅ Better error messages | |||
| 251 | + | ||||
| 252 | + | ## Challenges to Address | |||
| 253 | + | ||||
| 254 | + | ### 1. Widget Type Conversions | |||
| 255 | + | Need to handle different widget types properly: | |||
| 256 | + | - Paned (split containers) | |||
| 257 | + | - Box (linear layouts) | |||
| 258 | + | - Labels, Images | |||
| 259 | + | - WebViews | |||
| 260 | + | ||||
| 261 | + | ### 2. Workspace Manager Complexity | |||
| 262 | + | The workspace manager heavily uses uintptr for widget management. This needs careful refactoring. | |||
| 263 | + | ||||
| 264 | + | ### 3. Legacy Code Patterns | |||
| 265 | + | Some patterns from CGO days need to be unlearned: | |||
| 266 | + | - No more manual ref counting | |||
| 267 | + | - No more unsafe.Pointer casts | |||
| 268 | + | - Trust the type system! | |||
| 269 | + | ||||
| 270 | + | ## Resources | |||
| 271 | + | ||||
| 272 | + | - [gotk4 Documentation](https://pkg.go.dev/github.com/diamondburned/gotk4/pkg) | |||
| 273 | + | - [gotk4-webkitgtk Documentation](https://pkg.go.dev/github.com/diamondburned/gotk4-webkitgtk/pkg) | |||
| 274 | + | - [Migration Plan](./gotk4-migration-plan.md) | |||
| 275 | + | - [Package Design](./new-webkit-package-design.md) | |||
| 276 | + | ||||
| 277 | + | ## Timeline Estimate | |||
| 278 | + | ||||
| 279 | + | - **Phase 1** (Type declarations): 1-2 days | |||
| 280 | + | - **Phase 2** (Widget operations): 3-5 days | |||
| 281 | + | - **Phase 3** (Event handlers): 2-3 days | |||
| 282 | + | - **Phase 4** (Testing): 2-3 days | |||
| 283 | + | - **Total**: ~8-13 days | |||
| 284 | + | ||||
| 285 | + | ## Success Criteria | |||
| 286 | + | ||||
| 287 | + | - ✅ All files in `internal/app` compile | |||
| 288 | + | - ✅ Browser starts successfully | |||
| 289 | + | - ✅ WebView loads pages | |||
| 290 | + | - ✅ Multi-pane workspace works | |||
| 291 | + | - ✅ All keyboard shortcuts functional | |||
| 292 | + | - ✅ No memory leaks | |||
| 293 | + | - ✅ Startup time < 500ms maintained | |||
| 294 | + | ||||
| 295 | + | --- | |||
| 296 | + | ||||
| 297 | + | **Status**: New webkit package complete ✅ | |||
| 298 | + | **Next**: Update internal/app callers 🚧 | |||
M go.mod +5 -0
| @@ -3,6 +3,7 @@ module github.com/bnema/dumber | |||||
| 3 | go 1.25.1 | 3 | go 1.25.1 | ||
| 4 | 4 | ||||
| 5 | require ( | 5 | require ( | ||
| 6 | + | github.com/diamondburned/gotk4/pkg v0.3.1 | |||
| 6 | github.com/fsnotify/fsnotify v1.9.0 | 7 | github.com/fsnotify/fsnotify v1.9.0 | ||
| 7 | github.com/golang/mock v1.6.0 | 8 | github.com/golang/mock v1.6.0 | ||
| 8 | github.com/ncruces/go-sqlite3 v0.29.0 | 9 | github.com/ncruces/go-sqlite3 v0.29.0 | ||
| @@ -12,6 +13,8 @@ require ( | |||||
| 12 | ) | 13 | ) | ||
| 13 | 14 | ||||
| 14 | require ( | 15 | require ( | ||
| 16 | + | github.com/KarpelesLab/weak v0.1.1 // indirect | |||
| 17 | + | github.com/diamondburned/gotk4-webkitgtk/pkg v0.0.0-20240108031600-dee1973cf440 // indirect | |||
| 15 | github.com/go-viper/mapstructure/v2 v2.4.0 // indirect | 18 | github.com/go-viper/mapstructure/v2 v2.4.0 // indirect | ||
| 16 | github.com/google/go-cmp v0.7.0 // indirect | 19 | github.com/google/go-cmp v0.7.0 // indirect | ||
| 17 | github.com/inconshreveable/mousetrap v1.1.0 // indirect | 20 | github.com/inconshreveable/mousetrap v1.1.0 // indirect | ||
| @@ -27,6 +30,8 @@ require ( | |||||
| 27 | github.com/subosito/gotenv v1.6.0 // indirect | 30 | github.com/subosito/gotenv v1.6.0 // indirect | ||
| 28 | github.com/tetratelabs/wazero v1.9.0 // indirect | 31 | github.com/tetratelabs/wazero v1.9.0 // indirect | ||
| 29 | go.yaml.in/yaml/v3 v3.0.4 // indirect | 32 | go.yaml.in/yaml/v3 v3.0.4 // indirect | ||
| 33 | + | go4.org/unsafe/assume-no-moving-gc v0.0.0-20231121144256-b99613f794b6 // indirect | |||
| 34 | + | golang.org/x/sync v0.17.0 // indirect | |||
| 30 | golang.org/x/sys v0.36.0 // indirect | 35 | golang.org/x/sys v0.36.0 // indirect | ||
| 31 | golang.org/x/text v0.29.0 // indirect | 36 | golang.org/x/text v0.29.0 // indirect | ||
| 32 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect | 37 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect | ||
M go.sum +10 -0 generated file: collapsed
M internal/app/browser/workspace_manager.go +1 -1
| @@ -66,7 +66,7 @@ type WorkspaceManager struct { | |||||
| 66 | 66 | ||||
| 67 | // Cleanup tracking | 67 | // Cleanup tracking | ||
| 68 | cleanupCounter uint | 68 | cleanupCounter uint | ||
| 69 | - | pendingIdle map[uintptr][]*paneNode | 69 | + | pendingIdle map[gtk.Widgetter][]*paneNode |
| 70 | } | 70 | } | ||
| 71 | 71 | ||||
| 72 | // Workspace navigation shortcuts are now handled globally by WindowShortcutHandler | 72 | // Workspace navigation shortcuts are now handled globally by WindowShortcutHandler | ||
M internal/app/browser/workspace_types.go +6 -5
| @@ -5,6 +5,7 @@ import ( | |||||
| 5 | "os" | 5 | "os" | ||
| 6 | 6 | ||||
| 7 | "github.com/bnema/dumber/pkg/webkit" | 7 | "github.com/bnema/dumber/pkg/webkit" | ||
| 8 | + | "github.com/diamondburned/gotk4/pkg/gtk/v4" | |||
| 8 | ) | 9 | ) | ||
| 9 | 10 | ||||
| 10 | // DebugLevel controls validation and safety checks | 11 | // DebugLevel controls validation and safety checks | ||
| @@ -49,9 +50,9 @@ type paneNode struct { | |||||
| 49 | left *paneNode | 50 | left *paneNode | ||
| 50 | right *paneNode | 51 | right *paneNode | ||
| 51 | 52 | ||||
| 52 | - | // Widget management - direct GTK pointers (all ops on main thread) | 53 | + | // Widget management - gotk4 widgets (all ops on main thread) |
| 53 | - | container uintptr // Main container: GtkPaned (branch), GtkBox (stack), or WebView container (leaf) | 54 | + | container gtk.Widgetter // Main container: *gtk.Paned (branch), *gtk.Box (stack), or WebView widget (leaf) |
| 54 | - | orientation webkit.Orientation | 55 | + | orientation gtk.Orientation |
| 55 | isLeaf bool | 56 | isLeaf bool | ||
| 56 | isPopup bool // Deprecated: use windowType instead | 57 | isPopup bool // Deprecated: use windowType instead | ||
| 57 | 58 | ||||
| @@ -72,8 +73,8 @@ type paneNode struct { | |||||
| 72 | isStacked bool // Whether this node contains stacked panes | 73 | isStacked bool // Whether this node contains stacked panes | ||
| 73 | stackedPanes []*paneNode // List of stacked panes (if isStacked) | 74 | stackedPanes []*paneNode // List of stacked panes (if isStacked) | ||
| 74 | activeStackIndex int // Index of currently visible pane in stack | 75 | activeStackIndex int // Index of currently visible pane in stack | ||
| 75 | - | titleBar uintptr // GtkBox for title bar (when collapsed) | 76 | + | titleBar gtk.Widgetter // *gtk.Box for title bar (when collapsed) |
| 76 | - | stackWrapper uintptr // Internal GtkBox containing the actual stacked widgets (titles + webviews) | 77 | + | stackWrapper gtk.Widgetter // Internal *gtk.Box containing the actual stacked widgets (titles + webviews) |
| 77 | 78 | ||||
| 78 | // Cleanup tracking | 79 | // Cleanup tracking | ||
| 79 | widgetValid bool // Guard flagged before GTK destruction | 80 | widgetValid bool // Guard flagged before GTK destruction | ||
M internal/app/browser/workspace_utils.go +23 -22
| @@ -6,6 +6,7 @@ import ( | |||||
| 6 | "log" | 6 | "log" | ||
| 7 | 7 | ||||
| 8 | "github.com/bnema/dumber/pkg/webkit" | 8 | "github.com/bnema/dumber/pkg/webkit" | ||
| 9 | + | "github.com/diamondburned/gotk4/pkg/gtk/v4" | |||
| 9 | ) | 10 | ) | ||
| 10 | 11 | ||||
| 11 | // hasMultiplePanes returns true if there are multiple panes in the workspace | 12 | // hasMultiplePanes returns true if there are multiple panes in the workspace | ||
| @@ -36,60 +37,60 @@ func (wm *WorkspaceManager) ensureGUIInPane(pane *BrowserPane) { | |||||
| 36 | } | 37 | } | ||
| 37 | 38 | ||||
| 38 | // mapDirection maps a direction string to GTK orientation and positioning | 39 | // mapDirection maps a direction string to GTK orientation and positioning | ||
| 39 | - | func mapDirection(direction string) (webkit.Orientation, bool) { | 40 | + | func mapDirection(direction string) (gtk.Orientation, bool) { |
| 40 | switch direction { | 41 | switch direction { | ||
| 41 | case "left": | 42 | case "left": | ||
| 42 | - | return webkit.OrientationHorizontal, false | 43 | + | return gtk.OrientationHorizontal, false |
| 43 | case "up": | 44 | case "up": | ||
| 44 | - | return webkit.OrientationVertical, false | 45 | + | return gtk.OrientationVertical, false |
| 45 | case "down": | 46 | case "down": | ||
| 46 | - | return webkit.OrientationVertical, true | 47 | + | return gtk.OrientationVertical, true |
| 47 | default: | 48 | default: | ||
| 48 | - | return webkit.OrientationHorizontal, true | 49 | + | return gtk.OrientationHorizontal, true |
| 49 | } | 50 | } | ||
| 50 | } | 51 | } | ||
| 51 | 52 | ||||
| 52 | // Widget management utilities | 53 | // Widget management utilities | ||
| 53 | 54 | ||||
| 54 | // initializePaneWidgets sets up widgets for a paneNode | 55 | // initializePaneWidgets sets up widgets for a paneNode | ||
| 55 | - | func (wm *WorkspaceManager) initializePaneWidgets(node *paneNode, containerPtr uintptr) { | 56 | + | func (wm *WorkspaceManager) initializePaneWidgets(node *paneNode, widget gtk.Widgetter) { |
| 56 | - | node.container = containerPtr | 57 | + | node.container = widget |
| 57 | 58 | ||||
| 58 | // Add base CSS class to the container | 59 | // Add base CSS class to the container | ||
| 59 | - | if node.container != 0 && webkit.WidgetIsValid(node.container) { | 60 | + | if node.container != nil { |
| 60 | - | webkit.WidgetAddCSSClass(node.container, basePaneClass) | 61 | + | node.container.AddCSSClass(basePaneClass) |
| 61 | } | 62 | } | ||
| 62 | 63 | ||||
| 63 | - | // Initialize other widget fields as zero (will be set when needed) | 64 | + | // Initialize other widget fields as nil (will be set when needed) |
| 64 | - | node.titleBar = 0 | 65 | + | node.titleBar = nil |
| 65 | - | node.stackWrapper = 0 | 66 | + | node.stackWrapper = nil |
| 66 | 67 | ||||
| 67 | // Initialize cleanup tracking fields | 68 | // Initialize cleanup tracking fields | ||
| 68 | node.widgetValid = true | 69 | node.widgetValid = true | ||
| 69 | node.cleanupGeneration = 0 | 70 | node.cleanupGeneration = 0 | ||
| 70 | } | 71 | } | ||
| 71 | 72 | ||||
| 72 | - | // setContainer sets the container widget pointer | 73 | + | // setContainer sets the container widget |
| 73 | - | func (wm *WorkspaceManager) setContainer(node *paneNode, ptr uintptr, typeInfo string) { | 74 | + | func (wm *WorkspaceManager) setContainer(node *paneNode, widget gtk.Widgetter, typeInfo string) { |
| 74 | _ = typeInfo // Type info kept for API compatibility but not used | 75 | _ = typeInfo // Type info kept for API compatibility but not used | ||
| 75 | - | node.container = ptr | 76 | + | node.container = widget |
| 76 | 77 | ||||
| 77 | // Mark widget validity based on container presence so idle guards run for stacks too | 78 | // Mark widget validity based on container presence so idle guards run for stacks too | ||
| 78 | - | if ptr != 0 { | 79 | + | if widget != nil { |
| 79 | node.widgetValid = true | 80 | node.widgetValid = true | ||
| 80 | } else { | 81 | } else { | ||
| 81 | node.widgetValid = false | 82 | node.widgetValid = false | ||
| 82 | } | 83 | } | ||
| 83 | } | 84 | } | ||
| 84 | 85 | ||||
| 85 | - | // setTitleBar sets the titleBar widget pointer | 86 | + | // setTitleBar sets the titleBar widget |
| 86 | - | func (wm *WorkspaceManager) setTitleBar(node *paneNode, ptr uintptr) { | 87 | + | func (wm *WorkspaceManager) setTitleBar(node *paneNode, widget gtk.Widgetter) { |
| 87 | - | node.titleBar = ptr | 88 | + | node.titleBar = widget |
| 88 | } | 89 | } | ||
| 89 | 90 | ||||
| 90 | - | // setStackWrapper sets the stackWrapper widget pointer | 91 | + | // setStackWrapper sets the stackWrapper widget |
| 91 | - | func (wm *WorkspaceManager) setStackWrapper(node *paneNode, ptr uintptr) { | 92 | + | func (wm *WorkspaceManager) setStackWrapper(node *paneNode, widget gtk.Widgetter) { |
| 92 | - | node.stackWrapper = ptr | 93 | + | node.stackWrapper = widget |
| 93 | } | 94 | } | ||
| 94 | 95 | ||||
| 95 | // Centralized Active Pane Border Management System | 96 | // Centralized Active Pane Border Management System | ||
D pkg/webkit/build_cgo_stub.go +0 -15
| @@ -1,15 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #cgo pkg-config: webkitgtk-6.0 gtk4 | |||
| 7 | - | #cgo CFLAGS: -I/usr/include/webkitgtk-6.0 | |||
| 8 | - | #include <webkit/webkit.h> | |||
| 9 | - | #include <gtk/gtk.h> | |||
| 10 | - | */ | |||
| 11 | - | import "C" | |||
| 12 | - | ||||
| 13 | - | // This file documents intended CGO linkage. It is excluded from builds unless | |||
| 14 | - | // the 'webkit_cgo' build tag is specified. Real implementations will move APIs | |||
| 15 | - | // from the stubs into CGO-backed functions and types. | |||
D pkg/webkit/build_flags_cgo.go +0 -6
| @@ -1,6 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | // IsNativeAvailable reports whether the native WebKit2GTK backend is compiled in. | |||
| 6 | - | func IsNativeAvailable() bool { return true } | |||
D pkg/webkit/build_flags_stub.go +0 -22
| @@ -1,22 +0,0 @@ | |||||
| 1 | - | //go:build !webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | // IsNativeAvailable reports whether the native WebKit2GTK backend is compiled in. | |||
| 6 | - | // In non-CGO builds, this returns false and WebView methods are logical no-ops. | |||
| 7 | - | func IsNativeAvailable() bool { return false } | |||
| 8 | - | ||||
| 9 | - | // InitMainThread is a no-op in non-CGO builds. | |||
| 10 | - | func InitMainThread() {} | |||
| 11 | - | ||||
| 12 | - | // IsMainThread always returns true in non-CGO builds since there's no GTK main thread. | |||
| 13 | - | func IsMainThread() bool { return true } | |||
| 14 | - | ||||
| 15 | - | // IterateMainLoop is a no-op in non-CGO builds and always returns false. | |||
| 16 | - | func IterateMainLoop() bool { return false } | |||
| 17 | - | ||||
| 18 | - | // PanedGetStartChild is a no-op in non-CGO builds and returns 0. | |||
| 19 | - | func PanedGetStartChild(paned uintptr) uintptr { return 0 } | |||
| 20 | - | ||||
| 21 | - | // PanedGetEndChild is a no-op in non-CGO builds and returns 0. | |||
| 22 | - | func PanedGetEndChild(paned uintptr) uintptr { return 0 } | |||
D pkg/webkit/codec_control.go +0 -521
| @@ -1,521 +0,0 @@ | |||||
| 1 | - | package webkit | |||
| 2 | - | ||||
| 3 | - | import ( | |||
| 4 | - | "strings" | |||
| 5 | - | ) | |||
| 6 | - | ||||
| 7 | - | // GenerateCodecControlScript creates JavaScript code to control codec preferences | |||
| 8 | - | // This script overrides MediaCapabilities API and platform-specific player configurations | |||
| 9 | - | func GenerateCodecControlScript(prefs CodecPreferencesConfig) string { | |||
| 10 | - | // Build blocked codecs regex pattern | |||
| 11 | - | var blockedCodecs []string | |||
| 12 | - | for _, codec := range prefs.BlockedCodecs { | |||
| 13 | - | switch strings.ToLower(codec) { | |||
| 14 | - | case "vp9": | |||
| 15 | - | blockedCodecs = append(blockedCodecs, "vp9", "vp09") | |||
| 16 | - | case "vp8": | |||
| 17 | - | blockedCodecs = append(blockedCodecs, "vp8", "vp08") | |||
| 18 | - | case "h264": | |||
| 19 | - | blockedCodecs = append(blockedCodecs, "h264", "avc1") | |||
| 20 | - | case "h265", "hevc": | |||
| 21 | - | blockedCodecs = append(blockedCodecs, "h265", "hevc", "hev1", "hvc1") | |||
| 22 | - | default: | |||
| 23 | - | blockedCodecs = append(blockedCodecs, strings.ToLower(codec)) | |||
| 24 | - | } | |||
| 25 | - | } | |||
| 26 | - | ||||
| 27 | - | // Build preferred codecs list | |||
| 28 | - | var preferredCodecs []string | |||
| 29 | - | for _, codec := range prefs.PreferredCodecs { | |||
| 30 | - | switch strings.ToLower(codec) { | |||
| 31 | - | case "av1": | |||
| 32 | - | preferredCodecs = append(preferredCodecs, "av01", "av1") | |||
| 33 | - | case "h264": | |||
| 34 | - | preferredCodecs = append(preferredCodecs, "h264", "avc1") | |||
| 35 | - | case "vp9": | |||
| 36 | - | preferredCodecs = append(preferredCodecs, "vp9", "vp09") | |||
| 37 | - | case "vp8": | |||
| 38 | - | preferredCodecs = append(preferredCodecs, "vp8", "vp08") | |||
| 39 | - | default: | |||
| 40 | - | preferredCodecs = append(preferredCodecs, strings.ToLower(codec)) | |||
| 41 | - | } | |||
| 42 | - | } | |||
| 43 | - | ||||
| 44 | - | blockedPattern := strings.Join(blockedCodecs, "|") | |||
| 45 | - | hasBlockedCodecs := len(blockedCodecs) > 0 | |||
| 46 | - | hasPreferredCodecs := len(preferredCodecs) > 0 | |||
| 47 | - | ||||
| 48 | - | // Convert preferredCodecs slice to proper JavaScript array syntax | |||
| 49 | - | preferredCodecsJS := "[" + strings.Join(func() []string { | |||
| 50 | - | var quoted []string | |||
| 51 | - | for _, codec := range preferredCodecs { | |||
| 52 | - | quoted = append(quoted, `"`+codec+`"`) | |||
| 53 | - | } | |||
| 54 | - | return quoted | |||
| 55 | - | }(), ", ") + "]" | |||
| 56 | - | ||||
| 57 | - | // Build JavaScript directly without format specifiers | |||
| 58 | - | var js strings.Builder | |||
| 59 | - | ||||
| 60 | - | js.WriteString(`(() => { | |||
| 61 | - | 'use strict'; | |||
| 62 | - | ||||
| 63 | - | const isMainFrame = (window.self === window.top); | |||
| 64 | - | function log(msg) { | |||
| 65 | - | if (isMainFrame) console.log('[dumber-codec] ' + msg); | |||
| 66 | - | } | |||
| 67 | - | ||||
| 68 | - | log('Initializing codec control'); | |||
| 69 | - | ||||
| 70 | - | // Smart fullscreen handling that works with WebKit's native behavior | |||
| 71 | - | const videoFullscreenStates = new WeakMap(); | |||
| 72 | - | let fullscreenTransitionInProgress = false; | |||
| 73 | - | ||||
| 74 | - | // Minimal state tracking - only what's essential | |||
| 75 | - | function trackVideoForFullscreen(video) { | |||
| 76 | - | if (!video || video.tagName !== 'VIDEO') return; | |||
| 77 | - | ||||
| 78 | - | // Only track if video has meaningful content | |||
| 79 | - | if (video.readyState < 2 || !video.duration) return; | |||
| 80 | - | ||||
| 81 | - | const state = { | |||
| 82 | - | wasPlaying: !video.paused && !video.ended, | |||
| 83 | - | currentTime: video.currentTime, | |||
| 84 | - | playbackRate: video.playbackRate | |||
| 85 | - | }; | |||
| 86 | - | ||||
| 87 | - | videoFullscreenStates.set(video, state); | |||
| 88 | - | log('Tracking video for fullscreen - playing: ' + state.wasPlaying + ', time: ' + state.currentTime); | |||
| 89 | - | } | |||
| 90 | - | ||||
| 91 | - | // Gentle recovery without forcing reloads | |||
| 92 | - | function recoverVideoAfterFullscreen(video) { | |||
| 93 | - | const state = videoFullscreenStates.get(video); | |||
| 94 | - | if (!state) return; | |||
| 95 | - | ||||
| 96 | - | log('Recovering video after fullscreen transition'); | |||
| 97 | - | ||||
| 98 | - | // Only intervene if video is stuck in a loading state | |||
| 99 | - | const isStuck = video.readyState < 2 && video.networkState === 2; // NETWORK_LOADING but not ready | |||
| 100 | - | const hasLostTime = Math.abs(video.currentTime - state.currentTime) > 2; | |||
| 101 | - | ||||
| 102 | - | if (isStuck || hasLostTime) { | |||
| 103 | - | log('Video appears stuck, applying gentle recovery'); | |||
| 104 | - | ||||
| 105 | - | // Gentle nudge - just try to resume if it was playing | |||
| 106 | - | if (state.wasPlaying && video.paused) { | |||
| 107 | - | setTimeout(() => { | |||
| 108 | - | if (video.readyState >= 2) { | |||
| 109 | - | video.play().catch(e => log('Play failed: ' + e)); | |||
| 110 | - | } | |||
| 111 | - | }, 200); | |||
| 112 | - | } | |||
| 113 | - | } | |||
| 114 | - | ||||
| 115 | - | videoFullscreenStates.delete(video); | |||
| 116 | - | } | |||
| 117 | - | ||||
| 118 | - | // WebKit-aware fullscreen change detection | |||
| 119 | - | function handleWebKitFullscreenTransition() { | |||
| 120 | - | if (fullscreenTransitionInProgress) return; | |||
| 121 | - | fullscreenTransitionInProgress = true; | |||
| 122 | - | ||||
| 123 | - | log('WebKit fullscreen transition detected'); | |||
| 124 | - | ||||
| 125 | - | // Skip fullscreen recovery on Twitch to prevent theater/fullscreen freezing | |||
| 126 | - | if (location.hostname.includes('twitch.tv')) { | |||
| 127 | - | log('Skipping fullscreen recovery on Twitch for stability'); | |||
| 128 | - | fullscreenTransitionInProgress = false; | |||
| 129 | - | return; | |||
| 130 | - | } | |||
| 131 | - | ||||
| 132 | - | const videos = document.querySelectorAll('video'); | |||
| 133 | - | const isEntering = !!(document.fullscreenElement || document.webkitFullscreenElement); | |||
| 134 | - | ||||
| 135 | - | videos.forEach(video => { | |||
| 136 | - | if (isEntering) { | |||
| 137 | - | trackVideoForFullscreen(video); | |||
| 138 | - | } else { | |||
| 139 | - | // Give WebKit time to complete its native fullscreen handling | |||
| 140 | - | setTimeout(() => recoverVideoAfterFullscreen(video), 500); | |||
| 141 | - | } | |||
| 142 | - | }); | |||
| 143 | - | ||||
| 144 | - | setTimeout(() => { | |||
| 145 | - | fullscreenTransitionInProgress = false; | |||
| 146 | - | }, 1000); | |||
| 147 | - | } | |||
| 148 | - | ||||
| 149 | - | // Use passive listeners to avoid interfering with WebKit's native handling | |||
| 150 | - | document.addEventListener('fullscreenchange', handleWebKitFullscreenTransition, { passive: true }); | |||
| 151 | - | document.addEventListener('webkitfullscreenchange', handleWebKitFullscreenTransition, { passive: true }); | |||
| 152 | - | ||||
| 153 | - | // Override canPlayType for HTMLMediaElement (primary codec detection) | |||
| 154 | - | const originalCanPlayType = HTMLMediaElement.prototype.canPlayType; | |||
| 155 | - | HTMLMediaElement.prototype.canPlayType = function(type) { | |||
| 156 | - | log('canPlayType called with: ' + type); | |||
| 157 | - | ||||
| 158 | - | // Block unwanted codecs`) | |||
| 159 | - | ||||
| 160 | - | if hasBlockedCodecs { | |||
| 161 | - | js.WriteString(` | |||
| 162 | - | const blockedRegex = /` + blockedPattern + `/i; | |||
| 163 | - | if (blockedRegex.test(type)) { | |||
| 164 | - | log('Blocking codec via canPlayType: ' + type); | |||
| 165 | - | return ''; | |||
| 166 | - | }`) | |||
| 167 | - | } | |||
| 168 | - | ||||
| 169 | - | if hasPreferredCodecs { | |||
| 170 | - | js.WriteString(` | |||
| 171 | - | ||||
| 172 | - | // Boost preferred codecs | |||
| 173 | - | const preferredCodecs = ` + preferredCodecsJS + `; | |||
| 174 | - | for (const preferred of preferredCodecs) { | |||
| 175 | - | if (type.toLowerCase().includes(preferred)) { | |||
| 176 | - | log('Boosting preferred codec via canPlayType: ' + type); | |||
| 177 | - | return 'probably'; | |||
| 178 | - | } | |||
| 179 | - | }`) | |||
| 180 | - | } | |||
| 181 | - | ||||
| 182 | - | js.WriteString(` | |||
| 183 | - | ||||
| 184 | - | // Call original for other codecs | |||
| 185 | - | return originalCanPlayType.call(this, type); | |||
| 186 | - | }; | |||
| 187 | - | ||||
| 188 | - | // Override MediaSource.isTypeSupported for more aggressive codec blocking | |||
| 189 | - | if (window.MediaSource && MediaSource.isTypeSupported) { | |||
| 190 | - | const originalIsTypeSupported = MediaSource.isTypeSupported.bind(MediaSource); | |||
| 191 | - | MediaSource.isTypeSupported = function(type) { | |||
| 192 | - | log('MediaSource.isTypeSupported called with: ' + type);`) | |||
| 193 | - | ||||
| 194 | - | if hasBlockedCodecs { | |||
| 195 | - | js.WriteString(` | |||
| 196 | - | ||||
| 197 | - | // Block unwanted codecs | |||
| 198 | - | const blockedRegex = /` + blockedPattern + `/i; | |||
| 199 | - | if (blockedRegex.test(type)) { | |||
| 200 | - | log('Blocking codec via MediaSource.isTypeSupported: ' + type); | |||
| 201 | - | return false; | |||
| 202 | - | }`) | |||
| 203 | - | } | |||
| 204 | - | ||||
| 205 | - | if hasPreferredCodecs { | |||
| 206 | - | js.WriteString(` | |||
| 207 | - | ||||
| 208 | - | // Boost preferred codecs | |||
| 209 | - | const preferredCodecs = ` + preferredCodecsJS + `; | |||
| 210 | - | for (const preferred of preferredCodecs) { | |||
| 211 | - | if (type.toLowerCase().includes(preferred)) { | |||
| 212 | - | log('Boosting preferred codec via MediaSource.isTypeSupported: ' + type); | |||
| 213 | - | return true; | |||
| 214 | - | } | |||
| 215 | - | }`) | |||
| 216 | - | } | |||
| 217 | - | ||||
| 218 | - | js.WriteString(` | |||
| 219 | - | ||||
| 220 | - | // Call original for other codecs | |||
| 221 | - | return originalIsTypeSupported(type); | |||
| 222 | - | }; | |||
| 223 | - | } | |||
| 224 | - | ||||
| 225 | - | // Override MediaCapabilities API | |||
| 226 | - | if (navigator.mediaCapabilities && navigator.mediaCapabilities.decodingInfo) { | |||
| 227 | - | const originalDecodingInfo = navigator.mediaCapabilities.decodingInfo.bind(navigator.mediaCapabilities); | |||
| 228 | - | ||||
| 229 | - | navigator.mediaCapabilities.decodingInfo = async function(config) { | |||
| 230 | - | const contentType = config.video?.contentType || config.type || ''; | |||
| 231 | - | ||||
| 232 | - | // Parse resolution from video config for resolution-aware decisions | |||
| 233 | - | let width = 0, height = 0; | |||
| 234 | - | if (config.video) { | |||
| 235 | - | width = config.video.width || 0; | |||
| 236 | - | height = config.video.height || 0; | |||
| 237 | - | } | |||
| 238 | - | ||||
| 239 | - | // Determine if this is a high resolution request | |||
| 240 | - | const isHighRes = height >= 1440 || width >= 2560; // 1440p/1080p ultrawide+ | |||
| 241 | - | const is4K = height >= 2160 || width >= 3840; | |||
| 242 | - | const is1080p60 = (height >= 1080 || width >= 1920) && | |||
| 243 | - | (config.video?.framerate >= 50 || config.video?.frameRate >= 50); | |||
| 244 | - | ||||
| 245 | - | log('MediaCapabilities query - contentType: ' + contentType + | |||
| 246 | - | ', resolution: ' + width + 'x' + height + ', highRes: ' + isHighRes + ', 4K: ' + is4K + ', 1080p60: ' + is1080p60); | |||
| 247 | - | ||||
| 248 | - | // Block unwanted codecs`) | |||
| 249 | - | ||||
| 250 | - | if hasBlockedCodecs { | |||
| 251 | - | js.WriteString(` | |||
| 252 | - | const blockedRegex = /` + blockedPattern + `/i; | |||
| 253 | - | if (blockedRegex.test(contentType)) { | |||
| 254 | - | log('Blocking codec: ' + contentType); | |||
| 255 | - | return { | |||
| 256 | - | supported: false, | |||
| 257 | - | smooth: false, | |||
| 258 | - | powerEfficient: false | |||
| 259 | - | }; | |||
| 260 | - | }`) | |||
| 261 | - | } | |||
| 262 | - | ||||
| 263 | - | js.WriteString(` | |||
| 264 | - | ||||
| 265 | - | // Resolution-aware preferred codec handling`) | |||
| 266 | - | ||||
| 267 | - | if hasPreferredCodecs { | |||
| 268 | - | js.WriteString(` | |||
| 269 | - | const preferredCodecs = ` + preferredCodecsJS + `; | |||
| 270 | - | for (const preferred of preferredCodecs) { | |||
| 271 | - | if (contentType.toLowerCase().includes(preferred)) { | |||
| 272 | - | log('Boosting preferred codec: ' + contentType); | |||
| 273 | - | ||||
| 274 | - | // Resolution-aware capability reporting for AV1 | |||
| 275 | - | if (preferred === 'av01' || preferred === 'av1') { | |||
| 276 | - | // AV1 handling based on resolution | |||
| 277 | - | if (is4K) { | |||
| 278 | - | // 4K AV1: supported but not smooth (encourage VP9 fallback) | |||
| 279 | - | return { | |||
| 280 | - | supported: true, | |||
| 281 | - | smooth: false, | |||
| 282 | - | powerEfficient: false | |||
| 283 | - | }; | |||
| 284 | - | } else if (is1080p60) { | |||
| 285 | - | // 1080p60 AV1: supported but not power efficient | |||
| 286 | - | return { | |||
| 287 | - | supported: true, | |||
| 288 | - | smooth: true, | |||
| 289 | - | powerEfficient: false | |||
| 290 | - | }; | |||
| 291 | - | } else if (isHighRes) { | |||
| 292 | - | // 1440p AV1: supported but not optimal | |||
| 293 | - | return { | |||
| 294 | - | supported: true, | |||
| 295 | - | smooth: false, | |||
| 296 | - | powerEfficient: true | |||
| 297 | - | }; | |||
| 298 | - | } else { | |||
| 299 | - | // <= 1080p30 AV1: fully supported | |||
| 300 | - | return { | |||
| 301 | - | supported: true, | |||
| 302 | - | smooth: true, | |||
| 303 | - | powerEfficient: true | |||
| 304 | - | }; | |||
| 305 | - | } | |||
| 306 | - | } else { | |||
| 307 | - | // Other preferred codecs (VP9, H264) - always report as capable | |||
| 308 | - | return { | |||
| 309 | - | supported: true, | |||
| 310 | - | smooth: true, | |||
| 311 | - | powerEfficient: true | |||
| 312 | - | }; | |||
| 313 | - | } | |||
| 314 | - | } | |||
| 315 | - | }`) | |||
| 316 | - | } | |||
| 317 | - | ||||
| 318 | - | js.WriteString(` | |||
| 319 | - | ||||
| 320 | - | // Call original for other codecs | |||
| 321 | - | try { | |||
| 322 | - | return await originalDecodingInfo(config); | |||
| 323 | - | } catch (e) { | |||
| 324 | - | console.warn('[dumber-codec] MediaCapabilities error:', e); | |||
| 325 | - | return { | |||
| 326 | - | supported: false, | |||
| 327 | - | smooth: false, | |||
| 328 | - | powerEfficient: false | |||
| 329 | - | }; | |||
| 330 | - | } | |||
| 331 | - | }; | |||
| 332 | - | } | |||
| 333 | - | ||||
| 334 | - | // YouTube-specific codec forcing | |||
| 335 | - | if (location.hostname.includes('youtube.com')) { | |||
| 336 | - | log('Applying YouTube codec preferences'); | |||
| 337 | - | ||||
| 338 | - | // Set YouTube's localStorage preferences for smart AV1 usage | |||
| 339 | - | // 2048 = prefer AV1 for lower resolutions, fallback to VP9 for higher res | |||
| 340 | - | // This allows YouTube to make smarter codec decisions based on our MediaCapabilities | |||
| 341 | - | try { | |||
| 342 | - | localStorage.setItem('yt-player-av1-pref', '2048'); | |||
| 343 | - | Object.defineProperty(localStorage, 'yt-player-av1-pref', { | |||
| 344 | - | value: '2048', | |||
| 345 | - | writable: false, | |||
| 346 | - | configurable: false | |||
| 347 | - | }); | |||
| 348 | - | log('YouTube: Set smart AV1 localStorage preference (2048)'); | |||
| 349 | - | } catch (e) { | |||
| 350 | - | console.warn('[dumber-codec] YouTube: Failed to set localStorage:', e); | |||
| 351 | - | } | |||
| 352 | - | ||||
| 353 | - | // Override ytInitialPlayerResponse parsing | |||
| 354 | - | Object.defineProperty(window, 'ytplayer', { | |||
| 355 | - | configurable: true, | |||
| 356 | - | get() { | |||
| 357 | - | return this._ytplayer || null; | |||
| 358 | - | }, | |||
| 359 | - | set(player) { | |||
| 360 | - | if (player && player.config && player.config.args) {`) | |||
| 361 | - | ||||
| 362 | - | if prefs.ForceAV1 { | |||
| 363 | - | js.WriteString(` | |||
| 364 | - | // Force AV1 if enabled | |||
| 365 | - | player.config.args.preferred_codecs = 'av01'; | |||
| 366 | - | log('YouTube: Forced AV1 codec');`) | |||
| 367 | - | } | |||
| 368 | - | ||||
| 369 | - | if hasPreferredCodecs { | |||
| 370 | - | js.WriteString(` | |||
| 371 | - | // Set codec preference order | |||
| 372 | - | const preferredCodecs = ` + preferredCodecsJS + `; | |||
| 373 | - | const codecOrder = preferredCodecs.map(c => { | |||
| 374 | - | switch(c.toLowerCase()) { | |||
| 375 | - | case 'av1': case 'av01': return 'av01'; | |||
| 376 | - | case 'h264': case 'avc1': return 'avc1'; | |||
| 377 | - | case 'vp9': case 'vp09': return 'vp9'; | |||
| 378 | - | case 'vp8': case 'vp08': return 'vp8'; | |||
| 379 | - | default: return c; | |||
| 380 | - | } | |||
| 381 | - | }).join(','); | |||
| 382 | - | player.config.args.preferred_codecs = codecOrder; | |||
| 383 | - | log('YouTube: Set codec order: ' + codecOrder);`) | |||
| 384 | - | } | |||
| 385 | - | ||||
| 386 | - | js.WriteString(` | |||
| 387 | - | } | |||
| 388 | - | this._ytplayer = player; | |||
| 389 | - | } | |||
| 390 | - | }); | |||
| 391 | - | ||||
| 392 | - | // Intercept YouTube's format selection | |||
| 393 | - | const originalFetch = window.fetch; | |||
| 394 | - | window.fetch = function(input, init) { | |||
| 395 | - | if (typeof input === 'string' && input.includes('/youtubei/v1/player')) { | |||
| 396 | - | log('YouTube: Intercepting player request');`) | |||
| 397 | - | ||||
| 398 | - | if hasPreferredCodecs { | |||
| 399 | - | js.WriteString(` | |||
| 400 | - | ||||
| 401 | - | // Modify request to prefer our codecs | |||
| 402 | - | if (init && init.body) { | |||
| 403 | - | try { | |||
| 404 | - | const body = JSON.parse(init.body); | |||
| 405 | - | if (body.videoId) { | |||
| 406 | - | // Add codec preferences to the request | |||
| 407 | - | body.codecPreferences = ` + preferredCodecsJS + `; | |||
| 408 | - | init.body = JSON.stringify(body); | |||
| 409 | - | } | |||
| 410 | - | } catch (e) { | |||
| 411 | - | // Non-JSON body, ignore | |||
| 412 | - | } | |||
| 413 | - | }`) | |||
| 414 | - | } | |||
| 415 | - | ||||
| 416 | - | js.WriteString(` | |||
| 417 | - | } | |||
| 418 | - | ||||
| 419 | - | // Process YouTube player API responses for format manipulation | |||
| 420 | - | if (typeof input === 'string' && input.includes('/youtubei/v1/player')) { | |||
| 421 | - | return originalFetch.call(this, input, init).then(response => { | |||
| 422 | - | if (!response.ok) return response; | |||
| 423 | - | ||||
| 424 | - | return response.text().then(text => { | |||
| 425 | - | try { | |||
| 426 | - | const data = JSON.parse(text); | |||
| 427 | - | ||||
| 428 | - | // Manipulate streaming data if present | |||
| 429 | - | if (data.streamingData && data.streamingData.formats) { | |||
| 430 | - | log('YouTube: Processing format manifest'); | |||
| 431 | - | ||||
| 432 | - | // Sort formats to prioritize AV1 for lower resolutions, VP9 for higher | |||
| 433 | - | data.streamingData.formats.sort((a, b) => { | |||
| 434 | - | const aHeight = a.height || 0; | |||
| 435 | - | const bHeight = b.height || 0; | |||
| 436 | - | const aIsAV1 = a.mimeType && a.mimeType.includes('av01'); | |||
| 437 | - | const bIsAV1 = b.mimeType && b.mimeType.includes('av01'); | |||
| 438 | - | const aIsVP9 = a.mimeType && a.mimeType.includes('vp9'); | |||
| 439 | - | const bIsVP9 = b.mimeType && b.mimeType.includes('vp9'); | |||
| 440 | - | ||||
| 441 | - | // For resolutions <= 1080p, prioritize AV1 | |||
| 442 | - | if (Math.max(aHeight, bHeight) <= 1080) { | |||
| 443 | - | if (aIsAV1 && !bIsAV1) return -1; | |||
| 444 | - | if (!aIsAV1 && bIsAV1) return 1; | |||
| 445 | - | } | |||
| 446 | - | // For resolutions > 1080p, prioritize VP9 | |||
| 447 | - | else { | |||
| 448 | - | if (aIsVP9 && !bIsVP9) return -1; | |||
| 449 | - | if (!aIsVP9 && bIsVP9) return 1; | |||
| 450 | - | } | |||
| 451 | - | ||||
| 452 | - | return 0; | |||
| 453 | - | }); | |||
| 454 | - | ||||
| 455 | - | log('YouTube: Reordered formats for optimal codec selection'); | |||
| 456 | - | } | |||
| 457 | - | ||||
| 458 | - | return new Response(JSON.stringify(data), { | |||
| 459 | - | status: response.status, | |||
| 460 | - | statusText: response.statusText, | |||
| 461 | - | headers: response.headers | |||
| 462 | - | }); | |||
| 463 | - | } catch (e) { | |||
| 464 | - | console.warn('[dumber-codec] YouTube: Failed to process response:', e); | |||
| 465 | - | return new Response(text, { | |||
| 466 | - | status: response.status, | |||
| 467 | - | statusText: response.statusText, | |||
| 468 | - | headers: response.headers | |||
| 469 | - | }); | |||
| 470 | - | } | |||
| 471 | - | }); | |||
| 472 | - | }); | |||
| 473 | - | } | |||
| 474 | - | ||||
| 475 | - | return originalFetch.call(this, input, init); | |||
| 476 | - | }; | |||
| 477 | - | } | |||
| 478 | - | ||||
| 479 | - | // Twitch: No codec interference - let Twitch handle codec selection natively | |||
| 480 | - | if (location.hostname.includes('twitch.tv')) { | |||
| 481 | - | log('Detected Twitch domain - no codec interference for stability'); | |||
| 482 | - | // Twitch codec control completely removed to prevent theater/fullscreen freezing | |||
| 483 | - | } | |||
| 484 | - | ||||
| 485 | - | // Passive video monitoring without interfering with element creation | |||
| 486 | - | const monitorExistingVideos = () => { | |||
| 487 | - | const videos = document.querySelectorAll('video'); | |||
| 488 | - | videos.forEach(video => { | |||
| 489 | - | if (!video.__codecMonitored) { | |||
| 490 | - | video.__codecMonitored = true; | |||
| 491 | - | log('Found video element, adding passive monitoring'); | |||
| 492 | - | ||||
| 493 | - | // Passive codec detection only | |||
| 494 | - | video.addEventListener('canplay', function() { | |||
| 495 | - | log('Video can play - resolution: ' + this.videoWidth + 'x' + this.videoHeight); | |||
| 496 | - | }, { passive: true, once: true }); | |||
| 497 | - | } | |||
| 498 | - | }); | |||
| 499 | - | }; | |||
| 500 | - | ||||
| 501 | - | // Monitor for video elements periodically without overriding createElement | |||
| 502 | - | const videoObserver = new MutationObserver(monitorExistingVideos); | |||
| 503 | - | ||||
| 504 | - | // Wait for document.body to be available before observing | |||
| 505 | - | function startVideoObserver() { | |||
| 506 | - | if (document.body) { | |||
| 507 | - | videoObserver.observe(document.body, { childList: true, subtree: true }); | |||
| 508 | - | monitorExistingVideos(); // Check existing videos | |||
| 509 | - | log('Video observer started'); | |||
| 510 | - | } else { | |||
| 511 | - | // Retry after a short delay if body not ready | |||
| 512 | - | setTimeout(startVideoObserver, 50); | |||
| 513 | - | } | |||
| 514 | - | } | |||
| 515 | - | startVideoObserver(); | |||
| 516 | - | ||||
| 517 | - | log('Codec control initialization complete'); | |||
| 518 | - | })();`) | |||
| 519 | - | ||||
| 520 | - | return js.String() | |||
| 521 | - | } | |||
D pkg/webkit/debug_cgo.go +0 -137
| @@ -1,137 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #cgo pkg-config: webkitgtk-6.0 gtk4 | |||
| 7 | - | #cgo CFLAGS: -I/usr/include/webkitgtk-6.0 | |||
| 8 | - | #include <webkit/webkit.h> | |||
| 9 | - | #include <stdlib.h> | |||
| 10 | - | ||||
| 11 | - | // WebKit debug logging callback | |||
| 12 | - | extern void webkit_debug_log(char* message); | |||
| 13 | - | ||||
| 14 | - | // Forward declaration | |||
| 15 | - | static void webkit_debug_log_handler(const gchar *log_domain, | |||
| 16 | - | GLogLevelFlags log_level, | |||
| 17 | - | const gchar *message, | |||
| 18 | - | gpointer user_data); | |||
| 19 | - | ||||
| 20 | - | static void setup_webkit_debug_logging() { | |||
| 21 | - | // Enable WebKit debug logging if WEBKIT_DEBUG environment variable is set | |||
| 22 | - | const char* debug_env = g_getenv("WEBKIT_DEBUG"); | |||
| 23 | - | if (debug_env) { | |||
| 24 | - | g_setenv("G_MESSAGES_DEBUG", "WebKit", TRUE); | |||
| 25 | - | g_setenv("WEBKIT_DEBUG", debug_env, TRUE); | |||
| 26 | - | ||||
| 27 | - | // Set up custom log handler for better integration | |||
| 28 | - | g_log_set_handler("WebKit", | |||
| 29 | - | G_LOG_LEVEL_DEBUG | G_LOG_LEVEL_INFO | G_LOG_LEVEL_MESSAGE, | |||
| 30 | - | (GLogFunc)webkit_debug_log_handler, NULL); | |||
| 31 | - | } | |||
| 32 | - | } | |||
| 33 | - | ||||
| 34 | - | static void webkit_debug_log_handler(const gchar *log_domain, | |||
| 35 | - | GLogLevelFlags log_level, | |||
| 36 | - | const gchar *message, | |||
| 37 | - | gpointer user_data) { | |||
| 38 | - | // Format log message and send to Go | |||
| 39 | - | char* formatted_msg = g_strdup_printf("[%s] %s", log_domain, message); | |||
| 40 | - | webkit_debug_log(formatted_msg); | |||
| 41 | - | g_free(formatted_msg); | |||
| 42 | - | } | |||
| 43 | - | ||||
| 44 | - | // Enable detailed content filtering debug logs | |||
| 45 | - | static void enable_filtering_debug() { | |||
| 46 | - | g_setenv("WEBKIT_DEBUG", "Network:preconnectTo,ContentFilters", TRUE); | |||
| 47 | - | } | |||
| 48 | - | ||||
| 49 | - | // Check if WebView is in a valid state for operations | |||
| 50 | - | static gboolean check_webview_state(WebKitWebView *webview) { | |||
| 51 | - | if (!webview) return FALSE; | |||
| 52 | - | if (!WEBKIT_IS_WEB_VIEW(webview)) return FALSE; | |||
| 53 | - | ||||
| 54 | - | // Check if WebView is not being destroyed | |||
| 55 | - | GObject *obj = G_OBJECT(webview); | |||
| 56 | - | if (g_object_get_data(obj, "webkit-destroying")) return FALSE; | |||
| 57 | - | ||||
| 58 | - | return TRUE; | |||
| 59 | - | } | |||
| 60 | - | */ | |||
| 61 | - | import "C" | |||
| 62 | - | ||||
| 63 | - | import ( | |||
| 64 | - | "os" | |||
| 65 | - | ||||
| 66 | - | "github.com/bnema/dumber/internal/config" | |||
| 67 | - | "github.com/bnema/dumber/internal/logging" | |||
| 68 | - | ) | |||
| 69 | - | ||||
| 70 | - | //export webkit_debug_log | |||
| 71 | - | func webkit_debug_log(message *C.char) { | |||
| 72 | - | msg := C.GoString(message) | |||
| 73 | - | logging.Debug("[webkit-internal] " + msg) | |||
| 74 | - | } | |||
| 75 | - | ||||
| 76 | - | // SetupWebKitDebugLogging initializes WebKit debug logging based on config and environment variables | |||
| 77 | - | func SetupWebKitDebugLogging(cfg *config.Config) { | |||
| 78 | - | // Check if debug mode is enabled via config or environment variables | |||
| 79 | - | debugEnabled := (cfg != nil && cfg.Debug.EnableWebKitDebug) || | |||
| 80 | - | os.Getenv("WEBKIT_DEBUG") != "" || | |||
| 81 | - | os.Getenv("DUMBER_DEBUG") != "" || | |||
| 82 | - | (cfg != nil && cfg.Debug.EnableGeneralDebug) | |||
| 83 | - | ||||
| 84 | - | if debugEnabled { | |||
| 85 | - | logging.Info("[webkit] Enabling WebKit debug logging") | |||
| 86 | - | ||||
| 87 | - | // Set debug categories from config or environment | |||
| 88 | - | var debugCategories string | |||
| 89 | - | if cfg != nil && cfg.Debug.WebKitDebugCategories != "" { | |||
| 90 | - | debugCategories = cfg.Debug.WebKitDebugCategories | |||
| 91 | - | } else if envDebug := os.Getenv("WEBKIT_DEBUG"); envDebug != "" { | |||
| 92 | - | debugCategories = envDebug | |||
| 93 | - | } else { | |||
| 94 | - | debugCategories = "Network:preconnectTo,ContentFilters" | |||
| 95 | - | } | |||
| 96 | - | ||||
| 97 | - | // Set the environment variable for WebKit | |||
| 98 | - | os.Setenv("WEBKIT_DEBUG", debugCategories) | |||
| 99 | - | ||||
| 100 | - | C.setup_webkit_debug_logging() | |||
| 101 | - | ||||
| 102 | - | // Enable filtering-specific debug logs if configured | |||
| 103 | - | if cfg != nil && cfg.Debug.EnableFilteringDebug { | |||
| 104 | - | C.enable_filtering_debug() | |||
| 105 | - | logging.Info("[webkit] Content filtering debug logging enabled") | |||
| 106 | - | } | |||
| 107 | - | ||||
| 108 | - | logging.Info("[webkit] WebKit debug logging enabled with categories: " + debugCategories) | |||
| 109 | - | } | |||
| 110 | - | } | |||
| 111 | - | ||||
| 112 | - | // CheckWebViewState validates that a WebView is in a safe state for operations | |||
| 113 | - | func (w *WebView) CheckWebViewState() bool { | |||
| 114 | - | if w == nil || w.destroyed || w.native == nil || w.native.wv == nil { | |||
| 115 | - | return false | |||
| 116 | - | } | |||
| 117 | - | ||||
| 118 | - | return C.check_webview_state(w.native.wv) != 0 | |||
| 119 | - | } | |||
| 120 | - | ||||
| 121 | - | // LogDebugInfo logs debug information about the current WebView state | |||
| 122 | - | func (w *WebView) LogDebugInfo() { | |||
| 123 | - | if !w.CheckWebViewState() { | |||
| 124 | - | logging.Debug("[webkit] WebView is not in valid state") | |||
| 125 | - | return | |||
| 126 | - | } | |||
| 127 | - | ||||
| 128 | - | logging.Debug("[webkit] WebView state: valid and ready for operations") | |||
| 129 | - | ||||
| 130 | - | // Log content manager state | |||
| 131 | - | manager := C.webkit_web_view_get_user_content_manager(w.native.wv) | |||
| 132 | - | if manager != nil { | |||
| 133 | - | logging.Debug("[webkit] User content manager: available") | |||
| 134 | - | } else { | |||
| 135 | - | logging.Debug("[webkit] User content manager: not available") | |||
| 136 | - | } | |||
| 137 | - | } | |||
D pkg/webkit/debug_stub.go +0 -23
| @@ -1,23 +0,0 @@ | |||||
| 1 | - | //go:build !webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | import ( | |||
| 6 | - | "github.com/bnema/dumber/internal/config" | |||
| 7 | - | "github.com/bnema/dumber/internal/logging" | |||
| 8 | - | ) | |||
| 9 | - | ||||
| 10 | - | // SetupWebKitDebugLogging is a stub for non-CGO builds | |||
| 11 | - | func SetupWebKitDebugLogging(cfg *config.Config) { | |||
| 12 | - | logging.Info("[webkit] Debug logging not available in stub build") | |||
| 13 | - | } | |||
| 14 | - | ||||
| 15 | - | // CheckWebViewState always returns false in stub builds | |||
| 16 | - | func (w *WebView) CheckWebViewState() bool { | |||
| 17 | - | return false | |||
| 18 | - | } | |||
| 19 | - | ||||
| 20 | - | // LogDebugInfo is a stub for non-CGO builds | |||
| 21 | - | func (w *WebView) LogDebugInfo() { | |||
| 22 | - | logging.Debug("[webkit] Debug info not available in stub build") | |||
| 23 | - | } | |||
D pkg/webkit/devtools_cgo.go +0 -34
| @@ -1,34 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #cgo pkg-config: webkitgtk-6.0 gtk4 | |||
| 7 | - | #cgo CFLAGS: -I/usr/include/webkitgtk-6.0 | |||
| 8 | - | #include <webkit/webkit.h> | |||
| 9 | - | */ | |||
| 10 | - | import "C" | |||
| 11 | - | ||||
| 12 | - | func (w *WebView) ShowDevTools() error { | |||
| 13 | - | if w == nil || w.native == nil || w.native.wv == nil { | |||
| 14 | - | return ErrNotImplemented | |||
| 15 | - | } | |||
| 16 | - | insp := C.webkit_web_view_get_inspector(w.native.wv) | |||
| 17 | - | if insp == nil { | |||
| 18 | - | return ErrNotImplemented | |||
| 19 | - | } | |||
| 20 | - | C.webkit_web_inspector_show(insp) | |||
| 21 | - | return nil | |||
| 22 | - | } | |||
| 23 | - | ||||
| 24 | - | func (w *WebView) CloseDevTools() error { | |||
| 25 | - | if w == nil || w.native == nil || w.native.wv == nil { | |||
| 26 | - | return ErrNotImplemented | |||
| 27 | - | } | |||
| 28 | - | insp := C.webkit_web_view_get_inspector(w.native.wv) | |||
| 29 | - | if insp == nil { | |||
| 30 | - | return ErrNotImplemented | |||
| 31 | - | } | |||
| 32 | - | C.webkit_web_inspector_close(insp) | |||
| 33 | - | return nil | |||
| 34 | - | } | |||
D pkg/webkit/dom_events.go +0 -25
| @@ -1,25 +0,0 @@ | |||||
| 1 | - | package webkit | |||
| 2 | - | ||||
| 3 | - | import ( | |||
| 4 | - | "encoding/json" | |||
| 5 | - | "fmt" | |||
| 6 | - | ) | |||
| 7 | - | ||||
| 8 | - | // DispatchCustomEvent sends a CustomEvent into the page world with the provided detail payload. | |||
| 9 | - | func (w *WebView) DispatchCustomEvent(eventName string, detail map[string]any) error { | |||
| 10 | - | if w == nil || w.IsDestroyed() { | |||
| 11 | - | return ErrNotImplemented | |||
| 12 | - | } | |||
| 13 | - | ||||
| 14 | - | payload := "{}" | |||
| 15 | - | if detail != nil { | |||
| 16 | - | data, err := json.Marshal(detail) | |||
| 17 | - | if err != nil { | |||
| 18 | - | return fmt.Errorf("failed to marshal event detail: %w", err) | |||
| 19 | - | } | |||
| 20 | - | payload = string(data) | |||
| 21 | - | } | |||
| 22 | - | ||||
| 23 | - | script := fmt.Sprintf(`(function(){try{var detail=%s;document.dispatchEvent(new CustomEvent(%q,{detail:detail}));}catch(e){console.error('[dumber] Failed to dispatch %s', e);}})();`, payload, eventName, eventName) | |||
| 24 | - | return w.InjectScript(script) | |||
| 25 | - | } | |||
M pkg/webkit/errors.go +14 -7
| @@ -1,13 +1,20 @@ | |||||
| 1 | - | // Package webkit provides a WebKit2GTK-backed browser view and window. | |||
| 2 | package webkit | 1 | package webkit | ||
| 3 | 2 | ||||
| 4 | import "errors" | 3 | import "errors" | ||
| 5 | 4 | ||||
| 6 | - | // ErrNotImplemented is returned by stub implementations pending WebKit2GTK migration. | 5 | + | var ( |
| 7 | - | var ErrNotImplemented = errors.New("webkit: not implemented") | 6 | + | // ErrNotImplemented indicates a feature is not yet implemented |
| 7 | + | ErrNotImplemented = errors.New("webkit: not implemented") | |||
| 8 | 8 | ||||
| 9 | - | // ErrWebViewNotInitialized is returned when WebView operations are attempted on uninitialized WebView | 9 | + | // ErrWebViewNotInitialized indicates the WebView was not properly initialized |
| 10 | - | var ErrWebViewNotInitialized = errors.New("webkit: webview not initialized") | 10 | + | ErrWebViewNotInitialized = errors.New("webkit: webview not initialized") |
| 11 | 11 | ||||
| 12 | - | // ErrContentManagerNotFound is returned when WebKit user content manager cannot be retrieved | 12 | + | // ErrWebViewDestroyed indicates the WebView has been destroyed |
| 13 | - | var ErrContentManagerNotFound = errors.New("webkit: user content manager not found") | 13 | + | ErrWebViewDestroyed = errors.New("webkit: webview destroyed") |
| 14 | + | ||||
| 15 | + | // ErrInvalidURL indicates an invalid URL was provided | |||
| 16 | + | ErrInvalidURL = errors.New("webkit: invalid URL") | |||
| 17 | + | ||||
| 18 | + | // ErrMainThreadRequired indicates an operation must be called from the main thread | |||
| 19 | + | ErrMainThreadRequired = errors.New("webkit: operation must be called from main thread") | |||
| 20 | + | ) | |||
D pkg/webkit/filtering_cgo.go +0 -249
| @@ -1,249 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #cgo pkg-config: webkitgtk-6.0 gtk4 | |||
| 7 | - | #cgo CFLAGS: -I/usr/include/webkitgtk-6.0 | |||
| 8 | - | #include <webkit/webkit.h> | |||
| 9 | - | #include <stdlib.h> | |||
| 10 | - | ||||
| 11 | - | // Global filter store instance | |||
| 12 | - | static WebKitUserContentFilterStore *filter_store = NULL; | |||
| 13 | - | ||||
| 14 | - | // External Go functions | |||
| 15 | - | extern char* get_webkit_filter_store_path(); | |||
| 16 | - | extern void log_filter_success(char* identifier); | |||
| 17 | - | extern void log_filter_error(char* error_msg, char* identifier); | |||
| 18 | - | ||||
| 19 | - | // Callback for save operation completion | |||
| 20 | - | static void filter_save_callback(GObject *source_object, | |||
| 21 | - | GAsyncResult *result, | |||
| 22 | - | gpointer user_data) { | |||
| 23 | - | WebKitUserContentFilterStore *store = WEBKIT_USER_CONTENT_FILTER_STORE(source_object); | |||
| 24 | - | WebKitUserContentManager *manager = WEBKIT_USER_CONTENT_MANAGER(user_data); | |||
| 25 | - | GError *error = NULL; | |||
| 26 | - | ||||
| 27 | - | WebKitUserContentFilter *filter = webkit_user_content_filter_store_save_finish(store, result, &error); | |||
| 28 | - | ||||
| 29 | - | if (filter && !error) { | |||
| 30 | - | webkit_user_content_manager_add_filter(manager, filter); | |||
| 31 | - | const char *id = webkit_user_content_filter_get_identifier(filter); | |||
| 32 | - | log_filter_success((char*)id); | |||
| 33 | - | webkit_user_content_filter_unref(filter); | |||
| 34 | - | } | |||
| 35 | - | ||||
| 36 | - | if (error) { | |||
| 37 | - | char *msg = g_strdup(error->message); | |||
| 38 | - | log_filter_error(msg, "unknown"); | |||
| 39 | - | g_free(msg); | |||
| 40 | - | g_error_free(error); | |||
| 41 | - | } | |||
| 42 | - | } | |||
| 43 | - | ||||
| 44 | - | // Initialize filter store if not already done | |||
| 45 | - | static void ensure_filter_store() { | |||
| 46 | - | if (filter_store == NULL) { | |||
| 47 | - | // Get XDG-compliant path from Go (with tmp fallback) | |||
| 48 | - | char *store_path = get_webkit_filter_store_path(); | |||
| 49 | - | filter_store = webkit_user_content_filter_store_new(store_path); | |||
| 50 | - | free(store_path); // Free the C string returned by Go | |||
| 51 | - | } | |||
| 52 | - | } | |||
| 53 | - | ||||
| 54 | - | static void apply_content_filter(WebKitUserContentManager *manager, | |||
| 55 | - | const char *filter_json, | |||
| 56 | - | const char *identifier) { | |||
| 57 | - | ensure_filter_store(); | |||
| 58 | - | ||||
| 59 | - | GBytes *bytes = g_bytes_new(filter_json, strlen(filter_json)); | |||
| 60 | - | ||||
| 61 | - | // Save filter to store asynchronously - it will be applied in the callback | |||
| 62 | - | webkit_user_content_filter_store_save(filter_store, | |||
| 63 | - | identifier, | |||
| 64 | - | bytes, | |||
| 65 | - | NULL, | |||
| 66 | - | filter_save_callback, | |||
| 67 | - | manager); | |||
| 68 | - | ||||
| 69 | - | g_bytes_unref(bytes); | |||
| 70 | - | } | |||
| 71 | - | ||||
| 72 | - | static void inject_cosmetic_script(WebKitUserContentManager *manager, | |||
| 73 | - | const char *script_source) { | |||
| 74 | - | // Use isolated script world to prevent interference with page JavaScript | |||
| 75 | - | WebKitUserScript *script = webkit_user_script_new_for_world( | |||
| 76 | - | script_source, | |||
| 77 | - | WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES, | |||
| 78 | - | WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_END, // Changed from DOCUMENT_START to avoid preconnect interference | |||
| 79 | - | "dumber-cosmetic", // Isolated world name | |||
| 80 | - | NULL, NULL | |||
| 81 | - | ); | |||
| 82 | - | ||||
| 83 | - | webkit_user_content_manager_add_script(manager, script); | |||
| 84 | - | webkit_user_script_unref(script); | |||
| 85 | - | } | |||
| 86 | - | ||||
| 87 | - | static void clear_all_filters(WebKitUserContentManager *manager) { | |||
| 88 | - | webkit_user_content_manager_remove_all_filters(manager); | |||
| 89 | - | } | |||
| 90 | - | ||||
| 91 | - | static void clear_all_scripts(WebKitUserContentManager *manager) { | |||
| 92 | - | webkit_user_content_manager_remove_all_scripts(manager); | |||
| 93 | - | } | |||
| 94 | - | */ | |||
| 95 | - | import "C" | |||
| 96 | - | ||||
| 97 | - | import ( | |||
| 98 | - | "encoding/json" | |||
| 99 | - | "fmt" | |||
| 100 | - | "os" | |||
| 101 | - | "path/filepath" | |||
| 102 | - | "unsafe" | |||
| 103 | - | ||||
| 104 | - | "github.com/bnema/dumber/internal/config" | |||
| 105 | - | "github.com/bnema/dumber/internal/logging" | |||
| 106 | - | ) | |||
| 107 | - | ||||
| 108 | - | //export get_webkit_filter_store_path | |||
| 109 | - | func get_webkit_filter_store_path() *C.char { | |||
| 110 | - | // Try XDG directories first | |||
| 111 | - | if filterCacheDir, err := config.GetFilterCacheDir(); err == nil { | |||
| 112 | - | webkitFilterDir := filepath.Join(filterCacheDir, "webkit-store") | |||
| 113 | - | if err := os.MkdirAll(webkitFilterDir, 0755); err == nil { | |||
| 114 | - | return C.CString(webkitFilterDir) | |||
| 115 | - | } | |||
| 116 | - | } | |||
| 117 | - | ||||
| 118 | - | // Fallback to tmp if XDG fails | |||
| 119 | - | tmpDir := os.TempDir() | |||
| 120 | - | fallbackDir := filepath.Join(tmpDir, "dumber-filters") | |||
| 121 | - | if err := os.MkdirAll(fallbackDir, 0755); err == nil { | |||
| 122 | - | logging.Warn("[webkit] Using fallback tmp directory for filter store: " + fallbackDir) | |||
| 123 | - | return C.CString(fallbackDir) | |||
| 124 | - | } | |||
| 125 | - | ||||
| 126 | - | // Last resort - return tmp dir | |||
| 127 | - | logging.Error("[webkit] Failed to create filter store directory, using tmp") | |||
| 128 | - | return C.CString(tmpDir) | |||
| 129 | - | } | |||
| 130 | - | ||||
| 131 | - | //export log_filter_success | |||
| 132 | - | func log_filter_success(identifier *C.char) { | |||
| 133 | - | id := C.GoString(identifier) | |||
| 134 | - | logging.Info("[webkit] Network filter applied successfully: " + id) | |||
| 135 | - | } | |||
| 136 | - | ||||
| 137 | - | //export log_filter_error | |||
| 138 | - | func log_filter_error(errorMsg *C.char, identifier *C.char) { | |||
| 139 | - | msg := C.GoString(errorMsg) | |||
| 140 | - | id := C.GoString(identifier) | |||
| 141 | - | logging.Error("[webkit] Failed to apply network filter '" + id + "': " + msg) | |||
| 142 | - | } | |||
| 143 | - | ||||
| 144 | - | // ApplyContentFilters applies WebKit native content filters with error recovery | |||
| 145 | - | func (w *WebView) ApplyContentFilters(filters []byte, identifier string) error { | |||
| 146 | - | // Check WebView state with debug support | |||
| 147 | - | if !w.CheckWebViewState() { | |||
| 148 | - | w.LogDebugInfo() | |||
| 149 | - | return ErrWebViewNotInitialized | |||
| 150 | - | } | |||
| 151 | - | ||||
| 152 | - | // Validate input | |||
| 153 | - | if len(filters) == 0 || identifier == "" { | |||
| 154 | - | return fmt.Errorf("invalid filter parameters: empty filters or identifier") | |||
| 155 | - | } | |||
| 156 | - | ||||
| 157 | - | // Check if filters are valid JSON | |||
| 158 | - | if !json.Valid(filters) { | |||
| 159 | - | return fmt.Errorf("invalid filter JSON for identifier: %s", identifier) | |||
| 160 | - | } | |||
| 161 | - | ||||
| 162 | - | defer func() { | |||
| 163 | - | if r := recover(); r != nil { | |||
| 164 | - | logging.Error(fmt.Sprintf("[webkit] Panic in ApplyContentFilters: %v", r)) | |||
| 165 | - | } | |||
| 166 | - | }() | |||
| 167 | - | ||||
| 168 | - | manager := C.webkit_web_view_get_user_content_manager(w.native.wv) | |||
| 169 | - | if manager == nil { | |||
| 170 | - | return ErrContentManagerNotFound | |||
| 171 | - | } | |||
| 172 | - | ||||
| 173 | - | cFilters := C.CString(string(filters)) | |||
| 174 | - | cID := C.CString(identifier) | |||
| 175 | - | defer C.free(unsafe.Pointer(cFilters)) | |||
| 176 | - | defer C.free(unsafe.Pointer(cID)) | |||
| 177 | - | ||||
| 178 | - | logging.Info("[webkit] Applying network filters: " + identifier + " (" + fmt.Sprintf("%d", len(filters)) + " bytes)") | |||
| 179 | - | ||||
| 180 | - | // Apply filter with error checking | |||
| 181 | - | C.apply_content_filter(manager, cFilters, cID) | |||
| 182 | - | return nil | |||
| 183 | - | } | |||
| 184 | - | ||||
| 185 | - | // InjectCosmeticFilter injects JavaScript for cosmetic filtering with error recovery | |||
| 186 | - | func (w *WebView) InjectCosmeticFilter(script string) error { | |||
| 187 | - | // Check WebView state with debug support | |||
| 188 | - | if !w.CheckWebViewState() { | |||
| 189 | - | w.LogDebugInfo() | |||
| 190 | - | return ErrWebViewNotInitialized | |||
| 191 | - | } | |||
| 192 | - | ||||
| 193 | - | // Validate input | |||
| 194 | - | if len(script) == 0 { | |||
| 195 | - | return fmt.Errorf("empty cosmetic filter script") | |||
| 196 | - | } | |||
| 197 | - | ||||
| 198 | - | defer func() { | |||
| 199 | - | if r := recover(); r != nil { | |||
| 200 | - | logging.Error(fmt.Sprintf("[webkit] Panic in InjectCosmeticFilter: %v", r)) | |||
| 201 | - | } | |||
| 202 | - | }() | |||
| 203 | - | ||||
| 204 | - | manager := C.webkit_web_view_get_user_content_manager(w.native.wv) | |||
| 205 | - | if manager == nil { | |||
| 206 | - | return ErrContentManagerNotFound | |||
| 207 | - | } | |||
| 208 | - | ||||
| 209 | - | cScript := C.CString(script) | |||
| 210 | - | defer C.free(unsafe.Pointer(cScript)) | |||
| 211 | - | ||||
| 212 | - | logging.Info("[webkit] Injecting cosmetic filter script (" + fmt.Sprintf("%d", len(script)) + " chars)") | |||
| 213 | - | ||||
| 214 | - | // Inject script with error recovery | |||
| 215 | - | C.inject_cosmetic_script(manager, cScript) | |||
| 216 | - | return nil | |||
| 217 | - | } | |||
| 218 | - | ||||
| 219 | - | // ClearAllFilters removes all content filters | |||
| 220 | - | func (w *WebView) ClearAllFilters() error { | |||
| 221 | - | if w.native == nil || w.native.wv == nil { | |||
| 222 | - | return ErrWebViewNotInitialized | |||
| 223 | - | } | |||
| 224 | - | ||||
| 225 | - | manager := C.webkit_web_view_get_user_content_manager(w.native.wv) | |||
| 226 | - | if manager == nil { | |||
| 227 | - | return ErrContentManagerNotFound | |||
| 228 | - | } | |||
| 229 | - | ||||
| 230 | - | logging.Info("[webkit] Clearing all content filters") | |||
| 231 | - | C.clear_all_filters(manager) | |||
| 232 | - | return nil | |||
| 233 | - | } | |||
| 234 | - | ||||
| 235 | - | // ClearAllScripts removes all injected scripts | |||
| 236 | - | func (w *WebView) ClearAllScripts() error { | |||
| 237 | - | if w.native == nil || w.native.wv == nil { | |||
| 238 | - | return ErrWebViewNotInitialized | |||
| 239 | - | } | |||
| 240 | - | ||||
| 241 | - | manager := C.webkit_web_view_get_user_content_manager(w.native.wv) | |||
| 242 | - | if manager == nil { | |||
| 243 | - | return ErrContentManagerNotFound | |||
| 244 | - | } | |||
| 245 | - | ||||
| 246 | - | logging.Info("[webkit] Clearing all injected scripts") | |||
| 247 | - | C.clear_all_scripts(manager) | |||
| 248 | - | return nil | |||
| 249 | - | } | |||
D pkg/webkit/find.go +0 -35
| @@ -1,35 +0,0 @@ | |||||
| 1 | - | package webkit | |||
| 2 | - | ||||
| 3 | - | import ( | |||
| 4 | - | "fmt" | |||
| 5 | - | "strconv" | |||
| 6 | - | ) | |||
| 7 | - | ||||
| 8 | - | // OpenFind opens the in-page find overlay (reusing omnibox) with an optional initial query. | |||
| 9 | - | func (w *WebView) OpenFind(initial string) error { | |||
| 10 | - | if w == nil { | |||
| 11 | - | return ErrNotImplemented | |||
| 12 | - | } | |||
| 13 | - | quoted := strconv.Quote(initial) | |||
| 14 | - | // Prefer unified omnibox open via keyboard shortcut; fallback to legacy helper | |||
| 15 | - | js := fmt.Sprintf("(window.__dumber?.omnibox?.open ? window.__dumber.omnibox.open('find', %s) : (window.__dumber_find_open && window.__dumber_find_open(%s)))", quoted, quoted) | |||
| 16 | - | return w.InjectScript(js) | |||
| 17 | - | } | |||
| 18 | - | ||||
| 19 | - | // FindQuery sets or updates the current find query and applies highlighting. | |||
| 20 | - | func (w *WebView) FindQuery(q string) error { | |||
| 21 | - | if w == nil { | |||
| 22 | - | return ErrNotImplemented | |||
| 23 | - | } | |||
| 24 | - | quoted := strconv.Quote(q) | |||
| 25 | - | js := fmt.Sprintf("(window.__dumber?.omnibox?.findQuery ? window.__dumber.omnibox.findQuery(%s) : (window.__dumber_find_query && window.__dumber_find_query(%s)))", quoted, quoted) | |||
| 26 | - | return w.InjectScript(js) | |||
| 27 | - | } | |||
| 28 | - | ||||
| 29 | - | // CloseFind closes the find overlay and clears highlights. | |||
| 30 | - | func (w *WebView) CloseFind() error { | |||
| 31 | - | if w == nil { | |||
| 32 | - | return ErrNotImplemented | |||
| 33 | - | } | |||
| 34 | - | return w.InjectScript("(window.__dumber?.omnibox?.close ? window.__dumber.omnibox.close() : (window.__dumber_find_close && window.__dumber_find_close()))") | |||
| 35 | - | } | |||
D pkg/webkit/keyboard.go +0 -36
| @@ -1,36 +0,0 @@ | |||||
| 1 | - | //go:build !webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | import "fmt" | |||
| 6 | - | ||||
| 7 | - | // RegisterKeyboardShortcut binds a global or window-scoped accelerator to a callback. | |||
| 8 | - | func (w *WebView) RegisterKeyboardShortcut(accel string, callback func()) error { | |||
| 9 | - | if w == nil || w.destroyed { | |||
| 10 | - | return ErrNotImplemented | |||
| 11 | - | } | |||
| 12 | - | if accel == "" || callback == nil { | |||
| 13 | - | return fmt.Errorf("invalid shortcut registration") | |||
| 14 | - | } | |||
| 15 | - | // Placeholder: in real impl, bind GTK accelerator; for now, store for tests. | |||
| 16 | - | if shortcuts := getShortcutRegistry(w); shortcuts != nil { | |||
| 17 | - | shortcuts[accel] = callback | |||
| 18 | - | } | |||
| 19 | - | return nil | |||
| 20 | - | } | |||
| 21 | - | ||||
| 22 | - | // internal registry per view while no GTK binding exists. | |||
| 23 | - | type shortcutRegistry map[string]func() | |||
| 24 | - | ||||
| 25 | - | var viewShortcuts = make(map[*WebView]shortcutRegistry) | |||
| 26 | - | ||||
| 27 | - | func getShortcutRegistry(w *WebView) shortcutRegistry { | |||
| 28 | - | reg, ok := viewShortcuts[w] | |||
| 29 | - | if !ok { | |||
| 30 | - | reg = make(shortcutRegistry) | |||
| 31 | - | viewShortcuts[w] = reg | |||
| 32 | - | } | |||
| 33 | - | return reg | |||
| 34 | - | } | |||
| 35 | - | ||||
| 36 | - | // No layout-specific remaps in non-CGO build either. | |||
D pkg/webkit/keyboard_cgo.go +0 -813
| @@ -1,813 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #cgo pkg-config: gtk4 webkitgtk-6.0 | |||
| 7 | - | #include <gtk/gtk.h> | |||
| 8 | - | #include <gdk/gdk.h> | |||
| 9 | - | #include <webkit/webkit.h> | |||
| 10 | - | ||||
| 11 | - | // Declarations for Go callbacks | |||
| 12 | - | extern gboolean goOnKeyPress(unsigned long id, unsigned int keyval, GdkModifierType state); | |||
| 13 | - | extern void goOnButtonPress(unsigned long id, unsigned int button, GdkModifierType state); | |||
| 14 | - | extern void goOnScroll(unsigned long id, double dx, double dy, GdkModifierType state); | |||
| 15 | - | ||||
| 16 | - | // Key controller callback -> forward to Go | |||
| 17 | - | static gboolean on_key_pressed(GtkEventControllerKey* controller, guint keyval, guint keycode, GdkModifierType state, gpointer user_data) { | |||
| 18 | - | (void)controller; (void)keycode; | |||
| 19 | - | return goOnKeyPress((unsigned long)user_data, keyval, state); | |||
| 20 | - | } | |||
| 21 | - | ||||
| 22 | - | // Mouse click gesture -> forward side buttons to Go | |||
| 23 | - | static void on_click_pressed(GtkGestureClick* gesture, gint n_press, gdouble x, gdouble y, gpointer user_data) { | |||
| 24 | - | (void)n_press; (void)x; (void)y; | |||
| 25 | - | guint button = gtk_gesture_single_get_current_button(GTK_GESTURE_SINGLE(gesture)); | |||
| 26 | - | // Pass 0 for modifier state (not provided via gesture API) | |||
| 27 | - | goOnButtonPress((unsigned long)user_data, button, 0); | |||
| 28 | - | } | |||
| 29 | - | ||||
| 30 | - | // Attach controllers to a widget (GTK4) | |||
| 31 | - | static void attach_key_controller(GtkWidget* widget, unsigned long id) { | |||
| 32 | - | if (!widget) return; | |||
| 33 | - | GtkEventController* keyc = gtk_event_controller_key_new(); | |||
| 34 | - | // Capture phase so we see keys even if child consumes them (e.g., WebKit) | |||
| 35 | - | gtk_event_controller_set_propagation_phase(keyc, GTK_PHASE_CAPTURE); | |||
| 36 | - | g_signal_connect_data(keyc, "key-pressed", G_CALLBACK(on_key_pressed), (gpointer)id, NULL, 0); | |||
| 37 | - | gtk_widget_add_controller(widget, keyc); | |||
| 38 | - | } | |||
| 39 | - | ||||
| 40 | - | static void attach_mouse_gesture(GtkWidget* widget, unsigned long id) { | |||
| 41 | - | if (!widget) return; | |||
| 42 | - | GtkGesture* click = gtk_gesture_click_new(); | |||
| 43 | - | g_signal_connect_data(click, "pressed", G_CALLBACK(on_click_pressed), (gpointer)id, NULL, 0); | |||
| 44 | - | gtk_widget_add_controller(widget, GTK_EVENT_CONTROLLER(click)); | |||
| 45 | - | } | |||
| 46 | - | ||||
| 47 | - | // Legacy controller to capture side buttons (8/9) reliably in GTK4 | |||
| 48 | - | static gboolean on_legacy_event(GtkEventController* controller, GdkEvent* event, gpointer user_data) { | |||
| 49 | - | (void)controller; | |||
| 50 | - | if (!event) return FALSE; | |||
| 51 | - | GdkEventType type = gdk_event_get_event_type(event); | |||
| 52 | - | if (type == GDK_BUTTON_PRESS) { | |||
| 53 | - | guint button = gdk_button_event_get_button(event); | |||
| 54 | - | GdkModifierType state = gdk_event_get_modifier_state(event); | |||
| 55 | - | if (button == 8 || button == 9) { | |||
| 56 | - | goOnButtonPress((unsigned long)user_data, button, state); | |||
| 57 | - | return TRUE; // consume side buttons | |||
| 58 | - | } | |||
| 59 | - | return FALSE; // let WebKit handle normal clicks | |||
| 60 | - | } else if (type == GDK_SCROLL) { | |||
| 61 | - | double dx = 0.0, dy = 0.0; | |||
| 62 | - | gdk_scroll_event_get_deltas(event, &dx, &dy); | |||
| 63 | - | GdkModifierType state = gdk_event_get_modifier_state(event); | |||
| 64 | - | goOnScroll((unsigned long)user_data, dx, dy, state); | |||
| 65 | - | return FALSE; // don't steal regular scrolling | |||
| 66 | - | } | |||
| 67 | - | return FALSE; | |||
| 68 | - | } | |||
| 69 | - | ||||
| 70 | - | static void attach_mouse_legacy(GtkWidget* widget, unsigned long id) { | |||
| 71 | - | if (!widget) return; | |||
| 72 | - | GtkEventController* legacy = gtk_event_controller_legacy_new(); | |||
| 73 | - | gtk_event_controller_set_propagation_phase(legacy, GTK_PHASE_CAPTURE); | |||
| 74 | - | g_signal_connect_data(legacy, "event", G_CALLBACK(on_legacy_event), (gpointer)id, NULL, 0); | |||
| 75 | - | gtk_widget_add_controller(widget, legacy); | |||
| 76 | - | } | |||
| 77 | - | */ | |||
| 78 | - | import "C" | |||
| 79 | - | ||||
| 80 | - | import ( | |||
| 81 | - | "encoding/json" | |||
| 82 | - | "fmt" | |||
| 83 | - | "log" | |||
| 84 | - | "strings" | |||
| 85 | - | "sync" | |||
| 86 | - | "sync/atomic" | |||
| 87 | - | "time" | |||
| 88 | - | ) | |||
| 89 | - | ||||
| 90 | - | // Registry of accelerators per view id. | |||
| 91 | - | type shortcutRegistry map[string]func() | |||
| 92 | - | ||||
| 93 | - | var ( | |||
| 94 | - | regMu sync.RWMutex | |||
| 95 | - | viewShortcuts = make(map[uintptr]shortcutRegistry) | |||
| 96 | - | viewIDCounter uint64 | |||
| 97 | - | viewByID = make(map[uintptr]*WebView) | |||
| 98 | - | lastKeyTime = make(map[uintptr]map[string]time.Time) | |||
| 99 | - | ) | |||
| 100 | - | ||||
| 101 | - | const shortcutDebounceWindow = 120 * time.Millisecond | |||
| 102 | - | ||||
| 103 | - | // shouldDebounceShortcut returns true when the given key should be skipped | |||
| 104 | - | // because it was delivered within the debounce window for the same view. | |||
| 105 | - | func shouldDebounceShortcut(uid uintptr, key string, now time.Time) bool { | |||
| 106 | - | regMu.Lock() | |||
| 107 | - | defer regMu.Unlock() | |||
| 108 | - | ||||
| 109 | - | if _, ok := lastKeyTime[uid]; !ok { | |||
| 110 | - | lastKeyTime[uid] = make(map[string]time.Time) | |||
| 111 | - | } | |||
| 112 | - | last := lastKeyTime[uid][key] | |||
| 113 | - | if now.Sub(last) < shortcutDebounceWindow { | |||
| 114 | - | return true | |||
| 115 | - | } | |||
| 116 | - | lastKeyTime[uid][key] = now | |||
| 117 | - | return false | |||
| 118 | - | } | |||
| 119 | - | ||||
| 120 | - | // Locale hint function removed; no layout-specific remaps. | |||
| 121 | - | ||||
| 122 | - | // RegisterKeyboardShortcut registers a callback under an accelerator string. | |||
| 123 | - | func (w *WebView) RegisterKeyboardShortcut(accel string, callback func()) error { | |||
| 124 | - | if w == nil || w.destroyed { | |||
| 125 | - | return ErrNotImplemented | |||
| 126 | - | } | |||
| 127 | - | if accel == "" || callback == nil { | |||
| 128 | - | return fmt.Errorf("invalid shortcut registration") | |||
| 129 | - | } | |||
| 130 | - | regMu.Lock() | |||
| 131 | - | if _, ok := viewShortcuts[w.id]; !ok { | |||
| 132 | - | viewShortcuts[w.id] = make(shortcutRegistry) | |||
| 133 | - | } | |||
| 134 | - | viewShortcuts[w.id][accel] = callback | |||
| 135 | - | regMu.Unlock() | |||
| 136 | - | ||||
| 137 | - | // Register in global shortcuts registry for automatic webpage blocking | |||
| 138 | - | RegisterGlobalShortcut(accel) | |||
| 139 | - | ||||
| 140 | - | return nil | |||
| 141 | - | } | |||
| 142 | - | ||||
| 143 | - | //export goOnKeyPress | |||
| 144 | - | func goOnKeyPress(id C.ulong, keyval C.guint, state C.GdkModifierType) C.gboolean { | |||
| 145 | - | // Normalize and dispatch | |||
| 146 | - | uid := uintptr(id) | |||
| 147 | - | kv := uint(keyval) | |||
| 148 | - | st := uint(state) | |||
| 149 | - | ||||
| 150 | - | if dispatchAccelerator(uid, kv, st) { | |||
| 151 | - | return C.gboolean(1) | |||
| 152 | - | } | |||
| 153 | - | return C.gboolean(0) | |||
| 154 | - | } | |||
| 155 | - | ||||
| 156 | - | // getCLevelBridgeShortcut returns the shortcut string for shortcuts that need C-level bridge handling. | |||
| 157 | - | // These shortcuts are blocked at the webpage level and have their callbacks triggered directly from C code. | |||
| 158 | - | // Returns empty string if the shortcut doesn't need C-level handling. | |||
| 159 | - | func getCLevelBridgeShortcut(ctrl, alt, shift bool, keyName string) string { | |||
| 160 | - | // Alt+Arrow shortcuts - for workspace pane navigation | |||
| 161 | - | if alt && !ctrl && !shift { | |||
| 162 | - | switch keyName { | |||
| 163 | - | case "ArrowLeft": | |||
| 164 | - | return "alt+arrowleft" | |||
| 165 | - | case "ArrowRight": | |||
| 166 | - | return "alt+arrowright" | |||
| 167 | - | case "ArrowUp": | |||
| 168 | - | return "alt+arrowup" | |||
| 169 | - | case "ArrowDown": | |||
| 170 | - | return "alt+arrowdown" | |||
| 171 | - | } | |||
| 172 | - | } | |||
| 173 | - | ||||
| 174 | - | // Ctrl+W shortcut - for closing current pane via workspace manager | |||
| 175 | - | if ctrl && !alt && !shift && keyName == "w" { | |||
| 176 | - | return "ctrl+w" | |||
| 177 | - | } | |||
| 178 | - | ||||
| 179 | - | // Add other C-level bridge shortcuts here as needed | |||
| 180 | - | // Note: Most shortcuts (Ctrl+L, Ctrl+F, zoom) should NOT be here | |||
| 181 | - | // They work fine through normal GTK4 handling without C-level intervention | |||
| 182 | - | ||||
| 183 | - | return "" | |||
| 184 | - | } | |||
| 185 | - | ||||
| 186 | - | func dispatchAccelerator(uid uintptr, keyval uint, state uint) bool { | |||
| 187 | - | ctrl := (state & uint(C.GDK_CONTROL_MASK)) != 0 | |||
| 188 | - | alt := (state & uint(C.GDK_ALT_MASK)) != 0 | |||
| 189 | - | shift := (state & uint(C.GDK_SHIFT_MASK)) != 0 | |||
| 190 | - | // Map keyval to string names | |||
| 191 | - | var keyName string | |||
| 192 | - | logMinusEvent := false | |||
| 193 | - | switch keyval { | |||
| 194 | - | case uint(C.GDK_KEY_minus), uint(C.GDK_KEY_KP_Subtract), uint(C.GDK_KEY_underscore): | |||
| 195 | - | // Normalize minus; log raw detection for diagnostics | |||
| 196 | - | logMinusEvent = true | |||
| 197 | - | keyName = "-" | |||
| 198 | - | case uint(C.GDK_KEY_equal), uint(C.GDK_KEY_KP_Add): | |||
| 199 | - | keyName = "=" | |||
| 200 | - | case uint(C.GDK_KEY_0), uint(C.GDK_KEY_KP_0): | |||
| 201 | - | keyName = "0" | |||
| 202 | - | case uint(C.GDK_KEY_Left): | |||
| 203 | - | keyName = "ArrowLeft" | |||
| 204 | - | case uint(C.GDK_KEY_Right): | |||
| 205 | - | keyName = "ArrowRight" | |||
| 206 | - | case uint(C.GDK_KEY_Up): | |||
| 207 | - | keyName = "ArrowUp" | |||
| 208 | - | case uint(C.GDK_KEY_Down): | |||
| 209 | - | keyName = "ArrowDown" | |||
| 210 | - | case uint(C.GDK_KEY_KP_Left): | |||
| 211 | - | keyName = "ArrowLeft" | |||
| 212 | - | case uint(C.GDK_KEY_KP_Right): | |||
| 213 | - | keyName = "ArrowRight" | |||
| 214 | - | case uint(C.GDK_KEY_KP_Up): | |||
| 215 | - | keyName = "ArrowUp" | |||
| 216 | - | case uint(C.GDK_KEY_KP_Down): | |||
| 217 | - | keyName = "ArrowDown" | |||
| 218 | - | case uint(C.GDK_KEY_F12): | |||
| 219 | - | keyName = "F12" | |||
| 220 | - | case uint(C.GDK_KEY_F5): | |||
| 221 | - | keyName = "F5" | |||
| 222 | - | case uint(C.GDK_KEY_c), uint(C.GDK_KEY_C): | |||
| 223 | - | keyName = "c" | |||
| 224 | - | case uint(C.GDK_KEY_r), uint(C.GDK_KEY_R): | |||
| 225 | - | keyName = "r" | |||
| 226 | - | case uint(C.GDK_KEY_l), uint(C.GDK_KEY_L): | |||
| 227 | - | keyName = "l" | |||
| 228 | - | case uint(C.GDK_KEY_f), uint(C.GDK_KEY_F): | |||
| 229 | - | keyName = "f" | |||
| 230 | - | case uint(C.GDK_KEY_p), uint(C.GDK_KEY_P): | |||
| 231 | - | keyName = "p" | |||
| 232 | - | case uint(C.GDK_KEY_w), uint(C.GDK_KEY_W): | |||
| 233 | - | keyName = "w" | |||
| 234 | - | default: | |||
| 235 | - | // Filter out modifier keys themselves (like Ctrl, Alt, Shift) | |||
| 236 | - | // These keyvals shouldn't be logged as misses | |||
| 237 | - | switch keyval { | |||
| 238 | - | case 0xffe1, 0xffe2: // GDK_KEY_Shift_L, GDK_KEY_Shift_R | |||
| 239 | - | return false | |||
| 240 | - | case 0xffe3, 0xffe4: // GDK_KEY_Control_L, GDK_KEY_Control_R | |||
| 241 | - | return false | |||
| 242 | - | case 0xffe9, 0xffea: // GDK_KEY_Alt_L, GDK_KEY_Alt_R | |||
| 243 | - | return false | |||
| 244 | - | case 0xffeb, 0xffec: // GDK_KEY_Super_L, GDK_KEY_Super_R | |||
| 245 | - | return false | |||
| 246 | - | } | |||
| 247 | - | ||||
| 248 | - | // If Control held, log unknown keyval for diagnostics (but not modifier keys) | |||
| 249 | - | if ctrl { | |||
| 250 | - | log.Printf("[accelerator-miss] ctrl keyval=0x%x", keyval) | |||
| 251 | - | } | |||
| 252 | - | return false | |||
| 253 | - | } | |||
| 254 | - | ||||
| 255 | - | // Check for shortcuts that need C-level handling and trigger if found | |||
| 256 | - | shortcut := getCLevelBridgeShortcut(ctrl, alt, shift, keyName) | |||
| 257 | - | if shortcut != "" { | |||
| 258 | - | // For all C-level bridge shortcuts (Alt+Arrow and Ctrl+W), use global window shortcut handler | |||
| 259 | - | // The window shortcut handler now properly handles both popup and regular panes | |||
| 260 | - | shortcutsRegistryMu.RLock() | |||
| 261 | - | handle, exists := globalShortcutHandles[shortcut] | |||
| 262 | - | shortcutsRegistryMu.RUnlock() | |||
| 263 | - | ||||
| 264 | - | if exists && handle != 0 { | |||
| 265 | - | invokeWindowShortcutCallback(handle) | |||
| 266 | - | return true | |||
| 267 | - | } | |||
| 268 | - | } | |||
| 269 | - | ||||
| 270 | - | now := time.Now() | |||
| 271 | - | rawKey := fmt.Sprintf("raw:%v:%v:%v:%s", ctrl, alt, shift, keyName) | |||
| 272 | - | if shouldDebounceShortcut(uid, rawKey, now) { | |||
| 273 | - | return false | |||
| 274 | - | } | |||
| 275 | - | ||||
| 276 | - | if logMinusEvent { | |||
| 277 | - | log.Printf("[accelerator-raw] minus key detected ctrl=%v alt=%v keyval=0x%x", ctrl, alt, keyval) | |||
| 278 | - | } | |||
| 279 | - | ||||
| 280 | - | // Candidate accelerator strings in order | |||
| 281 | - | handled := false | |||
| 282 | - | candidates := []string{keyName} | |||
| 283 | - | if ctrl && shift { | |||
| 284 | - | // Ctrl+Shift combinations | |||
| 285 | - | candidates = append([]string{"cmdorctrl+shift+" + keyName, "ctrl+shift+" + keyName}, candidates...) | |||
| 286 | - | } else if ctrl { | |||
| 287 | - | // Common style: modifier + '+' + keyName (e.g., cmdorctrl+=) | |||
| 288 | - | candidates = append([]string{"cmdorctrl+" + keyName, "ctrl+" + keyName}, candidates...) | |||
| 289 | - | // Also accept style without the extra '+' for punctuation keys (e.g., cmdorctrl-) | |||
| 290 | - | candidates = append([]string{"cmdorctrl" + keyName, "ctrl" + keyName}, candidates...) | |||
| 291 | - | } | |||
| 292 | - | if alt { | |||
| 293 | - | candidates = append([]string{"alt+" + keyName}, candidates...) | |||
| 294 | - | } | |||
| 295 | - | ||||
| 296 | - | // Compute a single normalized shortcut string to forward to GUI (single source of truth) | |||
| 297 | - | normalized := "" | |||
| 298 | - | if ctrl && shift { | |||
| 299 | - | normalized = "cmdorctrl+shift+" + keyName | |||
| 300 | - | } else if ctrl { | |||
| 301 | - | normalized = "cmdorctrl+" + keyName | |||
| 302 | - | } else if alt { | |||
| 303 | - | normalized = "alt+" + keyName | |||
| 304 | - | } else if keyName != "" { | |||
| 305 | - | // For future modes like Vim, we may want to forward non-modified keys | |||
| 306 | - | // For now, only forward if a modifier is present to avoid noise | |||
| 307 | - | normalized = "" | |||
| 308 | - | } | |||
| 309 | - | ||||
| 310 | - | // Forward normalized shortcut to GUI KeyboardService via DOM event if present | |||
| 311 | - | if normalized != "" && !shouldDebounceShortcut(uid, "dom:"+normalized, now) { | |||
| 312 | - | regMu.RLock() | |||
| 313 | - | vw := viewByID[uid] | |||
| 314 | - | regMu.RUnlock() | |||
| 315 | - | if vw != nil { | |||
| 316 | - | _ = vw.InjectScript(fmt.Sprintf("document.dispatchEvent(new CustomEvent('dumber:key',{detail:{shortcut:'%s'}}));", normalized)) | |||
| 317 | - | } | |||
| 318 | - | } | |||
| 319 | - | ||||
| 320 | - | regMu.RLock() | |||
| 321 | - | reg := viewShortcuts[uid] | |||
| 322 | - | regMu.RUnlock() | |||
| 323 | - | if reg == nil { | |||
| 324 | - | return handled | |||
| 325 | - | } | |||
| 326 | - | ||||
| 327 | - | for _, name := range candidates { | |||
| 328 | - | if cb, ok := reg[name]; ok { | |||
| 329 | - | if shouldDebounceShortcut(uid, "shortcut:"+name, now) { | |||
| 330 | - | return handled | |||
| 331 | - | } | |||
| 332 | - | log.Printf("[accelerator] %s", name) | |||
| 333 | - | cb() | |||
| 334 | - | handled = true | |||
| 335 | - | break | |||
| 336 | - | } | |||
| 337 | - | } | |||
| 338 | - | ||||
| 339 | - | return handled | |||
| 340 | - | } | |||
| 341 | - | ||||
| 342 | - | func nextViewID() uintptr { | |||
| 343 | - | return uintptr(atomic.AddUint64(&viewIDCounter, 1)) | |||
| 344 | - | } | |||
| 345 | - | ||||
| 346 | - | func registerView(id uintptr, w *WebView) { | |||
| 347 | - | regMu.Lock() | |||
| 348 | - | viewByID[id] = w | |||
| 349 | - | regMu.Unlock() | |||
| 350 | - | } | |||
| 351 | - | ||||
| 352 | - | func unregisterView(id uintptr) { | |||
| 353 | - | regMu.Lock() | |||
| 354 | - | delete(viewByID, id) | |||
| 355 | - | delete(viewShortcuts, id) | |||
| 356 | - | regMu.Unlock() | |||
| 357 | - | } | |||
| 358 | - | ||||
| 359 | - | // AttachKeyboardControllers attaches GTK4 key and mouse controllers to the view widget. | |||
| 360 | - | func AttachKeyboardControllers(w *WebView) { | |||
| 361 | - | if w == nil || w.native == nil || w.native.view == nil { | |||
| 362 | - | return | |||
| 363 | - | } | |||
| 364 | - | C.attach_key_controller(w.native.view, C.ulong(w.id)) | |||
| 365 | - | if w.native.win != nil { | |||
| 366 | - | C.attach_key_controller(w.native.win, C.ulong(w.id)) | |||
| 367 | - | } | |||
| 368 | - | C.attach_mouse_gesture(w.native.view, C.ulong(w.id)) | |||
| 369 | - | // Legacy controller captures raw button presses (8/9) for back/forward reliably | |||
| 370 | - | C.attach_mouse_legacy(w.native.view, C.ulong(w.id)) | |||
| 371 | - | log.Printf("[input] GTK4 key/mouse controllers attached") | |||
| 372 | - | } | |||
| 373 | - | ||||
| 374 | - | //export goOnScroll | |||
| 375 | - | func goOnScroll(id C.ulong, dx C.double, dy C.double, state C.GdkModifierType) { | |||
| 376 | - | uid := uintptr(id) | |||
| 377 | - | regMu.RLock() | |||
| 378 | - | vw := viewByID[uid] | |||
| 379 | - | regMu.RUnlock() | |||
| 380 | - | if vw == nil { | |||
| 381 | - | return | |||
| 382 | - | } | |||
| 383 | - | // Ctrl+scroll zooms | |||
| 384 | - | if (uint(state) & uint(C.GDK_CONTROL_MASK)) != 0 { | |||
| 385 | - | if float64(dy) < 0 { | |||
| 386 | - | // scroll up -> zoom in | |||
| 387 | - | nz := vw.zoom | |||
| 388 | - | if nz <= 0 { | |||
| 389 | - | nz = 1.0 | |||
| 390 | - | } | |||
| 391 | - | nz *= 1.1 | |||
| 392 | - | if nz < 0.25 { | |||
| 393 | - | nz = 0.25 | |||
| 394 | - | } | |||
| 395 | - | if nz > 5.0 { | |||
| 396 | - | nz = 5.0 | |||
| 397 | - | } | |||
| 398 | - | _ = vw.SetZoom(nz) | |||
| 399 | - | } else if float64(dy) > 0 { | |||
| 400 | - | // scroll down -> zoom out | |||
| 401 | - | nz := vw.zoom | |||
| 402 | - | if nz <= 0 { | |||
| 403 | - | nz = 1.0 | |||
| 404 | - | } | |||
| 405 | - | nz /= 1.1 | |||
| 406 | - | if nz < 0.25 { | |||
| 407 | - | nz = 0.25 | |||
| 408 | - | } | |||
| 409 | - | if nz > 5.0 { | |||
| 410 | - | nz = 5.0 | |||
| 411 | - | } | |||
| 412 | - | _ = vw.SetZoom(nz) | |||
| 413 | - | } | |||
| 414 | - | } | |||
| 415 | - | } | |||
| 416 | - | ||||
| 417 | - | //export goOnThemeChanged | |||
| 418 | - | func goOnThemeChanged(id C.ulong, preferDark C.int) { | |||
| 419 | - | uid := uintptr(id) | |||
| 420 | - | regMu.RLock() | |||
| 421 | - | vw := viewByID[uid] | |||
| 422 | - | regMu.RUnlock() | |||
| 423 | - | if vw == nil { | |||
| 424 | - | return | |||
| 425 | - | } | |||
| 426 | - | // Inject runtime theme update into the page | |||
| 427 | - | dval := "false" | |||
| 428 | - | if int(preferDark) != 0 { | |||
| 429 | - | dval = "true" | |||
| 430 | - | } | |||
| 431 | - | js := fmt.Sprintf(`(() => { try { const d=%s; const cs=d?'dark':'light'; console.log('[dumber] theme change:'+cs); | |||
| 432 | - | let m=document.querySelector('meta[name="color-scheme"]'); | |||
| 433 | - | if(!m){ m=document.createElement('meta'); m.name='color-scheme'; document.head.appendChild(m); } | |||
| 434 | - | m.setAttribute('content', d ? 'dark light' : 'light dark'); | |||
| 435 | - | let s=document.getElementById('__dumber_theme_style'); | |||
| 436 | - | if(!s){ s=document.createElement('style'); s.id='__dumber_theme_style'; document.documentElement.appendChild(s); } | |||
| 437 | - | s.textContent=':root{color-scheme:' + (d?'dark':'light') + ';}'; | |||
| 438 | - | // Call the unified theme setter for Tailwind dark mode | |||
| 439 | - | if (window.__dumber_setTheme) { | |||
| 440 | - | window.__dumber_setTheme(cs); | |||
| 441 | - | } else { | |||
| 442 | - | // Retry after a short delay in case bridge hasn't loaded yet | |||
| 443 | - | setTimeout(() => { | |||
| 444 | - | if (window.__dumber_setTheme) { | |||
| 445 | - | window.__dumber_setTheme(cs); | |||
| 446 | - | } else { | |||
| 447 | - | // Fallback: directly apply dark class | |||
| 448 | - | console.warn('[dumber] Theme setter not available, using fallback'); | |||
| 449 | - | if (d) { | |||
| 450 | - | document.documentElement.classList.add('dark'); | |||
| 451 | - | } else { | |||
| 452 | - | document.documentElement.classList.remove('dark'); | |||
| 453 | - | } | |||
| 454 | - | } | |||
| 455 | - | }, 100); | |||
| 456 | - | } | |||
| 457 | - | } catch(e) { console.warn('[dumber] theme runtime update failed', e); } })();`, dval) | |||
| 458 | - | _ = vw.InjectScript(js) | |||
| 459 | - | } | |||
| 460 | - | ||||
| 461 | - | //export goOnUcmMessage | |||
| 462 | - | func goOnUcmMessage(id C.ulong, json *C.char) { | |||
| 463 | - | uid := uintptr(id) | |||
| 464 | - | regMu.RLock() | |||
| 465 | - | vw := viewByID[uid] | |||
| 466 | - | regMu.RUnlock() | |||
| 467 | - | if vw == nil || json == nil { | |||
| 468 | - | return | |||
| 469 | - | } | |||
| 470 | - | goPayload := C.GoString(json) | |||
| 471 | - | ||||
| 472 | - | // Handle rendering backend detection messages specially | |||
| 473 | - | if handleRenderingBackendMessage(goPayload) { | |||
| 474 | - | return | |||
| 475 | - | } | |||
| 476 | - | ||||
| 477 | - | // Handle keyboard blocking messages | |||
| 478 | - | if handleKeyboardBlockingMessage(vw, goPayload) { | |||
| 479 | - | return | |||
| 480 | - | } | |||
| 481 | - | ||||
| 482 | - | vw.dispatchScriptMessage(goPayload) | |||
| 483 | - | } | |||
| 484 | - | ||||
| 485 | - | //export goOnTitleChanged | |||
| 486 | - | func goOnTitleChanged(id C.ulong, ctitle *C.char) { | |||
| 487 | - | uid := uintptr(id) | |||
| 488 | - | regMu.RLock() | |||
| 489 | - | vw := viewByID[uid] | |||
| 490 | - | regMu.RUnlock() | |||
| 491 | - | if vw == nil || ctitle == nil { | |||
| 492 | - | return | |||
| 493 | - | } | |||
| 494 | - | title := C.GoString(ctitle) | |||
| 495 | - | vw.dispatchTitleChanged(title) | |||
| 496 | - | } | |||
| 497 | - | ||||
| 498 | - | //export goOnURIChanged | |||
| 499 | - | func goOnURIChanged(id C.ulong, curi *C.char) { | |||
| 500 | - | uid := uintptr(id) | |||
| 501 | - | regMu.RLock() | |||
| 502 | - | vw := viewByID[uid] | |||
| 503 | - | regMu.RUnlock() | |||
| 504 | - | if vw == nil || curi == nil { | |||
| 505 | - | return | |||
| 506 | - | } | |||
| 507 | - | uri := C.GoString(curi) | |||
| 508 | - | vw.dispatchURIChanged(uri) | |||
| 509 | - | } | |||
| 510 | - | ||||
| 511 | - | //export goOnFaviconURIChanged | |||
| 512 | - | func goOnFaviconURIChanged(id C.ulong, pageURI *C.char, faviconURI *C.char) { | |||
| 513 | - | uid := uintptr(id) | |||
| 514 | - | pageURLStr := C.GoString(pageURI) | |||
| 515 | - | faviconURLStr := C.GoString(faviconURI) | |||
| 516 | - | ||||
| 517 | - | log.Printf("[favicon] WebKit favicon URI changed for WebView ID %d - favicon: %s", uid, faviconURLStr) | |||
| 518 | - | ||||
| 519 | - | regMu.RLock() | |||
| 520 | - | vw := viewByID[uid] | |||
| 521 | - | regMu.RUnlock() | |||
| 522 | - | if vw == nil { | |||
| 523 | - | log.Printf("[favicon] WebView not found for ID %d", uid) | |||
| 524 | - | return | |||
| 525 | - | } | |||
| 526 | - | ||||
| 527 | - | vw.dispatchFaviconURIChanged(pageURLStr, faviconURLStr) | |||
| 528 | - | } | |||
| 529 | - | ||||
| 530 | - | //export goHandleNewWindowPolicy | |||
| 531 | - | func goHandleNewWindowPolicy(id C.ulong, curi *C.char, navType C.int, cframeName *C.char, isUserGesture C.gboolean, modifiers C.guint, mouseButton C.guint) C.gboolean { | |||
| 532 | - | uid := uintptr(id) | |||
| 533 | - | regMu.RLock() | |||
| 534 | - | vw := viewByID[uid] | |||
| 535 | - | regMu.RUnlock() | |||
| 536 | - | ||||
| 537 | - | if vw == nil { | |||
| 538 | - | log.Printf("[webkit] Policy decision: no WebView found for ID %d", uid) | |||
| 539 | - | return 0 // FALSE | |||
| 540 | - | } | |||
| 541 | - | ||||
| 542 | - | uri := "" | |||
| 543 | - | if curi != nil { | |||
| 544 | - | uri = C.GoString(curi) | |||
| 545 | - | } | |||
| 546 | - | ||||
| 547 | - | frameName := "" | |||
| 548 | - | if cframeName != nil { | |||
| 549 | - | frameName = C.GoString(cframeName) | |||
| 550 | - | } | |||
| 551 | - | ||||
| 552 | - | // Navigation type constants from WebKit headers | |||
| 553 | - | navTypeNames := map[int]string{ | |||
| 554 | - | 0: "LINK_CLICKED", | |||
| 555 | - | 1: "FORM_SUBMITTED", | |||
| 556 | - | 2: "BACK_FORWARD", | |||
| 557 | - | 3: "RELOAD", | |||
| 558 | - | 4: "FORM_RESUBMITTED", | |||
| 559 | - | 5: "OTHER", | |||
| 560 | - | } | |||
| 561 | - | ||||
| 562 | - | navTypeName := navTypeNames[int(navType)] | |||
| 563 | - | if navTypeName == "" { | |||
| 564 | - | navTypeName = fmt.Sprintf("UNKNOWN(%d)", int(navType)) | |||
| 565 | - | } | |||
| 566 | - | ||||
| 567 | - | // Convert parameters for analysis | |||
| 568 | - | userGesture := isUserGesture != 0 | |||
| 569 | - | mods := uint(modifiers) | |||
| 570 | - | button := uint(mouseButton) | |||
| 571 | - | ||||
| 572 | - | // Check for modifier keys that indicate new tab intent | |||
| 573 | - | const ( | |||
| 574 | - | GDK_CONTROL_MASK = 0x04 | |||
| 575 | - | GDK_META_MASK = 0x10000000 // Command key on macOS | |||
| 576 | - | ) | |||
| 577 | - | hasCtrlOrCmd := (mods&GDK_CONTROL_MASK != 0) || (mods&GDK_META_MASK != 0) | |||
| 578 | - | ||||
| 579 | - | log.Printf("[webkit] Policy decision for new window: URI=%s, NavType=%s, FrameName=%s, UserGesture=%v, Modifiers=0x%x, Button=%d, CtrlOrCmd=%v", | |||
| 580 | - | uri, navTypeName, frameName, userGesture, mods, button, hasCtrlOrCmd) | |||
| 581 | - | ||||
| 582 | - | // Enhanced detection logic for _blank vs popup using reliable heuristics | |||
| 583 | - | isRegularPane := false | |||
| 584 | - | ||||
| 585 | - | // Criteria for treating as regular pane (new panel): | |||
| 586 | - | // 1. Explicit _blank frame name (target="_blank" links) | |||
| 587 | - | // 2. User gesture with Ctrl/Cmd+click (open in new panel intent) | |||
| 588 | - | // 3. User-initiated OTHER navigation with no frame name (window.open("url", "_blank")) | |||
| 589 | - | if frameName == "_blank" { | |||
| 590 | - | isRegularPane = true | |||
| 591 | - | log.Printf("[webkit] _blank frame detected - will handle as new panel") | |||
| 592 | - | } else if userGesture && hasCtrlOrCmd && (navType == 0 || navType == 5) { | |||
| 593 | - | // WEBKIT_NAVIGATION_TYPE_LINK_CLICKED = 0, WEBKIT_NAVIGATION_TYPE_OTHER = 5 | |||
| 594 | - | isRegularPane = true | |||
| 595 | - | log.Printf("[webkit] Ctrl/Cmd+click detected - will handle as new panel") | |||
| 596 | - | } else if userGesture && navType == 5 && frameName == "" { | |||
| 597 | - | // window.open("url", "_blank") typically: user gesture + OTHER + no frame name | |||
| 598 | - | isRegularPane = true | |||
| 599 | - | log.Printf("[webkit] User-initiated window.open() detected - will handle as new panel") | |||
| 600 | - | } | |||
| 601 | - | ||||
| 602 | - | // Handle _blank targets by creating new panels directly (prevent WindowFeatures crash) | |||
| 603 | - | if isRegularPane { | |||
| 604 | - | log.Printf("[webkit] Creating new panel for _blank target: %s", uri) | |||
| 605 | - | ||||
| 606 | - | // Create new panel through workspace manager using existing popup handler | |||
| 607 | - | if vw.popupHandler != nil { | |||
| 608 | - | // Call popup handler to create a new panel | |||
| 609 | - | // The workspace manager will handle this as a regular panel based on URI markers | |||
| 610 | - | vw.popupHandler(uri + "#__dumber_frame_blank") | |||
| 611 | - | } | |||
| 612 | - | ||||
| 613 | - | return 1 // TRUE - we handled it by creating a new panel | |||
| 614 | - | } | |||
| 615 | - | ||||
| 616 | - | // For actual popups, let the create signal handle it | |||
| 617 | - | if vw.popupHandler != nil { | |||
| 618 | - | log.Printf("[webkit] Letting popup go through create signal for WindowFeatures handling: %s", uri) | |||
| 619 | - | return 0 // FALSE - let WebKit call create signal for popup handling | |||
| 620 | - | } else { | |||
| 621 | - | log.Printf("[webkit] No popup handler registered - allowing native popup for: %s", uri) | |||
| 622 | - | return 0 // FALSE - no handler, allow default popup | |||
| 623 | - | } | |||
| 624 | - | } | |||
| 625 | - | ||||
| 626 | - | //export goHandleLoadChanged | |||
| 627 | - | func goHandleLoadChanged(id C.ulong, curi *C.char, loadEvent C.int) { | |||
| 628 | - | uid := uintptr(id) | |||
| 629 | - | regMu.RLock() | |||
| 630 | - | vw := viewByID[uid] | |||
| 631 | - | regMu.RUnlock() | |||
| 632 | - | ||||
| 633 | - | if vw == nil { | |||
| 634 | - | return | |||
| 635 | - | } | |||
| 636 | - | ||||
| 637 | - | // OAuth auto-close is handled via WebKit's "close" signal when providers call window.close() | |||
| 638 | - | // No need to detect OAuth callback URLs - let the providers handle it | |||
| 639 | - | _ = curi // Suppress unused parameter warning | |||
| 640 | - | } | |||
| 641 | - | ||||
| 642 | - | //export goHandleWebViewClose | |||
| 643 | - | func goHandleWebViewClose(id C.ulong) { | |||
| 644 | - | uid := uintptr(id) | |||
| 645 | - | regMu.RLock() | |||
| 646 | - | vw := viewByID[uid] | |||
| 647 | - | regMu.RUnlock() | |||
| 648 | - | ||||
| 649 | - | if vw == nil { | |||
| 650 | - | log.Printf("[webkit] WebView close signal: no WebView found for ID %d", uid) | |||
| 651 | - | return | |||
| 652 | - | } | |||
| 653 | - | ||||
| 654 | - | log.Printf("[webkit] WebView close signal received for view_id: %d", uid) | |||
| 655 | - | ||||
| 656 | - | if vw.closeHandler != nil { | |||
| 657 | - | log.Printf("[webkit] Calling close handler for view_id: %d", uid) | |||
| 658 | - | vw.closeHandler() | |||
| 659 | - | } else { | |||
| 660 | - | log.Printf("[webkit] No close handler registered for view_id: %d", uid) | |||
| 661 | - | } | |||
| 662 | - | } | |||
| 663 | - | ||||
| 664 | - | //export goCreateNewPanel | |||
| 665 | - | func goCreateNewPanel(id C.ulong, curi *C.char) { | |||
| 666 | - | uid := uintptr(id) | |||
| 667 | - | regMu.RLock() | |||
| 668 | - | vw := viewByID[uid] | |||
| 669 | - | regMu.RUnlock() | |||
| 670 | - | ||||
| 671 | - | if vw == nil { | |||
| 672 | - | log.Printf("[webkit] Create panel: no WebView found for ID %d", uid) | |||
| 673 | - | return | |||
| 674 | - | } | |||
| 675 | - | ||||
| 676 | - | uri := "" | |||
| 677 | - | if curi != nil { | |||
| 678 | - | uri = C.GoString(curi) | |||
| 679 | - | } | |||
| 680 | - | ||||
| 681 | - | log.Printf("[webkit] Creating new panel for _blank target: %s", uri) | |||
| 682 | - | ||||
| 683 | - | // Create new panel through popup handler if available | |||
| 684 | - | if vw.popupHandler != nil { | |||
| 685 | - | vw.popupHandler(uri) | |||
| 686 | - | log.Printf("[webkit] New panel creation handled by popup handler") | |||
| 687 | - | } else { | |||
| 688 | - | log.Printf("[webkit] No popup handler available for panel creation") | |||
| 689 | - | } | |||
| 690 | - | } | |||
| 691 | - | ||||
| 692 | - | //export goHandlePopupGeometry | |||
| 693 | - | func goHandlePopupGeometry(id C.ulong, x, y, width, height C.int) { | |||
| 694 | - | // Store geometry for workspace manager to use | |||
| 695 | - | uid := uintptr(id) | |||
| 696 | - | regMu.Lock() | |||
| 697 | - | if vw := viewByID[uid]; vw != nil { | |||
| 698 | - | // For now, we'll store this in a simple way | |||
| 699 | - | // The workspace manager will handle the geometry | |||
| 700 | - | log.Printf("[webkit] Popup geometry: %dx%d at (%d,%d)", | |||
| 701 | - | int(width), int(height), int(x), int(y)) | |||
| 702 | - | } | |||
| 703 | - | regMu.Unlock() | |||
| 704 | - | } | |||
| 705 | - | ||||
| 706 | - | //export goOnButtonPress | |||
| 707 | - | func goOnButtonPress(id C.ulong, button C.guint, state C.GdkModifierType) { | |||
| 708 | - | uid := uintptr(id) | |||
| 709 | - | btn := uint(button) | |||
| 710 | - | log.Printf("[mouse] button=%d state=0x%x", btn, uint(state)) | |||
| 711 | - | regMu.RLock() | |||
| 712 | - | vw := viewByID[uid] | |||
| 713 | - | regMu.RUnlock() | |||
| 714 | - | if vw == nil { | |||
| 715 | - | return | |||
| 716 | - | } | |||
| 717 | - | switch btn { | |||
| 718 | - | case 8: // Back button on many mice | |||
| 719 | - | _ = vw.GoBack() | |||
| 720 | - | case 9: // Forward button on many mice | |||
| 721 | - | _ = vw.GoForward() | |||
| 722 | - | } | |||
| 723 | - | } | |||
| 724 | - | ||||
| 725 | - | //export goQuitMainLoop | |||
| 726 | - | func goQuitMainLoop() { | |||
| 727 | - | log.Printf("[webkit] Window close requested - quitting main loop") | |||
| 728 | - | QuitMainLoop() | |||
| 729 | - | } | |||
| 730 | - | ||||
| 731 | - | // handleRenderingBackendMessage processes rendering backend detection messages | |||
| 732 | - | func handleRenderingBackendMessage(payload string) bool { | |||
| 733 | - | // Parse JSON to check if this is a rendering backend detection message | |||
| 734 | - | if !strings.Contains(payload, "rendering_backend_detection") { | |||
| 735 | - | return false | |||
| 736 | - | } | |||
| 737 | - | ||||
| 738 | - | // Simple JSON parsing for the specific structure we expect | |||
| 739 | - | // {"type":"rendering_backend_detection","data":{...}} | |||
| 740 | - | var msg struct { | |||
| 741 | - | Type string `json:"type"` | |||
| 742 | - | Data struct { | |||
| 743 | - | WebGLAvailable bool `json:"webgl_available"` | |||
| 744 | - | Renderer string `json:"renderer"` | |||
| 745 | - | Vendor string `json:"vendor"` | |||
| 746 | - | Version string `json:"version"` | |||
| 747 | - | ShadingLanguageVersion string `json:"shading_language_version"` | |||
| 748 | - | MaxTextureSize int `json:"max_texture_size"` | |||
| 749 | - | HardwareAccelerated bool `json:"hardware_accelerated"` | |||
| 750 | - | } `json:"data"` | |||
| 751 | - | } | |||
| 752 | - | ||||
| 753 | - | if err := json.Unmarshal([]byte(payload), &msg); err != nil { | |||
| 754 | - | log.Printf("[webkit] Failed to parse rendering backend message: %v", err) | |||
| 755 | - | return false | |||
| 756 | - | } | |||
| 757 | - | ||||
| 758 | - | if msg.Type != "rendering_backend_detection" { | |||
| 759 | - | return false | |||
| 760 | - | } | |||
| 761 | - | ||||
| 762 | - | // Log the detected rendering backend information | |||
| 763 | - | backendType := "SOFTWARE" | |||
| 764 | - | if msg.Data.HardwareAccelerated { | |||
| 765 | - | backendType = "HARDWARE" | |||
| 766 | - | } | |||
| 767 | - | ||||
| 768 | - | log.Printf("[webkit] Detected rendering backend: %s", backendType) | |||
| 769 | - | log.Printf("[webkit] WebGL available: %v", msg.Data.WebGLAvailable) | |||
| 770 | - | log.Printf("[webkit] Renderer: %s", msg.Data.Renderer) | |||
| 771 | - | log.Printf("[webkit] Vendor: %s", msg.Data.Vendor) | |||
| 772 | - | log.Printf("[webkit] Version: %s", msg.Data.Version) | |||
| 773 | - | log.Printf("[webkit] Max texture size: %d", msg.Data.MaxTextureSize) | |||
| 774 | - | ||||
| 775 | - | return true | |||
| 776 | - | } | |||
| 777 | - | ||||
| 778 | - | // handleKeyboardBlockingMessage handles keyboard blocking control messages from omnibox | |||
| 779 | - | func handleKeyboardBlockingMessage(vw *WebView, payload string) bool { | |||
| 780 | - | if vw == nil || vw.IsDestroyed() { | |||
| 781 | - | return false | |||
| 782 | - | } | |||
| 783 | - | ||||
| 784 | - | var msg struct { | |||
| 785 | - | Type string `json:"type"` | |||
| 786 | - | Action string `json:"action"` | |||
| 787 | - | } | |||
| 788 | - | ||||
| 789 | - | if err := json.Unmarshal([]byte(payload), &msg); err != nil { | |||
| 790 | - | return false | |||
| 791 | - | } | |||
| 792 | - | ||||
| 793 | - | if msg.Type != "keyboard_blocking" { | |||
| 794 | - | return false | |||
| 795 | - | } | |||
| 796 | - | ||||
| 797 | - | switch msg.Action { | |||
| 798 | - | case "enable": | |||
| 799 | - | log.Printf("[webkit] Enabling page keyboard blocking for omnibox") | |||
| 800 | - | if err := vw.EnablePageKeyboardBlocking(); err != nil { | |||
| 801 | - | log.Printf("[webkit] Failed to enable keyboard blocking: %v", err) | |||
| 802 | - | } | |||
| 803 | - | case "disable": | |||
| 804 | - | log.Printf("[webkit] Disabling page keyboard blocking") | |||
| 805 | - | if err := vw.DisablePageKeyboardBlocking(); err != nil { | |||
| 806 | - | log.Printf("[webkit] Failed to disable keyboard blocking: %v", err) | |||
| 807 | - | } | |||
| 808 | - | default: | |||
| 809 | - | log.Printf("[webkit] Unknown keyboard blocking action: %s", msg.Action) | |||
| 810 | - | } | |||
| 811 | - | ||||
| 812 | - | return true | |||
| 813 | - | } | |||
D pkg/webkit/log_capture.go +0 -125
| @@ -1,125 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #include "log_capture.h" | |||
| 7 | - | */ | |||
| 8 | - | import "C" | |||
| 9 | - | ||||
| 10 | - | import ( | |||
| 11 | - | "time" | |||
| 12 | - | "unsafe" | |||
| 13 | - | ||||
| 14 | - | "github.com/bnema/dumber/internal/logging" | |||
| 15 | - | ) | |||
| 16 | - | ||||
| 17 | - | var webkitCaptureActive = false | |||
| 18 | - | var webkitCaptureChan chan struct{} | |||
| 19 | - | ||||
| 20 | - | //export goWebKitLogHandler | |||
| 21 | - | func goWebKitLogHandler(domain *C.char, level C.int, message *C.char) { | |||
| 22 | - | goDomain := C.GoString(domain) | |||
| 23 | - | goMessage := C.GoString(message) | |||
| 24 | - | ||||
| 25 | - | var levelStr string | |||
| 26 | - | switch level { | |||
| 27 | - | case C.G_LOG_LEVEL_ERROR: | |||
| 28 | - | levelStr = "ERROR" | |||
| 29 | - | case C.G_LOG_LEVEL_CRITICAL: | |||
| 30 | - | levelStr = "CRITICAL" | |||
| 31 | - | case C.G_LOG_LEVEL_WARNING: | |||
| 32 | - | levelStr = "WARNING" | |||
| 33 | - | case C.G_LOG_LEVEL_MESSAGE: | |||
| 34 | - | levelStr = "MESSAGE" | |||
| 35 | - | case C.G_LOG_LEVEL_INFO: | |||
| 36 | - | levelStr = "INFO" | |||
| 37 | - | case C.G_LOG_LEVEL_DEBUG: | |||
| 38 | - | levelStr = "DEBUG" | |||
| 39 | - | default: | |||
| 40 | - | levelStr = "UNKNOWN" | |||
| 41 | - | } | |||
| 42 | - | ||||
| 43 | - | logMessage := goMessage | |||
| 44 | - | if goDomain != "" { | |||
| 45 | - | logMessage = "[" + goDomain + "] " + goMessage | |||
| 46 | - | } | |||
| 47 | - | ||||
| 48 | - | // Send to logging system with appropriate level | |||
| 49 | - | if logger := logging.GetLogger(); logger != nil { | |||
| 50 | - | logger.WriteTagged("WEBKIT-"+levelStr, logMessage) | |||
| 51 | - | } | |||
| 52 | - | } | |||
| 53 | - | ||||
| 54 | - | // InitWebKitLogCapture initializes the WebKit log capture system | |||
| 55 | - | func InitWebKitLogCapture() error { | |||
| 56 | - | if webkitCaptureActive { | |||
| 57 | - | return nil | |||
| 58 | - | } | |||
| 59 | - | ||||
| 60 | - | // Initialize C-level log capture | |||
| 61 | - | C.webkit_init_log_capture() | |||
| 62 | - | ||||
| 63 | - | // Set up GLib log handlers | |||
| 64 | - | C.webkit_setup_glib_log_handlers() | |||
| 65 | - | ||||
| 66 | - | // Create channel for stopping capture | |||
| 67 | - | webkitCaptureChan = make(chan struct{}) | |||
| 68 | - | ||||
| 69 | - | // Start goroutine to read captured C output | |||
| 70 | - | go webkitLogReader() | |||
| 71 | - | ||||
| 72 | - | webkitCaptureActive = true | |||
| 73 | - | return nil | |||
| 74 | - | } | |||
| 75 | - | ||||
| 76 | - | // StopWebKitLogCapture stops the WebKit log capture | |||
| 77 | - | func StopWebKitLogCapture() { | |||
| 78 | - | if !webkitCaptureActive { | |||
| 79 | - | return | |||
| 80 | - | } | |||
| 81 | - | ||||
| 82 | - | // Signal the reader goroutine to stop | |||
| 83 | - | close(webkitCaptureChan) | |||
| 84 | - | ||||
| 85 | - | // Stop C-level capture | |||
| 86 | - | C.webkit_stop_log_capture() | |||
| 87 | - | ||||
| 88 | - | webkitCaptureActive = false | |||
| 89 | - | } | |||
| 90 | - | ||||
| 91 | - | // webkitLogReader reads captured C output in a goroutine | |||
| 92 | - | func webkitLogReader() { | |||
| 93 | - | buffer := make([]byte, 4096) | |||
| 94 | - | ||||
| 95 | - | for { | |||
| 96 | - | select { | |||
| 97 | - | case <-webkitCaptureChan: | |||
| 98 | - | return | |||
| 99 | - | default: | |||
| 100 | - | // Try to read captured output | |||
| 101 | - | n := int(C.webkit_read_captured_log((*C.char)(unsafe.Pointer(&buffer[0])), C.int(len(buffer)))) | |||
| 102 | - | if n > 0 { | |||
| 103 | - | message := string(buffer[:n]) | |||
| 104 | - | if logger := logging.GetLogger(); logger != nil { | |||
| 105 | - | logger.WriteTagged("WEBKIT-PRINTF", message) | |||
| 106 | - | } | |||
| 107 | - | } | |||
| 108 | - | ||||
| 109 | - | // Small delay to prevent busy waiting | |||
| 110 | - | time.Sleep(10 * time.Millisecond) | |||
| 111 | - | } | |||
| 112 | - | } | |||
| 113 | - | } | |||
| 114 | - | ||||
| 115 | - | // StartWebKitOutputCapture starts capturing webkit stdout/stderr | |||
| 116 | - | func StartWebKitOutputCapture() { | |||
| 117 | - | if webkitCaptureActive { | |||
| 118 | - | C.webkit_start_log_capture() | |||
| 119 | - | } | |||
| 120 | - | } | |||
| 121 | - | ||||
| 122 | - | // IsWebKitLogCaptureActive returns whether WebKit log capture is active | |||
| 123 | - | func IsWebKitLogCaptureActive() bool { | |||
| 124 | - | return webkitCaptureActive | |||
| 125 | - | } | |||
D pkg/webkit/log_capture.h +0 -108
| @@ -1,108 +0,0 @@ | |||||
| 1 | - | #ifndef WEBKIT_LOG_CAPTURE_H | |||
| 2 | - | #define WEBKIT_LOG_CAPTURE_H | |||
| 3 | - | ||||
| 4 | - | #include <stdio.h> | |||
| 5 | - | #include <stdlib.h> | |||
| 6 | - | #include <string.h> | |||
| 7 | - | #include <unistd.h> | |||
| 8 | - | #include <glib.h> | |||
| 9 | - | ||||
| 10 | - | static int webkit_log_pipe[2]; | |||
| 11 | - | static FILE* webkit_original_stdout; | |||
| 12 | - | static FILE* webkit_original_stderr; | |||
| 13 | - | static gboolean webkit_capture_enabled = FALSE; | |||
| 14 | - | ||||
| 15 | - | // Initialize log capture pipes | |||
| 16 | - | static inline void webkit_init_log_capture() { | |||
| 17 | - | if (webkit_capture_enabled) return; | |||
| 18 | - | ||||
| 19 | - | // Create pipe for capturing C output | |||
| 20 | - | if (pipe(webkit_log_pipe) == 0) { | |||
| 21 | - | // Duplicate stdout/stderr for restoration later | |||
| 22 | - | webkit_original_stdout = fdopen(dup(1), "w"); | |||
| 23 | - | webkit_original_stderr = fdopen(dup(2), "w"); | |||
| 24 | - | webkit_capture_enabled = TRUE; | |||
| 25 | - | ||||
| 26 | - | g_debug("WebKit log capture initialized"); | |||
| 27 | - | } else { | |||
| 28 | - | g_warning("Failed to initialize WebKit log capture"); | |||
| 29 | - | } | |||
| 30 | - | } | |||
| 31 | - | ||||
| 32 | - | // Start capturing WebKit output | |||
| 33 | - | static inline void webkit_start_log_capture() { | |||
| 34 | - | if (!webkit_capture_enabled) return; | |||
| 35 | - | ||||
| 36 | - | // Redirect stdout/stderr to pipe (for C printf statements) | |||
| 37 | - | dup2(webkit_log_pipe[1], 1); | |||
| 38 | - | dup2(webkit_log_pipe[1], 2); | |||
| 39 | - | } | |||
| 40 | - | ||||
| 41 | - | // Stop capturing and restore original output | |||
| 42 | - | static inline void webkit_stop_log_capture() { | |||
| 43 | - | if (!webkit_capture_enabled) return; | |||
| 44 | - | ||||
| 45 | - | // Restore original stdout/stderr | |||
| 46 | - | if (webkit_original_stdout) { | |||
| 47 | - | dup2(fileno(webkit_original_stdout), 1); | |||
| 48 | - | fclose(webkit_original_stdout); | |||
| 49 | - | } | |||
| 50 | - | if (webkit_original_stderr) { | |||
| 51 | - | dup2(fileno(webkit_original_stderr), 2); | |||
| 52 | - | fclose(webkit_original_stderr); | |||
| 53 | - | } | |||
| 54 | - | ||||
| 55 | - | close(webkit_log_pipe[0]); | |||
| 56 | - | close(webkit_log_pipe[1]); | |||
| 57 | - | webkit_capture_enabled = FALSE; | |||
| 58 | - | } | |||
| 59 | - | ||||
| 60 | - | // Read captured output (non-blocking) | |||
| 61 | - | static inline int webkit_read_captured_log(char* buffer, int buffer_size) { | |||
| 62 | - | if (!webkit_capture_enabled) return 0; | |||
| 63 | - | ||||
| 64 | - | fd_set read_fds; | |||
| 65 | - | struct timeval timeout; | |||
| 66 | - | ||||
| 67 | - | FD_ZERO(&read_fds); | |||
| 68 | - | FD_SET(webkit_log_pipe[0], &read_fds); | |||
| 69 | - | ||||
| 70 | - | // Non-blocking check | |||
| 71 | - | timeout.tv_sec = 0; | |||
| 72 | - | timeout.tv_usec = 0; | |||
| 73 | - | ||||
| 74 | - | int result = select(webkit_log_pipe[0] + 1, &read_fds, NULL, NULL, &timeout); | |||
| 75 | - | if (result > 0 && FD_ISSET(webkit_log_pipe[0], &read_fds)) { | |||
| 76 | - | int n = read(webkit_log_pipe[0], buffer, buffer_size - 1); | |||
| 77 | - | if (n > 0) { | |||
| 78 | - | buffer[n] = '\0'; | |||
| 79 | - | return n; | |||
| 80 | - | } | |||
| 81 | - | } | |||
| 82 | - | return 0; | |||
| 83 | - | } | |||
| 84 | - | ||||
| 85 | - | // GLib log handler to capture GLib/GTK/WebKit messages | |||
| 86 | - | static inline void webkit_glib_log_handler(const gchar *log_domain, | |||
| 87 | - | GLogLevelFlags log_level, | |||
| 88 | - | const gchar *message, | |||
| 89 | - | gpointer user_data) { | |||
| 90 | - | // Forward to Go callback | |||
| 91 | - | extern void goWebKitLogHandler(char* domain, int level, char* message); | |||
| 92 | - | goWebKitLogHandler((char*)log_domain, (int)log_level, (char*)message); | |||
| 93 | - | } | |||
| 94 | - | ||||
| 95 | - | // Set up GLib log handlers for various domains | |||
| 96 | - | static inline void webkit_setup_glib_log_handlers() { | |||
| 97 | - | // Set up log handlers for WebKit and GTK domains | |||
| 98 | - | g_log_set_handler("WebKit", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION, | |||
| 99 | - | webkit_glib_log_handler, NULL); | |||
| 100 | - | g_log_set_handler("Gtk", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION, | |||
| 101 | - | webkit_glib_log_handler, NULL); | |||
| 102 | - | g_log_set_handler("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION, | |||
| 103 | - | webkit_glib_log_handler, NULL); | |||
| 104 | - | g_log_set_handler(NULL, G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION, | |||
| 105 | - | webkit_glib_log_handler, NULL); | |||
| 106 | - | } | |||
| 107 | - | ||||
| 108 | - | #endif // WEBKIT_LOG_CAPTURE_H⏎̸ | |||
D pkg/webkit/log_capture_stub.go +0 -24
| @@ -1,24 +0,0 @@ | |||||
| 1 | - | //go:build !webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | // InitWebKitLogCapture initializes the WebKit log capture system (stub version) | |||
| 6 | - | func InitWebKitLogCapture() error { | |||
| 7 | - | // No-op for stub version | |||
| 8 | - | return nil | |||
| 9 | - | } | |||
| 10 | - | ||||
| 11 | - | // StopWebKitLogCapture stops the WebKit log capture (stub version) | |||
| 12 | - | func StopWebKitLogCapture() { | |||
| 13 | - | // No-op for stub version | |||
| 14 | - | } | |||
| 15 | - | ||||
| 16 | - | // StartWebKitOutputCapture starts capturing webkit stdout/stderr (stub version) | |||
| 17 | - | func StartWebKitOutputCapture() { | |||
| 18 | - | // No-op for stub version | |||
| 19 | - | } | |||
| 20 | - | ||||
| 21 | - | // IsWebKitLogCaptureActive returns whether WebKit log capture is active (stub version) | |||
| 22 | - | func IsWebKitLogCaptureActive() bool { | |||
| 23 | - | return false | |||
| 24 | - | } | |||
D pkg/webkit/loop.go +0 -13
| @@ -1,13 +0,0 @@ | |||||
| 1 | - | //go:build !webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | import "log" | |||
| 6 | - | ||||
| 7 | - | // RunMainLoop is a no-op in non-CGO builds. | |||
| 8 | - | func RunMainLoop() { | |||
| 9 | - | log.Printf("[webkit] RunMainLoop (non-CGO): no GUI loop available") | |||
| 10 | - | } | |||
| 11 | - | ||||
| 12 | - | // QuitMainLoop is a no-op in non-CGO builds. | |||
| 13 | - | func QuitMainLoop() {} | |||
D pkg/webkit/loop_cgo.go +0 -27
| @@ -1,27 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #cgo pkg-config: gtk4 | |||
| 7 | - | #include <gtk/gtk.h> | |||
| 8 | - | #include <glib.h> | |||
| 9 | - | */ | |||
| 10 | - | import "C" | |||
| 11 | - | ||||
| 12 | - | var mainLoop *C.GMainLoop | |||
| 13 | - | ||||
| 14 | - | // RunMainLoop enters the GLib main loop (GTK4) and blocks until quit. | |||
| 15 | - | func RunMainLoop() { | |||
| 16 | - | if mainLoop == nil { | |||
| 17 | - | mainLoop = C.g_main_loop_new(nil, C.gboolean(0)) | |||
| 18 | - | } | |||
| 19 | - | C.g_main_loop_run(mainLoop) | |||
| 20 | - | } | |||
| 21 | - | ||||
| 22 | - | // QuitMainLoop requests the main loop to exit. | |||
| 23 | - | func QuitMainLoop() { | |||
| 24 | - | if mainLoop != nil { | |||
| 25 | - | C.g_main_loop_quit(mainLoop) | |||
| 26 | - | } | |||
| 27 | - | } | |||
A pkg/webkit/mainloop.go +62 -0
| @@ -0,0 +1,62 @@ | |||||
| 1 | + | package webkit | |||
| 2 | + | ||||
| 3 | + | import ( | |||
| 4 | + | "runtime" | |||
| 5 | + | ||||
| 6 | + | "github.com/diamondburned/gotk4/pkg/glib/v2" | |||
| 7 | + | ) | |||
| 8 | + | ||||
| 9 | + | var ( | |||
| 10 | + | mainLoop *glib.MainLoop | |||
| 11 | + | mainThreadID = runtime.LockOSThread // Store the main thread | |||
| 12 | + | isInitialized bool | |||
| 13 | + | ) | |||
| 14 | + | ||||
| 15 | + | // InitMainThread locks the current goroutine to the OS thread for GTK operations. | |||
| 16 | + | // This must be called before any GTK operations. | |||
| 17 | + | func InitMainThread() { | |||
| 18 | + | if !isInitialized { | |||
| 19 | + | runtime.LockOSThread() | |||
| 20 | + | isInitialized = true | |||
| 21 | + | } | |||
| 22 | + | } | |||
| 23 | + | ||||
| 24 | + | // RunMainLoop starts the GTK main event loop. | |||
| 25 | + | // This function blocks until QuitMainLoop is called. | |||
| 26 | + | func RunMainLoop() { | |||
| 27 | + | InitMainThread() | |||
| 28 | + | ||||
| 29 | + | if mainLoop == nil { | |||
| 30 | + | mainLoop = glib.NewMainLoop(nil, false) | |||
| 31 | + | } | |||
| 32 | + | ||||
| 33 | + | mainLoop.Run() | |||
| 34 | + | } | |||
| 35 | + | ||||
| 36 | + | // QuitMainLoop stops the GTK main event loop. | |||
| 37 | + | func QuitMainLoop() { | |||
| 38 | + | if mainLoop != nil { | |||
| 39 | + | mainLoop.Quit() | |||
| 40 | + | } | |||
| 41 | + | } | |||
| 42 | + | ||||
| 43 | + | // IsMainThread returns true if called from the GTK main thread. | |||
| 44 | + | func IsMainThread() bool { | |||
| 45 | + | // In gotk4, we're always on the main thread since we lock it | |||
| 46 | + | return isInitialized | |||
| 47 | + | } | |||
| 48 | + | ||||
| 49 | + | // RunOnMainThread executes a function on the GTK main thread. | |||
| 50 | + | // If already on the main thread, executes immediately. | |||
| 51 | + | // Otherwise, schedules the function via glib.IdleAdd. | |||
| 52 | + | func RunOnMainThread(fn func()) { | |||
| 53 | + | if IsMainThread() { | |||
| 54 | + | fn() | |||
| 55 | + | return | |||
| 56 | + | } | |||
| 57 | + | ||||
| 58 | + | glib.IdleAdd(func() bool { | |||
| 59 | + | fn() | |||
| 60 | + | return false // Remove the idle handler after execution | |||
| 61 | + | }) | |||
| 62 | + | } | |||
D pkg/webkit/memory.go +0 -286
| @@ -1,286 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | import ( | |||
| 6 | - | "fmt" | |||
| 7 | - | "log" | |||
| 8 | - | "os" | |||
| 9 | - | "strconv" | |||
| 10 | - | "strings" | |||
| 11 | - | "time" | |||
| 12 | - | ) | |||
| 13 | - | ||||
| 14 | - | // ProcessMemoryInfo contains memory information for a WebKit process | |||
| 15 | - | type ProcessMemoryInfo struct { | |||
| 16 | - | PID int `json:"pid"` | |||
| 17 | - | VmRSS int64 `json:"vm_rss"` // Resident Set Size in KB | |||
| 18 | - | VmSize int64 `json:"vm_size"` // Virtual Memory Size in KB | |||
| 19 | - | VmPeak int64 `json:"vm_peak"` // Peak Virtual Memory in KB | |||
| 20 | - | ProcessName string `json:"process_name"` | |||
| 21 | - | } | |||
| 22 | - | ||||
| 23 | - | // WebViewMemoryManager handles memory monitoring and lifecycle management for WebViews | |||
| 24 | - | type WebViewMemoryManager struct { | |||
| 25 | - | views map[uintptr]*WebView | |||
| 26 | - | enableMonitoring bool | |||
| 27 | - | recycleThreshold int | |||
| 28 | - | monitoringInterval time.Duration | |||
| 29 | - | stopMonitoring chan struct{} | |||
| 30 | - | lastLoggedMemory int64 | |||
| 31 | - | } | |||
| 32 | - | ||||
| 33 | - | // NewWebViewMemoryManager creates a new memory manager | |||
| 34 | - | func NewWebViewMemoryManager(enableMonitoring bool, recycleThreshold int, monitoringInterval time.Duration) *WebViewMemoryManager { | |||
| 35 | - | return &WebViewMemoryManager{ | |||
| 36 | - | views: make(map[uintptr]*WebView), | |||
| 37 | - | enableMonitoring: enableMonitoring, | |||
| 38 | - | recycleThreshold: recycleThreshold, | |||
| 39 | - | monitoringInterval: monitoringInterval, | |||
| 40 | - | stopMonitoring: make(chan struct{}), | |||
| 41 | - | } | |||
| 42 | - | } | |||
| 43 | - | ||||
| 44 | - | // RegisterWebView registers a WebView for monitoring | |||
| 45 | - | func (mgr *WebViewMemoryManager) RegisterWebView(view *WebView) { | |||
| 46 | - | if mgr == nil || view == nil { | |||
| 47 | - | return | |||
| 48 | - | } | |||
| 49 | - | mgr.views[view.id] = view | |||
| 50 | - | ||||
| 51 | - | if mgr.enableMonitoring && len(mgr.views) == 1 { | |||
| 52 | - | // Start monitoring when first view is registered | |||
| 53 | - | go mgr.startMemoryMonitoring() | |||
| 54 | - | } | |||
| 55 | - | } | |||
| 56 | - | ||||
| 57 | - | // UnregisterWebView removes a WebView from monitoring | |||
| 58 | - | func (mgr *WebViewMemoryManager) UnregisterWebView(viewID uintptr) { | |||
| 59 | - | if mgr == nil { | |||
| 60 | - | return | |||
| 61 | - | } | |||
| 62 | - | delete(mgr.views, viewID) | |||
| 63 | - | ||||
| 64 | - | if len(mgr.views) == 0 { | |||
| 65 | - | // Stop monitoring when no views left | |||
| 66 | - | close(mgr.stopMonitoring) | |||
| 67 | - | mgr.stopMonitoring = make(chan struct{}) | |||
| 68 | - | } | |||
| 69 | - | } | |||
| 70 | - | ||||
| 71 | - | // startMemoryMonitoring starts the background memory monitoring routine | |||
| 72 | - | func (mgr *WebViewMemoryManager) startMemoryMonitoring() { | |||
| 73 | - | if mgr == nil || mgr.monitoringInterval <= 0 { | |||
| 74 | - | return | |||
| 75 | - | } | |||
| 76 | - | ||||
| 77 | - | ticker := time.NewTicker(mgr.monitoringInterval) | |||
| 78 | - | defer ticker.Stop() | |||
| 79 | - | ||||
| 80 | - | for { | |||
| 81 | - | select { | |||
| 82 | - | case <-ticker.C: | |||
| 83 | - | mgr.checkMemoryUsage() | |||
| 84 | - | case <-mgr.stopMonitoring: | |||
| 85 | - | return | |||
| 86 | - | } | |||
| 87 | - | } | |||
| 88 | - | } | |||
| 89 | - | ||||
| 90 | - | // checkMemoryUsage monitors memory usage of WebKit processes | |||
| 91 | - | func (mgr *WebViewMemoryManager) checkMemoryUsage() { | |||
| 92 | - | if mgr == nil { | |||
| 93 | - | return | |||
| 94 | - | } | |||
| 95 | - | ||||
| 96 | - | processes, err := mgr.getWebKitProcesses() | |||
| 97 | - | if err != nil { | |||
| 98 | - | if mgr.enableMonitoring { | |||
| 99 | - | log.Printf("[webkit] Error monitoring processes: %v", err) | |||
| 100 | - | } | |||
| 101 | - | return | |||
| 102 | - | } | |||
| 103 | - | ||||
| 104 | - | totalMemory := int64(0) | |||
| 105 | - | for _, proc := range processes { | |||
| 106 | - | totalMemory += proc.VmRSS | |||
| 107 | - | } | |||
| 108 | - | ||||
| 109 | - | // Only log if memory usage changed by more than 10MB (10240 KB) | |||
| 110 | - | const memoryChangeThreshold = 10240 // 10MB in KB | |||
| 111 | - | if mgr.enableMonitoring { | |||
| 112 | - | memoryDiff := totalMemory - mgr.lastLoggedMemory | |||
| 113 | - | if memoryDiff < 0 { | |||
| 114 | - | memoryDiff = -memoryDiff | |||
| 115 | - | } | |||
| 116 | - | ||||
| 117 | - | if mgr.lastLoggedMemory == 0 || memoryDiff >= memoryChangeThreshold { | |||
| 118 | - | log.Printf("[webkit] Memory usage: %d processes, total %.1f MB RSS", | |||
| 119 | - | len(processes), float64(totalMemory)/1024.0) | |||
| 120 | - | mgr.lastLoggedMemory = totalMemory | |||
| 121 | - | } | |||
| 122 | - | } | |||
| 123 | - | ||||
| 124 | - | // Check for recycling needs | |||
| 125 | - | for _, view := range mgr.views { | |||
| 126 | - | if view.memStats != nil && mgr.recycleThreshold > 0 { | |||
| 127 | - | if view.memStats.pageLoadCount >= mgr.recycleThreshold { | |||
| 128 | - | if mgr.enableMonitoring { | |||
| 129 | - | log.Printf("[webkit] WebView %d needs recycling (%d pages loaded)", | |||
| 130 | - | view.id, view.memStats.pageLoadCount) | |||
| 131 | - | } | |||
| 132 | - | } | |||
| 133 | - | } | |||
| 134 | - | } | |||
| 135 | - | } | |||
| 136 | - | ||||
| 137 | - | // getWebKitProcesses returns memory info for all WebKit-related processes | |||
| 138 | - | func (mgr *WebViewMemoryManager) getWebKitProcesses() ([]ProcessMemoryInfo, error) { | |||
| 139 | - | var processes []ProcessMemoryInfo | |||
| 140 | - | ||||
| 141 | - | // Find all WebKit processes by scanning /proc | |||
| 142 | - | procDir, err := os.ReadDir("/proc") | |||
| 143 | - | if err != nil { | |||
| 144 | - | return nil, fmt.Errorf("failed to read /proc: %w", err) | |||
| 145 | - | } | |||
| 146 | - | ||||
| 147 | - | for _, entry := range procDir { | |||
| 148 | - | if !entry.IsDir() { | |||
| 149 | - | continue | |||
| 150 | - | } | |||
| 151 | - | ||||
| 152 | - | pid, err := strconv.Atoi(entry.Name()) | |||
| 153 | - | if err != nil { | |||
| 154 | - | continue // Not a PID directory | |||
| 155 | - | } | |||
| 156 | - | ||||
| 157 | - | // Check if this is a WebKit process | |||
| 158 | - | cmdlinePath := fmt.Sprintf("/proc/%d/cmdline", pid) | |||
| 159 | - | cmdlineBytes, err := os.ReadFile(cmdlinePath) | |||
| 160 | - | if err != nil { | |||
| 161 | - | continue // Process might have exited | |||
| 162 | - | } | |||
| 163 | - | ||||
| 164 | - | cmdline := string(cmdlineBytes) | |||
| 165 | - | if !strings.Contains(cmdline, "WebKit") && !strings.Contains(cmdline, "dumber") { | |||
| 166 | - | continue // Not a WebKit or dumber process | |||
| 167 | - | } | |||
| 168 | - | ||||
| 169 | - | // Get memory information | |||
| 170 | - | statusPath := fmt.Sprintf("/proc/%d/status", pid) | |||
| 171 | - | statusData, err := os.ReadFile(statusPath) | |||
| 172 | - | if err != nil { | |||
| 173 | - | continue | |||
| 174 | - | } | |||
| 175 | - | ||||
| 176 | - | memInfo := mgr.parseMemoryStatus(string(statusData), pid) | |||
| 177 | - | if memInfo != nil { | |||
| 178 | - | // Extract process name from cmdline | |||
| 179 | - | parts := strings.Split(cmdline, "\x00") | |||
| 180 | - | if len(parts) > 0 { | |||
| 181 | - | memInfo.ProcessName = parts[0] | |||
| 182 | - | } | |||
| 183 | - | processes = append(processes, *memInfo) | |||
| 184 | - | } | |||
| 185 | - | } | |||
| 186 | - | ||||
| 187 | - | return processes, nil | |||
| 188 | - | } | |||
| 189 | - | ||||
| 190 | - | // parseMemoryStatus parses /proc/[pid]/status for memory information | |||
| 191 | - | func (mgr *WebViewMemoryManager) parseMemoryStatus(status string, pid int) *ProcessMemoryInfo { | |||
| 192 | - | lines := strings.Split(status, "\n") | |||
| 193 | - | info := &ProcessMemoryInfo{PID: pid} | |||
| 194 | - | ||||
| 195 | - | for _, line := range lines { | |||
| 196 | - | if strings.HasPrefix(line, "VmRSS:") { | |||
| 197 | - | if val := mgr.extractMemoryValue(line); val > 0 { | |||
| 198 | - | info.VmRSS = val | |||
| 199 | - | } | |||
| 200 | - | } else if strings.HasPrefix(line, "VmSize:") { | |||
| 201 | - | if val := mgr.extractMemoryValue(line); val > 0 { | |||
| 202 | - | info.VmSize = val | |||
| 203 | - | } | |||
| 204 | - | } else if strings.HasPrefix(line, "VmPeak:") { | |||
| 205 | - | if val := mgr.extractMemoryValue(line); val > 0 { | |||
| 206 | - | info.VmPeak = val | |||
| 207 | - | } | |||
| 208 | - | } | |||
| 209 | - | } | |||
| 210 | - | ||||
| 211 | - | // Only return if we found at least VmRSS | |||
| 212 | - | if info.VmRSS > 0 { | |||
| 213 | - | return info | |||
| 214 | - | } | |||
| 215 | - | ||||
| 216 | - | return nil | |||
| 217 | - | } | |||
| 218 | - | ||||
| 219 | - | // extractMemoryValue extracts memory value in KB from status lines like "VmRSS: 12345 kB" | |||
| 220 | - | func (mgr *WebViewMemoryManager) extractMemoryValue(line string) int64 { | |||
| 221 | - | parts := strings.Fields(line) | |||
| 222 | - | if len(parts) >= 2 { | |||
| 223 | - | val, err := strconv.ParseInt(parts[1], 10, 64) | |||
| 224 | - | if err == nil { | |||
| 225 | - | return val | |||
| 226 | - | } | |||
| 227 | - | } | |||
| 228 | - | return 0 | |||
| 229 | - | } | |||
| 230 | - | ||||
| 231 | - | // GetTotalMemoryUsage returns total memory usage of all WebKit processes in MB | |||
| 232 | - | func (mgr *WebViewMemoryManager) GetTotalMemoryUsage() (float64, error) { | |||
| 233 | - | if mgr == nil { | |||
| 234 | - | return 0, fmt.Errorf("memory manager is nil") | |||
| 235 | - | } | |||
| 236 | - | ||||
| 237 | - | processes, err := mgr.getWebKitProcesses() | |||
| 238 | - | if err != nil { | |||
| 239 | - | return 0, err | |||
| 240 | - | } | |||
| 241 | - | ||||
| 242 | - | totalKB := int64(0) | |||
| 243 | - | for _, proc := range processes { | |||
| 244 | - | totalKB += proc.VmRSS | |||
| 245 | - | } | |||
| 246 | - | ||||
| 247 | - | return float64(totalKB) / 1024.0, nil | |||
| 248 | - | } | |||
| 249 | - | ||||
| 250 | - | // GetDetailedMemoryInfo returns detailed memory information for all WebKit processes | |||
| 251 | - | func (mgr *WebViewMemoryManager) GetDetailedMemoryInfo() ([]ProcessMemoryInfo, error) { | |||
| 252 | - | if mgr == nil { | |||
| 253 | - | return nil, fmt.Errorf("memory manager is nil") | |||
| 254 | - | } | |||
| 255 | - | ||||
| 256 | - | return mgr.getWebKitProcesses() | |||
| 257 | - | } | |||
| 258 | - | ||||
| 259 | - | // ShouldRecycleWebView checks if a WebView should be recycled based on memory pressure | |||
| 260 | - | func (mgr *WebViewMemoryManager) ShouldRecycleWebView(view *WebView) bool { | |||
| 261 | - | if mgr == nil || view == nil || view.memStats == nil { | |||
| 262 | - | return false | |||
| 263 | - | } | |||
| 264 | - | ||||
| 265 | - | if mgr.recycleThreshold > 0 && view.memStats.pageLoadCount >= mgr.recycleThreshold { | |||
| 266 | - | return true | |||
| 267 | - | } | |||
| 268 | - | ||||
| 269 | - | return false | |||
| 270 | - | } | |||
| 271 | - | ||||
| 272 | - | // Global memory manager instance | |||
| 273 | - | var globalMemoryManager *WebViewMemoryManager | |||
| 274 | - | ||||
| 275 | - | // InitializeGlobalMemoryManager initializes the global memory manager | |||
| 276 | - | func InitializeGlobalMemoryManager(enableMonitoring bool, recycleThreshold int, monitoringInterval time.Duration) { | |||
| 277 | - | if monitoringInterval == 0 { | |||
| 278 | - | monitoringInterval = 30 * time.Second // Default 30 seconds | |||
| 279 | - | } | |||
| 280 | - | globalMemoryManager = NewWebViewMemoryManager(enableMonitoring, recycleThreshold, monitoringInterval) | |||
| 281 | - | } | |||
| 282 | - | ||||
| 283 | - | // GetGlobalMemoryManager returns the global memory manager | |||
| 284 | - | func GetGlobalMemoryManager() *WebViewMemoryManager { | |||
| 285 | - | return globalMemoryManager | |||
| 286 | - | } | |||
D pkg/webkit/memory_example.go +0 -189
| @@ -1,189 +0,0 @@ | |||||
| 1 | - | package webkit | |||
| 2 | - | ||||
| 3 | - | // GetMemoryOptimizedConfig returns a Config optimized for low memory usage | |||
| 4 | - | // This configuration aims to reduce memory usage by 40-60% compared to defaults | |||
| 5 | - | func GetMemoryOptimizedConfig() *Config { | |||
| 6 | - | return &Config{ | |||
| 7 | - | Memory: MemoryConfig{ | |||
| 8 | - | // Limit each WebView to 256MB (default: unlimited) | |||
| 9 | - | MemoryLimitMB: 256, | |||
| 10 | - | ||||
| 11 | - | // Aggressive memory pressure thresholds | |||
| 12 | - | ConservativeThreshold: 0.2, // Trigger cleanup at 20% (default: 33%) | |||
| 13 | - | StrictThreshold: 0.35, // Aggressive cleanup at 35% (default: 50%) | |||
| 14 | - | KillThreshold: 0.8, // Kill process at 80% to prevent OOM | |||
| 15 | - | ||||
| 16 | - | // Check memory usage every 2 seconds | |||
| 17 | - | PollIntervalSeconds: 2.0, | |||
| 18 | - | ||||
| 19 | - | // Use minimal caching for lowest memory usage | |||
| 20 | - | CacheModel: CacheModelDocumentViewer, | |||
| 21 | - | ||||
| 22 | - | // Disable memory-intensive caches | |||
| 23 | - | EnablePageCache: false, // Saves ~30-50MB but slower back/forward | |||
| 24 | - | EnableOfflineAppCache: false, // Saves ~10-20MB | |||
| 25 | - | ||||
| 26 | - | // Recycle WebView after 50 page loads to prevent memory accumulation | |||
| 27 | - | ProcessRecycleThreshold: 50, | |||
| 28 | - | ||||
| 29 | - | // Trigger JavaScript GC every 60 seconds | |||
| 30 | - | EnableGCInterval: 60, | |||
| 31 | - | ||||
| 32 | - | // Enable detailed memory monitoring and logging | |||
| 33 | - | EnableMemoryMonitoring: true, | |||
| 34 | - | }, | |||
| 35 | - | ||||
| 36 | - | // Disable developer tools to save memory (unless debugging) | |||
| 37 | - | EnableDeveloperExtras: false, | |||
| 38 | - | ||||
| 39 | - | // Use CPU rendering to save GPU memory (trade-off: slower rendering) | |||
| 40 | - | Rendering: RenderingConfig{ | |||
| 41 | - | Mode: "cpu", | |||
| 42 | - | }, | |||
| 43 | - | } | |||
| 44 | - | } | |||
| 45 | - | ||||
| 46 | - | // GetBalancedConfig returns a Config with moderate memory optimizations | |||
| 47 | - | // This configuration aims to reduce memory usage by 20-30% with minimal performance impact | |||
| 48 | - | func GetBalancedConfig() *Config { | |||
| 49 | - | return &Config{ | |||
| 50 | - | Memory: MemoryConfig{ | |||
| 51 | - | // Limit each WebView to 512MB | |||
| 52 | - | MemoryLimitMB: 512, | |||
| 53 | - | ||||
| 54 | - | // Moderate memory pressure thresholds | |||
| 55 | - | ConservativeThreshold: 0.25, | |||
| 56 | - | StrictThreshold: 0.4, | |||
| 57 | - | KillThreshold: 0.7, | |||
| 58 | - | ||||
| 59 | - | PollIntervalSeconds: 5.0, | |||
| 60 | - | ||||
| 61 | - | // Use default web browser caching | |||
| 62 | - | CacheModel: CacheModelWebBrowser, | |||
| 63 | - | ||||
| 64 | - | // Keep page cache but disable offline app cache | |||
| 65 | - | EnablePageCache: true, | |||
| 66 | - | EnableOfflineAppCache: false, | |||
| 67 | - | ||||
| 68 | - | // Recycle after more page loads | |||
| 69 | - | ProcessRecycleThreshold: 100, | |||
| 70 | - | ||||
| 71 | - | // Less frequent GC | |||
| 72 | - | EnableGCInterval: 120, | |||
| 73 | - | ||||
| 74 | - | EnableMemoryMonitoring: true, | |||
| 75 | - | }, | |||
| 76 | - | ||||
| 77 | - | EnableDeveloperExtras: false, | |||
| 78 | - | ||||
| 79 | - | // Use auto rendering (WebKit decides GPU vs CPU) | |||
| 80 | - | Rendering: RenderingConfig{ | |||
| 81 | - | Mode: "auto", | |||
| 82 | - | }, | |||
| 83 | - | } | |||
| 84 | - | } | |||
| 85 | - | ||||
| 86 | - | // GetHighPerformanceConfig returns a Config optimized for performance over memory | |||
| 87 | - | // This uses default/high memory settings for maximum performance | |||
| 88 | - | func GetHighPerformanceConfig() *Config { | |||
| 89 | - | return &Config{ | |||
| 90 | - | Memory: MemoryConfig{ | |||
| 91 | - | // No memory limit (use system default) | |||
| 92 | - | MemoryLimitMB: 0, | |||
| 93 | - | ||||
| 94 | - | // Relaxed memory pressure thresholds | |||
| 95 | - | ConservativeThreshold: 0.4, | |||
| 96 | - | StrictThreshold: 0.6, | |||
| 97 | - | KillThreshold: 0, // Disable kill threshold | |||
| 98 | - | ||||
| 99 | - | PollIntervalSeconds: 10.0, | |||
| 100 | - | ||||
| 101 | - | // Maximum caching for best performance | |||
| 102 | - | CacheModel: CacheModelPrimaryWebBrowser, | |||
| 103 | - | ||||
| 104 | - | // Enable all caches | |||
| 105 | - | EnablePageCache: true, | |||
| 106 | - | EnableOfflineAppCache: true, | |||
| 107 | - | ||||
| 108 | - | // Disable recycling | |||
| 109 | - | ProcessRecycleThreshold: 0, | |||
| 110 | - | ||||
| 111 | - | // Disable periodic GC | |||
| 112 | - | EnableGCInterval: 0, | |||
| 113 | - | ||||
| 114 | - | EnableMemoryMonitoring: false, | |||
| 115 | - | }, | |||
| 116 | - | ||||
| 117 | - | EnableDeveloperExtras: true, | |||
| 118 | - | ||||
| 119 | - | // Use GPU rendering for best performance | |||
| 120 | - | Rendering: RenderingConfig{ | |||
| 121 | - | Mode: "gpu", | |||
| 122 | - | }, | |||
| 123 | - | } | |||
| 124 | - | } | |||
| 125 | - | ||||
| 126 | - | // ValidateMemoryConfig validates memory configuration parameters | |||
| 127 | - | func ValidateMemoryConfig(config *MemoryConfig) error { | |||
| 128 | - | if config == nil { | |||
| 129 | - | return nil // Use defaults | |||
| 130 | - | } | |||
| 131 | - | ||||
| 132 | - | if config.ConservativeThreshold < 0 || config.ConservativeThreshold > 1 { | |||
| 133 | - | return &ValidationError{Field: "ConservativeThreshold", Message: "must be between 0.0 and 1.0"} | |||
| 134 | - | } | |||
| 135 | - | ||||
| 136 | - | if config.StrictThreshold < 0 || config.StrictThreshold > 1 { | |||
| 137 | - | return &ValidationError{Field: "StrictThreshold", Message: "must be between 0.0 and 1.0"} | |||
| 138 | - | } | |||
| 139 | - | ||||
| 140 | - | if config.KillThreshold < 0 || config.KillThreshold > 1 { | |||
| 141 | - | return &ValidationError{Field: "KillThreshold", Message: "must be between 0.0 and 1.0"} | |||
| 142 | - | } | |||
| 143 | - | ||||
| 144 | - | if config.ConservativeThreshold >= config.StrictThreshold { | |||
| 145 | - | return &ValidationError{Field: "StrictThreshold", Message: "must be greater than ConservativeThreshold"} | |||
| 146 | - | } | |||
| 147 | - | ||||
| 148 | - | if config.PollIntervalSeconds < 0 { | |||
| 149 | - | return &ValidationError{Field: "PollIntervalSeconds", Message: "must be non-negative"} | |||
| 150 | - | } | |||
| 151 | - | ||||
| 152 | - | return nil | |||
| 153 | - | } | |||
| 154 | - | ||||
| 155 | - | // ValidationError represents a configuration validation error | |||
| 156 | - | type ValidationError struct { | |||
| 157 | - | Field string | |||
| 158 | - | Message string | |||
| 159 | - | } | |||
| 160 | - | ||||
| 161 | - | func (e *ValidationError) Error() string { | |||
| 162 | - | return "validation error for " + e.Field + ": " + e.Message | |||
| 163 | - | } | |||
| 164 | - | ||||
| 165 | - | // LogMemoryConfiguration logs the current memory configuration for debugging | |||
| 166 | - | func LogMemoryConfiguration(config *Config) { | |||
| 167 | - | if config == nil || !config.Memory.EnableMemoryMonitoring { | |||
| 168 | - | return | |||
| 169 | - | } | |||
| 170 | - | ||||
| 171 | - | log := func(format string, args ...interface{}) { | |||
| 172 | - | // Use Go's standard log package | |||
| 173 | - | // log.Printf("[webkit-config] "+format, args...) | |||
| 174 | - | // For now, we'll just ignore since we don't have access to log here | |||
| 175 | - | _ = format | |||
| 176 | - | _ = args | |||
| 177 | - | } | |||
| 178 | - | ||||
| 179 | - | log("Memory configuration:") | |||
| 180 | - | log(" MemoryLimitMB: %d", config.Memory.MemoryLimitMB) | |||
| 181 | - | log(" ConservativeThreshold: %.2f", config.Memory.ConservativeThreshold) | |||
| 182 | - | log(" StrictThreshold: %.2f", config.Memory.StrictThreshold) | |||
| 183 | - | log(" KillThreshold: %.2f", config.Memory.KillThreshold) | |||
| 184 | - | log(" CacheModel: %s", config.Memory.CacheModel) | |||
| 185 | - | log(" EnablePageCache: %t", config.Memory.EnablePageCache) | |||
| 186 | - | log(" EnableOfflineAppCache: %t", config.Memory.EnableOfflineAppCache) | |||
| 187 | - | log(" ProcessRecycleThreshold: %d", config.Memory.ProcessRecycleThreshold) | |||
| 188 | - | log(" EnableGCInterval: %d seconds", config.Memory.EnableGCInterval) | |||
| 189 | - | } | |||
D pkg/webkit/print_cgo.go +0 -46
| @@ -1,46 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #cgo pkg-config: webkitgtk-6.0 gtk4 | |||
| 7 | - | #cgo CFLAGS: -I/usr/include/webkitgtk-6.0 | |||
| 8 | - | #include <webkit/webkit.h> | |||
| 9 | - | #include <gtk/gtk.h> | |||
| 10 | - | */ | |||
| 11 | - | import "C" | |||
| 12 | - | import "unsafe" | |||
| 13 | - | ||||
| 14 | - | // ShowPrintDialog shows the print dialog for the WebView | |||
| 15 | - | func (w *WebView) ShowPrintDialog() error { | |||
| 16 | - | if w == nil || w.native == nil || w.native.wv == nil { | |||
| 17 | - | return ErrNotImplemented | |||
| 18 | - | } | |||
| 19 | - | ||||
| 20 | - | // Create print operation | |||
| 21 | - | printOp := C.webkit_print_operation_new(w.native.wv) | |||
| 22 | - | if printOp == nil { | |||
| 23 | - | return ErrNotImplemented | |||
| 24 | - | } | |||
| 25 | - | ||||
| 26 | - | // Pass nil for parent window - print dialog will work without it | |||
| 27 | - | var parentWindow *C.GtkWindow = nil | |||
| 28 | - | ||||
| 29 | - | // Show print dialog | |||
| 30 | - | response := C.webkit_print_operation_run_dialog(printOp, parentWindow) | |||
| 31 | - | ||||
| 32 | - | // Clean up print operation | |||
| 33 | - | C.g_object_unref(C.gpointer(unsafe.Pointer(printOp))) | |||
| 34 | - | ||||
| 35 | - | // Handle the response | |||
| 36 | - | switch response { | |||
| 37 | - | case C.WEBKIT_PRINT_OPERATION_RESPONSE_PRINT: | |||
| 38 | - | // User clicked print - the operation will proceed | |||
| 39 | - | return nil | |||
| 40 | - | case C.WEBKIT_PRINT_OPERATION_RESPONSE_CANCEL: | |||
| 41 | - | // User cancelled - not an error | |||
| 42 | - | return nil | |||
| 43 | - | default: | |||
| 44 | - | return ErrNotImplemented | |||
| 45 | - | } | |||
| 46 | - | } | |||
D pkg/webkit/scheme.go +0 -9
| @@ -1,9 +0,0 @@ | |||||
| 1 | - | //go:build !webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | // SchemeResolver provides bytes and mime for a given custom URI. | |||
| 6 | - | type SchemeResolver func(uri string) (mime string, data []byte, ok bool) | |||
| 7 | - | ||||
| 8 | - | // SetURISchemeResolver is a no-op in non-CGO builds. | |||
| 9 | - | func SetURISchemeResolver(r SchemeResolver) { /* no-op */ } | |||
D pkg/webkit/scheme_cgo.go +0 -51
| @@ -1,51 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #include <stdlib.h> | |||
| 7 | - | */ | |||
| 8 | - | import "C" | |||
| 9 | - | ||||
| 10 | - | import ( | |||
| 11 | - | "unsafe" | |||
| 12 | - | ) | |||
| 13 | - | ||||
| 14 | - | // Resolver provides bytes and mime for a given custom URI. | |||
| 15 | - | type SchemeResolver func(uri string) (mime string, data []byte, ok bool) | |||
| 16 | - | ||||
| 17 | - | var globalResolver SchemeResolver | |||
| 18 | - | ||||
| 19 | - | // SetURISchemeResolver sets the resolver used by the custom URI scheme handler. | |||
| 20 | - | func SetURISchemeResolver(r SchemeResolver) { globalResolver = r } | |||
| 21 | - | ||||
| 22 | - | //export goResolveURIScheme | |||
| 23 | - | func goResolveURIScheme(curi *C.char, outLen *C.size_t, outMime **C.char) unsafe.Pointer { | |||
| 24 | - | if curi == nil || outLen == nil || outMime == nil { | |||
| 25 | - | return nil | |||
| 26 | - | } | |||
| 27 | - | uri := C.GoString(curi) | |||
| 28 | - | if globalResolver == nil { | |||
| 29 | - | *outLen = 0 | |||
| 30 | - | *outMime = nil | |||
| 31 | - | return nil | |||
| 32 | - | } | |||
| 33 | - | mime, data, ok := globalResolver(uri) | |||
| 34 | - | if !ok || len(data) == 0 { | |||
| 35 | - | *outLen = 0 | |||
| 36 | - | *outMime = nil | |||
| 37 | - | return nil | |||
| 38 | - | } | |||
| 39 | - | buf := C.malloc(C.size_t(len(data))) | |||
| 40 | - | if buf == nil { | |||
| 41 | - | *outLen = 0 | |||
| 42 | - | *outMime = nil | |||
| 43 | - | return nil | |||
| 44 | - | } | |||
| 45 | - | // Copy data into C buffer | |||
| 46 | - | dst := (*[1 << 30]byte)(buf)[:len(data):len(data)] | |||
| 47 | - | copy(dst, data) | |||
| 48 | - | *outLen = C.size_t(len(data)) | |||
| 49 | - | *outMime = C.CString(mime) | |||
| 50 | - | return buf | |||
| 51 | - | } | |||
D pkg/webkit/script.go +0 -13
| @@ -1,13 +0,0 @@ | |||||
| 1 | - | //go:build !webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | // InjectScript evaluates JavaScript in the active WebView context. | |||
| 6 | - | func (w *WebView) InjectScript(js string) error { | |||
| 7 | - | if w == nil || w.destroyed { | |||
| 8 | - | return ErrNotImplemented | |||
| 9 | - | } | |||
| 10 | - | // Store last script for potential debugging/testing. | |||
| 11 | - | _ = js | |||
| 12 | - | return nil | |||
| 13 | - | } | |||
D pkg/webkit/script_cgo.go +0 -81
| @@ -1,81 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #cgo pkg-config: webkitgtk-6.0 gtk4 | |||
| 7 | - | #cgo CFLAGS: -I/usr/include/webkitgtk-6.0 | |||
| 8 | - | #include <stdlib.h> | |||
| 9 | - | #include <webkit/webkit.h> | |||
| 10 | - | ||||
| 11 | - | static gboolean dumber_is_valid_web_view(WebKitWebView *wv) { | |||
| 12 | - | return WEBKIT_IS_WEB_VIEW(wv); | |||
| 13 | - | } | |||
| 14 | - | */ | |||
| 15 | - | import "C" | |||
| 16 | - | ||||
| 17 | - | import "unsafe" | |||
| 18 | - | ||||
| 19 | - | func (w *WebView) canEvaluateJavaScript() bool { | |||
| 20 | - | if w == nil || w.destroyed || w.native == nil || w.native.wv == nil { | |||
| 21 | - | return false | |||
| 22 | - | } | |||
| 23 | - | if C.dumber_is_valid_web_view(w.native.wv) == C.gboolean(0) { | |||
| 24 | - | if w.native != nil { | |||
| 25 | - | w.native.wv = nil | |||
| 26 | - | w.native.view = nil | |||
| 27 | - | } | |||
| 28 | - | w.destroyed = true | |||
| 29 | - | return false | |||
| 30 | - | } | |||
| 31 | - | return true | |||
| 32 | - | } | |||
| 33 | - | ||||
| 34 | - | func (w *WebView) InjectScript(js string) error { | |||
| 35 | - | if !w.canEvaluateJavaScript() { | |||
| 36 | - | return ErrNotImplemented | |||
| 37 | - | } | |||
| 38 | - | cjs := C.CString(js) | |||
| 39 | - | defer C.free(unsafe.Pointer(cjs)) | |||
| 40 | - | // Fire-and-forget evaluation using the modern API | |||
| 41 | - | // length: -1 (NUL-terminated), world_name/source_uri: NULL, starting_line_number: 0 | |||
| 42 | - | C.webkit_web_view_evaluate_javascript( | |||
| 43 | - | w.native.wv, | |||
| 44 | - | (*C.gchar)(cjs), | |||
| 45 | - | C.gssize(-1), | |||
| 46 | - | nil, // world_name | |||
| 47 | - | nil, // source_uri | |||
| 48 | - | nil, // cancellable | |||
| 49 | - | nil, // callback | |||
| 50 | - | nil, // user_data | |||
| 51 | - | ) | |||
| 52 | - | return nil | |||
| 53 | - | } | |||
| 54 | - | ||||
| 55 | - | // InjectScriptIntoWorld evaluates JavaScript in the specified script world. | |||
| 56 | - | func (w *WebView) InjectScriptIntoWorld(js string, worldName string) error { | |||
| 57 | - | if !w.canEvaluateJavaScript() { | |||
| 58 | - | return ErrNotImplemented | |||
| 59 | - | } | |||
| 60 | - | cjs := C.CString(js) | |||
| 61 | - | defer C.free(unsafe.Pointer(cjs)) | |||
| 62 | - | ||||
| 63 | - | var cworld *C.gchar | |||
| 64 | - | if worldName != "" { | |||
| 65 | - | cworld = (*C.gchar)(C.CString(worldName)) | |||
| 66 | - | defer C.free(unsafe.Pointer(cworld)) | |||
| 67 | - | } | |||
| 68 | - | ||||
| 69 | - | // Evaluate JavaScript in the specified world | |||
| 70 | - | C.webkit_web_view_evaluate_javascript( | |||
| 71 | - | w.native.wv, | |||
| 72 | - | (*C.gchar)(cjs), | |||
| 73 | - | C.gssize(-1), | |||
| 74 | - | cworld, // world_name | |||
| 75 | - | nil, // source_uri | |||
| 76 | - | nil, // cancellable | |||
| 77 | - | nil, // callback | |||
| 78 | - | nil, // user_data | |||
| 79 | - | ) | |||
| 80 | - | return nil | |||
| 81 | - | } | |||
D pkg/webkit/settings.go +0 -145
| @@ -1,145 +0,0 @@ | |||||
| 1 | - | package webkit | |||
| 2 | - | ||||
| 3 | - | // Config holds initialization settings for the WebKit-based browser components. | |||
| 4 | - | // This will map to WebKit2GTK and GTK settings in the real implementation. | |||
| 5 | - | type Config struct { | |||
| 6 | - | // Assets provides access to embedded GUI files | |||
| 7 | - | Assets interface{ ReadFile(string) ([]byte, error) } | |||
| 8 | - | ||||
| 9 | - | // InitialURL is the first URL to load when creating a WebView. | |||
| 10 | - | InitialURL string | |||
| 11 | - | ||||
| 12 | - | // UserAgent allows overriding the default user agent string. | |||
| 13 | - | UserAgent string | |||
| 14 | - | ||||
| 15 | - | // EnableDeveloperExtras enables devtools/inspector. | |||
| 16 | - | EnableDeveloperExtras bool | |||
| 17 | - | ||||
| 18 | - | // ZoomDefault sets an initial zoom factor (1.0 = 100%). | |||
| 19 | - | ZoomDefault float64 | |||
| 20 | - | ||||
| 21 | - | // DataDir is the base directory for persistent website data (cookies, localStorage, etc.). | |||
| 22 | - | DataDir string | |||
| 23 | - | // CacheDir is the base directory for cache data. | |||
| 24 | - | CacheDir string | |||
| 25 | - | ||||
| 26 | - | // Fonts apply to pages that don't specify fonts (browser defaults). | |||
| 27 | - | DefaultSansFont string | |||
| 28 | - | DefaultSerifFont string | |||
| 29 | - | DefaultMonospaceFont string | |||
| 30 | - | DefaultFontSize int // CSS px (~points) | |||
| 31 | - | ||||
| 32 | - | // Rendering controls GPU/CPU selection and debug options | |||
| 33 | - | Rendering RenderingConfig | |||
| 34 | - | ||||
| 35 | - | // VideoAcceleration controls video hardware acceleration settings | |||
| 36 | - | VideoAcceleration VideoAccelerationConfig | |||
| 37 | - | ||||
| 38 | - | // Memory controls memory optimization settings | |||
| 39 | - | Memory MemoryConfig | |||
| 40 | - | ||||
| 41 | - | // CodecPreferences for media playback | |||
| 42 | - | CodecPreferences CodecPreferencesConfig | |||
| 43 | - | ||||
| 44 | - | // APIToken holds the per-session token used to authenticate dumb://api requests | |||
| 45 | - | // It's optional; if empty, API token enforcement may be disabled by the app. | |||
| 46 | - | APIToken string | |||
| 47 | - | ||||
| 48 | - | // UseDomZoom toggles CSS/DOM-based zoom instead of WebKit's native zoom. | |||
| 49 | - | UseDomZoom bool | |||
| 50 | - | ||||
| 51 | - | // Colors defines the light/dark palette tokens for the GUI. | |||
| 52 | - | Colors ColorPalettes | |||
| 53 | - | ||||
| 54 | - | // CreateWindow controls whether to create a window during WebView initialization. | |||
| 55 | - | // Set to false when creating WebViews for workspace panes that will be reparented. | |||
| 56 | - | CreateWindow bool | |||
| 57 | - | } | |||
| 58 | - | ||||
| 59 | - | // ColorPalette holds semantic UI tokens for a theme. | |||
| 60 | - | type ColorPalette struct { | |||
| 61 | - | Background string | |||
| 62 | - | Surface string | |||
| 63 | - | SurfaceVariant string | |||
| 64 | - | Text string | |||
| 65 | - | Muted string | |||
| 66 | - | Accent string | |||
| 67 | - | Border string | |||
| 68 | - | } | |||
| 69 | - | ||||
| 70 | - | // ColorPalettes hosts both light and dark color palettes. | |||
| 71 | - | type ColorPalettes struct { | |||
| 72 | - | Light ColorPalette | |||
| 73 | - | Dark ColorPalette | |||
| 74 | - | } | |||
| 75 | - | ||||
| 76 | - | // CodecPreferencesConfig holds codec preferences for WebKit media playback | |||
| 77 | - | type CodecPreferencesConfig struct { | |||
| 78 | - | PreferredCodecs []string | |||
| 79 | - | BlockedCodecs []string | |||
| 80 | - | ForceAV1 bool | |||
| 81 | - | CustomUserAgent string | |||
| 82 | - | DisableTwitchCodecControl bool | |||
| 83 | - | } | |||
| 84 | - | ||||
| 85 | - | // RenderingConfig controls hardware acceleration preferences. | |||
| 86 | - | // Mode accepts: "auto" (default), "gpu", or "cpu". | |||
| 87 | - | // DebugGPU enables compositing indicators if supported. | |||
| 88 | - | type RenderingConfig struct { | |||
| 89 | - | Mode string | |||
| 90 | - | DebugGPU bool | |||
| 91 | - | } | |||
| 92 | - | ||||
| 93 | - | // VideoAccelerationConfig controls video hardware acceleration settings. | |||
| 94 | - | type VideoAccelerationConfig struct { | |||
| 95 | - | EnableVAAPI bool | |||
| 96 | - | AutoDetectGPU bool | |||
| 97 | - | VAAPIDriverName string | |||
| 98 | - | EnableAllDrivers bool | |||
| 99 | - | LegacyVAAPI bool | |||
| 100 | - | } | |||
| 101 | - | ||||
| 102 | - | // CacheModel represents WebKit cache model options for memory optimization. | |||
| 103 | - | type CacheModel string | |||
| 104 | - | ||||
| 105 | - | const ( | |||
| 106 | - | CacheModelDocumentViewer CacheModel = "document_viewer" // Minimal caching, lowest memory | |||
| 107 | - | CacheModelWebBrowser CacheModel = "web_browser" // Default, balanced caching | |||
| 108 | - | CacheModelPrimaryWebBrowser CacheModel = "primary_web_browser" // Maximum caching, highest memory | |||
| 109 | - | ) | |||
| 110 | - | ||||
| 111 | - | // MemoryConfig controls memory optimization settings. | |||
| 112 | - | type MemoryConfig struct { | |||
| 113 | - | // MemoryLimitMB sets the maximum memory limit per WebView in MB (0 = unlimited) | |||
| 114 | - | MemoryLimitMB int | |||
| 115 | - | ||||
| 116 | - | // ConservativeThreshold triggers early memory cleanup (0.0-1.0, default 0.33) | |||
| 117 | - | ConservativeThreshold float64 | |||
| 118 | - | ||||
| 119 | - | // StrictThreshold triggers aggressive memory cleanup (0.0-1.0, default 0.5) | |||
| 120 | - | StrictThreshold float64 | |||
| 121 | - | ||||
| 122 | - | // KillThreshold kills processes at this memory usage (0.0-1.0, 0 = disabled) | |||
| 123 | - | KillThreshold float64 | |||
| 124 | - | ||||
| 125 | - | // PollIntervalSeconds sets how often to check memory usage (default 2.0) | |||
| 126 | - | PollIntervalSeconds float64 | |||
| 127 | - | ||||
| 128 | - | // CacheModel determines caching strategy (default: web_browser) | |||
| 129 | - | CacheModel CacheModel | |||
| 130 | - | ||||
| 131 | - | // EnablePageCache enables back/forward page caching (default: true) | |||
| 132 | - | EnablePageCache bool | |||
| 133 | - | ||||
| 134 | - | // EnableOfflineAppCache enables offline application caching (default: true) | |||
| 135 | - | EnableOfflineAppCache bool | |||
| 136 | - | ||||
| 137 | - | // ProcessRecycleThreshold recycles WebView after N page loads (0 = disabled) | |||
| 138 | - | ProcessRecycleThreshold int | |||
| 139 | - | ||||
| 140 | - | // EnableGCInterval enables periodic JS garbage collection in seconds (0 = disabled) | |||
| 141 | - | EnableGCInterval int | |||
| 142 | - | ||||
| 143 | - | // EnableMemoryMonitoring logs memory usage and pressure events | |||
| 144 | - | EnableMemoryMonitoring bool | |||
| 145 | - | } | |||
D pkg/webkit/shortcuts_cgo.go +0 -565
| @@ -1,565 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | import ( | |||
| 6 | - | "fmt" | |||
| 7 | - | "log" | |||
| 8 | - | "strings" | |||
| 9 | - | "sync" | |||
| 10 | - | "sync/atomic" | |||
| 11 | - | "unsafe" | |||
| 12 | - | ) | |||
| 13 | - | ||||
| 14 | - | /* | |||
| 15 | - | #cgo pkg-config: gtk4 webkitgtk-6.0 | |||
| 16 | - | #include <gtk/gtk.h> | |||
| 17 | - | #include <webkit/webkit.h> | |||
| 18 | - | #include <stdint.h> | |||
| 19 | - | #include <stdlib.h> | |||
| 20 | - | ||||
| 21 | - | extern void goHandleWindowShortcut(uintptr_t handle); | |||
| 22 | - | ||||
| 23 | - | static GtkShortcutController* create_global_shortcut_controller(GtkWindow* window) { | |||
| 24 | - | if (!window) { | |||
| 25 | - | return NULL; | |||
| 26 | - | } | |||
| 27 | - | GtkEventController* event_controller = gtk_shortcut_controller_new(); | |||
| 28 | - | if (!event_controller) { | |||
| 29 | - | return NULL; | |||
| 30 | - | } | |||
| 31 | - | GtkShortcutController* controller = GTK_SHORTCUT_CONTROLLER(event_controller); | |||
| 32 | - | gtk_shortcut_controller_set_scope(controller, GTK_SHORTCUT_SCOPE_GLOBAL); | |||
| 33 | - | gtk_widget_add_controller(GTK_WIDGET(window), event_controller); | |||
| 34 | - | return controller; | |||
| 35 | - | } | |||
| 36 | - | ||||
| 37 | - | static gboolean shortcut_callback_bridge(GtkWidget* widget, GVariant* args, gpointer user_data) { | |||
| 38 | - | (void)widget; | |||
| 39 | - | // Properly handle the GVariant to avoid NULL string assertion | |||
| 40 | - | if (args != NULL && g_variant_is_of_type(args, G_VARIANT_TYPE_STRING)) { | |||
| 41 | - | // If args contains a string, we can safely ignore it | |||
| 42 | - | const gchar* str = g_variant_get_string(args, NULL); | |||
| 43 | - | (void)str; | |||
| 44 | - | } | |||
| 45 | - | uintptr_t handle = (uintptr_t)user_data; | |||
| 46 | - | if (handle == 0) { | |||
| 47 | - | return FALSE; | |||
| 48 | - | } | |||
| 49 | - | goHandleWindowShortcut(handle); | |||
| 50 | - | return TRUE; // Indicate we handled the shortcut | |||
| 51 | - | } | |||
| 52 | - | ||||
| 53 | - | // Alternative callback that doesn't use GVariant at all | |||
| 54 | - | static gboolean simple_shortcut_callback(GtkWidget* widget, gpointer user_data) { | |||
| 55 | - | (void)widget; | |||
| 56 | - | uintptr_t handle = (uintptr_t)user_data; | |||
| 57 | - | if (handle == 0) { | |||
| 58 | - | return FALSE; | |||
| 59 | - | } | |||
| 60 | - | goHandleWindowShortcut(handle); | |||
| 61 | - | return TRUE; | |||
| 62 | - | } | |||
| 63 | - | ||||
| 64 | - | static void add_shortcut_to_controller(GtkShortcutController* controller, | |||
| 65 | - | const char* trigger_str, | |||
| 66 | - | uintptr_t handle) { | |||
| 67 | - | if (!controller || !trigger_str || handle == 0) { | |||
| 68 | - | return; | |||
| 69 | - | } | |||
| 70 | - | GtkShortcutTrigger* trigger = gtk_shortcut_trigger_parse_string(trigger_str); | |||
| 71 | - | if (!trigger) { | |||
| 72 | - | return; | |||
| 73 | - | } | |||
| 74 | - | ||||
| 75 | - | // Try to create an action that doesn't involve problematic GVariant handling | |||
| 76 | - | // Use gtk_nothing_action for the shortcut and handle activation separately | |||
| 77 | - | GtkShortcutAction* action = gtk_callback_action_new((GtkShortcutFunc)shortcut_callback_bridge, | |||
| 78 | - | (gpointer)handle, | |||
| 79 | - | NULL); | |||
| 80 | - | if (!action) { | |||
| 81 | - | g_object_unref(trigger); | |||
| 82 | - | return; | |||
| 83 | - | } | |||
| 84 | - | GtkShortcut* shortcut = gtk_shortcut_new(trigger, action); | |||
| 85 | - | gtk_shortcut_controller_add_shortcut(controller, shortcut); | |||
| 86 | - | } | |||
| 87 | - | */ | |||
| 88 | - | import "C" | |||
| 89 | - | ||||
| 90 | - | var ( | |||
| 91 | - | globalShortcutMu sync.Mutex | |||
| 92 | - | globalShortcutCounter uint64 | |||
| 93 | - | globalShortcutCallbacks = make(map[uintptr]func()) | |||
| 94 | - | ) | |||
| 95 | - | ||||
| 96 | - | func registerWindowShortcutCallback(cb func()) uintptr { | |||
| 97 | - | if cb == nil { | |||
| 98 | - | return 0 | |||
| 99 | - | } | |||
| 100 | - | id := uintptr(atomic.AddUint64(&globalShortcutCounter, 1)) | |||
| 101 | - | if id == 0 { | |||
| 102 | - | // Should never happen, but guard against wrapping to 0 | |||
| 103 | - | id = uintptr(atomic.AddUint64(&globalShortcutCounter, 1)) | |||
| 104 | - | } | |||
| 105 | - | globalShortcutMu.Lock() | |||
| 106 | - | globalShortcutCallbacks[id] = cb | |||
| 107 | - | globalShortcutMu.Unlock() | |||
| 108 | - | return id | |||
| 109 | - | } | |||
| 110 | - | ||||
| 111 | - | func unregisterWindowShortcutCallback(id uintptr) { | |||
| 112 | - | if id == 0 { | |||
| 113 | - | return | |||
| 114 | - | } | |||
| 115 | - | globalShortcutMu.Lock() | |||
| 116 | - | delete(globalShortcutCallbacks, id) | |||
| 117 | - | globalShortcutMu.Unlock() | |||
| 118 | - | } | |||
| 119 | - | ||||
| 120 | - | func invokeWindowShortcutCallback(id uintptr) { | |||
| 121 | - | if id == 0 { | |||
| 122 | - | return | |||
| 123 | - | } | |||
| 124 | - | globalShortcutMu.Lock() | |||
| 125 | - | cb := globalShortcutCallbacks[id] | |||
| 126 | - | globalShortcutMu.Unlock() | |||
| 127 | - | if cb == nil { | |||
| 128 | - | log.Printf("[shortcuts] no handler for shortcut id=%d", id) | |||
| 129 | - | return | |||
| 130 | - | } | |||
| 131 | - | cb() | |||
| 132 | - | } | |||
| 133 | - | ||||
| 134 | - | //export goHandleWindowShortcut | |||
| 135 | - | func goHandleWindowShortcut(handle C.uintptr_t) { | |||
| 136 | - | invokeWindowShortcutCallback(uintptr(handle)) | |||
| 137 | - | } | |||
| 138 | - | ||||
| 139 | - | // Go wrapper functions for CGO - these can be called from other Go files | |||
| 140 | - | ||||
| 141 | - | // CreateGlobalShortcutController creates a GTK4 global shortcut controller for a window | |||
| 142 | - | func CreateGlobalShortcutController(window uintptr) uintptr { | |||
| 143 | - | if window == 0 { | |||
| 144 | - | return 0 | |||
| 145 | - | } | |||
| 146 | - | controller := C.create_global_shortcut_controller((*C.GtkWindow)(unsafe.Pointer(window))) | |||
| 147 | - | return uintptr(unsafe.Pointer(controller)) | |||
| 148 | - | } | |||
| 149 | - | ||||
| 150 | - | // AddShortcutToController adds a shortcut to the controller with a callback handle | |||
| 151 | - | func AddShortcutToController(controller uintptr, key string, handle uintptr) error { | |||
| 152 | - | if controller == 0 || key == "" || handle == 0 { | |||
| 153 | - | return ErrNotImplemented | |||
| 154 | - | } | |||
| 155 | - | ||||
| 156 | - | keyStr := C.CString(key) | |||
| 157 | - | defer C.free(unsafe.Pointer(keyStr)) | |||
| 158 | - | ||||
| 159 | - | C.add_shortcut_to_controller( | |||
| 160 | - | (*C.GtkShortcutController)(unsafe.Pointer(controller)), | |||
| 161 | - | keyStr, | |||
| 162 | - | C.uintptr_t(handle), | |||
| 163 | - | ) | |||
| 164 | - | ||||
| 165 | - | return nil | |||
| 166 | - | } | |||
| 167 | - | ||||
| 168 | - | // Global shortcuts registry to track all registered shortcuts for automatic blocking | |||
| 169 | - | var ( | |||
| 170 | - | globalShortcutsRegistry = make(map[string]bool) | |||
| 171 | - | shortcutsRegistryMu sync.RWMutex | |||
| 172 | - | // Map from shortcut key to callback handle for C-level triggering | |||
| 173 | - | globalShortcutHandles = make(map[string]uintptr) | |||
| 174 | - | ) | |||
| 175 | - | ||||
| 176 | - | // WebView tracking for dynamic protection refresh | |||
| 177 | - | var ( | |||
| 178 | - | activeWebViews = make(map[*WebView]bool) | |||
| 179 | - | activeWebViewsMu sync.RWMutex | |||
| 180 | - | ) | |||
| 181 | - | ||||
| 182 | - | // RegisterGlobalShortcut adds a shortcut to the global registry for automatic webpage blocking | |||
| 183 | - | func RegisterGlobalShortcut(shortcut string) { | |||
| 184 | - | shortcutsRegistryMu.Lock() | |||
| 185 | - | // Normalize shortcut format (convert to lowercase, standardize modifiers) | |||
| 186 | - | normalized := normalizeShortcut(shortcut) | |||
| 187 | - | ||||
| 188 | - | // Only proceed if this is a new shortcut registration | |||
| 189 | - | wasNew := !globalShortcutsRegistry[normalized] | |||
| 190 | - | if wasNew { | |||
| 191 | - | globalShortcutsRegistry[normalized] = true | |||
| 192 | - | log.Printf("[shortcuts] Registered global shortcut for blocking: %s -> %s", shortcut, normalized) | |||
| 193 | - | } | |||
| 194 | - | shortcutsRegistryMu.Unlock() | |||
| 195 | - | ||||
| 196 | - | // If we added a new shortcut, refresh protection on all active WebViews | |||
| 197 | - | if wasNew { | |||
| 198 | - | RefreshGlobalShortcutsProtection() | |||
| 199 | - | } | |||
| 200 | - | } | |||
| 201 | - | ||||
| 202 | - | // RegisterGlobalShortcutWithHandle adds a shortcut with its callback handle for C-level triggering | |||
| 203 | - | func RegisterGlobalShortcutWithHandle(shortcut string, handle uintptr) { | |||
| 204 | - | // First register the shortcut for blocking | |||
| 205 | - | RegisterGlobalShortcut(shortcut) | |||
| 206 | - | ||||
| 207 | - | // Then store the callback handle for C-level triggering | |||
| 208 | - | shortcutsRegistryMu.Lock() | |||
| 209 | - | normalized := normalizeShortcut(shortcut) | |||
| 210 | - | globalShortcutHandles[normalized] = handle | |||
| 211 | - | log.Printf("[shortcuts] Registered callback handle for shortcut: %s", shortcut) | |||
| 212 | - | shortcutsRegistryMu.Unlock() | |||
| 213 | - | } | |||
| 214 | - | ||||
| 215 | - | // GetRegisteredShortcuts returns a copy of all registered shortcuts | |||
| 216 | - | func GetRegisteredShortcuts() []string { | |||
| 217 | - | shortcutsRegistryMu.RLock() | |||
| 218 | - | defer shortcutsRegistryMu.RUnlock() | |||
| 219 | - | ||||
| 220 | - | shortcuts := make([]string, 0, len(globalShortcutsRegistry)) | |||
| 221 | - | for shortcut := range globalShortcutsRegistry { | |||
| 222 | - | shortcuts = append(shortcuts, shortcut) | |||
| 223 | - | } | |||
| 224 | - | return shortcuts | |||
| 225 | - | } | |||
| 226 | - | ||||
| 227 | - | // RegisterActiveWebView adds a WebView to the active registry for dynamic protection updates | |||
| 228 | - | func RegisterActiveWebView(w *WebView) { | |||
| 229 | - | if w == nil { | |||
| 230 | - | return | |||
| 231 | - | } | |||
| 232 | - | activeWebViewsMu.Lock() | |||
| 233 | - | defer activeWebViewsMu.Unlock() | |||
| 234 | - | activeWebViews[w] = true | |||
| 235 | - | // WebView registered for protection updates | |||
| 236 | - | } | |||
| 237 | - | ||||
| 238 | - | // UnregisterActiveWebView removes a WebView from the active registry | |||
| 239 | - | func UnregisterActiveWebView(w *WebView) { | |||
| 240 | - | if w == nil { | |||
| 241 | - | return | |||
| 242 | - | } | |||
| 243 | - | activeWebViewsMu.Lock() | |||
| 244 | - | defer activeWebViewsMu.Unlock() | |||
| 245 | - | delete(activeWebViews, w) | |||
| 246 | - | // WebView unregistered from protection updates | |||
| 247 | - | } | |||
| 248 | - | ||||
| 249 | - | // RefreshGlobalShortcutsProtection updates all active WebViews with current shortcut protection | |||
| 250 | - | func RefreshGlobalShortcutsProtection() { | |||
| 251 | - | activeWebViewsMu.RLock() | |||
| 252 | - | webViews := make([]*WebView, 0, len(activeWebViews)) | |||
| 253 | - | for wv := range activeWebViews { | |||
| 254 | - | webViews = append(webViews, wv) | |||
| 255 | - | } | |||
| 256 | - | activeWebViewsMu.RUnlock() | |||
| 257 | - | ||||
| 258 | - | if len(webViews) == 0 { | |||
| 259 | - | return | |||
| 260 | - | } | |||
| 261 | - | ||||
| 262 | - | for _, wv := range webViews { | |||
| 263 | - | if wv != nil && !wv.destroyed { | |||
| 264 | - | // Re-enable protection which will inject updated shortcut list | |||
| 265 | - | if err := wv.EnableGlobalShortcutsProtection(); err != nil { | |||
| 266 | - | log.Printf("[shortcuts] Failed to refresh protection for WebView: %v", err) | |||
| 267 | - | } | |||
| 268 | - | } | |||
| 269 | - | } | |||
| 270 | - | } | |||
| 271 | - | ||||
| 272 | - | // normalizeShortcut converts shortcuts to a standardized format for JavaScript blocking | |||
| 273 | - | func normalizeShortcut(shortcut string) string { | |||
| 274 | - | // Convert to lowercase and replace common variations | |||
| 275 | - | normalized := strings.ToLower(shortcut) | |||
| 276 | - | ||||
| 277 | - | // Standardize modifier keys | |||
| 278 | - | normalized = strings.ReplaceAll(normalized, "cmdorctrl+", "ctrl+") | |||
| 279 | - | normalized = strings.ReplaceAll(normalized, "cmd+", "ctrl+") // Treat cmd as ctrl for blocking | |||
| 280 | - | normalized = strings.ReplaceAll(normalized, "control+", "ctrl+") | |||
| 281 | - | ||||
| 282 | - | // Standardize arrow key names (handle both formats) | |||
| 283 | - | normalized = strings.ReplaceAll(normalized, "left", "arrowleft") | |||
| 284 | - | normalized = strings.ReplaceAll(normalized, "right", "arrowright") | |||
| 285 | - | normalized = strings.ReplaceAll(normalized, "up", "arrowup") | |||
| 286 | - | normalized = strings.ReplaceAll(normalized, "down", "arrowdown") | |||
| 287 | - | ||||
| 288 | - | // Fix double arrow prefixes that might occur from above replacements | |||
| 289 | - | normalized = strings.ReplaceAll(normalized, "arrowarrowleft", "arrowleft") | |||
| 290 | - | normalized = strings.ReplaceAll(normalized, "arrowarrowright", "arrowright") | |||
| 291 | - | normalized = strings.ReplaceAll(normalized, "arrowarrowup", "arrowup") | |||
| 292 | - | normalized = strings.ReplaceAll(normalized, "arrowarrowdown", "arrowdown") | |||
| 293 | - | ||||
| 294 | - | // Other key normalizations | |||
| 295 | - | normalized = strings.ReplaceAll(normalized, "equal", "equal") // For Ctrl+= | |||
| 296 | - | normalized = strings.ReplaceAll(normalized, "plus", "equal") // Normalize + to = | |||
| 297 | - | ||||
| 298 | - | return normalized | |||
| 299 | - | } | |||
| 300 | - | ||||
| 301 | - | // Keyboard event blocking functionality for global shortcuts protection | |||
| 302 | - | ||||
| 303 | - | // keyboardBlockerScript holds reference to the main-world keyboard blocking script | |||
| 304 | - | var keyboardBlockerScript *C.WebKitUserScript = nil | |||
| 305 | - | ||||
| 306 | - | // EnableGlobalShortcutsProtection injects a script to block all registered global shortcuts from reaching webpages | |||
| 307 | - | func (w *WebView) EnableGlobalShortcutsProtection() error { | |||
| 308 | - | if w == nil || w.destroyed || w.native == nil || w.native.ucm == nil { | |||
| 309 | - | return ErrWebViewNotInitialized | |||
| 310 | - | } | |||
| 311 | - | ||||
| 312 | - | // Get all registered shortcuts | |||
| 313 | - | shortcuts := GetRegisteredShortcuts() | |||
| 314 | - | if len(shortcuts) == 0 { | |||
| 315 | - | log.Printf("[shortcuts] No global shortcuts registered, skipping protection") | |||
| 316 | - | return nil | |||
| 317 | - | } | |||
| 318 | - | ||||
| 319 | - | // Generate JavaScript array of shortcuts to block | |||
| 320 | - | shortcutsJS := "[" | |||
| 321 | - | for i, shortcut := range shortcuts { | |||
| 322 | - | if i > 0 { | |||
| 323 | - | shortcutsJS += "," | |||
| 324 | - | } | |||
| 325 | - | shortcutsJS += `"` + shortcut + `"` | |||
| 326 | - | } | |||
| 327 | - | shortcutsJS += "]" | |||
| 328 | - | ||||
| 329 | - | // Create a version-based blocking script that can be updated dynamically | |||
| 330 | - | protectionVersion := len(shortcuts) // Use shortcuts count as version | |||
| 331 | - | globalProtectionScript := ` | |||
| 332 | - | (() => { | |||
| 333 | - | const newVersion = ` + fmt.Sprintf("%d", protectionVersion) + `; | |||
| 334 | - | const currentVersion = window.__dumber_shortcuts_protection_version || 0; | |||
| 335 | - | ||||
| 336 | - | // Only update if this is a newer version or first time | |||
| 337 | - | if (newVersion > currentVersion) { | |||
| 338 | - | // Clean up old protection if it exists | |||
| 339 | - | if (window.__dumber_cleanup_global_shortcuts) { | |||
| 340 | - | window.__dumber_cleanup_global_shortcuts(); | |||
| 341 | - | } | |||
| 342 | - | ||||
| 343 | - | window.__dumber_shortcuts_protection_version = newVersion; | |||
| 344 | - | ||||
| 345 | - | // List of global shortcuts to block from reaching the webpage | |||
| 346 | - | const globalShortcuts = ` + shortcutsJS + `; | |||
| 347 | - | console.log('[dumber] Protecting global shortcuts (v' + newVersion + '):', globalShortcuts); | |||
| 348 | - | ||||
| 349 | - | // Function to check if a key event matches any global shortcut | |||
| 350 | - | const isGlobalShortcut = (e) => { | |||
| 351 | - | const key = e.key.toLowerCase(); | |||
| 352 | - | const code = e.code.toLowerCase(); | |||
| 353 | - | ||||
| 354 | - | // Build shortcut string (similar to GTK format) | |||
| 355 | - | let shortcut = ''; | |||
| 356 | - | if (e.ctrlKey) shortcut += 'ctrl+'; | |||
| 357 | - | if (e.altKey) shortcut += 'alt+'; | |||
| 358 | - | if (e.shiftKey) shortcut += 'shift+'; | |||
| 359 | - | if (e.metaKey) shortcut += 'meta+'; | |||
| 360 | - | ||||
| 361 | - | // Try both key and code for matching | |||
| 362 | - | const keyShortcut = shortcut + key; | |||
| 363 | - | const codeShortcut = shortcut + code; | |||
| 364 | - | ||||
| 365 | - | // Special case mappings for common shortcuts | |||
| 366 | - | const specialMappings = { | |||
| 367 | - | 'ctrl+equal': ['ctrl+=', 'ctrl+plus'], | |||
| 368 | - | 'ctrl+minus': ['ctrl+-'], | |||
| 369 | - | 'f12': ['f12'], | |||
| 370 | - | 'ctrl+r': ['ctrl+r'], | |||
| 371 | - | 'ctrl+shift+r': ['ctrl+shift+r'], | |||
| 372 | - | 'f5': ['f5'], | |||
| 373 | - | // Alt+Arrow key mappings (handle both key and code variations) | |||
| 374 | - | 'alt+arrowleft': ['alt+left', 'alt+arrowleft'], | |||
| 375 | - | 'alt+arrowright': ['alt+right', 'alt+arrowright'], | |||
| 376 | - | 'alt+arrowup': ['alt+up', 'alt+arrowup'], | |||
| 377 | - | 'alt+arrowdown': ['alt+down', 'alt+arrowdown'] | |||
| 378 | - | }; | |||
| 379 | - | ||||
| 380 | - | // Check direct matches | |||
| 381 | - | if (globalShortcuts.includes(keyShortcut) || globalShortcuts.includes(codeShortcut)) { | |||
| 382 | - | return true; | |||
| 383 | - | } | |||
| 384 | - | ||||
| 385 | - | // Check special mappings | |||
| 386 | - | for (const [canonical, variants] of Object.entries(specialMappings)) { | |||
| 387 | - | if (variants.includes(keyShortcut) || variants.includes(codeShortcut)) { | |||
| 388 | - | if (globalShortcuts.includes(canonical)) { | |||
| 389 | - | return true; | |||
| 390 | - | } | |||
| 391 | - | } | |||
| 392 | - | } | |||
| 393 | - | ||||
| 394 | - | return false; | |||
| 395 | - | }; | |||
| 396 | - | ||||
| 397 | - | // Block only global shortcuts at capture phase | |||
| 398 | - | const blockGlobalShortcut = (e) => { | |||
| 399 | - | if (isGlobalShortcut(e)) { | |||
| 400 | - | console.log('[dumber] Blocked global shortcut from reaching page:', e.key, e.ctrlKey, e.altKey, e.shiftKey); | |||
| 401 | - | e.stopImmediatePropagation(); | |||
| 402 | - | e.preventDefault(); | |||
| 403 | - | e.stopPropagation(); | |||
| 404 | - | return false; | |||
| 405 | - | } | |||
| 406 | - | // Let other key events through normally | |||
| 407 | - | }; | |||
| 408 | - | ||||
| 409 | - | // Install listeners for keyboard events | |||
| 410 | - | document.addEventListener('keydown', blockGlobalShortcut, true); | |||
| 411 | - | document.addEventListener('keyup', blockGlobalShortcut, true); | |||
| 412 | - | document.addEventListener('keypress', blockGlobalShortcut, true); | |||
| 413 | - | ||||
| 414 | - | // Store cleanup function | |||
| 415 | - | window.__dumber_cleanup_global_shortcuts = () => { | |||
| 416 | - | document.removeEventListener('keydown', blockGlobalShortcut, true); | |||
| 417 | - | document.removeEventListener('keyup', blockGlobalShortcut, true); | |||
| 418 | - | document.removeEventListener('keypress', blockGlobalShortcut, true); | |||
| 419 | - | delete window.__dumber_shortcuts_protection_version; | |||
| 420 | - | delete window.__dumber_cleanup_global_shortcuts; | |||
| 421 | - | console.log('[dumber] Global shortcuts protection disabled'); | |||
| 422 | - | }; | |||
| 423 | - | ||||
| 424 | - | console.log('[dumber] Global shortcuts protection enabled for', globalShortcuts.length, 'shortcuts (v' + newVersion + ')'); | |||
| 425 | - | } else { | |||
| 426 | - | console.log('[dumber] Global shortcuts protection already up to date (v' + currentVersion + ')'); | |||
| 427 | - | } | |||
| 428 | - | })(); | |||
| 429 | - | ` | |||
| 430 | - | ||||
| 431 | - | // Inject the script into the main world at document start | |||
| 432 | - | cScript := C.CString(globalProtectionScript) | |||
| 433 | - | defer C.free(unsafe.Pointer(cScript)) | |||
| 434 | - | ||||
| 435 | - | script := C.webkit_user_script_new( | |||
| 436 | - | (*C.gchar)(cScript), | |||
| 437 | - | C.WEBKIT_USER_CONTENT_INJECT_TOP_FRAME, | |||
| 438 | - | C.WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, | |||
| 439 | - | nil, nil) // nil = main world | |||
| 440 | - | ||||
| 441 | - | if script == nil { | |||
| 442 | - | return ErrNotImplemented | |||
| 443 | - | } | |||
| 444 | - | ||||
| 445 | - | C.webkit_user_content_manager_add_script(w.native.ucm, script) | |||
| 446 | - | C.webkit_user_script_unref(script) // Clean up reference | |||
| 447 | - | ||||
| 448 | - | log.Printf("[shortcuts] Global shortcuts protection enabled for %d shortcuts", len(shortcuts)) | |||
| 449 | - | return nil | |||
| 450 | - | } | |||
| 451 | - | ||||
| 452 | - | // DisableGlobalShortcutsProtection removes the global shortcuts protection | |||
| 453 | - | func (w *WebView) DisableGlobalShortcutsProtection() error { | |||
| 454 | - | if w == nil || w.destroyed || w.native == nil { | |||
| 455 | - | return ErrWebViewNotInitialized | |||
| 456 | - | } | |||
| 457 | - | ||||
| 458 | - | // Execute cleanup script | |||
| 459 | - | cleanupScript := ` | |||
| 460 | - | if (window.__dumber_cleanup_global_shortcuts) { | |||
| 461 | - | window.__dumber_cleanup_global_shortcuts(); | |||
| 462 | - | } | |||
| 463 | - | ` | |||
| 464 | - | ||||
| 465 | - | return w.InjectScript(cleanupScript) | |||
| 466 | - | } | |||
| 467 | - | ||||
| 468 | - | // EnablePageKeyboardBlocking injects a script into the main world to block all keyboard events | |||
| 469 | - | // This prevents page JavaScript from receiving keyboard events while omnibox is active | |||
| 470 | - | func (w *WebView) EnablePageKeyboardBlocking() error { | |||
| 471 | - | if w == nil || w.destroyed || w.native == nil || w.native.ucm == nil { | |||
| 472 | - | return ErrWebViewNotInitialized | |||
| 473 | - | } | |||
| 474 | - | ||||
| 475 | - | // Remove any existing blocker script first | |||
| 476 | - | w.DisablePageKeyboardBlocking() | |||
| 477 | - | ||||
| 478 | - | // Script to block all keyboard and related events in the main world | |||
| 479 | - | blockingScript := ` | |||
| 480 | - | (() => { | |||
| 481 | - | // Store original state to restore later | |||
| 482 | - | if (!window.__dumber_event_blocker_installed) { | |||
| 483 | - | window.__dumber_event_blocker_installed = true; | |||
| 484 | - | ||||
| 485 | - | // List of events to block | |||
| 486 | - | const eventTypes = [ | |||
| 487 | - | 'keydown', 'keyup', 'keypress', | |||
| 488 | - | 'input', 'beforeinput', | |||
| 489 | - | 'compositionstart', 'compositionupdate', 'compositionend' | |||
| 490 | - | ]; | |||
| 491 | - | ||||
| 492 | - | // Block all keyboard-related events at capture phase | |||
| 493 | - | const blockEvent = (e) => { | |||
| 494 | - | e.stopImmediatePropagation(); | |||
| 495 | - | e.preventDefault(); | |||
| 496 | - | e.stopPropagation(); | |||
| 497 | - | return false; | |||
| 498 | - | }; | |||
| 499 | - | ||||
| 500 | - | // Install capture-phase event blockers | |||
| 501 | - | eventTypes.forEach(type => { | |||
| 502 | - | document.addEventListener(type, blockEvent, true); | |||
| 503 | - | }); | |||
| 504 | - | ||||
| 505 | - | // Store cleanup function | |||
| 506 | - | window.__dumber_cleanup_event_blocker = () => { | |||
| 507 | - | eventTypes.forEach(type => { | |||
| 508 | - | document.removeEventListener(type, blockEvent, true); | |||
| 509 | - | }); | |||
| 510 | - | delete window.__dumber_event_blocker_installed; | |||
| 511 | - | delete window.__dumber_cleanup_event_blocker; | |||
| 512 | - | }; | |||
| 513 | - | ||||
| 514 | - | console.log('[dumber] Page keyboard event blocking enabled'); | |||
| 515 | - | } | |||
| 516 | - | })(); | |||
| 517 | - | ` | |||
| 518 | - | ||||
| 519 | - | cScript := C.CString(blockingScript) | |||
| 520 | - | defer C.free(unsafe.Pointer(cScript)) | |||
| 521 | - | ||||
| 522 | - | // Inject into main world (nil world parameter = main world) | |||
| 523 | - | keyboardBlockerScript = C.webkit_user_script_new( | |||
| 524 | - | (*C.gchar)(cScript), | |||
| 525 | - | C.WEBKIT_USER_CONTENT_INJECT_TOP_FRAME, | |||
| 526 | - | C.WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, | |||
| 527 | - | nil, nil) // nil = main world | |||
| 528 | - | ||||
| 529 | - | if keyboardBlockerScript == nil { | |||
| 530 | - | return ErrNotImplemented | |||
| 531 | - | } | |||
| 532 | - | ||||
| 533 | - | C.webkit_user_content_manager_add_script(w.native.ucm, keyboardBlockerScript) | |||
| 534 | - | log.Printf("[webkit] Page keyboard event blocking enabled") | |||
| 535 | - | return nil | |||
| 536 | - | } | |||
| 537 | - | ||||
| 538 | - | // DisablePageKeyboardBlocking removes the keyboard blocking script and restores normal page behavior | |||
| 539 | - | func (w *WebView) DisablePageKeyboardBlocking() error { | |||
| 540 | - | if w == nil || w.destroyed || w.native == nil || w.native.ucm == nil { | |||
| 541 | - | return ErrWebViewNotInitialized | |||
| 542 | - | } | |||
| 543 | - | ||||
| 544 | - | // Execute cleanup script to remove event listeners | |||
| 545 | - | cleanupScript := ` | |||
| 546 | - | if (window.__dumber_cleanup_event_blocker) { | |||
| 547 | - | window.__dumber_cleanup_event_blocker(); | |||
| 548 | - | console.log('[dumber] Page keyboard event blocking disabled'); | |||
| 549 | - | } | |||
| 550 | - | ` | |||
| 551 | - | // Double-check WebView is still valid before script injection | |||
| 552 | - | if !w.IsDestroyed() { | |||
| 553 | - | w.InjectScript(cleanupScript) | |||
| 554 | - | } | |||
| 555 | - | ||||
| 556 | - | // Remove the user script if it exists | |||
| 557 | - | if keyboardBlockerScript != nil { | |||
| 558 | - | C.webkit_user_content_manager_remove_script(w.native.ucm, keyboardBlockerScript) | |||
| 559 | - | C.webkit_user_script_unref(keyboardBlockerScript) | |||
| 560 | - | keyboardBlockerScript = nil | |||
| 561 | - | log.Printf("[webkit] Keyboard blocker script removed") | |||
| 562 | - | } | |||
| 563 | - | ||||
| 564 | - | return nil | |||
| 565 | - | } | |||
D pkg/webkit/thread_helpers.c +0 -20
| @@ -1,20 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | // +build webkit_cgo | |||
| 3 | - | ||||
| 4 | - | #include <glib.h> | |||
| 5 | - | #include <pthread.h> | |||
| 6 | - | ||||
| 7 | - | static pthread_t main_thread_id; | |||
| 8 | - | ||||
| 9 | - | void store_main_thread_id() { | |||
| 10 | - | main_thread_id = pthread_self(); | |||
| 11 | - | } | |||
| 12 | - | ||||
| 13 | - | int is_main_thread() { | |||
| 14 | - | return pthread_equal(pthread_self(), main_thread_id); | |||
| 15 | - | } | |||
| 16 | - | ||||
| 17 | - | int iterate_main_loop() { | |||
| 18 | - | GMainContext *ctx = g_main_context_default(); | |||
| 19 | - | return g_main_context_iteration(ctx, FALSE); | |||
| 20 | - | } | |||
D pkg/webkit/toast_svelte_cgo.go +0 -73
| @@ -1,73 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | import ( | |||
| 6 | - | "fmt" | |||
| 7 | - | "log" | |||
| 8 | - | ) | |||
| 9 | - | ||||
| 10 | - | // getToastScript returns the unified GUI bundle-based toast notification script with GTK theme integration. | |||
| 11 | - | // This function is deprecated and should use the new unified approach via BrowserService.InjectToastSystem | |||
| 12 | - | func getToastScript(assets interface{ ReadFile(string) ([]byte, error) }) string { | |||
| 13 | - | // Read the unified GUI bundle from assets | |||
| 14 | - | var guiBundle string | |||
| 15 | - | if assets != nil { | |||
| 16 | - | bundleBytes, err := assets.ReadFile("gui/gui.min.js") | |||
| 17 | - | if err != nil { | |||
| 18 | - | // Fallback to error message if file not found | |||
| 19 | - | guiBundle = `console.error("❌ Failed to load unified GUI bundle: ` + err.Error() + `");` | |||
| 20 | - | log.Printf("[webkit] Failed to read GUI bundle: %v", err) | |||
| 21 | - | } else { | |||
| 22 | - | guiBundle = string(bundleBytes) | |||
| 23 | - | log.Printf("[webkit] Successfully loaded unified GUI bundle (%d bytes)", len(bundleBytes)) | |||
| 24 | - | } | |||
| 25 | - | } else { | |||
| 26 | - | guiBundle = `console.error("❌ Failed to load unified GUI bundle: assets not provided");` | |||
| 27 | - | log.Printf("[webkit] GUI bundle error: assets not provided") | |||
| 28 | - | } | |||
| 29 | - | ||||
| 30 | - | // GTK Theme Integration with new unified approach | |||
| 31 | - | themeIntegration := ` | |||
| 32 | - | // Set up theme change listener for dynamic updates | |||
| 33 | - | window.__dumber_setTheme = (theme) => { | |||
| 34 | - | window.__dumber_initial_theme = theme; | |||
| 35 | - | if (theme === 'dark') { | |||
| 36 | - | document.documentElement.classList.add('dark'); | |||
| 37 | - | } else { | |||
| 38 | - | document.documentElement.classList.remove('dark'); | |||
| 39 | - | } | |||
| 40 | - | }; | |||
| 41 | - | ` | |||
| 42 | - | ||||
| 43 | - | // Use unified GUI bundle approach | |||
| 44 | - | return fmt.Sprintf(`(function() { | |||
| 45 | - | function initializeToast() { | |||
| 46 | - | try { | |||
| 47 | - | %s | |||
| 48 | - | ||||
| 49 | - | %s | |||
| 50 | - | ||||
| 51 | - | // Initialize toast system via unified GUI bundle | |||
| 52 | - | if (window.__dumber_gui && window.__dumber_gui.initializeToast) { | |||
| 53 | - | window.__dumber_gui.initializeToast().then(() => { | |||
| 54 | - | console.log('✅ Toast system initialized via unified GUI bundle'); | |||
| 55 | - | }).catch((e) => { | |||
| 56 | - | console.error('❌ Toast initialization failed:', e); | |||
| 57 | - | }); | |||
| 58 | - | } else { | |||
| 59 | - | console.error('❌ Unified GUI bundle not properly loaded'); | |||
| 60 | - | } | |||
| 61 | - | } catch (e) { | |||
| 62 | - | console.error('❌ Failed to initialize toast system:', e); | |||
| 63 | - | } | |||
| 64 | - | } | |||
| 65 | - | ||||
| 66 | - | // Ensure DOM is ready before initializing | |||
| 67 | - | if (document.readyState === 'loading') { | |||
| 68 | - | document.addEventListener('DOMContentLoaded', initializeToast); | |||
| 69 | - | } else { | |||
| 70 | - | initializeToast(); | |||
| 71 | - | } | |||
| 72 | - | })();`, themeIntegration, guiBundle) | |||
| 73 | - | } | |||
A pkg/webkit/types.go +60 -0
| @@ -0,0 +1,60 @@ | |||||
| 1 | + | package webkit | |||
| 2 | + | ||||
| 3 | + | // WindowType indicates how a new WebView should be treated | |||
| 4 | + | type WindowType int | |||
| 5 | + | ||||
| 6 | + | const ( | |||
| 7 | + | // WindowTypeTab represents an independent WebView (future: tab) | |||
| 8 | + | WindowTypeTab WindowType = iota | |||
| 9 | + | // WindowTypePopup represents a related WebView (shares process/context) | |||
| 10 | + | WindowTypePopup | |||
| 11 | + | // WindowTypeUnknown indicates type not detected yet | |||
| 12 | + | WindowTypeUnknown | |||
| 13 | + | ) | |||
| 14 | + | ||||
| 15 | + | // WindowFeatures describes the window features detected from WebKitWindowProperties | |||
| 16 | + | type WindowFeatures struct { | |||
| 17 | + | Width int | |||
| 18 | + | Height int | |||
| 19 | + | ToolbarVisible bool | |||
| 20 | + | LocationbarVisible bool | |||
| 21 | + | MenubarVisible bool | |||
| 22 | + | Resizable bool | |||
| 23 | + | } | |||
| 24 | + | ||||
| 25 | + | // Config holds WebView configuration | |||
| 26 | + | type Config struct { | |||
| 27 | + | // UserAgent string for the WebView | |||
| 28 | + | UserAgent string | |||
| 29 | + | ||||
| 30 | + | // EnableJavaScript controls JavaScript execution | |||
| 31 | + | EnableJavaScript bool | |||
| 32 | + | ||||
| 33 | + | // EnableWebGL controls WebGL support | |||
| 34 | + | EnableWebGL bool | |||
| 35 | + | ||||
| 36 | + | // EnableMediaStream controls media stream support | |||
| 37 | + | EnableMediaStream bool | |||
| 38 | + | ||||
| 39 | + | // HardwareAcceleration controls GPU acceleration | |||
| 40 | + | HardwareAcceleration bool | |||
| 41 | + | ||||
| 42 | + | // DefaultFontSize in pixels | |||
| 43 | + | DefaultFontSize int | |||
| 44 | + | ||||
| 45 | + | // MinimumFontSize in pixels | |||
| 46 | + | MinimumFontSize int | |||
| 47 | + | } | |||
| 48 | + | ||||
| 49 | + | // GetDefaultConfig returns a Config with sensible defaults | |||
| 50 | + | func GetDefaultConfig() *Config { | |||
| 51 | + | return &Config{ | |||
| 52 | + | UserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36", | |||
| 53 | + | EnableJavaScript: true, | |||
| 54 | + | EnableWebGL: true, | |||
| 55 | + | EnableMediaStream: true, | |||
| 56 | + | HardwareAcceleration: true, | |||
| 57 | + | DefaultFontSize: 16, | |||
| 58 | + | MinimumFontSize: 8, | |||
| 59 | + | } | |||
| 60 | + | } | |||
D pkg/webkit/ucm_js_cgo.go.deprecated +0 -335
| @@ -1,335 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | // getOmniboxScript returns the injected omnibox/find component script. | |||
| 6 | - | // Kept in a cgo-tagged file to ensure availability when referenced | |||
| 7 | - | // from other cgo files in this package. | |||
| 8 | - | func getOmniboxScript() string { | |||
| 9 | - | return `(() => { | |||
| 10 | - | try { | |||
| 11 | - | if (window.__dumber_omnibox_loaded) return; // idempotent | |||
| 12 | - | window.__dumber_omnibox_loaded = true; | |||
| 13 | - | ||||
| 14 | - | const MAX_MATCHES = 2000; | |||
| 15 | - | const H = { | |||
| 16 | - | el: null, | |||
| 17 | - | box: null, | |||
| 18 | - | input: null, | |||
| 19 | - | list: null, | |||
| 20 | - | visible: false, | |||
| 21 | - | mode: 'omnibox', // 'omnibox' | 'find' | |||
| 22 | - | suggestions: [], | |||
| 23 | - | matches: [], // {el, context} | |||
| 24 | - | selectedIndex: -1, | |||
| 25 | - | activeIndex: -1, | |||
| 26 | - | debounceTimer: 0, | |||
| 27 | - | highlightNodes: [], | |||
| 28 | - | faded: false, | |||
| 29 | - | prevOverflow: '', | |||
| 30 | - | post(msg){ try { window.webkit?.messageHandlers?.dumber?.postMessage(JSON.stringify(msg)); } catch(_){} }, | |||
| 31 | - | render(){ | |||
| 32 | - | // Performance optimization: elements are pre-mounted, just show/hide | |||
| 33 | - | H.el.style.display = H.visible ? 'block' : 'none'; | |||
| 34 | - | if (!H.visible) return; | |||
| 35 | - | H.input.placeholder = H.mode === 'find' ? 'Find in page…' : 'Type URL or search…'; | |||
| 36 | - | H.input.focus(); | |||
| 37 | - | }, | |||
| 38 | - | setMode(m){ H.mode = m === 'find' ? 'find' : 'omnibox'; H.selectedIndex = -1; H.setFaded(false); H.paintList(); }, | |||
| 39 | - | open(mode, initial){ H.setMode(mode||'omnibox'); H.toggle(true); if (typeof initial==='string') { H.input.value = initial; H.onInput(); } }, | |||
| 40 | - | close(){ if (H.mode==='find') H.clearHighlights(); H.setFaded(false); H.toggle(false); }, | |||
| 41 | - | toggle(v){ | |||
| 42 | - | const newState = (typeof v==='boolean')? v : !H.visible; | |||
| 43 | - | if (newState && !H.visible) { | |||
| 44 | - | // Disable page scrolling while overlay is visible | |||
| 45 | - | H.prevOverflow = document.documentElement.style.overflow; | |||
| 46 | - | document.documentElement.style.overflow = 'hidden'; | |||
| 47 | - | } else if (!newState && H.visible) { | |||
| 48 | - | // Restore page scrolling on close | |||
| 49 | - | document.documentElement.style.overflow = H.prevOverflow || ''; | |||
| 50 | - | H.prevOverflow = ''; | |||
| 51 | - | } | |||
| 52 | - | H.visible = newState; | |||
| 53 | - | H.render(); | |||
| 54 | - | }, | |||
| 55 | - | setFaded(v){ | |||
| 56 | - | H.faded = !!v; | |||
| 57 | - | if (!H.box || !H.input || !H.list) return; | |||
| 58 | - | if (H.faded) { | |||
| 59 | - | H.box.style.background = 'rgba(27,27,27,0.25)'; | |||
| 60 | - | H.box.style.backdropFilter = 'blur(2px) saturate(110%)'; | |||
| 61 | - | H.box.style.webkitBackdropFilter = 'blur(2px) saturate(110%)'; | |||
| 62 | - | H.input.style.background = 'rgba(18,18,18,0.35)'; | |||
| 63 | - | H.input.style.color = '#eee'; | |||
| 64 | - | } else { | |||
| 65 | - | H.box.style.background = '#1b1b1b'; | |||
| 66 | - | H.box.style.backdropFilter = ''; | |||
| 67 | - | H.box.style.webkitBackdropFilter = ''; | |||
| 68 | - | H.input.style.background = '#121212'; | |||
| 69 | - | H.input.style.color = '#eee'; | |||
| 70 | - | } | |||
| 71 | - | }, | |||
| 72 | - | scrollListToSelection(){ | |||
| 73 | - | if (!H.list) return; | |||
| 74 | - | let idx = H.selectedIndex|0; | |||
| 75 | - | if (idx < 0) return; | |||
| 76 | - | // Account for header in find mode | |||
| 77 | - | const childIdx = (H.mode==='find' ? 1 : 0) + idx; | |||
| 78 | - | const el = H.list.children[childIdx]; | |||
| 79 | - | if (el && el.scrollIntoView) { | |||
| 80 | - | try { el.scrollIntoView({block:'nearest'}); } catch(_) { el.scrollIntoView(); } | |||
| 81 | - | } | |||
| 82 | - | }, | |||
| 83 | - | mount(){ | |||
| 84 | - | const root = document.createElement('div'); | |||
| 85 | - | root.id = 'dumber-omnibox-root'; | |||
| 86 | - | root.style.cssText = 'position:fixed;inset:0;z-index:2147483647;display:none;'; | |||
| 87 | - | const box = document.createElement('div'); | |||
| 88 | - | box.style.cssText = 'width:min(90vw, 720px);margin:8vh auto;padding:8px 12px;background:#1b1b1b;color:#eee;border:1px solid #444;border-radius:8px;box-shadow:0 10px 30px rgba(0,0,0,.6);font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,"Helvetica Neue",Arial,sans-serif;'; | |||
| 89 | - | const input = document.createElement('input'); | |||
| 90 | - | input.type = 'text'; | |||
| 91 | - | input.placeholder = 'Type URL or search…'; | |||
| 92 | - | input.style.cssText = 'width:100%;box-sizing:border-box;padding:10px 12px;border-radius:6px;border:1px solid #555;background:#121212;color:#eee;font-size:16px;outline:none;'; | |||
| 93 | - | const list = document.createElement('div'); | |||
| 94 | - | list.style.cssText = 'margin-top:8px;max-height:50vh;overflow:auto;'; | |||
| 95 | - | const style = document.createElement('style'); | |||
| 96 | - | style.textContent = '.dumber-find-highlight{background:#ffeb3b;color:#000;padding:0 1px;border-radius:2px;box-shadow:0 0 0 1px #c8b900 inset}.dumber-find-active{background:#ff9800 !important;color:#000;box-shadow:0 0 0 1px #b36b00 inset}'; | |||
| 97 | - | document.documentElement.appendChild(style); | |||
| 98 | - | box.appendChild(input); box.appendChild(list); root.appendChild(box); document.documentElement.appendChild(root); | |||
| 99 | - | H.box = box; | |||
| 100 | - | // Dynamic style updater for responsive behavior | |||
| 101 | - | const updateStyles = () => { | |||
| 102 | - | const vw = window.innerWidth; | |||
| 103 | - | const isSmall = vw < 640; | |||
| 104 | - | const isLarge = vw > 1920; | |||
| 105 | - | ||||
| 106 | - | if (box) { | |||
| 107 | - | box.style.width = isSmall ? '95vw' : isLarge ? 'min(90vw, 840px)' : 'min(90vw, 720px)'; | |||
| 108 | - | box.style.padding = isSmall ? '6px 8px' : '8px 12px'; | |||
| 109 | - | } | |||
| 110 | - | ||||
| 111 | - | if (input) { | |||
| 112 | - | input.style.fontSize = isSmall ? '14px' : isLarge ? '17px' : '16px'; | |||
| 113 | - | input.style.padding = isSmall ? '8px 10px' : '10px 12px'; | |||
| 114 | - | input.style.boxSizing = 'border-box'; | |||
| 115 | - | } | |||
| 116 | - | }; | |||
| 117 | - | updateStyles(); | |||
| 118 | - | window.addEventListener('resize', updateStyles); | |||
| 119 | - | // Click outside the box closes the overlay | |||
| 120 | - | root.addEventListener('mousedown', (e)=>{ | |||
| 121 | - | const tgt = e.target; | |||
| 122 | - | if (tgt && box && !box.contains(tgt)) { | |||
| 123 | - | e.preventDefault(); | |||
| 124 | - | e.stopPropagation(); | |||
| 125 | - | H.close(); | |||
| 126 | - | } | |||
| 127 | - | }, true); | |||
| 128 | - | box.addEventListener('mousedown', (e)=>{ e.stopPropagation(); }, true); | |||
| 129 | - | // Focus and select input on hover for quick typing | |||
| 130 | - | input.addEventListener('mouseenter', ()=>{ if (H.visible) { try { input.focus({preventScroll:true}); input.select(); } catch(_) { input.focus(); } } }); | |||
| 131 | - | root.addEventListener('mouseenter', ()=>{ if (H.visible) { try { input.focus({preventScroll:true}); } catch(_) { input.focus(); } H.setFaded(false); } }); | |||
| 132 | - | // Clear fading when user goes back to input typing | |||
| 133 | - | input.addEventListener('focus', ()=> H.setFaded(false)); | |||
| 134 | - | input.addEventListener('keydown', (e)=>{ | |||
| 135 | - | if (e.key === 'Escape'){ H.close(); } | |||
| 136 | - | else if (H.mode==='omnibox' && e.key === 'Enter'){ | |||
| 137 | - | const pick = H.suggestions && H.suggestions[H.selectedIndex|0]; | |||
| 138 | - | const v = (pick && pick.url) || input.value || ''; | |||
| 139 | - | if (v) H.post({type:'navigate', url:v}); | |||
| 140 | - | H.toggle(false); | |||
| 141 | - | } else if (H.mode==='find' && e.key === 'Enter'){ | |||
| 142 | - | e.preventDefault(); | |||
| 143 | - | if (e.shiftKey) { | |||
| 144 | - | H.jump(-1); | |||
| 145 | - | } else if (e.altKey) { | |||
| 146 | - | // Center on current match but keep overlay open for further navigation | |||
| 147 | - | H.revealSelection(); | |||
| 148 | - | } else { | |||
| 149 | - | // Default: center and close | |||
| 150 | - | H.revealSelection(); | |||
| 151 | - | H.close(); | |||
| 152 | - | } | |||
| 153 | - | } else if (e.key === 'ArrowDown' || e.key === 'ArrowUp'){ | |||
| 154 | - | e.preventDefault(); e.stopPropagation(); | |||
| 155 | - | const n = (H.mode==='find'? H.matches.length : H.suggestions.length); | |||
| 156 | - | if (n){ | |||
| 157 | - | H.selectedIndex = (H.selectedIndex||0) + (e.key==='ArrowDown'?1:-1); | |||
| 158 | - | if (H.selectedIndex<0) H.selectedIndex = n-1; if (H.selectedIndex>=n) H.selectedIndex = 0; | |||
| 159 | - | H.paintList(); | |||
| 160 | - | H.scrollListToSelection(); | |||
| 161 | - | // Fade overlay while navigating results; also reveal active match in find mode | |||
| 162 | - | H.setFaded(true); | |||
| 163 | - | if (H.mode==='find') { H.revealSelection(); } | |||
| 164 | - | } | |||
| 165 | - | } else { | |||
| 166 | - | // Any other key input should restore full opacity while editing | |||
| 167 | - | H.setFaded(false); | |||
| 168 | - | } | |||
| 169 | - | }); | |||
| 170 | - | input.addEventListener('input', ()=> { H.onInput(); H.setFaded(false); }); | |||
| 171 | - | input.addEventListener('mousedown', ()=> H.setFaded(false)); | |||
| 172 | - | input.addEventListener('click', ()=> H.setFaded(false)); | |||
| 173 | - | H.el = root; H.input = input; H.list = list; H.selectedIndex = -1; H.paintList(); | |||
| 174 | - | }, | |||
| 175 | - | onInput(){ | |||
| 176 | - | const q = H.input.value || ''; | |||
| 177 | - | if (H.mode === 'omnibox'){ | |||
| 178 | - | clearTimeout(H.debounceTimer); | |||
| 179 | - | H.debounceTimer = setTimeout(()=> H.post({type:'query', q, limit:10}), 120); | |||
| 180 | - | } else { | |||
| 181 | - | H.find(q); | |||
| 182 | - | } | |||
| 183 | - | }, | |||
| 184 | - | paintList(){ | |||
| 185 | - | const list = H.list; if (!list) return; list.textContent = ''; | |||
| 186 | - | ||||
| 187 | - | // Show/hide separator based on content | |||
| 188 | - | const hasContent = (H.mode==='omnibox' && H.suggestions.length > 0) || (H.mode==='find' && H.matches.length > 0); | |||
| 189 | - | list.style.borderTop = hasContent ? '1px solid #333' : 'none'; | |||
| 190 | - | ||||
| 191 | - | if (H.mode==='omnibox'){ | |||
| 192 | - | H.suggestions.forEach((s, i)=>{ | |||
| 193 | - | const item = document.createElement('div'); | |||
| 194 | - | item.style.cssText = 'padding:8px 10px;display:flex;gap:10px;align-items:center;cursor:pointer;border-bottom:1px solid #2a2a2a;'+(i===H.selectedIndex?'background:#0a0a0a;':''); | |||
| 195 | - | // Favicon chip (wrapper ensures perfect circle sizing) | |||
| 196 | - | const chip = document.createElement('div'); | |||
| 197 | - | chip.style.cssText = 'flex:0 0 20px;width:20px;height:20px;border-radius:50%;background:#ccc;border:1px solid rgba(0,0,0,.12);box-shadow:0 1px 2px rgba(0,0,0,.12);display:flex;align-items:center;justify-content:center;'; | |||
| 198 | - | const icon = document.createElement('img'); | |||
| 199 | - | icon.src = s.favicon || ''; | |||
| 200 | - | icon.loading = 'lazy'; | |||
| 201 | - | icon.style.cssText = 'width:16px;height:16px;filter:brightness(1.06) contrast(1.03);image-rendering:-webkit-optimize-contrast;'; | |||
| 202 | - | icon.onerror = ()=>{ chip.style.display='none'; }; | |||
| 203 | - | chip.appendChild(icon); | |||
| 204 | - | // Text line: Domain | full path (one line, fade at end) | |||
| 205 | - | let domain = '', path = ''; | |||
| 206 | - | try { const u = new URL(s.url, window.location.href); domain = u.hostname; path = (u.pathname||'') + (u.search||'') + (u.hash||''); } catch(_) { domain = s.url || ''; } | |||
| 207 | - | const text = document.createElement('div'); | |||
| 208 | - | text.style.cssText = 'flex:1;min-width:0;display:flex;gap:8px;align-items:center;white-space:nowrap;overflow:hidden;'; | |||
| 209 | - | // Apply gradient fade using mask for WebKit | |||
| 210 | - | text.style.webkitMaskImage = 'linear-gradient(90deg, black 85%, transparent 100%)'; | |||
| 211 | - | text.style.maskImage = 'linear-gradient(90deg, black 85%, transparent 100%)'; | |||
| 212 | - | const domainEl = document.createElement('span'); domainEl.textContent = domain; domainEl.style.cssText = 'color:#e6e6e6;opacity:.95;'; | |||
| 213 | - | const sep = document.createElement('span'); sep.textContent = ' | '; sep.style.cssText = 'color:#777;'; | |||
| 214 | - | const pathEl = document.createElement('span'); pathEl.textContent = path || '/'; pathEl.style.cssText = 'color:#9ad;'; | |||
| 215 | - | text.appendChild(domainEl); text.appendChild(sep); text.appendChild(pathEl); | |||
| 216 | - | item.appendChild(chip); item.appendChild(text); | |||
| 217 | - | item.addEventListener('mouseenter', ()=>{ H.selectedIndex = i; H.paintList(); H.scrollListToSelection(); H.setFaded(true); }); | |||
| 218 | - | item.addEventListener('click',()=>{ H.post({type:'navigate', url:s.url}); H.toggle(false); }); | |||
| 219 | - | list.appendChild(item); | |||
| 220 | - | }); | |||
| 221 | - | } else { | |||
| 222 | - | const total = H.matches.length; | |||
| 223 | - | const header = document.createElement('div'); | |||
| 224 | - | header.textContent = total ? total + ' matches' : 'No matches'; | |||
| 225 | - | header.style.cssText = 'padding:6px 10px;color:#bbb;font-size:12px;border-bottom:1px solid #2a2a2a;'; | |||
| 226 | - | list.appendChild(header); | |||
| 227 | - | H.matches.forEach((m, i)=>{ | |||
| 228 | - | const item = document.createElement('div'); | |||
| 229 | - | item.style.cssText = 'padding:8px 10px;cursor:pointer;border-bottom:1px solid #2a2a2a;'+(i===H.selectedIndex?'background:#0a0a0a;':''); | |||
| 230 | - | const ctx = document.createElement('div'); ctx.textContent = m.context || ''; ctx.style.cssText = 'color:#ddd;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;'; | |||
| 231 | - | item.appendChild(ctx); | |||
| 232 | - | item.addEventListener('mouseenter', ()=>{ H.selectedIndex = i; H.paintList(); H.scrollListToSelection(); H.setFaded(true); }); | |||
| 233 | - | item.addEventListener('click',()=>{ H.selectedIndex=i; H.revealSelection(); H.paintList(); H.close(); }); | |||
| 234 | - | list.appendChild(item); | |||
| 235 | - | }); | |||
| 236 | - | } | |||
| 237 | - | }, | |||
| 238 | - | setSuggestions(arr){ H.suggestions = Array.isArray(arr)? arr: []; H.selectedIndex = -1; H.paintList(); }, | |||
| 239 | - | // FIND MODE IMPLEMENTATION | |||
| 240 | - | clearHighlights(){ | |||
| 241 | - | try { | |||
| 242 | - | H.highlightNodes.forEach(({span, text})=>{ | |||
| 243 | - | const p = span.parentNode; if (!p) return; p.replaceChild(text, span); p.normalize(); | |||
| 244 | - | }); | |||
| 245 | - | } catch(_){} | |||
| 246 | - | H.highlightNodes = []; | |||
| 247 | - | H.matches = []; | |||
| 248 | - | H.selectedIndex = -1; | |||
| 249 | - | H.activeIndex = -1; | |||
| 250 | - | H.paintList(); | |||
| 251 | - | }, | |||
| 252 | - | find(q){ | |||
| 253 | - | H.clearHighlights(); | |||
| 254 | - | q = (q||'').trim(); if (!q) return; | |||
| 255 | - | const body = document.body; if (!body) return; | |||
| 256 | - | const root = document.getElementById('dumber-omnibox-root'); | |||
| 257 | - | const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT, { | |||
| 258 | - | acceptNode(node){ | |||
| 259 | - | if (!node.nodeValue || !node.nodeValue.trim()) return NodeFilter.FILTER_REJECT; | |||
| 260 | - | let el = node.parentElement; if (!el) return NodeFilter.FILTER_REJECT; | |||
| 261 | - | if (root && root.contains(el)) return NodeFilter.FILTER_REJECT; | |||
| 262 | - | const name = el.tagName; if (name==='SCRIPT'||name==='STYLE'||name==='NOSCRIPT') return NodeFilter.FILTER_REJECT; | |||
| 263 | - | if (getComputedStyle(el).visibility==='hidden' || getComputedStyle(el).display==='none') return NodeFilter.FILTER_REJECT; | |||
| 264 | - | return NodeFilter.FILTER_ACCEPT; | |||
| 265 | - | } | |||
| 266 | - | }); | |||
| 267 | - | const lc = q.toLowerCase(); | |||
| 268 | - | while (walker.nextNode()){ | |||
| 269 | - | const text = walker.currentNode; | |||
| 270 | - | let s = text.nodeValue; let i = 0; | |||
| 271 | - | while (s && (i = s.toLowerCase().indexOf(lc)) !== -1) { | |||
| 272 | - | const before = document.createTextNode(s.slice(0, i)); | |||
| 273 | - | const match = document.createTextNode(s.slice(i, i+q.length)); | |||
| 274 | - | const afterVal = s.slice(i+q.length); | |||
| 275 | - | const span = document.createElement('span'); span.className = 'dumber-find-highlight'; span.appendChild(match); | |||
| 276 | - | const parent = text.parentNode; if (!parent) break; | |||
| 277 | - | parent.insertBefore(before, text); | |||
| 278 | - | parent.insertBefore(span, text); | |||
| 279 | - | text.nodeValue = afterVal; | |||
| 280 | - | H.highlightNodes.push({span, text: match}); | |||
| 281 | - | const leftCtx = before.nodeValue.slice(-30); | |||
| 282 | - | let rightRaw = afterVal.slice(0, 30); | |||
| 283 | - | const boundaryIdx = rightRaw.search(/[\.,;:\-]/); | |||
| 284 | - | if (boundaryIdx !== -1) { | |||
| 285 | - | rightRaw = rightRaw.slice(0, boundaryIdx+1); | |||
| 286 | - | } | |||
| 287 | - | const context = (leftCtx + match.nodeValue + rightRaw).replace(/\s+/g,' ').trim(); | |||
| 288 | - | H.matches.push({el: span, context}); | |||
| 289 | - | if (H.matches.length >= MAX_MATCHES) break; | |||
| 290 | - | s = afterVal; | |||
| 291 | - | } | |||
| 292 | - | if (H.matches.length >= MAX_MATCHES) break; | |||
| 293 | - | } | |||
| 294 | - | H.selectedIndex = H.matches.length ? 0 : -1; | |||
| 295 | - | H.paintList(); | |||
| 296 | - | H.revealSelection(); | |||
| 297 | - | }, | |||
| 298 | - | revealSelection(){ | |||
| 299 | - | const prev = H.matches[H.activeIndex|0]; | |||
| 300 | - | if (prev && prev.el && prev.el.classList) { prev.el.classList.remove('dumber-find-active'); } | |||
| 301 | - | const m = H.matches[H.selectedIndex|0]; if (!m) return; | |||
| 302 | - | if (m.el && m.el.classList) { m.el.classList.add('dumber-find-active'); } | |||
| 303 | - | H.activeIndex = H.selectedIndex|0; | |||
| 304 | - | try { m.el.scrollIntoView({block:'center', inline:'nearest'}); } catch(_){ m.el.scrollIntoView(); } | |||
| 305 | - | }, | |||
| 306 | - | jump(delta){ | |||
| 307 | - | const n = H.matches.length; if (!n) return; | |||
| 308 | - | H.selectedIndex = ((H.selectedIndex||0) + delta) % n; if (H.selectedIndex<0) H.selectedIndex = n-1; | |||
| 309 | - | H.paintList(); H.revealSelection(); | |||
| 310 | - | } | |||
| 311 | - | }; | |||
| 312 | - | ||||
| 313 | - | // Keyboard hooks | |||
| 314 | - | window.addEventListener('keydown', (e)=>{ | |||
| 315 | - | const mod = (e.ctrlKey||e.metaKey); | |||
| 316 | - | if (mod && (e.key==='l' || e.key==='L')) { e.preventDefault(); H.open('omnibox'); } | |||
| 317 | - | if (mod && (e.key==='f' || e.key==='F')) { e.preventDefault(); H.open('find'); } | |||
| 318 | - | }, true); | |||
| 319 | - | ||||
| 320 | - | // Public API for native | |||
| 321 | - | window.__dumber_setSuggestions = (arr)=> H.setSuggestions(arr); | |||
| 322 | - | window.__dumber_toggle = ()=> H.toggle(); | |||
| 323 | - | window.__dumber_find_open = (q)=> H.open('find', q||''); | |||
| 324 | - | window.__dumber_find_close = ()=> H.close(); | |||
| 325 | - | window.__dumber_find_query = (q)=> { if (H.mode!=='find') H.setMode('find'); if (!H.visible) H.toggle(true); H.input.value = q||''; H.find(q||''); }; | |||
| 326 | - | ||||
| 327 | - | // Performance optimization: Pre-mount DOM elements immediately for instant show/hide | |||
| 328 | - | if (document.readyState === 'loading') { | |||
| 329 | - | document.addEventListener('DOMContentLoaded', ()=> H.mount()); | |||
| 330 | - | } else { | |||
| 331 | - | H.mount(); // DOM already ready | |||
| 332 | - | } | |||
| 333 | - | } catch (e) { /* no-op */ } | |||
| 334 | - | })();` | |||
| 335 | - | } | |||
M pkg/webkit/webview.go +297 -217
| @@ -1,317 +1,397 @@ | |||||
| 1 | - | //go:build !webkit_cgo | |||
| 2 | - | ||||
| 3 | package webkit | 1 | package webkit | ||
| 4 | 2 | ||||
| 5 | import ( | 3 | import ( | ||
| 6 | "fmt" | 4 | "fmt" | ||
| 7 | - | "log" | 5 | + | "sync" |
| 8 | - | "strconv" | |||
| 9 | "sync/atomic" | 6 | "sync/atomic" | ||
| 10 | - | "unsafe" | 7 | + | |
| 8 | + | webkit "github.com/diamondburned/gotk4-webkitgtk/pkg/webkit/v6" | |||
| 9 | + | "github.com/diamondburned/gotk4/pkg/gtk/v4" | |||
| 11 | ) | 10 | ) | ||
| 12 | 11 | ||||
| 13 | - | // Package-level ID counter for stub WebViews | 12 | + | var ( |
| 14 | - | var stubViewIDCounter uint64 | 13 | + | viewIDCounter uint64 |
| 14 | + | viewRegistry = make(map[uint64]*WebView) | |||
| 15 | + | viewMu sync.RWMutex | |||
| 16 | + | ) | |||
| 15 | 17 | ||||
| 16 | - | // nextStubViewID generates a unique ID for stub WebViews | 18 | + | // WebView wraps a WebKitGTK WebView |
| 17 | - | func nextStubViewID() uintptr { | 19 | + | type WebView struct { |
| 18 | - | return uintptr(atomic.AddUint64(&stubViewIDCounter, 1)) | 20 | + | view *webkit.WebView |
| 21 | + | id uint64 | |||
| 22 | + | ||||
| 23 | + | // State | |||
| 24 | + | config *Config | |||
| 25 | + | destroyed bool | |||
| 26 | + | mu sync.RWMutex | |||
| 27 | + | ||||
| 28 | + | // Event handlers | |||
| 29 | + | onScriptMessage func(string) | |||
| 30 | + | onTitleChanged func(string) | |||
| 31 | + | onURIChanged func(string) | |||
| 32 | + | onFaviconChanged func([]byte) | |||
| 33 | + | onFaviconURIChanged func(pageURI, faviconURI string) | |||
| 34 | + | onZoomChanged func(float64) | |||
| 35 | + | onPopup func(string) *WebView | |||
| 36 | + | onClose func() | |||
| 37 | + | onNavigationPolicy func(url string, isUserGesture bool) bool | |||
| 38 | + | onWindowTypeDetected func(WindowType, *WindowFeatures) | |||
| 19 | } | 39 | } | ||
| 20 | 40 | ||||
| 21 | - | // WebView represents a browser view powered by WebKit2GTK. | 41 | + | // NewWebView creates a new WebView with the given configuration |
| 22 | - | // Methods are currently stubs returning ErrNotImplemented to satisfy TDD ordering. | |||
| 23 | - | type WebView struct { | |||
| 24 | - | config *Config | |||
| 25 | - | visible bool | |||
| 26 | - | zoom float64 | |||
| 27 | - | url string | |||
| 28 | - | destroyed bool | |||
| 29 | - | window *Window | |||
| 30 | - | msgHandler func(payload string) | |||
| 31 | - | titleHandler func(title string) | |||
| 32 | - | uriHandler func(uri string) | |||
| 33 | - | faviconHandler func(data []byte) | |||
| 34 | - | faviconURIHandler func(pageURI, faviconURI string) | |||
| 35 | - | zoomHandler func(level float64) | |||
| 36 | - | popupHandler func(string) *WebView | |||
| 37 | - | closeHandler func() | |||
| 38 | - | navigationPolicyHandler func(url string, isUserGesture bool) bool | |||
| 39 | - | useDomZoom bool | |||
| 40 | - | domZoomSeed float64 | |||
| 41 | - | container uintptr | |||
| 42 | - | id uintptr // WebView unique identifier | |||
| 43 | - | ||||
| 44 | - | // Window type fields (no-op in stub) | |||
| 45 | - | windowType WindowType | |||
| 46 | - | windowFeatures *WindowFeatures | |||
| 47 | - | windowTypeCallback func(WindowType, *WindowFeatures) | |||
| 48 | - | } | |||
| 49 | - | ||||
| 50 | - | // NewWebView constructs a new WebView instance. | |||
| 51 | func NewWebView(cfg *Config) (*WebView, error) { | 42 | func NewWebView(cfg *Config) (*WebView, error) { | ||
| 52 | if cfg == nil { | 43 | if cfg == nil { | ||
| 53 | - | cfg = &Config{} | 44 | + | cfg = GetDefaultConfig() |
| 45 | + | } | |||
| 46 | + | ||||
| 47 | + | InitMainThread() | |||
| 48 | + | ||||
| 49 | + | // Create WebKitGTK WebView | |||
| 50 | + | wkView := webkit.NewWebView() | |||
| 51 | + | if wkView == nil { | |||
| 52 | + | return nil, ErrWebViewNotInitialized | |||
| 53 | + | } | |||
| 54 | + | ||||
| 55 | + | // Generate unique ID | |||
| 56 | + | id := atomic.AddUint64(&viewIDCounter, 1) | |||
| 57 | + | ||||
| 58 | + | wv := &WebView{ | |||
| 59 | + | view: wkView, | |||
| 60 | + | id: id, | |||
| 61 | + | config: cfg, | |||
| 54 | } | 62 | } | ||
| 55 | - | log.Printf("[webkit] NewWebView (non-CGO stub) — UI will not be displayed. Build with -tags=webkit_cgo for native window.") | 63 | + | |
| 56 | - | wv := &WebView{config: cfg, useDomZoom: cfg.UseDomZoom} | 64 | + | // Apply configuration |
| 57 | - | if cfg.ZoomDefault <= 0 { | 65 | + | if err := wv.applyConfig(); err != nil { |
| 58 | - | wv.zoom = 1.0 | 66 | + | return nil, err |
| 59 | - | } else { | |||
| 60 | - | wv.zoom = cfg.ZoomDefault | |||
| 61 | } | 67 | } | ||
| 62 | - | wv.domZoomSeed = wv.zoom | 68 | + | |
| 63 | - | wv.id = nextStubViewID() // Assign unique ID | 69 | + | // Setup event handlers |
| 64 | - | // Construction succeeds; create a logical window placeholder. | 70 | + | wv.setupEventHandlers() |
| 65 | - | wv.window = &Window{Title: "Dumber Browser"} | 71 | + | |
| 66 | - | wv.container = newWidgetHandle() | 72 | + | // Register in global registry |
| 73 | + | viewMu.Lock() | |||
| 74 | + | viewRegistry[id] = wv | |||
| 75 | + | viewMu.Unlock() | |||
| 76 | + | ||||
| 67 | return wv, nil | 77 | return wv, nil | ||
| 68 | } | 78 | } | ||
| 69 | 79 | ||||
| 70 | - | // NewWebViewWithRelated creates a new WebView related to an existing one (non-CGO stub) | 80 | + | // NewWebViewWithRelated creates a new WebView related to an existing one |
| 71 | - | func NewWebViewWithRelated(cfg *Config, relatedView *WebView) (*WebView, error) { | 81 | + | // (shares process context) |
| 72 | - | // In non-CGO build, just create a regular WebView | 82 | + | func NewWebViewWithRelated(cfg *Config, related *WebView) (*WebView, error) { |
| 83 | + | if related == nil { | |||
| 84 | + | return NewWebView(cfg) | |||
| 85 | + | } | |||
| 86 | + | ||||
| 87 | + | // TODO: Implement related view creation using webkit.NewWebViewWithRelatedView | |||
| 88 | + | // For now, create a regular view | |||
| 73 | return NewWebView(cfg) | 89 | return NewWebView(cfg) | ||
| 74 | } | 90 | } | ||
| 75 | 91 | ||||
| 76 | - | // LoadURL navigates the webview to the specified URL. | 92 | + | // applyConfig applies the configuration to the WebView settings |
| 77 | - | func (w *WebView) LoadURL(rawURL string) error { | 93 | + | func (w *WebView) applyConfig() error { |
| 78 | - | if w == nil || w.destroyed { | 94 | + | settings := w.view.Settings() |
| 79 | - | return ErrNotImplemented | 95 | + | if settings == nil { |
| 96 | + | return fmt.Errorf("webkit: failed to get settings") | |||
| 80 | } | 97 | } | ||
| 81 | - | if rawURL == "" { | 98 | + | |
| 82 | - | return fmt.Errorf("url cannot be empty") | 99 | + | // Apply settings from config |
| 100 | + | settings.SetEnableJavascript(w.config.EnableJavaScript) | |||
| 101 | + | settings.SetEnableWebgl(w.config.EnableWebGL) | |||
| 102 | + | settings.SetDefaultFontSize(uint(w.config.DefaultFontSize)) | |||
| 103 | + | settings.SetMinimumFontSize(uint(w.config.MinimumFontSize)) | |||
| 104 | + | ||||
| 105 | + | if w.config.UserAgent != "" { | |||
| 106 | + | settings.SetUserAgent(w.config.UserAgent) | |||
| 83 | } | 107 | } | ||
| 84 | - | // Minimal validation; actual navigation handled by CGO bridge later. | 108 | + | |
| 85 | - | w.url = rawURL | 109 | + | // Enable hardware acceleration if configured |
| 86 | - | log.Printf("[webkit] LoadURL (non-CGO stub): %s", rawURL) | 110 | + | settings.SetHardwareAccelerationPolicy(webkit.HardwareAccelerationPolicyAlways) |
| 111 | + | ||||
| 87 | return nil | 112 | return nil | ||
| 88 | } | 113 | } | ||
| 89 | 114 | ||||
| 90 | - | // Show makes the WebView visible. | 115 | + | // setupEventHandlers connects GTK signals to internal handlers |
| 91 | - | func (w *WebView) Show() error { | 116 | + | func (w *WebView) setupEventHandlers() { |
| 92 | - | if w == nil || w.destroyed { | 117 | + | // Title changed |
| 93 | - | return ErrNotImplemented | 118 | + | w.view.ConnectNotify("title", func() { |
| 94 | - | } | 119 | + | if w.onTitleChanged != nil { |
| 95 | - | w.visible = true | 120 | + | title := w.view.Title() |
| 96 | - | log.Printf("[webkit] Show (non-CGO stub): no native window will appear") | 121 | + | w.onTitleChanged(title) |
| 97 | - | return nil | 122 | + | } |
| 123 | + | }) | |||
| 124 | + | ||||
| 125 | + | // URI changed | |||
| 126 | + | w.view.ConnectNotify("uri", func() { | |||
| 127 | + | if w.onURIChanged != nil { | |||
| 128 | + | uri := w.view.URI() | |||
| 129 | + | w.onURIChanged(uri) | |||
| 130 | + | } | |||
| 131 | + | }) | |||
| 132 | + | ||||
| 133 | + | // Load changed | |||
| 134 | + | w.view.ConnectLoadChanged(func(event webkit.LoadEvent) { | |||
| 135 | + | // Handle load events if needed | |||
| 136 | + | }) | |||
| 137 | + | ||||
| 138 | + | // Close | |||
| 139 | + | w.view.ConnectClose(func() { | |||
| 140 | + | if w.onClose != nil { | |||
| 141 | + | w.onClose() | |||
| 142 | + | } | |||
| 143 | + | }) | |||
| 98 | } | 144 | } | ||
| 99 | 145 | ||||
| 100 | - | // Hide hides the WebView window. | 146 | + | // LoadURL loads the given URL in the WebView |
| 101 | - | func (w *WebView) Hide() error { | 147 | + | func (w *WebView) LoadURL(url string) error { |
| 102 | - | if w == nil || w.destroyed { | 148 | + | w.mu.RLock() |
| 103 | - | return ErrNotImplemented | 149 | + | defer w.mu.RUnlock() |
| 150 | + | ||||
| 151 | + | if w.destroyed { | |||
| 152 | + | return ErrWebViewDestroyed | |||
| 104 | } | 153 | } | ||
| 105 | - | w.visible = false | |||
| 106 | - | return nil | |||
| 107 | - | } | |||
| 108 | 154 | ||||
| 109 | - | // Destroy releases native resources. | 155 | + | if url == "" { |
| 110 | - | func (w *WebView) Destroy() error { | 156 | + | return ErrInvalidURL |
| 111 | - | if w == nil { | |||
| 112 | - | return ErrNotImplemented | |||
| 113 | } | 157 | } | ||
| 114 | - | w.destroyed = true | 158 | + | |
| 159 | + | w.view.LoadURI(url) | |||
| 115 | return nil | 160 | return nil | ||
| 116 | } | 161 | } | ||
| 117 | 162 | ||||
| 118 | - | // IsDestroyed returns whether this WebView has been destroyed | 163 | + | // GetCurrentURL returns the current URL |
| 119 | - | func (w *WebView) IsDestroyed() bool { | 164 | + | func (w *WebView) GetCurrentURL() string { |
| 120 | - | return w != nil && w.destroyed | 165 | + | w.mu.RLock() |
| 121 | - | } | 166 | + | defer w.mu.RUnlock() |
| 122 | 167 | ||||
| 123 | - | // Window returns the associated native window wrapper (non-nil). | 168 | + | if w.destroyed { |
| 124 | - | func (w *WebView) Window() *Window { return w.window } | 169 | + | return "" |
| 170 | + | } | |||
| 125 | 171 | ||||
| 126 | - | // GetCurrentURL returns the last requested URL (non-CGO build approximation). | 172 | + | return w.view.URI() |
| 127 | - | func (w *WebView) GetCurrentURL() string { return w.url } | 173 | + | } |
| 128 | 174 | ||||
| 129 | - | // GetTitle returns a stub page title. | 175 | + | // GetTitle returns the current page title |
| 130 | - | func (w *WebView) GetTitle() string { return "New Tab" } | 176 | + | func (w *WebView) GetTitle() string { |
| 177 | + | w.mu.RLock() | |||
| 178 | + | defer w.mu.RUnlock() | |||
| 131 | 179 | ||||
| 132 | - | // GoBack is not supported in the non-CGO stub. | 180 | + | if w.destroyed { |
| 133 | - | func (w *WebView) GoBack() error { return ErrNotImplemented } | 181 | + | return "" |
| 182 | + | } | |||
| 134 | 183 | ||||
| 135 | - | // GoForward is not supported in the non-CGO stub. | 184 | + | return w.view.Title() |
| 136 | - | func (w *WebView) GoForward() error { return ErrNotImplemented } | 185 | + | } |
| 137 | 186 | ||||
| 138 | - | // Reload is not supported in the non-CGO stub. | 187 | + | // GoBack navigates back in history |
| 139 | - | func (w *WebView) Reload() error { return ErrNotImplemented } | 188 | + | func (w *WebView) GoBack() error { |
| 189 | + | w.mu.RLock() | |||
| 190 | + | defer w.mu.RUnlock() | |||
| 140 | 191 | ||||
| 141 | - | // ReloadBypassCache is not supported in the non-CGO stub. | 192 | + | if w.destroyed { |
| 142 | - | func (w *WebView) ReloadBypassCache() error { return ErrNotImplemented } | 193 | + | return ErrWebViewDestroyed |
| 194 | + | } | |||
| 143 | 195 | ||||
| 144 | - | // ShowDevTools is a no-op in the non-CGO build. | 196 | + | w.view.GoBack() |
| 145 | - | func (w *WebView) ShowDevTools() error { return nil } | 197 | + | return nil |
| 198 | + | } | |||
| 146 | 199 | ||||
| 147 | - | // CloseDevTools is a no-op in the non-CGO build. | 200 | + | // GoForward navigates forward in history |
| 148 | - | func (w *WebView) CloseDevTools() error { return nil } | 201 | + | func (w *WebView) GoForward() error { |
| 202 | + | w.mu.RLock() | |||
| 203 | + | defer w.mu.RUnlock() | |||
| 149 | 204 | ||||
| 150 | - | // ShowPrintDialog is a no-op in the non-CGO build. | 205 | + | if w.destroyed { |
| 151 | - | func (w *WebView) ShowPrintDialog() error { return nil } | 206 | + | return ErrWebViewDestroyed |
| 207 | + | } | |||
| 152 | 208 | ||||
| 153 | - | // RegisterScriptMessageHandler registers a callback invoked when the content script posts a message. | 209 | + | w.view.GoForward() |
| 154 | - | func (w *WebView) RegisterScriptMessageHandler(cb func(payload string)) { w.msgHandler = cb } | 210 | + | return nil |
| 211 | + | } | |||
| 155 | 212 | ||||
| 156 | - | func (w *WebView) RegisterPopupHandler(cb func(string) *WebView) { w.popupHandler = cb } | 213 | + | // Reload reloads the current page |
| 214 | + | func (w *WebView) Reload() error { | |||
| 215 | + | w.mu.RLock() | |||
| 216 | + | defer w.mu.RUnlock() | |||
| 157 | 217 | ||||
| 158 | - | func (w *WebView) RegisterCloseHandler(cb func()) { w.closeHandler = cb } | 218 | + | if w.destroyed { |
| 219 | + | return ErrWebViewDestroyed | |||
| 220 | + | } | |||
| 159 | 221 | ||||
| 160 | - | func (w *WebView) RegisterNavigationPolicyHandler(cb func(url string, isUserGesture bool) bool) { | 222 | + | w.view.Reload() |
| 161 | - | w.navigationPolicyHandler = cb | 223 | + | return nil |
| 162 | } | 224 | } | ||
| 163 | 225 | ||||
| 164 | - | func (w *WebView) dispatchScriptMessage(payload string) { //nolint:unused // Called from CGO WebKit callbacks | 226 | + | // ReloadBypassCache reloads the current page, bypassing cache |
| 165 | - | if w != nil && w.msgHandler != nil { | 227 | + | func (w *WebView) ReloadBypassCache() error { |
| 166 | - | w.msgHandler(payload) | 228 | + | w.mu.RLock() |
| 167 | - | } | 229 | + | defer w.mu.RUnlock() |
| 168 | - | } | |||
| 169 | 230 | ||||
| 170 | - | func (w *WebView) dispatchPopupRequest(uri string) *WebView { //nolint:unused // Called from CGO WebKit callbacks | 231 | + | if w.destroyed { |
| 171 | - | if w != nil && w.popupHandler != nil { | 232 | + | return ErrWebViewDestroyed |
| 172 | - | return w.popupHandler(uri) | |||
| 173 | } | 233 | } | ||
| 234 | + | ||||
| 235 | + | w.view.ReloadBypassCache() | |||
| 174 | return nil | 236 | return nil | ||
| 175 | } | 237 | } | ||
| 176 | 238 | ||||
| 177 | - | // GetNativePointer returns nil for non-CGO build (stub implementation) | 239 | + | // Show makes the WebView visible |
| 178 | - | func (w *WebView) GetNativePointer() unsafe.Pointer { //nolint:unused // Needed for interface compatibility | 240 | + | func (w *WebView) Show() error { |
| 241 | + | w.mu.RLock() | |||
| 242 | + | defer w.mu.RUnlock() | |||
| 243 | + | ||||
| 244 | + | if w.destroyed { | |||
| 245 | + | return ErrWebViewDestroyed | |||
| 246 | + | } | |||
| 247 | + | ||||
| 248 | + | w.view.Show() | |||
| 179 | return nil | 249 | return nil | ||
| 180 | } | 250 | } | ||
| 181 | 251 | ||||
| 182 | - | // RegisterTitleChangedHandler registers a callback invoked when the page title changes. | 252 | + | // Hide makes the WebView invisible |
| 183 | - | func (w *WebView) RegisterTitleChangedHandler(cb func(title string)) { w.titleHandler = cb } | 253 | + | func (w *WebView) Hide() error { |
| 254 | + | w.mu.RLock() | |||
| 255 | + | defer w.mu.RUnlock() | |||
| 184 | 256 | ||||
| 185 | - | func (w *WebView) dispatchTitleChanged(title string) { //nolint:unused // Called from CGO WebKit callbacks | 257 | + | if w.destroyed { |
| 186 | - | if w != nil && w.titleHandler != nil { | 258 | + | return ErrWebViewDestroyed |
| 187 | - | w.titleHandler(title) | |||
| 188 | } | 259 | } | ||
| 260 | + | ||||
| 261 | + | w.view.Hide() | |||
| 262 | + | return nil | |||
| 189 | } | 263 | } | ||
| 190 | 264 | ||||
| 191 | - | // RegisterURIChangedHandler registers a callback invoked when the current page URI changes. | 265 | + | // Destroy destroys the WebView and releases resources |
| 192 | - | func (w *WebView) RegisterURIChangedHandler(cb func(uri string)) { w.uriHandler = cb } | 266 | + | func (w *WebView) Destroy() error { |
| 267 | + | w.mu.Lock() | |||
| 268 | + | defer w.mu.Unlock() | |||
| 193 | 269 | ||||
| 194 | - | func (w *WebView) dispatchURIChanged(uri string) { //nolint:unused // Called from CGO WebKit callbacks | 270 | + | if w.destroyed { |
| 195 | - | if w != nil && w.uriHandler != nil { | 271 | + | return nil |
| 196 | - | w.uriHandler(uri) | |||
| 197 | } | 272 | } | ||
| 198 | - | } | |||
| 199 | 273 | ||||
| 200 | - | // RegisterFaviconChangedHandler registers a callback invoked when the page favicon changes. | 274 | + | w.destroyed = true |
| 201 | - | func (w *WebView) RegisterFaviconChangedHandler(cb func(data []byte)) { w.faviconHandler = cb } | 275 | + | |
| 276 | + | // Unregister from global registry | |||
| 277 | + | viewMu.Lock() | |||
| 278 | + | delete(viewRegistry, w.id) | |||
| 279 | + | viewMu.Unlock() | |||
| 202 | 280 | ||||
| 203 | - | // RegisterFaviconURIChangedHandler registers a callback invoked when WebKit detects a favicon URI. | 281 | + | // The GTK widget will be cleaned up by Go GC |
| 204 | - | func (w *WebView) RegisterFaviconURIChangedHandler(cb func(pageURI, faviconURI string)) { | 282 | + | return nil |
| 205 | - | w.faviconURIHandler = cb | |||
| 206 | } | 283 | } | ||
| 207 | 284 | ||||
| 208 | - | func (w *WebView) dispatchFaviconChanged(data []byte) { //nolint:unused // Called from CGO WebKit callbacks | 285 | + | // IsDestroyed returns true if the WebView has been destroyed |
| 209 | - | if w != nil && w.faviconHandler != nil { | 286 | + | func (w *WebView) IsDestroyed() bool { |
| 210 | - | w.faviconHandler(data) | 287 | + | w.mu.RLock() |
| 211 | - | } | 288 | + | defer w.mu.RUnlock() |
| 289 | + | return w.destroyed | |||
| 212 | } | 290 | } | ||
| 213 | 291 | ||||
| 214 | - | // RegisterZoomChangedHandler registers a callback invoked when zoom level changes. | 292 | + | // ID returns the unique identifier for this WebView |
| 215 | - | func (w *WebView) RegisterZoomChangedHandler(cb func(level float64)) { w.zoomHandler = cb } | 293 | + | func (w *WebView) ID() uint64 { |
| 294 | + | return w.id | |||
| 295 | + | } | |||
| 216 | 296 | ||||
| 217 | - | func (w *WebView) dispatchZoomChanged(level float64) { | 297 | + | // AsWidget returns the WebView as a gtk.Widgetter |
| 218 | - | if w != nil && w.zoomHandler != nil { | 298 | + | func (w *WebView) AsWidget() gtk.Widgetter { |
| 219 | - | w.zoomHandler(level) | 299 | + | if w == nil || w.view == nil { |
| 300 | + | return nil | |||
| 220 | } | 301 | } | ||
| 302 | + | return w.view | |||
| 221 | } | 303 | } | ||
| 222 | 304 | ||||
| 223 | - | // Widget returns an empty handle in stub builds. | 305 | + | // Event handler registration methods |
| 224 | - | func (w *WebView) Widget() uintptr { return 0 } | |||
| 225 | - | ||||
| 226 | - | // RootWidget returns the container widget handle in CGO builds. Stub returns 0. | |||
| 227 | - | func (w *WebView) RootWidget() uintptr { return w.container } | |||
| 228 | 306 | ||||
| 229 | - | // DestroyWindow is a no-op in stub builds. | 307 | + | // RegisterScriptMessageHandler registers a handler for script messages |
| 230 | - | func (w *WebView) DestroyWindow() {} | 308 | + | func (w *WebView) RegisterScriptMessageHandler(handler func(string)) { |
| 231 | - | 309 | + | w.mu.Lock() | |
| 232 | - | // RunOnMainThread executes fn immediately in non-CGO builds. | 310 | + | defer w.mu.Unlock() |
| 233 | - | func (w *WebView) RunOnMainThread(fn func()) { | 311 | + | w.onScriptMessage = handler |
| 234 | - | if fn != nil { | |||
| 235 | - | fn() | |||
| 236 | - | } | |||
| 237 | } | 312 | } | ||
| 238 | 313 | ||||
| 239 | - | // PrepareForReparenting is a no-op in stub builds. | 314 | + | // RegisterTitleChangedHandler registers a handler for title changes |
| 240 | - | func (w *WebView) PrepareForReparenting() {} | 315 | + | func (w *WebView) RegisterTitleChangedHandler(handler func(string)) { |
| 241 | - | 316 | + | w.mu.Lock() | |
| 242 | - | // RefreshAfterReparenting is a no-op in stub builds. | 317 | + | defer w.mu.Unlock() |
| 243 | - | func (w *WebView) RefreshAfterReparenting() {} | 318 | + | w.onTitleChanged = handler |
| 319 | + | } | |||
| 244 | 320 | ||||
| 245 | - | // UsesDomZoom reports whether DOM-based zoom is enabled in this WebView. | 321 | + | // RegisterURIChangedHandler registers a handler for URI changes |
| 246 | - | func (w *WebView) UsesDomZoom() bool { | 322 | + | func (w *WebView) RegisterURIChangedHandler(handler func(string)) { |
| 247 | - | return w != nil && w.useDomZoom | 323 | + | w.mu.Lock() |
| 324 | + | defer w.mu.Unlock() | |||
| 325 | + | w.onURIChanged = handler | |||
| 248 | } | 326 | } | ||
| 249 | 327 | ||||
| 250 | - | // SeedDomZoom stores the desired DOM zoom level for the next navigation (stub implementation). | 328 | + | // RegisterFaviconChangedHandler registers a handler for favicon changes |
| 251 | - | func (w *WebView) SeedDomZoom(level float64) { | 329 | + | func (w *WebView) RegisterFaviconChangedHandler(handler func([]byte)) { |
| 252 | - | if w == nil || !w.useDomZoom { | 330 | + | w.mu.Lock() |
| 253 | - | return | 331 | + | defer w.mu.Unlock() |
| 254 | - | } | 332 | + | w.onFaviconChanged = handler |
| 255 | - | if level < 0.25 { | |||
| 256 | - | level = 0.25 | |||
| 257 | - | } else if level > 5.0 { | |||
| 258 | - | level = 5.0 | |||
| 259 | - | } | |||
| 260 | - | w.domZoomSeed = level | |||
| 261 | } | 333 | } | ||
| 262 | 334 | ||||
| 263 | - | // CreateRelatedView returns a new WebView (stub creates independent) | 335 | + | // RegisterFaviconURIChangedHandler registers a handler for favicon URI changes |
| 264 | - | func (w *WebView) CreateRelatedView() *WebView { | 336 | + | func (w *WebView) RegisterFaviconURIChangedHandler(handler func(pageURI, faviconURI string)) { |
| 265 | - | nw, _ := NewWebView(w.config) | 337 | + | w.mu.Lock() |
| 266 | - | return nw | 338 | + | defer w.mu.Unlock() |
| 339 | + | w.onFaviconURIChanged = handler | |||
| 267 | } | 340 | } | ||
| 268 | 341 | ||||
| 269 | - | // OnWindowTypeDetected registers a callback (stored but never invoked in stub) | 342 | + | // RegisterZoomChangedHandler registers a handler for zoom changes |
| 270 | - | func (w *WebView) OnWindowTypeDetected(callback func(WindowType, *WindowFeatures)) { | 343 | + | func (w *WebView) RegisterZoomChangedHandler(handler func(float64)) { |
| 271 | - | if w != nil { | 344 | + | w.mu.Lock() |
| 272 | - | w.windowTypeCallback = callback | 345 | + | defer w.mu.Unlock() |
| 273 | - | } | 346 | + | w.onZoomChanged = handler |
| 274 | } | 347 | } | ||
| 275 | 348 | ||||
| 276 | - | // InitializeContentBlocking initializes WebKit content blocking with filter manager (stub) | 349 | + | // RegisterPopupHandler registers a handler for popup requests |
| 277 | - | func (w *WebView) InitializeContentBlocking(filterManager interface{}) error { | 350 | + | func (w *WebView) RegisterPopupHandler(handler func(string) *WebView) { |
| 278 | - | return ErrNotImplemented | 351 | + | w.mu.Lock() |
| 352 | + | defer w.mu.Unlock() | |||
| 353 | + | w.onPopup = handler | |||
| 279 | } | 354 | } | ||
| 280 | 355 | ||||
| 281 | - | // OnNavigate sets up domain-specific cosmetic filtering on navigation (stub) | 356 | + | // RegisterCloseHandler registers a handler for close requests |
| 282 | - | func (w *WebView) OnNavigate(url string, filterManager interface{}, whitelist []string) { | 357 | + | func (w *WebView) RegisterCloseHandler(handler func()) { |
| 283 | - | // No-op in stub | 358 | + | w.mu.Lock() |
| 359 | + | defer w.mu.Unlock() | |||
| 360 | + | w.onClose = handler | |||
| 284 | } | 361 | } | ||
| 285 | 362 | ||||
| 286 | - | // UpdateContentFilters updates the content filters dynamically (stub) | 363 | + | // RegisterNavigationPolicyHandler registers a handler for navigation policy decisions |
| 287 | - | func (w *WebView) UpdateContentFilters(filterManager interface{}) error { | 364 | + | func (w *WebView) RegisterNavigationPolicyHandler(handler func(url string, isUserGesture bool) bool) { |
| 288 | - | return ErrNotImplemented | 365 | + | w.mu.Lock() |
| 366 | + | defer w.mu.Unlock() | |||
| 367 | + | w.onNavigationPolicy = handler | |||
| 289 | } | 368 | } | ||
| 290 | 369 | ||||
| 291 | - | // SetWindowFeatures sets the window features for this WebView (stub) | 370 | + | // OnWindowTypeDetected registers a handler for window type detection |
| 292 | - | func (w *WebView) SetWindowFeatures(features *WindowFeatures) { | 371 | + | func (w *WebView) OnWindowTypeDetected(handler func(WindowType, *WindowFeatures)) { |
| 293 | - | w.windowFeatures = features | 372 | + | w.mu.Lock() |
| 373 | + | defer w.mu.Unlock() | |||
| 374 | + | w.onWindowTypeDetected = handler | |||
| 294 | } | 375 | } | ||
| 295 | 376 | ||||
| 296 | - | // SetActive sets whether this WebView is currently active/focused (stub) | 377 | + | // RunOnMainThread executes a function on the GTK main thread |
| 297 | - | func (w *WebView) SetActive(active bool) { | 378 | + | func (w *WebView) RunOnMainThread(fn func()) { |
| 298 | - | // No-op in stub | 379 | + | RunOnMainThread(fn) |
| 299 | } | 380 | } | ||
| 300 | 381 | ||||
| 301 | - | // IsActive returns whether this WebView is currently active/focused (stub) | 382 | + | // GetWebView returns the underlying webkit.WebView for advanced operations |
| 302 | - | func (w *WebView) IsActive() bool { | 383 | + | func (w *WebView) GetWebView() *webkit.WebView { |
| 303 | - | return false | 384 | + | return w.view |
| 304 | } | 385 | } | ||
| 305 | 386 | ||||
| 306 | - | // ID returns the unique identifier for this WebView as a string (stub) | 387 | + | // Widget returns the WebView widget (for compatibility with old code expecting uintptr) |
| 307 | - | func (w *WebView) ID() string { | 388 | + | // Deprecated: Use AsWidget() instead |
| 308 | - | if w == nil { | 389 | + | func (w *WebView) Widget() gtk.Widgetter { |
| 309 | - | return "" | 390 | + | return w.AsWidget() |
| 310 | - | } | |||
| 311 | - | return strconv.FormatUint(uint64(w.id), 10) | |||
| 312 | } | 391 | } | ||
| 313 | 392 | ||||
| 314 | - | // PrefersDarkTheme returns true if GTK is configured to prefer dark theme (stub) | 393 | + | // RootWidget returns the root container widget for this WebView |
| 315 | - | func PrefersDarkTheme() bool { | 394 | + | // In the new architecture, this is just the WebView itself |
| 316 | - | return false // Fallback to light theme when not using CGO | 395 | + | func (w *WebView) RootWidget() gtk.Widgetter { |
| 396 | + | return w.AsWidget() | |||
| 317 | } | 397 | } | ||
D pkg/webkit/webview_callbacks.h +0 -110
| @@ -1,110 +0,0 @@ | |||||
| 1 | - | #ifndef WEBVIEW_CALLBACKS_H | |||
| 2 | - | #define WEBVIEW_CALLBACKS_H | |||
| 3 | - | ||||
| 4 | - | #include <gtk/gtk.h> | |||
| 5 | - | #include <webkit/webkit.h> | |||
| 6 | - | #include <glib-object.h> | |||
| 7 | - | ||||
| 8 | - | // Forward declarations for Go callbacks | |||
| 9 | - | extern void goOnTitleChanged(unsigned long id, char* title); | |||
| 10 | - | extern void goOnURIChanged(unsigned long id, char* uri); | |||
| 11 | - | extern void goOnThemeChanged(unsigned long id, int prefer_dark); | |||
| 12 | - | extern void goOnFaviconURIChanged(unsigned long id, char* page_uri, char* favicon_uri); | |||
| 13 | - | extern void* goResolveURIScheme(char* uri, size_t* out_len, char** out_mime); | |||
| 14 | - | extern void goQuitMainLoop(); | |||
| 15 | - | ||||
| 16 | - | // Static inline functions to avoid multiple definition errors | |||
| 17 | - | static inline void on_title_notify(GObject* obj, GParamSpec* pspec, gpointer user_data) { | |||
| 18 | - | (void)pspec; | |||
| 19 | - | WebKitWebView* view = WEBKIT_WEB_VIEW(obj); | |||
| 20 | - | const gchar* title = webkit_web_view_get_title(view); | |||
| 21 | - | GtkWindow* win = GTK_WINDOW(user_data); | |||
| 22 | - | if (title && win) { | |||
| 23 | - | gtk_window_set_title(win, title); | |||
| 24 | - | } | |||
| 25 | - | } | |||
| 26 | - | ||||
| 27 | - | static inline void on_title_notify_id(GObject* obj, GParamSpec* pspec, gpointer user_data) { | |||
| 28 | - | (void)pspec; (void)obj; | |||
| 29 | - | const gchar* title = webkit_web_view_get_title(WEBKIT_WEB_VIEW(obj)); | |||
| 30 | - | if (title) { goOnTitleChanged((unsigned long)user_data, (char*)title); } | |||
| 31 | - | } | |||
| 32 | - | ||||
| 33 | - | static inline void on_uri_notify(GObject* obj, GParamSpec* pspec, gpointer user_data) { | |||
| 34 | - | (void)pspec; (void)obj; | |||
| 35 | - | const gchar* uri = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(obj)); | |||
| 36 | - | if (uri) { goOnURIChanged((unsigned long)user_data, (char*)uri); } | |||
| 37 | - | } | |||
| 38 | - | ||||
| 39 | - | static inline void on_theme_changed(GObject* obj, GParamSpec* pspec, gpointer user_data) { | |||
| 40 | - | (void)pspec; | |||
| 41 | - | GtkSettings* settings = GTK_SETTINGS(obj); | |||
| 42 | - | if (!settings) return; | |||
| 43 | - | gboolean prefer = FALSE; | |||
| 44 | - | g_object_get(settings, "gtk-application-prefer-dark-theme", &prefer, NULL); | |||
| 45 | - | goOnThemeChanged((unsigned long)user_data, prefer ? 1 : 0); | |||
| 46 | - | } | |||
| 47 | - | ||||
| 48 | - | static inline void on_uri_scheme(WebKitURISchemeRequest* request, gpointer user_data) { | |||
| 49 | - | (void)user_data; | |||
| 50 | - | const gchar* uri = webkit_uri_scheme_request_get_uri(request); | |||
| 51 | - | size_t n = 0; | |||
| 52 | - | char* mime = NULL; | |||
| 53 | - | void* buf = goResolveURIScheme((char*)uri, &n, &mime); | |||
| 54 | - | if (buf && n > 0 && mime) { | |||
| 55 | - | GInputStream* stream = g_memory_input_stream_new_from_data(buf, (gssize)n, g_free); | |||
| 56 | - | webkit_uri_scheme_request_finish(request, stream, (gint64)n, mime); | |||
| 57 | - | g_object_unref(stream); | |||
| 58 | - | g_free(mime); | |||
| 59 | - | } else { | |||
| 60 | - | GError* err = g_error_new_literal(g_quark_from_string("dumber"), 404, "Not found"); | |||
| 61 | - | webkit_uri_scheme_request_finish_error(request, err); | |||
| 62 | - | g_error_free(err); | |||
| 63 | - | } | |||
| 64 | - | } | |||
| 65 | - | ||||
| 66 | - | static inline char* mask_uri_for_log(const char* uri) { | |||
| 67 | - | if (!uri) return g_strdup("NULL"); | |||
| 68 | - | const char* p = strstr(uri, "://"); | |||
| 69 | - | const char* start = p ? p + 3 : uri; | |||
| 70 | - | const char* slash = strchr(start, '/'); | |||
| 71 | - | size_t host_len = slash ? (size_t)(slash - start) : strlen(start); | |||
| 72 | - | const size_t max_len = 64; | |||
| 73 | - | if (host_len <= max_len) { | |||
| 74 | - | return g_strndup(start, host_len); | |||
| 75 | - | } else { | |||
| 76 | - | char* prefix = g_strndup(start, max_len); | |||
| 77 | - | char* res = g_strdup_printf("%s...", prefix); | |||
| 78 | - | g_free(prefix); | |||
| 79 | - | return res; | |||
| 80 | - | } | |||
| 81 | - | } | |||
| 82 | - | ||||
| 83 | - | static inline void on_favicon_changed(WebKitFaviconDatabase* database, gchar* page_uri, gchar* favicon_uri, gpointer user_data) { | |||
| 84 | - | (void)database; | |||
| 85 | - | ||||
| 86 | - | if (!favicon_uri || !page_uri) { | |||
| 87 | - | printf("[favicon-c] Invalid favicon or page URI for WebView ID %lu\n", (unsigned long)user_data); | |||
| 88 | - | return; | |||
| 89 | - | } | |||
| 90 | - | ||||
| 91 | - | // Log only a masked/shortened form of the URIs (no full URIs) | |||
| 92 | - | char* masked_page = mask_uri_for_log(page_uri); | |||
| 93 | - | char* masked_favicon = mask_uri_for_log(favicon_uri); | |||
| 94 | - | printf("[favicon-c] Favicon changed - page: %s, favicon: %s, WebView ID: %lu\n", | |||
| 95 | - | masked_page, masked_favicon, (unsigned long)user_data); | |||
| 96 | - | g_free(masked_page); | |||
| 97 | - | g_free(masked_favicon); | |||
| 98 | - | ||||
| 99 | - | // Pass the full page URI and favicon URI to Go | |||
| 100 | - | goOnFaviconURIChanged((unsigned long)user_data, page_uri, favicon_uri); | |||
| 101 | - | } | |||
| 102 | - | ||||
| 103 | - | // GTK4 close-request signal handler | |||
| 104 | - | static inline gboolean on_close_request(GtkWindow* window, gpointer user_data) { | |||
| 105 | - | (void)window; (void)user_data; | |||
| 106 | - | goQuitMainLoop(); | |||
| 107 | - | return FALSE; // Allow the window to close | |||
| 108 | - | } | |||
| 109 | - | ||||
| 110 | - | #endif // WEBVIEW_CALLBACKS_H⏎̸ | |||
D pkg/webkit/webview_cgo.go +0 -2846 large diff (2846 lines changed): collapsed
A pkg/webkit/widgets.go +287 -0
| @@ -0,0 +1,287 @@ | |||||
| 1 | + | package webkit | |||
| 2 | + | ||||
| 3 | + | import ( | |||
| 4 | + | "github.com/diamondburned/gotk4/pkg/gtk/v4" | |||
| 5 | + | "github.com/diamondburned/gotk4/pkg/pango" | |||
| 6 | + | ) | |||
| 7 | + | ||||
| 8 | + | // Paned wraps gtk.Paned for split pane layouts | |||
| 9 | + | type Paned struct { | |||
| 10 | + | paned *gtk.Paned | |||
| 11 | + | } | |||
| 12 | + | ||||
| 13 | + | // NewPaned creates a new Paned widget with the given orientation | |||
| 14 | + | func NewPaned(orientation gtk.Orientation) *Paned { | |||
| 15 | + | return &Paned{ | |||
| 16 | + | paned: gtk.NewPaned(orientation), | |||
| 17 | + | } | |||
| 18 | + | } | |||
| 19 | + | ||||
| 20 | + | // SetStartChild sets the first child of the paned | |||
| 21 | + | func (p *Paned) SetStartChild(child gtk.Widgetter) { | |||
| 22 | + | if p == nil || p.paned == nil { | |||
| 23 | + | return | |||
| 24 | + | } | |||
| 25 | + | p.paned.SetStartChild(child) | |||
| 26 | + | } | |||
| 27 | + | ||||
| 28 | + | // SetEndChild sets the second child of the paned | |||
| 29 | + | func (p *Paned) SetEndChild(child gtk.Widgetter) { | |||
| 30 | + | if p == nil || p.paned == nil { | |||
| 31 | + | return | |||
| 32 | + | } | |||
| 33 | + | p.paned.SetEndChild(child) | |||
| 34 | + | } | |||
| 35 | + | ||||
| 36 | + | // SetPosition sets the divider position | |||
| 37 | + | func (p *Paned) SetPosition(pos int) { | |||
| 38 | + | if p == nil || p.paned == nil { | |||
| 39 | + | return | |||
| 40 | + | } | |||
| 41 | + | p.paned.SetPosition(pos) | |||
| 42 | + | } | |||
| 43 | + | ||||
| 44 | + | // GetPosition returns the divider position | |||
| 45 | + | func (p *Paned) GetPosition() int { | |||
| 46 | + | if p == nil || p.paned == nil { | |||
| 47 | + | return 0 | |||
| 48 | + | } | |||
| 49 | + | return p.paned.Position() | |||
| 50 | + | } | |||
| 51 | + | ||||
| 52 | + | // SetResizeStartChild sets whether the start child should resize | |||
| 53 | + | func (p *Paned) SetResizeStartChild(resize bool) { | |||
| 54 | + | if p == nil || p.paned == nil { | |||
| 55 | + | return | |||
| 56 | + | } | |||
| 57 | + | p.paned.SetResizeStartChild(resize) | |||
| 58 | + | } | |||
| 59 | + | ||||
| 60 | + | // SetResizeEndChild sets whether the end child should resize | |||
| 61 | + | func (p *Paned) SetResizeEndChild(resize bool) { | |||
| 62 | + | if p == nil || p.paned == nil { | |||
| 63 | + | return | |||
| 64 | + | } | |||
| 65 | + | p.paned.SetResizeEndChild(resize) | |||
| 66 | + | } | |||
| 67 | + | ||||
| 68 | + | // AsWidget returns the paned as a Widgetter | |||
| 69 | + | func (p *Paned) AsWidget() gtk.Widgetter { | |||
| 70 | + | if p == nil || p.paned == nil { | |||
| 71 | + | return nil | |||
| 72 | + | } | |||
| 73 | + | return p.paned | |||
| 74 | + | } | |||
| 75 | + | ||||
| 76 | + | // StartChild returns the start child | |||
| 77 | + | func (p *Paned) StartChild() gtk.Widgetter { | |||
| 78 | + | if p == nil || p.paned == nil { | |||
| 79 | + | return nil | |||
| 80 | + | } | |||
| 81 | + | return p.paned.StartChild() | |||
| 82 | + | } | |||
| 83 | + | ||||
| 84 | + | // EndChild returns the end child | |||
| 85 | + | func (p *Paned) EndChild() gtk.Widgetter { | |||
| 86 | + | if p == nil || p.paned == nil { | |||
| 87 | + | return nil | |||
| 88 | + | } | |||
| 89 | + | return p.paned.EndChild() | |||
| 90 | + | } | |||
| 91 | + | ||||
| 92 | + | // Box wraps gtk.Box for layout management | |||
| 93 | + | type Box struct { | |||
| 94 | + | box *gtk.Box | |||
| 95 | + | } | |||
| 96 | + | ||||
| 97 | + | // NewBox creates a new Box with the given orientation and spacing | |||
| 98 | + | func NewBox(orientation gtk.Orientation, spacing int) *Box { | |||
| 99 | + | return &Box{ | |||
| 100 | + | box: gtk.NewBox(orientation, spacing), | |||
| 101 | + | } | |||
| 102 | + | } | |||
| 103 | + | ||||
| 104 | + | // Append adds a child to the end of the box | |||
| 105 | + | func (b *Box) Append(child gtk.Widgetter) { | |||
| 106 | + | if b == nil || b.box == nil { | |||
| 107 | + | return | |||
| 108 | + | } | |||
| 109 | + | b.box.Append(child) | |||
| 110 | + | } | |||
| 111 | + | ||||
| 112 | + | // Prepend adds a child to the beginning of the box | |||
| 113 | + | func (b *Box) Prepend(child gtk.Widgetter) { | |||
| 114 | + | if b == nil || b.box == nil { | |||
| 115 | + | return | |||
| 116 | + | } | |||
| 117 | + | b.box.Prepend(child) | |||
| 118 | + | } | |||
| 119 | + | ||||
| 120 | + | // Remove removes a child from the box | |||
| 121 | + | func (b *Box) Remove(child gtk.Widgetter) { | |||
| 122 | + | if b == nil || b.box == nil { | |||
| 123 | + | return | |||
| 124 | + | } | |||
| 125 | + | b.box.Remove(child) | |||
| 126 | + | } | |||
| 127 | + | ||||
| 128 | + | // InsertChildAfter inserts a child after the specified sibling | |||
| 129 | + | func (b *Box) InsertChildAfter(child, sibling gtk.Widgetter) { | |||
| 130 | + | if b == nil || b.box == nil { | |||
| 131 | + | return | |||
| 132 | + | } | |||
| 133 | + | b.box.InsertChildAfter(child, sibling) | |||
| 134 | + | } | |||
| 135 | + | ||||
| 136 | + | // AsWidget returns the box as a Widgetter | |||
| 137 | + | func (b *Box) AsWidget() gtk.Widgetter { | |||
| 138 | + | if b == nil || b.box == nil { | |||
| 139 | + | return nil | |||
| 140 | + | } | |||
| 141 | + | return b.box | |||
| 142 | + | } | |||
| 143 | + | ||||
| 144 | + | // Label wraps gtk.Label for text display | |||
| 145 | + | type Label struct { | |||
| 146 | + | label *gtk.Label | |||
| 147 | + | } | |||
| 148 | + | ||||
| 149 | + | // NewLabel creates a new Label with the given text | |||
| 150 | + | func NewLabel(text string) *Label { | |||
| 151 | + | return &Label{ | |||
| 152 | + | label: gtk.NewLabel(text), | |||
| 153 | + | } | |||
| 154 | + | } | |||
| 155 | + | ||||
| 156 | + | // SetText updates the label text | |||
| 157 | + | func (l *Label) SetText(text string) { | |||
| 158 | + | if l == nil || l.label == nil { | |||
| 159 | + | return | |||
| 160 | + | } | |||
| 161 | + | l.label.SetText(text) | |||
| 162 | + | } | |||
| 163 | + | ||||
| 164 | + | // GetText returns the current label text | |||
| 165 | + | func (l *Label) GetText() string { | |||
| 166 | + | if l == nil || l.label == nil { | |||
| 167 | + | return "" | |||
| 168 | + | } | |||
| 169 | + | return l.label.Text() | |||
| 170 | + | } | |||
| 171 | + | ||||
| 172 | + | // SetEllipsize sets the ellipsization mode | |||
| 173 | + | func (l *Label) SetEllipsize(mode pango.EllipsizeMode) { | |||
| 174 | + | if l == nil || l.label == nil { | |||
| 175 | + | return | |||
| 176 | + | } | |||
| 177 | + | l.label.SetEllipsize(mode) | |||
| 178 | + | } | |||
| 179 | + | ||||
| 180 | + | // SetMaxWidthChars sets the maximum width in characters | |||
| 181 | + | func (l *Label) SetMaxWidthChars(nChars int) { | |||
| 182 | + | if l == nil || l.label == nil { | |||
| 183 | + | return | |||
| 184 | + | } | |||
| 185 | + | l.label.SetMaxWidthChars(nChars) | |||
| 186 | + | } | |||
| 187 | + | ||||
| 188 | + | // AsWidget returns the label as a Widgetter | |||
| 189 | + | func (l *Label) AsWidget() gtk.Widgetter { | |||
| 190 | + | if l == nil || l.label == nil { | |||
| 191 | + | return nil | |||
| 192 | + | } | |||
| 193 | + | return l.label | |||
| 194 | + | } | |||
| 195 | + | ||||
| 196 | + | // Image wraps gtk.Image for displaying images (e.g., favicons) | |||
| 197 | + | type Image struct { | |||
| 198 | + | image *gtk.Image | |||
| 199 | + | } | |||
| 200 | + | ||||
| 201 | + | // NewImage creates a new empty Image | |||
| 202 | + | func NewImage() *Image { | |||
| 203 | + | return &Image{ | |||
| 204 | + | image: gtk.NewImage(), | |||
| 205 | + | } | |||
| 206 | + | } | |||
| 207 | + | ||||
| 208 | + | // NewImageFromFile creates a new Image from a file | |||
| 209 | + | func NewImageFromFile(filename string) *Image { | |||
| 210 | + | return &Image{ | |||
| 211 | + | image: gtk.NewImageFromFile(filename), | |||
| 212 | + | } | |||
| 213 | + | } | |||
| 214 | + | ||||
| 215 | + | // SetFromFile loads an image from a file | |||
| 216 | + | func (i *Image) SetFromFile(filename string) { | |||
| 217 | + | if i == nil || i.image == nil { | |||
| 218 | + | return | |||
| 219 | + | } | |||
| 220 | + | i.image.SetFromFile(filename) | |||
| 221 | + | } | |||
| 222 | + | ||||
| 223 | + | // SetPixelSize sets the pixel size for the image | |||
| 224 | + | func (i *Image) SetPixelSize(size int) { | |||
| 225 | + | if i == nil || i.image == nil { | |||
| 226 | + | return | |||
| 227 | + | } | |||
| 228 | + | i.image.SetPixelSize(size) | |||
| 229 | + | } | |||
| 230 | + | ||||
| 231 | + | // AsWidget returns the image as a Widgetter | |||
| 232 | + | func (i *Image) AsWidget() gtk.Widgetter { | |||
| 233 | + | if i == nil || i.image == nil { | |||
| 234 | + | return nil | |||
| 235 | + | } | |||
| 236 | + | return i.image | |||
| 237 | + | } | |||
| 238 | + | ||||
| 239 | + | // Widget helper functions for common operations | |||
| 240 | + | ||||
| 241 | + | // WidgetShow makes a widget visible | |||
| 242 | + | func WidgetShow(w gtk.Widgetter) { | |||
| 243 | + | if w == nil { | |||
| 244 | + | return | |||
| 245 | + | } | |||
| 246 | + | w.Show() | |||
| 247 | + | } | |||
| 248 | + | ||||
| 249 | + | // WidgetHide makes a widget invisible | |||
| 250 | + | func WidgetHide(w gtk.Widgetter) { | |||
| 251 | + | if w == nil { | |||
| 252 | + | return | |||
| 253 | + | } | |||
| 254 | + | w.Hide() | |||
| 255 | + | } | |||
| 256 | + | ||||
| 257 | + | // WidgetSetVisible sets the visibility of a widget | |||
| 258 | + | func WidgetSetVisible(w gtk.Widgetter, visible bool) { | |||
| 259 | + | if w == nil { | |||
| 260 | + | return | |||
| 261 | + | } | |||
| 262 | + | w.SetVisible(visible) | |||
| 263 | + | } | |||
| 264 | + | ||||
| 265 | + | // WidgetSetSizeRequest sets the minimum size request | |||
| 266 | + | func WidgetSetSizeRequest(w gtk.Widgetter, width, height int) { | |||
| 267 | + | if w == nil { | |||
| 268 | + | return | |||
| 269 | + | } | |||
| 270 | + | w.SetSizeRequest(width, height) | |||
| 271 | + | } | |||
| 272 | + | ||||
| 273 | + | // WidgetQueueResize queues a resize operation | |||
| 274 | + | func WidgetQueueResize(w gtk.Widgetter) { | |||
| 275 | + | if w == nil { | |||
| 276 | + | return | |||
| 277 | + | } | |||
| 278 | + | w.QueueResize() | |||
| 279 | + | } | |||
| 280 | + | ||||
| 281 | + | // WidgetGrabFocus gives focus to a widget | |||
| 282 | + | func WidgetGrabFocus(w gtk.Widgetter) { | |||
| 283 | + | if w == nil { | |||
| 284 | + | return | |||
| 285 | + | } | |||
| 286 | + | w.GrabFocus() | |||
| 287 | + | } | |||
M pkg/webkit/window.go +53 -39
| @@ -1,59 +1,73 @@ | |||||
| 1 | - | //go:build !webkit_cgo | |||
| 2 | - | ||||
| 3 | package webkit | 1 | package webkit | ||
| 4 | 2 | ||||
| 5 | - | import "sync" | 3 | + | import ( |
| 4 | + | "github.com/diamondburned/gotk4/pkg/gtk/v4" | |||
| 5 | + | ) | |||
| 6 | 6 | ||||
| 7 | - | // Window represents a top-level application window hosting a WebView. | 7 | + | // Window wraps a GTK Window for the browser |
| 8 | - | // Stub for future GTK application window management. | |||
| 9 | type Window struct { | 8 | type Window struct { | ||
| 10 | - | Title string | 9 | + | win *gtk.Window |
| 11 | - | child uintptr | |||
| 12 | - | mu sync.Mutex | |||
| 13 | } | 10 | } | ||
| 14 | 11 | ||||
| 15 | - | // NewWindow constructs a Window. In real implementation, this would create a GTK window. | 12 | + | // NewWindow creates a new GTK window with the given title |
| 16 | func NewWindow(title string) (*Window, error) { | 13 | func NewWindow(title string) (*Window, error) { | ||
| 17 | - | _ = title | 14 | + | InitMainThread() |
| 18 | - | return &Window{Title: title}, ErrNotImplemented | 15 | + | |
| 16 | + | win := gtk.NewWindow() | |||
| 17 | + | if win == nil { | |||
| 18 | + | return nil, ErrWebViewNotInitialized | |||
| 19 | + | } | |||
| 20 | + | ||||
| 21 | + | win.SetTitle(title) | |||
| 22 | + | win.SetDefaultSize(1024, 768) | |||
| 23 | + | ||||
| 24 | + | return &Window{win: win}, nil | |||
| 19 | } | 25 | } | ||
| 20 | 26 | ||||
| 21 | - | // SetTitle updates the window title (no-op in non-CGO build). | 27 | + | // SetTitle updates the window title |
| 22 | func (w *Window) SetTitle(title string) { | 28 | func (w *Window) SetTitle(title string) { | ||
| 23 | - | w.Title = title | 29 | + | if w == nil || w.win == nil { |
| 30 | + | return | |||
| 31 | + | } | |||
| 32 | + | w.win.SetTitle(title) | |||
| 24 | } | 33 | } | ||
| 25 | 34 | ||||
| 26 | - | // SetChild is a stubbed window child setter for non-CGO builds. | 35 | + | // SetChild sets the child widget of the window |
| 27 | - | // Simulates GTK4 behavior where setting child to 0 unparents the current child. | 36 | + | func (w *Window) SetChild(child gtk.Widgetter) { |
| 28 | - | func (w *Window) SetChild(child uintptr) { | 37 | + | if w == nil || w.win == nil { |
| 29 | - | if w == nil { | |||
| 30 | return | 38 | return | ||
| 31 | } | 39 | } | ||
| 40 | + | w.win.SetChild(child) | |||
| 41 | + | } | |||
| 32 | 42 | ||||
| 33 | - | w.mu.Lock() | 43 | + | // Show makes the window visible |
| 34 | - | defer w.mu.Unlock() | 44 | + | func (w *Window) Show() { |
| 35 | - | 45 | + | if w == nil || w.win == nil { | |
| 36 | - | // GTK4 behavior: Setting child to 0 removes and potentially invalidates the current child | 46 | + | return |
| 37 | - | if child == 0 && w.child != 0 { | |||
| 38 | - | // GTK4 automatically unparents the current child but keeps the widget alive | |||
| 39 | - | widgetMu.Lock() | |||
| 40 | - | if stub, ok := widgetState[w.child]; ok { | |||
| 41 | - | stub.parent = 0 | |||
| 42 | - | } | |||
| 43 | - | widgetMu.Unlock() | |||
| 44 | } | 47 | } | ||
| 48 | + | w.win.Show() | |||
| 49 | + | } | |||
| 45 | 50 | ||||
| 46 | - | // GTK4 validation: if child is not 0, it must be a valid widget | 51 | + | // Present brings the window to the front |
| 47 | - | if child != 0 { | 52 | + | func (w *Window) Present() { |
| 48 | - | widgetMu.Lock() | 53 | + | if w == nil || w.win == nil { |
| 49 | - | childStub, childExists := widgetState[child] | 54 | + | return |
| 50 | - | if !childExists || childStub.isDestroyed { | |||
| 51 | - | widgetMu.Unlock() | |||
| 52 | - | panic("GTK-CRITICAL simulation: gtk_window_set_child: assertion 'GTK_IS_WIDGET (widget)' failed - child is invalid") | |||
| 53 | - | } | |||
| 54 | - | childStub.parent = 1 // Simplified window handle | |||
| 55 | - | widgetMu.Unlock() | |||
| 56 | } | 55 | } | ||
| 56 | + | w.win.Present() | |||
| 57 | + | } | |||
| 57 | 58 | ||||
| 58 | - | w.child = child | 59 | + | // Close destroys the window |
| 60 | + | func (w *Window) Close() { | |||
| 61 | + | if w == nil || w.win == nil { | |||
| 62 | + | return | |||
| 63 | + | } | |||
| 64 | + | w.win.Close() | |||
| 65 | + | } | |||
| 66 | + | ||||
| 67 | + | // AsWindow returns the underlying gtk.Window for advanced operations | |||
| 68 | + | func (w *Window) AsWindow() *gtk.Window { | |||
| 69 | + | if w == nil { | |||
| 70 | + | return nil | |||
| 71 | + | } | |||
| 72 | + | return w.win | |||
| 59 | } | 73 | } | ||
D pkg/webkit/window_cgo.go +0 -62
| @@ -1,62 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #cgo pkg-config: webkitgtk-6.0 gtk4 | |||
| 7 | - | #cgo CFLAGS: -I/usr/include/webkitgtk-6.0 | |||
| 8 | - | #include <stdlib.h> | |||
| 9 | - | #include <gtk/gtk.h> | |||
| 10 | - | */ | |||
| 11 | - | import "C" | |||
| 12 | - | ||||
| 13 | - | import ( | |||
| 14 | - | "sync" | |||
| 15 | - | "unsafe" | |||
| 16 | - | ) | |||
| 17 | - | ||||
| 18 | - | type Window struct { | |||
| 19 | - | win *C.GtkWidget | |||
| 20 | - | shortcutController *C.GtkShortcutController | |||
| 21 | - | shortcutCallbacks map[string]func() | |||
| 22 | - | shortcutHandles map[string]uintptr | |||
| 23 | - | shortcutMu sync.Mutex | |||
| 24 | - | } | |||
| 25 | - | ||||
| 26 | - | func NewWindow(title string) (*Window, error) { | |||
| 27 | - | if C.gtk_init_check() == 0 { | |||
| 28 | - | return nil, ErrNotImplemented | |||
| 29 | - | } | |||
| 30 | - | ||||
| 31 | - | InitMainThread() | |||
| 32 | - | // GTK4: gtk_window_new() returns GtkWindow*, no toplevel enum | |||
| 33 | - | w := (*C.GtkWidget)(unsafe.Pointer(C.gtk_window_new())) | |||
| 34 | - | if w == nil { | |||
| 35 | - | return nil, ErrNotImplemented | |||
| 36 | - | } | |||
| 37 | - | ctitle := C.CString(title) | |||
| 38 | - | defer C.free(unsafe.Pointer(ctitle)) | |||
| 39 | - | C.gtk_window_set_title((*C.GtkWindow)(unsafe.Pointer(w)), (*C.gchar)(ctitle)) | |||
| 40 | - | return &Window{win: w}, nil | |||
| 41 | - | } | |||
| 42 | - | ||||
| 43 | - | func (w *Window) SetTitle(title string) { | |||
| 44 | - | if w == nil || w.win == nil { | |||
| 45 | - | return | |||
| 46 | - | } | |||
| 47 | - | ctitle := C.CString(title) | |||
| 48 | - | defer C.free(unsafe.Pointer(ctitle)) | |||
| 49 | - | C.gtk_window_set_title((*C.GtkWindow)(unsafe.Pointer(w.win)), (*C.gchar)(ctitle)) | |||
| 50 | - | } | |||
| 51 | - | ||||
| 52 | - | // SetChild assigns the given widget as the GtkWindow child. Passing 0 removes the child. | |||
| 53 | - | func (w *Window) SetChild(child uintptr) { | |||
| 54 | - | if w == nil || w.win == nil { | |||
| 55 | - | return | |||
| 56 | - | } | |||
| 57 | - | var widget *C.GtkWidget | |||
| 58 | - | if child != 0 { | |||
| 59 | - | widget = (*C.GtkWidget)(unsafe.Pointer(child)) | |||
| 60 | - | } | |||
| 61 | - | C.gtk_window_set_child((*C.GtkWindow)(unsafe.Pointer(w.win)), widget) | |||
| 62 | - | } | |||
D pkg/webkit/window_handler_cgo.go +0 -72
| @@ -1,72 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #cgo pkg-config: gtk4 webkitgtk-6.0 | |||
| 7 | - | #include <gtk/gtk.h> | |||
| 8 | - | #include <gdk/gdk.h> | |||
| 9 | - | #include <webkit/webkit.h> | |||
| 10 | - | ||||
| 11 | - | // Declarations for Go callbacks | |||
| 12 | - | extern GtkWidget* goHandleCreateWebView(unsigned long id, char* uri); | |||
| 13 | - | ||||
| 14 | - | // Handle create signal for popup windows - essential for window.open() support | |||
| 15 | - | static GtkWidget* on_create_web_view(WebKitWebView *web_view, | |||
| 16 | - | WebKitNavigationAction *navigation_action, | |||
| 17 | - | gpointer user_data) { | |||
| 18 | - | WebKitURIRequest *request = webkit_navigation_action_get_request(navigation_action); | |||
| 19 | - | const char* uri = webkit_uri_request_get_uri(request); | |||
| 20 | - | ||||
| 21 | - | printf("[webkit-create] Create signal for URI: %s\n", uri ? uri : "NULL"); | |||
| 22 | - | ||||
| 23 | - | unsigned long parent_view_id = (unsigned long)user_data; | |||
| 24 | - | ||||
| 25 | - | // Let Go handler create WebView and return it like Epiphany does | |||
| 26 | - | GtkWidget* new_webview = goHandleCreateWebView(parent_view_id, (char*)uri); | |||
| 27 | - | ||||
| 28 | - | if (new_webview) { | |||
| 29 | - | printf("[webkit-create] Go handler provided WebView - using workspace pane\n"); | |||
| 30 | - | return new_webview; | |||
| 31 | - | } else { | |||
| 32 | - | printf("[webkit-create] Go handler declined - allowing native popup window\n"); | |||
| 33 | - | return NULL; // Let WebKit create native popup window | |||
| 34 | - | } | |||
| 35 | - | } | |||
| 36 | - | ||||
| 37 | - | static void connect_create_signal(WebKitWebView* web_view, unsigned long id) { | |||
| 38 | - | if (!web_view) return; | |||
| 39 | - | g_signal_connect_data(G_OBJECT(web_view), "create", G_CALLBACK(on_create_web_view), (gpointer)id, NULL, 0); | |||
| 40 | - | printf("[webkit-debug] create-web-view callback ENABLED with WebKit-created WebViews\n"); | |||
| 41 | - | } | |||
| 42 | - | */ | |||
| 43 | - | import "C" | |||
| 44 | - | import ( | |||
| 45 | - | "log" | |||
| 46 | - | "unsafe" | |||
| 47 | - | ) | |||
| 48 | - | ||||
| 49 | - | //export goHandleCreateWebView | |||
| 50 | - | func goHandleCreateWebView(parentID C.ulong, curi *C.char) *C.GtkWidget { | |||
| 51 | - | uri := "" | |||
| 52 | - | if curi != nil { | |||
| 53 | - | uri = C.GoString(curi) | |||
| 54 | - | } | |||
| 55 | - | ||||
| 56 | - | log.Printf("[webkit] Create signal bypassed: URI=%s (handled by JavaScript bypass)", uri) | |||
| 57 | - | ||||
| 58 | - | // Always return NULL - window.open is now handled entirely by JavaScript bypass | |||
| 59 | - | // This prevents duplicate pane creation from WebKit's create signal | |||
| 60 | - | return nil | |||
| 61 | - | } | |||
| 62 | - | ||||
| 63 | - | // ConnectCreateSignal connects the create signal to a WebView | |||
| 64 | - | func ConnectCreateSignal(view *WebView) { | |||
| 65 | - | if view == nil || view.native == nil || view.native.view == nil { | |||
| 66 | - | log.Printf("[webkit] ConnectCreateSignal: invalid WebView") | |||
| 67 | - | return | |||
| 68 | - | } | |||
| 69 | - | ||||
| 70 | - | webkitView := (*C.WebKitWebView)(unsafe.Pointer(view.native.view)) | |||
| 71 | - | C.connect_create_signal(webkitView, C.ulong(view.id)) | |||
| 72 | - | } | |||
D pkg/webkit/window_shortcuts.go +0 -160
| @@ -1,160 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | import ( | |||
| 6 | - | "log" | |||
| 7 | - | "strings" | |||
| 8 | - | "unsafe" | |||
| 9 | - | ) | |||
| 10 | - | ||||
| 11 | - | // No C imports needed - using Go wrapper functions from shortcuts_cgo.go | |||
| 12 | - | ||||
| 13 | - | // WindowShortcuts manages global shortcuts at the window level | |||
| 14 | - | type WindowShortcuts struct { | |||
| 15 | - | window *Window | |||
| 16 | - | controller uintptr // *C.GtkShortcutController | |||
| 17 | - | callbacks map[string]uintptr | |||
| 18 | - | } | |||
| 19 | - | ||||
| 20 | - | // InitializeGlobalShortcuts sets up the GTK4 global shortcut controller | |||
| 21 | - | func (w *Window) InitializeGlobalShortcuts() *WindowShortcuts { | |||
| 22 | - | if w.win == nil { | |||
| 23 | - | log.Printf("[window-shortcuts] Cannot initialize - invalid window") | |||
| 24 | - | return nil | |||
| 25 | - | } | |||
| 26 | - | ||||
| 27 | - | controller := CreateGlobalShortcutController(uintptr(unsafe.Pointer(w.win))) | |||
| 28 | - | if controller == 0 { | |||
| 29 | - | log.Printf("[window-shortcuts] Failed to create shortcut controller") | |||
| 30 | - | return nil | |||
| 31 | - | } | |||
| 32 | - | ||||
| 33 | - | ws := &WindowShortcuts{ | |||
| 34 | - | window: w, | |||
| 35 | - | controller: controller, | |||
| 36 | - | callbacks: make(map[string]uintptr), | |||
| 37 | - | } | |||
| 38 | - | ||||
| 39 | - | log.Printf("[window-shortcuts] Global shortcut controller initialized") | |||
| 40 | - | return ws | |||
| 41 | - | } | |||
| 42 | - | ||||
| 43 | - | // RegisterGlobalShortcut registers a shortcut at the window level with global scope | |||
| 44 | - | func (ws *WindowShortcuts) RegisterGlobalShortcut(key string, callback func()) error { | |||
| 45 | - | if ws == nil || ws.controller == 0 { | |||
| 46 | - | return ErrNotImplemented | |||
| 47 | - | } | |||
| 48 | - | ||||
| 49 | - | // Convert key format (e.g., "ctrl+l" -> "<Control>l") | |||
| 50 | - | gtkKey := convertToGtkFormat(key) | |||
| 51 | - | if gtkKey == "" { | |||
| 52 | - | log.Printf("[window-shortcuts] Invalid key format: %s", key) | |||
| 53 | - | return ErrNotImplemented | |||
| 54 | - | } | |||
| 55 | - | ||||
| 56 | - | // Register callback and get handle | |||
| 57 | - | handle := registerWindowShortcutCallback(callback) | |||
| 58 | - | if handle == 0 { | |||
| 59 | - | log.Printf("[window-shortcuts] Failed to register callback for %s", key) | |||
| 60 | - | return ErrNotImplemented | |||
| 61 | - | } | |||
| 62 | - | ||||
| 63 | - | // Store handle for cleanup | |||
| 64 | - | ws.callbacks[key] = handle | |||
| 65 | - | ||||
| 66 | - | // Register with GTK using Go wrapper function | |||
| 67 | - | if err := AddShortcutToController(ws.controller, gtkKey, handle); err != nil { | |||
| 68 | - | log.Printf("[window-shortcuts] Failed to add shortcut to controller: %v", err) | |||
| 69 | - | unregisterWindowShortcutCallback(handle) | |||
| 70 | - | delete(ws.callbacks, key) | |||
| 71 | - | return err | |||
| 72 | - | } | |||
| 73 | - | ||||
| 74 | - | // Only add Alt+Arrow and Ctrl+W shortcuts to global blocking registry | |||
| 75 | - | // All other window shortcuts should bubble up to GTK for proper handling | |||
| 76 | - | if strings.HasPrefix(key, "alt+Arrow") { | |||
| 77 | - | RegisterGlobalShortcutWithHandle(key, handle) | |||
| 78 | - | } else if key == "ctrl+w" { | |||
| 79 | - | // Ctrl+W should also have callback handle for consistent pane closing | |||
| 80 | - | RegisterGlobalShortcutWithHandle(key, handle) | |||
| 81 | - | } | |||
| 82 | - | // Other shortcuts (Ctrl+L, Ctrl+F, zoom) are NOT registered for blocking | |||
| 83 | - | ||||
| 84 | - | log.Printf("[window-shortcuts] Registered global shortcut: %s -> %s", key, gtkKey) | |||
| 85 | - | return nil | |||
| 86 | - | } | |||
| 87 | - | ||||
| 88 | - | // Cleanup unregisters all shortcuts and cleans up resources | |||
| 89 | - | func (ws *WindowShortcuts) Cleanup() { | |||
| 90 | - | if ws == nil { | |||
| 91 | - | return | |||
| 92 | - | } | |||
| 93 | - | ||||
| 94 | - | // Unregister all callbacks | |||
| 95 | - | for key, handle := range ws.callbacks { | |||
| 96 | - | unregisterWindowShortcutCallback(handle) | |||
| 97 | - | log.Printf("[window-shortcuts] Unregistered shortcut: %s", key) | |||
| 98 | - | } | |||
| 99 | - | ||||
| 100 | - | ws.callbacks = nil | |||
| 101 | - | ws.controller = 0 | |||
| 102 | - | } | |||
| 103 | - | ||||
| 104 | - | // convertToGtkFormat converts common key formats to GTK shortcut format | |||
| 105 | - | func convertToGtkFormat(key string) string { | |||
| 106 | - | // Convert from electron/webkit format to GTK format | |||
| 107 | - | key = strings.ToLower(key) | |||
| 108 | - | ||||
| 109 | - | // Handle cmdorctrl -> Control | |||
| 110 | - | key = strings.ReplaceAll(key, "cmdorctrl+", "ctrl+") | |||
| 111 | - | key = strings.ReplaceAll(key, "cmd+", "ctrl+") | |||
| 112 | - | ||||
| 113 | - | // Build GTK format | |||
| 114 | - | var parts []string | |||
| 115 | - | components := strings.Split(key, "+") | |||
| 116 | - | ||||
| 117 | - | for i, part := range components { | |||
| 118 | - | if i == len(components)-1 { | |||
| 119 | - | // Last part is the key | |||
| 120 | - | switch part { | |||
| 121 | - | case "f12": | |||
| 122 | - | parts = append(parts, "F12") | |||
| 123 | - | case "f5": | |||
| 124 | - | parts = append(parts, "F5") | |||
| 125 | - | case "l": | |||
| 126 | - | parts = append(parts, "l") | |||
| 127 | - | case "f": | |||
| 128 | - | parts = append(parts, "f") | |||
| 129 | - | case "r": | |||
| 130 | - | parts = append(parts, "r") | |||
| 131 | - | case "c": | |||
| 132 | - | parts = append(parts, "c") | |||
| 133 | - | case "left", "arrowleft": | |||
| 134 | - | parts = append(parts, "Left") | |||
| 135 | - | case "right", "arrowright": | |||
| 136 | - | parts = append(parts, "Right") | |||
| 137 | - | case "up", "arrowup": | |||
| 138 | - | parts = append(parts, "Up") | |||
| 139 | - | case "down", "arrowdown": | |||
| 140 | - | parts = append(parts, "Down") | |||
| 141 | - | default: | |||
| 142 | - | parts = append(parts, part) | |||
| 143 | - | } | |||
| 144 | - | } else { | |||
| 145 | - | // Modifier | |||
| 146 | - | switch part { | |||
| 147 | - | case "ctrl": | |||
| 148 | - | parts = append(parts, "<Control>") | |||
| 149 | - | case "shift": | |||
| 150 | - | parts = append(parts, "<Shift>") | |||
| 151 | - | case "alt": | |||
| 152 | - | parts = append(parts, "<Alt>") | |||
| 153 | - | case "super": | |||
| 154 | - | parts = append(parts, "<Super>") | |||
| 155 | - | } | |||
| 156 | - | } | |||
| 157 | - | } | |||
| 158 | - | ||||
| 159 | - | return strings.Join(parts, "") | |||
| 160 | - | } | |||
D pkg/webkit/window_shortcuts_stub.go +0 -45
| @@ -1,45 +0,0 @@ | |||||
| 1 | - | //go:build !webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | import "log" | |||
| 6 | - | ||||
| 7 | - | // WindowShortcuts stub implementation for non-CGO builds | |||
| 8 | - | type WindowShortcuts struct { | |||
| 9 | - | window *Window | |||
| 10 | - | } | |||
| 11 | - | ||||
| 12 | - | // InitializeGlobalShortcuts returns a stub implementation for non-CGO builds | |||
| 13 | - | func (w *Window) InitializeGlobalShortcuts() *WindowShortcuts { | |||
| 14 | - | log.Printf("[window-shortcuts] Stub implementation - global shortcuts not available without webkit_cgo") | |||
| 15 | - | return &WindowShortcuts{ | |||
| 16 | - | window: w, | |||
| 17 | - | } | |||
| 18 | - | } | |||
| 19 | - | ||||
| 20 | - | // RegisterGlobalShortcut stub - always returns nil for non-CGO builds | |||
| 21 | - | func (ws *WindowShortcuts) RegisterGlobalShortcut(key string, callback func()) error { | |||
| 22 | - | log.Printf("[window-shortcuts] Stub: would register %s (webkit_cgo required for actual functionality)", key) | |||
| 23 | - | return nil | |||
| 24 | - | } | |||
| 25 | - | ||||
| 26 | - | // Cleanup stub implementation | |||
| 27 | - | func (ws *WindowShortcuts) Cleanup() { | |||
| 28 | - | log.Printf("[window-shortcuts] Stub cleanup") | |||
| 29 | - | } | |||
| 30 | - | ||||
| 31 | - | // Stub implementations for Go wrapper functions | |||
| 32 | - | func CreateGlobalShortcutController(window uintptr) uintptr { | |||
| 33 | - | return 0 | |||
| 34 | - | } | |||
| 35 | - | ||||
| 36 | - | func AddShortcutToController(controller uintptr, key string, handle uintptr) error { | |||
| 37 | - | return nil | |||
| 38 | - | } | |||
| 39 | - | ||||
| 40 | - | func registerWindowShortcutCallback(cb func()) uintptr { | |||
| 41 | - | return 0 | |||
| 42 | - | } | |||
| 43 | - | ||||
| 44 | - | func unregisterWindowShortcutCallback(id uintptr) { | |||
| 45 | - | } | |||
D pkg/webkit/window_types.go +0 -23
| @@ -1,23 +0,0 @@ | |||||
| 1 | - | package webkit | |||
| 2 | - | ||||
| 3 | - | // WindowType indicates how a new WebView should be treated | |||
| 4 | - | type WindowType int | |||
| 5 | - | ||||
| 6 | - | const ( | |||
| 7 | - | // WindowTypeTab represents an independent WebView (future: tab) | |||
| 8 | - | WindowTypeTab WindowType = iota | |||
| 9 | - | // WindowTypePopup represents a related WebView (shares process/context) | |||
| 10 | - | WindowTypePopup | |||
| 11 | - | // WindowTypeUnknown indicates type not detected yet | |||
| 12 | - | WindowTypeUnknown | |||
| 13 | - | ) | |||
| 14 | - | ||||
| 15 | - | // WindowFeatures describes the window features detected from WebKitWindowProperties | |||
| 16 | - | type WindowFeatures struct { | |||
| 17 | - | Width int | |||
| 18 | - | Height int | |||
| 19 | - | ToolbarVisible bool | |||
| 20 | - | LocationbarVisible bool | |||
| 21 | - | MenubarVisible bool | |||
| 22 | - | Resizable bool | |||
| 23 | - | } | |||
D pkg/webkit/workspace_widgets_cgo.go +0 -1350
| @@ -1,1350 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #cgo pkg-config: gtk4 | |||
| 7 | - | #include <gtk/gtk.h> | |||
| 8 | - | #include <gtk/gtktestutils.h> | |||
| 9 | - | #include <gtk/gtkbox.h> | |||
| 10 | - | #include <gtk/gtkpaned.h> | |||
| 11 | - | #include <gdk/gdk.h> | |||
| 12 | - | #include <glib.h> | |||
| 13 | - | #include <glib-object.h> | |||
| 14 | - | #include <graphene.h> | |||
| 15 | - | #include <pthread.h> | |||
| 16 | - | #include <stdint.h> | |||
| 17 | - | #include <stdlib.h> | |||
| 18 | - | ||||
| 19 | - | // Logging helper for diagnostics | |||
| 20 | - | #define WORKSPACE_LOG(fmt, ...) g_printerr("[workspace-cgo] " fmt "\n", ##__VA_ARGS__) | |||
| 21 | - | ||||
| 22 | - | // Helper functions for widget type checking | |||
| 23 | - | static gboolean is_paned_widget(GtkWidget *widget) { | |||
| 24 | - | return GTK_IS_PANED(widget); | |||
| 25 | - | } | |||
| 26 | - | ||||
| 27 | - | static gboolean is_box_widget(GtkWidget *widget) { | |||
| 28 | - | return GTK_IS_BOX(widget); | |||
| 29 | - | } | |||
| 30 | - | ||||
| 31 | - | // Callback function for idle handling following the existing pattern | |||
| 32 | - | extern gboolean goIdleCallback(uintptr_t handle); | |||
| 33 | - | extern void goHoverCallback(uintptr_t handle); | |||
| 34 | - | extern void goFocusEnterCallback(uintptr_t handle); | |||
| 35 | - | extern void goFocusLeaveCallback(uintptr_t handle); | |||
| 36 | - | extern void goTitleBarClickCallback(uintptr_t handle); | |||
| 37 | - | ||||
| 38 | - | // Main thread helpers implemented in thread_helpers.c | |||
| 39 | - | void store_main_thread_id(); | |||
| 40 | - | int is_main_thread(); | |||
| 41 | - | int iterate_main_loop(); | |||
| 42 | - | ||||
| 43 | - | static gboolean idle_callback_wrapper(gpointer data) { | |||
| 44 | - | return goIdleCallback((uintptr_t)data); | |||
| 45 | - | } | |||
| 46 | - | ||||
| 47 | - | static guint add_idle_callback(uintptr_t handle) { | |||
| 48 | - | return g_idle_add_full(G_PRIORITY_DEFAULT_IDLE, idle_callback_wrapper, (gpointer)handle, NULL); | |||
| 49 | - | } | |||
| 50 | - | ||||
| 51 | - | static gboolean remove_idle_callback(uintptr_t handle) { | |||
| 52 | - | return g_idle_remove_by_data((gpointer)handle); | |||
| 53 | - | } | |||
| 54 | - | ||||
| 55 | - | // Title bar click callback | |||
| 56 | - | static void title_bar_click_cb(GtkGestureClick* gesture, gint n_press, gdouble x, gdouble y, gpointer user_data) { | |||
| 57 | - | (void)gesture; (void)n_press; (void)x; (void)y; | |||
| 58 | - | uintptr_t handle = (uintptr_t)user_data; | |||
| 59 | - | goTitleBarClickCallback(handle); | |||
| 60 | - | } | |||
| 61 | - | ||||
| 62 | - | // Attach click handler to a widget (for title bars) | |||
| 63 | - | static void widget_attach_click_handler(GtkWidget* widget, uintptr_t handle) { | |||
| 64 | - | if (!widget) { | |||
| 65 | - | return; | |||
| 66 | - | } | |||
| 67 | - | GtkGesture* click = gtk_gesture_click_new(); | |||
| 68 | - | if (!click) { | |||
| 69 | - | return; | |||
| 70 | - | } | |||
| 71 | - | g_signal_connect_data(click, "pressed", G_CALLBACK(title_bar_click_cb), (gpointer)handle, NULL, 0); | |||
| 72 | - | gtk_widget_add_controller(widget, GTK_EVENT_CONTROLLER(click)); | |||
| 73 | - | } | |||
| 74 | - | ||||
| 75 | - | static void motion_enter_cb(GtkEventControllerMotion* controller, gdouble x, gdouble y, gpointer user_data) { | |||
| 76 | - | (void)controller; (void)x; (void)y; | |||
| 77 | - | uintptr_t handle = (uintptr_t)user_data; | |||
| 78 | - | goHoverCallback(handle); | |||
| 79 | - | } | |||
| 80 | - | ||||
| 81 | - | static GtkEventController* widget_add_hover_controller(GtkWidget* widget, uintptr_t handle) { | |||
| 82 | - | if (!widget) { | |||
| 83 | - | return NULL; | |||
| 84 | - | } | |||
| 85 | - | GtkEventController* motion = gtk_event_controller_motion_new(); | |||
| 86 | - | if (!motion) { | |||
| 87 | - | return NULL; | |||
| 88 | - | } | |||
| 89 | - | gtk_event_controller_set_propagation_phase(motion, GTK_PHASE_CAPTURE); | |||
| 90 | - | g_signal_connect_data(motion, "enter", G_CALLBACK(motion_enter_cb), (gpointer)handle, NULL, 0); | |||
| 91 | - | gtk_widget_add_controller(widget, motion); | |||
| 92 | - | return motion; | |||
| 93 | - | } | |||
| 94 | - | ||||
| 95 | - | static void widget_remove_controller(GtkWidget* widget, GtkEventController* controller) { | |||
| 96 | - | if (!widget || !controller) { | |||
| 97 | - | return; | |||
| 98 | - | } | |||
| 99 | - | gtk_widget_remove_controller(widget, controller); | |||
| 100 | - | } | |||
| 101 | - | ||||
| 102 | - | static gboolean widget_get_bounds(GtkWidget* widget, double* x, double* y, double* width, double* height) { | |||
| 103 | - | if (!widget || !x || !y || !width || !height) { | |||
| 104 | - | return FALSE; | |||
| 105 | - | } | |||
| 106 | - | GtkWidget* root = GTK_WIDGET(gtk_widget_get_root(widget)); | |||
| 107 | - | if (!root) { | |||
| 108 | - | return FALSE; | |||
| 109 | - | } | |||
| 110 | - | graphene_rect_t rect; | |||
| 111 | - | if (!gtk_widget_compute_bounds(widget, root, &rect)) { | |||
| 112 | - | return FALSE; | |||
| 113 | - | } | |||
| 114 | - | *x = rect.origin.x; | |||
| 115 | - | *y = rect.origin.y; | |||
| 116 | - | *width = rect.size.width; | |||
| 117 | - | *height = rect.size.height; | |||
| 118 | - | return TRUE; | |||
| 119 | - | } | |||
| 120 | - | ||||
| 121 | - | // Widget validation helper to prevent crashes from invalid widget pointers | |||
| 122 | - | static gboolean is_valid_widget(gpointer widget) { | |||
| 123 | - | return widget != NULL && GTK_IS_WIDGET(widget); | |||
| 124 | - | } | |||
| 125 | - | ||||
| 126 | - | // Forward declarations for focus controller callbacks defined later in this file | |||
| 127 | - | static void focus_enter_cb(GtkEventControllerFocus* controller, gpointer user_data); | |||
| 128 | - | static void focus_leave_cb(GtkEventControllerFocus* controller, gpointer user_data); | |||
| 129 | - | ||||
| 130 | - | typedef struct { | |||
| 131 | - | GtkEventController* controller; | |||
| 132 | - | GtkWidget* widget; | |||
| 133 | - | gboolean is_attached; | |||
| 134 | - | } ControllerTracker; | |||
| 135 | - | ||||
| 136 | - | static GHashTable* controller_registry = NULL; | |||
| 137 | - | ||||
| 138 | - | static void init_controller_registry(void) { | |||
| 139 | - | if (controller_registry == NULL) { | |||
| 140 | - | controller_registry = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, g_free); | |||
| 141 | - | } | |||
| 142 | - | } | |||
| 143 | - | ||||
| 144 | - | static void controller_on_widget_destroy(GtkWidget* widget, gpointer user_data) { | |||
| 145 | - | (void)widget; | |||
| 146 | - | ControllerTracker* tracker = (ControllerTracker*)user_data; | |||
| 147 | - | if (!tracker) { | |||
| 148 | - | return; | |||
| 149 | - | } | |||
| 150 | - | tracker->is_attached = FALSE; | |||
| 151 | - | } | |||
| 152 | - | ||||
| 153 | - | static GtkEventController* widget_add_focus_controller(GtkWidget* widget, uintptr_t nodePtr) { | |||
| 154 | - | if (!widget) { | |||
| 155 | - | return NULL; | |||
| 156 | - | } | |||
| 157 | - | ||||
| 158 | - | init_controller_registry(); | |||
| 159 | - | ||||
| 160 | - | GtkEventController* focus = gtk_event_controller_focus_new(); | |||
| 161 | - | if (!focus) { | |||
| 162 | - | return NULL; | |||
| 163 | - | } | |||
| 164 | - | ||||
| 165 | - | gtk_event_controller_set_propagation_phase(focus, GTK_PHASE_CAPTURE); | |||
| 166 | - | g_signal_connect(focus, "enter", G_CALLBACK(focus_enter_cb), (gpointer)nodePtr); | |||
| 167 | - | g_signal_connect(focus, "leave", G_CALLBACK(focus_leave_cb), (gpointer)nodePtr); | |||
| 168 | - | ||||
| 169 | - | ControllerTracker* tracker = g_new0(ControllerTracker, 1); | |||
| 170 | - | tracker->controller = focus; | |||
| 171 | - | tracker->widget = widget; | |||
| 172 | - | tracker->is_attached = TRUE; | |||
| 173 | - | ||||
| 174 | - | g_hash_table_insert(controller_registry, focus, tracker); | |||
| 175 | - | ||||
| 176 | - | g_signal_connect(widget, "destroy", G_CALLBACK(controller_on_widget_destroy), tracker); | |||
| 177 | - | ||||
| 178 | - | gtk_widget_add_controller(widget, focus); | |||
| 179 | - | return focus; | |||
| 180 | - | } | |||
| 181 | - | ||||
| 182 | - | static void widget_remove_focus_controller(GtkWidget* widget, GtkEventController* controller) { | |||
| 183 | - | if (!controller_registry || !controller) { | |||
| 184 | - | return; | |||
| 185 | - | } | |||
| 186 | - | ||||
| 187 | - | ControllerTracker* tracker = g_hash_table_lookup(controller_registry, controller); | |||
| 188 | - | if (!tracker) { | |||
| 189 | - | return; | |||
| 190 | - | } | |||
| 191 | - | ||||
| 192 | - | if (!tracker->is_attached) { | |||
| 193 | - | return; | |||
| 194 | - | } | |||
| 195 | - | ||||
| 196 | - | if (!GTK_IS_WIDGET(widget)) { | |||
| 197 | - | tracker->is_attached = FALSE; | |||
| 198 | - | return; | |||
| 199 | - | } | |||
| 200 | - | ||||
| 201 | - | GtkWidget* owner = gtk_event_controller_get_widget(controller); | |||
| 202 | - | if (GTK_IS_WIDGET(owner) && owner == widget) { | |||
| 203 | - | gtk_widget_remove_controller(widget, controller); | |||
| 204 | - | } | |||
| 205 | - | ||||
| 206 | - | tracker->is_attached = FALSE; | |||
| 207 | - | ||||
| 208 | - | // Remove from registry; GTK drops the final reference when removing controller | |||
| 209 | - | g_hash_table_remove(controller_registry, controller); | |||
| 210 | - | } | |||
| 211 | - | ||||
| 212 | - | static GtkWidget* paned_get_start_child(GtkWidget* paned) { | |||
| 213 | - | if (!paned) return NULL; | |||
| 214 | - | return gtk_paned_get_start_child(GTK_PANED(paned)); | |||
| 215 | - | } | |||
| 216 | - | ||||
| 217 | - | static GtkWidget* paned_get_end_child(GtkWidget* paned) { | |||
| 218 | - | if (!paned) return NULL; | |||
| 219 | - | return gtk_paned_get_end_child(GTK_PANED(paned)); | |||
| 220 | - | } | |||
| 221 | - | ||||
| 222 | - | static void on_widget_destroyed(GtkWidget* widget, gpointer user_data) { | |||
| 223 | - | (void)user_data; | |||
| 224 | - | guint ref_count = widget ? G_OBJECT(widget)->ref_count : 0; | |||
| 225 | - | WORKSPACE_LOG("widget destroyed: %p ref_count=%u", widget, ref_count); | |||
| 226 | - | } | |||
| 227 | - | ||||
| 228 | - | static void hook_destroy_signal(GtkWidget* widget) { | |||
| 229 | - | if (!widget) return; | |||
| 230 | - | g_signal_connect(widget, "destroy", G_CALLBACK(on_widget_destroyed), NULL); | |||
| 231 | - | } | |||
| 232 | - | ||||
| 233 | - | static unsigned int widget_get_ref_count(GtkWidget* widget) { | |||
| 234 | - | if (!widget) { | |||
| 235 | - | return 0; | |||
| 236 | - | } | |||
| 237 | - | return G_OBJECT(widget)->ref_count; | |||
| 238 | - | } | |||
| 239 | - | ||||
| 240 | - | // Widget realization helpers for proper WebView reparenting | |||
| 241 | - | // Force widget realization and ensure it's ready for rendering | |||
| 242 | - | static void ensure_widget_realized(GtkWidget* widget) { | |||
| 243 | - | if (!widget) return; | |||
| 244 | - | ||||
| 245 | - | // Make widget visible first | |||
| 246 | - | gtk_widget_set_visible(widget, TRUE); | |||
| 247 | - | ||||
| 248 | - | // For WebKitWebView, we need to ensure the widget is properly sized | |||
| 249 | - | gtk_widget_set_size_request(widget, 100, 100); // Minimum size to force allocation | |||
| 250 | - | ||||
| 251 | - | // Queue a redraw to force the rendering context to reinitialize | |||
| 252 | - | gtk_widget_queue_draw(widget); | |||
| 253 | - | WORKSPACE_LOG("ensure_widget_realized: widget=%p", widget); | |||
| 254 | - | } | |||
| 255 | - | ||||
| 256 | - | static void add_css_provider(const char* css) { | |||
| 257 | - | if (!css) { | |||
| 258 | - | return; | |||
| 259 | - | } | |||
| 260 | - | GtkCssProvider* provider = gtk_css_provider_new(); | |||
| 261 | - | if (!provider) { | |||
| 262 | - | return; | |||
| 263 | - | } | |||
| 264 | - | gtk_css_provider_load_from_string(provider, css); | |||
| 265 | - | GdkDisplay* display = gdk_display_get_default(); | |||
| 266 | - | if (display) { | |||
| 267 | - | gtk_style_context_add_provider_for_display(display, GTK_STYLE_PROVIDER(provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); | |||
| 268 | - | } | |||
| 269 | - | g_object_unref(provider); | |||
| 270 | - | } | |||
| 271 | - | ||||
| 272 | - | static void widget_add_css_class(GtkWidget* widget, const char* name) { | |||
| 273 | - | if (!widget || !name) return; | |||
| 274 | - | gtk_widget_add_css_class(widget, name); | |||
| 275 | - | } | |||
| 276 | - | ||||
| 277 | - | static void widget_remove_css_class(GtkWidget* widget, const char* name) { | |||
| 278 | - | if (!widget || !name) return; | |||
| 279 | - | gtk_widget_remove_css_class(widget, name); | |||
| 280 | - | } | |||
| 281 | - | ||||
| 282 | - | // GtkBox helpers for stacked panes | |||
| 283 | - | static GtkWidget* box_new(GtkOrientation orientation, int spacing) { | |||
| 284 | - | return gtk_box_new(orientation, spacing); | |||
| 285 | - | } | |||
| 286 | - | ||||
| 287 | - | static void box_append(GtkWidget* box, GtkWidget* child) { | |||
| 288 | - | if (!box || !child) return; | |||
| 289 | - | gtk_box_append(GTK_BOX(box), child); | |||
| 290 | - | } | |||
| 291 | - | ||||
| 292 | - | static void box_prepend(GtkWidget* box, GtkWidget* child) { | |||
| 293 | - | if (!box || !child) return; | |||
| 294 | - | gtk_box_prepend(GTK_BOX(box), child); | |||
| 295 | - | } | |||
| 296 | - | ||||
| 297 | - | static void box_remove(GtkWidget* box, GtkWidget* child) { | |||
| 298 | - | if (!box || !child) return; | |||
| 299 | - | gtk_box_remove(GTK_BOX(box), child); | |||
| 300 | - | } | |||
| 301 | - | ||||
| 302 | - | static void box_insert_child_after(GtkWidget* box, GtkWidget* child, GtkWidget* sibling) { | |||
| 303 | - | if (!box || !child) return; | |||
| 304 | - | gtk_box_insert_child_after(GTK_BOX(box), child, sibling); | |||
| 305 | - | } | |||
| 306 | - | ||||
| 307 | - | // Widget visibility helpers for stacked panes | |||
| 308 | - | static void widget_set_visible(GtkWidget* widget, gboolean visible) { | |||
| 309 | - | if (!widget) return; | |||
| 310 | - | gtk_widget_set_visible(widget, visible); | |||
| 311 | - | } | |||
| 312 | - | ||||
| 313 | - | ||||
| 314 | - | static gboolean widget_get_visible(GtkWidget* widget) { | |||
| 315 | - | if (!widget) return FALSE; | |||
| 316 | - | return gtk_widget_get_visible(widget); | |||
| 317 | - | } | |||
| 318 | - | ||||
| 319 | - | static void widget_hide(GtkWidget* widget) { | |||
| 320 | - | if (!widget) return; | |||
| 321 | - | gtk_widget_set_visible(widget, FALSE); | |||
| 322 | - | } | |||
| 323 | - | ||||
| 324 | - | static void widget_show(GtkWidget* widget) { | |||
| 325 | - | if (!widget) return; | |||
| 326 | - | gtk_widget_set_visible(widget, TRUE); | |||
| 327 | - | } | |||
| 328 | - | ||||
| 329 | - | // workspace_gtk_test_init removed - moved to test files only | |||
| 330 | - | ||||
| 331 | - | // Label helpers for title bars | |||
| 332 | - | static GtkWidget* label_new(const char* text) { | |||
| 333 | - | return gtk_label_new(text); | |||
| 334 | - | } | |||
| 335 | - | ||||
| 336 | - | static void label_set_text(GtkWidget* label, const char* text) { | |||
| 337 | - | if (!label || !text) return; | |||
| 338 | - | gtk_label_set_text(GTK_LABEL(label), text); | |||
| 339 | - | } | |||
| 340 | - | ||||
| 341 | - | static const char* label_get_text(GtkWidget* label) { | |||
| 342 | - | if (!label) return NULL; | |||
| 343 | - | return gtk_label_get_text(GTK_LABEL(label)); | |||
| 344 | - | } | |||
| 345 | - | ||||
| 346 | - | static void label_set_ellipsize(GtkWidget* label, int mode) { | |||
| 347 | - | if (!label) return; | |||
| 348 | - | gtk_label_set_ellipsize(GTK_LABEL(label), (PangoEllipsizeMode)mode); | |||
| 349 | - | } | |||
| 350 | - | ||||
| 351 | - | static void label_set_max_width_chars(GtkWidget* label, int n_chars) { | |||
| 352 | - | if (!label) return; | |||
| 353 | - | gtk_label_set_max_width_chars(GTK_LABEL(label), n_chars); | |||
| 354 | - | } | |||
| 355 | - | ||||
| 356 | - | // GTK4 Focus Controller helpers for focus state machine | |||
| 357 | - | static void focus_enter_cb(GtkEventControllerFocus* controller, gpointer user_data) { | |||
| 358 | - | (void)controller; | |||
| 359 | - | uintptr_t nodePtr = (uintptr_t)user_data; | |||
| 360 | - | goFocusEnterCallback(nodePtr); | |||
| 361 | - | } | |||
| 362 | - | ||||
| 363 | - | static void focus_leave_cb(GtkEventControllerFocus* controller, gpointer user_data) { | |||
| 364 | - | (void)controller; | |||
| 365 | - | uintptr_t nodePtr = (uintptr_t)user_data; | |||
| 366 | - | goFocusLeaveCallback(nodePtr); | |||
| 367 | - | } | |||
| 368 | - | ||||
| 369 | - | // Widget allocation helper using modern GTK4 API | |||
| 370 | - | static void widget_get_allocation_modern(GtkWidget* widget, int* x, int* y, int* width, int* height) { | |||
| 371 | - | if (!widget || !x || !y || !width || !height) { | |||
| 372 | - | *x = *y = *width = *height = 0; | |||
| 373 | - | return; | |||
| 374 | - | } | |||
| 375 | - | ||||
| 376 | - | graphene_rect_t bounds; | |||
| 377 | - | // Compute bounds relative to the widget itself (pass widget as target) | |||
| 378 | - | if (gtk_widget_compute_bounds(widget, widget, &bounds)) { | |||
| 379 | - | // Extract integer coordinates from the graphene rect | |||
| 380 | - | *x = (int)bounds.origin.x; | |||
| 381 | - | *y = (int)bounds.origin.y; | |||
| 382 | - | *width = (int)bounds.size.width; | |||
| 383 | - | *height = (int)bounds.size.height; | |||
| 384 | - | } else { | |||
| 385 | - | // Fallback if compute_bounds fails | |||
| 386 | - | *x = *y = 0; | |||
| 387 | - | *width = gtk_widget_get_width(widget); | |||
| 388 | - | *height = gtk_widget_get_height(widget); | |||
| 389 | - | } | |||
| 390 | - | } | |||
| 391 | - | ||||
| 392 | - | // GtkImage helpers for favicon display | |||
| 393 | - | static GtkWidget* image_new(void) { | |||
| 394 | - | return gtk_image_new(); | |||
| 395 | - | } | |||
| 396 | - | ||||
| 397 | - | static GtkWidget* image_new_from_file(const char* filename) { | |||
| 398 | - | if (!filename) return NULL; | |||
| 399 | - | return gtk_image_new_from_file(filename); | |||
| 400 | - | } | |||
| 401 | - | ||||
| 402 | - | static void image_set_from_file(GtkWidget* image, const char* filename) { | |||
| 403 | - | if (!image || !filename) return; | |||
| 404 | - | gtk_image_set_from_file(GTK_IMAGE(image), filename); | |||
| 405 | - | } | |||
| 406 | - | ||||
| 407 | - | static void image_set_pixel_size(GtkWidget* image, int pixel_size) { | |||
| 408 | - | if (!image) return; | |||
| 409 | - | gtk_image_set_pixel_size(GTK_IMAGE(image), pixel_size); | |||
| 410 | - | } | |||
| 411 | - | */ | |||
| 412 | - | import "C" | |||
| 413 | - | ||||
| 414 | - | import ( | |||
| 415 | - | "log" | |||
| 416 | - | "sync" | |||
| 417 | - | "unsafe" | |||
| 418 | - | ) | |||
| 419 | - | ||||
| 420 | - | // WidgetBounds captures absolute widget bounds relative to the toplevel window. | |||
| 421 | - | type WidgetBounds struct { | |||
| 422 | - | X float64 | |||
| 423 | - | Y float64 | |||
| 424 | - | Width float64 | |||
| 425 | - | Height float64 | |||
| 426 | - | } | |||
| 427 | - | ||||
| 428 | - | // FocusCallbacks holds the enter and leave callbacks for focus events | |||
| 429 | - | type FocusCallbacks struct { | |||
| 430 | - | OnEnter func() | |||
| 431 | - | OnLeave func() | |||
| 432 | - | } | |||
| 433 | - | ||||
| 434 | - | // WidgetAllocation represents a widget's allocation (position and size) | |||
| 435 | - | type WidgetAllocation struct { | |||
| 436 | - | X int | |||
| 437 | - | Y int | |||
| 438 | - | Width int | |||
| 439 | - | Height int | |||
| 440 | - | } | |||
| 441 | - | ||||
| 442 | - | var ( | |||
| 443 | - | hoverMu sync.Mutex | |||
| 444 | - | hoverCallbacks = make(map[uintptr]func()) | |||
| 445 | - | hoverControllers = make(map[uintptr]uintptr) | |||
| 446 | - | nextHoverID uintptr = 1 | |||
| 447 | - | // gtkTestInitOnce removed - no longer needed | |||
| 448 | - | ||||
| 449 | - | // Focus controller management | |||
| 450 | - | focusMu sync.Mutex | |||
| 451 | - | focusCallbacks = make(map[uintptr]FocusCallbacks) | |||
| 452 | - | focusControllers = make(map[uintptr]uintptr) | |||
| 453 | - | nextFocusID uintptr = 1 | |||
| 454 | - | ||||
| 455 | - | // Title bar click management | |||
| 456 | - | titleBarMu sync.Mutex | |||
| 457 | - | titleBarCallbacks = make(map[uintptr]func()) | |||
| 458 | - | nextTitleBarID uintptr = 1 | |||
| 459 | - | ||||
| 460 | - | mainThreadInitialized bool | |||
| 461 | - | ) | |||
| 462 | - | ||||
| 463 | - | // InitMainThread should be called once during gtk_init to store the main thread ID. | |||
| 464 | - | func InitMainThread() { | |||
| 465 | - | if !mainThreadInitialized { | |||
| 466 | - | C.store_main_thread_id() | |||
| 467 | - | mainThreadInitialized = true | |||
| 468 | - | } | |||
| 469 | - | } | |||
| 470 | - | ||||
| 471 | - | // IsMainThread returns true if the current goroutine is running on the GTK main thread. | |||
| 472 | - | func IsMainThread() bool { | |||
| 473 | - | if !mainThreadInitialized { | |||
| 474 | - | return false | |||
| 475 | - | } | |||
| 476 | - | return C.is_main_thread() == 1 | |||
| 477 | - | } | |||
| 478 | - | ||||
| 479 | - | func widgetIsValid(widget uintptr) bool { | |||
| 480 | - | if widget == 0 { | |||
| 481 | - | return false | |||
| 482 | - | } | |||
| 483 | - | return C.is_valid_widget(C.gpointer(unsafe.Pointer(widget))) != 0 | |||
| 484 | - | } | |||
| 485 | - | ||||
| 486 | - | func widgetRefCount(widget uintptr) uint { | |||
| 487 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 488 | - | return 0 | |||
| 489 | - | } | |||
| 490 | - | return uint(C.widget_get_ref_count((*C.GtkWidget)(unsafe.Pointer(widget)))) | |||
| 491 | - | } | |||
| 492 | - | ||||
| 493 | - | // WidgetIsValid exposes GTK_IS_WIDGET checks for diagnostics in Go. | |||
| 494 | - | func WidgetIsValid(widget uintptr) bool { | |||
| 495 | - | return widgetIsValid(widget) | |||
| 496 | - | } | |||
| 497 | - | ||||
| 498 | - | // IsPaned checks if a widget is a GtkPaned container. | |||
| 499 | - | func IsPaned(widget uintptr) bool { | |||
| 500 | - | if widget == 0 { | |||
| 501 | - | return false | |||
| 502 | - | } | |||
| 503 | - | return C.is_paned_widget((*C.GtkWidget)(unsafe.Pointer(widget))) != 0 | |||
| 504 | - | } | |||
| 505 | - | ||||
| 506 | - | // IsBox checks if a widget is a GtkBox container. | |||
| 507 | - | func IsBox(widget uintptr) bool { | |||
| 508 | - | if widget == 0 { | |||
| 509 | - | return false | |||
| 510 | - | } | |||
| 511 | - | return C.is_box_widget((*C.GtkWidget)(unsafe.Pointer(widget))) != 0 | |||
| 512 | - | } | |||
| 513 | - | ||||
| 514 | - | // WidgetRefCount exposes the widget reference count for debugging. | |||
| 515 | - | func WidgetRefCount(widget uintptr) uint { | |||
| 516 | - | return widgetRefCount(widget) | |||
| 517 | - | } | |||
| 518 | - | ||||
| 519 | - | // WidgetHookDestroy attaches a destroy signal handler for diagnostics (debug builds). | |||
| 520 | - | func WidgetHookDestroy(widget uintptr) { | |||
| 521 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 522 | - | return | |||
| 523 | - | } | |||
| 524 | - | C.hook_destroy_signal((*C.GtkWidget)(unsafe.Pointer(widget))) | |||
| 525 | - | } | |||
| 526 | - | ||||
| 527 | - | // AddCSSProvider installs application-level CSS rules. | |||
| 528 | - | func AddCSSProvider(css string) { | |||
| 529 | - | if css == "" { | |||
| 530 | - | return | |||
| 531 | - | } | |||
| 532 | - | cstr := C.CString(css) | |||
| 533 | - | defer C.free(unsafe.Pointer(cstr)) | |||
| 534 | - | C.add_css_provider(cstr) | |||
| 535 | - | } | |||
| 536 | - | ||||
| 537 | - | // WidgetAddCSSClass attaches a CSS class to a widget. | |||
| 538 | - | func WidgetAddCSSClass(widget uintptr, class string) { | |||
| 539 | - | if widget == 0 || class == "" || !widgetIsValid(widget) { | |||
| 540 | - | return | |||
| 541 | - | } | |||
| 542 | - | cstr := C.CString(class) | |||
| 543 | - | defer C.free(unsafe.Pointer(cstr)) | |||
| 544 | - | C.widget_add_css_class((*C.GtkWidget)(unsafe.Pointer(widget)), cstr) | |||
| 545 | - | } | |||
| 546 | - | ||||
| 547 | - | // WidgetRemoveCSSClass removes a CSS class from a widget. | |||
| 548 | - | func WidgetRemoveCSSClass(widget uintptr, class string) { | |||
| 549 | - | if widget == 0 || class == "" || !widgetIsValid(widget) { | |||
| 550 | - | return | |||
| 551 | - | } | |||
| 552 | - | cstr := C.CString(class) | |||
| 553 | - | defer C.free(unsafe.Pointer(cstr)) | |||
| 554 | - | C.widget_remove_css_class((*C.GtkWidget)(unsafe.Pointer(widget)), cstr) | |||
| 555 | - | } | |||
| 556 | - | ||||
| 557 | - | // Orientation mirrors GtkOrientation for workspace layout helpers. | |||
| 558 | - | type Orientation int | |||
| 559 | - | ||||
| 560 | - | const ( | |||
| 561 | - | OrientationHorizontal Orientation = Orientation(C.GTK_ORIENTATION_HORIZONTAL) | |||
| 562 | - | OrientationVertical Orientation = Orientation(C.GTK_ORIENTATION_VERTICAL) | |||
| 563 | - | ) | |||
| 564 | - | ||||
| 565 | - | func goBool(b bool) C.gboolean { | |||
| 566 | - | if b { | |||
| 567 | - | return C.gboolean(1) | |||
| 568 | - | } | |||
| 569 | - | return C.gboolean(0) | |||
| 570 | - | } | |||
| 571 | - | ||||
| 572 | - | // NewPaned constructs a GtkPaned widget for the given orientation. | |||
| 573 | - | func NewPaned(orientation Orientation) uintptr { | |||
| 574 | - | paned := C.gtk_paned_new(C.GtkOrientation(orientation)) | |||
| 575 | - | return uintptr(unsafe.Pointer(paned)) | |||
| 576 | - | } | |||
| 577 | - | ||||
| 578 | - | // PanedSetStartChild assigns the start child of a GtkPaned. | |||
| 579 | - | func PanedSetStartChild(paned uintptr, child uintptr) { | |||
| 580 | - | if child != 0 { | |||
| 581 | - | // Check if widget already has a parent and force unparent if needed | |||
| 582 | - | parent := C.gtk_widget_get_parent((*C.GtkWidget)(unsafe.Pointer(child))) | |||
| 583 | - | if parent != nil { | |||
| 584 | - | C.gtk_widget_unparent((*C.GtkWidget)(unsafe.Pointer(child))) | |||
| 585 | - | } | |||
| 586 | - | } | |||
| 587 | - | C.gtk_paned_set_start_child((*C.GtkPaned)(unsafe.Pointer(paned)), (*C.GtkWidget)(unsafe.Pointer(child))) | |||
| 588 | - | } | |||
| 589 | - | ||||
| 590 | - | // PanedSetEndChild assigns the end child of a GtkPaned. | |||
| 591 | - | func PanedSetEndChild(paned uintptr, child uintptr) { | |||
| 592 | - | if child != 0 { | |||
| 593 | - | // Check if widget already has a parent and force unparent if needed | |||
| 594 | - | parent := C.gtk_widget_get_parent((*C.GtkWidget)(unsafe.Pointer(child))) | |||
| 595 | - | if parent != nil { | |||
| 596 | - | C.gtk_widget_unparent((*C.GtkWidget)(unsafe.Pointer(child))) | |||
| 597 | - | } | |||
| 598 | - | } | |||
| 599 | - | C.gtk_paned_set_end_child((*C.GtkPaned)(unsafe.Pointer(paned)), (*C.GtkWidget)(unsafe.Pointer(child))) | |||
| 600 | - | } | |||
| 601 | - | ||||
| 602 | - | // PanedGetStartChild returns the start child pointer for diagnostics. | |||
| 603 | - | func PanedGetStartChild(paned uintptr) uintptr { | |||
| 604 | - | if paned == 0 { | |||
| 605 | - | return 0 | |||
| 606 | - | } | |||
| 607 | - | child := C.paned_get_start_child((*C.GtkWidget)(unsafe.Pointer(paned))) | |||
| 608 | - | return uintptr(unsafe.Pointer(child)) | |||
| 609 | - | } | |||
| 610 | - | ||||
| 611 | - | // PanedGetEndChild returns the end child pointer for diagnostics. | |||
| 612 | - | func PanedGetEndChild(paned uintptr) uintptr { | |||
| 613 | - | if paned == 0 { | |||
| 614 | - | return 0 | |||
| 615 | - | } | |||
| 616 | - | child := C.paned_get_end_child((*C.GtkWidget)(unsafe.Pointer(paned))) | |||
| 617 | - | return uintptr(unsafe.Pointer(child)) | |||
| 618 | - | } | |||
| 619 | - | ||||
| 620 | - | // PanedSetResizeStart configures whether the start child should expand when the paned is resized. | |||
| 621 | - | func PanedSetResizeStart(paned uintptr, resize bool) { | |||
| 622 | - | C.gtk_paned_set_resize_start_child((*C.GtkPaned)(unsafe.Pointer(paned)), goBool(resize)) | |||
| 623 | - | } | |||
| 624 | - | ||||
| 625 | - | // PanedSetResizeEnd configures whether the end child should expand when the paned is resized. | |||
| 626 | - | func PanedSetResizeEnd(paned uintptr, resize bool) { | |||
| 627 | - | C.gtk_paned_set_resize_end_child((*C.GtkPaned)(unsafe.Pointer(paned)), goBool(resize)) | |||
| 628 | - | } | |||
| 629 | - | ||||
| 630 | - | // PanedSetPosition sets the pixel position of the divider. | |||
| 631 | - | func PanedSetPosition(paned uintptr, pos int) { | |||
| 632 | - | if paned == 0 { | |||
| 633 | - | return | |||
| 634 | - | } | |||
| 635 | - | C.gtk_paned_set_position((*C.GtkPaned)(unsafe.Pointer(paned)), C.int(pos)) | |||
| 636 | - | } | |||
| 637 | - | ||||
| 638 | - | // PanedGetPosition gets the current position of the divider in a GtkPaned | |||
| 639 | - | func PanedGetPosition(paned uintptr) int { | |||
| 640 | - | if paned == 0 { | |||
| 641 | - | return 0 | |||
| 642 | - | } | |||
| 643 | - | if !widgetIsValid(paned) { | |||
| 644 | - | return 0 | |||
| 645 | - | } | |||
| 646 | - | return int(C.gtk_paned_get_position((*C.GtkPaned)(unsafe.Pointer(paned)))) | |||
| 647 | - | } | |||
| 648 | - | ||||
| 649 | - | // WidgetUnparent detaches a widget from its current parent. | |||
| 650 | - | func WidgetUnparent(widget uintptr) { | |||
| 651 | - | if ok := WidgetUnparentChecked(widget); !ok { | |||
| 652 | - | log.Printf("[workspace] WidgetUnparent skipped for widget=%#x", widget) | |||
| 653 | - | } | |||
| 654 | - | } | |||
| 655 | - | ||||
| 656 | - | // WidgetUnparentChecked safely detaches a widget from its parent if still valid. | |||
| 657 | - | // | |||
| 658 | - | // Return semantics: | |||
| 659 | - | // - Returns false if the widget pointer is zero or not a valid GTK widget (invalid input). | |||
| 660 | - | // - Returns true if the widget has no parent (already detached). | |||
| 661 | - | // - Returns true if the widget was successfully unparented (parent changed or is now nil). | |||
| 662 | - | // - Returns false if the widget is still valid and the parent did not change (unparent failed). | |||
| 663 | - | // | |||
| 664 | - | // Callers can use the return value to distinguish between invalid input, already-detached widgets, and successful unparenting. | |||
| 665 | - | func WidgetUnparentChecked(widget uintptr) bool { | |||
| 666 | - | if widget == 0 { | |||
| 667 | - | log.Printf("[workspace] WidgetUnparentChecked: widget=0") | |||
| 668 | - | return false | |||
| 669 | - | } | |||
| 670 | - | ||||
| 671 | - | if !widgetIsValid(widget) { | |||
| 672 | - | log.Printf("[workspace] WidgetUnparentChecked: widget=%#x invalid before unparent", widget) | |||
| 673 | - | return false | |||
| 674 | - | } | |||
| 675 | - | ||||
| 676 | - | parentBefore := WidgetGetParent(widget) | |||
| 677 | - | if parentBefore == 0 { | |||
| 678 | - | log.Printf("[workspace] WidgetUnparentChecked: widget=%#x has no parent", widget) | |||
| 679 | - | return true | |||
| 680 | - | } | |||
| 681 | - | ||||
| 682 | - | refBefore := widgetRefCount(widget) | |||
| 683 | - | log.Printf("[workspace] WidgetUnparentChecked: widget=%#x parent=%#x ref_before=%d", widget, parentBefore, refBefore) | |||
| 684 | - | ||||
| 685 | - | C.gtk_widget_unparent((*C.GtkWidget)(unsafe.Pointer(widget))) | |||
| 686 | - | ||||
| 687 | - | if !widgetIsValid(widget) { | |||
| 688 | - | log.Printf("[workspace] WidgetUnparentChecked: widget=%#x invalid after unparent", widget) | |||
| 689 | - | return true | |||
| 690 | - | } | |||
| 691 | - | ||||
| 692 | - | parentAfter := WidgetGetParent(widget) | |||
| 693 | - | refAfter := widgetRefCount(widget) | |||
| 694 | - | log.Printf("[workspace] WidgetUnparentChecked: widget=%#x parent_after=%#x ref_after=%d", widget, parentAfter, refAfter) | |||
| 695 | - | ||||
| 696 | - | return parentAfter == 0 || parentAfter != parentBefore | |||
| 697 | - | } | |||
| 698 | - | ||||
| 699 | - | // WidgetSetHExpand configures horizontal expand for a widget. | |||
| 700 | - | func WidgetSetHExpand(widget uintptr, expand bool) { | |||
| 701 | - | if widget == 0 { | |||
| 702 | - | return | |||
| 703 | - | } | |||
| 704 | - | log.Printf("[workspace] WidgetSetHExpand widget=%#x expand=%v", widget, expand) | |||
| 705 | - | C.gtk_widget_set_hexpand((*C.GtkWidget)(unsafe.Pointer(widget)), goBool(expand)) | |||
| 706 | - | } | |||
| 707 | - | ||||
| 708 | - | func WidgetGetParent(widget uintptr) uintptr { | |||
| 709 | - | if widget == 0 { | |||
| 710 | - | log.Printf("[workspace] WidgetGetParent: widget=0") | |||
| 711 | - | return 0 | |||
| 712 | - | } | |||
| 713 | - | if !widgetIsValid(widget) { | |||
| 714 | - | log.Printf("[workspace] WidgetGetParent: widget=%#x invalid", widget) | |||
| 715 | - | return 0 | |||
| 716 | - | } | |||
| 717 | - | parent := C.gtk_widget_get_parent((*C.GtkWidget)(unsafe.Pointer(widget))) | |||
| 718 | - | // Reduced logging: only debug mode shows individual widget operations | |||
| 719 | - | return uintptr(unsafe.Pointer(parent)) | |||
| 720 | - | } | |||
| 721 | - | ||||
| 722 | - | // WidgetSetVExpand configures vertical expand for a widget. | |||
| 723 | - | func WidgetSetVExpand(widget uintptr, expand bool) { | |||
| 724 | - | if widget == 0 { | |||
| 725 | - | return | |||
| 726 | - | } | |||
| 727 | - | log.Printf("[workspace] WidgetSetVExpand widget=%#x expand=%v", widget, expand) | |||
| 728 | - | C.gtk_widget_set_vexpand((*C.GtkWidget)(unsafe.Pointer(widget)), goBool(expand)) | |||
| 729 | - | } | |||
| 730 | - | ||||
| 731 | - | // WidgetSetSizeRequest sets the minimum size request for a widget. | |||
| 732 | - | // Use -1 for width or height to unset that dimension. | |||
| 733 | - | func WidgetSetSizeRequest(widget uintptr, width, height int) { | |||
| 734 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 735 | - | return | |||
| 736 | - | } | |||
| 737 | - | log.Printf("[workspace] WidgetSetSizeRequest widget=%#x width=%d height=%d", widget, width, height) | |||
| 738 | - | C.gtk_widget_set_size_request((*C.GtkWidget)(unsafe.Pointer(widget)), C.int(width), C.int(height)) | |||
| 739 | - | } | |||
| 740 | - | ||||
| 741 | - | // WidgetResetSizeRequest clears explicit size constraints so GTK can recalculate allocation. | |||
| 742 | - | func WidgetResetSizeRequest(widget uintptr) { | |||
| 743 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 744 | - | return | |||
| 745 | - | } | |||
| 746 | - | C.gtk_widget_set_size_request((*C.GtkWidget)(unsafe.Pointer(widget)), C.int(-1), C.int(-1)) | |||
| 747 | - | } | |||
| 748 | - | ||||
| 749 | - | // WidgetShow makes the widget visible. | |||
| 750 | - | func WidgetShow(widget uintptr) { | |||
| 751 | - | if widget == 0 { | |||
| 752 | - | return | |||
| 753 | - | } | |||
| 754 | - | log.Printf("[workspace] WidgetShow widget=%#x", widget) | |||
| 755 | - | C.gtk_widget_set_visible((*C.GtkWidget)(unsafe.Pointer(widget)), C.gboolean(1)) | |||
| 756 | - | } | |||
| 757 | - | ||||
| 758 | - | // WidgetGrabFocus focuses the widget if possible. | |||
| 759 | - | func WidgetGrabFocus(widget uintptr) { | |||
| 760 | - | if widget == 0 { | |||
| 761 | - | return | |||
| 762 | - | } | |||
| 763 | - | if !widgetIsValid(widget) { | |||
| 764 | - | log.Printf("[workspace] WidgetGrabFocus skipped invalid widget=%#x", widget) | |||
| 765 | - | return | |||
| 766 | - | } | |||
| 767 | - | // Reduced logging: focus grab logged only in consolidated focus operation | |||
| 768 | - | C.gtk_widget_grab_focus((*C.GtkWidget)(unsafe.Pointer(widget))) | |||
| 769 | - | } | |||
| 770 | - | ||||
| 771 | - | // WidgetSetFocusChild sets or clears the focus child of a widget. | |||
| 772 | - | // Pass 0 as child to clear the focus child (prevents GTK focus chain warnings during reparenting). | |||
| 773 | - | func WidgetSetFocusChild(widget uintptr, child uintptr) { | |||
| 774 | - | if widget == 0 { | |||
| 775 | - | return | |||
| 776 | - | } | |||
| 777 | - | if !widgetIsValid(widget) { | |||
| 778 | - | log.Printf("[workspace] WidgetSetFocusChild skipped invalid widget=%#x", widget) | |||
| 779 | - | return | |||
| 780 | - | } | |||
| 781 | - | var childPtr *C.GtkWidget | |||
| 782 | - | if child != 0 { | |||
| 783 | - | if !widgetIsValid(child) { | |||
| 784 | - | log.Printf("[workspace] WidgetSetFocusChild skipped invalid child=%#x", child) | |||
| 785 | - | return | |||
| 786 | - | } | |||
| 787 | - | childPtr = (*C.GtkWidget)(unsafe.Pointer(child)) | |||
| 788 | - | } | |||
| 789 | - | C.gtk_widget_set_focus_child((*C.GtkWidget)(unsafe.Pointer(widget)), childPtr) | |||
| 790 | - | log.Printf("[workspace] WidgetSetFocusChild widget=%#x child=%#x", widget, child) | |||
| 791 | - | } | |||
| 792 | - | ||||
| 793 | - | // WidgetRef increments the reference count to keep the widget alive during reparenting. | |||
| 794 | - | func WidgetRef(widget uintptr) bool { | |||
| 795 | - | if widget == 0 { | |||
| 796 | - | return false | |||
| 797 | - | } | |||
| 798 | - | if !widgetIsValid(widget) { | |||
| 799 | - | log.Printf("[workspace] WidgetRef skipped invalid widget=%#x", widget) | |||
| 800 | - | return false | |||
| 801 | - | } | |||
| 802 | - | before := widgetRefCount(widget) | |||
| 803 | - | log.Printf("[workspace] WidgetRef widget=%#x ref_before=%d", widget, before) | |||
| 804 | - | C.g_object_ref(C.gpointer(unsafe.Pointer(widget))) | |||
| 805 | - | after := widgetRefCount(widget) | |||
| 806 | - | log.Printf("[workspace] WidgetRef widget=%#x ref_after=%d", widget, after) | |||
| 807 | - | return true | |||
| 808 | - | } | |||
| 809 | - | ||||
| 810 | - | // WidgetUnref releases a previously held widget reference. | |||
| 811 | - | func WidgetUnref(widget uintptr) { | |||
| 812 | - | if widget == 0 { | |||
| 813 | - | return | |||
| 814 | - | } | |||
| 815 | - | if !widgetIsValid(widget) { | |||
| 816 | - | log.Printf("[workspace] WidgetUnref skipped invalid widget=%#x", widget) | |||
| 817 | - | return | |||
| 818 | - | } | |||
| 819 | - | before := widgetRefCount(widget) | |||
| 820 | - | log.Printf("[workspace] WidgetUnref widget=%#x ref_before=%d", widget, before) | |||
| 821 | - | C.g_object_unref(C.gpointer(unsafe.Pointer(widget))) | |||
| 822 | - | if widgetIsValid(widget) { | |||
| 823 | - | after := widgetRefCount(widget) | |||
| 824 | - | log.Printf("[workspace] WidgetUnref widget=%#x ref_after=%d", widget, after) | |||
| 825 | - | } else { | |||
| 826 | - | log.Printf("[workspace] WidgetUnref widget=%#x now invalid", widget) | |||
| 827 | - | } | |||
| 828 | - | } | |||
| 829 | - | ||||
| 830 | - | // WidgetQueueAllocate queues an allocation on the widget. | |||
| 831 | - | func WidgetQueueAllocate(widget uintptr) { | |||
| 832 | - | if widget == 0 { | |||
| 833 | - | return | |||
| 834 | - | } | |||
| 835 | - | log.Printf("[workspace] WidgetQueueAllocate widget=%#x", widget) | |||
| 836 | - | C.gtk_widget_queue_allocate((*C.GtkWidget)(unsafe.Pointer(widget))) | |||
| 837 | - | } | |||
| 838 | - | ||||
| 839 | - | // WidgetQueueResize forces GTK to recalculate the widget's layout and size allocation. | |||
| 840 | - | // This is useful when a widget's size requirements have changed (e.g., after adding children). | |||
| 841 | - | func WidgetQueueResize(widget uintptr) { | |||
| 842 | - | if widget == 0 { | |||
| 843 | - | return | |||
| 844 | - | } | |||
| 845 | - | if !widgetIsValid(widget) { | |||
| 846 | - | log.Printf("[workspace] WidgetQueueResize skipped invalid widget=%#x", widget) | |||
| 847 | - | return | |||
| 848 | - | } | |||
| 849 | - | log.Printf("[workspace] WidgetQueueResize widget=%#x", widget) | |||
| 850 | - | C.gtk_widget_queue_resize((*C.GtkWidget)(unsafe.Pointer(widget))) | |||
| 851 | - | } | |||
| 852 | - | ||||
| 853 | - | // WidgetRealizeInContainer ensures a widget is properly realized within a container | |||
| 854 | - | func WidgetRealizeInContainer(widget uintptr) { | |||
| 855 | - | if widget == 0 { | |||
| 856 | - | return | |||
| 857 | - | } | |||
| 858 | - | // Reduced logging: widget realization logged only in consolidated focus operation | |||
| 859 | - | C.ensure_widget_realized((*C.GtkWidget)(unsafe.Pointer(widget))) | |||
| 860 | - | } | |||
| 861 | - | ||||
| 862 | - | // WidgetAddHoverHandler registers a hover callback for the given widget and | |||
| 863 | - | // returns a token that can be used to detach it later. | |||
| 864 | - | func WidgetAddHoverHandler(widget uintptr, fn func()) uintptr { | |||
| 865 | - | if widget == 0 || fn == nil || !widgetIsValid(widget) { | |||
| 866 | - | return 0 | |||
| 867 | - | } | |||
| 868 | - | hoverMu.Lock() | |||
| 869 | - | token := nextHoverID | |||
| 870 | - | nextHoverID++ | |||
| 871 | - | hoverCallbacks[token] = fn | |||
| 872 | - | hoverMu.Unlock() | |||
| 873 | - | ||||
| 874 | - | controller := C.widget_add_hover_controller((*C.GtkWidget)(unsafe.Pointer(widget)), C.uintptr_t(token)) | |||
| 875 | - | if controller == nil { | |||
| 876 | - | hoverMu.Lock() | |||
| 877 | - | delete(hoverCallbacks, token) | |||
| 878 | - | hoverMu.Unlock() | |||
| 879 | - | return 0 | |||
| 880 | - | } | |||
| 881 | - | ||||
| 882 | - | hoverMu.Lock() | |||
| 883 | - | hoverControllers[token] = uintptr(unsafe.Pointer(controller)) | |||
| 884 | - | hoverMu.Unlock() | |||
| 885 | - | return token | |||
| 886 | - | } | |||
| 887 | - | ||||
| 888 | - | // WidgetRemoveHoverHandler removes a previously registered hover callback. | |||
| 889 | - | func WidgetRemoveHoverHandler(widget uintptr, token uintptr) { | |||
| 890 | - | if token == 0 { | |||
| 891 | - | return | |||
| 892 | - | } | |||
| 893 | - | ||||
| 894 | - | hoverMu.Lock() | |||
| 895 | - | controller := hoverControllers[token] | |||
| 896 | - | delete(hoverCallbacks, token) | |||
| 897 | - | delete(hoverControllers, token) | |||
| 898 | - | hoverMu.Unlock() | |||
| 899 | - | ||||
| 900 | - | if controller == 0 { | |||
| 901 | - | return | |||
| 902 | - | } | |||
| 903 | - | ||||
| 904 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 905 | - | return | |||
| 906 | - | } | |||
| 907 | - | ||||
| 908 | - | C.widget_remove_controller((*C.GtkWidget)(unsafe.Pointer(widget)), (*C.GtkEventController)(unsafe.Pointer(controller))) | |||
| 909 | - | } | |||
| 910 | - | ||||
| 911 | - | // WidgetAttachClickHandler attaches a click handler to any widget (for title bars) | |||
| 912 | - | func WidgetAttachClickHandler(widget uintptr, fn func()) uintptr { | |||
| 913 | - | if widget == 0 || fn == nil || !widgetIsValid(widget) { | |||
| 914 | - | return 0 | |||
| 915 | - | } | |||
| 916 | - | titleBarMu.Lock() | |||
| 917 | - | token := nextTitleBarID | |||
| 918 | - | nextTitleBarID++ | |||
| 919 | - | titleBarCallbacks[token] = fn | |||
| 920 | - | titleBarMu.Unlock() | |||
| 921 | - | ||||
| 922 | - | C.widget_attach_click_handler((*C.GtkWidget)(unsafe.Pointer(widget)), C.uintptr_t(token)) | |||
| 923 | - | ||||
| 924 | - | return token | |||
| 925 | - | } | |||
| 926 | - | ||||
| 927 | - | // WidgetGetBounds returns the absolute bounds of the widget relative to the root window. | |||
| 928 | - | func WidgetGetBounds(widget uintptr) (WidgetBounds, bool) { | |||
| 929 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 930 | - | return WidgetBounds{}, false | |||
| 931 | - | } | |||
| 932 | - | ||||
| 933 | - | var x, y, width, height C.double | |||
| 934 | - | if C.widget_get_bounds((*C.GtkWidget)(unsafe.Pointer(widget)), (*C.double)(&x), (*C.double)(&y), (*C.double)(&width), (*C.double)(&height)) == 0 { | |||
| 935 | - | return WidgetBounds{}, false | |||
| 936 | - | } | |||
| 937 | - | ||||
| 938 | - | return WidgetBounds{ | |||
| 939 | - | X: float64(x), | |||
| 940 | - | Y: float64(y), | |||
| 941 | - | Width: float64(width), | |||
| 942 | - | Height: float64(height), | |||
| 943 | - | }, true | |||
| 944 | - | } | |||
| 945 | - | ||||
| 946 | - | // Global storage for idle callbacks | |||
| 947 | - | var ( | |||
| 948 | - | idleCallbacks = make(map[uintptr]func() bool) | |||
| 949 | - | nextIdleID uintptr = 1 | |||
| 950 | - | ) | |||
| 951 | - | ||||
| 952 | - | // IdleAdd schedules a function to be called when the main loop is idle. | |||
| 953 | - | func IdleAdd(fn func() bool) uintptr { | |||
| 954 | - | if fn == nil { | |||
| 955 | - | return 0 | |||
| 956 | - | } | |||
| 957 | - | id := nextIdleID | |||
| 958 | - | nextIdleID++ | |||
| 959 | - | idleCallbacks[id] = fn | |||
| 960 | - | if C.add_idle_callback(C.uintptr_t(id)) == 0 { | |||
| 961 | - | delete(idleCallbacks, id) | |||
| 962 | - | return 0 | |||
| 963 | - | } | |||
| 964 | - | return id | |||
| 965 | - | } | |||
| 966 | - | ||||
| 967 | - | // IdleRemove cancels a previously scheduled idle callback. | |||
| 968 | - | func IdleRemove(handle uintptr) { | |||
| 969 | - | if handle == 0 { | |||
| 970 | - | return | |||
| 971 | - | } | |||
| 972 | - | C.remove_idle_callback(C.uintptr_t(handle)) | |||
| 973 | - | delete(idleCallbacks, handle) | |||
| 974 | - | } | |||
| 975 | - | ||||
| 976 | - | // IterateMainLoop processes a single GTK main loop iteration and reports if work was handled. | |||
| 977 | - | func IterateMainLoop() bool { | |||
| 978 | - | return C.iterate_main_loop() == 1 | |||
| 979 | - | } | |||
| 980 | - | ||||
| 981 | - | //export goIdleCallback | |||
| 982 | - | func goIdleCallback(handle uintptr) C.gboolean { | |||
| 983 | - | if fn, ok := idleCallbacks[handle]; ok { | |||
| 984 | - | delete(idleCallbacks, handle) // Clean up after calling | |||
| 985 | - | if fn() { | |||
| 986 | - | return C.gboolean(1) // G_SOURCE_CONTINUE | |||
| 987 | - | } | |||
| 988 | - | } | |||
| 989 | - | return C.gboolean(0) // G_SOURCE_REMOVE | |||
| 990 | - | } | |||
| 991 | - | ||||
| 992 | - | //export goHoverCallback | |||
| 993 | - | func goHoverCallback(handle C.uintptr_t) { | |||
| 994 | - | token := uintptr(handle) | |||
| 995 | - | hoverMu.Lock() | |||
| 996 | - | fn := hoverCallbacks[token] | |||
| 997 | - | hoverMu.Unlock() | |||
| 998 | - | if fn != nil { | |||
| 999 | - | fn() | |||
| 1000 | - | } | |||
| 1001 | - | } | |||
| 1002 | - | ||||
| 1003 | - | //export goTitleBarClickCallback | |||
| 1004 | - | func goTitleBarClickCallback(handle C.uintptr_t) { | |||
| 1005 | - | token := uintptr(handle) | |||
| 1006 | - | titleBarMu.Lock() | |||
| 1007 | - | fn := titleBarCallbacks[token] | |||
| 1008 | - | titleBarMu.Unlock() | |||
| 1009 | - | if fn != nil { | |||
| 1010 | - | fn() | |||
| 1011 | - | } | |||
| 1012 | - | } | |||
| 1013 | - | ||||
| 1014 | - | // GtkBox functions for stacked panes | |||
| 1015 | - | ||||
| 1016 | - | // NewBox creates a new GtkBox widget with the specified orientation and spacing. | |||
| 1017 | - | func NewBox(orientation Orientation, spacing int) uintptr { | |||
| 1018 | - | box := C.box_new(C.GtkOrientation(orientation), C.int(spacing)) | |||
| 1019 | - | return uintptr(unsafe.Pointer(box)) | |||
| 1020 | - | } | |||
| 1021 | - | ||||
| 1022 | - | // BoxAppend adds a child widget to the end of a GtkBox. | |||
| 1023 | - | func BoxAppend(box uintptr, child uintptr) { | |||
| 1024 | - | if box == 0 || child == 0 { | |||
| 1025 | - | return | |||
| 1026 | - | } | |||
| 1027 | - | log.Printf("[workspace] BoxAppend box=%#x child=%#x", box, child) | |||
| 1028 | - | C.box_append((*C.GtkWidget)(unsafe.Pointer(box)), (*C.GtkWidget)(unsafe.Pointer(child))) | |||
| 1029 | - | } | |||
| 1030 | - | ||||
| 1031 | - | // BoxPrepend adds a child widget to the beginning of a GtkBox. | |||
| 1032 | - | func BoxPrepend(box uintptr, child uintptr) { | |||
| 1033 | - | if box == 0 || child == 0 { | |||
| 1034 | - | return | |||
| 1035 | - | } | |||
| 1036 | - | log.Printf("[workspace] BoxPrepend box=%#x child=%#x", box, child) | |||
| 1037 | - | C.box_prepend((*C.GtkWidget)(unsafe.Pointer(box)), (*C.GtkWidget)(unsafe.Pointer(child))) | |||
| 1038 | - | } | |||
| 1039 | - | ||||
| 1040 | - | // BoxRemove removes a child widget from a GtkBox. | |||
| 1041 | - | func BoxRemove(box uintptr, child uintptr) { | |||
| 1042 | - | if box == 0 || child == 0 { | |||
| 1043 | - | return | |||
| 1044 | - | } | |||
| 1045 | - | log.Printf("[workspace] BoxRemove box=%#x child=%#x", box, child) | |||
| 1046 | - | C.box_remove((*C.GtkWidget)(unsafe.Pointer(box)), (*C.GtkWidget)(unsafe.Pointer(child))) | |||
| 1047 | - | } | |||
| 1048 | - | ||||
| 1049 | - | // BoxInsertChildAfter inserts a child widget after a sibling in a GtkBox. | |||
| 1050 | - | func BoxInsertChildAfter(box uintptr, child uintptr, sibling uintptr) { | |||
| 1051 | - | if box == 0 || child == 0 { | |||
| 1052 | - | return | |||
| 1053 | - | } | |||
| 1054 | - | log.Printf("[workspace] BoxInsertChildAfter box=%#x child=%#x sibling=%#x", box, child, sibling) | |||
| 1055 | - | C.box_insert_child_after((*C.GtkWidget)(unsafe.Pointer(box)), (*C.GtkWidget)(unsafe.Pointer(child)), (*C.GtkWidget)(unsafe.Pointer(sibling))) | |||
| 1056 | - | } | |||
| 1057 | - | ||||
| 1058 | - | // Widget visibility functions for stacked panes | |||
| 1059 | - | ||||
| 1060 | - | // WidgetSetVisible sets the visibility state of a widget. | |||
| 1061 | - | func WidgetSetVisible(widget uintptr, visible bool) { | |||
| 1062 | - | if widget == 0 { | |||
| 1063 | - | return | |||
| 1064 | - | } | |||
| 1065 | - | log.Printf("[workspace] WidgetSetVisible widget=%#x visible=%v", widget, visible) | |||
| 1066 | - | C.widget_set_visible((*C.GtkWidget)(unsafe.Pointer(widget)), goBool(visible)) | |||
| 1067 | - | } | |||
| 1068 | - | ||||
| 1069 | - | // WidgetGetVisible returns the visibility state of a widget. | |||
| 1070 | - | func WidgetGetVisible(widget uintptr) bool { | |||
| 1071 | - | if widget == 0 { | |||
| 1072 | - | return false | |||
| 1073 | - | } | |||
| 1074 | - | return C.widget_get_visible((*C.GtkWidget)(unsafe.Pointer(widget))) != 0 | |||
| 1075 | - | } | |||
| 1076 | - | ||||
| 1077 | - | // WidgetHide hides a widget. | |||
| 1078 | - | func WidgetHide(widget uintptr) { | |||
| 1079 | - | if widget == 0 { | |||
| 1080 | - | return | |||
| 1081 | - | } | |||
| 1082 | - | log.Printf("[workspace] WidgetHide widget=%#x", widget) | |||
| 1083 | - | C.widget_hide((*C.GtkWidget)(unsafe.Pointer(widget))) | |||
| 1084 | - | } | |||
| 1085 | - | ||||
| 1086 | - | // Label functions for title bars | |||
| 1087 | - | ||||
| 1088 | - | // NewLabel creates a new GtkLabel widget with the specified text. | |||
| 1089 | - | func NewLabel(text string) uintptr { | |||
| 1090 | - | cstr := C.CString(text) | |||
| 1091 | - | defer C.free(unsafe.Pointer(cstr)) | |||
| 1092 | - | label := C.label_new(cstr) | |||
| 1093 | - | return uintptr(unsafe.Pointer(label)) | |||
| 1094 | - | } | |||
| 1095 | - | ||||
| 1096 | - | // LabelSetText sets the text of a GtkLabel. | |||
| 1097 | - | func LabelSetText(label uintptr, text string) { | |||
| 1098 | - | if label == 0 { | |||
| 1099 | - | return | |||
| 1100 | - | } | |||
| 1101 | - | cstr := C.CString(text) | |||
| 1102 | - | defer C.free(unsafe.Pointer(cstr)) | |||
| 1103 | - | C.label_set_text((*C.GtkWidget)(unsafe.Pointer(label)), cstr) | |||
| 1104 | - | } | |||
| 1105 | - | ||||
| 1106 | - | // LabelGetText returns the text of a GtkLabel. | |||
| 1107 | - | func LabelGetText(label uintptr) string { | |||
| 1108 | - | if label == 0 { | |||
| 1109 | - | return "" | |||
| 1110 | - | } | |||
| 1111 | - | cstr := C.label_get_text((*C.GtkWidget)(unsafe.Pointer(label))) | |||
| 1112 | - | if cstr == nil { | |||
| 1113 | - | return "" | |||
| 1114 | - | } | |||
| 1115 | - | return C.GoString(cstr) | |||
| 1116 | - | } | |||
| 1117 | - | ||||
| 1118 | - | // EllipsizeMode represents PangoEllipsizeMode values. | |||
| 1119 | - | type EllipsizeMode int | |||
| 1120 | - | ||||
| 1121 | - | const ( | |||
| 1122 | - | EllipsizeNone EllipsizeMode = 0 // PANGO_ELLIPSIZE_NONE | |||
| 1123 | - | EllipsizeStart EllipsizeMode = 1 // PANGO_ELLIPSIZE_START | |||
| 1124 | - | EllipsizeMiddle EllipsizeMode = 2 // PANGO_ELLIPSIZE_MIDDLE | |||
| 1125 | - | EllipsizeEnd EllipsizeMode = 3 // PANGO_ELLIPSIZE_END | |||
| 1126 | - | ) | |||
| 1127 | - | ||||
| 1128 | - | // LabelSetEllipsize sets the ellipsization mode for a GtkLabel. | |||
| 1129 | - | func LabelSetEllipsize(label uintptr, mode EllipsizeMode) { | |||
| 1130 | - | if label == 0 { | |||
| 1131 | - | return | |||
| 1132 | - | } | |||
| 1133 | - | C.label_set_ellipsize((*C.GtkWidget)(unsafe.Pointer(label)), C.int(mode)) | |||
| 1134 | - | } | |||
| 1135 | - | ||||
| 1136 | - | // LabelSetMaxWidthChars sets the maximum width in characters for a GtkLabel. | |||
| 1137 | - | func LabelSetMaxWidthChars(label uintptr, nChars int) { | |||
| 1138 | - | if label == 0 { | |||
| 1139 | - | return | |||
| 1140 | - | } | |||
| 1141 | - | C.label_set_max_width_chars((*C.GtkWidget)(unsafe.Pointer(label)), C.int(nChars)) | |||
| 1142 | - | } | |||
| 1143 | - | ||||
| 1144 | - | // WidgetWaitForDraw is deprecated - GTK4 handles widget operations automatically | |||
| 1145 | - | // This function is kept for compatibility but does nothing in production | |||
| 1146 | - | func WidgetWaitForDraw(widget uintptr) { | |||
| 1147 | - | // GTK4 documentation states: never force a redraw | |||
| 1148 | - | // Widget operations are handled automatically by the GTK4 main loop | |||
| 1149 | - | // This function is a no-op in production code | |||
| 1150 | - | } | |||
| 1151 | - | ||||
| 1152 | - | // WidgetQueueDraw safely queues a redraw operation (GTK4 recommended approach) | |||
| 1153 | - | func WidgetQueueDraw(widget uintptr) { | |||
| 1154 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 1155 | - | return | |||
| 1156 | - | } | |||
| 1157 | - | C.gtk_widget_queue_draw((*C.GtkWidget)(unsafe.Pointer(widget))) | |||
| 1158 | - | } | |||
| 1159 | - | ||||
| 1160 | - | // WidgetHasCSSClass checks if a widget has a specific CSS class | |||
| 1161 | - | func WidgetHasCSSClass(widget uintptr, class string) bool { | |||
| 1162 | - | if widget == 0 || class == "" || !widgetIsValid(widget) { | |||
| 1163 | - | return false | |||
| 1164 | - | } | |||
| 1165 | - | cstr := C.CString(class) | |||
| 1166 | - | defer C.free(unsafe.Pointer(cstr)) | |||
| 1167 | - | result := C.gtk_widget_has_css_class((*C.GtkWidget)(unsafe.Pointer(widget)), cstr) | |||
| 1168 | - | return result != 0 | |||
| 1169 | - | } | |||
| 1170 | - | ||||
| 1171 | - | // Widget margin functions for creating visual borders | |||
| 1172 | - | ||||
| 1173 | - | // WidgetSetMargin sets all margins (top, right, bottom, left) to the same value | |||
| 1174 | - | func WidgetSetMargin(widget uintptr, margin int) { | |||
| 1175 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 1176 | - | return | |||
| 1177 | - | } | |||
| 1178 | - | w := (*C.GtkWidget)(unsafe.Pointer(widget)) | |||
| 1179 | - | C.gtk_widget_set_margin_top(w, C.int(margin)) | |||
| 1180 | - | C.gtk_widget_set_margin_bottom(w, C.int(margin)) | |||
| 1181 | - | C.gtk_widget_set_margin_start(w, C.int(margin)) | |||
| 1182 | - | C.gtk_widget_set_margin_end(w, C.int(margin)) | |||
| 1183 | - | } | |||
| 1184 | - | ||||
| 1185 | - | // WidgetSetMarginTop sets the top margin | |||
| 1186 | - | func WidgetSetMarginTop(widget uintptr, margin int) { | |||
| 1187 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 1188 | - | return | |||
| 1189 | - | } | |||
| 1190 | - | C.gtk_widget_set_margin_top((*C.GtkWidget)(unsafe.Pointer(widget)), C.int(margin)) | |||
| 1191 | - | } | |||
| 1192 | - | ||||
| 1193 | - | // WidgetSetMarginBottom sets the bottom margin | |||
| 1194 | - | func WidgetSetMarginBottom(widget uintptr, margin int) { | |||
| 1195 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 1196 | - | return | |||
| 1197 | - | } | |||
| 1198 | - | C.gtk_widget_set_margin_bottom((*C.GtkWidget)(unsafe.Pointer(widget)), C.int(margin)) | |||
| 1199 | - | } | |||
| 1200 | - | ||||
| 1201 | - | // WidgetSetMarginStart sets the start (left in LTR) margin | |||
| 1202 | - | func WidgetSetMarginStart(widget uintptr, margin int) { | |||
| 1203 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 1204 | - | return | |||
| 1205 | - | } | |||
| 1206 | - | C.gtk_widget_set_margin_start((*C.GtkWidget)(unsafe.Pointer(widget)), C.int(margin)) | |||
| 1207 | - | } | |||
| 1208 | - | ||||
| 1209 | - | // WidgetSetMarginEnd sets the end (right in LTR) margin | |||
| 1210 | - | func WidgetSetMarginEnd(widget uintptr, margin int) { | |||
| 1211 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 1212 | - | return | |||
| 1213 | - | } | |||
| 1214 | - | C.gtk_widget_set_margin_end((*C.GtkWidget)(unsafe.Pointer(widget)), C.int(margin)) | |||
| 1215 | - | } | |||
| 1216 | - | ||||
| 1217 | - | // GTK4 Focus Controller functions for focus state machine | |||
| 1218 | - | ||||
| 1219 | - | // WidgetAddFocusController registers focus callbacks for the given widget and | |||
| 1220 | - | // returns a token that can be used to detach it later. | |||
| 1221 | - | func WidgetAddFocusController(widget uintptr, onEnter, onLeave func()) uintptr { | |||
| 1222 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 1223 | - | return 0 | |||
| 1224 | - | } | |||
| 1225 | - | ||||
| 1226 | - | focusMu.Lock() | |||
| 1227 | - | token := nextFocusID | |||
| 1228 | - | nextFocusID++ | |||
| 1229 | - | ||||
| 1230 | - | callbacks := FocusCallbacks{ | |||
| 1231 | - | OnEnter: onEnter, | |||
| 1232 | - | OnLeave: onLeave, | |||
| 1233 | - | } | |||
| 1234 | - | focusCallbacks[token] = callbacks | |||
| 1235 | - | focusMu.Unlock() | |||
| 1236 | - | ||||
| 1237 | - | controller := C.widget_add_focus_controller((*C.GtkWidget)(unsafe.Pointer(widget)), C.uintptr_t(token)) | |||
| 1238 | - | if controller == nil { | |||
| 1239 | - | focusMu.Lock() | |||
| 1240 | - | delete(focusCallbacks, token) | |||
| 1241 | - | focusMu.Unlock() | |||
| 1242 | - | return 0 | |||
| 1243 | - | } | |||
| 1244 | - | ||||
| 1245 | - | focusMu.Lock() | |||
| 1246 | - | focusControllers[token] = uintptr(unsafe.Pointer(controller)) | |||
| 1247 | - | focusMu.Unlock() | |||
| 1248 | - | return token | |||
| 1249 | - | } | |||
| 1250 | - | ||||
| 1251 | - | // WidgetRemoveFocusController removes a previously registered focus controller. | |||
| 1252 | - | func WidgetRemoveFocusController(widget uintptr, token uintptr) { | |||
| 1253 | - | if token == 0 { | |||
| 1254 | - | return | |||
| 1255 | - | } | |||
| 1256 | - | ||||
| 1257 | - | focusMu.Lock() | |||
| 1258 | - | controller := focusControllers[token] | |||
| 1259 | - | delete(focusCallbacks, token) | |||
| 1260 | - | delete(focusControllers, token) | |||
| 1261 | - | focusMu.Unlock() | |||
| 1262 | - | ||||
| 1263 | - | if controller == 0 { | |||
| 1264 | - | return | |||
| 1265 | - | } | |||
| 1266 | - | ||||
| 1267 | - | if widget == 0 || !widgetIsValid(widget) { | |||
| 1268 | - | return | |||
| 1269 | - | } | |||
| 1270 | - | ||||
| 1271 | - | C.widget_remove_focus_controller((*C.GtkWidget)(unsafe.Pointer(widget)), (*C.GtkEventController)(unsafe.Pointer(controller))) | |||
| 1272 | - | } | |||
| 1273 | - | ||||
| 1274 | - | //export goFocusEnterCallback | |||
| 1275 | - | func goFocusEnterCallback(handle C.uintptr_t) { | |||
| 1276 | - | token := uintptr(handle) | |||
| 1277 | - | focusMu.Lock() | |||
| 1278 | - | callbacks := focusCallbacks[token] | |||
| 1279 | - | focusMu.Unlock() | |||
| 1280 | - | ||||
| 1281 | - | if callbacks.OnEnter != nil { | |||
| 1282 | - | callbacks.OnEnter() | |||
| 1283 | - | } | |||
| 1284 | - | } | |||
| 1285 | - | ||||
| 1286 | - | //export goFocusLeaveCallback | |||
| 1287 | - | func goFocusLeaveCallback(handle C.uintptr_t) { | |||
| 1288 | - | token := uintptr(handle) | |||
| 1289 | - | focusMu.Lock() | |||
| 1290 | - | callbacks := focusCallbacks[token] | |||
| 1291 | - | focusMu.Unlock() | |||
| 1292 | - | ||||
| 1293 | - | if callbacks.OnLeave != nil { | |||
| 1294 | - | callbacks.OnLeave() | |||
| 1295 | - | } | |||
| 1296 | - | } | |||
| 1297 | - | ||||
| 1298 | - | // WidgetGetAllocation gets the bounds (position and size) of a widget using modern GTK4 API | |||
| 1299 | - | func WidgetGetAllocation(widget uintptr) WidgetAllocation { | |||
| 1300 | - | var x, y, width, height C.int | |||
| 1301 | - | ||||
| 1302 | - | C.widget_get_allocation_modern( | |||
| 1303 | - | (*C.GtkWidget)(unsafe.Pointer(widget)), | |||
| 1304 | - | &x, &y, &width, &height, | |||
| 1305 | - | ) | |||
| 1306 | - | ||||
| 1307 | - | return WidgetAllocation{ | |||
| 1308 | - | X: int(x), | |||
| 1309 | - | Y: int(y), | |||
| 1310 | - | Width: int(width), | |||
| 1311 | - | Height: int(height), | |||
| 1312 | - | } | |||
| 1313 | - | } | |||
| 1314 | - | ||||
| 1315 | - | // GtkImage functions for favicon display | |||
| 1316 | - | ||||
| 1317 | - | // NewImage creates a new empty GtkImage widget. | |||
| 1318 | - | func NewImage() uintptr { | |||
| 1319 | - | image := C.image_new() | |||
| 1320 | - | return uintptr(unsafe.Pointer(image)) | |||
| 1321 | - | } | |||
| 1322 | - | ||||
| 1323 | - | // ImageNewFromFile creates a new GtkImage widget from a file path. | |||
| 1324 | - | func ImageNewFromFile(filename string) uintptr { | |||
| 1325 | - | if filename == "" { | |||
| 1326 | - | return 0 | |||
| 1327 | - | } | |||
| 1328 | - | cstr := C.CString(filename) | |||
| 1329 | - | defer C.free(unsafe.Pointer(cstr)) | |||
| 1330 | - | image := C.image_new_from_file(cstr) | |||
| 1331 | - | return uintptr(unsafe.Pointer(image)) | |||
| 1332 | - | } | |||
| 1333 | - | ||||
| 1334 | - | // ImageSetFromFile updates an existing GtkImage to display an image from a file. | |||
| 1335 | - | func ImageSetFromFile(image uintptr, filename string) { | |||
| 1336 | - | if image == 0 || filename == "" { | |||
| 1337 | - | return | |||
| 1338 | - | } | |||
| 1339 | - | cstr := C.CString(filename) | |||
| 1340 | - | defer C.free(unsafe.Pointer(cstr)) | |||
| 1341 | - | C.image_set_from_file((*C.GtkWidget)(unsafe.Pointer(image)), cstr) | |||
| 1342 | - | } | |||
| 1343 | - | ||||
| 1344 | - | // ImageSetPixelSize sets the pixel size for the image (used for scaling icons). | |||
| 1345 | - | func ImageSetPixelSize(image uintptr, pixelSize int) { | |||
| 1346 | - | if image == 0 { | |||
| 1347 | - | return | |||
| 1348 | - | } | |||
| 1349 | - | C.image_set_pixel_size((*C.GtkWidget)(unsafe.Pointer(image)), C.int(pixelSize)) | |||
| 1350 | - | } | |||
D pkg/webkit/workspace_widgets_stub.go +0 -605
| @@ -1,605 +0,0 @@ | |||||
| 1 | - | //go:build !webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | import "sync" | |||
| 6 | - | ||||
| 7 | - | // Orientation mirrors GtkOrientation in stub builds. | |||
| 8 | - | type Orientation int | |||
| 9 | - | ||||
| 10 | - | const ( | |||
| 11 | - | OrientationHorizontal Orientation = 0 | |||
| 12 | - | OrientationVertical Orientation = 1 | |||
| 13 | - | ) | |||
| 14 | - | ||||
| 15 | - | // WidgetBounds mirrors the CGO struct for stub builds. | |||
| 16 | - | type WidgetBounds struct { | |||
| 17 | - | X float64 | |||
| 18 | - | Y float64 | |||
| 19 | - | Width float64 | |||
| 20 | - | Height float64 | |||
| 21 | - | } | |||
| 22 | - | ||||
| 23 | - | // WidgetAllocation represents a widget's allocation (position and size) in stub builds | |||
| 24 | - | type WidgetAllocation struct { | |||
| 25 | - | X int | |||
| 26 | - | Y int | |||
| 27 | - | Width int | |||
| 28 | - | Height int | |||
| 29 | - | } | |||
| 30 | - | ||||
| 31 | - | type widgetStub struct { | |||
| 32 | - | startChild uintptr | |||
| 33 | - | endChild uintptr | |||
| 34 | - | bounds WidgetBounds | |||
| 35 | - | hasBounds bool | |||
| 36 | - | hover map[uintptr]func() | |||
| 37 | - | // GTK4 lifecycle simulation | |||
| 38 | - | parent uintptr | |||
| 39 | - | isDestroyed bool | |||
| 40 | - | refCount uint | |||
| 41 | - | widgetType string // Track widget type for IsPaned, etc. | |||
| 42 | - | // GTK focus management simulation | |||
| 43 | - | hasFocus bool | |||
| 44 | - | canFocus bool | |||
| 45 | - | focusedChild uintptr | |||
| 46 | - | } | |||
| 47 | - | ||||
| 48 | - | var ( | |||
| 49 | - | widgetMu sync.Mutex | |||
| 50 | - | widgetState = map[uintptr]*widgetStub{} | |||
| 51 | - | nextWidgetID uintptr = 1 | |||
| 52 | - | nextHoverToken uintptr = 1 | |||
| 53 | - | // GTK focus management simulation | |||
| 54 | - | globalFocusedWidget uintptr | |||
| 55 | - | focusWarningEnabled bool = true | |||
| 56 | - | gtkTestInitOnce sync.Once | |||
| 57 | - | ) | |||
| 58 | - | ||||
| 59 | - | func newWidgetHandle() uintptr { | |||
| 60 | - | widgetMu.Lock() | |||
| 61 | - | defer widgetMu.Unlock() | |||
| 62 | - | id := nextWidgetID | |||
| 63 | - | nextWidgetID++ | |||
| 64 | - | widgetState[id] = &widgetStub{ | |||
| 65 | - | refCount: 1, // GTK widgets start with ref count 1 | |||
| 66 | - | canFocus: true, // Most widgets can receive focus | |||
| 67 | - | } | |||
| 68 | - | return id | |||
| 69 | - | } | |||
| 70 | - | ||||
| 71 | - | // NewTestWidget returns a unique widget handle for tests. | |||
| 72 | - | func NewTestWidget() uintptr { return newWidgetHandle() } | |||
| 73 | - | ||||
| 74 | - | // SetWidgetBoundsForTesting assigns bounds for the widget in stub builds. | |||
| 75 | - | func SetWidgetBoundsForTesting(widget uintptr, bounds WidgetBounds) { | |||
| 76 | - | widgetMu.Lock() | |||
| 77 | - | defer widgetMu.Unlock() | |||
| 78 | - | stub, ok := widgetState[widget] | |||
| 79 | - | if !ok { | |||
| 80 | - | stub = &widgetStub{} | |||
| 81 | - | widgetState[widget] = stub | |||
| 82 | - | } | |||
| 83 | - | stub.bounds = bounds | |||
| 84 | - | stub.hasBounds = true | |||
| 85 | - | } | |||
| 86 | - | ||||
| 87 | - | // ResetWidgetStubsForTesting clears widget stub state for deterministic tests. | |||
| 88 | - | func ResetWidgetStubsForTesting() { | |||
| 89 | - | widgetMu.Lock() | |||
| 90 | - | defer widgetMu.Unlock() | |||
| 91 | - | widgetState = map[uintptr]*widgetStub{} | |||
| 92 | - | nextWidgetID = 1 | |||
| 93 | - | nextHoverToken = 1 | |||
| 94 | - | } | |||
| 95 | - | ||||
| 96 | - | func NewPaned(orientation Orientation) uintptr { | |||
| 97 | - | widgetMu.Lock() | |||
| 98 | - | defer widgetMu.Unlock() | |||
| 99 | - | id := nextWidgetID | |||
| 100 | - | nextWidgetID++ | |||
| 101 | - | widgetState[id] = &widgetStub{ | |||
| 102 | - | refCount: 1, | |||
| 103 | - | canFocus: true, | |||
| 104 | - | widgetType: "paned", // Mark as paned widget | |||
| 105 | - | } | |||
| 106 | - | return id | |||
| 107 | - | } | |||
| 108 | - | ||||
| 109 | - | func PanedSetStartChild(paned uintptr, child uintptr) { | |||
| 110 | - | widgetMu.Lock() | |||
| 111 | - | defer widgetMu.Unlock() | |||
| 112 | - | ||||
| 113 | - | // GTK4 validation: paned must be a valid widget | |||
| 114 | - | if paned == 0 { | |||
| 115 | - | panic("GTK-CRITICAL simulation: gtk_widget_get_parent: assertion 'GTK_IS_WIDGET (widget)' failed - paned is NULL") | |||
| 116 | - | } | |||
| 117 | - | ||||
| 118 | - | stub, ok := widgetState[paned] | |||
| 119 | - | if !ok || stub.isDestroyed { | |||
| 120 | - | panic("GTK-CRITICAL simulation: gtk_widget_get_parent: assertion 'GTK_IS_WIDGET (widget)' failed - paned is invalid") | |||
| 121 | - | } | |||
| 122 | - | ||||
| 123 | - | // GTK4 validation: if child is not 0, it must be a valid widget | |||
| 124 | - | if child != 0 { | |||
| 125 | - | childStub, childExists := widgetState[child] | |||
| 126 | - | if !childExists || childStub.isDestroyed { | |||
| 127 | - | panic("GTK-CRITICAL simulation: gtk_widget_insert_before: assertion 'GTK_IS_WIDGET (widget)' failed - child is invalid") | |||
| 128 | - | } | |||
| 129 | - | } | |||
| 130 | - | ||||
| 131 | - | // GTK4 behavior: setting child to 0 automatically unparents the old child | |||
| 132 | - | if stub.startChild != 0 && child == 0 { | |||
| 133 | - | if oldChild, exists := widgetState[stub.startChild]; exists { | |||
| 134 | - | oldChild.parent = 0 // Automatically unparent | |||
| 135 | - | } | |||
| 136 | - | } | |||
| 137 | - | // Set new child and establish parent relationship | |||
| 138 | - | stub.startChild = child | |||
| 139 | - | if child != 0 { | |||
| 140 | - | if childStub, exists := widgetState[child]; exists { | |||
| 141 | - | // Simulate the exact GTK focus management issue from production | |||
| 142 | - | // When reparenting a widget with focus hierarchy to a new parent, | |||
| 143 | - | // GTK's focus management calls gtk_paned_set_focus_child with (nil) | |||
| 144 | - | if focusWarningEnabled && (childStub.hasFocus || childStub.focusedChild != 0) { | |||
| 145 | - | panic("GTK-WARNING simulation: Error finding last focus widget of GtkPaned, gtk_paned_set_focus_child was called on widget (nil) which is not child") | |||
| 146 | - | } | |||
| 147 | - | childStub.parent = paned | |||
| 148 | - | } | |||
| 149 | - | } | |||
| 150 | - | } | |||
| 151 | - | ||||
| 152 | - | func PanedSetEndChild(paned uintptr, child uintptr) { | |||
| 153 | - | widgetMu.Lock() | |||
| 154 | - | defer widgetMu.Unlock() | |||
| 155 | - | ||||
| 156 | - | // GTK4 validation: paned must be a valid widget | |||
| 157 | - | if paned == 0 { | |||
| 158 | - | panic("GTK-CRITICAL simulation: gtk_widget_get_parent: assertion 'GTK_IS_WIDGET (widget)' failed - paned is NULL") | |||
| 159 | - | } | |||
| 160 | - | ||||
| 161 | - | stub, ok := widgetState[paned] | |||
| 162 | - | if !ok || stub.isDestroyed { | |||
| 163 | - | panic("GTK-CRITICAL simulation: gtk_widget_get_parent: assertion 'GTK_IS_WIDGET (widget)' failed - paned is invalid") | |||
| 164 | - | } | |||
| 165 | - | ||||
| 166 | - | // GTK4 validation: if child is not 0, it must be a valid widget | |||
| 167 | - | if child != 0 { | |||
| 168 | - | childStub, childExists := widgetState[child] | |||
| 169 | - | if !childExists || childStub.isDestroyed { | |||
| 170 | - | panic("GTK-CRITICAL simulation: gtk_widget_insert_before: assertion 'GTK_IS_WIDGET (widget)' failed - child is invalid") | |||
| 171 | - | } | |||
| 172 | - | } | |||
| 173 | - | ||||
| 174 | - | // GTK4 behavior: setting child to 0 automatically unparents the old child | |||
| 175 | - | if stub.endChild != 0 && child == 0 { | |||
| 176 | - | if oldChild, exists := widgetState[stub.endChild]; exists { | |||
| 177 | - | oldChild.parent = 0 // Automatically unparent | |||
| 178 | - | } | |||
| 179 | - | } | |||
| 180 | - | // Set new child and establish parent relationship | |||
| 181 | - | stub.endChild = child | |||
| 182 | - | if child != 0 { | |||
| 183 | - | if childStub, exists := widgetState[child]; exists { | |||
| 184 | - | // Simulate the exact GTK focus management issue from production | |||
| 185 | - | // When reparenting a widget with focus hierarchy to a new parent, | |||
| 186 | - | // GTK's focus management calls gtk_paned_set_focus_child with (nil) | |||
| 187 | - | if focusWarningEnabled && (childStub.hasFocus || childStub.focusedChild != 0) { | |||
| 188 | - | panic("GTK-WARNING simulation: Error finding last focus widget of GtkPaned, gtk_paned_set_focus_child was called on widget (nil) which is not child") | |||
| 189 | - | } | |||
| 190 | - | childStub.parent = paned | |||
| 191 | - | } | |||
| 192 | - | } | |||
| 193 | - | } | |||
| 194 | - | ||||
| 195 | - | func PanedSetResizeStart(paned uintptr, resize bool) {} | |||
| 196 | - | ||||
| 197 | - | func PanedSetResizeEnd(paned uintptr, resize bool) {} | |||
| 198 | - | ||||
| 199 | - | // PanedSetPosition is a no-op in stub builds. | |||
| 200 | - | func PanedSetPosition(paned uintptr, pos int) {} | |||
| 201 | - | ||||
| 202 | - | // PanedGetPosition gets the current position of the divider in a GtkPaned (stub) | |||
| 203 | - | func PanedGetPosition(paned uintptr) int { return 0 } | |||
| 204 | - | ||||
| 205 | - | func WidgetUnparent(widget uintptr) { | |||
| 206 | - | widgetMu.Lock() | |||
| 207 | - | defer widgetMu.Unlock() | |||
| 208 | - | if stub, ok := widgetState[widget]; ok { | |||
| 209 | - | // GTK4 CRITICAL simulation: unparenting widget with no parent is illegal | |||
| 210 | - | if stub.parent == 0 { | |||
| 211 | - | // In real GTK4, this would cause: gtk_widget_get_parent: assertion 'GTK_IS_WIDGET (widget)' failed | |||
| 212 | - | // We'll simulate this by marking the widget as destroyed | |||
| 213 | - | stub.isDestroyed = true | |||
| 214 | - | panic("GTK-CRITICAL simulation: gtk_widget_unparent called on widget with no parent") | |||
| 215 | - | } | |||
| 216 | - | // Remove from parent's child list | |||
| 217 | - | if parentStub, exists := widgetState[stub.parent]; exists { | |||
| 218 | - | if parentStub.startChild == widget { | |||
| 219 | - | parentStub.startChild = 0 | |||
| 220 | - | } | |||
| 221 | - | if parentStub.endChild == widget { | |||
| 222 | - | parentStub.endChild = 0 | |||
| 223 | - | } | |||
| 224 | - | } | |||
| 225 | - | stub.parent = 0 | |||
| 226 | - | } | |||
| 227 | - | } | |||
| 228 | - | ||||
| 229 | - | func WidgetSetHExpand(widget uintptr, expand bool) {} | |||
| 230 | - | ||||
| 231 | - | func WidgetSetVExpand(widget uintptr, expand bool) {} | |||
| 232 | - | ||||
| 233 | - | func WidgetGetParent(widget uintptr) uintptr { | |||
| 234 | - | widgetMu.Lock() | |||
| 235 | - | defer widgetMu.Unlock() | |||
| 236 | - | if stub, ok := widgetState[widget]; ok && !stub.isDestroyed { | |||
| 237 | - | return stub.parent | |||
| 238 | - | } | |||
| 239 | - | return 0 | |||
| 240 | - | } | |||
| 241 | - | ||||
| 242 | - | func WidgetShow(widget uintptr) {} | |||
| 243 | - | ||||
| 244 | - | func WidgetGrabFocus(widget uintptr) { | |||
| 245 | - | widgetMu.Lock() | |||
| 246 | - | defer widgetMu.Unlock() | |||
| 247 | - | ||||
| 248 | - | if widget == 0 { | |||
| 249 | - | return | |||
| 250 | - | } | |||
| 251 | - | ||||
| 252 | - | stub, ok := widgetState[widget] | |||
| 253 | - | if !ok || stub.isDestroyed || !stub.canFocus { | |||
| 254 | - | return | |||
| 255 | - | } | |||
| 256 | - | ||||
| 257 | - | // Clear previous focus | |||
| 258 | - | if globalFocusedWidget != 0 { | |||
| 259 | - | if prevStub, exists := widgetState[globalFocusedWidget]; exists { | |||
| 260 | - | prevStub.hasFocus = false | |||
| 261 | - | } | |||
| 262 | - | } | |||
| 263 | - | ||||
| 264 | - | // Set new focus | |||
| 265 | - | stub.hasFocus = true | |||
| 266 | - | globalFocusedWidget = widget | |||
| 267 | - | ||||
| 268 | - | // Simulate focus in parent hierarchy - each parent should point to its direct focused child | |||
| 269 | - | currentChild := widget | |||
| 270 | - | parent := stub.parent | |||
| 271 | - | for parent != 0 { | |||
| 272 | - | if parentStub, exists := widgetState[parent]; exists { | |||
| 273 | - | parentStub.focusedChild = currentChild // Direct child that contains focus | |||
| 274 | - | currentChild = parent // Move up the hierarchy | |||
| 275 | - | parent = parentStub.parent | |||
| 276 | - | } else { | |||
| 277 | - | break | |||
| 278 | - | } | |||
| 279 | - | } | |||
| 280 | - | } | |||
| 281 | - | ||||
| 282 | - | // WidgetSetFocusChild sets or clears the focus child of a widget. | |||
| 283 | - | // Pass 0 as child to clear the focus child (prevents GTK focus chain warnings during reparenting). | |||
| 284 | - | func WidgetSetFocusChild(widget uintptr, child uintptr) { | |||
| 285 | - | widgetMu.Lock() | |||
| 286 | - | defer widgetMu.Unlock() | |||
| 287 | - | ||||
| 288 | - | if widget == 0 { | |||
| 289 | - | return | |||
| 290 | - | } | |||
| 291 | - | ||||
| 292 | - | stub, ok := widgetState[widget] | |||
| 293 | - | if !ok || stub.isDestroyed { | |||
| 294 | - | return | |||
| 295 | - | } | |||
| 296 | - | ||||
| 297 | - | stub.focusedChild = child | |||
| 298 | - | } | |||
| 299 | - | ||||
| 300 | - | func WidgetRef(widget uintptr) bool { | |||
| 301 | - | widgetMu.Lock() | |||
| 302 | - | defer widgetMu.Unlock() | |||
| 303 | - | _, ok := widgetState[widget] | |||
| 304 | - | return ok | |||
| 305 | - | } | |||
| 306 | - | ||||
| 307 | - | func WidgetUnref(widget uintptr) {} | |||
| 308 | - | ||||
| 309 | - | func WidgetQueueAllocate(widget uintptr) {} | |||
| 310 | - | ||||
| 311 | - | func WidgetRealizeInContainer(widget uintptr) {} | |||
| 312 | - | ||||
| 313 | - | func WidgetSetSizeRequest(widget uintptr, width, height int) {} | |||
| 314 | - | ||||
| 315 | - | func WidgetResetSizeRequest(widget uintptr) {} | |||
| 316 | - | ||||
| 317 | - | func WidgetQueueResize(widget uintptr) {} | |||
| 318 | - | ||||
| 319 | - | func WidgetHookDestroy(widget uintptr) {} | |||
| 320 | - | ||||
| 321 | - | func WidgetIsValid(widget uintptr) bool { | |||
| 322 | - | widgetMu.Lock() | |||
| 323 | - | defer widgetMu.Unlock() | |||
| 324 | - | if widget == 0 { | |||
| 325 | - | return false | |||
| 326 | - | } | |||
| 327 | - | if stub, ok := widgetState[widget]; ok { | |||
| 328 | - | return !stub.isDestroyed | |||
| 329 | - | } | |||
| 330 | - | return false | |||
| 331 | - | } | |||
| 332 | - | ||||
| 333 | - | // IsPaned checks if a widget is a GtkPaned container. | |||
| 334 | - | func IsPaned(widget uintptr) bool { | |||
| 335 | - | widgetMu.Lock() | |||
| 336 | - | defer widgetMu.Unlock() | |||
| 337 | - | if widget == 0 { | |||
| 338 | - | return false | |||
| 339 | - | } | |||
| 340 | - | if stub, ok := widgetState[widget]; ok && !stub.isDestroyed { | |||
| 341 | - | return stub.widgetType == "paned" | |||
| 342 | - | } | |||
| 343 | - | return false | |||
| 344 | - | } | |||
| 345 | - | ||||
| 346 | - | // IsBox checks if a widget is a GtkBox container. | |||
| 347 | - | func IsBox(widget uintptr) bool { | |||
| 348 | - | widgetMu.Lock() | |||
| 349 | - | defer widgetMu.Unlock() | |||
| 350 | - | if widget == 0 { | |||
| 351 | - | return false | |||
| 352 | - | } | |||
| 353 | - | if stub, ok := widgetState[widget]; ok && !stub.isDestroyed { | |||
| 354 | - | return stub.widgetType == "box" | |||
| 355 | - | } | |||
| 356 | - | return false | |||
| 357 | - | } | |||
| 358 | - | ||||
| 359 | - | func WidgetRefCount(widget uintptr) uint { | |||
| 360 | - | if WidgetIsValid(widget) { | |||
| 361 | - | return 1 | |||
| 362 | - | } | |||
| 363 | - | return 0 | |||
| 364 | - | } | |||
| 365 | - | ||||
| 366 | - | func WidgetAddHoverHandler(widget uintptr, fn func()) uintptr { | |||
| 367 | - | if widget == 0 || fn == nil { | |||
| 368 | - | return 0 | |||
| 369 | - | } | |||
| 370 | - | widgetMu.Lock() | |||
| 371 | - | defer widgetMu.Unlock() | |||
| 372 | - | stub, ok := widgetState[widget] | |||
| 373 | - | if !ok { | |||
| 374 | - | stub = &widgetStub{} | |||
| 375 | - | widgetState[widget] = stub | |||
| 376 | - | } | |||
| 377 | - | if stub.hover == nil { | |||
| 378 | - | stub.hover = make(map[uintptr]func()) | |||
| 379 | - | } | |||
| 380 | - | token := nextHoverToken | |||
| 381 | - | nextHoverToken++ | |||
| 382 | - | stub.hover[token] = fn | |||
| 383 | - | return token | |||
| 384 | - | } | |||
| 385 | - | ||||
| 386 | - | func WidgetRemoveHoverHandler(widget uintptr, token uintptr) { | |||
| 387 | - | widgetMu.Lock() | |||
| 388 | - | defer widgetMu.Unlock() | |||
| 389 | - | if stub, ok := widgetState[widget]; ok && stub.hover != nil { | |||
| 390 | - | delete(stub.hover, token) | |||
| 391 | - | } | |||
| 392 | - | } | |||
| 393 | - | ||||
| 394 | - | func WidgetGetBounds(widget uintptr) (WidgetBounds, bool) { | |||
| 395 | - | widgetMu.Lock() | |||
| 396 | - | defer widgetMu.Unlock() | |||
| 397 | - | stub, ok := widgetState[widget] | |||
| 398 | - | if !ok || !stub.hasBounds { | |||
| 399 | - | return WidgetBounds{}, false | |||
| 400 | - | } | |||
| 401 | - | return stub.bounds, true | |||
| 402 | - | } | |||
| 403 | - | ||||
| 404 | - | // WidgetWaitForDraw is a no-op validation stub in this build. | |||
| 405 | - | // It does NOT provide any synchronization or guarantee that widget draw operations are complete. | |||
| 406 | - | // In the stub, it only validates the widget state and does not wait for any operations. | |||
| 407 | - | // In real GTK builds, this would wait for all pending draw operations to complete. | |||
| 408 | - | func WidgetWaitForDraw(widget uintptr) { | |||
| 409 | - | gtkTestInitOnce.Do(func() {}) | |||
| 410 | - | widgetMu.Lock() | |||
| 411 | - | defer widgetMu.Unlock() | |||
| 412 | - | ||||
| 413 | - | // Validate widget is still valid after any recent operations | |||
| 414 | - | if widget != 0 { | |||
| 415 | - | stub, ok := widgetState[widget] | |||
| 416 | - | if !ok || stub.isDestroyed { | |||
| 417 | - | panic("GTK-CRITICAL simulation: gtk_test_widget_wait_for_draw: widget is invalid") | |||
| 418 | - | } | |||
| 419 | - | } | |||
| 420 | - | } | |||
| 421 | - | ||||
| 422 | - | // IdleAdd simulates GTK's idle callback system - DEPRECATED, use WidgetWaitForDraw instead | |||
| 423 | - | func IdleAdd(fn func() bool) uintptr { | |||
| 424 | - | if fn != nil { | |||
| 425 | - | fn() | |||
| 426 | - | } | |||
| 427 | - | return 0 | |||
| 428 | - | } | |||
| 429 | - | ||||
| 430 | - | // IdleRemove cancels a simulated idle callback (no-op in stub builds). | |||
| 431 | - | func IdleRemove(handle uintptr) { | |||
| 432 | - | _ = handle | |||
| 433 | - | } | |||
| 434 | - | ||||
| 435 | - | func AddCSSProvider(css string) {} | |||
| 436 | - | ||||
| 437 | - | func WidgetAddCSSClass(widget uintptr, class string) {} | |||
| 438 | - | ||||
| 439 | - | func WidgetRemoveCSSClass(widget uintptr, class string) {} | |||
| 440 | - | ||||
| 441 | - | func WidgetHasCSSClass(widget uintptr, class string) bool { | |||
| 442 | - | // In stub mode, we don't track CSS classes | |||
| 443 | - | return false | |||
| 444 | - | } | |||
| 445 | - | ||||
| 446 | - | // Widget margin functions for creating visual borders (stub implementations) | |||
| 447 | - | ||||
| 448 | - | func WidgetSetMargin(widget uintptr, margin int) {} | |||
| 449 | - | ||||
| 450 | - | func WidgetSetMarginTop(widget uintptr, margin int) {} | |||
| 451 | - | ||||
| 452 | - | func WidgetSetMarginBottom(widget uintptr, margin int) {} | |||
| 453 | - | ||||
| 454 | - | func WidgetSetMarginStart(widget uintptr, margin int) {} | |||
| 455 | - | ||||
| 456 | - | func WidgetSetMarginEnd(widget uintptr, margin int) {} | |||
| 457 | - | ||||
| 458 | - | func WidgetQueueDraw(widget uintptr) { | |||
| 459 | - | // Stub implementation - no-op | |||
| 460 | - | } | |||
| 461 | - | ||||
| 462 | - | // Focus controller functions for GTK4 EventControllerFocus (stub implementations) | |||
| 463 | - | func WidgetAddFocusController(widget uintptr, onEnter, onLeave func()) uintptr { | |||
| 464 | - | // Stub implementation - return a unique token | |||
| 465 | - | token := nextHoverToken | |||
| 466 | - | nextHoverToken++ | |||
| 467 | - | return token | |||
| 468 | - | } | |||
| 469 | - | ||||
| 470 | - | func WidgetRemoveFocusController(widget uintptr, token uintptr) { | |||
| 471 | - | // Stub implementation - no-op | |||
| 472 | - | } | |||
| 473 | - | ||||
| 474 | - | // SimulateFocusForTesting gives focus to a widget for test scenarios | |||
| 475 | - | func SimulateFocusForTesting(widget uintptr) { | |||
| 476 | - | WidgetGrabFocus(widget) | |||
| 477 | - | } | |||
| 478 | - | ||||
| 479 | - | // GtkBox functions for stacked panes (stub implementations) | |||
| 480 | - | ||||
| 481 | - | func NewBox(orientation Orientation, spacing int) uintptr { | |||
| 482 | - | widgetMu.Lock() | |||
| 483 | - | defer widgetMu.Unlock() | |||
| 484 | - | id := nextWidgetID | |||
| 485 | - | nextWidgetID++ | |||
| 486 | - | widgetState[id] = &widgetStub{ | |||
| 487 | - | refCount: 1, | |||
| 488 | - | canFocus: true, | |||
| 489 | - | widgetType: "box", // Mark as box widget | |||
| 490 | - | } | |||
| 491 | - | return id | |||
| 492 | - | } | |||
| 493 | - | ||||
| 494 | - | func BoxAppend(box uintptr, child uintptr) { | |||
| 495 | - | widgetMu.Lock() | |||
| 496 | - | defer widgetMu.Unlock() | |||
| 497 | - | ||||
| 498 | - | if box == 0 || child == 0 { | |||
| 499 | - | return | |||
| 500 | - | } | |||
| 501 | - | ||||
| 502 | - | boxStub, ok := widgetState[box] | |||
| 503 | - | if !ok || boxStub.isDestroyed { | |||
| 504 | - | panic("GTK-CRITICAL simulation: gtk_box_append: box is invalid") | |||
| 505 | - | } | |||
| 506 | - | ||||
| 507 | - | childStub, ok := widgetState[child] | |||
| 508 | - | if !ok || childStub.isDestroyed { | |||
| 509 | - | panic("GTK-CRITICAL simulation: gtk_box_append: child is invalid") | |||
| 510 | - | } | |||
| 511 | - | ||||
| 512 | - | if childStub.parent != 0 && childStub.parent != box { | |||
| 513 | - | panic("GTK-CRITICAL simulation: gtk_box_append: child already has a different parent") | |||
| 514 | - | } | |||
| 515 | - | childStub.parent = box | |||
| 516 | - | } | |||
| 517 | - | ||||
| 518 | - | func BoxPrepend(box uintptr, child uintptr) { | |||
| 519 | - | BoxAppend(box, child) | |||
| 520 | - | } | |||
| 521 | - | ||||
| 522 | - | func BoxRemove(box uintptr, child uintptr) { | |||
| 523 | - | widgetMu.Lock() | |||
| 524 | - | defer widgetMu.Unlock() | |||
| 525 | - | ||||
| 526 | - | if box == 0 || child == 0 { | |||
| 527 | - | return | |||
| 528 | - | } | |||
| 529 | - | ||||
| 530 | - | childStub, ok := widgetState[child] | |||
| 531 | - | if !ok || childStub.isDestroyed { | |||
| 532 | - | panic("GTK-CRITICAL simulation: gtk_box_remove: child is invalid") | |||
| 533 | - | } | |||
| 534 | - | ||||
| 535 | - | if childStub.parent != box { | |||
| 536 | - | panic("GTK-CRITICAL simulation: gtk_box_remove: child is not parented to the specified box") | |||
| 537 | - | } | |||
| 538 | - | ||||
| 539 | - | childStub.parent = 0 | |||
| 540 | - | } | |||
| 541 | - | ||||
| 542 | - | func BoxInsertChildAfter(box uintptr, child uintptr, sibling uintptr) { | |||
| 543 | - | BoxAppend(box, child) | |||
| 544 | - | } | |||
| 545 | - | ||||
| 546 | - | // Widget visibility functions for stacked panes (stub implementations) | |||
| 547 | - | ||||
| 548 | - | func WidgetSetVisible(widget uintptr, visible bool) {} | |||
| 549 | - | ||||
| 550 | - | func WidgetGetVisible(widget uintptr) bool { return true } | |||
| 551 | - | ||||
| 552 | - | func WidgetHide(widget uintptr) {} | |||
| 553 | - | ||||
| 554 | - | // Label functions for title bars (stub implementations) | |||
| 555 | - | ||||
| 556 | - | func NewLabel(text string) uintptr { | |||
| 557 | - | return newWidgetHandle() | |||
| 558 | - | } | |||
| 559 | - | ||||
| 560 | - | func LabelSetText(label uintptr, text string) {} | |||
| 561 | - | ||||
| 562 | - | func LabelGetText(label uintptr) string { return "" } | |||
| 563 | - | ||||
| 564 | - | // EllipsizeMode represents PangoEllipsizeMode values in stub builds. | |||
| 565 | - | type EllipsizeMode int | |||
| 566 | - | ||||
| 567 | - | const ( | |||
| 568 | - | EllipsizeNone EllipsizeMode = 0 | |||
| 569 | - | EllipsizeStart EllipsizeMode = 1 | |||
| 570 | - | EllipsizeMiddle EllipsizeMode = 2 | |||
| 571 | - | EllipsizeEnd EllipsizeMode = 3 | |||
| 572 | - | ) | |||
| 573 | - | ||||
| 574 | - | func LabelSetEllipsize(label uintptr, mode EllipsizeMode) {} | |||
| 575 | - | ||||
| 576 | - | func LabelSetMaxWidthChars(label uintptr, nChars int) {} | |||
| 577 | - | ||||
| 578 | - | // SetTestContainer is a testing helper to set the container field for WebView in stub builds | |||
| 579 | - | func (w *WebView) SetTestContainer(container uintptr) { | |||
| 580 | - | w.container = container | |||
| 581 | - | } | |||
| 582 | - | ||||
| 583 | - | // WidgetGetAllocation returns a stub allocation for the widget | |||
| 584 | - | func WidgetGetAllocation(widget uintptr) WidgetAllocation { | |||
| 585 | - | widgetMu.Lock() | |||
| 586 | - | defer widgetMu.Unlock() | |||
| 587 | - | ||||
| 588 | - | // Return stub allocation based on widget bounds if available | |||
| 589 | - | if stub, ok := widgetState[widget]; ok && stub.hasBounds { | |||
| 590 | - | return WidgetAllocation{ | |||
| 591 | - | X: int(stub.bounds.X), | |||
| 592 | - | Y: int(stub.bounds.Y), | |||
| 593 | - | Width: int(stub.bounds.Width), | |||
| 594 | - | Height: int(stub.bounds.Height), | |||
| 595 | - | } | |||
| 596 | - | } | |||
| 597 | - | ||||
| 598 | - | // Default stub allocation for testing | |||
| 599 | - | return WidgetAllocation{ | |||
| 600 | - | X: 0, | |||
| 601 | - | Y: 0, | |||
| 602 | - | Width: 400, | |||
| 603 | - | Height: 300, | |||
| 604 | - | } | |||
| 605 | - | } | |||
D pkg/webkit/zoom.go +0 -35
| @@ -1,35 +0,0 @@ | |||||
| 1 | - | //go:build !webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | const ( | |||
| 6 | - | zoomMin = 0.25 | |||
| 7 | - | zoomMax = 5.0 | |||
| 8 | - | ) | |||
| 9 | - | ||||
| 10 | - | // SetZoom sets the current zoom factor for the WebView. | |||
| 11 | - | func (w *WebView) SetZoom(level float64) error { | |||
| 12 | - | if w == nil || w.destroyed { | |||
| 13 | - | return ErrNotImplemented | |||
| 14 | - | } | |||
| 15 | - | if level < zoomMin { | |||
| 16 | - | level = zoomMin | |||
| 17 | - | } | |||
| 18 | - | if level > zoomMax { | |||
| 19 | - | level = zoomMax | |||
| 20 | - | } | |||
| 21 | - | w.zoom = level | |||
| 22 | - | if w.useDomZoom { | |||
| 23 | - | w.SeedDomZoom(level) | |||
| 24 | - | } | |||
| 25 | - | w.dispatchZoomChanged(w.zoom) | |||
| 26 | - | return nil | |||
| 27 | - | } | |||
| 28 | - | ||||
| 29 | - | // GetZoom returns the current zoom factor. | |||
| 30 | - | func (w *WebView) GetZoom() (float64, error) { | |||
| 31 | - | if w == nil || w.destroyed { | |||
| 32 | - | return 1.0, ErrNotImplemented | |||
| 33 | - | } | |||
| 34 | - | return w.zoom, nil | |||
| 35 | - | } | |||
D pkg/webkit/zoom_cgo.go +0 -43
| @@ -1,43 +0,0 @@ | |||||
| 1 | - | //go:build webkit_cgo | |||
| 2 | - | ||||
| 3 | - | package webkit | |||
| 4 | - | ||||
| 5 | - | /* | |||
| 6 | - | #cgo pkg-config: webkitgtk-6.0 gtk4 | |||
| 7 | - | #cgo CFLAGS: -I/usr/include/webkitgtk-6.0 | |||
| 8 | - | #include <webkit/webkit.h> | |||
| 9 | - | */ | |||
| 10 | - | import "C" | |||
| 11 | - | ||||
| 12 | - | import "fmt" | |||
| 13 | - | ||||
| 14 | - | func (w *WebView) SetZoom(level float64) error { | |||
| 15 | - | if w == nil || w.destroyed || w.native == nil || w.native.wv == nil { | |||
| 16 | - | return ErrNotImplemented | |||
| 17 | - | } | |||
| 18 | - | level = clampDomZoom(level) | |||
| 19 | - | w.zoom = level | |||
| 20 | - | if w.useDomZoom { | |||
| 21 | - | w.SeedDomZoom(level) | |||
| 22 | - | script := fmt.Sprintf(`(function(){try{const lvl=%[1]f;window.__dumber_dom_zoom_level=lvl;if(window.__dumber_applyDomZoom){window.__dumber_applyDomZoom(lvl);}else{if(Math.abs(lvl-1.0)<1e-6){document.documentElement.style.zoom='';if(document.body){document.body.style.zoom='';}}else{const value=lvl.toString();document.documentElement.style.zoom=value;if(document.body){document.body.style.zoom=value;}}}}catch(e){console.error('[dumber] DOM zoom error',e);}})();`, level) | |||
| 23 | - | if err := w.InjectScript(script); err != nil { | |||
| 24 | - | C.webkit_web_view_set_zoom_level(w.native.wv, C.gdouble(level)) | |||
| 25 | - | } | |||
| 26 | - | } else { | |||
| 27 | - | C.webkit_web_view_set_zoom_level(w.native.wv, C.gdouble(level)) | |||
| 28 | - | } | |||
| 29 | - | w.dispatchZoomChanged(w.zoom) | |||
| 30 | - | return nil | |||
| 31 | - | } | |||
| 32 | - | ||||
| 33 | - | func (w *WebView) GetZoom() (float64, error) { | |||
| 34 | - | if w == nil || w.destroyed || w.native == nil || w.native.wv == nil { | |||
| 35 | - | return 1.0, ErrNotImplemented | |||
| 36 | - | } | |||
| 37 | - | if w.useDomZoom { | |||
| 38 | - | return w.zoom, nil | |||
| 39 | - | } | |||
| 40 | - | z := float64(C.webkit_web_view_get_zoom_level(w.native.wv)) | |||
| 41 | - | w.zoom = z | |||
| 42 | - | return z, nil | |||
| 43 | - | } | |||