port

package
v0.28.0 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package port defines interfaces for infrastructure adapters.

Package port defines application-layer interfaces for external capabilities. Ports abstract infrastructure concerns, allowing the application layer to remain independent of specific implementations (WebKit, GTK, etc.).

Package port defines interfaces for external dependencies.

Package port defines interfaces for external dependencies.

Package port defines interfaces for external dependencies.

Package port defines interfaces for external dependencies.

Package port defines interfaces for external dependencies.

Package port defines application-layer interfaces for external capabilities. Ports abstract infrastructure concerns, allowing the application layer to remain independent of specific implementations (WebKit, GTK, etc.).

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrPkgConfigMissing indicates pkg-config is not available on the host.
	ErrPkgConfigMissing = errors.New("pkg-config missing")
	// ErrPkgConfigPackageMissing indicates the requested .pc package was not found.
	ErrPkgConfigPackageMissing = errors.New("pkg-config package missing")
)
View Source
var ErrUpdateCheckTransient = errors.New("transient update check failure")

ErrUpdateCheckTransient indicates a temporary update-check failure that should not be treated as actionable.

Functions

This section is empty.

Types

type AccentKeyHandler added in v0.28.0

type AccentKeyHandler interface {
	OnKeyPressed(ctx context.Context, char rune, shiftHeld bool) bool
	OnKeyReleased(ctx context.Context, char rune)
}

AccentKeyHandler receives accent/dead-key events from the WebView JS bridge.

type AccentPickerUI added in v0.23.0

type AccentPickerUI interface {
	// Show displays the accent picker with the given accent variants.
	// selectedCallback is called when the user selects an accent.
	// cancelCallback is called when the user cancels (Escape key).
	Show(accents []rune, selectedCallback func(accent rune), cancelCallback func())

	// Hide hides the accent picker.
	Hide()

	// IsVisible returns true if the accent picker is currently visible.
	IsVisible() bool
}

AccentPickerUI defines the interface for displaying an accent selection overlay. The picker shows a list of accented characters and allows the user to select one via arrow keys, number keys (1-9), or Enter.

type AllKeybindingsResetter added in v0.28.0

type AllKeybindingsResetter interface {
	Execute(ctx context.Context) error
}

AllKeybindingsResetter resets all keybindings to defaults (narrow interface for the handler).

type AutoCopyConfig added in v0.28.0

type AutoCopyConfig interface {
	IsAutoCopyEnabled() bool
}

AutoCopyConfig provides the clipboard auto-copy setting.

type Cache added in v0.20.1

type Cache[K comparable, V any] interface {
	// Get retrieves a value by key. Returns the value and true if found,
	// or the zero value and false if not found.
	Get(key K) (V, bool)

	// Set stores a value for the given key. If the cache is at capacity,
	// the least recently used entry may be evicted.
	Set(key K, value V)

	// Remove deletes a key from the cache.
	Remove(key K)

	// Len returns the number of items currently in the cache.
	Len() int
}

Cache is a generic cache interface for storing key-value pairs. Implementations should be thread-safe.

type Clipboard

type Clipboard interface {
	// WriteText copies text to the clipboard.
	WriteText(ctx context.Context, text string) error

	// ReadText reads text from the clipboard.
	// Returns empty string if clipboard is empty or contains non-text data.
	ReadText(ctx context.Context) (string, error)

	// Clear clears the clipboard contents.
	Clear(ctx context.Context) error

	// HasText returns true if the clipboard contains text data.
	HasText(ctx context.Context) (bool, error)
}

Clipboard defines the port interface for clipboard operations. This abstracts platform-specific clipboard implementations (GTK, etc.).

type ColorPalette

type ColorPalette struct {
	Background     string `json:"background"`
	Surface        string `json:"surface"`
	SurfaceVariant string `json:"surface_variant"`
	Text           string `json:"text"`
	Muted          string `json:"muted"`
	Accent         string `json:"accent"`
	Border         string `json:"border"`
}

type ColorSchemeDetector added in v0.23.0

type ColorSchemeDetector interface {
	// Name returns a human-readable name for this detector.
	Name() string

	// Priority returns the detector's priority.
	// Higher values = higher priority (checked first).
	// Recommended ranges:
	//   - 100+: Runtime detectors (libadwaita, GTK Settings)
	//   -  50+: Config file detectors
	//   -  10+: Fallback detectors (gsettings, env vars)
	Priority() int

	// Available returns true if this detector can be used.
	// For example, libadwaita detector returns false before adw.Init().
	Available() bool

	// Detect returns the detected preference and whether detection succeeded.
	// Returns (preference, true) on success, (_, false) if unavailable or detection failed.
	Detect() (prefersDark bool, ok bool)
}

ColorSchemeDetector detects the system's color scheme preference. Multiple detectors can be registered with different priorities.

type ColorSchemePreference added in v0.23.0

type ColorSchemePreference struct {
	// PrefersDark indicates whether dark mode is preferred.
	PrefersDark bool

	// Source identifies which detector provided this preference.
	// Empty string means fallback was used.
	Source string
}

ColorSchemePreference represents the resolved color scheme preference.

type ColorSchemeResolver added in v0.23.0

type ColorSchemeResolver interface {
	// Resolve returns the current color scheme preference.
	// It checks config for explicit overrides, then queries detectors by priority.
	// If all detectors fail, defaults to dark mode.
	Resolve() ColorSchemePreference

	// RegisterDetector adds a detector to the resolver.
	// Safe to call at any time; the resolver re-evaluates on next Resolve().
	RegisterDetector(detector ColorSchemeDetector)

	// Refresh forces re-evaluation of the color scheme.
	// Call this after registering new detectors or when system preferences change.
	// Returns the new preference.
	Refresh() ColorSchemePreference

	// OnChange registers a callback for color scheme changes.
	// The callback is invoked when Refresh() results in a different preference.
	// Returns a function to unregister the callback.
	OnChange(callback func(ColorSchemePreference)) func()
}

ColorSchemeResolver resolves the effective color scheme preference. It manages multiple detectors and respects config overrides.

type ConfigMigrator added in v0.22.0

type ConfigMigrator interface {
	// CheckMigration checks if user config is missing any default keys.
	// Returns nil if no migration is needed (config file doesn't exist or is complete).
	CheckMigration() (*MigrationResult, error)

	// DetectChanges analyzes user config and returns all detected changes.
	// This provides a detailed diff-like view of what migration would do.
	DetectChanges() ([]KeyChange, error)

	// Migrate adds missing default keys and removes deprecated keys from the user's config file.
	// Returns the list of keys that were added/renamed/removed.
	Migrate() ([]string, error)

	// GetKeyInfo returns detailed information about a config key.
	GetKeyInfo(key string) KeyInfo

	// GetConfigFile returns the path to the user's config file.
	GetConfigFile() (string, error)
}

ConfigMigrator checks for and applies config migrations.

type ConfigSchemaProvider added in v0.22.0

type ConfigSchemaProvider interface {
	// GetSchema returns all configuration keys with their metadata.
	GetSchema() []entity.ConfigKeyInfo
}

ConfigSchemaProvider provides configuration schema information.

type ConfigTransformer added in v0.26.0

type ConfigTransformer interface {
	// TransformLegacyActions converts old-format action bindings (slices)
	// to new ActionBinding format (map with keys and desc).
	// Modifies the rawConfig map in place.
	TransformLegacyActions(rawConfig map[string]any)
}

ConfigTransformer transforms legacy config formats to current format.

type ContentInjector

type ContentInjector interface {
	// InjectThemeCSS injects CSS variables into the page for theming.
	// The css parameter should contain CSS custom property declarations.
	InjectThemeCSS(ctx context.Context, css string) error

	// InjectFindHighlightCSS injects CSS used to style in-page find highlights.
	InjectFindHighlightCSS(ctx context.Context, css string) error

	// RefreshScripts clears and re-injects user scripts for a single WebView.
	// Called when appearance settings change so future navigations pick up latest values.
	// Returns an error if the refresh could not be performed.
	RefreshScripts(ctx context.Context, wv WebView) error
}

