| 1 | //! Settings say what the value is, where it came from and when it applies. |
| 2 | //! Hosts own persistence, schema validation and reset actions. |
| 3 | |
| 4 | use crate::{Paint, Role, Theme, glyphs, text}; |
| 5 | use ratatui::{ |
| 6 | buffer::Buffer, |
| 7 | layout::Rect, |
| 8 | style::Modifier, |
| 9 | text::{Line, Span}, |
| 10 | widgets::{Paragraph, Widget}, |
| 11 | }; |
| 12 | use std::borrow::Cow; |
| 13 | use unicode_segmentation::UnicodeSegmentation; |
| 14 | |
| 15 | // Prefer word boundaries without discarding whitespace or changing styled runs. |
| 16 | // Words wider than the row still break at whole graphemes. |
| 17 | fn wrap_spans(spans: &[Span<'static>], width: u16) -> Vec<Line<'static>> { |
| 18 | let width = usize::from(width); |
| 19 | if width == 0 { |
| 20 | return Vec::new(); |
| 21 | } |
| 22 | let graphemes: Vec<_> = spans |
| 23 | .iter() |
| 24 | .flat_map(|span| { |
| 25 | span.content.graphemes(true).map(move |grapheme| { |
| 26 | let cells = text::width(grapheme); |
| 27 | if cells > width { |
| 28 | ("?", 1, span.style) |
| 29 | } else { |
| 30 | (grapheme, cells, span.style) |
| 31 | } |
| 32 | }) |
| 33 | }) |
| 34 | .collect(); |
| 35 | let whitespace = |grapheme: &str| grapheme.chars().next().is_some_and(char::is_whitespace); |
| 36 | let mut lines = Vec::new(); |
| 37 | let mut start = 0; |
| 38 | while start < graphemes.len() { |
| 39 | let mut end = start; |
| 40 | let mut cells = 0; |
| 41 | let mut last_boundary = None; |
| 42 | while end < graphemes.len() && cells + graphemes[end].1 <= width { |
| 43 | cells += graphemes[end].1; |
| 44 | if whitespace(graphemes[end].0) { |
| 45 | last_boundary = Some(end + 1); |
| 46 | } |
| 47 | end += 1; |
| 48 | } |
| 49 | if end < graphemes.len() |
| 50 | && !whitespace(graphemes[end].0) |
| 51 | && let Some(boundary) = last_boundary |
| 52 | { |
| 53 | end = boundary; |
| 54 | } |
| 55 | let mut current: Vec<Span<'static>> = Vec::new(); |
| 56 | for &(grapheme, _, style) in &graphemes[start..end] { |
| 57 | if let Some(last) = current.last_mut() |
| 58 | && last.style == style |
| 59 | { |
| 60 | last.content.to_mut().push_str(grapheme); |
| 61 | } else { |
| 62 | current.push(Span::styled(grapheme.to_string(), style)); |
| 63 | } |
| 64 | } |
| 65 | lines.push(Line::from(current)); |
| 66 | start = end; |
| 67 | } |
| 68 | lines |
| 69 | } |
| 70 | |
| 71 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 72 | pub struct SettingWords { |
| 73 | pub applies_now: Cow<'static, str>, |
| 74 | pub changed: Cow<'static, str>, |
| 75 | pub reset: Cow<'static, str>, |
| 76 | pub default: Cow<'static, str>, |
| 77 | } |
| 78 | impl Default for SettingWords { |
| 79 | fn default() -> Self { |
| 80 | Self { |
| 81 | applies_now: "Applies now".into(), |
| 82 | changed: "changed".into(), |
| 83 | reset: "reset to default".into(), |
| 84 | default: "Default".into(), |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | #[derive(Clone, Debug)] |
| 90 | pub struct SettingRow<'a> { |
| 91 | pub label: Cow<'a, str>, |
| 92 | pub value: Cow<'a, str>, |
| 93 | pub source: Option<Cow<'a, str>>, |
| 94 | pub apply: Option<Cow<'a, str>>, |
| 95 | pub locked: Option<Cow<'a, str>>, |
| 96 | pub changed: bool, |
| 97 | pub modified: bool, |
| 98 | pub selected: bool, |
| 99 | /// Whether to show the default `applies_now` fact on unmodified, unchanged |
| 100 | /// rows when no explicit `apply` text is set (default `true`). |
| 101 | pub show_default_apply: bool, |
| 102 | pub words: SettingWords, |
| 103 | } |
| 104 | impl<'a> SettingRow<'a> { |
| 105 | #[must_use] |
| 106 | pub fn new(label: impl Into<Cow<'a, str>>, value: impl Into<Cow<'a, str>>) -> Self { |
| 107 | Self { |
| 108 | label: label.into(), |
| 109 | value: value.into(), |
| 110 | source: None, |
| 111 | apply: None, |
| 112 | locked: None, |
| 113 | changed: false, |
| 114 | modified: false, |
| 115 | selected: false, |
| 116 | show_default_apply: true, |
| 117 | words: SettingWords::default(), |
| 118 | } |
| 119 | } |
| 120 | #[must_use] |
| 121 | pub fn source(mut self, source: impl Into<Cow<'a, str>>) -> Self { |
| 122 | self.source = Some(source.into()); |
| 123 | self |
| 124 | } |
| 125 | #[must_use] |
| 126 | pub fn apply(mut self, apply: impl Into<Cow<'a, str>>) -> Self { |
| 127 | self.apply = Some(apply.into()); |
| 128 | self |
| 129 | } |
| 130 | #[must_use] |
| 131 | pub fn locked(mut self, reason: impl Into<Cow<'a, str>>) -> Self { |
| 132 | self.locked = Some(reason.into()); |
| 133 | self |
| 134 | } |
| 135 | #[must_use] |
| 136 | pub fn changed(mut self, changed: bool) -> Self { |
| 137 | self.changed = changed; |
| 138 | self |
| 139 | } |
| 140 | #[must_use] |
| 141 | pub fn modified(mut self, modified: bool) -> Self { |
| 142 | self.modified = modified; |
| 143 | self |
| 144 | } |
| 145 | #[must_use] |
| 146 | pub fn selected(mut self, selected: bool) -> Self { |
| 147 | self.selected = selected; |
| 148 | self |
| 149 | } |
| 150 | /// Control whether unmodified, unchanged rows display the default |
| 151 | /// `applies_now` fact (default `true`). Setting `false` suppresses it |
| 152 | /// unless an explicit `apply` fact is provided or the row is modified or |
| 153 | /// changed. |
| 154 | #[must_use] |
| 155 | pub fn show_default_apply(mut self, show: bool) -> Self { |
| 156 | self.show_default_apply = show; |
| 157 | self |
| 158 | } |
| 159 | #[must_use] |
| 160 | pub fn with_words(mut self, words: &SettingWords) -> Self { |
| 161 | self.words = words.clone(); |
| 162 | self |
| 163 | } |
| 164 | #[must_use] |
| 165 | pub fn lines(&self, width: u16, theme: &Theme) -> Vec<Line<'static>> { |
| 166 | let label_style = if self.selected { |
| 167 | theme.fg(Role::Foreground).add_modifier(Modifier::BOLD) |
| 168 | } else { |
| 169 | theme.fg(Role::Foreground) |
| 170 | }; |
| 171 | let marker = glyphs::pick(glyphs::selection_marker(self.selected), theme.ascii()); |
| 172 | let mut spans = vec![ |
| 173 | Span::styled(format!("{marker} "), theme.fg(Role::Accent)), |
| 174 | Span::styled(text::display_safe(&self.label).into_owned(), label_style), |
| 175 | Span::raw(" "), |
| 176 | Span::styled( |
| 177 | text::display_safe(&self.value).into_owned(), |
| 178 | theme.fg(if self.locked.is_some() { |
| 179 | Role::Muted |
| 180 | } else { |
| 181 | Role::Foreground |
| 182 | }), |
| 183 | ), |
| 184 | ]; |
| 185 | let separator = if theme.ascii() { " " } else { " · " }; |
| 186 | let apply = self.apply.as_deref().or_else(|| { |
| 187 | (self.show_default_apply || self.modified || self.changed) |
| 188 | .then_some(self.words.applies_now.as_ref()) |
| 189 | }); |
| 190 | for fact in [ |
| 191 | self.source.as_deref(), |
| 192 | apply, |
| 193 | self.locked.as_deref(), |
| 194 | self.changed.then_some(self.words.changed.as_ref()), |
| 195 | ] |
| 196 | .into_iter() |
| 197 | .flatten() |
| 198 | { |
| 199 | if !fact.is_empty() { |
| 200 | spans.push(Span::styled( |
| 201 | format!("{separator}{}", text::display_safe(fact)), |
| 202 | theme.fg(Role::Muted), |
| 203 | )); |
| 204 | } |
| 205 | } |
| 206 | // A locked setting cannot promise a reset action. |
| 207 | if self.modified && self.locked.is_none() { |
| 208 | spans.push(Span::styled( |
| 209 | format!("{separator}r {}", text::display_safe(&self.words.reset)), |
| 210 | theme.fg(Role::Muted), |
| 211 | )); |
| 212 | } |
| 213 | wrap_spans(&spans, width) |
| 214 | } |
| 215 | } |
| 216 | impl Paint for SettingRow<'_> { |
| 217 | fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) { |
| 218 | let area = area.intersection(buf.area); |
| 219 | if area.is_empty() { |
| 220 | return; |
| 221 | } |
| 222 | let lines = self.lines(area.width, theme); |
| 223 | if self.selected { |
| 224 | let shown = u16::try_from(lines.len()) |
| 225 | .unwrap_or(u16::MAX) |
| 226 | .min(area.height); |
| 227 | buf.set_style( |
| 228 | Rect { |
| 229 | height: shown, |
| 230 | ..area |
| 231 | }, |
| 232 | theme.bg(Role::Selected), |
| 233 | ); |
| 234 | } |
| 235 | Paragraph::new(lines).render(area, buf); |
| 236 | } |
| 237 | fn height(&self, width: u16, theme: &Theme) -> u16 { |
| 238 | u16::try_from(self.lines(width, theme).len()).unwrap_or(u16::MAX) |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | #[derive(Clone, Debug)] |
| 243 | pub struct SettingDetail<'a> { |
| 244 | pub label: Cow<'a, str>, |
| 245 | pub description: Cow<'a, str>, |
| 246 | pub apply: Option<Cow<'a, str>>, |
| 247 | pub source: Option<Cow<'a, str>>, |
| 248 | pub default_value: Option<Cow<'a, str>>, |
| 249 | pub locked: Option<Cow<'a, str>>, |
| 250 | pub modified: bool, |
| 251 | pub words: SettingWords, |
| 252 | } |
| 253 | impl<'a> SettingDetail<'a> { |
| 254 | #[must_use] |
| 255 | pub fn new(label: impl Into<Cow<'a, str>>, description: impl Into<Cow<'a, str>>) -> Self { |
| 256 | Self { |
| 257 | label: label.into(), |
| 258 | description: description.into(), |
| 259 | apply: None, |
| 260 | source: None, |
| 261 | default_value: None, |
| 262 | locked: None, |
| 263 | modified: false, |
| 264 | words: SettingWords::default(), |
| 265 | } |
| 266 | } |
| 267 | #[must_use] |
| 268 | pub fn apply(mut self, apply: impl Into<Cow<'a, str>>) -> Self { |
| 269 | self.apply = Some(apply.into()); |
| 270 | self |
| 271 | } |
| 272 | #[must_use] |
| 273 | pub fn source(mut self, source: impl Into<Cow<'a, str>>) -> Self { |
| 274 | self.source = Some(source.into()); |
| 275 | self |
| 276 | } |
| 277 | #[must_use] |
| 278 | pub fn default_value(mut self, value: impl Into<Cow<'a, str>>) -> Self { |
| 279 | self.default_value = Some(value.into()); |
| 280 | self |
| 281 | } |
| 282 | #[must_use] |
| 283 | pub fn locked(mut self, reason: impl Into<Cow<'a, str>>) -> Self { |
| 284 | self.locked = Some(reason.into()); |
| 285 | self |
| 286 | } |
| 287 | #[must_use] |
| 288 | pub fn modified(mut self, modified: bool) -> Self { |
| 289 | self.modified = modified; |
| 290 | self |
| 291 | } |
| 292 | #[must_use] |
| 293 | pub fn with_words(mut self, words: &SettingWords) -> Self { |
| 294 | self.words = words.clone(); |
| 295 | self |
| 296 | } |
| 297 | #[must_use] |
| 298 | pub fn lines(&self, width: u16, theme: &Theme) -> Vec<Line<'static>> { |
| 299 | if width == 0 { |
| 300 | return Vec::new(); |
| 301 | } |
| 302 | let mut lines = wrap_spans( |
| 303 | &[Span::styled( |
| 304 | text::display_safe(&self.label).into_owned(), |
| 305 | theme.fg(Role::Foreground).add_modifier(Modifier::BOLD), |
| 306 | )], |
| 307 | width, |
| 308 | ); |
| 309 | for paragraph in self.description.lines() { |
| 310 | lines.extend(wrap_spans( |
| 311 | &[Span::styled( |
| 312 | text::display_safe(paragraph).into_owned(), |
| 313 | theme.fg(Role::Foreground), |
| 314 | )], |
| 315 | width, |
| 316 | )); |
| 317 | } |
| 318 | let mut facts = vec![ |
| 319 | self.apply |
| 320 | .as_deref() |
| 321 | .unwrap_or(&self.words.applies_now) |
| 322 | .to_string(), |
| 323 | ]; |
| 324 | if let Some(source) = &self.source { |
| 325 | facts.push(source.to_string()); |
| 326 | } |
| 327 | if let Some(value) = &self.default_value { |
| 328 | facts.push(format!("{}: {value}", self.words.default)); |
| 329 | } |
| 330 | if let Some(reason) = &self.locked { |
| 331 | facts.push(reason.to_string()); |
| 332 | } |
| 333 | if self.modified && self.locked.is_none() { |
| 334 | facts.push(format!("r {}", self.words.reset)); |
| 335 | } |
| 336 | for fact in facts { |
| 337 | lines.extend(wrap_spans( |
| 338 | &[Span::styled( |
| 339 | text::display_safe(&fact).into_owned(), |
| 340 | theme.fg(Role::Muted), |
| 341 | )], |
| 342 | width, |
| 343 | )); |
| 344 | } |
| 345 | lines |
| 346 | } |
| 347 | } |
| 348 | impl Paint for SettingDetail<'_> { |
| 349 | fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) { |
| 350 | let area = area.intersection(buf.area); |
| 351 | if area.is_empty() { |
| 352 | return; |
| 353 | } |
| 354 | Paragraph::new(self.lines(area.width, theme)).render(area, buf); |
| 355 | } |
| 356 | fn height(&self, width: u16, theme: &Theme) -> u16 { |
| 357 | u16::try_from(self.lines(width, theme).len()).unwrap_or(u16::MAX) |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | /// One section entry in a [`SettingsRail`], pairing a display label with its |
| 362 | /// current item or search-match count. |
| 363 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 364 | pub struct SettingsSection<'a> { |
| 365 | /// Section title shown in the rail. |
| 366 | pub label: Cow<'a, str>, |
| 367 | /// Number of settings in this section (or matching settings while searching). |
| 368 | pub count: usize, |
| 369 | } |
| 370 | |
| 371 | impl<'a> SettingsSection<'a> { |
| 372 | /// Create a section entry with a `label` and `count`. |
| 373 | #[must_use] |
| 374 | pub fn new(label: impl Into<Cow<'a, str>>, count: usize) -> Self { |
| 375 | Self { |
| 376 | label: label.into(), |
| 377 | count, |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | /// Count how many matching items fall into each section index in |
| 383 | /// `0..section_count`. Out-of-range indices in `item_sections` are ignored. |
| 384 | #[must_use] |
| 385 | pub fn section_match_counts(section_count: usize, item_sections: &[usize]) -> Vec<usize> { |
| 386 | let mut counts = vec![0; section_count]; |
| 387 | for §ion in item_sections { |
| 388 | if let Some(slot) = counts.get_mut(section) { |
| 389 | *slot += 1; |
| 390 | } |
| 391 | } |
| 392 | counts |
| 393 | } |
| 394 | |
| 395 | /// Vertical section navigation rail for Settings, displaying per-section match |
| 396 | /// counts, dimming zero-match sections while searching, and showing an |
| 397 | /// `Esc clear` cue when a search filter is active. |
| 398 | #[derive(Clone, Debug)] |
| 399 | pub struct SettingsRail<'a> { |
| 400 | sections: &'a [SettingsSection<'a>], |
| 401 | active: usize, |
| 402 | searching: bool, |
| 403 | clear_hint: Cow<'a, str>, |
| 404 | } |
| 405 | |
| 406 | impl<'a> SettingsRail<'a> { |
| 407 | /// Create a settings rail for `sections` with `active` selected. |
| 408 | #[must_use] |
| 409 | pub fn new(sections: &'a [SettingsSection<'a>], active: usize) -> Self { |
| 410 | Self { |
| 411 | sections, |
| 412 | active, |
| 413 | searching: false, |
| 414 | clear_hint: Cow::Borrowed("Esc clear"), |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | /// Mark whether a search query is active. While searching, inactive |
| 419 | /// zero-match sections recede and the clear cue is shown when height |
| 420 | /// permits. |
| 421 | #[must_use] |
| 422 | pub const fn searching(mut self, searching: bool) -> Self { |
| 423 | self.searching = searching; |
| 424 | self |
| 425 | } |
| 426 | |
| 427 | /// Override the search-clear cue (default `"Esc clear"`). Pass an empty |
| 428 | /// string to hide it. |
| 429 | #[must_use] |
| 430 | pub fn clear_hint(mut self, hint: impl Into<Cow<'a, str>>) -> Self { |
| 431 | self.clear_hint = hint.into(); |
| 432 | self |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | impl Paint for SettingsRail<'_> { |
| 437 | fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) { |
| 438 | let area = area.intersection(buf.area); |
| 439 | if area.is_empty() { |
| 440 | return; |
| 441 | } |
| 442 | let ascii = theme.ascii(); |
| 443 | let width = usize::from(area.width); |
| 444 | let clear_text = self |
| 445 | .searching |
| 446 | .then(|| text::display_safe(&self.clear_hint).into_owned()) |
| 447 | .filter(|s| !s.is_empty()); |
| 448 | let show_clear = clear_text.is_some() && (area.height >= 2 || self.sections.is_empty()); |
| 449 | let list_rows = usize::from(area.height.saturating_sub(u16::from(show_clear))); |
| 450 | |
| 451 | if !self.sections.is_empty() && list_rows > 0 { |
| 452 | let active = self.active.min(self.sections.len() - 1); |
| 453 | let start = if active >= list_rows { |
| 454 | active + 1 - list_rows |
| 455 | } else { |
| 456 | 0 |
| 457 | }; |
| 458 | let end = (start + list_rows).min(self.sections.len()); |
| 459 | for (row_idx, section_idx) in (start..end).enumerate() { |
| 460 | let section = &self.sections[section_idx]; |
| 461 | let is_active = section_idx == active; |
| 462 | let dimmed = !is_active && self.searching && section.count == 0; |
| 463 | let y = area.y + row_idx as u16; |
| 464 | let row_rect = Rect { |
| 465 | y, |
| 466 | height: 1, |
| 467 | ..area |
| 468 | }; |
| 469 | if is_active { |
| 470 | buf.set_style(row_rect, theme.bg(Role::Selected)); |
| 471 | } |
| 472 | |
| 473 | let marker = glyphs::pick(glyphs::selection_marker(is_active), ascii); |
| 474 | let marker_w = text::width(marker) + 1; |
| 475 | let count_str = section.count.to_string(); |
| 476 | let count_w = text::width(&count_str); |
| 477 | let show_count = width >= marker_w + count_w + 2; |
| 478 | let label_budget = if show_count { |
| 479 | width.saturating_sub(marker_w + count_w + 1) |
| 480 | } else { |
| 481 | width.saturating_sub(marker_w) |
| 482 | }; |
| 483 | |
| 484 | let label_style = if is_active { |
| 485 | theme.fg(Role::Foreground).add_modifier(Modifier::BOLD) |
| 486 | } else if dimmed { |
| 487 | theme.fg(Role::Muted).add_modifier(Modifier::DIM) |
| 488 | } else { |
| 489 | theme.fg(Role::Foreground) |
| 490 | }; |
| 491 | let count_style = if is_active { |
| 492 | theme.fg(Role::Foreground) |
| 493 | } else if dimmed { |
| 494 | theme.fg(Role::Muted).add_modifier(Modifier::DIM) |
| 495 | } else { |
| 496 | theme.fg(Role::Muted) |
| 497 | }; |
| 498 | let marker_style = if is_active { |
| 499 | theme.fg(Role::Accent) |
| 500 | } else { |
| 501 | theme.fg(Role::Muted) |
| 502 | }; |
| 503 | |
| 504 | let safe_label = text::display_safe(§ion.label); |
| 505 | let mut spans = Vec::new(); |
| 506 | if width >= marker_w { |
| 507 | spans.push(Span::styled(format!("{marker} "), marker_style)); |
| 508 | if label_budget > 0 { |
| 509 | spans.push(Span::styled( |
| 510 | text::truncate(&safe_label, label_budget, ascii).into_owned(), |
| 511 | label_style, |
| 512 | )); |
| 513 | } |
| 514 | } else { |
| 515 | spans.push(Span::styled( |
| 516 | text::truncate(&safe_label, width, ascii).into_owned(), |
| 517 | label_style, |
| 518 | )); |
| 519 | } |
| 520 | Line::from(spans).render(row_rect, buf); |
| 521 | |
| 522 | if show_count { |
| 523 | let cx = area |
| 524 | .right() |
| 525 | .saturating_sub(u16::try_from(count_w).unwrap_or(0)); |
| 526 | buf.set_stringn(cx, y, &count_str, count_w, count_style); |
| 527 | } |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | if show_clear && let Some(clear) = clear_text { |
| 532 | let y = area.bottom() - 1; |
| 533 | let text = text::truncate(&clear, width, ascii); |
| 534 | buf.set_stringn(area.x, y, text.as_ref(), width, theme.fg(Role::Hint)); |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | fn height(&self, _width: u16, _theme: &Theme) -> u16 { |
| 539 | let cue = u16::from(self.searching && !text::display_safe(&self.clear_hint).is_empty()); |
| 540 | u16::try_from(self.sections.len()) |
| 541 | .unwrap_or(u16::MAX) |
| 542 | .saturating_add(cue) |
| 543 | } |
| 544 | } |
| 545 |