From d24536002b5cf317f81477fe1cf50564aee01d8b Mon Sep 17 00:00:00 2001 From: Adnan Jaweed Date: Mon, 7 Sep 2026 08:53:01 -0400 Subject: [PATCH 1/7] Add Linux native monitoring and sampled game FPS preview --- .github/workflows/linux.yml | 62 +++ tauri-app/src-tauri/Cargo.toml | 2 +- tauri-app/src-tauri/linux/cleanmeter-run | 39 ++ tauri-app/src-tauri/src/commands.rs | 25 +- tauri-app/src-tauri/src/lib.rs | 52 +- tauri-app/src-tauri/src/linux_autostart.rs | 57 ++ tauri-app/src-tauri/src/linux_fps.rs | 141 +++++ tauri-app/src-tauri/src/linux_monitor.rs | 175 +++++++ tauri-app/src-tauri/src/linux_sensors.rs | 489 ++++++++++++++++++ tauri-app/src-tauri/src/main.rs | 17 + tauri-app/src-tauri/src/platform.rs | 38 ++ tauri-app/src-tauri/src/shortcuts.rs | 2 + tauri-app/src-tauri/src/tray.rs | 11 +- tauri-app/src-tauri/tauri.conf.json | 15 +- tauri-app/src-tauri/tauri.linux.conf.json | 32 ++ tauri-app/src-tauri/tauri.windows.conf.json | 10 + tauri-app/src/App.tsx | 10 +- tauri-app/src/OverlayApp.tsx | 6 +- .../src/components/overlay/FpsSection.tsx | 10 +- .../src/components/settings/LinuxSupport.tsx | 24 + tauri-app/src/components/settings/TopBar.tsx | 4 +- .../settings/settings/SettingsTab.tsx | 15 +- .../components/settings/stats/FpsSection.tsx | 33 +- .../components/settings/stats/StatsTab.tsx | 2 + .../settings/style/PositionGrid.tsx | 3 + tauri-app/src/lib/tauri.ts | 16 + tauri-app/src/stores/platform-store.ts | 11 + 27 files changed, 1250 insertions(+), 51 deletions(-) create mode 100644 .github/workflows/linux.yml create mode 100755 tauri-app/src-tauri/linux/cleanmeter-run create mode 100644 tauri-app/src-tauri/src/linux_autostart.rs create mode 100644 tauri-app/src-tauri/src/linux_fps.rs create mode 100644 tauri-app/src-tauri/src/linux_monitor.rs create mode 100644 tauri-app/src-tauri/src/linux_sensors.rs create mode 100644 tauri-app/src-tauri/src/platform.rs create mode 100644 tauri-app/src-tauri/tauri.linux.conf.json create mode 100644 tauri-app/src-tauri/tauri.windows.conf.json create mode 100644 tauri-app/src/components/settings/LinuxSupport.tsx create mode 100644 tauri-app/src/stores/platform-store.ts diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml new file mode 100644 index 0000000..6979b0d --- /dev/null +++ b/.github/workflows/linux.yml @@ -0,0 +1,62 @@ +name: Linux preview + +on: + push: + branches: [feat/linux-support] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + linux: + runs-on: ubuntu-22.04 + timeout-minutes: 45 + defaults: + run: + working-directory: tauri-app + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + cache-dependency-path: tauri-app/package-lock.json + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + with: + workspaces: tauri-app/src-tauri + - name: Install Linux build and smoke-test dependencies + run: | + sudo apt-get update + sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev patchelf rpm xvfb dbus-x11 + - run: npm ci + - run: npm run lint && npm test && npm run build + - name: Test native backend + run: cargo test --locked --manifest-path src-tauri/Cargo.toml --lib + - name: Build Linux packages + env: + APPIMAGE_EXTRACT_AND_RUN: '1' + run: npm run tauri -- build --bundles deb,rpm,appimage + - name: Smoke test GUI and native monitoring + run: | + set +e + RUST_LOG=info WEBKIT_DISABLE_COMPOSITING_MODE=1 timeout 15s dbus-run-session -- xvfb-run -a src-tauri/target/release/cleanmeter > linux-smoke.log 2>&1 + result=$? + set -e + cat linux-smoke.log + test "$result" -eq 124 + grep -q 'Linux monitoring connected' linux-smoke.log + test -x src-tauri/linux/cleanmeter-run + - uses: actions/upload-artifact@v4 + if: always() + with: + name: cleanmeter-linux-x86_64 + if-no-files-found: error + path: | + tauri-app/src-tauri/target/release/bundle/deb/*.deb + tauri-app/src-tauri/target/release/bundle/rpm/*.rpm + tauri-app/src-tauri/target/release/bundle/appimage/*.AppImage + tauri-app/linux-smoke.log diff --git a/tauri-app/src-tauri/Cargo.toml b/tauri-app/src-tauri/Cargo.toml index b2341d0..bfe993f 100644 --- a/tauri-app/src-tauri/Cargo.toml +++ b/tauri-app/src-tauri/Cargo.toml @@ -31,9 +31,9 @@ log = "0.4" env_logger = "0.11" dirs = "6" -winreg = "0.55" [target.'cfg(windows)'.dependencies] +winreg = "0.55" windows = { version = "0.58", features = [ "Win32_Foundation", "Win32_Storage_FileSystem", diff --git a/tauri-app/src-tauri/linux/cleanmeter-run b/tauri-app/src-tauri/linux/cleanmeter-run new file mode 100755 index 0000000..68c4f9b --- /dev/null +++ b/tauri-app/src-tauri/linux/cleanmeter-run @@ -0,0 +1,39 @@ +#!/bin/sh +# Launch a native or Proton game with sampled FPS telemetry for Cleanmeter. +set -eu +if [ "$#" -eq 0 ]; then + echo 'Usage: cleanmeter-run [args...]' >&2 + echo 'Steam launch options: cleanmeter-run %command%' >&2 + exit 2 +fi +if ! command -v mangohud >/dev/null 2>&1; then + echo 'Install MangoHud first (Ubuntu/Debian: sudo apt install mangohud).' >&2 + exit 1 +fi +case "${XDG_CACHE_HOME:-}" in + /*) cache=$XDG_CACHE_HOME ;; + *) cache=$HOME/.cache ;; +esac +umask 077 +mkdir -p "$cache/cleanmeter/fps" +session=$(mktemp -d "$cache/cleanmeter/fps/session.XXXXXX") +case "$session" in + *,*) echo 'MangoHud requires a cache path without commas.' >&2; rmdir "$session"; exit 1 ;; +esac +child= +cleanup() { rm -rf -- "$session"; } +trap cleanup EXIT +trap 'if [ -n "$child" ]; then kill -TERM "$child" 2>/dev/null || true; fi' INT TERM +# A private config file avoids altering the user's MangoHud configuration. +# Uploads are not enabled. Files are removed when the launched process exits. +cat > "$session/MangoHud.conf" < bool { +fn foreground_is_ours(_app: &AppHandle) -> bool { use windows::Win32::System::Threading::GetCurrentProcessId; use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId}; unsafe { @@ -192,15 +192,9 @@ fn foreground_is_ours() -> bool { } } -/// Non-Windows stub. Returning `false` leaves the overlay permanently click-through -/// off Windows, which is the honest answer: there is no foreground check implemented -/// there, and the app is Windows-only in every load-bearing part (requireAdministrator -/// manifest, the PawnIO driver, PresentMon, the HardwareMonitor sidecar). CI builds a -/// single `windows-latest` matrix entry, so a second real implementation here could -/// never be compiled or tested and would only rot. #[cfg(not(windows))] -fn foreground_is_ours() -> bool { - false +fn foreground_is_ours(app: &AppHandle) -> bool { + app.webview_windows().values().any(|w| w.is_focused().unwrap_or(false)) } /// Bring a window to the front without letting tao fabricate a keystroke. @@ -299,7 +293,7 @@ pub fn sync_overlay_interactive(app: &AppHandle) { .get_webview_window("settings") .map(|w| w.is_visible().unwrap_or(false)) .unwrap_or(false); - apply_overlay_interactive(app, settings_shown && foreground_is_ours()); + apply_overlay_interactive(app, settings_shown && foreground_is_ours(app)); } #[tauri::command] @@ -320,6 +314,7 @@ pub fn set_overlay_visible(visible: bool, app: AppHandle) { #[tauri::command] pub fn set_overlay_position(x: i32, y: i32, app: AppHandle) { + if crate::platform::native_wayland() { return; } if let Some(overlay) = app.get_webview_window("overlay") { let _ = overlay.set_position(tauri::Position::Physical(tauri::PhysicalPosition::new(x, y))); } @@ -389,6 +384,12 @@ const AUTOSTART_TASK: &str = "CleanMeter"; #[tauri::command] pub fn set_auto_start(enabled: bool) -> Result<(), String> { + #[cfg(target_os = "linux")] + { + let config=dirs::config_dir().ok_or("Configuration directory unavailable")?; + let exe=std::env::var_os("APPIMAGE").map(std::path::PathBuf::from).unwrap_or(std::env::current_exe().map_err(|e|e.to_string())?); + return crate::linux_autostart::set(&config,&exe,enabled); + } #[cfg(windows)] { use std::os::windows::process::CommandExt; @@ -450,6 +451,8 @@ pub fn set_auto_start(enabled: bool) -> Result<(), String> { #[tauri::command] pub fn get_auto_start() -> bool { + #[cfg(target_os = "linux")] + return dirs::config_dir().map(|p|crate::linux_autostart::enabled(&p)).unwrap_or(false); #[cfg(windows)] { use std::os::windows::process::CommandExt; diff --git a/tauri-app/src-tauri/src/lib.rs b/tauri-app/src-tauri/src/lib.rs index aeb2e17..5c0fc3b 100644 --- a/tauri-app/src-tauri/src/lib.rs +++ b/tauri-app/src-tauri/src/lib.rs @@ -1,3 +1,12 @@ +mod platform; +#[cfg(any(target_os = "linux", test))] +mod linux_sensors; +#[cfg(any(target_os = "linux", test))] +mod linux_fps; +#[cfg(any(target_os = "linux", test))] +mod linux_autostart; +#[cfg(target_os = "linux")] +mod linux_monitor; mod commands; mod pipe_client; mod shortcuts; @@ -254,10 +263,20 @@ pub fn run() { return; } + // Prefer XWayland on Wayland desktops that provide it: absolute overlay + // placement and global shortcuts are X11 capabilities. Respect an explicit + // GDK_BACKEND choice and retain a windowed native-Wayland fallback. + #[cfg(target_os = "linux")] + if std::env::var_os("GDK_BACKEND").is_none() && std::env::var_os("DISPLAY").is_some() { + std::env::set_var("GDK_BACKEND", "x11"); + } env_logger::init(); - tauri::Builder::default() - .plugin(tauri_plugin_global_shortcut::Builder::new().build()) + let mut builder = tauri::Builder::default(); + if !platform::native_wayland() { + builder = builder.plugin(tauri_plugin_global_shortcut::Builder::new().build()); + } + builder .plugin(tauri_plugin_fs::init()) .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_shell::init()) @@ -345,9 +364,11 @@ pub fn run() { } // Honor "Start minimized": when on, leave the settings window // hidden (config is visible:false) so the app starts to tray. - if !start_minimized { + if !start_minimized || cfg!(target_os = "linux") { let _ = window.show(); commands::bring_to_front(&window); + #[cfg(target_os = "linux")] + if start_minimized {let _=window.minimize();} } } @@ -362,17 +383,36 @@ pub fn run() { let app_handle = app.handle().clone(); let running = Arc::new(AtomicBool::new(true)); let running_clone = running.clone(); + #[cfg(windows)] let running_for_hw = running.clone(); + #[cfg(not(target_os = "linux"))] tauri::async_runtime::spawn(async move { pipe_client::run_pipe_client(app_handle, cmd_rx, running_clone).await; }); + #[cfg(target_os = "linux")] + { + app.manage(SidecarHealth::default()); + let settings=app.state::().get_settings(); + std::thread::spawn(move || linux_monitor::run(app_handle,cmd_rx,running_clone,settings.polling_rate,settings.sensors.framerate.target_app_name)); + if platform::native_wayland() { + if let Some(overlay)=app.get_webview_window("overlay") { + let _=overlay.set_decorations(true); + let _=overlay.set_focusable(true); + let _=overlay.set_skip_taskbar(false); + let _=overlay.set_title("Cleanmeter — hardware monitor"); + } + } + } // Store running flag for cleanup app.manage(running); // Set up system tray - tray::setup_tray(app.handle())?; + if let Err(error)=tray::setup_tray(app.handle()) { + log::warn!("System tray unavailable: {error}"); + if let Some(window)=app.get_webview_window("settings") {let _=window.show();} + } // Supervise HardwareMonitor as a child process. Spawning it once was // fragile: if a stale instance still held the named pipe at launch @@ -600,7 +640,10 @@ pub fn run() { tauri::WindowEvent::CloseRequested { api, .. } => { api.prevent_close(); if let Some(window) = app_handle3.get_webview_window("settings") { + #[cfg(not(target_os = "linux"))] let _ = window.hide(); + #[cfg(target_os = "linux")] + let _ = window.minimize(); } // hide() is not guaranteed to emit Focused(false), so // close the gate explicitly on the hide-to-tray path. @@ -646,6 +689,7 @@ pub fn run() { Ok(()) }) .invoke_handler(tauri::generate_handler![ + platform::get_platform_info, commands::get_settings, commands::save_settings, commands::clear_settings, diff --git a/tauri-app/src-tauri/src/linux_autostart.rs b/tauri-app/src-tauri/src/linux_autostart.rs new file mode 100644 index 0000000..5af8654 --- /dev/null +++ b/tauri-app/src-tauri/src/linux_autostart.rs @@ -0,0 +1,57 @@ +use std::{fs, path::Path}; + +/// Desktop Entry Exec quoting has two escaping layers: argument quoting and +/// desktop-string escaping. Percent is a field-code marker, not a shell escape. +fn desktop_exec(exe: &str) -> Result { + if exe.chars().any(|c| c == '\n' || c == '\r' || c == '\0') { + return Err("Invalid executable path".into()); + } + let mut out = String::from("\""); + for c in exe.chars() { + match c { + '%' => out.push_str("%%"), + '\\' => out.push_str("\\\\\\\\"), + '"' | '`' | '$' => { + out.push_str("\\\\"); + out.push(c); + } + _ => out.push(c), + } + } + out.push('"'); + Ok(out) +} +pub fn set(config: &Path, exe: &Path, enabled: bool) -> Result<(), String> { + let path = config.join("autostart/com.cleanmeter.desktop.desktop"); + if !enabled { + return match fs::remove_file(path) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e.to_string()), + }; + } + let exec = desktop_exec(exe.to_str().ok_or("Executable path is not UTF-8")?)?; + fs::create_dir_all(path.parent().unwrap()).map_err(|e| e.to_string())?; + fs::write(path,format!("[Desktop Entry]\nType=Application\nName=Cleanmeter\nExec={exec}\nTerminal=false\nX-GNOME-Autostart-enabled=true\n")).map_err(|e|e.to_string()) +} +pub fn enabled(config: &Path) -> bool { + fs::read_to_string(config.join("autostart/com.cleanmeter.desktop.desktop")) + .map(|s| { + !s.lines() + .any(|l| matches!(l.trim(), "Hidden=true" | "X-GNOME-Autostart-enabled=false")) + }) + .unwrap_or(false) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn exec_paths_are_literal() { + assert_eq!( + desktop_exec("/opt/Clean meter/100%/app").unwrap(), + "\"/opt/Clean meter/100%%/app\"" + ); + assert_eq!(desktop_exec("/tmp/$HOME").unwrap(), "\"/tmp/\\\\$HOME\""); + assert!(desktop_exec("a\nb").is_err()); + } +} diff --git a/tauri-app/src-tauri/src/linux_fps.rs b/tauri-app/src-tauri/src/linux_fps.rs new file mode 100644 index 0000000..3527e3d --- /dev/null +++ b/tauri-app/src-tauri/src/linux_fps.rs @@ -0,0 +1,141 @@ +//! Read live MangoHud CSV samples created by cleanmeter-run. This is sampled +//! FPS/frametime, not per-frame capture, so percentile-low recording is omitted. +use std::{ + fs::{self, File}, + io::{Read, Seek, SeekFrom}, + path::{Path, PathBuf}, + time::{Duration, SystemTime}, +}; + +#[derive(Clone, Debug)] +pub struct FpsSample { + pub app: String, + pub fps: f32, + pub frametime: f32, + pub modified: SystemTime, +} + +fn columns(header: &str) -> Option<(usize, usize)> { + let v: Vec<_> = header.trim().split(',').map(str::trim).collect(); + Some(( + v.iter().position(|s| *s == "fps")?, + v.iter().position(|s| *s == "frametime")?, + )) +} +fn values(row: &str, columns: (usize, usize)) -> Option<(f32, f32)> { + let v: Vec<_> = row.trim().split(',').collect(); + let fps: f32 = v.get(columns.0)?.trim().parse().ok()?; + let ft: f32 = v.get(columns.1)?.trim().parse().ok()?; + if !fps.is_finite() || !ft.is_finite() || fps <= 0.0 || ft <= 0.0 { + return None; + } + Some((fps, ft)) +} +fn read_sample(path: &Path, now: SystemTime) -> Option { + let meta = fs::symlink_metadata(path).ok()?; + if !meta.file_type().is_file() || meta.len() > 128 * 1024 * 1024 { + return None; + } + let modified = meta.modified().ok()?; + if now.duration_since(modified).unwrap_or_default() > Duration::from_secs(3) { + return None; + } + let mut f = File::open(path).ok()?; + let mut header = String::new(); + f.by_ref().take(4096).read_to_string(&mut header).ok()?; + let cols = header.lines().find_map(columns)?; + let offset = meta.len().saturating_sub(16384); + f.seek(SeekFrom::Start(offset)).ok()?; + let mut tail = String::new(); + f.take(16384).read_to_string(&mut tail).ok()?; + // A producer may be halfway through a write. Only consume complete rows. + let end = tail.rfind('\n')?; + let start = if offset > 0 { tail.find('\n')? + 1 } else { 0 }; + if start >= end { + return None; + } + let (fps, frametime) = tail[start..end] + .lines() + .rev() + .find_map(|l| values(l, cols))?; + let stem = path.file_stem()?.to_str()?; + // MangoHud names logs _YYYY-MM-DD_HH-MM-SS.csv. + let app = if stem.len() > 20 && stem.is_char_boundary(stem.len() - 20) { + &stem[..stem.len() - 20] + } else { + stem + }; + Some(FpsSample { + app: app.to_string(), + fps, + frametime, + modified, + }) +} + +pub fn samples(root: &Path) -> Vec { + let now = SystemTime::now(); + let mut result = vec![]; + let sessions: Vec = fs::read_dir(root) + .into_iter() + .flatten() + .filter_map(Result::ok) + .take(128) + .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false)) + .map(|e| e.path()) + .collect(); + for session in sessions { + for file in fs::read_dir(session) + .into_iter() + .flatten() + .filter_map(Result::ok) + .take(64) + { + let path = file.path(); + if path.extension().and_then(|s| s.to_str()) != Some("csv") + || path.to_string_lossy().ends_with("_summary.csv") + { + continue; + } + if let Some(sample) = read_sample(&path, now) { + result.push(sample); + } + } + } + result.sort_by(|a, b| b.modified.cmp(&a.modified)); + result +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn headers_are_not_assumed_to_have_fixed_positions() { + let c = columns("cpu_load,frametime,fps,elapsed").unwrap(); + assert_eq!(values("30,8.3,120,500", c), Some((120.0, 8.3))); + assert_eq!(values("0,NaN,120,1", c), None); + assert_eq!(columns("os,cpu,gpu"), None); + } + #[test] + fn reads_latest_complete_row_and_rejects_stale_logs() { + let dir = std::env::temp_dir().join(format!( + "cleanmeter-fps-{}", + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&dir).unwrap(); + let p = dir.join("game_2026-09-07_12-00-00.csv"); + fs::write( + &p, + "os,cpu,gpu\nLinux,CPU,GPU\nfps,frametime,elapsed\n60,16.6,100\n120,8.3,200\n999,1", + ) + .unwrap(); + let sample = read_sample(&p, SystemTime::now()).unwrap(); + assert_eq!(sample.app, "game"); + assert_eq!(sample.fps, 120.0); + assert!(read_sample(&p, SystemTime::now() + Duration::from_secs(10)).is_none()); + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/tauri-app/src-tauri/src/linux_monitor.rs b/tauri-app/src-tauri/src/linux_monitor.rs new file mode 100644 index 0000000..b6715b7 --- /dev/null +++ b/tauri-app/src-tauri/src/linux_monitor.rs @@ -0,0 +1,175 @@ +use crate::{ + commands::SidecarHealth, + linux_fps, + linux_sensors::{append_nvidia, sensor, LinuxSensors}, + pipe_client::PipeCommand, + types::{Hardware, HardwareType, PipeStatus, SensorType, SidecarStatus}, +}; +use std::{ + io::Read, + path::Path, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + time::{Duration, Instant}, +}; +use tauri::{AppHandle, Emitter, Manager}; +use tokio::sync::mpsc; + +/// Bound driver-tool latency: a stuck NVIDIA driver must not stall CPU/RAM. +fn nvidia() -> String { + use std::process::{Command, Stdio}; + let Ok(mut child)=Command::new("nvidia-smi").args(["--query-gpu=uuid,name,utilization.gpu,temperature.gpu,memory.used,memory.total,power.draw","--format=csv,noheader,nounits"]).stdout(Stdio::piped()).stderr(Stdio::null()).spawn() else {return String::new()}; + let start = Instant::now(); + loop { + match child.try_wait() { + Ok(Some(status)) => { + let mut out = String::new(); + if status.success() { + if let Some(stdout) = child.stdout.take() { + let _ = stdout.take(32768).read_to_string(&mut out); + } + } + return out; + } + Err(_) => { + let _ = child.kill(); + let _ = child.wait(); + return String::new(); + } + _ => {} + } + if start.elapsed() > Duration::from_millis(750) { + let _ = child.kill(); + let _ = child.wait(); + return String::new(); + } + std::thread::sleep(Duration::from_millis(10)); + } +} + +pub fn run( + app: AppHandle, + mut commands: mpsc::Receiver, + running: Arc, + polling: u64, + target: String, +) { + let mut reader = LinuxSensors::default(); + let mut interval = Duration::from_millis(polling.clamp(100, 5000)); + let mut target = target; + let fps_dir = dirs::cache_dir() + .unwrap_or_else(std::env::temp_dir) + .join("cleanmeter/fps"); + let mut previous = Instant::now(); + let mut next = Instant::now(); + let mut nv_next = Instant::now(); + let mut nv = String::new(); + let mut connected = false; + let mut last_apps = vec![]; + while running.load(Ordering::Relaxed) { + while let Ok(command) = commands.try_recv() { + match command { + PipeCommand::SelectPollingRate(ms) => { + interval = Duration::from_millis(u64::from(ms).clamp(100, 5000)); + next = Instant::now(); + } + PipeCommand::SelectPresentMonApp(app) => { + target = if app == "Auto" { String::new() } else { app } + } + PipeCommand::RefreshPresentMonApps => { + last_apps.clear(); + next = Instant::now(); + } + PipeCommand::SetLowsMode(_) => {} + } + } + if Instant::now() < next { + std::thread::sleep(Duration::from_millis(20)); + continue; + } + let now = Instant::now(); + let elapsed = now.duration_since(previous); + previous = now; + match reader.sample(Path::new("/proc"), Path::new("/sys"), elapsed) { + Ok(mut data) => { + if now >= nv_next { + nv = nvidia(); + nv_next = Instant::now() + Duration::from_secs(1); + } + append_nvidia(&mut data, &nv); + let samples = linux_fps::samples(&fps_dir); + let mut apps: Vec<_> = samples.iter().map(|s| s.app.clone()).collect(); + apps.sort(); + apps.dedup(); + if apps != last_apps { + let _ = app.emit("present-mon-apps", &apps); + last_apps = apps; + } + let chosen = if target.is_empty() || target == "Auto" { + samples.first() + } else { + samples.iter().find(|s| s.app == target) + }; + if let Some(s) = chosen { + let id = "/linux/fps"; + data.hardwares.push(Hardware { + identifier: id.into(), + name: format!("MangoHud: {}", s.app), + hardware_type: HardwareType::Unknown, + }); + if let Some(v) = sensor( + id, + "presented", + "Presented Frames", + SensorType::Frequency, + s.fps as f64, + ) { + data.sensors.push(v); + } + if let Some(v) = sensor( + id, + "frametime", + "Frametime", + SensorType::TimeSpan, + s.frametime as f64, + ) { + data.sensors.push(v); + } + } + if !connected { + log::info!( + "Linux monitoring connected ({} sensors)", + data.sensors.len() + ); + let _ = app.emit("pipe-status", PipeStatus { connected: true }); + connected = true; + } + if let Some(h) = app.try_state::() { + let mut health = h.0.lock().unwrap(); + if health.spawn_error.take().is_some() { + let _ = app.emit("sidecar-status", health.clone()); + } + } + let _ = app.emit("sensor-data", data); + } + Err(error) => { + if connected { + let _ = app.emit("pipe-status", PipeStatus { connected: false }); + connected = false; + } + let status = SidecarStatus { + exits: 0, + spawn_error: Some(error), + }; + if let Some(h) = app.try_state::() { + *h.0.lock().unwrap() = status.clone(); + } + let _ = app.emit("sidecar-status", status); + } + } + next = now + interval; + } + let _ = app.emit("pipe-status", PipeStatus { connected: false }); +} diff --git a/tauri-app/src-tauri/src/linux_sensors.rs b/tauri-app/src-tauri/src/linux_sensors.rs new file mode 100644 index 0000000..46c6abc --- /dev/null +++ b/tauri-app/src-tauri/src/linux_sensors.rs @@ -0,0 +1,489 @@ +//! Read-only Linux telemetry. Missing/permission-denied optional sensors are +//! omitted; the backend never elevates privileges or substitutes another GPU. +use crate::types::{Hardware, HardwareMonitorData, HardwareType, Sensor, SensorType}; +use std::{ + collections::HashMap, + fs, + path::{Path, PathBuf}, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; + +#[derive(Default)] +pub struct LinuxSensors { + cpu: Option<(u64, u64)>, + network: HashMap, +} + +pub fn sensor(hw: &str, key: &str, name: &str, kind: SensorType, value: f64) -> Option { + if !value.is_finite() || value < 0.0 || value > f32::MAX as f64 { + return None; + } + Some(Sensor { + identifier: format!("{hw}/{key}"), + hardware_identifier: hw.into(), + name: name.into(), + sensor_type: kind, + value: value as f32, + }) +} +fn add( + data: &mut HardwareMonitorData, + hw: &str, + key: &str, + name: &str, + kind: SensorType, + value: f64, +) { + if let Some(s) = sensor(hw, key, name, kind, value) { + data.sensors.push(s); + } +} +fn hardware(data: &mut HardwareMonitorData, id: &str, name: &str, kind: HardwareType) { + data.hardwares.push(Hardware { + identifier: id.into(), + name: name.into(), + hardware_type: kind, + }); +} +fn number(path: impl AsRef) -> Option { + fs::read_to_string(path).ok()?.trim().parse().ok() +} +fn entries(path: impl AsRef) -> Vec { + let mut paths: Vec<_> = fs::read_dir(path) + .into_iter() + .flatten() + .filter_map(Result::ok) + .map(|e| e.path()) + .collect(); + paths.sort(); + paths +} +fn cpu_counters(text: &str) -> Option<(u64, u64)> { + let line = text.lines().find(|l| l.starts_with("cpu "))?; + // guest and guest_nice are already included in user/nice; don't count twice. + let fields: Vec = line + .split_whitespace() + .skip(1) + .take(8) + .map(str::parse) + .collect::>() + .ok()?; + if fields.len() < 4 { + return None; + } + Some(( + fields.iter().try_fold(0u64, |a, b| a.checked_add(*b))?, + fields[3].checked_add(*fields.get(4).unwrap_or(&0))?, + )) +} +fn memory(text: &str) -> Option<(u64, u64)> { + let values: HashMap<_, _> = text + .lines() + .filter_map(|l| { + let mut v = l.split_whitespace(); + Some(( + v.next()?.trim_end_matches(':'), + v.next()?.parse::().ok()?, + )) + }) + .collect(); + let total = *values.get("MemTotal")?; + let available = *values.get("MemAvailable")?; + if total == 0 || available > total { + return None; + } + Some((total, total - available)) +} +fn network(text: &str) -> HashMap { + text.lines() + .filter_map(|l| { + let (name, fields) = l.split_once(':')?; + let name = name.trim(); + if name == "lo" { + return None; + } + let v: Vec<_> = fields.split_whitespace().collect(); + Some(( + name.into(), + (v.first()?.parse().ok()?, v.get(8)?.parse().ok()?), + )) + }) + .collect() +} + +impl LinuxSensors { + pub fn sample( + &mut self, + proc: &Path, + sys: &Path, + elapsed: Duration, + ) -> Result { + let cpu = cpu_counters( + &fs::read_to_string(proc.join("stat")) + .map_err(|e| format!("CPU readings unavailable: {e}"))?, + ) + .ok_or("Invalid /proc/stat")?; + let (total, used) = memory( + &fs::read_to_string(proc.join("meminfo")) + .map_err(|e| format!("Memory readings unavailable: {e}"))?, + ) + .ok_or("Invalid /proc/meminfo")?; + let mut data = HardwareMonitorData { + hardwares: vec![], + sensors: vec![], + last_poll_time: SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as i64, + }; + let cpu_name = fs::read_to_string(proc.join("cpuinfo")) + .ok() + .and_then(|s| { + s.lines().find_map(|l| { + l.strip_prefix("model name") + .and_then(|l| l.split_once(':')) + .map(|(_, v)| v.trim().to_owned()) + }) + }) + .unwrap_or_else(|| "CPU".into()); + hardware(&mut data, "/linux/cpu", &cpu_name, HardwareType::Cpu); + if let Some((prev_total, prev_idle)) = self.cpu { + if let (Some(delta), Some(idle)) = + (cpu.0.checked_sub(prev_total), cpu.1.checked_sub(prev_idle)) + { + if delta > 0 && idle <= delta { + add( + &mut data, + "/linux/cpu", + "load", + "CPU Total", + SensorType::Load, + 100.0 * (delta - idle) as f64 / delta as f64, + ); + } + } + } + self.cpu = Some(cpu); + hardware(&mut data, "/ram", "Physical Memory", HardwareType::Memory); + add( + &mut data, + "/ram", + "load", + "Memory", + SensorType::Load, + 100.0 * used as f64 / total as f64, + ); + add( + &mut data, + "/ram", + "used", + "Memory Used", + SensorType::Data, + used as f64 / 1_048_576.0, + ); + add( + &mut data, + "/ram", + "total", + "Memory Total", + SensorType::Data, + total as f64 / 1_048_576.0, + ); + let net = network(&fs::read_to_string(proc.join("net/dev")).unwrap_or_default()); + let mut names: Vec<_> = net.keys().collect(); + names.sort(); + for name in names { + let (rx, tx) = net[name]; + let id = format!("/linux/network/{name}"); + hardware(&mut data, &id, name, HardwareType::Network); + if let Some((old_rx, old_tx)) = self.network.get(name) { + if elapsed.as_secs_f64() > 0.0 { + if let Some(delta) = rx.checked_sub(*old_rx) { + add( + &mut data, + &id, + "download", + "Download Speed", + SensorType::Throughput, + delta as f64 / elapsed.as_secs_f64(), + ); + } + if let Some(delta) = tx.checked_sub(*old_tx) { + add( + &mut data, + &id, + "upload", + "Upload Speed", + SensorType::Throughput, + delta as f64 / elapsed.as_secs_f64(), + ); + } + } + } + } + self.network = net; + for hw in entries(sys.join("class/hwmon")) { + let name = fs::read_to_string(hw.join("name")).unwrap_or_default(); + if matches!( + name.trim(), + "coretemp" | "k10temp" | "zenpower" | "cpu_thermal" | "fam15h_power" + ) { + // Pick package/Tctl/Tdie over a single core where labels exist. + let mut temps: Vec<_> = entries(&hw) + .into_iter() + .filter(|p| { + p.file_name() + .and_then(|s| s.to_str()) + .map(|s| s.starts_with("temp") && s.ends_with("_input")) + .unwrap_or(false) + }) + .collect(); + temps.sort_by_key(|p| { + let label = fs::read_to_string( + p.with_file_name( + p.file_name() + .unwrap() + .to_string_lossy() + .replace("_input", "_label"), + ), + ) + .unwrap_or_default(); + if label.contains("Package") || label.contains("Tctl") || label.contains("Tdie") + { + 0 + } else { + 1 + } + }); + if let Some(value) = temps.iter().find_map(number) { + add( + &mut data, + "/linux/cpu", + "temperature", + "CPU Package", + SensorType::Temperature, + value / 1000.0, + ); + break; + } + } + } + for card in entries(sys.join("class/drm")) { + let name = card.file_name().unwrap_or_default().to_string_lossy(); + if !name + .strip_prefix("card") + .map(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit())) + .unwrap_or(false) + { + continue; + } + let device = card.join("device"); + let vendor = fs::read_to_string(device.join("vendor")).unwrap_or_default(); + let (kind, label) = match vendor.trim() { + "0x1002" => (HardwareType::GpuAmd, "AMD GPU"), + "0x8086" => (HardwareType::GpuIntel, "Intel GPU"), + _ => continue, + }; + let address = fs::canonicalize(&device) + .ok() + .and_then(|p| p.file_name().map(|s| s.to_string_lossy().into_owned())) + .unwrap_or_else(|| name.into_owned()); + let id = format!("/linux/gpu/{address}"); + hardware(&mut data, &id, &format!("{label} ({address})"), kind); + if let Some(v) = number(device.join("gpu_busy_percent")).filter(|v| *v <= 100.0) { + add(&mut data, &id, "load", "GPU Core", SensorType::Load, v); + } + if let Some(used) = number(device.join("mem_info_vram_used")) { + add( + &mut data, + &id, + "memory-used", + "GPU Memory Used", + SensorType::SmallData, + used / 1_048_576.0, + ); + if let Some(total) = number(device.join("mem_info_vram_total")).filter(|v| *v > 0.0) + { + add( + &mut data, + &id, + "memory-total", + "GPU Memory Total", + SensorType::SmallData, + total / 1_048_576.0, + ); + add( + &mut data, + &id, + "memory-load", + "GPU Memory", + SensorType::Load, + (100.0 * used / total).min(100.0), + ); + } + } + for hw in entries(device.join("hwmon")) { + if let Some(v) = number(hw.join("temp1_input")) { + add( + &mut data, + &id, + "temperature", + "GPU Core", + SensorType::Temperature, + v / 1000.0, + ); + } + if let Some(v) = + number(hw.join("power1_average")).or_else(|| number(hw.join("power1_input"))) + { + add( + &mut data, + &id, + "power", + "GPU Power", + SensorType::Power, + v / 1_000_000.0, + ); + } + } + } + Ok(data) + } +} + +/// NVIDIA's driver supplies nvidia-smi; unknown/N/A fields stay absent. +pub fn append_nvidia(data: &mut HardwareMonitorData, csv: &str) { + for row in csv.lines().take(32) { + let v: Vec<_> = row.split(',').map(str::trim).collect(); + if v.len() != 7 || !v[0].starts_with("GPU-") { + continue; + } + let id = format!("/linux/nvidia/{}", v[0]); + hardware(data, &id, v[1], HardwareType::GpuNvidia); + for (idx, key, name, kind) in [ + (2, "load", "GPU Core", SensorType::Load), + (3, "temperature", "GPU Core", SensorType::Temperature), + (4, "memory-used", "GPU Memory Used", SensorType::SmallData), + (5, "memory-total", "GPU Memory Total", SensorType::SmallData), + (6, "power", "GPU Power", SensorType::Power), + ] { + if let Ok(n) = v[idx].parse::() { + add(data, &id, key, name, kind, n); + } + } + if let (Ok(used), Ok(total)) = (v[4].parse::(), v[5].parse::()) { + if total > 0.0 { + add( + data, + &id, + "memory-load", + "GPU Memory", + SensorType::Load, + (100.0 * used / total).min(100.0), + ); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn cpu_does_not_double_count_guests() { + assert_eq!( + cpu_counters("cpu 100 20 30 400 10 2 3 5 40 8"), + Some((570, 410)) + ); + } + #[test] + fn memory_excludes_reclaimable_cache() { + assert_eq!( + memory("MemTotal: 1000 kB\nMemFree: 100 kB\nMemAvailable: 600 kB"), + Some((1000, 400)) + ); + assert_eq!(memory("MemTotal: 0 kB\nMemAvailable: 0 kB"), None); + } + #[test] + fn network_uses_byte_counters_and_excludes_loopback() { + let n = network(" lo: 99 0 0 0 0 0 0 0 99\n eth0: 1000 0 0 0 0 0 0 0 2000"); + assert_eq!(n.len(), 1); + assert_eq!(n["eth0"], (1000, 2000)); + } + #[test] + fn nvidia_omits_unavailable_and_nonfinite_values() { + let mut d = HardwareMonitorData { + hardwares: vec![], + sensors: vec![], + last_poll_time: 0, + }; + append_nvidia(&mut d, "GPU-123, RTX Test, 30, N/A, 1024, 4096, NaN"); + assert_eq!(d.hardwares.len(), 1); + assert!(!d.sensors.iter().any( + |s| s.sensor_type == SensorType::Temperature || s.sensor_type == SensorType::Power + )); + assert_eq!( + d.sensors + .iter() + .find(|s| s.identifier.ends_with("memory-load")) + .unwrap() + .value, + 25.0 + ); + } + #[test] + fn fixture_rates_units_and_counter_reset() { + let root = std::env::temp_dir().join(format!( + "cleanmeter-linux-{}", + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(root.join("net")).unwrap(); + fs::write(root.join("stat"), "cpu 100 0 0 100 0 0 0 0").unwrap(); + fs::write( + root.join("meminfo"), + "MemTotal: 2097152 kB\nMemAvailable: 1048576 kB", + ) + .unwrap(); + fs::write(root.join("net/dev"), "eth0: 100 0 0 0 0 0 0 0 200").unwrap(); + let mut s = LinuxSensors::default(); + s.sample(&root, &root, Duration::from_secs(1)).unwrap(); + fs::write(root.join("stat"), "cpu 150 0 0 150 0 0 0 0").unwrap(); + fs::write(root.join("net/dev"), "eth0: 1100 0 0 0 0 0 0 0 2200").unwrap(); + let d = s.sample(&root, &root, Duration::from_millis(500)).unwrap(); + assert_eq!( + d.sensors + .iter() + .find(|v| v.name == "CPU Total") + .unwrap() + .value, + 50.0 + ); + assert_eq!( + d.sensors + .iter() + .find(|v| v.name == "Download Speed") + .unwrap() + .value, + 2000.0 + ); + assert_eq!( + d.sensors + .iter() + .find(|v| v.name == "Memory Used") + .unwrap() + .value, + 1.0 + ); + fs::write(root.join("net/dev"), "eth0: 1 0 0 0 0 0 0 0 1").unwrap(); + assert!(!s + .sample(&root, &root, Duration::from_secs(1)) + .unwrap() + .sensors + .iter() + .any(|s| s.sensor_type == SensorType::Throughput)); + fs::remove_dir_all(root).unwrap(); + } +} diff --git a/tauri-app/src-tauri/src/main.rs b/tauri-app/src-tauri/src/main.rs index 65ab72f..67bfe95 100644 --- a/tauri-app/src-tauri/src/main.rs +++ b/tauri-app/src-tauri/src/main.rs @@ -2,5 +2,22 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] fn main() { + // AppImage users can invoke the bundled launcher without installing it in PATH. + #[cfg(target_os = "linux")] + { + use std::os::unix::process::CommandExt; + let mut args = std::env::args_os().skip(1); + if args.next().as_deref() == Some(std::ffi::OsStr::new("--run")) { + // Use our compiled-in script, preserving each game argument verbatim. + let error = std::process::Command::new("sh") + .arg("-c") + .arg(include_str!("../linux/cleanmeter-run")) + .arg("cleanmeter-run") + .args(args) + .exec(); + eprintln!("Could not launch game: {error}"); + std::process::exit(1); + } + } cleanmeter_lib::run() } diff --git a/tauri-app/src-tauri/src/platform.rs b/tauri-app/src-tauri/src/platform.rs new file mode 100644 index 0000000..e05f9b3 --- /dev/null +++ b/tauri-app/src-tauri/src/platform.rs @@ -0,0 +1,38 @@ +use serde::Serialize; +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PlatformInfo { + pub os: &'static str, + pub display_backend: &'static str, + pub can_position_overlay: bool, + pub global_shortcuts: bool, + pub percentile_lows: bool, +} +pub fn native_wayland() -> bool { + cfg!(target_os = "linux") + && std::env::var("GDK_BACKEND") + .map(|s| s == "wayland") + .unwrap_or_else(|_| { + std::env::var_os("DISPLAY").is_none() + && std::env::var_os("WAYLAND_DISPLAY").is_some() + }) +} +#[tauri::command] +pub fn get_platform_info() -> PlatformInfo { + let wayland = native_wayland(); + PlatformInfo { + os: std::env::consts::OS, + display_backend: if cfg!(target_os = "linux") { + if wayland { + "wayland" + } else { + "x11" + } + } else { + "native" + }, + can_position_overlay: !wayland, + global_shortcuts: !wayland, + percentile_lows: cfg!(windows), + } +} diff --git a/tauri-app/src-tauri/src/shortcuts.rs b/tauri-app/src-tauri/src/shortcuts.rs index 00bc482..9c14e37 100644 --- a/tauri-app/src-tauri/src/shortcuts.rs +++ b/tauri-app/src-tauri/src/shortcuts.rs @@ -213,11 +213,13 @@ pub fn toggle_recording(app: &AppHandle) { /// reset to defaults — so there is one place that knows the mapping from /// settings field to action. pub fn apply_all(app: &AppHandle, settings: &OverlaySettings) { + if crate::platform::native_wayland() { return; } let mut unavailable = HashMap::<&'static str, String>::new(); for (action, accelerator) in [ (ShortcutAction::ToggleOverlay, &settings.overlay_shortcut), (ShortcutAction::ToggleRecording, &settings.recording_shortcut), ] { + if cfg!(target_os = "linux") && action == ShortcutAction::ToggleRecording { continue; } if let Err(accel) = apply(app, action, accelerator) { unavailable.insert(action.settings_key(), accel); } diff --git a/tauri-app/src-tauri/src/tray.rs b/tauri-app/src-tauri/src/tray.rs index 5663abe..25e79ad 100644 --- a/tauri-app/src-tauri/src/tray.rs +++ b/tauri-app/src-tauri/src/tray.rs @@ -12,12 +12,11 @@ pub fn setup_tray(app: &AppHandle) -> Result<(), Box> { let menu = Menu::with_items(app, &[&show, &toggle, &separator, &quit])?; - let tray = app.tray_by_id("main").unwrap_or_else(|| { - tauri::tray::TrayIconBuilder::with_id("main") - .menu(&menu) - .build(app) - .expect("Failed to build tray icon") - }); + let tray = if let Some(tray)=app.tray_by_id("main") { tray } else { + let mut builder=tauri::tray::TrayIconBuilder::with_id("main").menu(&menu); + if let Some(icon)=app.default_window_icon() {builder=builder.icon(icon.clone());} + builder.build(app)? + }; tray.set_menu(Some(menu))?; diff --git a/tauri-app/src-tauri/tauri.conf.json b/tauri-app/src-tauri/tauri.conf.json index 12875f9..d4d185a 100644 --- a/tauri-app/src-tauri/tauri.conf.json +++ b/tauri-app/src-tauri/tauri.conf.json @@ -1,5 +1,5 @@ { - "$schema": "https://raw.githubusercontent.com/nicegui/toolkits/refs/heads/main/tauri/schema.json", + "$schema": "https://schema.tauri.app/config/2", "productName": "Cleanmeter", "identifier": "com.cleanmeter.desktop", "version": "2.2.17", @@ -57,7 +57,12 @@ "bundle": { "active": true, "createUpdaterArtifacts": true, - "targets": ["nsis", "deb", "dmg", "app"], + "targets": [ + "nsis", + "deb", + "dmg", + "app" + ], "icon": [ "icons/32x32.png", "icons/128x128.png", @@ -81,12 +86,6 @@ "%1" ] } - }, - "resources": { - "../../HardwareMonitor/HardwareMonitor/bin/Release/net8.0/win-x64/publish/*.exe": "./", - "../../HardwareMonitor/HardwareMonitor/bin/Release/net8.0/win-x64/publish/*.dll": "./", - "../../HardwareMonitor/HardwareMonitor/bin/Release/net8.0/win-x64/publish/*.txt": "./", - "../../pawnio/*.exe": "./" } }, "plugins": { diff --git a/tauri-app/src-tauri/tauri.linux.conf.json b/tauri-app/src-tauri/tauri.linux.conf.json new file mode 100644 index 0000000..28184c0 --- /dev/null +++ b/tauri-app/src-tauri/tauri.linux.conf.json @@ -0,0 +1,32 @@ +{ + "bundle": { + "targets": [ + "deb", + "rpm", + "appimage" + ], + "createUpdaterArtifacts": false, + "linux": { + "deb": { + "depends": [ + "libwebkit2gtk-4.1-0", + "libgtk-3-0", + "libayatana-appindicator3-1" + ], + "files": { + "/usr/bin/cleanmeter-run": "linux/cleanmeter-run" + } + }, + "rpm": { + "files": { + "/usr/bin/cleanmeter-run": "linux/cleanmeter-run" + } + }, + "appimage": { + "files": { + "/usr/bin/cleanmeter-run": "linux/cleanmeter-run" + } + } + } + } +} diff --git a/tauri-app/src-tauri/tauri.windows.conf.json b/tauri-app/src-tauri/tauri.windows.conf.json new file mode 100644 index 0000000..dd5db22 --- /dev/null +++ b/tauri-app/src-tauri/tauri.windows.conf.json @@ -0,0 +1,10 @@ +{ + "bundle": { + "resources": { + "../../HardwareMonitor/HardwareMonitor/bin/Release/net8.0/win-x64/publish/*.exe": "./", + "../../HardwareMonitor/HardwareMonitor/bin/Release/net8.0/win-x64/publish/*.dll": "./", + "../../HardwareMonitor/HardwareMonitor/bin/Release/net8.0/win-x64/publish/*.txt": "./", + "../../pawnio/*.exe": "./" + } + } +} diff --git a/tauri-app/src/App.tsx b/tauri-app/src/App.tsx index 4f70087..cabb594 100644 --- a/tauri-app/src/App.tsx +++ b/tauri-app/src/App.tsx @@ -1,3 +1,4 @@ +import { usePlatformStore } from "@/stores/platform-store"; import { useCallback, useEffect, useRef, useState } from "react"; import { TopBar } from "@/components/settings/TopBar"; import { TabNav, type SettingsTab as TabKey } from "@/components/settings/TabNav"; @@ -18,6 +19,7 @@ import { useToastStore } from "@/stores/toast-store"; import { HOTKEY_IN_USE_MESSAGE } from "@/lib/shortcuts"; function MonitoringBanner() { + const linux = usePlatformStore((s) => s.platform.os === "linux"); const sensorData = useSettingsStore((s) => s.sensorData); const pipeStatus = useSettingsStore((s) => s.pipeStatus); const sidecarStatus = useSettingsStore((s) => s.sidecarStatus); @@ -45,20 +47,20 @@ function MonitoringBanner() { // Only a failing verdict is worth telling the user about, and only then is it // worth paying for the .NET probe. useEffect(() => { - if (verdict !== "failed") return; + if (verdict !== "failed" || linux) return; checkDotnetRuntime() .then((ok) => { if (!ok) setDotnetMissing(true); }) .catch(() => {}); - }, [verdict]); + }, [verdict, linux]); if (verdict !== "failed") return null; return (
Monitoring not connected. - {dotnetMissing ? ( + {linux ? {sidecarStatus.spawnError ?? "Linux sensor readings are unavailable. Try restarting Cleanmeter."} : dotnetMissing ? ( {" "}.NET 8 Desktop Runtime is required but not installed.{" "} s.load); + useEffect(() => { void loadPlatform(); }, [loadPlatform]); const [activeTab, setActiveTab] = useState("stats"); // Startup splash: shown on every launch from first paint, covering the UI // (and the light→dark theme flash while saved settings load) until the diff --git a/tauri-app/src/OverlayApp.tsx b/tauri-app/src/OverlayApp.tsx index 98af90f..58dfb17 100644 --- a/tauri-app/src/OverlayApp.tsx +++ b/tauri-app/src/OverlayApp.tsx @@ -1,3 +1,4 @@ +import { usePlatformStore } from "@/stores/platform-store"; import { useEffect, useRef, useState } from "react"; import { OverlayHud } from "@/components/overlay/OverlayHud"; import { useSensorData } from "@/hooks/useSensorData"; @@ -55,6 +56,9 @@ function clampToMonitor( } export default function OverlayApp() { + const loadPlatform = usePlatformStore((s) => s.load); + const canPosition = usePlatformStore((s) => s.platform.canPositionOverlay); + useEffect(() => { void loadPlatform(); }, [loadPlatform]); const loadSettings = useSettingsStore((s) => s.loadSettings); const updateSettings = useSettingsStore((s) => s.updateSettings); const settings = useSettingsStore((s) => s.settings); @@ -225,7 +229,7 @@ export default function OverlayApp() { // monitors + settings (instead of an async Tauri round-trip) so mousemove // events that fire on the same tick as mousedown aren't dropped. const onMouseDown = (e: React.MouseEvent) => { - if (!settings.useCustomPosition) return; + if (!canPosition || !settings.useCustomPosition) return; if (e.button !== 0) return; if (monitors.length === 0) return; e.preventDefault(); diff --git a/tauri-app/src/components/overlay/FpsSection.tsx b/tauri-app/src/components/overlay/FpsSection.tsx index 615861d..eaac40c 100644 --- a/tauri-app/src/components/overlay/FpsSection.tsx +++ b/tauri-app/src/components/overlay/FpsSection.tsx @@ -1,3 +1,4 @@ +import { usePlatformStore } from "@/stores/platform-store"; import { Pill } from "./Pill"; import { FrametimeGraph } from "./FrametimeGraph"; import { useSettingsStore } from "@/stores/settings-store"; @@ -25,6 +26,7 @@ interface FpsSectionProps { } export function FpsSection({ isHorizontal }: FpsSectionProps) { + const lowsSupported = usePlatformStore((s) => s.platform.percentileLows); const settings = useSettingsStore((s) => s.settings); const sensorData = useSettingsStore((s) => s.sensorData); const frametimeHistory = useFrametimeHistory(); @@ -38,8 +40,8 @@ export function FpsSection({ isHorizontal }: FpsSectionProps) { if ( !framerate.isEnabled && !frametime.isEnabled && - !onePercentLow.isEnabled && - !zeroPointOnePercentLow.isEnabled + !(lowsSupported && onePercentLow.isEnabled) && + !(lowsSupported && zeroPointOnePercentLow.isEnabled) ) return null; @@ -98,8 +100,8 @@ export function FpsSection({ isHorizontal }: FpsSectionProps) { // earlier worry that "0 1%" reads as "your worst frames were 0 fps" bites // only while the average shows a live number, and it is the lesser evil // against a value that looks negative. - const showOnePercent = onePercentLow.isEnabled; - const showZeroPointOne = zeroPointOnePercentLow.isEnabled; + const showOnePercent = lowsSupported && onePercentLow.isEnabled; + const showZeroPointOne = lowsSupported && zeroPointOnePercentLow.isEnabled; const valueStyle: React.CSSProperties = { fontSize: valueFontSize, diff --git a/tauri-app/src/components/settings/LinuxSupport.tsx b/tauri-app/src/components/settings/LinuxSupport.tsx new file mode 100644 index 0000000..67f94eb --- /dev/null +++ b/tauri-app/src/components/settings/LinuxSupport.tsx @@ -0,0 +1,24 @@ +import { usePlatformStore } from "@/stores/platform-store"; +import { useSettingsStore } from "@/stores/settings-store"; +import { Switch } from "@/components/shadcn/switch"; + +export function LinuxSupport() { + const { os, canPositionOverlay } = usePlatformStore((s) => s.platform); + const visible = useSettingsStore((s) => s.overlayVisible); + const setVisible = useSettingsStore((s) => s.setOverlayVisible); + if (os !== "linux") return null; + return ( +
+ +

+ {canPositionOverlay + ? "Linux preview · X11/XWayland. Overlay visibility in fullscreen games depends on your desktop." + : "Wayland controls window placement. Use the monitor as a separate window, or sign in with an X11 session for overlay positioning and global shortcuts."} +

+

Temperature, power, and GPU readings depend on your hardware driver. Unavailable sensors are not collected.

+
+ ); +} diff --git a/tauri-app/src/components/settings/TopBar.tsx b/tauri-app/src/components/settings/TopBar.tsx index 4c3876e..2634490 100644 --- a/tauri-app/src/components/settings/TopBar.tsx +++ b/tauri-app/src/components/settings/TopBar.tsx @@ -1,3 +1,4 @@ +import { usePlatformStore } from "@/stores/platform-store"; import { Minus, X } from "lucide-react"; import { isBrowser } from "@/lib/tauri"; import { cn } from "@/lib/utils"; @@ -100,6 +101,7 @@ function CleanmeterLogo() { } export function TopBar() { + const linux = usePlatformStore((s) => s.platform.os === "linux"); // Defer startDragging() until the mouse actually moves. Calling it on // mousedown would make Windows swallow the mouseup event, breaking the // click → click → dblclick sequence the browser needs for onDoubleClick. @@ -177,7 +179,7 @@ export function TopBar() { appWindowPromise.then((w) => w.hide())} + onClick={() => appWindowPromise.then((w) => linux ? w.minimize() : w.hide())} title="Close to tray" className="hover:bg-destructive hover:text-destructive-foreground" > diff --git a/tauri-app/src/components/settings/settings/SettingsTab.tsx b/tauri-app/src/components/settings/settings/SettingsTab.tsx index 927ce67..615f8eb 100644 --- a/tauri-app/src/components/settings/settings/SettingsTab.tsx +++ b/tauri-app/src/components/settings/settings/SettingsTab.tsx @@ -1,3 +1,4 @@ +import { usePlatformStore } from "@/stores/platform-store"; import * as React from "react"; import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"; import { Checkbox } from "@/components/shadcn/checkbox"; @@ -47,6 +48,7 @@ function SectionCard({ } function GeneralSection() { + const linux = usePlatformStore((s) => s.platform.os === "linux"); const startMinimized = useSettingsStore((s) => s.preferences.startMinimized); const updatePreferences = useSettingsStore((s) => s.updatePreferences); const pixelShift = useSettingsStore((s) => s.settings.pixelShift); @@ -85,7 +87,7 @@ function GeneralSection() { disabled={autoStartPending} onCheckedChange={(v) => handleStartWithWindows(v === true)} /> - Start with windows + {linux ? "Start at login" : "Start with Windows"}
+ {platform.os === "linux" && ( +
+

Install MangoHud, then launch your game with cleanmeter-run. Steam launch options:

+ cleanmeter-run %command% +

FPS and frametime are sampled every 100 ms. Percentile lows and benchmark recording require per-frame capture and are unavailable in this Linux preview.

+ {presentMonApps.length === 0 &&

No game telemetry yet. Start a game with the launcher above.

} +
+ )} ); } diff --git a/tauri-app/src/components/settings/stats/StatsTab.tsx b/tauri-app/src/components/settings/stats/StatsTab.tsx index 9c7f44f..af30a89 100644 --- a/tauri-app/src/components/settings/stats/StatsTab.tsx +++ b/tauri-app/src/components/settings/stats/StatsTab.tsx @@ -1,3 +1,4 @@ +import { LinuxSupport } from "../LinuxSupport"; import { useEffect, useState } from "react"; import { useSettingsStore } from "@/stores/settings-store"; import { FpsSection } from "./FpsSection"; @@ -36,6 +37,7 @@ export function StatsTab() { // the change note on 2790:1636. What it used to state is now editable — // Settings -> Shortcuts owns both bindings (see shortcuts.rs).
+ diff --git a/tauri-app/src/components/settings/style/PositionGrid.tsx b/tauri-app/src/components/settings/style/PositionGrid.tsx index b008000..1ee8f17 100644 --- a/tauri-app/src/components/settings/style/PositionGrid.tsx +++ b/tauri-app/src/components/settings/style/PositionGrid.tsx @@ -1,3 +1,4 @@ +import { usePlatformStore } from "@/stores/platform-store"; import { CollapsibleCard } from "./CollapsibleCard"; import { Switch } from "@/components/shadcn/switch"; import { cn } from "@/lib/utils"; @@ -47,6 +48,8 @@ export function PositionGrid() { const updateSettings = useSettingsStore((s) => s.updateSettings); const { useCustomPosition, positionIndex } = settings; + const canPosition = usePlatformStore((s) => s.platform.canPositionOverlay); + if (!canPosition) return

Your Wayland desktop manages window position. Drag the monitor using its title bar.

; return (
diff --git a/tauri-app/src/lib/tauri.ts b/tauri-app/src/lib/tauri.ts index 609940e..983c7ea 100644 --- a/tauri-app/src/lib/tauri.ts +++ b/tauri-app/src/lib/tauri.ts @@ -156,6 +156,7 @@ export const checkForUpdate = async (): Promise => { // The preview reports an update so the download banner has a state to be in. if (usePreviewFixture) return previewUpdate(); if (isBrowser) return null; + if ((await getPlatformInfo()).os === "linux") return null; const { check } = await import("@tauri-apps/plugin-updater"); return check(); }; @@ -274,3 +275,18 @@ export const pickImageAttachment = async (): Promise< const name = selected.split(/[/\\]/).pop() ?? "attachment"; return { path: selected, name }; }; + +export interface PlatformInfo { + os: string; + displayBackend: string; + canPositionOverlay: boolean; + globalShortcuts: boolean; + percentileLows: boolean; +} +export const getPlatformInfo = () => { + if (isBrowser) { + const linux = navigator.platform.toLowerCase().includes("linux") || (import.meta.env.DEV && new URLSearchParams(location.search).get("platform") === "linux"); + return Promise.resolve({ os: linux ? "linux" : "windows", displayBackend: linux ? "x11" : "native", canPositionOverlay: true, globalShortcuts: true, percentileLows: !linux }); + } + return safeInvoke("get_platform_info"); +}; diff --git a/tauri-app/src/stores/platform-store.ts b/tauri-app/src/stores/platform-store.ts new file mode 100644 index 0000000..b026614 --- /dev/null +++ b/tauri-app/src/stores/platform-store.ts @@ -0,0 +1,11 @@ +import { create } from "zustand"; +import { getPlatformInfo, type PlatformInfo } from "@/lib/tauri"; + +const linux = typeof navigator !== "undefined" && navigator.platform.toLowerCase().includes("linux"); +export const usePlatformStore = create<{ platform: PlatformInfo; load: () => Promise }>((set) => ({ + platform: { os: linux ? "linux" : "windows", displayBackend: linux ? "x11" : "native", canPositionOverlay: true, globalShortcuts: true, percentileLows: !linux }, + load: async () => { + try { const platform = await getPlatformInfo(); if (platform) set({ platform }); } + catch (error) { console.error("Could not read platform capabilities", error); } + }, +})); From de2596e637aad41f8ce54390818fa00dbeaed3f8 Mon Sep 17 00:00:00 2001 From: Adnan Jaweed Date: Mon, 7 Sep 2026 09:00:19 -0400 Subject: [PATCH 2/7] Handle Linux desktop fallbacks and validate live MangoHud integration --- .github/workflows/linux.yml | 43 ++++++ docs/linux.md | 134 ++++++++++++++++++ tauri-app/src-tauri/linux/cleanmeter-run | 10 +- tauri-app/src-tauri/linux/test_launcher.py | 69 +++++++++ tauri-app/src-tauri/src/commands.rs | 1 + tauri-app/src-tauri/src/lib.rs | 15 ++ tauri-app/src-tauri/src/linux_autostart.rs | 27 +++- tauri-app/src-tauri/src/linux_fps.rs | 8 +- tauri-app/src-tauri/src/linux_monitor.rs | 27 ++++ tauri-app/src-tauri/src/linux_sensors.rs | 32 +++++ tauri-app/src-tauri/src/main.rs | 10 +- tauri-app/src-tauri/tauri.linux.conf.json | 3 + tauri-app/src/App.tsx | 2 +- tauri-app/src/OverlayApp.tsx | 4 +- .../src/components/overlay/CpuSection.tsx | 9 +- .../src/components/overlay/FpsSection.tsx | 4 +- .../src/components/overlay/GpuSection.tsx | 13 +- .../src/components/settings/LinuxSupport.tsx | 4 +- .../components/settings/help/FaqSection.tsx | 9 +- .../settings/settings/SettingsTab.tsx | 2 +- .../components/settings/stats/FpsSection.tsx | 3 +- tauri-app/src/hooks/useHotkey.ts | 3 + tauri-app/src/lib/tauri.ts | 6 + 23 files changed, 417 insertions(+), 21 deletions(-) create mode 100644 docs/linux.md create mode 100644 tauri-app/src-tauri/linux/test_launcher.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 6979b0d..ee719b5 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -34,6 +34,7 @@ jobs: sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev patchelf rpm xvfb dbus-x11 - run: npm ci - run: npm run lint && npm test && npm run build + - run: python3 src-tauri/linux/test_launcher.py - name: Test native backend run: cargo test --locked --manifest-path src-tauri/Cargo.toml --lib - name: Build Linux packages @@ -60,3 +61,45 @@ jobs: tauri-app/src-tauri/target/release/bundle/rpm/*.rpm tauri-app/src-tauri/target/release/bundle/appimage/*.AppImage tauri-app/linux-smoke.log + + live-fps: + needs: linux + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/download-artifact@v4 + with: + name: cleanmeter-linux-x86_64 + path: packages + - name: Install desktop runtime and real MangoHud + run: | + sudo apt-get update + sudo apt-get install -y libwebkit2gtk-4.1-0 libayatana-appindicator3-1 mangohud vulkan-tools mesa-vulkan-drivers xvfb + mangohud --version + - name: Verify real Vulkan FPS through the AppImage launcher + run: | + image=$(find packages -name '*.AppImage' -print -quit) + chmod +x "$image" + "$image" --appimage-extract > /dev/null + chmod +x squashfs-root/usr/bin/cleanmeter + export XDG_CACHE_HOME="$RUNNER_TEMP/cleanmeter-live-test" + xvfb-run -a squashfs-root/usr/bin/cleanmeter --run vkcube > game.log 2>&1 & + game=$! + trap 'kill "$game" 2>/dev/null || true' EXIT + for attempt in $(seq 1 20); do + squashfs-root/usr/bin/cleanmeter --diagnose > diagnostics.json + if python3 -c 'import json; d=json.load(open("diagnostics.json")); assert any(g["fps"] > 0 and g["frametime"] > 0 for g in d["games"]); assert any(s["name"] == "CPU Total" for s in d["hardware"]["sensors"])'; then + cat diagnostics.json + exit 0 + fi + sleep 1 + done + cat game.log + exit 1 + - uses: actions/upload-artifact@v4 + if: always() + with: + name: cleanmeter-live-fps-evidence + path: | + diagnostics.json + game.log diff --git a/docs/linux.md b/docs/linux.md new file mode 100644 index 0000000..22c3902 --- /dev/null +++ b/docs/linux.md @@ -0,0 +1,134 @@ +# Cleanmeter for Linux (preview) + +The Linux build uses a native Rust monitoring backend. It does not require .NET, +PresentMon, PawnIO, a Windows service, or administrator privileges to run. +Packages target x86-64 desktops: Debian/Ubuntu `.deb`, Fedora-family `.rpm`, and +an AppImage. ARM and Steam Deck Gaming Mode are not validated. + +## Install and start + +Download the `cleanmeter-linux-x86_64` artifact from a successful **Linux preview** +GitHub Actions run on `feat/linux-support`. These are development packages, not a +published stable release. Extract the artifact, then use the appropriate command +with the actual filename: + +```sh +sudo apt install ./Cleanmeter_2.2.17_amd64.deb +# or, on Fedora: +sudo dnf install ./Cleanmeter-2.2.17-1.x86_64.rpm +# or: +chmod +x ./Cleanmeter_2.2.17_amd64.AppImage +./Cleanmeter_2.2.17_amd64.AppImage +``` + +Package filenames can vary; use the name in your downloaded artifact. AppImages +still need a working desktop and graphics driver. If FUSE is unavailable, use +`--appimage-extract-and-run`. Hardware monitoring starts when Cleanmeter starts. + +The app prefers X11/XWayland when available. On native Wayland it uses a normal +monitor window, without absolute overlay positioning or global shortcuts. +Exclusive fullscreen, native Wayland games under an XWayland session, and +Gamescope can obscure external overlay windows. Borderless/windowed mode is the +recommended starting point. This preview does not inject Cleanmeter's UI into games. + +Closing Settings minimizes it to the taskbar. Stats has a visibility switch and +a Quit button, so a desktop without tray icons still has controls. Start at login +writes an XDG autostart entry for the current executable; if you move an AppImage, +turn Start at login off and back on to update its path. + +## Game FPS and frametime + +Install **MangoHud 0.7.0 or newer** through your distribution or the +[upstream project](https://github.com/flightlessmango/MangoHud#installation). +Check with `mangohud --version`. Older distro packages, including 0.6.x, cannot +provide the live CSV output used here. Hardware monitoring works without MangoHud. + +For a native game: + +```sh +cleanmeter-run /path/to/game [arguments] +``` + +For Steam installed on the host, set the game's launch options to: + +```text +cleanmeter-run %command% +``` + +With an AppImage, use its absolute path instead: + +```text +"/home/you/Applications/Cleanmeter.AppImage" --run %command% +``` + +`--run` launches the game without starting a second monitor instance; keep the +Cleanmeter app open separately. The DEB/RPM also accept `cleanmeter --run ...`. +Some OpenGL games need `cleanmeter-run --dlsym game`. Proton games need the +appropriate MangoHud libraries inside their Steam runtime. Flatpak Steam, Snap +Steam, anti-cheat games, and Gamescope require separate validation; this preview +does not configure their sandbox permissions or promise compatibility. + +The launcher creates private temporary logs under +`$XDG_CACHE_HOME/cleanmeter/fps` (or `~/.cache/cleanmeter/fps`), removes its session +on normal exit, and disables log uploads. It preserves game arguments and exit +codes. An interrupted machine or SIGKILL can leave session files; they can be +removed after the game exits. Keep cache paths free of commas (MangoHud uses them +as configuration separators). + +FPS and frametime are sampled every 100 ms by MangoHud, then read at Cleanmeter's +polling rate. Auto chooses the most recently updated game; selecting a game pins +the source. Readings expire after three seconds without a log update. Unsupported +or absent readings show a dash. **1%/0.1% lows and benchmark recording are disabled** +because these logs are sampled telemetry, not reliable per-frame capture. + +## Hardware coverage + +| Reading | Source and limits | +| --- | --- | +| CPU utilization | `/proc/stat` deltas; first poll establishes a baseline | +| CPU temperature | Recognized `hwmon` CPU drivers; prefers package/Tctl/Tdie | +| CPU power | Not collected in this preview | +| RAM | `/proc/meminfo`, using `MemAvailable` to account for reclaimable cache | +| Network | `/proc/net/dev` byte deltas; excludes loopback; counter resets are discarded | +| AMD GPU | DRM/sysfs busy percentage, VRAM, temperature and power when exposed | +| NVIDIA GPU | Driver's `nvidia-smi`, with a bounded timeout; N/A readings are omitted | +| Intel GPU | Enumerated through DRM; only exposed sysfs sensors are read. Utilization, VRAM, and power are often unavailable | + +Optional unreadable sensors stay absent; the app does not change device permissions. +GPU selection remains scoped to one GPU. Linux identifiers differ from Windows, +so manually imported Windows sensor selections may need to be selected again. + +## Diagnose and build + +Print current hardware and active game samples without opening a GUI: + +```sh +cleanmeter --diagnose +# or ./Cleanmeter.AppImage --diagnose +``` + +This includes hardware names and local interface identifiers; review it before +sharing. It does not send diagnostics anywhere. + +On Ubuntu 22.04+ with Rust and Node 22 installed: + +```sh +sudo apt install build-essential libwebkit2gtk-4.1-dev libgtk-3-dev \ + libayatana-appindicator3-dev librsvg2-dev libssl-dev patchelf rpm +cd tauri-app +npm ci +npm run lint +npm test +npm run build +python3 src-tauri/linux/test_launcher.py +cargo test --locked --manifest-path src-tauri/Cargo.toml --lib +npm run tauri -- build --bundles deb,rpm,appimage +``` + +The platform-specific Tauri configurations keep Windows sidecar resources out of +Linux bundles. `.github/workflows/linux.yml` builds all three package formats, +smoke-tests desktop startup, and checks live MangoHud FPS with a software-rendered +Vulkan cube on Ubuntu 24.04. Physical GPU drivers, actual games, Fedora installs, +and native Wayland compositor behavior still need device testing before release. +Linux updates are installed manually through a downloaded package; the Windows +in-app updater is disabled for this preview. diff --git a/tauri-app/src-tauri/linux/cleanmeter-run b/tauri-app/src-tauri/linux/cleanmeter-run index 68c4f9b..5d98bd0 100755 --- a/tauri-app/src-tauri/linux/cleanmeter-run +++ b/tauri-app/src-tauri/linux/cleanmeter-run @@ -10,6 +10,12 @@ if ! command -v mangohud >/dev/null 2>&1; then echo 'Install MangoHud first (Ubuntu/Debian: sudo apt install mangohud).' >&2 exit 1 fi +# 0.6.x only saves CSV files when logging stops; live reads need 0.7+. +version=$(mangohud --version 2>/dev/null || true) +if ! printf '%s\n' "$version" | awk -F. '/^[0-9]+\.[0-9]+/ { if ($1 > 0 || $2 >= 7) ok=1 } END { exit !ok }'; then + echo "Cleanmeter FPS requires MangoHud 0.7.0 or newer (found: $version)." >&2 + exit 1 +fi case "${XDG_CACHE_HOME:-}" in /*) cache=$XDG_CACHE_HOME ;; *) cache=$HOME/.cache ;; @@ -30,9 +36,11 @@ cat > "$session/MangoHud.conf" < Result<(), String> { + linux_monitor::diagnostics() +} diff --git a/tauri-app/src-tauri/src/linux_autostart.rs b/tauri-app/src-tauri/src/linux_autostart.rs index 5af8654..414c627 100644 --- a/tauri-app/src-tauri/src/linux_autostart.rs +++ b/tauri-app/src-tauri/src/linux_autostart.rs @@ -22,7 +22,7 @@ fn desktop_exec(exe: &str) -> Result { Ok(out) } pub fn set(config: &Path, exe: &Path, enabled: bool) -> Result<(), String> { - let path = config.join("autostart/com.cleanmeter.desktop.desktop"); + let path = config.join("autostart/com.cleanmeter.desktop"); if !enabled { return match fs::remove_file(path) { Ok(()) => Ok(()), @@ -35,7 +35,7 @@ pub fn set(config: &Path, exe: &Path, enabled: bool) -> Result<(), String> { fs::write(path,format!("[Desktop Entry]\nType=Application\nName=Cleanmeter\nExec={exec}\nTerminal=false\nX-GNOME-Autostart-enabled=true\n")).map_err(|e|e.to_string()) } pub fn enabled(config: &Path) -> bool { - fs::read_to_string(config.join("autostart/com.cleanmeter.desktop.desktop")) + fs::read_to_string(config.join("autostart/com.cleanmeter.desktop")) .map(|s| { !s.lines() .any(|l| matches!(l.trim(), "Hidden=true" | "X-GNOME-Autostart-enabled=false")) @@ -54,4 +54,27 @@ mod tests { assert_eq!(desktop_exec("/tmp/$HOME").unwrap(), "\"/tmp/\\\\$HOME\""); assert!(desktop_exec("a\nb").is_err()); } + + #[test] + fn toggles_only_our_autostart_entry() { + let root = std::env::temp_dir().join(format!( + "cleanmeter-autostart-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(root.join("autostart")).unwrap(); + let other = root.join("autostart/another.desktop"); + fs::write(&other, "other app").unwrap(); + assert!(!enabled(&root)); + set(&root, Path::new("/apps/Clean meter.AppImage"), true).unwrap(); + assert!(enabled(&root)); + set(&root, Path::new("/apps/Clean meter.AppImage"), false).unwrap(); + assert!(!enabled(&root)); + set(&root, Path::new("/apps/Clean meter.AppImage"), false).unwrap(); + assert_eq!(fs::read_to_string(other).unwrap(), "other app"); + fs::remove_dir_all(root).unwrap(); + } } diff --git a/tauri-app/src-tauri/src/linux_fps.rs b/tauri-app/src-tauri/src/linux_fps.rs index 3527e3d..30bf64d 100644 --- a/tauri-app/src-tauri/src/linux_fps.rs +++ b/tauri-app/src-tauri/src/linux_fps.rs @@ -57,7 +57,8 @@ fn read_sample(path: &Path, now: SystemTime) -> Option { let (fps, frametime) = tail[start..end] .lines() .rev() - .find_map(|l| values(l, cols))?; + .find(|l| !l.trim().is_empty()) + .and_then(|l| values(l, cols))?; let stem = path.file_stem()?.to_str()?; // MangoHud names logs _YYYY-MM-DD_HH-MM-SS.csv. let app = if stem.len() > 20 && stem.is_char_boundary(stem.len() - 20) { @@ -136,6 +137,11 @@ mod tests { assert_eq!(sample.app, "game"); assert_eq!(sample.fps, 120.0); assert!(read_sample(&p, SystemTime::now() + Duration::from_secs(10)).is_none()); + fs::write(&p, "fps,frametime\n60,16.6\n0,0\n").unwrap(); + assert!( + read_sample(&p, SystemTime::now()).is_none(), + "a fresh invalid row must not revive old FPS" + ); fs::remove_dir_all(dir).unwrap(); } } diff --git a/tauri-app/src-tauri/src/linux_monitor.rs b/tauri-app/src-tauri/src/linux_monitor.rs index b6715b7..2506f87 100644 --- a/tauri-app/src-tauri/src/linux_monitor.rs +++ b/tauri-app/src-tauri/src/linux_monitor.rs @@ -173,3 +173,30 @@ pub fn run( } let _ = app.emit("pipe-status", PipeStatus { connected: false }); } + +/// Useful for driver troubleshooting and an end-to-end Linux smoke test. +pub fn diagnostics() -> Result<(), String> { + let mut reader = LinuxSensors::default(); + reader.sample(Path::new("/proc"), Path::new("/sys"), Duration::ZERO)?; + let start = Instant::now(); + std::thread::sleep(Duration::from_millis(250)); + let mut data = reader.sample(Path::new("/proc"), Path::new("/sys"), start.elapsed())?; + append_nvidia(&mut data, &nvidia()); + let dir = dirs::cache_dir() + .unwrap_or_else(std::env::temp_dir) + .join("cleanmeter/fps"); + let games: Vec<_> = linux_fps::samples(&dir) + .iter() + .map(|s| { + serde_json::json!({ + "app": s.app, "fps": s.fps, "frametime": s.frametime + }) + }) + .collect(); + let output = serde_json::json!({ "hardware": data, "games": games }); + println!( + "{}", + serde_json::to_string_pretty(&output).map_err(|e| e.to_string())? + ); + Ok(()) +} diff --git a/tauri-app/src-tauri/src/linux_sensors.rs b/tauri-app/src-tauri/src/linux_sensors.rs index 46c6abc..80d7378 100644 --- a/tauri-app/src-tauri/src/linux_sensors.rs +++ b/tauri-app/src-tauri/src/linux_sensors.rs @@ -448,11 +448,43 @@ mod tests { ) .unwrap(); fs::write(root.join("net/dev"), "eth0: 100 0 0 0 0 0 0 0 200").unwrap(); + let gpu = root.join("class/drm/card0/device"); + fs::create_dir_all(gpu.join("hwmon/hwmon0")).unwrap(); + for (file, value) in [ + ("vendor", "0x1002"), + ("gpu_busy_percent", "42"), + ("mem_info_vram_used", "1073741824"), + ("mem_info_vram_total", "4294967296"), + ("hwmon/hwmon0/temp1_input", "65000"), + ("hwmon/hwmon0/power1_average", "125000000"), + ] { + fs::write(gpu.join(file), value).unwrap(); + } let mut s = LinuxSensors::default(); s.sample(&root, &root, Duration::from_secs(1)).unwrap(); fs::write(root.join("stat"), "cpu 150 0 0 150 0 0 0 0").unwrap(); fs::write(root.join("net/dev"), "eth0: 1100 0 0 0 0 0 0 0 2200").unwrap(); let d = s.sample(&root, &root, Duration::from_millis(500)).unwrap(); + assert!(d + .hardwares + .iter() + .any(|h| h.hardware_type == HardwareType::GpuAmd)); + for (name, kind, expected) in [ + ("GPU Core", SensorType::Load, 42.0), + ("GPU Core", SensorType::Temperature, 65.0), + ("GPU Power", SensorType::Power, 125.0), + ("GPU Memory Used", SensorType::SmallData, 1024.0), + ("GPU Memory", SensorType::Load, 25.0), + ] { + assert_eq!( + d.sensors + .iter() + .find(|s| s.name == name && s.sensor_type == kind) + .unwrap() + .value, + expected + ); + } assert_eq!( d.sensors .iter() diff --git a/tauri-app/src-tauri/src/main.rs b/tauri-app/src-tauri/src/main.rs index 67bfe95..794ba37 100644 --- a/tauri-app/src-tauri/src/main.rs +++ b/tauri-app/src-tauri/src/main.rs @@ -7,7 +7,15 @@ fn main() { { use std::os::unix::process::CommandExt; let mut args = std::env::args_os().skip(1); - if args.next().as_deref() == Some(std::ffi::OsStr::new("--run")) { + let action = args.next(); + if action.as_deref() == Some(std::ffi::OsStr::new("--diagnose")) { + if let Err(error) = cleanmeter_lib::linux_diagnostics() { + eprintln!("{error}"); + std::process::exit(1); + } + return; + } + if action.as_deref() == Some(std::ffi::OsStr::new("--run")) { // Use our compiled-in script, preserving each game argument verbatim. let error = std::process::Command::new("sh") .arg("-c") diff --git a/tauri-app/src-tauri/tauri.linux.conf.json b/tauri-app/src-tauri/tauri.linux.conf.json index 28184c0..4d486d7 100644 --- a/tauri-app/src-tauri/tauri.linux.conf.json +++ b/tauri-app/src-tauri/tauri.linux.conf.json @@ -28,5 +28,8 @@ } } } + }, + "app": { + "trayIcon": null } } diff --git a/tauri-app/src/App.tsx b/tauri-app/src/App.tsx index cabb594..3a68ab6 100644 --- a/tauri-app/src/App.tsx +++ b/tauri-app/src/App.tsx @@ -39,7 +39,7 @@ function MonitoringBanner() { }, []); const verdict = monitoringVerdict({ - hasSensorData: !!sensorData, + hasSensorData: !!sensorData && (!linux || !sidecarStatus.spawnError), sidecar: sidecarStatus, graceExpired, }); diff --git a/tauri-app/src/OverlayApp.tsx b/tauri-app/src/OverlayApp.tsx index 58dfb17..b7257cf 100644 --- a/tauri-app/src/OverlayApp.tsx +++ b/tauri-app/src/OverlayApp.tsx @@ -119,7 +119,7 @@ export default function OverlayApp() { // HUD pixels — never freezes the rest of the desktop. useEffect(() => { const el = hudRef.current; - if (!el || monitors.length === 0) return; + if (!el || (canPosition && monitors.length === 0)) return; const monitor = monitors[settings.selectedDisplayIndex] ?? monitors[0]; const apply = () => { @@ -130,6 +130,7 @@ export default function OverlayApp() { const hudH = Math.max(1, Math.ceil(rect.height * scale)); hudSizeRef.current = { w: hudW, h: hudH }; setOverlaySize(hudW, hudH); + if (!canPosition) return; // Skip position updates while the user is actively dragging. if (dragStart.current) return; @@ -179,6 +180,7 @@ export default function OverlayApp() { // changes — not on every settings update (font sizes, sensor toggles, // etc. would otherwise round-trip a no-op setOverlayPosition). }, [ + canPosition, settings.selectedDisplayIndex, settings.useCustomPosition, settings.positionX, diff --git a/tauri-app/src/components/overlay/CpuSection.tsx b/tauri-app/src/components/overlay/CpuSection.tsx index 79ab64a..7dd4851 100644 --- a/tauri-app/src/components/overlay/CpuSection.tsx +++ b/tauri-app/src/components/overlay/CpuSection.tsx @@ -1,3 +1,4 @@ +import { usePlatformStore } from "@/stores/platform-store"; import { Pill } from "./Pill"; import { ProgressRing } from "./ProgressRing"; import { ProgressBar } from "./ProgressBar"; @@ -9,6 +10,7 @@ interface CpuSectionProps { } export function CpuSection({ isHorizontal }: CpuSectionProps) { + const linux = usePlatformStore((s) => s.platform.os === "linux"); const settings = useSettingsStore((s) => s.settings); const sensorData = useSettingsStore((s) => s.sensorData); const sensors = sensorData?.sensors ?? []; @@ -33,6 +35,7 @@ export function CpuSection({ isHorizontal }: CpuSectionProps) { const cpuPowerVal = findSensorById(sensors, cpuConsumption.customReadingId)?.value ?? 0; const temp = formatTemperature(cpuTempVal, settings.temperatureUnit); + if (linux && !findSensorById(sensors, cpuTemp.customReadingId)) temp.label = "—"; return ( @@ -59,14 +62,14 @@ export function CpuSection({ isHorizontal }: CpuSectionProps) { ) : (
- {formatValue(cpuUsageVal)} + {linux && !findSensorById(sensors, cpuUsage.customReadingId) ? "—" : formatValue(cpuUsageVal)} %
@@ -77,7 +80,7 @@ export function CpuSection({ isHorizontal }: CpuSectionProps) { {cpuConsumption.isEnabled && (
- {formatValue(cpuPowerVal)} + {linux && !findSensorById(sensors, cpuConsumption.customReadingId) ? "—" : formatValue(cpuPowerVal)} W
diff --git a/tauri-app/src/components/overlay/FpsSection.tsx b/tauri-app/src/components/overlay/FpsSection.tsx index eaac40c..b93022b 100644 --- a/tauri-app/src/components/overlay/FpsSection.tsx +++ b/tauri-app/src/components/overlay/FpsSection.tsx @@ -76,7 +76,7 @@ export function FpsSection({ isHorizontal }: FpsSectionProps) { const onePercentValue = Math.round(onePercentLowSensor?.value ?? 0); const zeroPointOneValue = Math.round(zeroPointOneLowSensor?.value ?? 0); const lastFrametime = frametimeHistory.length > 0 ? frametimeHistory[frametimeHistory.length - 1] : 0; - const showFrametime = frametime.isEnabled && frametimeHistory.length > 2; + const showFrametime = frametime.isEnabled && frametimeHistory.length > 2 && (lowsSupported || !!fpsSensor); // A low with no reading yet reads 0, and the cluster STAYS on screen. // // The sidecar reports 0 while it warms up — LOWS_MIN_TOTAL_MS is 5s, and @@ -165,7 +165,7 @@ export function FpsSection({ isHorizontal }: FpsSectionProps) { ); const valueText = framerate.isEnabled && ( - {formatValue(fpsValue)} + {!lowsSupported && !fpsSensor ? "—" : formatValue(fpsValue)} ); // Only ever BETWEEN things. With the average hidden it would lead the pill, diff --git a/tauri-app/src/components/overlay/GpuSection.tsx b/tauri-app/src/components/overlay/GpuSection.tsx index 21b70eb..19fc564 100644 --- a/tauri-app/src/components/overlay/GpuSection.tsx +++ b/tauri-app/src/components/overlay/GpuSection.tsx @@ -1,3 +1,4 @@ +import { usePlatformStore } from "@/stores/platform-store"; import { Pill } from "./Pill"; import { ProgressRing } from "./ProgressRing"; import { ProgressBar } from "./ProgressBar"; @@ -11,6 +12,7 @@ interface GpuSectionProps { } export function GpuSection({ isHorizontal }: GpuSectionProps) { + const linux = usePlatformStore((s) => s.platform.os === "linux"); const settings = useSettingsStore((s) => s.settings); const sensorData = useSettingsStore((s) => s.sensorData); const sensors = sensorData?.sensors ?? []; @@ -79,6 +81,7 @@ export function GpuSection({ isHorizontal }: GpuSectionProps) { : vramLoadVal; const temp = formatTemperature(gpuTempVal, settings.temperatureUnit); + if (linux && !findSensorById(sensors, gpuTemp.customReadingId)) temp.label = "—"; return ( @@ -105,14 +108,14 @@ export function GpuSection({ isHorizontal }: GpuSectionProps) { ) : (
- {formatValue(gpuUsageVal)} + {linux && !findSensorById(sensors, gpuUsage.customReadingId) ? "—" : formatValue(gpuUsageVal)} %
@@ -127,14 +130,14 @@ export function GpuSection({ isHorizontal }: GpuSectionProps) { 0 ? formatValue(vramUsedVal, 1) : formatValue(vramUsageVal, 0)} + label={linux && !vramUsedSensor && !findSensorById(sensors, vramUsage.customReadingId) ? "—" : vramUsedVal > 0 ? formatValue(vramUsedVal, 1) : formatValue(vramUsageVal, 0)} unit={vramUsedVal > 0 ? "GB" : "%"} boundaries={vramUsage.boundaries} /> ) : (
- {vramUsedVal > 0 ? formatValue(vramUsedVal, 1) : formatValue(vramUsageVal, 0)} + {linux && !vramUsedSensor && !findSensorById(sensors, vramUsage.customReadingId) ? "—" : vramUsedVal > 0 ? formatValue(vramUsedVal, 1) : formatValue(vramUsageVal, 0)} {vramUsedVal > 0 ? "GB" : "%"}
@@ -145,7 +148,7 @@ export function GpuSection({ isHorizontal }: GpuSectionProps) { {gpuConsumption.isEnabled && (
- {formatValue(gpuPowerVal)} + {linux && !findSensorById(sensors, gpuConsumption.customReadingId) ? "—" : formatValue(gpuPowerVal)} W
diff --git a/tauri-app/src/components/settings/LinuxSupport.tsx b/tauri-app/src/components/settings/LinuxSupport.tsx index 67f94eb..d645201 100644 --- a/tauri-app/src/components/settings/LinuxSupport.tsx +++ b/tauri-app/src/components/settings/LinuxSupport.tsx @@ -1,3 +1,4 @@ +import { quitApp } from "@/lib/tauri"; import { usePlatformStore } from "@/stores/platform-store"; import { useSettingsStore } from "@/stores/settings-store"; import { Switch } from "@/components/shadcn/switch"; @@ -18,7 +19,8 @@ export function LinuxSupport() { ? "Linux preview · X11/XWayland. Overlay visibility in fullscreen games depends on your desktop." : "Wayland controls window placement. Use the monitor as a separate window, or sign in with an X11 session for overlay positioning and global shortcuts."}

-

Temperature, power, and GPU readings depend on your hardware driver. Unavailable sensors are not collected.

+

Temperature, power, and GPU readings depend on your hardware driver. Unavailable readings show a dash. CPU power is not collected in this preview.

+ ); } diff --git a/tauri-app/src/components/settings/help/FaqSection.tsx b/tauri-app/src/components/settings/help/FaqSection.tsx index c088955..eff4424 100644 --- a/tauri-app/src/components/settings/help/FaqSection.tsx +++ b/tauri-app/src/components/settings/help/FaqSection.tsx @@ -1,3 +1,4 @@ +import { usePlatformStore } from "@/stores/platform-store"; import { CollapsibleCard } from "../style/CollapsibleCard"; type FaqItem = { @@ -25,10 +26,16 @@ const FAQ_ITEMS: FaqItem[] = [ ]; export function FaqSection() { + const linux = usePlatformStore((s) => s.platform.os === "linux"); + const items = linux ? [ + { question: "How do I enable game FPS?", answer: "Install MangoHud 0.7.0 or newer and set Steam launch options to cleanmeter-run %command%. For native games, use cleanmeter-run followed by the game command. AppImage users can use ./Cleanmeter.AppImage --run followed by the game command." }, + { question: "What are the Linux preview limitations?", answer: "FPS and frametime are sampled. Percentile lows and benchmark recording are unavailable. Overlay positioning and global shortcuts need X11/XWayland; native Wayland uses a separate monitor window. Fullscreen visibility depends on your desktop compositor. Flatpak Steam and Gamescope sessions are not validated." }, + { question: "Which hardware readings are available?", answer: "CPU, RAM, and network readings come from Linux. AMD GPU sensors come from the kernel; NVIDIA readings require nvidia-smi. Intel GPU readings depend on available kernel sensors. Missing temperature or power readings show a dash. CPU power is not collected in this preview." }, + ] : FAQ_ITEMS; return (
    - {FAQ_ITEMS.map((item, idx) => ( + {items.map((item, idx) => (
  1. {idx + 1}. {item.question} diff --git a/tauri-app/src/components/settings/settings/SettingsTab.tsx b/tauri-app/src/components/settings/settings/SettingsTab.tsx index 615f8eb..be7950c 100644 --- a/tauri-app/src/components/settings/settings/SettingsTab.tsx +++ b/tauri-app/src/components/settings/settings/SettingsTab.tsx @@ -163,7 +163,7 @@ function ShortcutsSection() { accelerator={overlayAccelerator} defaultAccelerator={OVERLAY_SHORTCUT_DEFAULT} onChange={(overlayShortcut) => updateSettings({ overlayShortcut })} - conflictsWith={{ "Start/stop FPS lows recording": recordingAccelerator }} + conflictsWith={platform.percentileLows ? { "Start/stop FPS lows recording": recordingAccelerator } : {}} className="gap-[var(--spacingL)]" /> {platform.percentileLows && {platform.os === "linux" && (

    -

    Install MangoHud, then launch your game with cleanmeter-run. Steam launch options:

    +

    Install MangoHud 0.7.0 or newer, then launch your game with cleanmeter-run. Steam launch options:

    cleanmeter-run %command% +

    Using AppImage? Run ./Cleanmeter.AppImage --run your-game instead.

    FPS and frametime are sampled every 100 ms. Percentile lows and benchmark recording require per-frame capture and are unavailable in this Linux preview.

    {presentMonApps.length === 0 &&

    No game telemetry yet. Start a game with the launcher above.

    }
    diff --git a/tauri-app/src/hooks/useHotkey.ts b/tauri-app/src/hooks/useHotkey.ts index 8c84c4c..d04e1f5 100644 --- a/tauri-app/src/hooks/useHotkey.ts +++ b/tauri-app/src/hooks/useHotkey.ts @@ -9,6 +9,9 @@ export function useHotkey() { let unlisten: (() => void) | undefined; onHotkey((action) => { + if (action === "hide-overlay") { + useSettingsStore.getState().setOverlayVisible(false); + } if (action === "toggle-overlay") { toggleOverlay(); } diff --git a/tauri-app/src/lib/tauri.ts b/tauri-app/src/lib/tauri.ts index 983c7ea..3a2bec6 100644 --- a/tauri-app/src/lib/tauri.ts +++ b/tauri-app/src/lib/tauri.ts @@ -290,3 +290,9 @@ export const getPlatformInfo = () => { } return safeInvoke("get_platform_info"); }; + +export const quitApp = async (): Promise => { + if (isBrowser) return; + const { exit } = await import("@tauri-apps/plugin-process"); + await exit(0); +}; From 5c467a437d0637ded2047449120cca000a383372 Mon Sep 17 00:00:00 2001 From: Adnan Jaweed Date: Mon, 7 Sep 2026 09:04:30 -0400 Subject: [PATCH 3/7] Replay Linux telemetry state and check native Wayland startup --- .github/workflows/linux.yml | 26 ++++++++++++++++++++++-- README.md | 10 ++++++++- tauri-app/src-tauri/src/lib.rs | 2 ++ tauri-app/src-tauri/src/linux_monitor.rs | 9 ++++++-- tauri-app/src/hooks/useSensorData.ts | 11 ++++++++++ tauri-app/src/lib/tauri.ts | 5 +++-- 6 files changed, 56 insertions(+), 7 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index ee719b5..60fd931 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -31,7 +31,7 @@ jobs: - name: Install Linux build and smoke-test dependencies run: | sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev patchelf rpm xvfb dbus-x11 + sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev patchelf rpm xvfb dbus-x11 weston - run: npm ci - run: npm run lint && npm test && npm run build - run: python3 src-tauri/linux/test_launcher.py @@ -44,13 +44,33 @@ jobs: - name: Smoke test GUI and native monitoring run: | set +e - RUST_LOG=info WEBKIT_DISABLE_COMPOSITING_MODE=1 timeout 15s dbus-run-session -- xvfb-run -a src-tauri/target/release/cleanmeter > linux-smoke.log 2>&1 + RUST_LOG=info WEBKIT_DISABLE_COMPOSITING_MODE=1 timeout 15s xvfb-run -a dbus-run-session -- src-tauri/target/release/cleanmeter > linux-smoke.log 2>&1 result=$? set -e cat linux-smoke.log test "$result" -eq 124 grep -q 'Linux monitoring connected' linux-smoke.log test -x src-tauri/linux/cleanmeter-run + - name: Smoke test native Wayland fallback + run: | + export XDG_RUNTIME_DIR="$RUNNER_TEMP/cleanmeter-wayland" + mkdir -p "$XDG_RUNTIME_DIR" + chmod 700 "$XDG_RUNTIME_DIR" + weston --backend=headless-backend.so --socket=cleanmeter-test --idle-time=0 > weston.log 2>&1 & + compositor=$! + trap 'kill "$compositor" 2>/dev/null || true' EXIT + for attempt in $(seq 1 20); do + test -S "$XDG_RUNTIME_DIR/cleanmeter-test" && break + sleep 0.5 + done + set +e + env -u DISPLAY GDK_BACKEND=wayland WAYLAND_DISPLAY=cleanmeter-test RUST_LOG=info WEBKIT_DISABLE_COMPOSITING_MODE=1 timeout 15s dbus-run-session -- src-tauri/target/release/cleanmeter > wayland-smoke.log 2>&1 + result=$? + set -e + cat wayland-smoke.log + test "$result" -eq 124 + grep -q 'Linux monitoring connected' wayland-smoke.log + grep -q 'Display backend: wayland' wayland-smoke.log - uses: actions/upload-artifact@v4 if: always() with: @@ -61,6 +81,8 @@ jobs: tauri-app/src-tauri/target/release/bundle/rpm/*.rpm tauri-app/src-tauri/target/release/bundle/appimage/*.AppImage tauri-app/linux-smoke.log + tauri-app/wayland-smoke.log + tauri-app/weston.log live-fps: needs: linux diff --git a/README.md b/README.md index 5117c42..445703c 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,15 @@ A clean, minimal performance overlay for gamers. Monitor your system stats witho - **Network speed** — download/upload rates with live graph - **Smart sensor auto-select** — picks the right CPU, GPU, RAM, and network sensors automatically -## Requirements +## Linux preview + +Linux support is available on the `feat/linux-support` branch with native hardware +monitoring and sampled game FPS through MangoHud 0.7+. DEB, RPM, and AppImage +packages are built by the Linux preview workflow. See the [Linux setup guide](docs/linux.md) +for installation, Steam launch options, hardware coverage, and Wayland limitations. +Percentile lows and benchmark recording are not yet supported on Linux. + +## Windows requirements - Windows 10/11 (x64) - [.NET 8 Desktop Runtime](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) — required for hardware monitoring diff --git a/tauri-app/src-tauri/src/lib.rs b/tauri-app/src-tauri/src/lib.rs index 80e79fb..fbd029e 100644 --- a/tauri-app/src-tauri/src/lib.rs +++ b/tauri-app/src-tauri/src/lib.rs @@ -291,6 +291,8 @@ pub fn run() { })) .setup(|app| { info!("Cleanmeter starting up..."); + #[cfg(target_os = "linux")] + info!("Display backend: {}", platform::get_platform_info().display_backend); // Initialize the settings manager early so startup can read the // start_minimized preference before deciding whether to show the diff --git a/tauri-app/src-tauri/src/linux_monitor.rs b/tauri-app/src-tauri/src/linux_monitor.rs index 2506f87..78b68a6 100644 --- a/tauri-app/src-tauri/src/linux_monitor.rs +++ b/tauri-app/src-tauri/src/linux_monitor.rs @@ -68,6 +68,7 @@ pub fn run( let mut nv = String::new(); let mut connected = false; let mut last_apps = vec![]; + let mut apps_next = Instant::now(); while running.load(Ordering::Relaxed) { while let Ok(command) = commands.try_recv() { match command { @@ -79,7 +80,7 @@ pub fn run( target = if app == "Auto" { String::new() } else { app } } PipeCommand::RefreshPresentMonApps => { - last_apps.clear(); + apps_next = Instant::now(); next = Instant::now(); } PipeCommand::SetLowsMode(_) => {} @@ -103,9 +104,13 @@ pub fn run( let mut apps: Vec<_> = samples.iter().map(|s| s.app.clone()).collect(); apps.sort(); apps.dedup(); - if apps != last_apps { + // Webviews may subscribe after the first poll. Replay the list + // and connection status periodically even if nothing changed. + if apps != last_apps || now >= apps_next { let _ = app.emit("present-mon-apps", &apps); + let _ = app.emit("pipe-status", PipeStatus { connected: true }); last_apps = apps; + apps_next = now + Duration::from_secs(2); } let chosen = if target.is_empty() || target == "Auto" { samples.first() diff --git a/tauri-app/src/hooks/useSensorData.ts b/tauri-app/src/hooks/useSensorData.ts index 7632194..d91586b 100644 --- a/tauri-app/src/hooks/useSensorData.ts +++ b/tauri-app/src/hooks/useSensorData.ts @@ -1,3 +1,4 @@ +import { usePlatformStore } from "@/stores/platform-store"; import { useEffect, useRef, useState } from "react"; import { onSensorData, @@ -49,6 +50,8 @@ export function useSensorData() { /** Hook for overlay — keeps a rolling buffer of frametime values */ export function useFrametimeHistory(maxPoints = 30) { + const linux = usePlatformStore((s) => s.platform.os === "linux"); + const previousGame = useRef(""); const sensorData = useSettingsStore((s) => s.sensorData); const bufferRef = useRef([]); const prevData = useRef(null); @@ -62,6 +65,14 @@ export function useFrametimeHistory(maxPoints = 30) { /* eslint-disable react-hooks/refs */ if (sensorData && sensorData !== prevData.current) { prevData.current = sensorData; + if (linux) { + const game = sensorData.hardwares.find((h) => h.identifier === "/linux/fps")?.name ?? ""; + if (game !== previousGame.current) { + previousGame.current = game; + bufferRef.current = []; + setHistory([]); + } + } const frametime = sensorData.sensors.find( (s) => s.name.toLowerCase().includes("frametime") || s.identifier.toLowerCase().includes("frametime") diff --git a/tauri-app/src/lib/tauri.ts b/tauri-app/src/lib/tauri.ts index 3a2bec6..16d1070 100644 --- a/tauri-app/src/lib/tauri.ts +++ b/tauri-app/src/lib/tauri.ts @@ -153,10 +153,10 @@ export type AppUpdate = import("@tauri-apps/plugin-updater").Update; // Returns the pending Update when a newer release exists, or null when the app // is current (or running in the browser preview, which has no Tauri runtime). export const checkForUpdate = async (): Promise => { + if ((await getPlatformInfo()).os === "linux") return null; // The preview reports an update so the download banner has a state to be in. if (usePreviewFixture) return previewUpdate(); if (isBrowser) return null; - if ((await getPlatformInfo()).os === "linux") return null; const { check } = await import("@tauri-apps/plugin-updater"); return check(); }; @@ -286,7 +286,8 @@ export interface PlatformInfo { export const getPlatformInfo = () => { if (isBrowser) { const linux = navigator.platform.toLowerCase().includes("linux") || (import.meta.env.DEV && new URLSearchParams(location.search).get("platform") === "linux"); - return Promise.resolve({ os: linux ? "linux" : "windows", displayBackend: linux ? "x11" : "native", canPositionOverlay: true, globalShortcuts: true, percentileLows: !linux }); + const wayland = linux && import.meta.env.DEV && new URLSearchParams(location.search).get("display") === "wayland"; + return Promise.resolve({ os: linux ? "linux" : "windows", displayBackend: linux ? (wayland ? "wayland" : "x11") : "native", canPositionOverlay: !wayland, globalShortcuts: !wayland, percentileLows: !linux }); } return safeInvoke("get_platform_info"); }; From 246ea8df38db3708d50ee1d269e2a21e72e4a646 Mon Sep 17 00:00:00 2001 From: Adnan Jaweed Date: Mon, 7 Sep 2026 09:12:08 -0400 Subject: [PATCH 4/7] Use pinned MangoHud for live FPS validation and preserve rate intervals --- .github/workflows/linux.yml | 12 +++++++++--- docs/linux.md | 9 +++++++-- tauri-app/src-tauri/src/linux_monitor.rs | 3 ++- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 60fd931..23f23fe 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -96,7 +96,13 @@ jobs: - name: Install desktop runtime and real MangoHud run: | sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-0 libayatana-appindicator3-1 mangohud vulkan-tools mesa-vulkan-drivers xvfb + sudo apt-get install -y libwebkit2gtk-4.1-0 libayatana-appindicator3-1 libxnvctrl0 vulkan-tools mesa-vulkan-drivers xvfb + curl -fL https://github.com/flightlessmango/MangoHud/releases/download/v0.7.2/MangoHud-0.7.2.r0.g7b80f73.tar.gz -o mangohud.tar.gz + echo '16b5a5d39b82825bac69ead0f2dd5c5f2bbc32b973a2f7b117a775a0b8731f58 mangohud.tar.gz' | sha256sum -c - + tar -xzf mangohud.tar.gz + cd MangoHud + tar -xf MangoHud-package.tar + sudo bash mangohud-setup.sh install mangohud --version - name: Verify real Vulkan FPS through the AppImage launcher run: | @@ -105,11 +111,11 @@ jobs: "$image" --appimage-extract > /dev/null chmod +x squashfs-root/usr/bin/cleanmeter export XDG_CACHE_HOME="$RUNNER_TEMP/cleanmeter-live-test" - xvfb-run -a squashfs-root/usr/bin/cleanmeter --run vkcube > game.log 2>&1 & + xvfb-run -a squashfs-root/AppRun --run vkcube > game.log 2>&1 & game=$! trap 'kill "$game" 2>/dev/null || true' EXIT for attempt in $(seq 1 20); do - squashfs-root/usr/bin/cleanmeter --diagnose > diagnostics.json + squashfs-root/AppRun --diagnose > diagnostics.json if python3 -c 'import json; d=json.load(open("diagnostics.json")); assert any(g["fps"] > 0 and g["frametime"] > 0 for g in d["games"]); assert any(s["name"] == "CPU Total" for s in d["hardware"]["sensors"])'; then cat diagnostics.json exit 0 diff --git a/docs/linux.md b/docs/linux.md index 22c3902..df6c93d 100644 --- a/docs/linux.md +++ b/docs/linux.md @@ -40,7 +40,7 @@ turn Start at login off and back on to update its path. Install **MangoHud 0.7.0 or newer** through your distribution or the [upstream project](https://github.com/flightlessmango/MangoHud#installation). -Check with `mangohud --version`. Older distro packages, including 0.6.x, cannot +Check with `mangohud --version`. Older distro packages, including Ubuntu 22.04/24.04 packages based on 0.6.x, cannot provide the live CSV output used here. Hardware monitoring works without MangoHud. For a native game: @@ -127,8 +127,13 @@ npm run tauri -- build --bundles deb,rpm,appimage The platform-specific Tauri configurations keep Windows sidecar resources out of Linux bundles. `.github/workflows/linux.yml` builds all three package formats, -smoke-tests desktop startup, and checks live MangoHud FPS with a software-rendered +smoke-tests X11 and native Wayland startup, and checks live MangoHud 0.7.2 FPS with a software-rendered Vulkan cube on Ubuntu 24.04. Physical GPU drivers, actual games, Fedora installs, and native Wayland compositor behavior still need device testing before release. Linux updates are installed manually through a downloaded package; the Windows in-app updater is disabled for this preview. + +The standalone TypeScript check (`npx tsc --noEmit -p tsconfig.app.json`) currently +reports five pre-existing diagnostics also present on the base Windows branch. +The Linux changes do not introduce additional diagnostics; lint, frontend unit +tests, and the production Vite build are checked separately. diff --git a/tauri-app/src-tauri/src/linux_monitor.rs b/tauri-app/src-tauri/src/linux_monitor.rs index 78b68a6..d92e8dc 100644 --- a/tauri-app/src-tauri/src/linux_monitor.rs +++ b/tauri-app/src-tauri/src/linux_monitor.rs @@ -92,9 +92,10 @@ pub fn run( } let now = Instant::now(); let elapsed = now.duration_since(previous); - previous = now; match reader.sample(Path::new("/proc"), Path::new("/sys"), elapsed) { Ok(mut data) => { + // Rates span successful snapshots, including any failed polls. + previous = now; if now >= nv_next { nv = nvidia(); nv_next = Instant::now() + Duration::from_secs(1); From d8b757b29da7323c4b672380ac9f46e29ff66896 Mon Sep 17 00:00:00 2001 From: Adnan Jaweed Date: Mon, 7 Sep 2026 09:17:05 -0400 Subject: [PATCH 5/7] Reject invalid GPU memory totals before computing utilization --- tauri-app/src-tauri/src/linux_sensors.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/tauri-app/src-tauri/src/linux_sensors.rs b/tauri-app/src-tauri/src/linux_sensors.rs index 80d7378..b6a061f 100644 --- a/tauri-app/src-tauri/src/linux_sensors.rs +++ b/tauri-app/src-tauri/src/linux_sensors.rs @@ -293,7 +293,9 @@ impl LinuxSensors { if let Some(v) = number(device.join("gpu_busy_percent")).filter(|v| *v <= 100.0) { add(&mut data, &id, "load", "GPU Core", SensorType::Load, v); } - if let Some(used) = number(device.join("mem_info_vram_used")) { + if let Some(used) = + number(device.join("mem_info_vram_used")).filter(|v| v.is_finite() && *v >= 0.0) + { add( &mut data, &id, @@ -302,7 +304,8 @@ impl LinuxSensors { SensorType::SmallData, used / 1_048_576.0, ); - if let Some(total) = number(device.join("mem_info_vram_total")).filter(|v| *v > 0.0) + if let Some(total) = + number(device.join("mem_info_vram_total")).filter(|v| v.is_finite() && *v > 0.0) { add( &mut data, @@ -372,7 +375,7 @@ pub fn append_nvidia(data: &mut HardwareMonitorData, csv: &str) { } } if let (Ok(used), Ok(total)) = (v[4].parse::(), v[5].parse::()) { - if total > 0.0 { + if used.is_finite() && used >= 0.0 && total.is_finite() && total > 0.0 { add( data, &id, @@ -430,6 +433,12 @@ mod tests { .value, 25.0 ); + d.sensors.clear(); + append_nvidia(&mut d, "GPU-123, RTX Test, 30, 60, NaN, 4096, 120"); + assert!(!d + .sensors + .iter() + .any(|s| s.identifier.ends_with("memory-load"))); } #[test] fn fixture_rates_units_and_counter_reset() { From 230490c2e3ccbec1e413239ec11fb310f3ae12de Mon Sep 17 00:00:00 2001 From: Adnan Jaweed Date: Mon, 7 Sep 2026 09:20:23 -0400 Subject: [PATCH 6/7] Accept upstream MangoHud version prefixes in game launcher --- tauri-app/src-tauri/linux/cleanmeter-run | 2 +- tauri-app/src-tauri/linux/test_launcher.py | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/tauri-app/src-tauri/linux/cleanmeter-run b/tauri-app/src-tauri/linux/cleanmeter-run index 5d98bd0..28b2775 100755 --- a/tauri-app/src-tauri/linux/cleanmeter-run +++ b/tauri-app/src-tauri/linux/cleanmeter-run @@ -12,7 +12,7 @@ if ! command -v mangohud >/dev/null 2>&1; then fi # 0.6.x only saves CSV files when logging stops; live reads need 0.7+. version=$(mangohud --version 2>/dev/null || true) -if ! printf '%s\n' "$version" | awk -F. '/^[0-9]+\.[0-9]+/ { if ($1 > 0 || $2 >= 7) ok=1 } END { exit !ok }'; then +if ! printf '%s\n' "$version" | awk -F. '/^v?[0-9]+\.[0-9]+/ { major=$1; sub(/^v/, "", major); if (major+0 > 0 || $2+0 >= 7) ok=1 } END { exit !ok }'; then echo "Cleanmeter FPS requires MangoHud 0.7.0 or newer (found: $version)." >&2 exit 1 fi diff --git a/tauri-app/src-tauri/linux/test_launcher.py b/tauri-app/src-tauri/linux/test_launcher.py index 325aaa2..813e552 100644 --- a/tauri-app/src-tauri/linux/test_launcher.py +++ b/tauri-app/src-tauri/linux/test_launcher.py @@ -17,7 +17,7 @@ def setUp(self): fake.write_text("""#!/usr/bin/env python3 import json, os, pathlib, sys if sys.argv[1:] == ['--version']: - print(os.environ.get('TEST_VERSION', '0.7.2')) + print(os.environ.get('TEST_VERSION', 'v0.7.2')) sys.exit(0) config = pathlib.Path(os.environ['MANGOHUD_CONFIGFILE']) pathlib.Path(os.environ['TEST_RESULT']).write_text(json.dumps({ @@ -48,13 +48,18 @@ def test_literal_arguments_private_config_exit_code_and_cleanup(self): self.assertEqual(list((Path(self.env["XDG_CACHE_HOME"]) / "cleanmeter/fps").iterdir()), []) def test_rejects_old_or_unknown_mangohud_without_starting_game(self): - for version in ["0.6.5", "unknown", ""]: + for version in ["0.6.5", "v0.6.9", "unknown", ""]: self.env["TEST_VERSION"] = version result = self.run_launcher("game") self.assertEqual(result.returncode, 1) self.assertIn("0.7.0 or newer", result.stderr) self.assertFalse((self.root / "result.json").exists()) + def test_accepts_upstream_and_distro_version_formats(self): + for version in ["v0.7.2", "0.7.0", "v1.0.0"]: + self.env["TEST_VERSION"] = version + self.assertEqual(self.run_launcher("game").returncode, 17) + def test_usage_without_game(self): self.assertEqual(self.run_launcher().returncode, 2) From abf6e59a9ffc4f8b9cf7eb3ffecb90ce39e9fb16 Mon Sep 17 00:00:00 2001 From: Adnan Jaweed Date: Mon, 7 Sep 2026 09:29:32 -0400 Subject: [PATCH 7/7] Keep MangoHud sampling active while hiding its visual HUD --- .github/workflows/linux.yml | 1 + tauri-app/src-tauri/linux/cleanmeter-run | 7 +++++-- tauri-app/src-tauri/linux/test_launcher.py | 2 ++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 23f23fe..79ac436 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -123,6 +123,7 @@ jobs: sleep 1 done cat game.log + find "$XDG_CACHE_HOME/cleanmeter/fps" -name '*.csv' -exec sh -c 'head -n 4 "$1"; tail -n 3 "$1"' sh {} \; exit 1 - uses: actions/upload-artifact@v4 if: always() diff --git a/tauri-app/src-tauri/linux/cleanmeter-run b/tauri-app/src-tauri/linux/cleanmeter-run index 28b2775..65ef4b1 100755 --- a/tauri-app/src-tauri/linux/cleanmeter-run +++ b/tauri-app/src-tauri/linux/cleanmeter-run @@ -32,15 +32,18 @@ trap cleanup EXIT trap 'if [ -n "$child" ]; then kill -TERM "$child" 2>/dev/null || true; fi' INT TERM # A private config file avoids altering the user's MangoHud configuration. # Uploads are not enabled. Files are removed when the launched process exits. +# MangoHud 0.7.x no_display prevents autostart_log from running. Transparent +# rendering keeps that update path active without showing a second HUD. cat > "$session/MangoHud.conf" <