ContentInjector defines the port interface for injecting scripts and styles into web views. This abstracts platform-specific content injection implementations (WebKit, etc.).

type CookiePolicy added in v0.28.0

type CookiePolicy string

CookiePolicy controls cookie acceptance behavior for the engine's network session.

const (
	// CookiePolicyAlways accepts all cookies.
	CookiePolicyAlways CookiePolicy = "always"
	// CookiePolicyNoThirdParty rejects third-party cookies.
	CookiePolicyNoThirdParty CookiePolicy = "no_third_party"
	// CookiePolicyNever rejects all cookies.
	CookiePolicyNever CookiePolicy = "never"
)

type DatabaseProvider added in v0.22.0

type DatabaseProvider interface {
	// DB returns the database connection, initializing it if necessary.
	// Returns an error if initialization fails.
	DB(ctx context.Context) (*sql.DB, error)

	// Close closes the database connection if it was initialized.
	Close() error

	// IsInitialized returns true if the database has been initialized.
	IsInitialized() bool
}

DatabaseProvider provides access to the database connection. Implementations may initialize the database lazily on first access.

Currently used by the lazy repository infrastructure (sqlite.LazyDB and lazy_repos.go), which is kept for potential future optimization scenarios where deferring database initialization past first paint provides latency benefits.

type DesktopIntegration

type DesktopIntegration interface {
	// GetStatus checks the current desktop integration state.
	GetStatus(ctx context.Context) (*DesktopIntegrationStatus, error)

	// InstallDesktopFile writes the desktop file to XDG applications directory.
	// Returns the path where the file was installed.
	// Idempotent: safe to call multiple times.
	InstallDesktopFile(ctx context.Context) (string, error)

	// InstallIcon writes the icon file to XDG icons directory.
	// Returns the path where the icon was installed.
	// Idempotent: safe to call multiple times.
	InstallIcon(ctx context.Context, svgData []byte) (string, error)

	// RemoveDesktopFile removes the desktop file from XDG applications directory.
	// Idempotent: returns nil if file doesn't exist.
	RemoveDesktopFile(ctx context.Context) error

	// RemoveIcon removes the icon file from XDG icons directory.
	// Idempotent: returns nil if file doesn't exist.
	RemoveIcon(ctx context.Context) error

	// SetAsDefaultBrowser sets dumber as the default web browser using xdg-settings.
	// Returns error if desktop file is not installed.
	SetAsDefaultBrowser(ctx context.Context) error

	// UnsetAsDefaultBrowser resets default browser if dumber is currently default.
	// Idempotent: returns nil if not currently default.
	UnsetAsDefaultBrowser(ctx context.Context) error
}

DesktopIntegration provides desktop environment integration operations.

type DesktopIntegrationStatus

type DesktopIntegrationStatus struct {
	DesktopFileInstalled bool
	DesktopFilePath      string
	IconInstalled        bool
	IconFilePath         string
	IsDefaultBrowser     bool
	ExecutablePath       string
}

DesktopIntegrationStatus represents the current state of desktop integration.

type DevToolsOpener added in v0.28.0

type DevToolsOpener interface {
	OpenDevTools()
}

DevToolsOpener is an optional capability for WebViews that support developer tools.

type DiffFormatter added in v0.22.0

type DiffFormatter interface {
	// FormatChangesAsDiff returns changes formatted as a diff-like string for display.
	FormatChangesAsDiff(changes []KeyChange) string
}

DiffFormatter formats config changes for display.

type DownloadEvent added in v0.25.0

type DownloadEvent struct {
	Type        DownloadEventType
	Filename    string
	Destination string
	Error       error // Set when Type is DownloadEventFailed
}

DownloadEvent contains information about a download event.

type DownloadEventHandler added in v0.25.0

type DownloadEventHandler interface {
	OnDownloadEvent(ctx context.Context, event DownloadEvent)
}

DownloadEventHandler receives download event notifications.

type DownloadEventType added in v0.25.0

type DownloadEventType int

DownloadEventType represents the type of download event.

const (
	// DownloadEventStarted indicates a download has begun.
	DownloadEventStarted DownloadEventType = iota
	// DownloadEventFinished indicates a download completed successfully.
	DownloadEventFinished
	// DownloadEventFailed indicates a download failed.
	DownloadEventFailed
)

type DownloadPrepareInput added in v0.28.0

type DownloadPrepareInput struct {
	SuggestedFilename string
	Response          DownloadResponse
	DownloadDir       string
}

DownloadPrepareInput matches usecase.PrepareDownloadInput.

type DownloadPrepareOutput added in v0.28.0

type DownloadPrepareOutput struct {
	Filename        string
	DestinationPath string
}

DownloadPrepareOutput matches usecase.PrepareDownloadOutput.

type DownloadPreparer added in v0.28.0

type DownloadPreparer interface {
	Execute(ctx context.Context, input DownloadPrepareInput) *DownloadPrepareOutput
}

DownloadPreparer resolves download destination paths with deduplication.

type DownloadResponse added in v0.26.0

type DownloadResponse interface {
	GetMimeType() string
	GetSuggestedFilename() string
	GetUri() string
}

DownloadResponse provides access to response metadata for downloads. This abstracts the WebKit URIResponse to allow testing without CGO.

type Engine added in v0.28.0

type Engine interface {
	// Factory returns the WebViewFactory for creating new WebView instances.
	Factory() WebViewFactory

	// Pool returns the WebViewPool for acquiring pre-warmed WebView instances.
	Pool() WebViewPool

	// ContentInjector returns the ContentInjector for injecting scripts and styles.
	ContentInjector() ContentInjector

	// SettingsApplier returns the SettingsApplier for applying browser settings.
	SettingsApplier() SettingsApplier

	// FilterApplier returns the FilterApplier for applying content filters.
	// Returns nil if content filtering is not supported by this engine.
	FilterApplier() FilterApplier

	// FaviconDatabase returns the FaviconDatabase for async favicon lookups.
	FaviconDatabase() FaviconDatabase

	// InternalSchemePath returns the URI scheme used for internal app resources.
	InternalSchemePath() string

	// Close releases all resources held by the engine.
	Close() error

	// RegisterHandlers registers all WebUI message bridge handlers.
	RegisterHandlers(ctx context.Context, deps HandlerDependencies) error

	// RegisterAccentHandlers registers accent/dead-key input handlers.
	RegisterAccentHandlers(ctx context.Context, handler AccentKeyHandler) error

	// ConfigureDownloads sets up download handling for this engine.
	ConfigureDownloads(ctx context.Context, downloadPath string, eventHandler DownloadEventHandler, preparer DownloadPreparer) error

	// OnToolkitReady is called after the UI toolkit has initialized.
	OnToolkitReady(ctx context.Context) error

	// UpdateAppearance updates default background color for new WebViews.
	UpdateAppearance(ctx context.Context, r, g, b, alpha float64) error

	// UpdateSettings applies runtime config changes to engine internals.
	UpdateSettings(ctx context.Context, update EngineSettingsUpdate) error

	// SetHandlerContext sets the base context for message handler dispatch.
	SetHandlerContext(ctx context.Context)
}

Engine is the top-level interface for a browser engine implementation. It provides access to all engine subsystems and manages the lifecycle of the underlying browser context.

Engines are fully initialized by their constructor (e.g., webkit.NewEngine). There is no separate Init step.

type EngineOptions added in v0.28.0

type EngineOptions struct {
	// DataDir is the directory for persistent data (cookies, storage, etc.).
	DataDir string

	// CacheDir is the directory for cache data.
	CacheDir string

	// CookiePolicy controls cookie acceptance behavior.
	// Empty value means runtime defaults are used.
	CookiePolicy CookiePolicy

	// WebProcessMemory configures memory pressure for web processes.
	// nil means use engine defaults.
	WebProcessMemory *MemoryPressureConfig

	// NetworkProcessMemory configures memory pressure for the network process.
	// nil means use engine defaults.
	NetworkProcessMemory *MemoryPressureConfig
}

