webkit

package
v0.20.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 23, 2025 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ScriptWorldName is the isolated world used for the injected UI.
	ScriptWorldName = "dumber"
	// MessageHandlerName is the name of the script message handler registered with WebKit.
	MessageHandlerName = "dumber"
)
View Source
const (
	HomePath   = "home"
	ConfigPath = "config"
	ErrorPath  = "error"
	IndexHTML  = "index.html"
)

Scheme path constants

Variables

This section is empty.

Functions

This section is empty.

Types

type ContentInjector

type ContentInjector struct {
	// contains filtered or unexported fields
}

ContentInjector encapsulates script injection into WebViews. It injects minimal scripts for dark mode detection in web pages and theme CSS variables for internal pages (dumb://). Implements port.ContentInjector interface.

func NewContentInjector

func NewContentInjector(prefersDark bool) *ContentInjector

NewContentInjector creates a new injector instance. The prefersDark parameter should come from ThemeManager.PrefersDark().

func (*ContentInjector) InjectFindHighlightCSS

func (ci *ContentInjector) InjectFindHighlightCSS(ctx context.Context, css string) error

InjectFindHighlightCSS stores CSS for find-in-page highlight styling.

func (*ContentInjector) InjectScripts

func (ci *ContentInjector) InjectScripts(ctx context.Context, ucm *webkit.UserContentManager, webviewID WebViewID)

InjectScripts adds the minimal dark mode detection scripts to the given content manager. Only injects: - window.__dumber_gtk_prefers_dark flag - window.__dumber_webview_id (for debugging) - darkModeScript (patches matchMedia for prefers-color-scheme)

func (*ContentInjector) InjectThemeCSS

func (ci *ContentInjector) InjectThemeCSS(ctx context.Context, css string) error

InjectThemeCSS stores CSS variables for injection into internal pages. Implements port.ContentInjector interface. The CSS will be injected when InjectScripts is called on WebView creation.

func (*ContentInjector) PrefersDark

func (ci *ContentInjector) PrefersDark() bool

PrefersDark returns the current dark mode preference.

func (*ContentInjector) SetPrefersDark

func (ci *ContentInjector) SetPrefersDark(prefersDark bool)

SetPrefersDark updates the dark mode preference. Call this when theme changes at runtime.

type DumbSchemeHandler

type DumbSchemeHandler struct {
	// contains filtered or unexported fields
}

DumbSchemeHandler handles dumb:// URI scheme requests.

func NewDumbSchemeHandler

func NewDumbSchemeHandler(ctx context.Context) *DumbSchemeHandler

NewDumbSchemeHandler creates a new handler for the dumb:// scheme.

func (*DumbSchemeHandler) HandleRequest

func (h *DumbSchemeHandler) HandleRequest(reqPtr uintptr)

HandleRequest processes a scheme request and sends the response.

func (*DumbSchemeHandler) RegisterPage

func (h *DumbSchemeHandler) RegisterPage(path string, handler PageHandler)

RegisterPage registers a handler for a specific path.

func (*DumbSchemeHandler) RegisterWithContext

func (h *DumbSchemeHandler) RegisterWithContext(wkCtx *WebKitContext)

RegisterWithContext registers the dumb:// scheme with a WebKitContext.

func (*DumbSchemeHandler) SetAssets

func (h *DumbSchemeHandler) SetAssets(assets embed.FS)

SetAssets sets the embedded filesystem containing webui assets.

type FaviconDatabase

type FaviconDatabase = webkit.FaviconDatabase

FaviconDatabase is a type alias for webkit.FaviconDatabase. Re-exported for use by UI layer without direct puregotk-webkit import.

type FilterApplier

type FilterApplier interface {
	ApplyTo(ctx context.Context, ucm *webkit.UserContentManager)
}

FilterApplier applies content filters to a UserContentManager. This interface decouples the pool from the filtering package.

type LoadEvent

type LoadEvent int

LoadEvent represents WebKit load events.

type Message

type Message struct {
	Type         string          `json:"type"`
	Payload      json.RawMessage `json:"payload"`
	WebViewID    uint64          `json:"webview_id,omitempty"`
	WebViewIDAlt uint64          `json:"webviewId,omitempty"`
}

Message represents a JS -> Go message envelope sent via postMessage.

type MessageHandler

type MessageHandler interface {
	Handle(ctx context.Context, webviewID WebViewID, payload json.RawMessage) (any, error)
}

MessageHandler handles a decoded message payload.

type MessageHandlerFunc

type MessageHandlerFunc func(ctx context.Context, webviewID WebViewID, payload json.RawMessage) (any, error)

MessageHandlerFunc adapts a function to the MessageHandler interface.

func (MessageHandlerFunc) Handle

func (f MessageHandlerFunc) Handle(ctx context.Context, webviewID WebViewID, payload json.RawMessage) (any, error)

Handle calls f(ctx, webviewID, payload).

type MessageRouter

type MessageRouter struct {
	// contains filtered or unexported fields
}

MessageRouter dispatches script-message events to registered handlers.

func NewMessageRouter

func NewMessageRouter(ctx context.Context) *MessageRouter

NewMessageRouter creates a new message router.

func (*MessageRouter) RegisterHandler

func (r *MessageRouter) RegisterHandler(msgType string, handler MessageHandler) error

RegisterHandler registers a handler for a message type.

func (*MessageRouter) RegisterHandlerWithCallbacks

func (r *MessageRouter) RegisterHandlerWithCallbacks(msgType, callback, errorCallback, worldName string, handler MessageHandler) error

RegisterHandlerWithCallbacks registers a handler and response callbacks. callback is invoked on success, errorCallback (optional) on failure. worldName allows targeting a specific script world (empty for main world).

func (*MessageRouter) SetupMessageHandler

func (r *MessageRouter) SetupMessageHandler(ucm *webkit.UserContentManager, _ string) (uint32, error)

SetupMessageHandler wires the router into the given UserContentManager. It registers the script message handler in the MAIN world (not isolated). WebKit's messageHandlers is only available in main world. The isolated world GUI scripts dispatch CustomEvents to main world, which forwards to this handler.

type PageHandler

type PageHandler interface {
	Handle(req *SchemeRequest) *SchemeResponse
}

PageHandler generates content for a specific page path.

type PageHandlerFunc

type PageHandlerFunc func(req *SchemeRequest) *SchemeResponse

PageHandlerFunc is an adapter to allow use of ordinary functions as PageHandlers.

func (PageHandlerFunc) Handle

type PoolConfig

type PoolConfig struct {
	// MinSize is the minimum number of warm WebViews to maintain.
	MinSize int
	// MaxSize is the maximum number of WebViews to keep in the pool.
	MaxSize int
	// PrewarmCount is the number of WebViews to pre-create on startup.
	PrewarmCount int
	// IdleTimeout is how long idle views stay in the pool before being destroyed.
	IdleTimeout time.Duration
}

PoolConfig configures the WebView pool behavior.

func DefaultPoolConfig

func DefaultPoolConfig() PoolConfig

DefaultPoolConfig returns sensible defaults for the pool.

type PopupRequest

type PopupRequest struct {
	TargetURI     string
	FrameName     string // e.g., "_blank", custom name, or empty
	IsUserGesture bool
	ParentID      WebViewID
}

PopupRequest contains information about a popup window request from the create signal.

type SchemeRequest

type SchemeRequest struct {
	URI    string
	Path   string
	Method string
	Scheme string
	// contains filtered or unexported fields
}

SchemeRequest represents a request to a custom URI scheme.

type SchemeResponse

type SchemeResponse struct {
	Data        []byte
	ContentType string
	StatusCode  int
}

SchemeResponse represents a response to a scheme request.

type SettingsManager

type SettingsManager struct {
	// contains filtered or unexported fields
}

SettingsManager creates and manages WebKit Settings instances from config.

func NewSettingsManager

func NewSettingsManager(ctx context.Context, cfg *config.Config) *SettingsManager

NewSettingsManager creates a new SettingsManager with the given config.

func (*SettingsManager) ApplyToWebView

func (sm *SettingsManager) ApplyToWebView(ctx context.Context, wv *webkit.WebView)

ApplyToWebView applies current settings to an existing WebView. This can be used to update a WebView's settings after config hot-reload.

func (*SettingsManager) CreateSettings

func (sm *SettingsManager) CreateSettings(ctx context.Context) *webkit.Settings

CreateSettings creates a new webkit.Settings instance configured from the current config.

func (*SettingsManager) UpdateFromConfig

func (sm *SettingsManager) UpdateFromConfig(ctx context.Context, cfg *config.Config)

UpdateFromConfig updates the manager with a new config (for hot-reload). Note: This doesn't update already-created Settings instances. New WebViews will use the updated config.

type WebKitContext

type WebKitContext struct {
	// contains filtered or unexported fields
}

WebKitContext manages the shared WebContext and persistent NetworkSession. IMPORTANT: This MUST be initialized before creating any WebViews.

func NewWebKitContext

func NewWebKitContext(ctx context.Context, dataDir, cacheDir string) (*WebKitContext, error)

NewWebKitContext creates and initializes a WebKitContext with a persistent NetworkSession. The dataDir and cacheDir are used for cookie storage, cache, and other persistent data. This MUST be called before creating any WebViews to ensure they use persistent storage.

func (*WebKitContext) CacheDir

func (c *WebKitContext) CacheDir() string

CacheDir returns the cache directory path.

func (*WebKitContext) Close

func (c *WebKitContext) Close() error

Close performs cleanup. Currently a no-op as WebKit handles cleanup internally.

func (*WebKitContext) Context

func (c *WebKitContext) Context() *webkit.WebContext

Context returns the shared WebContext.

func (*WebKitContext) DataDir

func (c *WebKitContext) DataDir() string

DataDir returns the data directory path.

func (*WebKitContext) FaviconDatabase

func (c *WebKitContext) FaviconDatabase() *webkit.FaviconDatabase

FaviconDatabase returns the favicon database for persistent favicon storage.

func (*WebKitContext) IsInitialized

func (c *WebKitContext) IsInitialized() bool

IsInitialized returns true if the context has been successfully initialized.

func (*WebKitContext) NetworkSession

func (c *WebKitContext) NetworkSession() *webkit.NetworkSession

NetworkSession returns the persistent NetworkSession.

func (*WebKitContext) PrefetchDNS

func (c *WebKitContext) PrefetchDNS(hostname string)

PrefetchDNS prefetches DNS for the given hostname to speed up future requests.

type WebView

type WebView struct {

	// Callbacks (set by UI layer)
	OnLoadChanged     func(LoadEvent)
	OnTitleChanged    func(string)
	OnURIChanged      func(string)
	OnProgressChanged func(float64)
	OnFaviconChanged  func(*gdk.Texture) // Called when page favicon changes
	OnClose           func()
	OnCreate          func(PopupRequest) *WebView // Return new WebView or nil to block popup
	OnReadyToShow     func()                      // Called when popup is ready to display
	OnLinkMiddleClick func(uri string) bool       // Return true if handled (blocks navigation)
	// contains filtered or unexported fields
}

WebView wraps webkit.WebView with Go-level state tracking and callbacks.

func LookupWebView

func LookupWebView(id WebViewID) *WebView

LookupWebView returns a WebView by ID from the global registry.

func NewWebView

func NewWebView(ctx context.Context, wkCtx *WebKitContext, settings *SettingsManager) (*WebView, error)

NewWebView creates a new WebView with the given context and settings. Uses the persistent NetworkSession from wkCtx for cookie/data persistence.

func NewWebViewWithRelated

func NewWebViewWithRelated(ctx context.Context, parent *WebView, settings *SettingsManager) (*WebView, error)

NewWebViewWithRelated creates a WebView that shares session/cookies with parent. This is required for popup windows to maintain authentication state.

func (*WebView) AttachFrontend

func (wv *WebView) AttachFrontend(ctx context.Context, injector *ContentInjector, router *MessageRouter) error

AttachFrontend injects scripts/styles and wires the message router once per WebView.

func (*WebView) CanGoBack

func (wv *WebView) CanGoBack() bool

CanGoBack returns true if back navigation is possible.

func (*WebView) CanGoForward

func (wv *WebView) CanGoForward() bool

CanGoForward returns true if forward navigation is possible.

func (*WebView) Close

func (wv *WebView) Close()

Close triggers the close callback as if window.close() was called. This is used for programmatic popup closure (e.g., OAuth auto-close).

func (*WebView) Destroy

func (wv *WebView) Destroy()

Destroy cleans up the WebView resources.

func (*WebView) DisconnectSignals

func (wv *WebView) DisconnectSignals()

DisconnectSignals disconnects all GLib signal handlers from the WebView. This must be called before releasing the WebView to the pool or destroying it to prevent callbacks from firing on freed/pooled WebViews.

func (*WebView) EstimatedProgress

func (wv *WebView) EstimatedProgress() float64

EstimatedProgress returns the estimated load progress (0.0 to 1.0).

func (*WebView) Favicon

func (wv *WebView) Favicon() *gdk.Texture

Favicon returns the current page favicon as a GdkTexture. Returns nil if no favicon is available.

func (*WebView) GetFindController

func (wv *WebView) GetFindController() port.FindController

GetFindController returns the WebKit FindController wrapped in the port interface. The adapter is cached to prevent the Go wrapper from being garbage collected.

func (*WebView) GetZoomLevel

func (wv *WebView) GetZoomLevel() float64

GetZoomLevel returns the current zoom level.

func (*WebView) GoBack

func (wv *WebView) GoBack(ctx context.Context) error

GoBack navigates back in history.

func (*WebView) GoForward

func (wv *WebView) GoForward(ctx context.Context) error

GoForward navigates forward in history.

func (*WebView) ID

func (wv *WebView) ID() WebViewID

ID returns the unique identifier for this WebView.

func (*WebView) IsDestroyed

func (wv *WebView) IsDestroyed() bool

IsDestroyed returns true if the WebView has been destroyed.

func (*WebView) IsLoading

func (wv *WebView) IsLoading() bool

IsLoading returns true if a page is currently loading.

func (*WebView) LoadHTML

func (wv *WebView) LoadHTML(ctx context.Context, content, baseURI string) error

LoadHTML loads HTML content with an optional base URI.

func (*WebView) LoadURI

func (wv *WebView) LoadURI(ctx context.Context, uri string) error

LoadURI loads the given URI.

func (*WebView) Reload

func (wv *WebView) Reload(ctx context.Context) error

Reload reloads the current page.

func (*WebView) ReloadBypassCache

func (wv *WebView) ReloadBypassCache(ctx context.Context) error

ReloadBypassCache reloads the current page, bypassing the cache.

func (*WebView) RunJavaScript

func (wv *WebView) RunJavaScript(ctx context.Context, script, worldName string)

RunJavaScript executes script in the specified world (empty for main world). This is fire-and-forget: it does not block and errors are logged asynchronously. Safe to call from any context including GTK signal handlers.

func (*WebView) SetCallbacks

func (wv *WebView) SetCallbacks(callbacks *port.WebViewCallbacks)

SetCallbacks registers callback handlers for WebView events. Pass nil to clear all callbacks.

func (*WebView) SetZoomLevel

func (wv *WebView) SetZoomLevel(ctx context.Context, level float64) error

SetZoomLevel sets the zoom level (1.0 = 100%).

func (*WebView) ShowDevTools

func (wv *WebView) ShowDevTools() error

ShowDevTools opens the WebKit inspector/developer tools.

func (*WebView) State

func (wv *WebView) State() port.WebViewState

State returns the current WebView state as a snapshot.

func (*WebView) Stop

func (wv *WebView) Stop(ctx context.Context) error

Stop stops the current load operation.

func (*WebView) Title

func (wv *WebView) Title() string

Title returns the current page title.

func (*WebView) URI

func (wv *WebView) URI() string

URI returns the current URI.

func (*WebView) UserContentManager

func (wv *WebView) UserContentManager() *webkit.UserContentManager

UserContentManager returns the content manager associated with this WebView.

func (*WebView) Widget

func (wv *WebView) Widget() *webkit.WebView

Widget returns the underlying webkit.WebView for GTK embedding.

type WebViewFactory

type WebViewFactory struct {
	// contains filtered or unexported fields
}

WebViewFactory creates WebView instances for the application. It supports creating regular WebViews (optionally via pool) and related WebViews that share session/cookies with a parent (for popups).

func NewWebViewFactory

func NewWebViewFactory(
	wkCtx *WebKitContext,
	settings *SettingsManager,
	pool *WebViewPool,
	injector *ContentInjector,
	router *MessageRouter,
) *WebViewFactory

NewWebViewFactory creates a new WebViewFactory. The pool parameter is optional; if nil, WebViews are created directly.

func (*WebViewFactory) Create

func (f *WebViewFactory) Create(ctx context.Context) (*WebView, error)

Create creates a new WebView instance. If a pool is configured, it will try to acquire from the pool first.

func (*WebViewFactory) CreateRelated

func (f *WebViewFactory) CreateRelated(ctx context.Context, parentID port.WebViewID) (*WebView, error)

CreateRelated creates a WebView that shares session/cookies with the parent. This is required for popup windows to maintain authentication state (OAuth). Related WebViews bypass the pool since they must be linked to a specific parent.

func (*WebViewFactory) Release

func (f *WebViewFactory) Release(ctx context.Context, wv *WebView)

Release returns a WebView to the pool if available, otherwise destroys it. Related WebViews (popups) should be destroyed directly, not released to pool.

func (*WebViewFactory) SetFilterApplier

func (f *WebViewFactory) SetFilterApplier(applier FilterApplier)

SetFilterApplier sets the content filter applier. Filters will be applied to all newly created WebViews.

type WebViewID

type WebViewID = port.WebViewID

WebViewID is an alias to port.WebViewID for clean architecture compliance. Infrastructure layer uses the type defined in the application port.

type WebViewPool

type WebViewPool struct {
	// contains filtered or unexported fields
}

WebViewPool manages a pool of pre-created WebViews for fast tab creation.

func NewWebViewPool

func NewWebViewPool(
	ctx context.Context,
	wkCtx *WebKitContext,
	settings *SettingsManager,
	cfg PoolConfig,
	injector *ContentInjector,
	router *MessageRouter,
) *WebViewPool

NewWebViewPool creates a new WebView pool.

func (*WebViewPool) Acquire

func (p *WebViewPool) Acquire(ctx context.Context) (*WebView, error)

Acquire gets a WebView from the pool or creates a new one.

func (*WebViewPool) Close

func (p *WebViewPool) Close(ctx context.Context)

Close shuts down the pool and destroys all pooled WebViews.

func (*WebViewPool) Prewarm

func (p *WebViewPool) Prewarm(ctx context.Context, count int)

Prewarm creates WebViews synchronously to populate the pool. Must be called from the GTK main thread (after GTK application is initialized).

func (*WebViewPool) Release

func (p *WebViewPool) Release(ctx context.Context, wv *WebView)

Release returns a WebView to the pool. For safety, we always destroy and never pool WebViews that have been used. This prevents crashes from GLib signals firing after the widget tree is modified. The pool is only used for prewarmed WebViews that haven't been attached to UI yet.

func (*WebViewPool) SetFilterApplier

func (p *WebViewPool) SetFilterApplier(applier FilterApplier)

SetFilterApplier sets the content filter applier. Filters will be applied to all newly created WebViews.

func (*WebViewPool) Size

func (p *WebViewPool) Size() int

Size returns the current number of WebViews in the pool.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL