1use ratatui::layout::{Constraint, Layout, Rect};
2use ratatui::style::{Color, Modifier, Style};
3use ratatui::widgets::{Block, Borders, List, ListItem, ListState, Paragraph};
4use ratatui::Frame;
5
6use crate::config::{disk_has_unresolved_keyring_sentinel, Config};
7
8#[derive(PartialEq, Eq)]
9pub enum SettingsField {
10 BaseUrl,
11 DownloadDir,
12 UseHttps,
13}
14
15pub struct SettingsScreen {
17 pub base_url: String,
18 pub download_dir: String,
19 pub use_https: bool,
20 pub auth_status: String,
21 pub version: String,
22 pub server_version: String,
23 pub github_url: String,
24
25 pub selected_index: usize,
26 pub editing: bool,
27 pub edit_buffer: String,
28 pub edit_cursor: usize,
29 pub message: Option<(String, Color)>,
30}
31
32impl SettingsScreen {
33 pub fn new(config: &Config, romm_server_version: Option<&str>) -> Self {
34 let auth_status = match &config.auth {
35 Some(crate::config::AuthConfig::Basic { username, .. }) => {
36 format!("Basic (user: {})", username)
37 }
38 Some(crate::config::AuthConfig::Bearer { .. }) => "API Token".to_string(),
39 Some(crate::config::AuthConfig::ApiKey { header, .. }) => {
40 format!("API key (header: {})", header)
41 }
42 None => {
43 if disk_has_unresolved_keyring_sentinel(config) {
44 "None — disk still references keyring; set API_TOKEN / ROMM_TOKEN_FILE or see docs/troubleshooting-auth.md"
45 .to_string()
46 } else {
47 "None (no API credentials in env/keyring)".to_string()
48 }
49 }
50 };
51
52 let server_version = romm_server_version
53 .map(String::from)
54 .unwrap_or_else(|| "unavailable (heartbeat failed)".to_string());
55
56 Self {
57 base_url: config.base_url.clone(),
58 download_dir: config.download_dir.clone(),
59 use_https: config.use_https,
60 auth_status,
61 version: env!("CARGO_PKG_VERSION").to_string(),
62 server_version,
63 github_url: "https://github.com/patricksmill/romm-cli".to_string(),
64 selected_index: 0,
65 editing: false,
66 edit_buffer: String::new(),
67 edit_cursor: 0,
68 message: None,
69 }
70 }
71
72 pub fn next(&mut self) {
73 if !self.editing {
74 self.selected_index = (self.selected_index + 1) % 4;
75 }
76 }
77
78 pub fn previous(&mut self) {
79 if !self.editing {
80 if self.selected_index == 0 {
81 self.selected_index = 3;
82 } else {
83 self.selected_index -= 1;
84 }
85 }
86 }
87
88 pub fn enter_edit(&mut self) {
89 if self.selected_index == 2 {
90 self.use_https = !self.use_https;
92 if self.use_https && self.base_url.starts_with("http://") {
93 self.base_url = self.base_url.replace("http://", "https://");
94 self.message = Some(("Upgraded to HTTPS".to_string(), Color::Green));
95 }
96 } else {
97 self.editing = true;
98 self.edit_buffer = if self.selected_index == 0 {
99 self.base_url.clone()
100 } else {
101 self.download_dir.clone()
102 };
103 self.edit_cursor = self.edit_buffer.len();
104 }
105 }
106
107 pub fn save_edit(&mut self) -> bool {
108 if !self.editing {
109 return true; }
111 if self.selected_index == 0 {
112 self.base_url = self.edit_buffer.trim().to_string();
113 } else if self.selected_index == 1 {
114 self.download_dir = self.edit_buffer.trim().to_string();
115 }
116 self.editing = false;
117 true
118 }
119
120 pub fn cancel_edit(&mut self) {
121 self.editing = false;
122 self.message = None;
123 }
124
125 pub fn add_char(&mut self, c: char) {
126 if self.editing {
127 self.edit_buffer.insert(self.edit_cursor, c);
128 self.edit_cursor += 1;
129 }
130 }
131
132 pub fn delete_char(&mut self) {
133 if self.editing && self.edit_cursor > 0 {
134 self.edit_buffer.remove(self.edit_cursor - 1);
135 self.edit_cursor -= 1;
136 }
137 }
138
139 pub fn move_cursor_left(&mut self) {
140 if self.editing && self.edit_cursor > 0 {
141 self.edit_cursor -= 1;
142 }
143 }
144
145 pub fn move_cursor_right(&mut self) {
146 if self.editing && self.edit_cursor < self.edit_buffer.len() {
147 self.edit_cursor += 1;
148 }
149 }
150
151 pub fn render(&self, f: &mut Frame, area: Rect) {
152 let chunks = Layout::default()
153 .constraints([
154 Constraint::Length(4), Constraint::Min(10), Constraint::Length(3), Constraint::Length(3), ])
159 .direction(ratatui::layout::Direction::Vertical)
160 .split(area);
161
162 let info = [
164 format!(
165 "romm-cli: v{} | RomM server: {}",
166 self.version, self.server_version
167 ),
168 format!("GitHub: {}", self.github_url),
169 format!("Auth: {}", self.auth_status),
170 ];
171 f.render_widget(
172 Paragraph::new(info.join("\n")).block(Block::default().borders(Borders::BOTTOM)),
173 chunks[0],
174 );
175
176 let items = [
178 ListItem::new(format!(
179 "Base URL: {}",
180 if self.editing && self.selected_index == 0 {
181 &self.edit_buffer
182 } else {
183 &self.base_url
184 }
185 )),
186 ListItem::new(format!(
187 "Download Dir: {}",
188 if self.editing && self.selected_index == 1 {
189 &self.edit_buffer
190 } else {
191 &self.download_dir
192 }
193 )),
194 ListItem::new(format!(
195 "Use HTTPS: {}",
196 if self.use_https { "[X] Yes" } else { "[ ] No" }
197 )),
198 ListItem::new(format!(
199 "Auth: {} (Enter to change)",
200 self.auth_status
201 )),
202 ];
203
204 let mut state = ListState::default();
205 state.select(Some(self.selected_index));
206
207 let list = List::new(items)
208 .block(
209 Block::default()
210 .title(" Configuration ")
211 .borders(Borders::ALL),
212 )
213 .highlight_style(
214 Style::default()
215 .add_modifier(Modifier::BOLD)
216 .fg(Color::Yellow),
217 )
218 .highlight_symbol(">> ");
219
220 f.render_stateful_widget(list, chunks[1], &mut state);
221
222 if let Some((msg, color)) = &self.message {
224 f.render_widget(
225 Paragraph::new(msg.as_str()).style(Style::default().fg(*color)),
226 chunks[2],
227 );
228 } else if self.editing {
229 f.render_widget(
230 Paragraph::new("Editing... Enter: save Esc: cancel")
231 .style(Style::default().fg(Color::Cyan)),
232 chunks[2],
233 );
234 }
235
236 let help = if self.editing {
238 "Backspace: delete Arrows: move cursor Enter: save Esc: cancel"
239 } else {
240 "↑/↓: select Enter: edit/toggle S: save to disk Esc: back"
241 };
242 f.render_widget(
243 Paragraph::new(help).block(Block::default().borders(Borders::ALL)),
244 chunks[3],
245 );
246 }
247
248 pub fn cursor_position(&self, area: Rect) -> Option<(u16, u16)> {
249 if !self.editing {
250 return None;
251 }
252
253 let chunks = Layout::default()
254 .constraints([
255 Constraint::Length(4),
256 Constraint::Min(10),
257 Constraint::Length(3),
258 Constraint::Length(3),
259 ])
260 .direction(ratatui::layout::Direction::Vertical)
261 .split(area);
262
263 let list_area = chunks[1];
264 let y = list_area.y + 1 + self.selected_index as u16;
265 let label_len = 17;
267 let x = list_area.x + 3 + label_len + self.edit_cursor as u16;
268
269 Some((x, y))
270 }
271}