EngineOptions configures engine initialization.

type EngineSettingsUpdate added in v0.28.0

type EngineSettingsUpdate struct {
	// Raw holds the implementation-specific config.
	// WebKit engine expects *infrastructure/config.Config.
	Raw any //nolint:iface // intentional: see type comment above
}

EngineSettingsUpdate carries a runtime config change to the engine.

The Raw field holds the implementation-specific config object; each engine implementation type-asserts it to its concrete config type (e.g. the WebKit engine asserts to *infrastructure/config.Config).

This is the only intentional use of `any` in the Engine port. A fully typed approach would require either moving the entire config schema into the domain layer (a large refactor) or defining a SettingsProvider interface — which would itself reduce to `any` because callers would embed engine-specific data behind an empty interface. Until the config schema is promoted to domain, the type assertion in the engine implementation is the least-invasive option.

type EntryInputTarget added in v0.28.0

type EntryInputTarget interface {
	TextInputTarget
	IsGTKEntryTarget() bool
}

EntryInputTarget is a marker interface implemented by text input targets that wrap a native entry widget. Used for keyboard routing decisions.

type FaviconDatabase added in v0.28.0

type FaviconDatabase interface {
	// GetFaviconAsync retrieves the favicon for the given page URL asynchronously.
	// The callback is invoked with the favicon Texture when available.
	GetFaviconAsync(pageURL string, callback func(Texture))
}

FaviconDatabase defines the port interface for async favicon lookups. Implementations retrieve favicons from an engine-managed database and deliver them via callback on the main thread.

type FaviconService added in v0.28.0

type FaviconService interface {
	GetCached(domain string) ([]byte, bool)
	Get(ctx context.Context, domain string) ([]byte, error)
	DiskPathPNG(domain string) string
	HasPNGOnDisk(domain string) bool
	HasPNGSizedOnDisk(domain string, size int) bool
	EnsureSizedPNG(ctx context.Context, domain string, size int) error
	EnsureCacheDir() error
	// EnsureDiskCache ensures a favicon is written to the on-disk cache for the given
	// domain. It is intentionally fire-and-forget: any errors are logged internally by
	// the implementation and are not returned to the caller.
	EnsureDiskCache(ctx context.Context, domain string)
	Close()
}

FaviconService provides favicon retrieval and caching.

type FileSystem

type FileSystem interface {
	Exists(ctx context.Context, path string) (bool, error)
	IsDirectory(ctx context.Context, path string) (bool, error)
	GetSize(ctx context.Context, path string) (int64, error)
	RemoveAll(ctx context.Context, path string) error
}

FileSystem provides file system operations for the application layer.

type FilterApplier added in v0.28.0

type FilterApplier interface {
	// ApplyToAll applies content filters to all provided WebView instances.
	ApplyToAll(ctx context.Context, webviews []WebView)
}

FilterApplier defines the port interface for applying content filters to WebViews. Implementations configure content blocking rules on a set of WebView instances. This interface is optional; Engine.FilterApplier() returns nil if not supported.

type FilterManager added in v0.28.0

type FilterManager interface {
	SetStatusCallback(fn func(FilterStatus))
	LoadAsync(ctx context.Context)
}

FilterManager manages content filters.

type FilterManagerProvider added in v0.28.0

type FilterManagerProvider interface {
	InternalFilterManager() FilterManager
}

FilterManagerProvider is an optional capability interface for engines that support content filter management (e.g. ad blocking). Callers should type-assert the Engine to FilterManagerProvider rather than a concrete engine type.

type FilterState added in v0.28.0

type FilterState string

FilterState represents the current state of the content filter system.

const (
	// FilterStateUninitialized means the filter manager has not been initialized yet.
	FilterStateUninitialized FilterState = "uninitialized"
	// FilterStateLoading means filters are being downloaded or compiled.
	FilterStateLoading FilterState = "loading"
	// FilterStateActive means filters are loaded and active.
	FilterStateActive FilterState = "active"
	// FilterStateDisabled means filtering is disabled by configuration.
	FilterStateDisabled FilterState = "disabled"
	// FilterStateError means an error occurred during filter loading.
	FilterStateError FilterState = "error"
)

type FilterStatus added in v0.28.0

type FilterStatus struct {
	State   FilterState
	Message string
	Version string
}

FilterStatus represents the current status of the content filter system. Used for UI toast notifications and status reporting.

type FindController

type FindController interface {
	Search(text string, options FindOptions, maxMatches uint)
	CountMatches(text string, options FindOptions, maxMatches uint)
	SearchNext()
	SearchPrevious()
	SearchFinish()
	GetSearchText() string

	// Signal connections
	OnFoundText(callback func(matchCount uint)) uint
	OnFailedToFindText(callback func()) uint
	OnCountedMatches(callback func(matchCount uint)) uint
	DisconnectSignal(id uint)
}

FindController abstracts WebKit's FindController for clean architecture.

type FindOptions

type FindOptions struct {
	CaseInsensitive bool
	AtWordStarts    bool
	WrapAround      bool
}

FindOptions configures search behavior.

type Focusable added in v0.28.0

type Focusable interface {
	Focus(ctx context.Context)
}

Focusable is optionally implemented by text input targets that can restore focus after the accent picker closes.

type FocusedInputProvider added in v0.23.0

type FocusedInputProvider interface {
	// GetFocusedInput returns the currently focused text input target.
	// Returns nil if no text input has focus.
	GetFocusedInput() TextInputTarget

	// SetFocusedInput sets the currently focused text input target.
	// Pass nil to clear focus.
	SetFocusedInput(target TextInputTarget)
}

FocusedInputProvider tracks which text input target currently has focus. This allows the accent picker to insert text into the correct input field.

type FontCategory added in v0.24.0

type FontCategory string

FontCategory represents a category of fonts for fallback selection.

const (
	// FontCategorySansSerif is for sans-serif fonts (UI text).
	FontCategorySansSerif FontCategory = "sans-serif"
	// FontCategorySerif is for serif fonts (reading content).
	FontCategorySerif FontCategory = "serif"
	// FontCategoryMonospace is for monospace fonts (code, fixed-width).
	FontCategoryMonospace FontCategory = "monospace"
)

type FontDetector added in v0.24.0

type FontDetector interface {
	// GetAvailableFonts returns a list of font family names installed on the system.
	// Returns an error if font detection is not available (e.g., fc-list missing).
	GetAvailableFonts(ctx context.Context) ([]string, error)

	// SelectBestFont returns the first available font from the fallback chain,
	// or the generic CSS fallback (e.g., "sans-serif") if none are installed.
	// The category is used to determine the generic fallback.
	SelectBestFont(ctx context.Context, category FontCategory, fallbackChain []string) string

	// IsAvailable returns true if font detection is available on this system.
	IsAvailable(ctx context.Context) bool
}

FontDetector detects available system fonts and selects the best font from a fallback chain. This is used during first-run config creation to ensure configured fonts are actually installed.

type GPUVendor

type GPUVendor string

GPUVendor identifies the GPU manufacturer for vendor-specific optimizations.

const (
	// GPUVendorAMD represents AMD/ATI GPUs (vendor ID 0x1002)
	GPUVendorAMD GPUVendor = "amd"
	// GPUVendorIntel represents Intel integrated/discrete GPUs (vendor ID 0x8086)
	GPUVendorIntel GPUVendor = "intel"
	// GPUVendorNVIDIA represents NVIDIA GPUs (vendor ID 0x10de)
	GPUVendorNVIDIA GPUVendor = "nvidia"
	// GPUVendorUnknown represents undetected or unsupported GPUs
	GPUVendorUnknown GPUVendor = "unknown"
)

