1// Package port defines application-layer interfaces for external capabilities.
2// Ports abstract infrastructure concerns, allowing the application layer to
3// remain independent of specific implementations (WebKit, GTK, etc.).
4package port
5
6import (
7 "context"
8 "fmt"
9
10 "github.com/bnema/dumber/internal/application/dto"
11 "github.com/bnema/dumber/internal/domain/entity"
12)
13
14// WebViewID uniquely identifies a WebView instance.
15type WebViewID uint64
16
17// LoadEvent represents page load state transitions.
18type LoadEvent int
19
20const (
21 // LoadStarted indicates navigation has begun.
22 LoadStarted LoadEvent = iota
23 // LoadRedirected indicates a redirect occurred.
24 LoadRedirected
25 // LoadCommitted indicates content is being received.
26 LoadCommitted
27 // LoadFinished indicates the page has fully loaded.
28 LoadFinished
29)
30
31// String returns a human-readable representation of the load event.
32func (e LoadEvent) String() string {
33 switch e {
34 case LoadStarted:
35 return "started"
36 case LoadRedirected:
37 return "redirected"
38 case LoadCommitted:
39 return "committed"
40 case LoadFinished:
41 return "finished"
42 default:
43 return "unknown"
44 }
45}
46
47// WebViewState represents a snapshot of the current WebView state.
48// This is an immutable struct that can be safely passed between components.
49type WebViewState struct {
50 URI string
51 Title string
52 IsLoading bool
53 Progress float64 // 0.0 to 1.0
54 CanGoBack bool
55 CanGoFwd bool
56 ZoomLevel float64
57}
58
59// WebProcessTerminationReason describes why the web process terminated.
60type WebProcessTerminationReason int
61
62const (
63 WebProcessTerminationUnknown WebProcessTerminationReason = iota
64 WebProcessTerminationCrashed
65 WebProcessTerminationExceededMemory
66 WebProcessTerminationByAPI
67)
68
69// PopupRequest contains metadata about a popup window request.
70type PopupRequest struct {
71 TargetURI string
72 FrameName string // e.g., "_blank", custom name, or empty
73 IsUserGesture bool
74 NoJavaScriptAccess bool // true for noopener/noreferrer-style popups with no opener access
75 ParentViewID WebViewID
76
77 SourceBrowserID int32
78 SourceFrameID string
79 SourceFrameURL string
80
81 Engine dto.BrowserEngineKind
82 TargetDisposition dto.WindowDisposition
83 PopupFeatures dto.PopupFeatures
84}
85
86// Texture represents a graphics texture returned by the engine.
87// GoPointer returns a native toolkit pointer (e.g. *gdk.Texture in GTK engines).
88// Engine implementations are responsible for the concrete type.
89type Texture interface {
90 GoPointer() uintptr
91}
92
93// WebViewCallbacks defines callback handlers for WebView events.
94// Implementations should invoke these on the main thread/goroutine.
95type WebViewCallbacks struct {
96 // OnLoadChanged is called when load state changes.
97 OnLoadChanged func(event LoadEvent)
98 // OnTitleChanged is called when the page title changes.
99 OnTitleChanged func(title string)
100 // OnURIChanged is called when the URI changes.
101 OnURIChanged func(uri string)
102 // OnProgressChanged is called during page load with progress 0.0-1.0.
103 OnProgressChanged func(progress float64)
104 // OnFaviconChanged is called when the page favicon changes.
105 // The parameter is a *gdk.Texture (passed as Texture interface to avoid GTK import in port layer).
106 OnFaviconChanged func(favicon Texture)
107 // OnFaviconURLChanged is called when the engine discovers ordered favicon URL candidates for a page.
108 OnFaviconURLChanged func(pageURL string, iconURLs []string)
109 // OnClose is called when the WebView requests to close.
110 OnClose func()
111 // OnCreate is called when a popup window is requested.
112 // Return a WebView to allow the popup, or nil to block it.
113 OnCreate func(request PopupRequest) WebView
114 // OnReadyToShow is called when a popup WebView is ready to display.
115 OnReadyToShow func()
116 // OnLinkHover is called when hovering over a link, image, or media element.
117 // The uri parameter contains the target URL, or empty string when leaving.
118 OnLinkHover func(uri string)
119 // OnWebProcessTerminated is called when the web process exits unexpectedly.
120 OnWebProcessTerminated func(reason WebProcessTerminationReason, reasonLabel string, uri string)
121
122 // OnPermissionRequest is called when a site requests permission (mic, camera, screen sharing).
123 // Return true to indicate the request was handled. Call allow()/deny() to respond.
124 // The permission types are passed as strings ("microphone", "camera", "display", etc.).
125 // The metadata map carries permission-type-specific context; for website_data_access both
126 // entity.PermissionMetadataKeyRequestingDomain and entity.PermissionMetadataKeyCurrentDomain must be populated.
127 OnPermissionRequest func(origin string, permTypes []string, metadata map[string]string, allow, deny func()) bool
128
129 // OnLinkMiddleClick is called when a link is middle-clicked.
130 // Return true if handled (blocks default navigation).
131 OnLinkMiddleClick func(uri string) bool
132
133 // OnEnterFullscreen is called when the WebView requests fullscreen mode.
134 // Return true to prevent fullscreen.
135 OnEnterFullscreen func() bool
136
137 // OnLeaveFullscreen is called when the WebView exits fullscreen mode.
138 // Return true to prevent leaving fullscreen.
139 OnLeaveFullscreen func() bool
140
141 // OnAudioStateChanged is called when audio playback starts or stops.
142 OnAudioStateChanged func(playing bool)
143 // OnTouchpadNavigationGesture is called while a two-finger touchpad history
144 // navigation gesture is progressing or finishing.
145 OnTouchpadNavigationGesture func(gesture entity.TouchpadNavigationGesture)
146
147 // OnEditableFocusChanged is called when the page focus enters or leaves an
148 // editable target such as input, textarea, or contenteditable content.
149 OnEditableFocusChanged func(editable bool)
150
151 // OnJSDialog is called when the page requests a JavaScript dialog (alert,
152 // confirm, prompt) or the beforeunload "Leave page?" confirmation. The UI
153 // shows the dialog scoped to this WebView and calls respond exactly once
154 // when the user answers (ok=false for cancel/dismiss; input is only
155 // meaningful for prompts). Return false if no dialog could be shown; the
156 // engine then answers with a cancel itself. respond is idempotent and safe
157 // to call from the GTK thread.
158 OnJSDialog func(req JSDialogRequest, respond func(ok bool, input string)) bool
159 // OnJSDialogReset is called when the engine canceled a pending dialog (page
160 // navigation, WebView destruction). The UI must hide any dialog shown for
161 // this WebView without invoking respond.
162 OnJSDialogReset func()
163}
164
165// FindOptions configures search behavior.
166type FindOptions struct {
167 CaseInsensitive bool
168 AtWordStarts bool
169 WrapAround bool
170}
171
172// FindController abstracts WebKit's FindController for clean architecture.
173type FindController interface {
174 Search(text string, options FindOptions, maxMatches uint)
175 CountMatches(text string, options FindOptions, maxMatches uint)
176 SearchNext()
177 SearchPrevious()
178 SearchFinish()
179 GetSearchText() string
180
181 // Signal connections
182 OnFoundText(callback func(matchCount uint)) uint
183 OnFailedToFindText(callback func()) uint
184 OnCountedMatches(callback func(matchCount uint)) uint
185 DisconnectSignal(id uint)
186}
187
188// PageNavigator is the navigation subset of WebView. Consumers that only
189// load, reload, or stop pages depend on this instead of the full WebView.
190type PageNavigator interface {
191 // LoadURI navigates to the specified URI.
192 LoadURI(ctx context.Context, uri string) error
193
194 // LoadHTML loads HTML content with an optional base URI for relative links.
195 LoadHTML(ctx context.Context, content, baseURI string) error
196
197 // Reload reloads the current page.
198 Reload(ctx context.Context) error
199
200 // ReloadBypassCache reloads the current page, bypassing cache.
201 ReloadBypassCache(ctx context.Context) error
202
203 // Stop stops the current page load.
204 Stop(ctx context.Context) error
205
206 // GoBack navigates back in history.
207 // Uses WebKit native navigation if available, falls back to JavaScript history.back() for SPA compatibility.
208 GoBack(ctx context.Context) error
209
210 // GoForward navigates forward in history.
211 // Uses WebKit native navigation if available, falls back to JavaScript history.forward() for SPA compatibility.
212 GoForward(ctx context.Context) error
213}
214
215// WebView defines the port interface for browser view operations.
216// This interface abstracts the underlying browser engine (WebKit, etc.)
217// and exposes only the navigation and state capabilities needed by
218// the application layer.
219type WebView interface {
220 PageNavigator
221
222 // ID returns the unique identifier for this WebView.
223 ID() WebViewID
224
225 // --- State Queries ---
226
227 // State returns the current WebView state as a snapshot.
228 State() WebViewState
229
230 // URI returns the current URI.
231 URI() string
232
233 // Title returns the current page title.
234 Title() string
235
236 // IsLoading returns true if a page is currently loading.
237 IsLoading() bool
238
239 // EstimatedProgress returns the load progress (0.0 to 1.0).
240 EstimatedProgress() float64
241
242 // CanGoBack returns true if back navigation is available.
243 CanGoBack() bool
244
245 // CanGoForward returns true if forward navigation is available.
246 CanGoForward() bool
247
248 // --- Zoom ---
249
250 // SetZoomLevel sets the zoom level (1.0 = 100%).
251 SetZoomLevel(ctx context.Context, level float64) error
252
253 // GetZoomLevel returns the current zoom level.
254 GetZoomLevel() float64
255
256 // --- Find ---
257
258 // GetFindController returns the find controller for text search.
259 // Returns nil if find is not supported.
260 GetFindController() FindController
261
262 // --- Callbacks ---
263
264 // SetCallbacks registers callback handlers for WebView events.
265 // Pass nil to clear all callbacks.
266 SetCallbacks(callbacks *WebViewCallbacks)
267
268 // --- Appearance ---
269
270 // RunJavaScript executes a script in the main world. Fire-and-forget.
271 RunJavaScript(ctx context.Context, script string)
272
273 // SetBackgroundColor sets the background color shown before content paints (0.0-1.0 RGBA).
274 SetBackgroundColor(r, g, b, a float64)
275
276 // ResetBackgroundToDefault resets the background to white (browser default).
277 ResetBackgroundToDefault()
278
279 // --- Favicon ---
280
281 // Favicon returns the current page favicon, or nil if unavailable.
282 Favicon() Texture
283
284 // Generation returns a monotonic counter incremented on pool reuse.
285 // Used to detect stale callbacks after a WebView is recycled.
286 Generation() uint64
287
288 // --- Media/Fullscreen State ---
289
290 // IsFullscreen returns true if the WebView is currently in fullscreen mode.
291 IsFullscreen() bool
292
293 // IsPlayingAudio returns true if the WebView is currently playing audio.
294 IsPlayingAudio() bool
295
296 // --- Lifecycle ---
297
298 // IsDestroyed returns true if the WebView has been destroyed.
299 IsDestroyed() bool
300
301 // Destroy releases all resources associated with this WebView.
302 // After calling Destroy, the WebView should not be used.
303 Destroy()
304}
305
306// WebViewPool defines the port interface for WebView pooling.
307// Pools maintain pre-created WebViews for fast tab creation.
308type WebViewPool interface {
309 // Acquire obtains a WebView from the pool or creates a new one.
310 // The context can be used for cancellation.
311 Acquire(ctx context.Context) (WebView, error)
312
313 // Release returns a WebView to the pool for reuse.
314 // The WebView will be reset to a blank state.
315 // If the pool is full, the WebView will be destroyed.
316 Release(wv WebView)
317
318 // Prewarm creates WebViews synchronously to populate the pool.
319 // Pass count <= 0 to use the default prewarm count.
320 Prewarm(count int)
321
322 // PrewarmAsync schedules WebView creation on the toolkit idle loop,
323 // avoiding blocking startup while still warming up WebViews.
324 // Pass count <= 0 to use the default prewarm count.
325 PrewarmAsync(ctx context.Context, count int)
326
327 // Size returns the current number of available WebViews in the pool.
328 Size() int
329
330 // Close shuts down the pool and destroys all pooled WebViews.
331 Close()
332}
333
334// WebViewFactory creates new WebView instances.
335// This is used when direct WebView creation is needed without pooling.
336type WebViewFactory interface {
337 // Create creates a new WebView instance.
338 Create(ctx context.Context) (WebView, error)
339
340 // CreateRelated creates a WebView that shares session/cookies with parent.
341 // This is required for popup windows to maintain authentication state.
342 // Popup WebViews bypass the pool since they must be related to a specific parent.
343 CreateRelated(ctx context.Context, parentID WebViewID) (WebView, error)
344}
345
346// DevToolsOpener is an optional capability for WebViews that support developer tools.
347type DevToolsOpener interface {
348 OpenDevTools()
349}
350
351// Printer is an optional capability for WebViews that support printing.
352type Printer interface {
353 PrintPage()
354}
355
356// PopupLifecycleCapable is implemented by WebViews that support the full popup
357// pane lifecycle. SetOnClose composes the provided function with any existing
358// close handler so multiple callers can register close hooks without
359// overwriting one another. PrimePopupNavigation lets engines preserve the popup
360// target URI before the browser is fully created.
361type PopupLifecycleCapable interface {
362 SetOnReadyToShow(fn func())
363 SetOnClose(fn func())
364 Show()
365 PrimePopupNavigation(uri string)
366}
367
368// PopupFeatureResolver is implemented by engines that can only resolve popup
369// window properties after the related WebView reaches ready-to-show.
370type PopupFeatureResolver interface {
371 ResolvePopupFeatures() dto.PopupFeatures
372}
373
374// PopupOpenerCapable is implemented by popup WebViews that can emulate opener
375// semantics when a popup must be created directly instead of through a native
376// related-popup lifecycle, and that can report or observe synthetic opener
377// traffic needed by OAuth flows.
378type PopupOpenerCapable interface {
379 EnablePopupOpenerBridge(parent WebView, noJavaScriptAccess bool)
380 AddOpenerMessageCallback(fn func())
381 AddOpenerNavigationCallback(fn func(uri string))
382 HasActivePopupOpenerBridge() bool
383}
384
385// ViewportSyncCapable is implemented by WebViews that can explicitly resync
386// their internal viewport state after UI lifecycle events such as reparenting,
387// visibility toggles, or layout promotion that may not emit a size change.
388//
389// Implementations should make this cheap, safe to call often, and resilient to
390// duplicate requests.
391type ViewportSyncCapable interface {
392 SyncViewport(ctx context.Context, reason string)
393}
394
395// OAuthCallbackCapable is implemented by WebViews that support OAuth auto-close callbacks.
396// It is an optional capability; callers should type-assert port.WebView to this interface
397// before use and degrade gracefully when it is absent.
398type OAuthCallbackCapable interface {
399 // AddCloseCallback registers fn to be called when the WebView is programmatically closed.
400 // Multiple callbacks may be registered; each will be called in registration order.
401 AddCloseCallback(fn func())
402 // AddNavigationCallback registers fn to be called whenever the URI changes or a
403 // committed load is detected. The uri parameter contains the new URL.
404 // Multiple callbacks may be registered; each will be called in registration order.
405 AddNavigationCallback(fn func(uri string))
406 // Close triggers a programmatic close of the WebView (equivalent to window.close()).
407 Close()
408}
409
410// TextInputTargetProvider is an optional capability for WebViews that support
411// text input method integration.
412type TextInputTargetProvider interface {
413 TextInputTarget() TextInputTarget
414}
415
416// PageScrollCommand identifies a semantic vim-scroll request at the
417// application boundary without depending on usecase package enums.
418type PageScrollCommand int
419
420const (
421 PageScrollCommandLeft PageScrollCommand = iota
422 PageScrollCommandRight
423 PageScrollCommandUp
424 PageScrollCommandDown
425 PageScrollCommandUpFast
426 PageScrollCommandDownFast
427)
428
429// PageScrollRequest carries a semantic vim-scroll command identity and its
430// fallback pixel deltas. Engines own the execution strategy and may use the
431// fallback delta when no native mechanism exists for the command.
432type PageScrollRequest struct {
433 Command PageScrollCommand
434 FallbackDX int
435 FallbackDY int
436 // Continuous distinguishes autonomous held-key steps from the guaranteed
437 // tap step so adapters can cancel queued held work without dropping taps.
438 Continuous bool
439}
440
441// IsValid reports whether c is a supported semantic page-scroll command.
442func (c PageScrollCommand) IsValid() bool {
443 return c >= PageScrollCommandLeft && c <= PageScrollCommandDownFast
444}
445
446// Validate checks the command identity carried by a page-scroll request.
447func (r PageScrollRequest) Validate() error {
448 if !r.Command.IsValid() {
449 return fmt.Errorf("unsupported page scroll command %d", r.Command)
450 }
451 return nil
452}
453
454// PageScrollable is an optional capability for WebViews that support semantic
455// page scrolling. Page scrolling is used by keyboard-driven navigation modes
456// such as Vim mode.
457//
458// Engines own the execution strategy. When a native mechanism exists for the
459// requested command, the engine may ignore the fallback delta. Otherwise it
460// should use the fallback delta as a JavaScript-driven scroll amount.
461type PageScrollable interface {
462 ScrollPage(ctx context.Context, request PageScrollRequest) error
463}
464
465// PageScrollCanceler is an optional capability for adapters that queue held
466// vim-scroll work. Implementations discard unconsumed continuous deltas while
467// preserving any guaranteed tap already accepted.
468type PageScrollCanceler interface {
469 CancelPageScroll(ctx context.Context)
470}
471
472// AccessibilityEnabler is an optional capability for adapters that can enable
473// browser accessibility tooling once per WebView. Engines that do not support
474// accessibility leave this unimplemented so callers can type-assert safely.
475type AccessibilityEnabler interface {
476 EnableAccessibility()
477}
478
479// SemanticNavigable is an optional WebView capability for visible structural
480// navigation. Unsupported engines safely leave it unimplemented.
481type SemanticNavigable interface {
482 NavigateSemantic(ctx context.Context, request dto.SemanticNavigationRequest) error
483}
484
485// SemanticNavigationActivator is an optional WebView capability for activating
486// the link associated with the current semantic navigation target.
487type SemanticNavigationActivator interface {
488 ActivateSemanticNavigationTarget(ctx context.Context) error
489}
490
491// SemanticNavigationHighlightClearer is an optional WebView capability for
492// removing the visual target left by semantic navigation.
493type SemanticNavigationHighlightClearer interface {
494 ClearSemanticNavigationHighlight(ctx context.Context) error
495}
496
497// PageInputFocuser is an optional WebView capability for moving Vim Mode
498// input focus to the next eligible page input. With no active eligible input,
499// implementations focus the first one. Unsupported engines safely leave it
500// unimplemented.
501type PageInputFocuser interface {
502 FocusNextInput()
503}
504
505// PageFocusNavigator is an optional WebView capability for keeping native-like
506// focus traversal inside the active page when the host window would otherwise
507// move focus outside the WebView.
508type PageFocusNavigator interface {
509 NavigatePageFocus(backward bool)
510}