port

package
v0.26.2 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package port defines interfaces for infrastructure adapters.

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 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")
)

Functions

This section is empty.

Types

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 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
}

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

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 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 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 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 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)) uint32
	OnFailedToFindText(callback func()) uint32
	OnCountedMatches(callback func(matchCount uint)) uint32
	DisconnectSignal(id uint32)
}

FindController abstracts WebKit's FindController for clean architecture.

type FindOptions

type FindOptions struct {
	CaseInsensitive bool
	AtWordStarts    bool
	WrapAround      bool
}

FindOptions configures search behavior.

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 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 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 KeybindingsConfig added in v0.26.0

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

KeybindingsConfig represents all keybindings for the UI.

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 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 WebContext creation.
	// Returns nil if no settings are configured.
	ApplyWebProcessSettings(ctx context.Context, cfg *MemoryPressureConfig) (any, error)
}

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

type MemoryPressureConfig added in v0.23.0

type MemoryPressureConfig struct {
	// MemoryLimitMB sets the memory limit in megabytes.
	// 0 means unset (uses WebKit default: system RAM capped at 3GB).
	MemoryLimitMB int

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

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

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

MemoryPressureConfig holds memory pressure settings for a WebKit process. Zero values mean "use WebKit 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 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 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 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 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 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

	// ApplyEnvironment sets all rendering environment variables.
	// Must be called before any GTK/GStreamer initialization.
	ApplyEnvironment(ctx context.Context, settings RenderingEnvSettings) error

	// 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.

type RenderingEnvSettings

type RenderingEnvSettings struct {
	// --- GStreamer settings (from MediaConfig) ---
	// ForceVSync enables vertical sync for video playback.
	ForceVSync bool
	// GLRenderingMode controls OpenGL API selection: "auto", "gles2", "gl3", "none".
	GLRenderingMode string
	// GStreamerDebugLevel sets GStreamer debug verbosity (0-5).
	GStreamerDebugLevel int

	// --- WebKit compositor settings (from RenderingConfig) ---
	DisableDMABufRenderer  bool
	ForceCompositingMode   bool
	DisableCompositingMode bool

	// --- GTK/GSK settings (from RenderingConfig) ---
	GSKRenderer    string
	DisableMipmaps bool
	PreferGL       bool

	// --- Debug settings ---
	ShowFPS      bool
	SampleMemory bool
	DebugFrames  bool

	// --- Skia rendering thread settings (from PerformanceConfig) ---
	// SkiaCPUPaintingThreads sets WEBKIT_SKIA_CPU_PAINTING_THREADS.
	// 0 means unset (use WebKit default).
	SkiaCPUPaintingThreads int
	// SkiaGPUPaintingThreads sets WEBKIT_SKIA_GPU_PAINTING_THREADS.
	// -1 means unset; 0 disables GPU tile painting.
	SkiaGPUPaintingThreads int
	// SkiaEnableCPURendering forces CPU rendering via WEBKIT_SKIA_ENABLE_CPU_RENDERING=1.
	SkiaEnableCPURendering bool
}

RenderingEnvSettings contains all rendering-related environment settings. This is a port-local type to avoid import cycles with config package.

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 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 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 Texture

type Texture interface {
	// GoPointer returns the underlying C pointer for GTK interop.
	GoPointer() uintptr
}

Texture represents a graphics texture (abstraction over gdk.Texture). This interface allows the port layer to work with textures without importing GTK/GDK packages directly.

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 WebKitContextOptions added in v0.23.0

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

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

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

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

WebKitContextOptions configures WebKitContext creation.

func (*WebKitContextOptions) IsNetworkProcessMemoryConfigured added in v0.23.0

func (o *WebKitContextOptions) IsNetworkProcessMemoryConfigured() bool

IsNetworkProcessMemoryConfigured returns true if network process memory settings are configured.

func (*WebKitContextOptions) IsWebProcessMemoryConfigured added in v0.23.0

func (o *WebKitContextOptions) IsWebProcessMemoryConfigured() bool

IsWebProcessMemoryConfigured returns true if web process memory settings are configured.

type WebKitContextProvider added in v0.23.0

type WebKitContextProvider interface {
	// Initialize sets up the WebKit context with the given options.
	// Must be called before any other methods.
	Initialize(ctx context.Context, opts WebKitContextOptions) error

	// DataDir returns the data directory path.
	DataDir() string

	// CacheDir returns the cache directory path.
	CacheDir() string

	// PrefetchDNS prefetches DNS for the given hostname.
	PrefetchDNS(hostname string)

	// Close releases resources held by the context.
	Close() error
}

WebKitContextProvider creates and manages WebKit contexts. This interface abstracts WebKit context creation for testability.

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)

	// 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)
}

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 in the background to populate the pool.
	// Pass count <= 0 to use the default prewarm count.
	Prewarm(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