type HandlerDependencies added in v0.28.0

type HandlerDependencies struct {
	HistoryUC         HomepageHistory
	FavoritesUC       HomepageFavorites
	Clipboard         Clipboard
	AutoCopyConfig    AutoCopyConfig
	OnClipboardCopied func(textLen int)
}

HandlerDependencies holds use cases needed by WebUI message handlers.

type HardwareInfo added in v0.23.0

type HardwareInfo struct {
	// CPU information
	CPUCores   int // Number of physical CPU cores
	CPUThreads int // Number of logical CPU threads (with hyperthreading)

	// Memory information (in bytes)
	TotalRAM     uint64 // Total system RAM
	AvailableRAM uint64 // Currently available RAM

	// GPU information
	GPUVendor GPUVendor // AMD, Intel, NVIDIA, or Unknown
	GPUName   string    // Human-readable GPU name (e.g., "AMD Radeon RX 9070 XT")
	VRAM      uint64    // Video memory in bytes (0 if unknown)
}

HardwareInfo contains detected system hardware specifications. Used for performance profile auto-tuning.

func (HardwareInfo) CPUCoresOrDefault added in v0.23.0

func (h HardwareInfo) CPUCoresOrDefault(fallback int) int

CPUCoresOrDefault returns CPUCores if > 0, otherwise returns the fallback.

func (HardwareInfo) CPUThreadsOrDefault added in v0.23.0

func (h HardwareInfo) CPUThreadsOrDefault(fallback int) int

CPUThreadsOrDefault returns CPUThreads if > 0, otherwise returns the fallback.

func (HardwareInfo) HasDedicatedGPU added in v0.23.0

func (h HardwareInfo) HasDedicatedGPU() bool

HasDedicatedGPU returns true if a discrete GPU with VRAM was detected.

func (HardwareInfo) TotalRAMMB added in v0.23.0

func (h HardwareInfo) TotalRAMMB() int

TotalRAMMB returns total RAM in megabytes. Returns 0 if RAM exceeds int range (unlikely on any real system).

func (HardwareInfo) VRAMMB added in v0.23.0

func (h HardwareInfo) VRAMMB() int

VRAMMB returns VRAM in megabytes. Returns 0 if VRAM exceeds int range (unlikely on any real system).

type HardwareSurveyor added in v0.23.0

type HardwareSurveyor interface {
	// Survey detects and returns hardware information.
	// This should be called once at startup and cached.
	Survey(ctx context.Context) HardwareInfo
}

HardwareSurveyor detects system hardware specifications.

type HistorySearchInput added in v0.28.0

type HistorySearchInput struct {
	Query string
	Limit int
}

HistorySearchInput holds search parameters (moved from usecase.SearchInput).

type HistorySearchOutput added in v0.28.0

type HistorySearchOutput struct {
	Matches []entity.HistoryMatch
}

HistorySearchOutput holds search results (moved from usecase.SearchOutput).

type HomepageFavorites added in v0.28.0

type HomepageFavorites interface {
	GetAll(ctx context.Context) ([]*entity.Favorite, error)
	SetShortcut(ctx context.Context, id entity.FavoriteID, key *int) error
	GetByShortcut(ctx context.Context, key int) (*entity.Favorite, error)
	Move(ctx context.Context, id entity.FavoriteID, folderID *entity.FolderID) error
	GetAllFolders(ctx context.Context) ([]*entity.Folder, error)
	CreateFolder(ctx context.Context, name string, parentID *entity.FolderID) (*entity.Folder, error)
	DeleteFolder(ctx context.Context, id entity.FolderID) error
	UpdateFolder(ctx context.Context, id entity.FolderID, name, icon string) error
	GetAllTags(ctx context.Context) ([]*entity.Tag, error)
	AddTag(ctx context.Context, name, color string) (*entity.Tag, error)
	DeleteTag(ctx context.Context, id entity.TagID) error
	UpdateTag(ctx context.Context, id entity.TagID, name, color string) error
	TagFavorite(ctx context.Context, favID entity.FavoriteID, tagID entity.TagID) error
	UntagFavorite(ctx context.Context, favID entity.FavoriteID, tagID entity.TagID) error
}

HomepageFavorites provides favorites/folders/tags operations needed by the WebUI homepage handlers.

type HomepageHistory added in v0.28.0

type HomepageHistory interface {
	GetRecent(ctx context.Context, limit, offset int) ([]*entity.HistoryEntry, error)
	Search(ctx context.Context, input HistorySearchInput) (*HistorySearchOutput, error)
	Delete(ctx context.Context, id int64) error
	ClearAll(ctx context.Context) error
	ClearOlderThan(ctx context.Context, before time.Time) error
	GetAnalytics(ctx context.Context) (*entity.HistoryAnalytics, error)
	GetDomainStats(ctx context.Context, limit int) ([]*entity.DomainStat, error)
	DeleteByDomain(ctx context.Context, domain string) error
}

HomepageHistory provides history operations needed by the WebUI homepage handlers.

type IdleInhibitor added in v0.20.1

type IdleInhibitor interface {
	// Inhibit increments the inhibit refcount. First call activates inhibition.
	// Safe to call multiple times (refcounted).
	Inhibit(ctx context.Context, reason string) error

	// Uninhibit decrements the refcount. When zero, releases inhibition.
	// Safe to call even if not currently inhibited (no-op).
	Uninhibit(ctx context.Context) error

	// IsInhibited returns true if currently inhibiting idle.
	IsInhibited() bool

	// Close releases any held resources. Should be called on application shutdown.
	Close() error
}

IdleInhibitor prevents system idle/screensaver during fullscreen video playback. Implementations use refcounting internally - multiple Inhibit calls require matching Uninhibit calls before inhibition is released.

type KeyChange added in v0.22.0

type KeyChange struct {
	Type     KeyChangeType // Type of change
	OldKey   string        // Old key name (for removed/renamed)
	NewKey   string        // New key name (for added/renamed)
	OldValue string        // Old value (for renamed/consolidated)
	NewValue string        // New/default value
}

KeyChange represents a detected change between user config and defaults.

type KeyChangeType added in v0.22.0

type KeyChangeType int

KeyChangeType indicates the type of config key change.

const (
	// KeyChangeAdded indicates a new key was added to defaults.
	KeyChangeAdded KeyChangeType = iota
	// KeyChangeRemoved indicates a key in user config no longer exists in defaults.
	KeyChangeRemoved
	// KeyChangeRenamed indicates a key was renamed (detected via similarity).
	KeyChangeRenamed
)

func (KeyChangeType) String added in v0.22.0

func (t KeyChangeType) String() string

String returns a display symbol for the change type.

type KeyInfo added in v0.22.0

type KeyInfo struct {
	// Key is the dot-notation key path (e.g., "update.enable_on_startup").
	Key string
	// Type is the Go type of the value (e.g., "bool", "int", "string").
	Type string
	// DefaultValue is a string representation of the default value.
	DefaultValue string
}

KeyInfo contains metadata about a config key for display purposes.

type KeybindingConflict added in v0.26.0

type KeybindingConflict struct {
	ConflictingAction string `json:"conflicting_action"`
	ConflictingMode   string `json:"conflicting_mode"`
	Key               string `json:"key"`
}

KeybindingConflict represents a detected conflict.

type KeybindingEntry added in v0.26.0

type KeybindingEntry struct {
	Action      string   `json:"action"`
	Description string   `json:"description"`
	Keys        []string `json:"keys"`
	DefaultKeys []string `json:"default_keys"`
	IsCustom    bool     `json:"is_custom"`
}

KeybindingEntry represents a single keybinding for the UI.

type KeybindingGroup added in v0.26.0

type KeybindingGroup struct {
	Mode        string            `json:"mode"`
	DisplayName string            `json:"display_name"`
	Bindings    []KeybindingEntry `json:"bindings"`
	Activation  string            `json:"activation,omitempty"`
}

