Skip to main content

strat9_kernel/arch/x86_64/vga/
status_line.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23use alloc::{format, string::String};
24use core::sync::atomic::{AtomicU64, Ordering};
25use spin::Mutex;
26
27use super::{
28    current_fps, is_available, with_writer, TextAlign, TextOptions, UiTheme, VgaWriter, VGA_WRITER,
29};
30
31static STATUS_LAST_REFRESH_TICK: AtomicU64 = AtomicU64::new(0);
32const STATUS_REFRESH_PERIOD_TICKS: u64 = 100; // 100Hz timer => 1s
33static STATUS_LAST_IP_REFRESH_TICK: AtomicU64 = AtomicU64::new(0);
34const STATUS_IP_REFRESH_PERIOD_TICKS: u64 = 3_000; // 100Hz timer => 30s
35
36#[derive(Debug, Clone)]
37struct StatusLineInfo {
38    hostname: String,
39    ip: String,
40}
41
42static STATUS_LINE_INFO: Mutex<Option<StatusLineInfo>> = Mutex::new(None);
43
44const STATUS_NET_INFO_DEFAULT: &str = "n/a | n/a";
45const STATUS_HOSTNAME_BUF_CAP: usize = 64;
46const STATUS_NET_BUF_CAP: usize = 96;
47const STATUS_LEFT_TEXT_CAP: usize = 128;
48const STATUS_RIGHT_TEXT_CAP: usize = 320;
49const STATUS_BAR_LEFT_MIN_COLS: usize = 8;
50const STATUS_BAR_GAP_COLS: usize = 2;
51
52/// Performs the status line info operation.
53fn status_line_info() -> StatusLineInfo {
54    let mut guard = STATUS_LINE_INFO.lock();
55    if guard.is_none() {
56        *guard = Some(StatusLineInfo {
57            hostname: String::from("strat9"),
58            ip: String::from(STATUS_NET_INFO_DEFAULT),
59        });
60    }
61    guard.as_ref().cloned().unwrap_or(StatusLineInfo {
62        hostname: String::from("strat9"),
63        ip: String::from(STATUS_NET_INFO_DEFAULT),
64    })
65}
66
67/// Stack-only string buffer to avoid heap allocation in the status-line path.
68struct StackStr<const N: usize> {
69    buf: [u8; N],
70    len: usize,
71}
72
73impl<const N: usize> StackStr<N> {
74    /// Creates a new instance.
75    const fn new() -> Self {
76        Self {
77            buf: [0; N],
78            len: 0,
79        }
80    }
81
82    fn is_empty(&self) -> bool {
83        self.len == 0
84    }
85
86    fn char_len(&self) -> usize {
87        self.as_str().chars().count()
88    }
89
90    fn push_str(&mut self, s: &str) {
91        let _ = core::fmt::Write::write_str(self, s);
92    }
93
94    fn push_char(&mut self, ch: char) {
95        let mut buf = [0u8; 4];
96        self.push_str(ch.encode_utf8(&mut buf));
97    }
98
99    /// Returns this as str.
100    fn as_str(&self) -> &str {
101        unsafe { core::str::from_utf8_unchecked(&self.buf[..self.len]) }
102    }
103}
104
105impl<const N: usize> core::fmt::Write for StackStr<N> {
106    /// Writes str.
107    fn write_str(&mut self, s: &str) -> core::fmt::Result {
108        let bytes = s.as_bytes();
109        let avail = N - self.len;
110        let n = bytes.len().min(avail);
111        self.buf[self.len..self.len + n].copy_from_slice(&bytes[..n]);
112        self.len += n;
113        Ok(())
114    }
115}
116
117impl<const N: usize> core::fmt::Display for StackStr<N> {
118    /// Performs the fmt operation.
119    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
120        f.write_str(self.as_str())
121    }
122}
123
124struct StatusLineRender {
125    left: StackStr<STATUS_LEFT_TEXT_CAP>,
126    right: StackStr<STATUS_RIGHT_TEXT_CAP>,
127}
128
129impl StatusLineRender {
130    fn new(hostname: &str, ip: &str, tick: u64) -> Self {
131        use core::fmt::Write;
132
133        let total_secs = tick / 100;
134        let h = total_secs / 3600;
135        let m = (total_secs % 3600) / 60;
136        let s = total_secs % 60;
137        let fps = current_fps(tick);
138        let mem = format_mem_usage_stack();
139
140        let mut left = StackStr::<STATUS_LEFT_TEXT_CAP>::new();
141        let _ = write!(left, " {} ", hostname);
142
143        let mut right = StackStr::<STATUS_RIGHT_TEXT_CAP>::new();
144        let _ = write!(
145            right,
146            "ip:{}  ver:{}  up:{:02}:{:02}:{:02}  ticks:{}  fps:{}  load:n/a  mem:{} ",
147            ip,
148            env!("CARGO_PKG_VERSION"),
149            h,
150            m,
151            s,
152            tick,
153            fps,
154            mem.as_str()
155        );
156
157        Self { left, right }
158    }
159}
160
161fn fit_status_bar_text<const N: usize>(text: &str, max_cols: usize) -> StackStr<N> {
162    let mut out = StackStr::<N>::new();
163    if max_cols == 0 {
164        return out;
165    }
166
167    let total_cols = text.chars().count();
168    if total_cols <= max_cols {
169        out.push_str(text);
170        return out;
171    }
172
173    if max_cols <= 3 {
174        for _ in 0..max_cols {
175            out.push_char('.');
176        }
177        return out;
178    }
179
180    for ch in text.chars().take(max_cols - 3) {
181        out.push_char(ch);
182    }
183    out.push_str("...");
184    out
185}
186
187/// Performs the draw status bar inner operation.
188fn draw_status_bar_inner(w: &mut VgaWriter, left: &str, right: &str, theme: UiTheme) {
189    let saved_clip = w.clip;
190    w.reset_clip_rect();
191
192    let (gw, gh) = w.glyph_size();
193    if gh == 0 || gw == 0 {
194        w.clip = saved_clip;
195        return;
196    }
197
198    let total_cols = w.width() / gw;
199    if total_cols == 0 {
200        w.clip = saved_clip;
201        return;
202    }
203
204    // Ensure we draw through the back buffer so present() doesn't overwrite us.
205    let (prev_draw, prev_track) = w.begin_viewport_render();
206
207    let bar_h = gh;
208    let y = w.height().saturating_sub(bar_h);
209    w.fill_rect(0, y, w.width(), bar_h, theme.status_bg);
210
211    let available_cols = total_cols.saturating_sub(STATUS_BAR_GAP_COLS);
212    let left_cols = left.chars().count();
213    let right_cols = right.chars().count();
214
215    let right_budget_cols = if left_cols.saturating_add(right_cols) > available_cols {
216        available_cols.saturating_sub(core::cmp::min(left_cols, STATUS_BAR_LEFT_MIN_COLS))
217    } else {
218        right_cols
219    };
220    let fitted_right = fit_status_bar_text::<STATUS_RIGHT_TEXT_CAP>(right, right_budget_cols);
221    let fitted_right_cols = fitted_right.char_len();
222    let left_budget_cols = available_cols.saturating_sub(fitted_right_cols);
223    let fitted_left = fit_status_bar_text::<STATUS_LEFT_TEXT_CAP>(left, left_budget_cols);
224
225    let left_width = fitted_left.char_len().saturating_mul(gw);
226    let right_width = fitted_right.char_len().saturating_mul(gw);
227
228    if !fitted_left.is_empty() {
229        let left_opts = TextOptions {
230            fg: theme.status_text,
231            bg: theme.status_bg,
232            align: TextAlign::Left,
233            wrap: false,
234            max_width: Some(left_width),
235        };
236        w.draw_text(0, y, fitted_left.as_str(), left_opts);
237    }
238
239    if !fitted_right.is_empty() {
240        let right_opts = TextOptions {
241            fg: theme.status_text,
242            bg: theme.status_bg,
243            align: TextAlign::Right,
244            wrap: false,
245            max_width: Some(right_width),
246        };
247        let right_x = w.width().saturating_sub(right_width);
248        w.draw_text(right_x, y, fitted_right.as_str(), right_opts);
249    }
250
251    w.clip = saved_clip;
252    w.end_viewport_render(prev_draw, prev_track);
253}
254
255/// Performs the ui draw status bar operation.
256pub fn ui_draw_status_bar(left: &str, right: &str, theme: UiTheme) {
257    let _ = with_writer(|w| {
258        draw_status_bar_inner(w, left, right, theme);
259    });
260}
261
262/// Sets status hostname.
263pub fn set_status_hostname(hostname: &str) {
264    let mut guard = STATUS_LINE_INFO.lock();
265    if guard.is_none() {
266        *guard = Some(StatusLineInfo {
267            hostname: String::new(),
268            ip: String::from(STATUS_NET_INFO_DEFAULT),
269        });
270    }
271    if let Some(info) = guard.as_mut() {
272        info.hostname.clear();
273        info.hostname.push_str(hostname);
274    }
275}
276
277/// Sets status ip.
278pub fn set_status_ip(ip: &str) {
279    let mut guard = STATUS_LINE_INFO.lock();
280    if guard.is_none() {
281        *guard = Some(StatusLineInfo {
282            hostname: String::from("strat9"),
283            ip: String::new(),
284        });
285    }
286    if let Some(info) = guard.as_mut() {
287        info.ip.clear();
288        info.ip.push_str(ip);
289    }
290}
291
292/// Performs the draw system status line operation.
293pub fn draw_system_status_line(theme: UiTheme) {
294    // Lite mode has no status strip: it repaints a full-width row on a timer,
295    // which is exactly the periodic framebuffer traffic we are avoiding.
296    if super::is_lite() {
297        return;
298    }
299    let info = status_line_info();
300    let tick = crate::process::scheduler::ticks();
301    let render = StatusLineRender::new(&info.hostname, &info.ip, tick);
302    ui_draw_status_bar(render.left.as_str(), render.right.as_str(), theme);
303}
304
305/// Performs the draw boot status line operation.
306pub(super) fn draw_boot_status_line(theme: UiTheme) {
307    let _ = with_writer(|w| {
308        draw_status_bar_inner(
309            w,
310            " strat9 ",
311            "ip:n/a | n/a  ver:boot  up:00:00:00  ticks:0  load:n/a  mem:n/a ",
312            theme,
313        );
314    });
315}
316
317fn read_status_net_value(paths: &[&str], invalid_values: &[&str]) -> Option<String> {
318    for path in paths {
319        let fd = match crate::vfs::open(path, crate::vfs::OpenFlags::READ) {
320            Ok(fd) => fd,
321            Err(_) => continue,
322        };
323        let mut buf = [0u8; 96];
324        let read_res = crate::vfs::read(fd, &mut buf);
325        let _ = crate::vfs::close(fd);
326        let n = match read_res {
327            Ok(n) => n,
328            Err(_) => continue,
329        };
330        if n == 0 {
331            continue;
332        }
333        let Ok(text) = core::str::from_utf8(&buf[..n]) else {
334            continue;
335        };
336        let mut value = text.trim();
337        if let Some(slash) = value.find('/') {
338            value = &value[..slash];
339        }
340        if value.is_empty() || invalid_values.iter().any(|invalid| value == *invalid) {
341            continue;
342        }
343        return Some(String::from(value));
344    }
345    None
346}
347
348/// Performs the refresh status ip from net scheme operation.
349fn refresh_status_ip_from_net_scheme() {
350    let tick = crate::process::scheduler::ticks();
351    let last = STATUS_LAST_IP_REFRESH_TICK.load(Ordering::Relaxed);
352    if tick.saturating_sub(last) < STATUS_IP_REFRESH_PERIOD_TICKS {
353        return;
354    }
355    if STATUS_LAST_IP_REFRESH_TICK
356        .compare_exchange(last, tick, Ordering::Relaxed, Ordering::Relaxed)
357        .is_err()
358    {
359        return;
360    }
361
362    let ipv4 = read_status_net_value(&["/net/address", "/net/ip"], &["0.0.0.0", "169.254.0.0"])
363        .unwrap_or_else(|| String::from("n/a"));
364    let ipv6 = read_status_net_value(&["/net/ip6/address", "/net/ip6"], &["::"])
365        .unwrap_or_else(|| String::from("n/a"));
366    let display = format!("{} | {}", ipv4, ipv6);
367    set_status_ip(&display);
368}
369
370fn try_status_line_snapshot() -> Option<(
371    StackStr<STATUS_HOSTNAME_BUF_CAP>,
372    StackStr<STATUS_NET_BUF_CAP>,
373)> {
374    let guard = STATUS_LINE_INFO.try_lock()?;
375    let (hostname, ip) = if let Some(info) = guard.as_ref() {
376        (info.hostname.as_str(), info.ip.as_str())
377    } else {
378        ("strat9", STATUS_NET_INFO_DEFAULT)
379    };
380
381    let mut hostname_buf = StackStr::<STATUS_HOSTNAME_BUF_CAP>::new();
382    hostname_buf.push_str(hostname);
383
384    let mut ip_buf = StackStr::<STATUS_NET_BUF_CAP>::new();
385    ip_buf.push_str(ip);
386
387    Some((hostname_buf, ip_buf))
388}
389
390/// Performs the maybe refresh system status line operation.
391pub fn maybe_refresh_system_status_line(theme: UiTheme) {
392    if !is_available() || super::is_lite() || !crate::vasistas_state::kernel_fb_allowed() {
393        return;
394    }
395
396    let tick = crate::process::scheduler::ticks();
397    let last = STATUS_LAST_REFRESH_TICK.load(Ordering::Relaxed);
398    if tick.saturating_sub(last) < STATUS_REFRESH_PERIOD_TICKS {
399        return;
400    }
401    if STATUS_LAST_REFRESH_TICK
402        .compare_exchange(last, tick, Ordering::Relaxed, Ordering::Relaxed)
403        .is_err()
404    {
405        return;
406    }
407    refresh_status_ip_from_net_scheme();
408
409    let Some((hostname, ip)) = try_status_line_snapshot() else {
410        return;
411    };
412
413    let render = StatusLineRender::new(hostname.as_str(), ip.as_str(), tick);
414
415    if let Some(mut writer) = VGA_WRITER.try_lock() {
416        draw_status_bar_inner(
417            &mut writer,
418            render.left.as_str(),
419            render.right.as_str(),
420            theme,
421        );
422        writer.flush_display();
423    }
424}
425
426fn format_mem_usage_stack() -> StackStr<32> {
427    use core::fmt::Write;
428
429    let lock = crate::memory::buddy::get_allocator();
430    let Some(guard) = lock.try_lock() else {
431        let mut buf = StackStr::<32>::new();
432        buf.push_str("n/a");
433        return buf;
434    };
435    let Some(alloc) = guard.as_ref() else {
436        let mut buf = StackStr::<32>::new();
437        buf.push_str("n/a");
438        return buf;
439    };
440
441    let (total_pages, allocated_pages) = alloc.page_totals();
442    let page_size = 4096usize;
443    let total = total_pages.saturating_mul(page_size);
444    let used = allocated_pages.saturating_mul(page_size);
445    let free = total.saturating_sub(used);
446
447    let mut buf = StackStr::<32>::new();
448    let _ = write!(
449        buf,
450        "{}/{}",
451        format_size_stack(free),
452        format_size_stack(total)
453    );
454    buf
455}
456
457/// Performs the format size stack operation.
458fn format_size_stack(bytes: usize) -> StackStr<16> {
459    use core::fmt::Write;
460    const KB: usize = 1024;
461    const MB: usize = 1024 * KB;
462    const GB: usize = 1024 * MB;
463    let mut buf = StackStr::<16>::new();
464    if bytes >= GB {
465        let _ = write!(buf, "{}G", bytes / GB);
466    } else if bytes >= MB {
467        let _ = write!(buf, "{}M", bytes / MB);
468    } else if bytes >= KB {
469        let _ = write!(buf, "{}K", bytes / KB);
470    } else {
471        let _ = write!(buf, "{}B", bytes);
472    }
473    buf
474}
475
476/// Performs the status line task main operation.
477pub extern "C" fn status_line_task_main() -> ! {
478    let mut last_tick = 0u64;
479    let mut diag_counter = 0u64;
480    loop {
481        let tick = crate::process::scheduler::ticks();
482        // In quiet mode, skip all rendering and heartbeat output.
483        if !crate::debug_cfg::is_quiet() && tick != last_tick {
484            last_tick = tick;
485            // Fallback if creation of the dedicated console task failed.
486            if !crate::arch::x86_64::vgabuf::console_task_active() {
487                crate::arch::x86_64::vgabuf::vgabuf_flush_to_framebuffer();
488            }
489            maybe_refresh_system_status_line(UiTheme::OCEAN_STATUS);
490        }
491        diag_counter += 1;
492        if !crate::debug_cfg::is_quiet() && diag_counter % 5000 == 0 {
493            crate::serial_println!(
494                "[status-line] heartbeat tick={} vga={}",
495                tick,
496                is_available()
497            );
498        }
499        crate::process::yield_task();
500    }
501}