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
152// FindOptions configures search behavior.
153type FindOptions struct {
154 CaseInsensitive bool
155 AtWordStarts bool
156 WrapAround bool
157}
158
159// FindController abstracts WebKit's FindController for clean architecture.
160type FindController interface {
161 Search(text string, options FindOptions, maxMatches uint)
162 CountMatches(text string, options FindOptions, maxMatches uint)
163 SearchNext()
164 SearchPrevious()
165 SearchFinish()
166 GetSearchText() string
167
168 // Signal connections
169 OnFoundText(callback func(matchCount uint)) uint
170 OnFailedToFindText(callback func()) uint
171 OnCountedMatches(callback func(matchCount uint)) uint
172 DisconnectSignal(id uint)
173}
174
175// WebView defines the port interface for browser view operations.
176// This interface abstracts the underlying browser engine (WebKit, etc.)
177// and exposes only the navigation and state capabilities needed by
178// the application layer.
179type WebView interface {
180 // ID returns the unique identifier for this WebView.
181 ID() WebViewID
182
183 // --- Navigation ---
184
185 // LoadURI navigates to the specified URI.
186 LoadURI(ctx context.Context, uri string) error
187
188 // LoadHTML loads HTML content with an optional base URI for relative links.
189 LoadHTML(ctx context.Context, content, baseURI string) error
190
191 // Reload reloads the current page.
192 Reload(ctx context.Context) error
193
194 // ReloadBypassCache reloads the current page, bypassing cache.
195 ReloadBypassCache(ctx context.Context) error
196
197 // Stop stops the current page load.
198 Stop(ctx context.Context) error
199
200 // GoBack navigates back in history.
201 // Uses WebKit native navigation if available, falls back to JavaScript history.back() for SPA compatibility.
202 GoBack(ctx context.Context) error
203
204 // GoForward navigates forward in history.
205 // Uses WebKit native navigation if available, falls back to JavaScript history.forward() for SPA compatibility.
206 GoForward(ctx context.Context) error
207
208 // --- State Queries ---
209
210 // State returns the current WebView state as a snapshot.
211 State() WebViewState
212
213 // URI returns the current URI.
214 URI() string
215
216 // Title returns the current page title.
217 Title() string
218
219 // IsLoading returns true if a page is currently loading.
220 IsLoading() bool
221
222 // EstimatedProgress returns the load progress (0.0 to 1.0).
223 EstimatedProgress() float64
224
225 // CanGoBack returns true if back navigation is available.
226 CanGoBack() bool
227
228 // CanGoForward returns true if forward navigation is available.
229 CanGoForward() bool
230
231 // --- Zoom ---
232
233 // SetZoomLevel sets the zoom level (1.0 = 100%).
234 SetZoomLevel(ctx context.Context, level float64) error
235
236 // GetZoomLevel returns the current zoom level.
237 GetZoomLevel() float64
238
239 // --- Find ---
240
241 // GetFindController returns the find controller for text search.
242 // Returns nil if find is not supported.
243 GetFindController() FindController
244
245 // --- Callbacks ---
246
247 // SetCallbacks registers callback handlers for WebView events.
248 // Pass nil to clear all callbacks.
249 SetCallbacks(callbacks *WebViewCallbacks)
250
251 // --- Appearance ---
252
253 // RunJavaScript executes a script in the main world. Fire-and-forget.
254 RunJavaScript(ctx context.Context, script string)
255
256 // SetBackgroundColor sets the background color shown before content paints (0.0-1.0 RGBA).
257 SetBackgroundColor(r, g, b, a float64)
258
259 // ResetBackgroundToDefault resets the background to white (browser default).
260 ResetBackgroundToDefault()
261
262 // --- Favicon ---
263
264 // Favicon returns the current page favicon, or nil if unavailable.
265 Favicon() Texture
266
267 // Generation returns a monotonic counter incremented on pool reuse.
268 // Used to detect stale callbacks after a WebView is recycled.
269 Generation() uint64
270
271 // --- Media/Fullscreen State ---
272
273 // IsFullscreen returns true if the WebView is currently in fullscreen mode.
274 IsFullscreen() bool
275
276 // IsPlayingAudio returns true if the WebView is currently playing audio.
277 IsPlayingAudio() bool
278
279 // --- Lifecycle ---
280
281 // IsDestroyed returns true if the WebView has been destroyed.
282 IsDestroyed() bool
283
284 // Destroy releases all resources associated with this WebView.
285 // After calling Destroy, the WebView should not be used.
286 Destroy()
287}
288
289// WebViewPool defines the port interface for WebView pooling.
290// Pools maintain pre-created WebViews for fast tab creation.
291type WebViewPool interface {
292 // Acquire obtains a WebView from the pool or creates a new one.
293 // The context can be used for cancellation.
294 Acquire(ctx context.Context) (WebView, error)
295
296 // Release returns a WebView to the pool for reuse.
297 // The WebView will be reset to a blank state.
298 // If the pool is full, the WebView will be destroyed.
299 Release(wv WebView)
300
301 // Prewarm creates WebViews synchronously to populate the pool.
302 // Pass count <= 0 to use the default prewarm count.
303 Prewarm(count int)
304
305 // PrewarmAsync schedules WebView creation on the toolkit idle loop,
306 // avoiding blocking startup while still warming up WebViews.
307 // Pass count <= 0 to use the default prewarm count.
308 PrewarmAsync(ctx context.Context, count int)
309
310 // Size returns the current number of available WebViews in the pool.
311 Size() int
312
313 // Close shuts down the pool and destroys all pooled WebViews.
314 Close()
315}
316
317// WebViewFactory creates new WebView instances.
318// This is used when direct WebView creation is needed without pooling.
319type WebViewFactory interface {
320 // Create creates a new WebView instance.
321 Create(ctx context.Context) (WebView, error)
322
323 // CreateRelated creates a WebView that shares session/cookies with parent.
324 // This is required for popup windows to maintain authentication state.
325 // Popup WebViews bypass the pool since they must be related to a specific parent.
326 CreateRelated(ctx context.Context, parentID WebViewID) (WebView, error)
327}
328
329// DevToolsOpener is an optional capability for WebViews that support developer tools.
330type DevToolsOpener interface {
331 OpenDevTools()
332}
333
334// Printer is an optional capability for WebViews that support printing.
335type Printer interface {
336 PrintPage()
337}
338
339// PopupLifecycleCapable is implemented by WebViews that support the full popup
340// pane lifecycle. SetOnClose composes the provided function with any existing
341// close handler so multiple callers can register close hooks without
342// overwriting one another. PrimePopupNavigation lets engines preserve the popup
343// target URI before the browser is fully created.
344type PopupLifecycleCapable interface {
345 SetOnReadyToShow(fn func())
346 SetOnClose(fn func())
347 Show()
348 PrimePopupNavigation(uri string)
349}
350
351// PopupFeatureResolver is implemented by engines that can only resolve popup
352// window properties after the related WebView reaches ready-to-show.
353type PopupFeatureResolver interface {
354 ResolvePopupFeatures() dto.PopupFeatures
355}
356
357// PopupOpenerCapable is implemented by popup WebViews that can emulate opener
358// semantics when a popup must be created directly instead of through a native
359// related-popup lifecycle, and that can report or observe synthetic opener
360// traffic needed by OAuth flows.
361type PopupOpenerCapable interface {
362 EnablePopupOpenerBridge(parent WebView, noJavaScriptAccess bool)
363 AddOpenerMessageCallback(fn func())
364 AddOpenerNavigationCallback(fn func(uri string))
365 HasActivePopupOpenerBridge() bool
366}
367
368// ViewportSyncCapable is implemented by WebViews that can explicitly resync
369// their internal viewport state after UI lifecycle events such as reparenting,
370// visibility toggles, or layout promotion that may not emit a size change.
371//
372// Implementations should make this cheap, safe to call often, and resilient to
373// duplicate requests.
374type ViewportSyncCapable interface {
375 SyncViewport(ctx context.Context, reason string)
376}
377
378// OAuthCallbackCapable is implemented by WebViews that support OAuth auto-close callbacks.
379// It is an optional capability; callers should type-assert port.WebView to this interface
380// before use and degrade gracefully when it is absent.
381type OAuthCallbackCapable interface {
382 // AddCloseCallback registers fn to be called when the WebView is programmatically closed.
383 // Multiple callbacks may be registered; each will be called in registration order.
384 AddCloseCallback(fn func())
385 // AddNavigationCallback registers fn to be called whenever the URI changes or a
386 // committed load is detected. The uri parameter contains the new URL.
387 // Multiple callbacks may be registered; each will be called in registration order.
388 AddNavigationCallback(fn func(uri string))
389 // Close triggers a programmatic close of the WebView (equivalent to window.close()).
390 Close()
391}
392
393// TextInputTargetProvider is an optional capability for WebViews that support
394// text input method integration.
395type TextInputTargetProvider interface {
396 TextInputTarget() TextInputTarget
397}
398
399// PageScrollCommand identifies a semantic vim-scroll request at the
400// application boundary without depending on usecase package enums.
401type PageScrollCommand int
402
403const (
404 PageScrollCommandLeft PageScrollCommand = iota
405 PageScrollCommandRight
406 PageScrollCommandUp
407 PageScrollCommandDown
408 PageScrollCommandUpFast
409 PageScrollCommandDownFast
410)
411
412// PageScrollRequest carries a semantic vim-scroll command identity and its
413// fallback pixel deltas. Engines own the execution strategy and may use the
414// fallback delta when no native mechanism exists for the command.
415type PageScrollRequest struct {
416 Command PageScrollCommand
417 FallbackDX int
418 FallbackDY int
419 // Continuous distinguishes autonomous held-key steps from the guaranteed
420 // tap step so adapters can cancel queued held work without dropping taps.
421 Continuous bool
422}
423
424// IsValid reports whether c is a supported semantic page-scroll command.
425func (c PageScrollCommand) IsValid() bool {
426 return c >= PageScrollCommandLeft && c <= PageScrollCommandDownFast
427}
428
429// Validate checks the command identity carried by a page-scroll request.
430func (r PageScrollRequest) Validate() error {
431 if !r.Command.IsValid() {
432 return fmt.Errorf("unsupported page scroll command %d", r.Command)
433 }
434 return nil
435}
436
437// PageScrollable is an optional capability for WebViews that support semantic
438// page scrolling. Page scrolling is used by keyboard-driven navigation modes
439// such as Vim mode.
440//
441// Engines own the execution strategy. When a native mechanism exists for the
442// requested command, the engine may ignore the fallback delta. Otherwise it
443// should use the fallback delta as a JavaScript-driven scroll amount.
444type PageScrollable interface {
445 ScrollPage(ctx context.Context, request PageScrollRequest) error
446}
447
448// PageScrollCanceler is an optional capability for adapters that queue held
449// vim-scroll work. Implementations discard unconsumed continuous deltas while
450// preserving any guaranteed tap already accepted.
451type PageScrollCanceler interface {
452 CancelPageScroll(ctx context.Context)
453}
454
455// AccessibilityEnabler is an optional capability for adapters that can enable
456// browser accessibility tooling once per WebView. Engines that do not support
457// accessibility leave this unimplemented so callers can type-assert safely.
458type AccessibilityEnabler interface {
459 EnableAccessibility()
460}
461
462// SemanticNavigable is an optional WebView capability for visible structural
463// navigation. Unsupported engines safely leave it unimplemented.
464type SemanticNavigable interface {
465 NavigateSemantic(ctx context.Context, request dto.SemanticNavigationRequest) error
466}
467
468// SemanticNavigationActivator is an optional WebView capability for activating
469// the link associated with the current semantic navigation target.
470type SemanticNavigationActivator interface {
471 ActivateSemanticNavigationTarget(ctx context.Context) error
472}
473
474// SemanticNavigationHighlightClearer is an optional WebView capability for
475// removing the visual target left by semantic navigation.
476type SemanticNavigationHighlightClearer interface {
477 ClearSemanticNavigationHighlight(ctx context.Context) error
478}
479
480// PageInputFocuser is an optional WebView capability for moving Vim Mode
481// input focus to the next eligible page input. With no active eligible input,
482// implementations focus the first one. Unsupported engines safely leave it
483// unimplemented.
484type PageInputFocuser interface {
485 FocusNextInput()
486}
487
488// PageFocusNavigator is an optional WebView capability for keeping native-like
489// focus traversal inside the active page when the host window would otherwise
490// move focus outside the WebView.
491type PageFocusNavigator interface {
492 NavigatePageFocus(backward bool)
493}