KeybindingGroup represents keybindings for a mode.

type KeybindingResetter added in v0.28.0

type KeybindingResetter interface {
	Execute(ctx context.Context, req ResetKeybindingRequest) error
}

KeybindingResetter resets a single keybinding to default (narrow interface for the handler).

type KeybindingSetter added in v0.28.0

type KeybindingSetter interface {
	Execute(ctx context.Context, req SetKeybindingRequest) (SetKeybindingResponse, error)
}

KeybindingSetter updates a single keybinding (narrow interface for the handler).

type KeybindingsConfig added in v0.26.0

type KeybindingsConfig struct {
	Groups []KeybindingGroup `json:"groups"`
}

KeybindingsConfig represents all keybindings for the UI.

type KeybindingsGetter added in v0.28.0

type KeybindingsGetter interface {
	Execute(ctx context.Context) (KeybindingsConfig, error)
}

KeybindingsGetter retrieves all keybindings (narrow interface for the handler).

type KeybindingsProvider added in v0.26.0

type KeybindingsProvider interface {
	GetKeybindings(ctx context.Context) (KeybindingsConfig, error)
	GetDefaultKeybindings(ctx context.Context) (KeybindingsConfig, error)
	CheckConflicts(ctx context.Context, mode, action string, keys []string) ([]KeybindingConflict, error)
}

KeybindingsProvider provides keybinding configuration data.

type KeybindingsSaver added in v0.26.0

type KeybindingsSaver interface {
	SetKeybinding(ctx context.Context, req SetKeybindingRequest) error
	ResetKeybinding(ctx context.Context, req ResetKeybindingRequest) error
	ResetAllKeybindings(ctx context.Context) error
}

KeybindingsSaver persists keybinding changes.

type LoadEvent

type LoadEvent int

LoadEvent represents page load state transitions.

const (
	// LoadStarted indicates navigation has begun.
	LoadStarted LoadEvent = iota
	// LoadRedirected indicates a redirect occurred.
	LoadRedirected
	// LoadCommitted indicates content is being received.
	LoadCommitted
	// LoadFinished indicates the page has fully loaded.
	LoadFinished
)

func (LoadEvent) String

func (e LoadEvent) String() string

String returns a human-readable representation of the load event.

type LoggerFromContext added in v0.27.0

type LoggerFromContext func(ctx context.Context) *zerolog.Logger

LoggerFromContext resolves the current request/session logger from context. Use cases depend on this boundary instead of importing infrastructure logging.

type MediaDiagnostics

type MediaDiagnostics interface {
	// RunDiagnostics checks GStreamer plugins and VA-API availability.
	RunDiagnostics(ctx context.Context) *MediaDiagnosticsResult
}

MediaDiagnostics provides video playback capability detection.

type MediaDiagnosticsResult

type MediaDiagnosticsResult struct {
	// GStreamer availability
	GStreamerAvailable bool

	// GStreamer plugins
	HasVAPlugin      bool // gst-plugins-bad VA (modern stateless decoders)
	HasVAAPIPlugin   bool // gstreamer-vaapi (legacy)
	HasNVCodecPlugin bool // nvcodec for NVIDIA

	// Detected hardware decoders
	AV1Decoders  []string
	H264Decoders []string
	H265Decoders []string
	VP9Decoders  []string

	// VA-API info
	VAAPIAvailable bool
	VAAPIDriver    string
	VAAPIVersion   string

	// Summary
	HWAccelAvailable bool
	AV1HWAvailable   bool
	Warnings         []string
}

MediaDiagnosticsResult contains hardware acceleration detection results.

type MemoryPressureApplier added in v0.23.0

type MemoryPressureApplier interface {
	// ApplyNetworkProcessSettings applies memory pressure settings to the network process.
	// Must be called BEFORE creating any NetworkSession.
	ApplyNetworkProcessSettings(ctx context.Context, cfg *MemoryPressureConfig) error

	// ApplyWebProcessSettings applies memory pressure settings to web processes.
	// Returns an opaque settings object that should be passed to context creation.
	// Returns nil if no settings are configured.
	ApplyWebProcessSettings(ctx context.Context, cfg *MemoryPressureConfig) (any, error)
}

MemoryPressureApplier applies memory pressure settings to engine processes. This interface abstracts engine-specific memory pressure configuration to allow testing without engine dependencies.

type MemoryPressureConfig added in v0.23.0

type MemoryPressureConfig struct {
	// MemoryLimitMB sets the memory limit in megabytes.
	// 0 means unset (uses engine default).
	MemoryLimitMB int

	// PollIntervalSec sets the interval for memory usage checks.
	// 0 means unset (uses engine default: 30 seconds).
	PollIntervalSec float64

	// ConservativeThreshold sets threshold for conservative memory release.
	// Must be in (0, 1). 0 means unset (uses engine default: 0.33).
	ConservativeThreshold float64

	// StrictThreshold sets threshold for strict memory release.
	// Must be in (0, 1). 0 means unset (uses engine default: 0.5).
	StrictThreshold float64
}

MemoryPressureConfig holds memory pressure settings for an engine process. This is a value type (no infrastructure dependencies) co-located with the interfaces that use it (MemoryPressureApplier, EngineOptions). Zero values mean "use engine defaults".

func (*MemoryPressureConfig) IsConfigured added in v0.23.0

func (c *MemoryPressureConfig) IsConfigured() bool

IsConfigured returns true if any memory pressure setting is configured.

type MessageRouter added in v0.28.0

type MessageRouter interface {
	// RegisterHandler registers a named message handler callable from JavaScript.
	// The handler receives a JSON-encoded message string and returns a
	// JSON-encoded response string.
	RegisterHandler(name string, handler func(message string) (string, error))

	// PostMessage sends a message to the JavaScript context of the given WebView.
	PostMessage(webviewID WebViewID, message string) error
}

MessageRouter defines the port interface for bidirectional JS-to-Go messaging. It allows JavaScript running in a WebView to invoke named Go handlers, and allows Go code to post messages back to a specific WebView.

type MigrationResult added in v0.22.0

type MigrationResult struct {
	// MissingKeys contains the keys that exist in defaults but not in user config.
	MissingKeys []string
	// ConfigFile is the path to the user's config file.
	ConfigFile string
}

MigrationResult contains the result of a config migration check.

type NativeWidgetProvider added in v0.28.0

type NativeWidgetProvider interface {
	NativeWidget() uintptr
}

NativeWidgetProvider is an optional capability for WebViews that can provide a native widget pointer for embedding into the host toolkit's layout system. For GTK-based engines this returns a *gtk.Widget pointer; other engines provide their equivalent embedding handle.

type Notification

type Notification interface {
	// Show displays a notification with the given message and type.
	// Duration is in milliseconds; pass 0 for default duration.
	// Returns an ID that can be used to dismiss the notification.
	Show(ctx context.Context, message string, notifType NotificationType, durationMs int) NotificationID

	// ShowZoom displays a special zoom level notification.
	// These typically appear in a fixed position and auto-dismiss.
	ShowZoom(ctx context.Context, zoomPercent int) NotificationID

	// Dismiss removes a specific notification by ID.
	Dismiss(ctx context.Context, id NotificationID)

	// Clear removes all displayed notifications.
	Clear(ctx context.Context)
}

Notification represents the port interface for user notifications/toasts. This abstracts the presentation layer (GTK/libadwaita toasts, frontend overlay, etc.).

type NotificationID

type NotificationID string

NotificationID uniquely identifies a displayed notification.

type NotificationType

type NotificationType int

NotificationType indicates the visual style of a notification.

const (
	// NotificationInfo is for informational messages.
	NotificationInfo NotificationType = iota
	// NotificationSuccess is for success confirmations.
	NotificationSuccess
	// NotificationError is for error messages.
	NotificationError
	// NotificationWarning is for warning messages.
	NotificationWarning
)

