1use std::collections::HashMap;
6use std::env;
7use std::fs;
8use std::path::PathBuf;
9
10use serde::{Deserialize, Serialize};
11
12use crate::{
13 Activity, HarnessId, HarnessStatus, LayoutNode, Mail, Showcase, Workspace, WorkspaceId,
14};
15
16#[derive(Debug, Clone, Default, Serialize, Deserialize)]
17#[serde(default)]
18pub struct AppState {
19 pub workspaces: Vec<Workspace>,
20 pub layouts: HashMap<WorkspaceId, LayoutNode>,
21 pub active: Option<WorkspaceId>,
22 pub focused: Option<HarnessId>,
23 pub mail: Vec<Mail>,
24 pub activity: Vec<Activity>,
25 pub showcases: Vec<Showcase>,
26}
27
28impl AppState {
29 pub fn path() -> PathBuf {
31 match env::var("TERMDEN_STATE_FILE") {
32 Ok(path) if !path.is_empty() => PathBuf::from(path),
33 _ => state_dir().join("state.json"),
34 }
35 }
36
37 pub fn load() -> Option<Self> {
40 let path = Self::path();
41 let text = fs::read_to_string(&path).ok()?;
42 match serde_json::from_str::<Self>(&text) {
43 Ok(mut state) => {
44 for harness in state
46 .workspaces
47 .iter_mut()
48 .flat_map(|w| w.harnesses.iter_mut())
49 {
50 harness.status = HarnessStatus::Idle;
51 }
52 Some(state)
53 }
54 Err(error) => {
55 let backup = path.with_extension("json.corrupt");
56 eprintln!(
57 "termden: could not parse {} ({error}); moved to {}",
58 path.display(),
59 backup.display()
60 );
61 let _ = fs::rename(&path, backup);
62 None
63 }
64 }
65 }
66
67 pub fn save(&self) -> std::io::Result<()> {
69 let path = Self::path();
70 if let Some(parent) = path.parent() {
71 fs::create_dir_all(parent)?;
72 }
73 let tmp = path.with_extension("json.tmp");
74 let text = serde_json::to_string_pretty(self).map_err(std::io::Error::other)?;
75 fs::write(&tmp, text)?;
76 fs::rename(tmp, path)
77 }
78
79 pub fn next_harness_id(&self) -> HarnessId {
80 let max = self
84 .workspaces
85 .iter()
86 .flat_map(|w| w.harnesses.iter())
87 .map(|h| h.id.raw())
88 .chain(
89 self.activity
90 .iter()
91 .filter_map(|entry| entry.harness.map(|id| id.raw())),
92 )
93 .max()
94 .unwrap_or(0);
95 HarnessId::new(max + 1)
96 }
97
98 pub fn next_workspace_id(&self) -> WorkspaceId {
99 let max = self
100 .workspaces
101 .iter()
102 .map(|w| w.id.raw())
103 .max()
104 .unwrap_or(0);
105 WorkspaceId::new(max + 1)
106 }
107}
108
109pub fn state_dir() -> PathBuf {
110 xdg_dir("XDG_STATE_HOME", ".local/state").join("termden")
111}
112
113pub fn runtime_dir() -> PathBuf {
115 match env::var("XDG_RUNTIME_DIR") {
116 Ok(dir) if !dir.is_empty() => PathBuf::from(dir).join("termden"),
117 _ => env::temp_dir().join(format!("termden-{}", env::var("USER").unwrap_or_default())),
118 }
119}
120
121pub fn control_socket() -> PathBuf {
123 match env::var("TERMDEN_CONTROL_SOCKET") {
124 Ok(path) if !path.is_empty() => PathBuf::from(path),
125 _ => runtime_dir().join("app.sock"),
126 }
127}
128
129pub(crate) fn xdg_dir(var: &str, fallback: &str) -> PathBuf {
130 if let Ok(dir) = env::var(var) {
131 if !dir.is_empty() {
132 return PathBuf::from(dir);
133 }
134 }
135 match env::var("HOME") {
136 Ok(home) => PathBuf::from(home).join(fallback),
137 Err(_) => PathBuf::from(fallback),
138 }
139}
140
141#[cfg(test)]
142mod tests {
143 use super::*;
144 use crate::{Axis, Harness, HarnessKind};
145
146 #[test]
147 fn round_trips_through_json() {
148 let ws = WorkspaceId::new(1);
149 let mut state = AppState {
150 workspaces: vec![Workspace {
151 id: ws,
152 name: "w".into(),
153 path: "/tmp".into(),
154 accent: 0,
155 expanded: true,
156 home: false,
157 unloaded: false,
158 harnesses: vec![Harness {
159 id: HarnessId::new(4),
160 workspace: ws,
161 name: "shell".into(),
162 kind: HarnessKind::Shell,
163 cwd: ".".into(),
164 status: HarnessStatus::Working,
165 subagents: vec![],
166 unread: 0,
167 tag: String::new(),
168 title: String::new(),
169 pronouns: String::new(),
170 color: None,
171 announced: true,
172 started: true,
173 }],
174 }],
175 active: Some(ws),
176 focused: Some(HarnessId::new(4)),
177 ..Default::default()
178 };
179 state.layouts.insert(
180 ws,
181 LayoutNode::split(
182 Axis::Vertical,
183 0.4,
184 LayoutNode::leaf(HarnessId::new(4)),
185 LayoutNode::leaf(HarnessId::new(5)),
186 ),
187 );
188
189 let text = serde_json::to_string(&state).unwrap();
190 let back: AppState = serde_json::from_str(&text).unwrap();
191 assert_eq!(
192 back.layouts[&ws].leaves(),
193 [HarnessId::new(4), HarnessId::new(5)]
194 );
195 assert_eq!(back.next_harness_id(), HarnessId::new(5));
196 assert_eq!(back.next_workspace_id(), WorkspaceId::new(2));
197 }
198
199 #[test]
200 fn ids_are_not_reused_while_activity_still_remembers_them() {
201 let state = AppState {
204 activity: vec![Activity {
205 time: "00:00".into(),
206 name: "gone".into(),
207 message: "left".into(),
208 accent: 0,
209 to: None,
210 harness: Some(HarnessId::new(7)),
211 ..Default::default()
212 }],
213 ..Default::default()
214 };
215 assert_eq!(state.next_harness_id(), HarnessId::new(8));
216 }
217}