1package cef
2
3import (
4 "context"
5 "strings"
6 "sync"
7 "sync/atomic"
8 "time"
9
10 purecef "github.com/bnema/purego-cef/cef"
11
12 "github.com/bnema/dumber/internal/application/dto"
13 "github.com/bnema/dumber/internal/application/port"
14 downloadutil "github.com/bnema/dumber/internal/domain/download"
15 "github.com/bnema/dumber/internal/logging"
16)
17
18// Console message markers used by injected JavaScript for log filtering.
19const (
20 consoleMarkerVideoDiag = "[VIDEO-DIAG]"
21 consoleMarkerAutoCopy = "[AUTO-COPY]"
22 consoleMarkerScaleProbe = "[SCALE-PROBE]"
23)
24
25// handlerSet implements all CEF handler interfaces and dispatches events to the
26// owning WebView. A single struct is used so that the Client's Get*Handler
27// methods can return the same receiver, avoiding extra allocations.
28type handlerSet struct {
29 wv *WebView
30 fileDialogPresenter fileDialogPresenter
31 renderHandlerOnce sync.Once
32 renderHandler purecef.RenderHandler
33 permissions permissionTracker
34}
35
36// Compile-time interface checks.
37var (
38 _ purecef.Client = (*handlerSet)(nil)
39 _ purecef.DisplayHandler = (*handlerSet)(nil)
40 _ purecef.LoadHandler = (*handlerSet)(nil)
41 _ purecef.LifeSpanHandler = (*handlerSet)(nil)
42 _ purecef.RequestHandler = (*handlerSet)(nil)
43 _ purecef.AudioHandler = (*handlerSet)(nil)
44 _ purecef.ContextMenuHandler = (*handlerSet)(nil)
45 _ purecef.DialogHandler = (*handlerSet)(nil)
46 _ purecef.DownloadHandler = (*handlerSet)(nil)
47 _ purecef.FindHandler = (*handlerSet)(nil)
48 _ purecef.PermissionHandler = (*handlerSet)(nil)
49)
50
51// ===========================================================================
52// Client
53// ===========================================================================
54
55func (h *handlerSet) GetAudioHandler() purecef.AudioHandler {
56 // Always return the audio handler — without it, CEF has no audio output
57 // path and refuses to start media decoding, breaking all video playback.
58 // The handler accepts audio but discards packets (no-op) until a real
59 // audio backend (PipeWire/PulseAudio) is wired up.
60 return h
61}
62func (h *handlerSet) GetCommandHandler() purecef.CommandHandler { return nil }
63func (h *handlerSet) GetContextMenuHandler() purecef.ContextMenuHandler { return h }
64func (h *handlerSet) GetDialogHandler() purecef.DialogHandler { return h }
65func (h *handlerSet) GetDisplayHandler() purecef.DisplayHandler { return h }
66func (h *handlerSet) GetDownloadHandler() purecef.DownloadHandler {
67 if h.downloadHandler() != nil {
68 return h
69 }
70 return nil
71}
72func (h *handlerSet) GetDragHandler() purecef.DragHandler { return nil }
73func (h *handlerSet) GetFindHandler() purecef.FindHandler { return h }
74func (h *handlerSet) GetFocusHandler() purecef.FocusHandler { return nil }
75func (h *handlerSet) GetFrameHandler() purecef.FrameHandler { return nil }
76func (h *handlerSet) GetPermissionHandler() purecef.PermissionHandler { return h }
77func (h *handlerSet) GetJsdialogHandler() purecef.JsdialogHandler { return h }
78func (h *handlerSet) GetKeyboardHandler() purecef.KeyboardHandler { return nil }
79func (h *handlerSet) GetLifeSpanHandler() purecef.LifeSpanHandler { return h }
80func (h *handlerSet) GetLoadHandler() purecef.LoadHandler { return h }
81func (h *handlerSet) GetPrintHandler() purecef.PrintHandler { return nil }
82func (h *handlerSet) GetRenderHandler() purecef.RenderHandler {
83 if h == nil {
84 return nil
85 }
86 h.renderHandlerOnce.Do(func() {
87 h.renderHandler = newDumberRenderHandler(h.wv)
88 })
89 return h.renderHandler
90}
91func (h *handlerSet) GetRequestHandler() purecef.RequestHandler { return h }
92
93func (h *handlerSet) OnProcessMessageReceived(
94 browser purecef.Browser,
95 _ purecef.Frame,
96 _ purecef.ProcessID,
97 message purecef.ProcessMessage,
98) int32 {
99 if h == nil || h.wv == nil || h.wv.engine == nil {
100 return 0
101 }
102 action, payload, ok := decodeRendererBridgeProcessMessage(message)
103 if !ok {
104 return 0
105 }
106
107 log := logging.FromContext(h.wv.ctx)
108 log.Debug().
109 Str("action", action).
110 Int("payload_len", len(payload)).
111 Msg("cef: renderer bridge message received")
112
113 switch action {
114 case rendererBridgeActionExplicitTextCopy:
115 req, err := decodeRendererBridgeExplicitTextCopyPayload([]byte(payload))
116 if err != nil {
117 log.Debug().Str("action", action).Msg("cef: invalid explicit copy payload")
118 return 1
119 }
120 h.wv.engine.handleExplicitClipboardBridgeText(h.wv.id, req.Action, req.Text)
121 case rendererBridgeActionEditableFocusChanged:
122 h.wv.setEditableFocus(payload == "1" || strings.EqualFold(payload, "true"))
123 case rendererBridgeActionFocusSync:
124 h.wv.engine.handleEditableFocusBridge(browser)
125 case rendererBridgeActionPopupOpen:
126 req, err := decodeRendererBridgePopupOpenPayload([]byte(payload))
127 if err != nil {
128 log.Debug().Str("action", action).Msg("cef: invalid popup_open payload")
129 return 1
130 }
131 h.wv.handleSyntheticPopupOpen(req.URL, req.FrameName, req.ProxyID, req.UserGesture, req.NoJavaScriptAccess)
132 case rendererBridgeActionPopupNavigate:
133 req, err := decodeRendererBridgePopupNavigatePayload([]byte(payload))
134 if err != nil {
135 log.Debug().Str("action", action).Msg("cef: invalid popup_navigate payload")
136 return 1
137 }
138 h.wv.handleSyntheticPopupNavigate(req.ProxyID, req.URL)
139 case rendererBridgeActionPopupClose:
140 req, err := decodeRendererBridgePopupClosePayload([]byte(payload))
141 if err != nil {
142 log.Debug().Str("action", action).Msg("cef: invalid popup_close payload")
143 return 1
144 }
145 h.wv.handleSyntheticPopupClose(req.ProxyID)
146 case rendererBridgeActionReady:
147 log.Debug().
148 Str("frame_url", logging.TruncateURL(payload, logging.PermissionLogURLMaxLen)).
149 Msg("cef: renderer bridge ready")
150 default:
151 log.Debug().Str("action", action).Msg("cef: unknown renderer bridge action")
152 }
153 return 1
154}
155
156// ===========================================================================
157// RenderHandler methods live in render_handler_adapter.go. handlerSet keeps
158// Dumber's non-render CEF handlers and returns a delegating render handler from
159// GetRenderHandler.
160// ===========================================================================
161
162// ===========================================================================
163// DisplayHandler (13 methods)
164// ===========================================================================
165
166// OnAddressChange updates the cached URI when the main frame navigates.
167func (h *handlerSet) OnAddressChange(_ purecef.Browser, frame purecef.Frame, url string) {
168 if frame != nil && frame.IsMain() {
169 if h.wv != nil && h.wv.ctx != nil {
170 logging.FromContext(h.wv.ctx).Debug().
171 Str("url", logging.TruncateURL(url, logging.PermissionLogURLMaxLen)).
172 Msg("cef: OnAddressChange")
173 }
174 h.wv.updateURI(url)
175 }
176}
177
178// OnTitleChange updates the cached title.
179func (h *handlerSet) OnTitleChange(_ purecef.Browser, title string) {
180 h.wv.updateTitle(title)
181}
182
183func (h *handlerSet) OnFaviconUrlchange(browser purecef.Browser, iconURLs purecef.StringList) {
184 if h == nil || h.wv == nil {
185 return
186 }
187 h.wv.mu.RLock()
188 pageURL, committedURL, cb, currentBrowser, documentSeq := h.wv.uri, h.wv.committedURL, h.wv.callbacks, h.wv.browser, h.wv.documentSeq
189 h.wv.mu.RUnlock()
190 if cb == nil || cb.OnFaviconURLChanged == nil || browser == nil || currentBrowser == nil ||
191 browser.GetIdentifier() != currentBrowser.GetIdentifier() {
192 return
193 }
194 if committedURL == "" {
195 committedURL = pageURL
196 }
197 candidates := resolveFaviconCandidates(committedURL, decodeCEFStringList(iconURLs))
198 if len(candidates) == 0 {
199 return
200 }
201 h.wv.mu.Lock()
202 if h.wv.documentSeq != documentSeq || h.wv.uri != pageURL {
203 h.wv.mu.Unlock()
204 return
205 }
206 h.wv.faviconEngineDocumentSeq = documentSeq
207 h.wv.mu.Unlock()
208 h.wv.runOnGTK(func() {
209 if !h.faviconCallbackCurrent(cb, browser, documentSeq, pageURL) {
210 return
211 }
212 cb.OnFaviconURLChanged(pageURL, candidates)
213 })
214}
215
216// faviconCallbackCurrent reports whether a queued favicon callback still
217// belongs to the current committed document, callback owner, and browser. The
218// GTK hop outlives the state it was queued for, so callbacks revalidate before
219// handing candidates to the UI.
220func (h *handlerSet) faviconCallbackCurrent(cb *port.WebViewCallbacks, browser purecef.Browser, documentSeq uint64, pageURL string) bool {
221 if h == nil || h.wv == nil || cb == nil {
222 return false
223 }
224 h.wv.mu.RLock()
225 currentBrowser := h.wv.browser
226 current := h.wv.callbacks == cb && h.wv.documentSeq == documentSeq && h.wv.uri == pageURL
227 h.wv.mu.RUnlock()
228 if !current {
229 return false
230 }
231 if browser == nil {
232 // No captured browser identity to compare; the document checks above
233 // still bound the callback.
234 return true
235 }
236 return currentBrowser != nil && currentBrowser.GetIdentifier() == browser.GetIdentifier()
237}
238
239// OnFullscreenModeChange toggles the fullscreen atomic and fires callbacks.
240func (h *handlerSet) OnFullscreenModeChange(_ purecef.Browser, fullscreen int32) {
241 entering := fullscreen != 0
242 h.wv.fullscreen.Store(entering)
243
244 h.wv.mu.RLock()
245 cb := h.wv.callbacks
246 h.wv.mu.RUnlock()
247 if cb == nil {
248 return
249 }
250 if entering && cb.OnEnterFullscreen != nil {
251 h.wv.runOnGTK(func() {
252 cb.OnEnterFullscreen()
253 })
254 }
255 if !entering && cb.OnLeaveFullscreen != nil {
256 h.wv.runOnGTK(func() {
257 cb.OnLeaveFullscreen()
258 })
259 }
260}
261
262func (h *handlerSet) OnTooltip(_ purecef.Browser, _ uintptr) int32 { return 0 }
263
264// OnStatusMessage fires the OnLinkHover callback with the status text
265// and caches the hover URI for middle-click interception.
266func (h *handlerSet) OnStatusMessage(_ purecef.Browser, value string) {
267 h.wv.updateHoverURI(value)
268
269 h.wv.mu.RLock()
270 cb := h.wv.callbacks
271 h.wv.mu.RUnlock()
272 if cb != nil && cb.OnLinkHover != nil {
273 h.wv.runOnGTK(func() {
274 cb.OnLinkHover(value)
275 })
276 }
277}
278
279func (h *handlerSet) OnConsoleMessage(
280 _ purecef.Browser,
281 level purecef.LogSeverity,
282 message, source string,
283 line int32,
284) int32 {
285 if h.wv != nil && h.wv.ctx != nil &&
286 (strings.Contains(message, consoleMarkerVideoDiag) ||
287 strings.Contains(message, consoleMarkerAutoCopy) ||
288 strings.Contains(message, consoleMarkerScaleProbe)) {
289 log := logging.FromContext(h.wv.ctx).With().
290 Str("component", "cef-console").
291 Str("source", source).
292 Int32("line", line).
293 Logger()
294 switch level {
295 case purecef.LogSeverityLogseverityError, purecef.LogSeverityLogseverityFatal:
296 log.Error().Str("message", message).Msg("cef: console message")
297 case purecef.LogSeverityLogseverityWarning:
298 log.Warn().Str("message", message).Msg("cef: console message")
299 default:
300 log.Info().Str("message", message).Msg("cef: console message")
301 }
302 }
303 return 0
304}
305
306func (h *handlerSet) OnAutoResize(_ purecef.Browser, _ *purecef.Size) int32 { return 0 }
307
308// OnLoadingProgressChange updates the cached progress value.
309func (h *handlerSet) OnLoadingProgressChange(_ purecef.Browser, progress float64) {
310 if h.wv != nil && h.wv.ctx != nil {
311 logging.FromContext(h.wv.ctx).Trace().
312 Float64("progress", progress).
313 Msg("cef: OnLoadingProgressChange")
314 }
315 h.wv.updateProgress(progress)
316}
317
318func (h *handlerSet) OnCursorChange(
319 _ purecef.Browser,
320 _ uintptr,
321 cursorType purecef.CursorType,
322 _ *purecef.CursorInfo,
323) int32 {
324 if h == nil || h.wv == nil {
325 return 0
326 }
327 name := cefCursorToGDKName(cursorType)
328 h.wv.runOnGTK(func() {
329 if h.wv.viewBridge != nil {
330 h.wv.viewBridge.SetCursorFromName(name)
331 }
332 })
333 return 1 // handled
334}
335
336func (h *handlerSet) OnMediaAccessChange(_ purecef.Browser, _, _ int32) {}
337
338func (h *handlerSet) OnContentsBoundsChange(_ purecef.Browser, _ *purecef.Rect) int32 { return 0 }
339
340func (h *handlerSet) GetRootWindowScreenRect(_ purecef.Browser, _ *purecef.Rect) int32 { return 0 }
341
342// ===========================================================================
343// LoadHandler (4 methods)
344// ===========================================================================
345
346type faviconSourceVisitorRetention struct {
347 id uint64
348 visitor purecef.StringVisitor
349}
350
351type faviconSourceVisitor struct {
352 visit func(string)
353}
354
355func (v faviconSourceVisitor) Visit(source string) {
356 if v.visit != nil {
357 v.visit(source)
358 }
359}
360
361// OnLoadingStateChange updates the loading/navigation state cache and fires callbacks.
362func (h *handlerSet) OnLoadingStateChange(browser purecef.Browser, isloading, cangoback, cangoforward int32) {
363 loading := isloading != 0
364 h.wv.updateLoadState(loading, cangoback != 0, cangoforward != 0)
365 if h.wv != nil && h.wv.ctx != nil {
366 h.wv.mu.RLock()
367 uri := h.wv.uri
368 progress := h.wv.progress
369 pendingURI := h.wv.pendingURI
370 h.wv.mu.RUnlock()
371 logging.FromContext(h.wv.ctx).Debug().
372 Bool("loading", loading).
373 Bool("can_go_back", cangoback != 0).
374 Bool("can_go_forward", cangoforward != 0).
375 Float64("progress", progress).
376 Str("uri", logging.TruncateURL(uri, logging.PermissionLogURLMaxLen)).
377 Str("pending_uri", logging.TruncateURL(pendingURI, logging.PermissionLogURLMaxLen)).
378 Msg("cef: OnLoadingStateChange")
379 }
380
381 if !loading && h.wv.viewBridge != nil {
382 h.wv.runOnGTK(func() {
383 if h.wv.viewBridge != nil && h.wv.viewBridge.HasFocus() {
384 h.wv.mu.RLock()
385 host := h.wv.host
386 h.wv.mu.RUnlock()
387 if host != nil {
388 syncWindowlessBrowserFocus(host)
389 }
390 }
391 })
392 }
393
394 h.wv.mu.RLock()
395 cb := h.wv.callbacks
396 pageURL := h.wv.uri
397 committedURL := h.wv.committedURL
398 h.wv.mu.RUnlock()
399 if committedURL == "" {
400 committedURL = pageURL
401 }
402 if !loading && cb != nil && cb.OnFaviconURLChanged != nil {
403 h.emitDiscoveredFaviconCandidates(browser, pageURL, committedURL, cb)
404 }
405 if cb != nil && cb.OnLoadChanged != nil {
406 if loading {
407 h.wv.runOnGTK(func() {
408 cb.OnLoadChanged(port.LoadStarted)
409 })
410 } else {
411 h.wv.runOnGTK(func() {
412 cb.OnLoadChanged(port.LoadFinished)
413 })
414 }
415 }
416}
417
418var faviconSourceVisitorRetentionID atomic.Uint64
419
420func (wv *WebView) retainFaviconSourceVisitor(visitor purecef.StringVisitor) func() {
421 if wv == nil || visitor == nil {
422 return func() {}
423 }
424 id := faviconSourceVisitorRetentionID.Add(1)
425 wv.faviconSourceVisitorsMu.Lock()
426 wv.faviconSourceVisitors = append(wv.faviconSourceVisitors, faviconSourceVisitorRetention{id: id, visitor: visitor})
427 wv.faviconSourceVisitorsMu.Unlock()
428 return func() {
429 wv.faviconSourceVisitorsMu.Lock()
430 defer wv.faviconSourceVisitorsMu.Unlock()
431 for i, candidate := range wv.faviconSourceVisitors {
432 if candidate.id != id {
433 continue
434 }
435 last := len(wv.faviconSourceVisitors) - 1
436 copy(wv.faviconSourceVisitors[i:], wv.faviconSourceVisitors[i+1:])
437 wv.faviconSourceVisitors[last] = faviconSourceVisitorRetention{}
438 wv.faviconSourceVisitors = wv.faviconSourceVisitors[:last]
439 return
440 }
441 }
442}
443
444func (h *handlerSet) emitDiscoveredFaviconCandidates(browser purecef.Browser, pageURL, committedURL string, cb *port.WebViewCallbacks) {
445 if h == nil || h.wv == nil || cb == nil || cb.OnFaviconURLChanged == nil {
446 return
447 }
448 h.wv.mu.Lock()
449 documentSeq := h.wv.documentSeq
450 if h.wv.faviconEngineDocumentSeq == documentSeq || h.wv.faviconSourceCompletedDocumentSeq == documentSeq ||
451 h.wv.faviconSourcePendingToken != 0 || documentSeq == 0 {
452 h.wv.mu.Unlock()
453 return
454 }
455 h.wv.faviconSourceRequestSerial++
456 token := h.wv.faviconSourceRequestSerial
457 h.wv.faviconSourcePendingToken = token
458 h.wv.mu.Unlock()
459 finish := func() {
460 h.wv.mu.Lock()
461 if h.wv.documentSeq == documentSeq && h.wv.faviconSourcePendingToken == token {
462 h.wv.faviconSourcePendingToken = 0
463 h.wv.faviconSourceCompletedDocumentSeq = documentSeq
464 }
465 h.wv.mu.Unlock()
466 }
467 fallback := fallbackFaviconCandidates(committedURL)
468 emit := func(candidates []string) {
469 if len(candidates) == 0 {
470 return
471 }
472 h.wv.runOnGTK(func() {
473 if !h.faviconCallbackCurrent(cb, browser, documentSeq, pageURL) {
474 return
475 }
476 cb.OnFaviconURLChanged(pageURL, candidates)
477 })
478 }
479 if browser == nil {
480 finish()
481 emit(fallback)
482 return
483 }
484 frame := browser.GetMainFrame()
485 if frame == nil {
486 finish()
487 emit(fallback)
488 return
489 }
490 var releaseOnce sync.Once
491 var release func()
492 visitor := cefNewStringVisitor(faviconSourceVisitor{visit: func(source string) {
493 releaseOnce.Do(func() {
494 if release != nil {
495 release()
496 }
497 })
498 finish()
499 if !h.faviconCallbackCurrent(cb, browser, documentSeq, pageURL) {
500 return
501 }
502 h.wv.mu.RLock()
503 engineWon := h.wv.faviconEngineDocumentSeq == documentSeq
504 h.wv.mu.RUnlock()
505 if engineWon {
506 return
507 }
508 candidates := DiscoverFaviconCandidates(committedURL, source)
509 if len(candidates) == 0 {
510 candidates = fallback
511 }
512 emit(candidates)
513 }})
514 release = h.wv.retainFaviconSourceVisitor(visitor)
515 time.AfterFunc(5*time.Second, func() {
516 releaseOnce.Do(func() {
517 if release != nil {
518 release()
519 }
520 })
521 finish()
522 })
523 frame.GetSource(visitor)
524}
525
526// OnLoadStart fires LoadCommitted for main frame navigations.
527// In CEF this callback runs after navigation commit, so it is the closest
528// equivalent to WebKit's LoadCommitted event.
529func (h *handlerSet) OnLoadStart(_ purecef.Browser, frame purecef.Frame, _ purecef.TransitionType) {
530 if frame == nil || !frame.IsMain() {
531 return
532 }
533 // Post-commit fallback for navigation paths that bypass OnBeforeBrowse
534 // (same-page, error, and helper-driven commits). Main frame only.
535 if h.wv != nil {
536 // A new document replaces the page that asked for any open JS dialog.
537 h.wv.cancelJSDialogs()
538 h.wv.invalidateScrollMotion()
539 h.wv.mu.Lock()
540 h.wv.documentSeq++
541 h.wv.faviconSourcePendingToken = 0
542 h.wv.faviconSourceCompletedDocumentSeq = 0
543 h.wv.mu.Unlock()
544 }
545 bridgeNonce := h.wv.ensureBridgeNonce()
546 if openerBridgeScript := h.wv.popupOpenerBridgeScript(bridgeNonce); openerBridgeScript != "" {
547 if h.wv != nil && h.wv.ctx != nil {
548 parentURI, active, blocked := h.wv.popupOpenerBridgeState()
549 logging.FromContext(h.wv.ctx).Debug().
550 Uint64("webview_id", uint64(h.wv.id)).
551 Str("url", logging.TruncateURL(frame.GetURL(), logging.PermissionLogURLMaxLen)).
552 Str("parent_uri", logging.TruncateURL(parentURI, logging.PermissionLogURLMaxLen)).
553 Bool("bridge_active", active).
554 Bool("bridge_blocked", blocked).
555 Msg("cef: injecting popup opener bridge")
556 }
557 frame.ExecuteJavaScript(openerBridgeScript, frame.GetURL(), 0)
558 }
559 if h.wv != nil && h.wv.ctx != nil {
560 logging.FromContext(h.wv.ctx).Debug().
561 Str("url", logging.TruncateURL(frame.GetURL(), logging.PermissionLogURLMaxLen)).
562 Msg("cef: OnLoadStart")
563 }
564 h.wv.setEditableFocus(false)
565 h.wv.updateURI(frame.GetURL())
566 h.wv.mu.RLock()
567 cb := h.wv.callbacks
568 h.wv.mu.RUnlock()
569 if cb != nil && cb.OnLoadChanged != nil {
570 h.wv.runOnGTK(func() {
571 cb.OnLoadChanged(port.LoadCommitted)
572 })
573 }
574}
575
576// OnLoadEnd resets crash count and injects content scripts for the main frame.
577func (h *handlerSet) OnLoadEnd(browser purecef.Browser, frame purecef.Frame, httpStatusCode int32) {
578 log := logging.FromContext(h.wv.ctx)
579 log.Debug().
580 Bool("frame_nil", frame == nil).
581 Bool("is_main", frame != nil && frame.IsMain()).
582 Int32("http_status", httpStatusCode).
583 Msg("cef: OnLoadEnd")
584 if frame == nil || !frame.IsMain() {
585 return
586 }
587 // Successful load — reset the consecutive crash counter.
588 h.wv.crashCount.Store(0)
589
590 // If a queued startup navigation is still pending after about:blank finished,
591 // replay it now that the initial main-frame load completed.
592 frameURL := frame.GetURL()
593 pendingURI, pendingIntentID := h.wv.pendingNavigationSnapshot()
594 if pendingURI != "" && !pendingURIEquivalent(frameURL, pendingURI) {
595 if strings.EqualFold(strings.TrimSpace(frameURL), "about:blank") {
596 rearmed := h.wv.rearmPendingNavigationAfterBlankLoadEnd(pendingIntentID)
597 log.Info().
598 Str("pending_uri", logging.TruncateURL(pendingURI, logging.PermissionLogURLMaxLen)).
599 Bool("rearmed", rearmed).
600 Msg("cef: replaying pending navigation after about:blank load end")
601 h.wv.schedulePendingNavigationReplayForIntent(0, pendingIntentID)
602 }
603 }
604
605 // Inject scripts and styles after page load.
606 // Must run on GTK thread — OnLoadEnd fires on the CEF IO thread,
607 // and JavaScript injection requires the main thread.
608 if cefScaleProbeEnabled() && shouldRunCEFScaleProbe(frameURL, httpStatusCode) {
609 // Do not retain/use CEF callback-scoped frame wrappers across the GTK idle hop.
610 // Re-read the current main frame through WebView.RunJavaScript instead.
611 h.wv.runOnGTK(func() {
612 snapshot := cefScaleProbeSnapshot(h.wv)
613 event := logging.FromContext(h.wv.ctx).Debug()
614 for key, value := range snapshot.logFields() {
615 event = event.Interface(key, value)
616 }
617 event.Msg("cef: injecting scale probe")
618 h.wv.RunJavaScript(context.Background(), cefScaleProbeScript)
619 })
620 }
621 if h.wv.engine != nil && h.wv.engine.contentInj != nil {
622 // Capture navigation identity for the GTK hop from the callback's
623 // browser: a process swap or a newer navigation can stale this
624 // event before it runs.
625 event := h.wv.captureInjectionEvent(browser, frameURL)
626 h.wv.runOnGTK(func() {
627 h.wv.engine.contentInj.onLoadEndForEvent(h.wv, event)
628 })
629 }
630
631 // NOTE: We intentionally do NOT dispatch LoadFinished or ProgressChanged(1.0)
632 // here. OnLoadEnd is a per-frame event, and during cross-site navigations
633 // (process swap), CEF fires OnLoadEnd for the OLD main frame before the new
634 // page finishes loading. Dispatching LoadFinished here caused the progress
635 // bar to hide prematurely while the new page was still loading.
636 //
637 // OnLoadingStateChange(isLoading=false) is the correct browser-level signal
638 // for load completion — CEF guarantees it fires AFTER all OnLoadEnd calls.
639 // CEF's OnLoadingProgressChange also provides progress=1.0 at completion.
640}
641
642const cefErrAborted purecef.Errorcode = -3
643
644// OnLoadError handles failed main-frame navigations that never reach
645// OnLoadStart. CEF still sends OnLoadingStateChange(false) after load errors,
646// so this callback only synthesizes the missing committed event needed to reveal
647// the pane; the normal browser-level loading-state callback remains responsible
648// for the terminal LoadFinished state.
649func (h *handlerSet) OnLoadError(_ purecef.Browser, frame purecef.Frame, errorCode purecef.Errorcode, errorText, failedURL string) {
650 if h == nil || h.wv == nil || frame == nil || !frame.IsMain() {
651 return
652 }
653 if errorCode == cefErrAborted {
654 return
655 }
656 if failedURL == "" {
657 failedURL = frame.GetURL()
658 }
659
660 h.wv.mu.RLock()
661 currentURI := h.wv.uri
662 cb := h.wv.callbacks
663 h.wv.mu.RUnlock()
664
665 if h.wv.ctx != nil {
666 logging.FromContext(h.wv.ctx).Debug().
667 Int32("error_code", errorCode).
668 Str("error_text", errorText).
669 Str("failed_url", logging.TruncateURL(failedURL, logging.PermissionLogURLMaxLen)).
670 Msg("cef: OnLoadError")
671 }
672
673 if failedURL != "" {
674 h.wv.updateURI(failedURL)
675 }
676
677 if cb == nil || cb.OnLoadChanged == nil {
678 return
679 }
680 if failedURL != "" && !pendingURIEquivalent(currentURI, failedURL) {
681 h.wv.runOnGTK(func() {
682 cb.OnLoadChanged(port.LoadCommitted)
683 })
684 }
685}
686
687func mapCEFPopupFeatures(in *purecef.PopupFeatures) dto.PopupFeatures {
688 if in == nil {
689 return dto.PopupFeatures{State: dto.PopupFeaturesNone}
690 }
691
692 state := dto.PopupFeaturesNone
693 if in.Xset != 0 || in.Yset != 0 || in.Widthset != 0 || in.Heightset != 0 || in.Ispopup != 0 {
694 state = dto.PopupFeaturesSpecified
695 }
696 return dto.PopupFeatures{
697 State: state,
698 X: int(in.X),
699 Y: int(in.Y),
700 Width: int(in.Width),
701 Height: int(in.Height),
702 XSet: in.Xset != 0,
703 YSet: in.Yset != 0,
704 WidthSet: in.Widthset != 0,
705 HeightSet: in.Heightset != 0,
706 IsPopup: in.Ispopup != 0,
707 IsPopupSet: true,
708 }
709}
710
711func mapCEFWindowDisposition(disposition purecef.WindowOpenDisposition) dto.WindowDisposition {
712 switch disposition {
713 case purecef.WindowOpenDispositionWodCurrentTab:
714 return dto.WindowDispositionCurrentTab
715 case purecef.WindowOpenDispositionWodNewPopup:
716 return dto.WindowDispositionNewPopup
717 case purecef.WindowOpenDispositionWodNewWindow:
718 return dto.WindowDispositionNewWindow
719 case purecef.WindowOpenDispositionWodNewForegroundTab,
720 purecef.WindowOpenDispositionWodNewBackgroundTab,
721 purecef.WindowOpenDispositionWodSingletonTab,
722 purecef.WindowOpenDispositionWodSwitchToTab:
723 return dto.WindowDispositionNewTab
724 default:
725 return ""
726 }
727}
728
729// ===========================================================================
730// LifeSpanHandler (6 methods)
731// ===========================================================================
732
733// OnBeforePopup intercepts popup requests (target="_blank", window.open).
734// When the coordinator returns a related CEF popup shell we hand that shell's
735// client back to CEF and allow native popup creation so opener semantics are
736// preserved. Otherwise we keep blocking and let the coordinator's fallback
737// pane handle the navigation.
738func (h *handlerSet) OnBeforePopup(
739 browser purecef.Browser, frame purecef.Frame, popupID int32, targetURL, targetFrameName string,
740 targetDisposition purecef.WindowOpenDisposition, userGesture int32, popupFeatures *purecef.PopupFeatures,
741 windowInfo *purecef.WindowInfo, clientSlot *purecef.RawClientWriteSlot, settings *purecef.BrowserSettings,
742 _ *purecef.DictionaryValue, noJavaScriptAccess *bool,
743) bool {
744 if targetURL == "" {
745 return true
746 }
747
748 h.wv.mu.RLock()
749 cb := h.wv.callbacks
750 h.wv.mu.RUnlock()
751 if cb == nil || cb.OnCreate == nil {
752 return true
753 }
754
755 requestNoJavaScriptAccess := false
756 if noJavaScriptAccess != nil {
757 requestNoJavaScriptAccess = *noJavaScriptAccess
758 }
759 var popup port.WebView
760 sourceBrowserID := int32(0)
761 if browser != nil {
762 sourceBrowserID = browser.GetIdentifier()
763 }
764 sourceFrameID := ""
765 sourceFrameURL := ""
766 if frame != nil {
767 sourceFrameID = frame.GetIdentifier()
768 sourceFrameURL = frame.GetURL()
769 }
770
771 dispatchResult := h.wv.runOnGTKSyncLabel("cef.on_before_popup", func() {
772 popup = cb.OnCreate(port.PopupRequest{
773 Engine: dto.BrowserEngineCEF,
774 PopupFeatures: mapCEFPopupFeatures(popupFeatures),
775 TargetURI: targetURL,
776 FrameName: targetFrameName,
777 IsUserGesture: userGesture != 0,
778 NoJavaScriptAccess: requestNoJavaScriptAccess,
779 ParentViewID: h.wv.id,
780 SourceBrowserID: sourceBrowserID,
781 SourceFrameID: sourceFrameID,
782 SourceFrameURL: sourceFrameURL,
783 TargetDisposition: mapCEFWindowDisposition(targetDisposition),
784 })
785 })
786 if !dispatchResult.Completed() {
787 logging.FromContext(h.currentContext()).Warn().
788 Str("target_url", logging.TruncateURL(targetURL, logging.PermissionLogURLMaxLen)).
789 Str("target_frame", targetFrameName).
790 Dur("elapsed", dispatchResult.Elapsed).
791 Str("dispatch_status", string(dispatchResult.Status)).
792 Msg("cef: blocked popup after GTK dispatch did not complete")
793 return true
794 }
795
796 cefPopup, ok := popup.(*WebView)
797 if !ok || cefPopup == nil {
798 return true
799 }
800
801 decision := dto.HostDecision{}
802 if carrier, ok := popup.(port.BrowsingContextHostDecisionCapable); ok {
803 if got, hasDecision := carrier.BrowsingContextHostDecision(); hasDecision {
804 decision = got
805 }
806 }
807
808 return h.handlePopupHostDecision(
809 cefPopup,
810 decision,
811 requestNoJavaScriptAccess,
812 popupID,
813 targetURL,
814 targetDisposition,
815 windowInfo,
816 clientSlot,
817 settings,
818 )
819}
820
821func (h *handlerSet) handlePopupHostDecision(
822 cefPopup *WebView,
823 decision dto.HostDecision,
824 requestNoJavaScriptAccess bool,
825 popupID int32,
826 targetURL string,
827 targetDisposition purecef.WindowOpenDisposition,
828 windowInfo *purecef.WindowInfo,
829 clientSlot *purecef.RawClientWriteSlot,
830 settings *purecef.BrowserSettings,
831) bool {
832 cefPopup.setPopupNoJavaScriptAccess(requestNoJavaScriptAccess)
833 switch decision.Kind {
834 case dto.HostDecisionCreateNativePopup:
835 if cefPopup.prepareNativePopup(popupID, targetURL, windowInfo, clientSlot, settings) {
836 logging.FromContext(h.currentContext()).Debug().
837 Int32("popup_id", popupID).
838 Str("target_url", logging.TruncateURL(targetURL, logging.PermissionLogURLMaxLen)).
839 Msg("cef: native popup armed")
840 return false
841 }
842
843 fallbackEligible := !decision.RequiresNativeOpener && decision.ReasonCode != dto.HostDecisionReasonAuthNativePopup
844 if fallbackEligible {
845 // The Phase 3 abort callback may synchronously detach and adopt this
846 // shell. Arm direct creation first so the adopted shell can create a
847 // browser and retain the synthetic opener bridge when allowed.
848 cefPopup.preparePopupShellDirectBrowserCreation()
849 }
850 abortInvoked := cefPopup.abortNativePopupHost()
851 if !abortInvoked {
852 cefPopup.Destroy()
853 }
854 logging.FromContext(h.currentContext()).Warn().
855 Str("engine", string(dto.BrowserEngineCEF)).
856 Str("source_host", string(decision.SourceHost)).
857 Str("decision", string(decision.Kind)).
858 Str("target_disposition", string(mapCEFWindowDisposition(targetDisposition))).
859 Str("reason_code", string(dto.BrowsingContextFailureNativeArm)).
860 Int32("popup_id", popupID).
861 Str("target_url", logging.TruncateURL(targetURL, logging.PermissionLogURLMaxLen)).
862 Bool("fallback_eligible", fallbackEligible).
863 Bool("host_abort_invoked", abortInvoked).
864 Msg("cef: native popup arming failed")
865 return true
866 case dto.HostDecisionCreateBrowserWindow,
867 dto.HostDecisionCreatePane,
868 dto.HostDecisionReuseNamedPane:
869 // CEF's native popup is blocked. A related shell adopted by a Dumber
870 // host must create its browser directly; noopener controls whether the
871 // synthetic opener/postMessage bridge is installed.
872 directCreationPrepared := cefPopup.preparePopupShellDirectBrowserCreation()
873 if !directCreationPrepared && cefPopup.isNativePopupCandidate() {
874 // Clear only a still-unprepared candidate; an already-started fallback
875 // owns its opener state and must remain intact.
876 cefPopup.discardNativePopupCandidate()
877 }
878 logging.FromContext(h.currentContext()).Debug().
879 Int32("popup_id", popupID).
880 Str("target_url", logging.TruncateURL(targetURL, logging.PermissionLogURLMaxLen)).
881 Str("decision", string(decision.Kind)).
882 Bool("direct_creation_prepared", directCreationPrepared).
883 Msg("cef: blocking native popup for related shell browser creation")
884 return true
885 case dto.HostDecisionAwaitPopupFeatures, dto.HostDecisionDeny:
886 cefPopup.Destroy()
887 logging.FromContext(h.currentContext()).Warn().
888 Int32("popup_id", popupID).
889 Str("target_url", logging.TruncateURL(targetURL, logging.PermissionLogURLMaxLen)).
890 Str("decision", string(decision.Kind)).
891 Msg("cef: denied popup host decision")
892 return true
893 default:
894 if !cefPopup.preparePopupShellDirectBrowserCreation() {
895 cefPopup.discardNativePopupCandidate()
896 }
897 logging.FromContext(h.currentContext()).Debug().
898 Int32("popup_id", popupID).
899 Str("target_url", logging.TruncateURL(targetURL, logging.PermissionLogURLMaxLen)).
900 Msg("cef: missing host decision, blocking native popup and using popup shell browser creation")
901 return true
902 }
903}
904
905func (h *handlerSet) OnBeforePopupAborted(_ purecef.Browser, popupID int32) {
906 if popup := h.wv.takePendingNativePopup(popupID); popup != nil {
907 popup.handleNativePopupAborted()
908 }
909}
910
911func (h *handlerSet) OnBeforeDevToolsPopup(
912 _ purecef.Browser, _ *purecef.WindowInfo, _ *purecef.RawClientWriteSlot,
913 _ *purecef.BrowserSettings, _ *purecef.DictionaryValue, _ *bool,
914) {
915}
916
917// OnAfterCreated stores the browser and host references and enables input.
918func (h *handlerSet) OnAfterCreated(browser purecef.Browser) {
919 log := logging.FromContext(h.wv.ctx)
920 if browser == nil {
921 log.Warn().Msg("cef: OnAfterCreated called with nil browser")
922 if h.wv.engine != nil {
923 // No browser will ever complete this creation: resolve the
924 // pending count so quiescence cannot strand on it.
925 h.wv.engine.activity.NoteCreationResolved()
926 }
927 return
928 }
929 browserID := browser.GetIdentifier()
930 log.Debug().Int32("browser_id", browserID).Msg("cef: OnAfterCreated")
931
932 host := browser.GetHost()
933 if host == nil {
934 log.Warn().Msg("cef: OnAfterCreated returned nil host")
935 if h.wv.engine != nil {
936 // No view will ever attach to this browser: resolve the
937 // pending count so quiescence cannot strand on it.
938 h.wv.engine.activity.NoteCreationResolved()
939 }
940 return
941 }
942
943 state := h.attachAfterCreatedBrowser(browser, host, browserID)
944 if state.closeDuplicate {
945 log.Warn().
946 Int32("browser_id", browserID).
947 Int32("existing_browser_id", state.duplicateBrowserID).
948 Msg("cef: duplicate popup browser attached after shell already had a browser; closing duplicate")
949 if h.wv.engine != nil {
950 h.wv.engine.activity.NoteCreationResolved()
951 }
952 host.CloseBrowser(1)
953 return
954 }
955
956 h.finishAfterCreated(browser, host, state)
957}
958
959func (h *handlerSet) attachAfterCreatedBrowser(
960 browser purecef.Browser,
961 host purecef.BrowserHost,
962 browserID int32,
963) afterCreatedState {
964 state := afterCreatedState{}
965 h.wv.mu.Lock()
966
967 if existing := h.wv.browser; existing != nil {
968 existingID := existing.GetIdentifier()
969 if existingID != 0 && existingID != browserID {
970 state.closeDuplicate = true
971 state.duplicateBrowserID = existingID
972 h.wv.mu.Unlock()
973 return state
974 }
975 }
976
977 h.wv.browser = browser
978 h.wv.host = host
979 h.wv.clearAppliedZoomCompensation()
980 h.wv.pendingCreate = nil
981 bridge := h.wv.viewBridge
982 h.wv.inputAttached = bridge == nil
983 state.inputAttached = h.wv.inputAttached
984 if h.wv.findCtrl != nil {
985 h.wv.findCtrl.setHost(host)
986 }
987 state.nativePopupParent = h.wv.nativePopupParent
988 state.nativePopupID = h.wv.nativePopupID
989 h.wv.nativePopupParent = nil
990 h.wv.nativePopupID = 0
991 h.wv.nativePopupFallbackStarted = false
992 state.hasPendingNavigation = strings.TrimSpace(h.wv.pendingURI) != ""
993 h.wv.mu.Unlock()
994
995 if bridge != nil {
996 wv := h.wv
997 log := logging.FromContext(wv.ctx)
998 log.Debug().
999 Uint64("webview_id", uint64(wv.id)).
1000 Int32("browser_id", browserID).
1001 Bool("destroyed", wv.destroyed.Load()).
1002 Bool("bridge_present", true).
1003 Msg("cef: scheduling input bridge attachment")
1004 wv.runOnGTK(func() {
1005 currentBridge := wv.viewBridge
1006 log.Debug().
1007 Uint64("webview_id", uint64(wv.id)).
1008 Int32("browser_id", browserID).
1009 Bool("destroyed", wv.destroyed.Load()).
1010 Bool("bridge_present", currentBridge != nil).
1011 Bool("bridge_stale", currentBridge != bridge).
1012 Msg("cef: starting input bridge attachment")
1013 if wv.destroyed.Load() || currentBridge == nil || currentBridge != bridge || bridge.IsDestroyed() {
1014 wv.handleInputAttachFailure(ErrAdapterDestroyed, host)
1015 return
1016 }
1017 if err := bridge.AttachInputToWidget(host, wv.nativeWidget, wv.bridgeInputOptions()); err != nil {
1018 wv.handleInputAttachFailure(err, host)
1019 return
1020 }
1021 bridgeFocused := bridge.HasFocus()
1022 if bridgeFocused {
1023 syncWindowlessBrowserFocus(host)
1024 } else {
1025 host.Invalidate(purecef.PaintElementTypePetView)
1026 }
1027 wv.markInputAttached()
1028 log.Debug().
1029 Uint64("webview_id", uint64(wv.id)).
1030 Int32("browser_id", browserID).
1031 Bool("destroyed", wv.destroyed.Load()).
1032 Bool("bridge_present", wv.viewBridge != nil).
1033 Bool("bridge_focused", bridgeFocused).
1034 Msg("cef: input bridge attachment succeeded")
1035 })
1036 }
1037
1038 // CEF OSR starts hidden. SyncViewport reads GTK's mapped, ancestor-aware
1039 // effective state on the main context and reports that truthful initial state.
1040 if h.wv != nil {
1041 if h.wv.ctx != nil {
1042 logging.FromContext(h.wv.ctx).Info().
1043 Int32("windowless_frame_rate_configured", host.GetWindowlessFrameRate()).
1044 Msg("cef: browser initial/configured windowless frame rate")
1045 }
1046 h.wv.SyncViewport(h.wv.ctx, "after-created")
1047 }
1048 return state
1049}
1050
1051func (wv *WebView) handleInputAttachFailure(err error, host purecef.BrowserHost) {
1052 if wv == nil || err == nil {
1053 return
1054 }
1055 if wv.ctx != nil {
1056 browserID := int32(0)
1057 if host != nil {
1058 if browser := host.GetBrowser(); browser != nil {
1059 browserID = browser.GetIdentifier()
1060 }
1061 }
1062 logging.FromContext(wv.ctx).Warn().Err(err).
1063 Uint64("webview_id", uint64(wv.id)).
1064 Int32("browser_id", browserID).
1065 Bool("destroyed", wv.destroyed.Load()).
1066 Bool("bridge_present", wv.viewBridge != nil).
1067 Msg("cef: input bridge attachment failed")
1068 }
1069 if host != nil && !wv.destroyed.Load() {
1070 host.CloseBrowser(1)
1071 return
1072 }
1073 wv.runCloseCallbacks()
1074}
1075
1076func (h *handlerSet) finishAfterCreated(
1077 browser purecef.Browser,
1078 host purecef.BrowserHost,
1079 state afterCreatedState,
1080) {
1081 if h.wv.engine != nil {
1082 h.wv.engine.recordBrowserAfterCreated(browser)
1083 h.wv.engine.registerWebView(h.wv)
1084 h.wv.engine.bindBrowserWebView(browser, h.wv)
1085 }
1086 h.wv.stopNativePopupFallbackTimer()
1087 if state.inputAttached {
1088 // Request an initial OSR frame even before the first real navigation
1089 // commits. This restores the about:blank warm-up paint that the stable
1090 // startup path relied on and prevents the rendering bridge from staying idle.
1091 host.Invalidate(purecef.PaintElementTypePetView)
1092 }
1093 if state.hasPendingNavigation {
1094 h.wv.schedulePendingNavigationReplay()
1095 }
1096 if state.nativePopupParent != nil && state.nativePopupID != 0 {
1097 state.nativePopupParent.clearPendingNativePopup(state.nativePopupID, h.wv)
1098 }
1099 h.wv.scheduleStartAdaptiveFrameRatePolling()
1100 h.wv.scheduleStartBeginFrameLoop()
1101 h.wv.applyAccessibilityIfReady()
1102 h.wv.fireReadyToShow()
1103}
1104
1105type afterCreatedState struct {
1106 inputAttached bool
1107 hasPendingNavigation bool
1108 nativePopupParent *WebView
1109 nativePopupID int32
1110 duplicateBrowserID int32
1111 closeDuplicate bool
1112}
1113
1114// DoClose returns false to allow the default close behavior.
1115func (h *handlerSet) DoClose(_ purecef.Browser) bool {
1116 return false
1117}
1118
1119// OnBeforeClose fires the OnClose callback.
1120func (h *handlerSet) OnBeforeClose(browser purecef.Browser) {
1121 h.denyPendingPermissions()
1122 if h.wv.engine != nil {
1123 browserID := int32(0)
1124 if browser != nil {
1125 browserID = browser.GetIdentifier()
1126 }
1127 h.wv.engine.unregisterWebView(h.wv, browserID)
1128 }
1129 h.wv.mu.Lock()
1130 h.wv.browser = nil
1131 h.wv.host = nil
1132 h.wv.clearAppliedZoomCompensation()
1133 h.wv.inputAttached = false
1134 if h.wv.findCtrl != nil {
1135 h.wv.findCtrl.setHost(nil)
1136 }
1137 h.wv.mu.Unlock()
1138 if h.wv.destroyed.Load() {
1139 h.wv.destroyViewBridgeOnGTKAsync()
1140 } else if h.wv.viewBridge != nil {
1141 wv := h.wv
1142 wv.runOnGTK(func() {
1143 if wv.viewBridge == nil {
1144 return
1145 }
1146 if err := wv.viewBridge.SetInputHost(nil); err != nil && wv.ctx != nil {
1147 logging.FromContext(wv.ctx).Warn().Err(err).Msg("cef: failed to clear cef2gtk input host")
1148 }
1149 })
1150 }
1151 h.wv.scheduleStopAdaptiveFrameRatePolling()
1152 h.wv.scheduleStopBeginFrameLoop()
1153
1154 h.wv.mu.RLock()
1155 cb := h.wv.callbacks
1156 h.wv.mu.RUnlock()
1157 if cb != nil && cb.OnClose != nil {
1158 h.wv.runOnGTK(func() {
1159 cb.OnClose()
1160 })
1161 }
1162 h.wv.runCloseCallbacks()
1163}
1164
1165// ===========================================================================
1166// RequestHandler (11 methods)
1167// ===========================================================================
1168
1169func (h *handlerSet) OnBeforeBrowse(browser purecef.Browser, frame purecef.Frame, request purecef.Request, _, _ int32) bool {
1170 if frame == nil || !frame.IsMain() || request == nil {
1171 return false
1172 }
1173 // Pre-commit invalidation for every main-frame navigation. The allow /
1174 // cancel decision below is unchanged; subframe navigations never reach
1175 // this point and do not cancel the main page's gesture.
1176 if h.wv != nil {
1177 h.wv.invalidateScrollMotion()
1178 }
1179
1180 handler := h.downloadHandler()
1181 if handler == nil || !strings.EqualFold(request.GetMethod(), "GET") {
1182 return false
1183 }
1184
1185 url := request.GetURL()
1186 if !downloadutil.ShouldForceDownloadForURI(url) || browser == nil {
1187 return false
1188 }
1189
1190 host := browser.GetHost()
1191 if host == nil {
1192 return false
1193 }
1194
1195 logging.FromContext(h.currentContext()).Debug().
1196 Str("url", logging.TruncateURL(url, maxSchemeTruncatedURLLength)).
1197 Msg("cef: forcing download for navigation")
1198
1199 host.StartDownload(url)
1200 return true
1201}
1202
1203func (h *handlerSet) CanDownload(browser purecef.Browser, url, requestMethod string) bool {
1204 handler := h.downloadHandler()
1205 if handler == nil {
1206 return false
1207 }
1208 return handler.canDownload(browser, url, requestMethod)
1209}
1210
1211func (h *handlerSet) OnBeforeDownload(
1212 browser purecef.Browser,
1213 downloadItem purecef.DownloadItem,
1214 suggestedName string,
1215 callback purecef.BeforeDownloadCallback,
1216) bool {
1217 handler := h.downloadHandler()
1218 if handler == nil {
1219 return false
1220 }
1221 return handler.onBeforeDownload(h.currentContext(), browser, downloadItem, suggestedName, callback)
1222}
1223
1224func (h *handlerSet) OnDownloadUpdated(
1225 browser purecef.Browser,
1226 downloadItem purecef.DownloadItem,
1227 callback purecef.DownloadItemCallback,
1228) {
1229 handler := h.downloadHandler()
1230 if handler == nil {
1231 return
1232 }
1233 handler.onDownloadUpdated(h.currentContext(), browser, downloadItem, callback)
1234}
1235
1236func (h *handlerSet) downloadHandler() *downloadHandler {
1237 if h == nil || h.wv == nil || h.wv.engine == nil {
1238 return nil
1239 }
1240 return h.wv.engine.currentDownloadHandler()
1241}
1242
1243func (h *handlerSet) currentContext() context.Context {
1244 if h == nil || h.wv == nil || h.wv.ctx == nil {
1245 return context.Background()
1246 }
1247 return h.wv.ctx
1248}
1249
1250func (h *handlerSet) OnOpenUrlfromTab(
1251 _ purecef.Browser,
1252 _ purecef.Frame,
1253 _ string,
1254 _ purecef.WindowOpenDisposition,
1255 _ int32,
1256) int32 {
1257 return 0
1258}
1259
1260func (h *handlerSet) GetResourceRequestHandler(
1261 _ purecef.Browser, _ purecef.Frame, _ purecef.Request,
1262 _, _ int32, _ string, _ *int32,
1263) purecef.ResourceRequestHandler {
1264 return nil
1265}
1266
1267func (h *handlerSet) GetAuthCredentials(
1268 _ purecef.Browser, _ string, _ int32, _ string, _ int32,
1269 _, _ string, _ purecef.AuthCallback,
1270) int32 {
1271 return 0
1272}
1273
1274func (h *handlerSet) OnCertificateError(
1275 _ purecef.Browser,
1276 _ purecef.Errorcode,
1277 _ string,
1278 _ purecef.Sslinfo,
1279 _ purecef.Callback,
1280) int32 {
1281 return 0
1282}
1283
1284func (h *handlerSet) OnSelectClientCertificate(
1285 _ purecef.Browser, _ int32, _ string, _ int32,
1286 _ []purecef.X509Certificate, _ purecef.SelectClientCertificateCallback,
1287) int32 {
1288 return 0
1289}
1290
1291func (h *handlerSet) OnRenderViewReady(_ purecef.Browser) {}
1292
1293func (h *handlerSet) OnRenderProcessUnresponsive(_ purecef.Browser, _ purecef.UnresponsiveProcessCallback) int32 {
1294 return 0
1295}
1296
1297func (h *handlerSet) OnRenderProcessResponsive(_ purecef.Browser) {}
1298
1299// maxConsecutiveCrashes caps how many times OnRenderProcessTerminated will
1300// forward the event before suppressing further notifications. This prevents
1301// infinite crash → redirect → crash loops.
1302const maxConsecutiveCrashes = 3
1303
1304// OnRenderProcessTerminated fires the OnWebProcessTerminated callback with a mapped reason.
1305func (h *handlerSet) OnRenderProcessTerminated(_ purecef.Browser, status purecef.TerminationStatus, _ int32, _ string) {
1306 // CEF never resets dialog state on a renderer crash; don't leave the UI
1307 // (and the dead page's callback) hanging.
1308 h.wv.cancelJSDialogs()
1309
1310 if h.wv.crashCount.Add(1) > maxConsecutiveCrashes {
1311 return // suppress to break the loop
1312 }
1313
1314 var reason port.WebProcessTerminationReason
1315 var label string
1316 switch status {
1317 case purecef.TerminationStatusTsAbnormalTermination:
1318 reason = port.WebProcessTerminationCrashed
1319 label = "abnormal termination"
1320 case purecef.TerminationStatusTsProcessWasKilled:
1321 reason = port.WebProcessTerminationByAPI
1322 label = "killed"
1323 case purecef.TerminationStatusTsProcessCrashed:
1324 reason = port.WebProcessTerminationCrashed
1325 label = "crashed"
1326 case purecef.TerminationStatusTsProcessOom:
1327 reason = port.WebProcessTerminationExceededMemory
1328 label = "out of memory"
1329 default:
1330 reason = port.WebProcessTerminationUnknown
1331 label = "unknown"
1332 }
1333
1334 h.wv.mu.RLock()
1335 cb := h.wv.callbacks
1336 uri := h.wv.uri
1337 h.wv.mu.RUnlock()
1338 if cb != nil && cb.OnWebProcessTerminated != nil {
1339 h.wv.runOnGTK(func() {
1340 cb.OnWebProcessTerminated(reason, label, uri)
1341 })
1342 }
1343}
1344
1345func (h *handlerSet) OnDocumentAvailableInMainFrame(_ purecef.Browser) {}
1346
1347// ===========================================================================
1348// AudioHandler (5 methods)
1349// ===========================================================================
1350
1351func (h *handlerSet) GetAudioParameters(_ purecef.Browser, _ *purecef.AudioParameters) int32 {
1352 return 1 // proceed with defaults
1353}
1354
1355// OnAudioStreamStarted handles the start of an audio stream.
1356// The third callback argument is the channel count (not frames-per-buffer);
1357// frames-per-buffer comes from params.FramesPerBuffer.
1358func (h *handlerSet) OnAudioStreamStarted(_ purecef.Browser, params *purecef.AudioParameters, channels int32) {
1359 // Validate params and factory first
1360 if params == nil || h.wv.audioOutputFactory == nil {
1361 return
1362 }
1363
1364 // Build format from CEF parameters
1365 format := h.buildAudioStreamFormat(params, channels)
1366
1367 if h.wv.ctx != nil {
1368 logging.FromContext(h.wv.ctx).Info().
1369 Int("sample_rate", format.SampleRate).
1370 Int("channels", format.ChannelCount).
1371 Int("frames_per_buffer", format.FramesPerBuffer).
1372 Int32("channel_layout", params.ChannelLayout).
1373 Msg("cef: OnAudioStreamStarted")
1374 }
1375
1376 // Starting a stream invalidates both a previous publication and any older
1377 // creation already in flight. Close detached streams outside the mutex.
1378 generation, previous, accepted := h.wv.beginAudioStreamStart()
1379 if !accepted {
1380 return
1381 }
1382 h.wv.closeDetachedAudioStream(previous)
1383 h.wv.audioPacketCount.Store(0)
1384 h.wv.audioWriteCount.Store(0)
1385
1386 ctx := h.wv.ctx
1387 if ctx == nil {
1388 ctx = context.Background()
1389 }
1390 stream, err := h.wv.audioOutputFactory.NewStream(ctx, format)
1391 if err != nil {
1392 if h.wv.ctx != nil {
1393 logging.FromContext(h.wv.ctx).Warn().Err(err).
1394 Int("sample_rate", format.SampleRate).Int("channels", format.ChannelCount).
1395 Msg("cef: failed to create audio output stream")
1396 }
1397 return
1398 }
1399
1400 replaced, published := h.wv.publishAudioStream(generation, stream)
1401 if !published {
1402 // Stop, Destroy, or a newer Start won the race. This callback owns the
1403 // unpublishable stream and closes it exactly once.
1404 h.wv.closeDetachedAudioStream(&audioStreamHandle{stream: stream, generation: generation})
1405 return
1406 }
1407 h.wv.closeDetachedAudioStream(replaced)
1408 if h.wv.ctx != nil {
1409 logging.FromContext(h.wv.ctx).Info().
1410 Int("sample_rate", format.SampleRate).Int("channels", format.ChannelCount).
1411 Int("frames_per_buffer", format.FramesPerBuffer).
1412 Msg("cef: audio output stream created successfully")
1413 }
1414}
1415
1416// buildAudioStreamFormat converts CEF AudioParameters to port.AudioStreamFormat.
1417// channels is the authoritative channel count from the callback; params.FramesPerBuffer
1418// supplies the buffer size.
1419func (h *handlerSet) buildAudioStreamFormat(params *purecef.AudioParameters, channels int32) port.AudioStreamFormat {
1420 return port.AudioStreamFormat{
1421 SampleRate: int(params.SampleRate),
1422 ChannelCount: int(channels),
1423 FramesPerBuffer: int(params.FramesPerBuffer),
1424 }
1425}
1426
1427// OnAudioStreamPacket is a real-time callback: it atomically snapshots an
1428// immutable handle and performs only allocation-free atomic diagnostics. It
1429// never takes a lifecycle mutex or emits synchronous logs.
1430func (h *handlerSet) OnAudioStreamPacket(_ purecef.Browser, data [][]float32, frames int32, _ int64) {
1431 if len(data) == 0 || frames <= 0 {
1432 return
1433 }
1434 handle := h.wv.audioStream.Load()
1435 if handle == nil || handle.stream == nil {
1436 return
1437 }
1438 h.wv.audioPacketCount.Add(1)
1439 if handle.stream.Write(data) == nil {
1440 h.wv.audioWriteCount.Add(1)
1441 }
1442}
1443
1444// OnAudioStreamStopped handles stream stop.
1445func (h *handlerSet) OnAudioStreamStopped(_ purecef.Browser) {
1446 if h.wv.ctx != nil {
1447 logging.FromContext(h.wv.ctx).Info().
1448 Uint64("packets_received", h.wv.audioPacketCount.Load()).
1449 Uint64("writes_succeeded", h.wv.audioWriteCount.Load()).
1450 Msg("cef: OnAudioStreamStopped")
1451 }
1452 h.wv.setAudioPlaying(false)
1453 h.wv.closeAudioStream()
1454}
1455
1456// OnAudioStreamError handles stream errors.
1457func (h *handlerSet) OnAudioStreamError(_ purecef.Browser, message string) {
1458 if h.wv.ctx != nil {
1459 event := logging.FromContext(h.wv.ctx).Warn()
1460 logMsg := "cef: audio stream error"
1461 if h.wv.destroyed.Load() && message == "Socket closed unexpectedly" {
1462 event = logging.FromContext(h.wv.ctx).Debug()
1463 logMsg = "cef: audio stream closed during shutdown"
1464 }
1465 event.
1466 Str("error", message).
1467 Uint64("packets_received", h.wv.audioPacketCount.Load()).
1468 Uint64("writes_succeeded", h.wv.audioWriteCount.Load()).
1469 Msg(logMsg)
1470 }
1471 h.wv.setAudioPlaying(false)
1472 h.wv.closeAudioStream()
1473}
1474
1475// ===========================================================================
1476// FindHandler (1 method)
1477// ===========================================================================
1478
1479// OnFindResult dispatches CEF find results to the WebView's FindController.
1480func (h *handlerSet) OnFindResult(
1481 _ purecef.Browser,
1482 identifier, count int32,
1483 _ *purecef.Rect,
1484 activematchordinal, finalupdate int32,
1485) {
1486 if h.wv.findCtrl != nil {
1487 h.wv.findCtrl.handleFindResult(identifier, count, activematchordinal, finalupdate)
1488 }
1489}
1490
1491// cefCursorNames maps CEF cursor types to GDK/CSS cursor names.
1492var cefCursorNames = map[purecef.CursorType]string{
1493 purecef.CursorTypeCtPointer: "default",
1494 purecef.CursorTypeCtCross: "crosshair",
1495 purecef.CursorTypeCtHand: "pointer",
1496 purecef.CursorTypeCtIbeam: "text",
1497 purecef.CursorTypeCtWait: "wait",
1498 purecef.CursorTypeCtHelp: "help",
1499 purecef.CursorTypeCtEastresize: "e-resize",
1500 purecef.CursorTypeCtNorthresize: "n-resize",
1501 purecef.CursorTypeCtNortheastresize: "ne-resize",
1502 purecef.CursorTypeCtNorthwestresize: "nw-resize",
1503 purecef.CursorTypeCtSouthresize: "s-resize",
1504 purecef.CursorTypeCtSoutheastresize: "se-resize",
1505 purecef.CursorTypeCtSouthwestresize: "sw-resize",
1506 purecef.CursorTypeCtWestresize: "w-resize",
1507 purecef.CursorTypeCtNorthsouthresize: "ns-resize",
1508 purecef.CursorTypeCtEastwestresize: "ew-resize",
1509 purecef.CursorTypeCtNortheastsouthwestresize: "nesw-resize",
1510 purecef.CursorTypeCtNorthwestsoutheastresize: "nwse-resize",
1511 purecef.CursorTypeCtColumnresize: "col-resize",
1512 purecef.CursorTypeCtRowresize: "row-resize",
1513 purecef.CursorTypeCtMove: "move",
1514 purecef.CursorTypeCtProgress: "progress",
1515 purecef.CursorTypeCtNodrop: "no-drop",
1516 purecef.CursorTypeCtNotallowed: "not-allowed",
1517 purecef.CursorTypeCtGrab: "grab",
1518 purecef.CursorTypeCtGrabbing: "grabbing",
1519 purecef.CursorTypeCtZoomin: "zoom-in",
1520 purecef.CursorTypeCtZoomout: "zoom-out",
1521 purecef.CursorTypeCtNone: "none",
1522}
1523
1524// cefCursorToGDKName maps a CEF cursor type to a GDK/CSS cursor name.
1525func cefCursorToGDKName(ct purecef.CursorType) string {
1526 if name, ok := cefCursorNames[ct]; ok {
1527 return name
1528 }
1529 return "default"
1530}