func (NotificationType) String

func (t NotificationType) String() string

String returns a human-readable representation of the notification type.

type OAuthCallbackCapable added in v0.28.0

type OAuthCallbackCapable interface {
	// AddCloseCallback registers fn to be called when the WebView is programmatically closed.
	// Multiple callbacks may be registered; each will be called in registration order.
	AddCloseCallback(fn func())
	// AddNavigationCallback registers fn to be called whenever the URI changes or a
	// committed load is detected. The uri parameter contains the new URL.
	// Multiple callbacks may be registered; each will be called in registration order.
	AddNavigationCallback(fn func(uri string))
	// Close triggers a programmatic close of the WebView (equivalent to window.close()).
	Close()
}

OAuthCallbackCapable is implemented by WebViews that support OAuth auto-close callbacks. It is an optional capability; callers should type-assert port.WebView to this interface before use and degrade gracefully when it is absent.

type PermissionDialogPresenter added in v0.27.0

type PermissionDialogPresenter interface {
	// ShowPermissionDialog displays a permission request dialog to the user.
	// The callback is invoked with the user's decision.
	//
	// Parameters:
	//   - ctx: context for cancellation and logging
	//   - origin: the website origin requesting permission (e.g., "https://meet.example.com")
	//   - permTypes: the types of permissions being requested
	//   - metadata: permission-type-specific context; for website_data_access both
	//     entity.PermissionMetadataKeyRequestingDomain and entity.PermissionMetadataKeyCurrentDomain must be set
	//   - callback: invoked when the user makes a decision or dialog is dismissed
	ShowPermissionDialog(
		ctx context.Context,
		origin string,
		permTypes []entity.PermissionType,
		metadata entity.PermissionMetadata,
		callback func(result PermissionDialogResult),
	)
}

PermissionDialogPresenter defines the interface for showing permission dialogs. This is implemented by the UI layer (Adwaita dialogs).

type PermissionDialogResult added in v0.27.0

type PermissionDialogResult struct {
	// Allowed is true if the user clicked "Allow" or "Always Allow".
	Allowed bool

	// Persistent is true if the user clicked "Always Allow" (save this decision).
	// This should only be true for mic/camera permissions, not display capture.
	Persistent bool
}

PermissionDialogResult represents the user's response from a permission dialog.

type PermissionRepository added in v0.27.0

type PermissionRepository interface {
	// Get retrieves the permission record for a specific origin and permission type.
	// Returns nil if no record exists (treat as "prompt" state).
	Get(ctx context.Context, origin string, permType entity.PermissionType) (*entity.PermissionRecord, error)

	// Set saves or updates a permission record.
	Set(ctx context.Context, record *entity.PermissionRecord) error

	// Delete removes a permission record for a specific origin and type.
	Delete(ctx context.Context, origin string, permType entity.PermissionType) error

	// GetAll retrieves all permission records for an origin.
	GetAll(ctx context.Context, origin string) ([]*entity.PermissionRecord, error)
}

PermissionRepository defines operations for permission persistence. Persistable types include microphone, camera, website_data_access, and others where CanPersist() returns true.

type PkgConfigError

type PkgConfigError struct {
	Kind    PkgConfigErrorKind
	Package string
	Output  string
	Err     error
}

PkgConfigError wraps an error returned by pkg-config probing.

func (*PkgConfigError) Error

func (e *PkgConfigError) Error() string

func (*PkgConfigError) Unwrap

func (e *PkgConfigError) Unwrap() error

type PkgConfigErrorKind

type PkgConfigErrorKind string

PkgConfigErrorKind describes the category of a pkg-config failure.

const (
	PkgConfigErrorKindCommandMissing PkgConfigErrorKind = "command_missing"
	PkgConfigErrorKindPackageMissing PkgConfigErrorKind = "package_missing"
	PkgConfigErrorKindUnknown        PkgConfigErrorKind = "unknown"
)

type PopupCapable added in v0.28.0

type PopupCapable interface {
	SetOnReadyToShow(fn func())
	SetOnClose(fn func())
	Show()
}

PopupCapable is implemented by WebViews that support popup lifecycle callbacks. SetOnClose composes the provided function with any existing close handler so that multiple callers can each register a close callback without overwriting one another.

type PopupRequest

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

PopupRequest contains metadata about a popup window request.

type Printer added in v0.28.0

type Printer interface {
	PrintPage()
}

Printer is an optional capability for WebViews that support printing.

type RenderingEnvManager

type RenderingEnvManager interface {
	// DetectGPUVendor identifies the primary GPU vendor from system info.
	// Uses /sys/class/drm/card*/device/vendor as primary detection method.
	DetectGPUVendor(ctx context.Context) GPUVendor

	// GetAppliedVars returns a map of environment variables that were set.
	// Useful for logging and debugging.
	GetAppliedVars() map[string]string
}

RenderingEnvManager configures rendering environment variables for GStreamer, WebKit, and GTK/GSK. Environment variables must be set BEFORE GTK/WebKit initialization.

Note: ApplyEnvironment was removed from this interface because rendering settings are engine-specific and are handled by concrete implementations (e.g. WebKit/GTK/GStreamer) to avoid port bloat.

type ResetKeybindingRequest added in v0.26.0

type ResetKeybindingRequest struct {
	RequestID string `json:"requestId"`
	Mode      string `json:"mode"`
	Action    string `json:"action"`
}

ResetKeybindingRequest represents a request to reset a keybinding.

type RuntimeVersionProbe

type RuntimeVersionProbe interface {
	PkgConfigModVersion(ctx context.Context, pkgName string, prefix string) (string, error)
}

RuntimeVersionProbe provides runtime dependency discovery.

Implementations may use pkg-config and may apply a prefix override to influence pkg-config search paths.

type SchemeHandler added in v0.28.0

type SchemeHandler interface {
	// RegisterScheme registers a handler for the given URI scheme.
	// The handler receives the full URI and returns the response body,
	// MIME type, and any error.
	RegisterScheme(scheme string, handler func(uri string) ([]byte, string, error))
}

SchemeHandler defines the port interface for registering custom URI schemes. Implementations intercept navigation to registered schemes and serve content from application code.

type ScriptRefresher added in v0.28.0

type ScriptRefresher interface {
	// RefreshAll re-injects scripts into all provided WebView instances.
	RefreshAll(ctx context.Context, webviews []WebView)
}

ScriptRefresher defines the port interface for refreshing injected scripts across multiple WebView instances (e.g., after a settings change).

type SearchShortcut

type SearchShortcut struct {
	URL         string `json:"url"`
	Description string `json:"description"`
}

type SelfUpdateBlockedReason added in v0.23.2

type SelfUpdateBlockedReason string

SelfUpdateBlockedReason indicates why self-update is not available.

const (
	// SelfUpdateAllowed means self-update is possible.
	SelfUpdateAllowed SelfUpdateBlockedReason = ""
	// SelfUpdateBlockedFlatpak means updates are managed by Flatpak.
	SelfUpdateBlockedFlatpak SelfUpdateBlockedReason = "flatpak"
	// SelfUpdateBlockedPacman means updates are managed by pacman/AUR.
	SelfUpdateBlockedPacman SelfUpdateBlockedReason = "pacman"
	// SelfUpdateBlockedNotWritable means the binary is not writable.
	SelfUpdateBlockedNotWritable SelfUpdateBlockedReason = "not_writable"
)

type SessionLogConfig

type SessionLogConfig struct {
	Level         string
	Format        string
	TimeFormat    string
	LogDir        string
	WriteToStderr bool
	EnableFileLog bool
}

type SessionLogger

type SessionLogger interface {
	CreateLogger(ctx context.Context, sessionID entity.SessionID, cfg SessionLogConfig) (zerolog.Logger, func(), error)
}

SessionLogger creates a logger tied to a session.

type SessionSpawner added in v0.21.0

