Documentation
¶
Overview ¶
Package settings is Silk's preferences-storage runtime — the equivalent of Qt's QSettings. It wraps a TDoc-backed file with a Qt-style key/value API: hierarchical groups, typed getters with default values, optional ordered arrays, and an explicit Sync() flush.
Why a TDoc backend instead of native registry / plist? Three reasons:
- Cross-platform parity. The same .silkui-style file format works on macOS, Linux, Windows; users who copy ~/.config/<app> between machines see settings carry over.
- Re-uses Silk's existing persistence layer. TDoc already handles numeric types, strings, lists, nested structures — no JSON or INI library to add.
- Editable by hand. Plist is binary on modern macOS; the registry is opaque. A TDoc text file is grep-friendly, diffable, and can be hand-edited when the app is misconfigured.
Typical usage:
import "github.com/uk0/silk/settings"
s := settings.Default("MyOrg", "MyApp")
s.SetValue("editor/fontSize", 14)
size := s.Int("editor/fontSize", 12) // 12 if not set
s.Sync()
Group syntax: SetValue("group/sub/key", v) writes to the nested path. BeginGroup("group") makes subsequent calls relative to that prefix:
s.BeginGroup("editor")
s.SetValue("fontSize", 14) // → editor/fontSize
s.SetValue("theme", "dark") // → editor/theme
s.EndGroup()
Goal lined up against QSettings: feature-parity for the dominant 90% of API calls (Value, SetValue, Contains, Remove, AllKeys, BeginGroup, EndGroup, beginReadArray, beginWriteArray, Sync, Status). The Qt Format / Scope / Organization / Application metadata is NOT modelled — Silk's TDoc-based path resolution covers the same ground in one pass.
Index ¶
- func DefaultPath(org, app string) string
- type Settings
- func (s *Settings) AllKeys() []string
- func (s *Settings) BeginGroup(name string)
- func (s *Settings) Bool(key string, def bool) bool
- func (s *Settings) Clear()
- func (s *Settings) Contains(key string) bool
- func (s *Settings) EndGroup()
- func (s *Settings) Float64(key string, def float64) float64
- func (s *Settings) Group() string
- func (s *Settings) Int(key string, def int64) int64
- func (s *Settings) IsDirty() bool
- func (s *Settings) Path() string
- func (s *Settings) Remove(key string)
- func (s *Settings) SetBool(key string, v bool) error
- func (s *Settings) SetFloat64(key string, v float64) error
- func (s *Settings) SetInt(key string, v int64) error
- func (s *Settings) SetString(key string, v string) error
- func (s *Settings) SetStringList(key string, v []string) error
- func (s *Settings) SetValue(key string, value interface{}) error
- func (s *Settings) Status() error
- func (s *Settings) String(key string, def string) string
- func (s *Settings) StringList(key string, def []string) []string
- func (s *Settings) Sync() error
- func (s *Settings) Value(key string, def ...interface{}) interface{}
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultPath ¶
DefaultPath returns the OS-conventional path for an app's settings file. The output structure follows each platform's HIG-recommended layout:
macOS: ~/Library/Application Support/<org>/<app>/<app>.silkui
Linux: $XDG_CONFIG_HOME/<org>/<app>/<app>.conf
(falls back to ~/.config/<org>/<app>/<app>.conf when XDG
is unset)
Windows: %APPDATA%\<org>\<app>\<app>.ini
Why per-app subdir under per-org subdir: matches what every native installer does. A user shipping multiple apps from one org gets all of them under one umbrella; a single app stays in its own folder so uninstall is just an rm -rf <app>.
Empty org or app substitutes "Silk" / "App" so callers without metadata still get a stable path. This is a safety net — production apps should always supply both.
Types ¶
type Settings ¶
type Settings struct {
// contains filtered or unexported fields
}
Settings holds an in-memory TDoc-backed key/value store. Reads and writes are concurrent-safe via an internal RWMutex; the TDoc itself is not goroutine-safe, so all access goes through the lock.
The persistence model is "lazy load, explicit flush": opening a file that doesn't exist yet does not error — it produces an empty Settings whose first Sync writes a fresh file. SetValue marks the instance dirty; Sync writes only if dirty so frequent ticking syncs are cheap no-ops.
func Default ¶
Default opens (or prepares to open) the user's per-app settings file. The path is platform-dependent — see DefaultPath. Errors from path resolution are deferred to Sync; this constructor never fails.
func New ¶
New constructs a Settings rooted at path. The file is not loaded until the first read or write. A path of "" yields an in-memory instance (Sync is then a no-op + sets Status to errInMemoryOnly).
For platform-default paths use Default(org, app) — that path resolution is OS-aware (macOS Application Support, XDG on Linux, %APPDATA% on Windows).
func NewMemory ¶
func NewMemory() *Settings
NewMemory returns a Settings with no backing file. All operations happen in memory; useful for tests and ephemeral runs. Sync is a no-op and returns nil.
func (*Settings) AllKeys ¶
AllKeys returns every leaf key (no group prefixes), filtered to the current group when one is active. Result is sorted for determinism — callers iterating in tests don't have to depend on map order.
"Leaf key" = a TDoc node carrying a value. Nodes that are pure containers (e.g. groups with no own value) are not returned.
func (*Settings) BeginGroup ¶
BeginGroup pushes name onto the group stack. Subsequent SetValue / Value / Contains / Remove calls treat their keys as relative to the current group. Must be matched by an EndGroup at the same nesting depth — unbalanced calls are diagnosable via Group() returning the current full prefix.
Empty names are ignored to keep API tolerant against e.g. dynamic group construction that produces a blank string.
func (*Settings) Bool ¶
Bool reads key as a boolean. "true"/"True"/"1" → true; "false"/ "False"/"0" → false. Anything else returns the default.
func (*Settings) Clear ¶
func (s *Settings) Clear()
Clear empties the entire settings store, including all groups. Equivalent to deleting the backing file but in-memory.
func (*Settings) EndGroup ¶
func (s *Settings) EndGroup()
EndGroup pops the most recent BeginGroup. No-op when no group is active so well-meaning callers don't crash on early-out paths.
func (*Settings) Group ¶
Group returns the current group prefix joined by "/". Empty string when no BeginGroup is active.
func (*Settings) IsDirty ¶
IsDirty reports whether there are pending writes that Sync would flush. Cheap inspection used by tooling that wants to gate "Save" menu items.
func (*Settings) Remove ¶
Remove deletes the entry at key. Removing a group prefix removes every nested key under it (Qt's recursive-remove semantics).
Mark dirty regardless of whether the key existed — Qt's remove also dirties even on a missing key.
Implementation note: the underlying TDoc.AddChild does not set the parent pointer on the inserted node, so calling Detach() on the removed node is a no-op (the parent.subs slice still references it). We instead Clear() the node — wiping its value and any nested children — and let AllKeys / Contains skip value-less leaves. This matches the observable Qt behaviour without modifying core/tdoc.
func (*Settings) SetBool ¶
SetBool writes a boolean as "true" / "false". Mirrors Qt's QSettings::setValue with a Bool — the canonical lowercase form so the persisted file is human-readable.
func (*Settings) SetFloat64 ¶
SetFloat64 writes a float64.
func (*Settings) SetStringList ¶
SetStringList writes a string slice using the comma encoding above.
func (*Settings) SetValue ¶
SetValue writes value at key, creating any intermediate groups as needed. value must be a type the persist layer accepts (string, numeric, bool, []string). Type mismatch returns an error rather than panicking on the persist boundary.
Marks the instance dirty; Sync flushes it.
func (*Settings) Status ¶
Status returns the most recent IO error, or nil. Cleared on the next successful Sync. Useful for hosts that want to surface a "settings corrupted, falling back to defaults" state to the user.
func (*Settings) String ¶
String reads key as a string. The default form (one of two) returns def when the key is missing.
func (*Settings) StringList ¶
StringList reads key as a comma-separated list of values, mirroring the Qt convention of storing QStringList as a comma-joined string. Empty value yields an empty (non-nil) slice; missing key yields the supplied default.
Escape handling: a literal comma inside an item is double-comma encoded ("a,b,c" → ["a", "b", "c"]; "a,,b" → ["a,b"]). This matches Qt's QSettings format on the INI backend.
func (*Settings) Sync ¶
Sync flushes pending writes to disk. No-op when nothing has changed since the last Sync, or when this is an in-memory instance. Errors are saved into Status() and returned from this call.
Creates parent directories as needed — apps invoked from a fresh install on a host with no ~/.config/MyOrg can still persist on first run.
func (*Settings) Value ¶
Value reads key into a Go value. The first variadic argument, if present, is returned when the key is missing — typed default. Without a default, missing keys return nil.
Decoding strategy: TDoc stores everything as a persisted string. We return the raw string here and let the caller pick a type via the typed accessors (Bool, Int, Float64, String, StringList) which re-decode through PersistSscan.
Lock policy: takes the write lock so loadOnce can run safely on the first call. The cost is negligible for read-heavy workloads because settings access is rare relative to UI updates.