Files

88 lines
1.7 KiB
Go

package main
import (
"encoding/json"
"os"
"path/filepath"
"fyne.io/fyne/v2"
)
const (
DefaultWindowWidth = 800.0
DefaultWindowHeight = 600.0
ConfigFileName = "secure-editor-go-config.json"
)
// windowConfig is persisted to ~/.cache/secure-editor-go-config.json so the
// editor remembers its window size across runs.
type windowConfig struct {
Width float32 `json:"width"`
Height float32 `json:"height"`
}
func configPath() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".cache", ConfigFileName), nil
}
func defaultConfig() windowConfig {
return windowConfig{Width: DefaultWindowWidth, Height: DefaultWindowHeight}
}
func loadConfig() windowConfig {
p, err := configPath()
if err != nil {
return defaultConfig()
}
data, err := os.ReadFile(p)
if err != nil {
return defaultConfig()
}
var c windowConfig
if err := json.Unmarshal(data, &c); err != nil {
return defaultConfig()
}
if c.Width <= 0 || c.Height <= 0 {
return defaultConfig()
}
return c
}
func saveConfig(size fyne.Size) {
p, err := configPath()
if err != nil {
return
}
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
return
}
c := windowConfig{Width: size.Width, Height: size.Height}
data, err := json.MarshalIndent(c, "", " ")
if err != nil {
return
}
_ = os.WriteFile(p, data, 0644)
}
// clampToScreen shrinks size so it never exceeds the visible desktop area.
// When the desktop size can't be determined it returns size unchanged.
func clampToScreen(size fyne.Size) fyne.Size {
sw, sh := desktopSize()
if sw <= 0 || sh <= 0 {
return size
}
w, h := size.Width, size.Height
if w > sw {
w = sw
}
if h > sh {
h = sh
}
return fyne.NewSize(w, h)
}