type SessionSpawner interface {
	// SpawnWithSession starts a new dumber instance to restore a session.
	SpawnWithSession(sessionID entity.SessionID) error
}

SessionSpawner spawns a new dumber instance for resurrection.

type SetKeybindingRequest added in v0.26.0

type SetKeybindingRequest struct {
	RequestID string   `json:"requestId"`
	Mode      string   `json:"mode"`
	Action    string   `json:"action"`
	Keys      []string `json:"keys"`
}

SetKeybindingRequest represents a request to update a keybinding.

type SetKeybindingResponse added in v0.26.0

type SetKeybindingResponse struct {
	Conflicts []KeybindingConflict `json:"conflicts"`
}

SetKeybindingResponse is the response from setting a keybinding.

type SettingsApplier added in v0.28.0

type SettingsApplier interface {
	// ApplyToAll applies settings to all provided WebView instances.
	ApplyToAll(ctx context.Context, webviews []WebView)
}

SettingsApplier defines the port interface for applying browser settings to WebViews. Implementations apply engine-specific settings (security, features, etc.) uniformly across a set of WebView instances.

type SnapshotService added in v0.28.0

type SnapshotService interface {
	// Start begins the snapshot service with the given context.
	Start(ctx context.Context)
	// Stop stops the service and saves the final state.
	Stop(ctx context.Context) error
	// SetReady marks the service as ready to save snapshots.
	// Call this after the session has been persisted to the database.
	SetReady()
	// MarkDirty signals that session state has changed and should be saved.
	MarkDirty()
	// SaveNow forces an immediate save (e.g. for shutdown).
	SaveNow(ctx context.Context) error
}

SnapshotService manages debounced session-state snapshots.

type TabListProvider added in v0.21.0

type TabListProvider interface {
	// GetTabList returns the current tab list state.
	GetTabList() *entity.TabList
	// GetSessionID returns the current session ID.
	GetSessionID() entity.SessionID
}

TabListProvider provides access to the current tab list state. Implemented by the UI layer to allow the snapshot service to read state.

type TextInputTarget added in v0.23.0

type TextInputTarget interface {
	// InsertText inserts text at the current cursor position.
	InsertText(ctx context.Context, text string) error

	// DeleteBeforeCursor deletes n characters before the cursor position.
	DeleteBeforeCursor(ctx context.Context, n int) error
}

TextInputTarget represents a text input field that can receive text insertions. Implementations include GTK Entry widgets and WebView text fields.

type TextInputTargetProvider added in v0.28.0

type TextInputTargetProvider interface {
	TextInputTarget() TextInputTarget
}

TextInputTargetProvider is an optional capability for WebViews that support text input method integration.

type Texture

type Texture interface {
	GoPointer() uintptr
}

Texture represents a graphics texture returned by the engine. GoPointer returns a native toolkit pointer (e.g. *gdk.Texture in GTK engines). Engine implementations are responsible for the concrete type.

type ToolkitAvailabilityNotifier added in v0.28.0

type ToolkitAvailabilityNotifier interface {
	MarkAvailable()
}

ToolkitAvailabilityNotifier signals that a toolkit (e.g., GTK/Adwaita) is available.

type UpdateApplier added in v0.21.0

type UpdateApplier interface {
	// CanSelfUpdate checks if the current binary is writable by the current user.
	// Returns true if auto-update is possible, false if user lacks write permission.
	CanSelfUpdate(ctx context.Context) bool

	// SelfUpdateBlockedReason returns why self-update is blocked, or empty if allowed.
	SelfUpdateBlockedReason(ctx context.Context) SelfUpdateBlockedReason

	// GetBinaryPath returns the path to the currently running binary.
	GetBinaryPath() (string, error)

	// StageUpdate prepares the new binary to be applied on exit.
	// The staged update will be applied when ApplyOnExit is called.
	StageUpdate(ctx context.Context, newBinaryPath string) error

	// HasStagedUpdate checks if there is an update staged and ready to apply.
	HasStagedUpdate(ctx context.Context) bool

	// ApplyOnExit replaces the current binary with the staged update.
	// This should be called during graceful shutdown.
	// Returns the path to the backup of the old binary.
	ApplyOnExit(ctx context.Context) (backupPath string, err error)

	// ClearStagedUpdate removes any staged update without applying it.
	ClearStagedUpdate(ctx context.Context) error
}

UpdateApplier stages and applies updates.

type UpdateChecker added in v0.21.0

type UpdateChecker interface {
	// CheckForUpdate compares the current version with the latest available release.
	// Returns update info including whether a newer version is available.
	CheckForUpdate(ctx context.Context, currentVersion string) (*entity.UpdateInfo, error)
}

UpdateChecker checks for available updates from a remote source.

type UpdateDownloader added in v0.21.0

type UpdateDownloader interface {
	// Download fetches the update archive to the specified destination directory.
	// Returns the path to the downloaded archive file.
	Download(ctx context.Context, downloadURL string, destDir string) (archivePath string, err error)

	// Extract extracts the binary from the downloaded archive.
	// Returns the path to the extracted binary.
	Extract(ctx context.Context, archivePath string, destDir string) (binaryPath string, err error)
}

UpdateDownloader downloads and extracts update archives.

type WebProcessTerminationReason added in v0.27.0

type WebProcessTerminationReason int

WebProcessTerminationReason describes why the web process terminated.

const (
	WebProcessTerminationUnknown WebProcessTerminationReason = iota
	WebProcessTerminationCrashed
	WebProcessTerminationExceededMemory
	WebProcessTerminationByAPI
)

type WebUIAppearanceConfig

type WebUIAppearanceConfig struct {
	SansFont        string       `json:"sans_font"`
	SerifFont       string       `json:"serif_font"`
	MonospaceFont   string       `json:"monospace_font"`
	DefaultFontSize int          `json:"default_font_size"`
	ColorScheme     string       `json:"color_scheme"`
	LightPalette    ColorPalette `json:"light_palette"`
	DarkPalette     ColorPalette `json:"dark_palette"`
}

type WebUIConfig

type WebUIConfig struct {
	Appearance          WebUIAppearanceConfig     `json:"appearance"`
	Performance         WebUIPerformanceConfig    `json:"performance"`
	DefaultUIScale      float64                   `json:"default_ui_scale"`
	DefaultSearchEngine string                    `json:"default_search_engine"`
	SearchShortcuts     map[string]SearchShortcut `json:"search_shortcuts"`
}

WebUIConfig represents the subset of configuration editable in dumb://config.

type WebUIConfigSaver

type WebUIConfigSaver interface {
	SaveWebUIConfig(ctx context.Context, cfg WebUIConfig) error
}

WebUIConfigSaver persists WebUI configuration changes.

type WebUICustomPerformanceConfig added in v0.23.0

type WebUICustomPerformanceConfig struct {
	SkiaCPUThreads         int `json:"skia_cpu_threads"`
	SkiaGPUThreads         int `json:"skia_gpu_threads"`
	WebProcessMemoryMB     int `json:"web_process_memory_mb"`
	NetworkProcessMemoryMB int `json:"network_process_memory_mb"`
	WebViewPoolPrewarm     int `json:"webview_pool_prewarm"`
}

WebUICustomPerformanceConfig holds user-editable fields for custom profile.

type WebUIPerformanceConfig added in v0.23.0

type WebUIPerformanceConfig struct {
	Profile string                       `json:"profile"`
	Custom  WebUICustomPerformanceConfig `json:"custom"`
}

WebUIPerformanceConfig represents performance settings editable in dumb://config.

type WebView

