-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate.go
More file actions
86 lines (71 loc) · 1.89 KB
/
Copy pathstate.go
File metadata and controls
86 lines (71 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
// WindowState holds the saved window geometry
type WindowState struct {
Width int `json:"width"`
Height int `json:"height"`
X int `json:"x"`
Y int `json:"y"`
}
// IsValid returns true if the state has valid dimensions
func (s *WindowState) IsValid() bool {
return s != nil && s.Width > 0 && s.Height > 0
}
// getStatePath returns the path to the state file
func getStatePath() string {
configDir := getConfigDir()
if configDir == "" {
return ""
}
return filepath.Join(configDir, "state.json")
}
// LoadWindowState loads the window state from the state file
// Returns nil if no state exists or can't be read
func LoadWindowState() *WindowState {
statePath := getStatePath()
if statePath == "" {
return nil
}
data, err := os.ReadFile(statePath)
if err != nil {
// File doesn't exist or can't be read - that's fine
return nil
}
var state WindowState
if err := json.Unmarshal(data, &state); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to parse state file %s: %v\n", statePath, err)
return nil
}
if !state.IsValid() {
return nil
}
return &state
}
// SaveWindowState saves the window state to the state file
func SaveWindowState(state WindowState) error {
if !state.IsValid() {
return nil // Don't save invalid state
}
statePath := getStatePath()
if statePath == "" {
return fmt.Errorf("could not determine state file path")
}
// Ensure config directory exists
configDir := filepath.Dir(statePath)
if err := os.MkdirAll(configDir, 0755); err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
data, err := json.MarshalIndent(state, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal state: %w", err)
}
if err := os.WriteFile(statePath, data, 0644); err != nil {
return fmt.Errorf("failed to write state file: %w", err)
}
return nil
}