type WebView interface {
	// ID returns the unique identifier for this WebView.
	ID() WebViewID

	// LoadURI navigates to the specified URI.
	LoadURI(ctx context.Context, uri string) error

	// LoadHTML loads HTML content with an optional base URI for relative links.
	LoadHTML(ctx context.Context, content, baseURI string) error

	// Reload reloads the current page.
	Reload(ctx context.Context) error

	// ReloadBypassCache reloads the current page, bypassing cache.
	ReloadBypassCache(ctx context.Context) error

	// Stop stops the current page load.
	Stop(ctx context.Context) error

	// GoBack navigates back in history.
	// Uses WebKit native navigation if available, falls back to JavaScript history.back() for SPA compatibility.
	GoBack(ctx context.Context) error

	// GoForward navigates forward in history.
	// Uses WebKit native navigation if available, falls back to JavaScript history.forward() for SPA compatibility.
	GoForward(ctx context.Context) error

	// State returns the current WebView state as a snapshot.
	State() WebViewState

	// URI returns the current URI.
	URI() string

	// Title returns the current page title.
	Title() string

	// IsLoading returns true if a page is currently loading.
	IsLoading() bool

	// EstimatedProgress returns the load progress (0.0 to 1.0).
	EstimatedProgress() float64

	// CanGoBack returns true if back navigation is available.
	CanGoBack() bool

	// CanGoForward returns true if forward navigation is available.
	CanGoForward() bool

	// SetZoomLevel sets the zoom level (1.0 = 100%).
	SetZoomLevel(ctx context.Context, level float64) error

	// GetZoomLevel returns the current zoom level.
	GetZoomLevel() float64

	// GetFindController returns the find controller for text search.
	// Returns nil if find is not supported.
	GetFindController() FindController

	// SetCallbacks registers callback handlers for WebView events.
	// Pass nil to clear all callbacks.
	SetCallbacks(callbacks *WebViewCallbacks)

	// RunJavaScript executes a script in the main world. Fire-and-forget.
	RunJavaScript(ctx context.Context, script string)

	// SetBackgroundColor sets the background color shown before content paints (0.0-1.0 RGBA).
	SetBackgroundColor(r, g, b, a float64)

	// ResetBackgroundToDefault resets the background to white (browser default).
	ResetBackgroundToDefault()

	// Favicon returns the current page favicon, or nil if unavailable.
	Favicon() Texture

	// Generation returns a monotonic counter incremented on pool reuse.
	// Used to detect stale callbacks after a WebView is recycled.
	Generation() uint64

	// IsFullscreen returns true if the WebView is currently in fullscreen mode.
	IsFullscreen() bool

	// IsPlayingAudio returns true if the WebView is currently playing audio.
	IsPlayingAudio() bool

	// IsDestroyed returns true if the WebView has been destroyed.
	IsDestroyed() bool

	// Destroy releases all resources associated with this WebView.
	// After calling Destroy, the WebView should not be used.
	Destroy()
}

WebView defines the port interface for browser view operations. This interface abstracts the underlying browser engine (WebKit, etc.) and exposes only the navigation and state capabilities needed by the application layer.

type WebViewCallbacks

type WebViewCallbacks struct {
	// OnLoadChanged is called when load state changes.
	OnLoadChanged func(event LoadEvent)
	// OnTitleChanged is called when the page title changes.
	OnTitleChanged func(title string)
	// OnURIChanged is called when the URI changes.
	OnURIChanged func(uri string)
	// OnProgressChanged is called during page load with progress 0.0-1.0.
	OnProgressChanged func(progress float64)
	// OnFaviconChanged is called when the page favicon changes.
	// The parameter is a *gdk.Texture (passed as Texture interface to avoid GTK import in port layer).
	OnFaviconChanged func(favicon Texture)
	// OnClose is called when the WebView requests to close.
	OnClose func()
	// OnCreate is called when a popup window is requested.
	// Return a WebView to allow the popup, or nil to block it.
	OnCreate func(request PopupRequest) WebView
	// OnReadyToShow is called when a popup WebView is ready to display.
	OnReadyToShow func()
	// OnLinkHover is called when hovering over a link, image, or media element.
	// The uri parameter contains the target URL, or empty string when leaving.
	OnLinkHover func(uri string)
	// OnWebProcessTerminated is called when the web process exits unexpectedly.
	OnWebProcessTerminated func(reason WebProcessTerminationReason, reasonLabel string, uri string)

	// OnPermissionRequest is called when a site requests permission (mic, camera, screen sharing).
	// Return true to indicate the request was handled. Call allow()/deny() to respond.
	// The permission types are passed as strings ("microphone", "camera", "display", etc.).
	// The metadata map carries permission-type-specific context; for website_data_access both
	// entity.PermissionMetadataKeyRequestingDomain and entity.PermissionMetadataKeyCurrentDomain must be populated.
	OnPermissionRequest func(origin string, permTypes []string, metadata map[string]string, allow, deny func()) bool

	// OnLinkMiddleClick is called when a link is middle-clicked.
	// Return true if handled (blocks default navigation).
	OnLinkMiddleClick func(uri string) bool

	// OnEnterFullscreen is called when the WebView requests fullscreen mode.
	// Return true to prevent fullscreen.
	OnEnterFullscreen func() bool

	// OnLeaveFullscreen is called when the WebView exits fullscreen mode.
	// Return true to prevent leaving fullscreen.
	OnLeaveFullscreen func() bool

	// OnAudioStateChanged is called when audio playback starts or stops.
	OnAudioStateChanged func(playing bool)
}

WebViewCallbacks defines callback handlers for WebView events. Implementations should invoke these on the main thread/goroutine.

type WebViewFactory

type WebViewFactory interface {
	// Create creates a new WebView instance.
	Create(ctx context.Context) (WebView, error)

	// CreateRelated creates a WebView that shares session/cookies with parent.
	// This is required for popup windows to maintain authentication state.
	// Popup WebViews bypass the pool since they must be related to a specific parent.
	CreateRelated(ctx context.Context, parentID WebViewID) (WebView, error)
}

WebViewFactory creates new WebView instances. This is used when direct WebView creation is needed without pooling.

type WebViewID

type WebViewID uint64

WebViewID uniquely identifies a WebView instance.

type WebViewPool

type WebViewPool interface {
	// Acquire obtains a WebView from the pool or creates a new one.
	// The context can be used for cancellation.
	Acquire(ctx context.Context) (WebView, error)

	// Release returns a WebView to the pool for reuse.
	// The WebView will be reset to a blank state.
	// If the pool is full, the WebView will be destroyed.
	Release(wv WebView)

	// Prewarm creates WebViews synchronously to populate the pool.
	// Pass count <= 0 to use the default prewarm count.
	Prewarm(count int)

	// PrewarmAsync schedules WebView creation on the toolkit idle loop,
	// avoiding blocking startup while still warming up WebViews.
	// Pass count <= 0 to use the default prewarm count.
	PrewarmAsync(ctx context.Context, count int)

	// Size returns the current number of available WebViews in the pool.
	Size() int

	// Close shuts down the pool and destroys all pooled WebViews.
	Close()
}

WebViewPool defines the port interface for WebView pooling. Pools maintain pre-created WebViews for fast tab creation.

type WebViewState

type WebViewState struct {
	URI       string
	Title     string
	IsLoading bool
	Progress  float64 // 0.0 to 1.0
	CanGoBack bool
	CanGoFwd  bool
	ZoomLevel float64
}

WebViewState represents a snapshot of the current WebView state. This is an immutable struct that can be safely passed between components.

type XDGPaths

type XDGPaths interface {
	ConfigDir() (string, error)
	DataDir() (string, error)
	StateDir() (string, error)
	CacheDir() (string, error)

	FilterJSONDir() (string, error)
	FilterStoreDir() (string, error)
	FilterCacheDir() (string, error)

	// ManDir returns the user man page directory (man1 section).
	// Typically $XDG_DATA_HOME/man/man1 or ~/.local/share/man/man1.
	ManDir() (string, error)

	// DownloadDir returns the user's download directory.
	// Typically $XDG_DOWNLOAD_DIR or ~/Downloads.
	DownloadDir() (string, error)
}

XDGPaths provides XDG Base Directory paths.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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