From 1f94edc1600d2e9ad80054fb382ea13610c85408 Mon Sep 17 00:00:00 2001 From: Saad Abdul Hakeem <152530391+saadah7@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:18:08 +0530 Subject: [PATCH 1/8] Add native Linux telemetry and per-frame FPS statistics --- tauri-app/src-tauri/linux/cleanmeter-run | 51 ++ tauri-app/src-tauri/linux/test_launcher.py | 76 +++ tauri-app/src-tauri/src/linux_fps.rs | 283 +++++++++ tauri-app/src-tauri/src/linux_frame_lows.rs | 95 +++ tauri-app/src-tauri/src/linux_monitor.rs | 223 ++++++++ tauri-app/src-tauri/src/linux_sensors.rs | 603 ++++++++++++++++++++ 6 files changed, 1331 insertions(+) create mode 100755 tauri-app/src-tauri/linux/cleanmeter-run create mode 100644 tauri-app/src-tauri/linux/test_launcher.py create mode 100644 tauri-app/src-tauri/src/linux_fps.rs create mode 100644 tauri-app/src-tauri/src/linux_frame_lows.rs create mode 100644 tauri-app/src-tauri/src/linux_monitor.rs create mode 100644 tauri-app/src-tauri/src/linux_sensors.rs diff --git a/tauri-app/src-tauri/linux/cleanmeter-run b/tauri-app/src-tauri/linux/cleanmeter-run new file mode 100755 index 0000000..ab71231 --- /dev/null +++ b/tauri-app/src-tauri/linux/cleanmeter-run @@ -0,0 +1,51 @@ +#!/bin/sh +# Launch a native or Proton game with per-frame 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 +# 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. '/^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 +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 +touch "$session/cleanmeter-per-frame" +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. +# 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" < 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() { + 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(|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) { + &stem[..stem.len() - 20] + } else { + stem + }; + Some(FpsSample { + path: path.to_path_buf(), + app: app.to_string(), + fps, + frametime, + modified, + }) +} + +/// Incrementally consume complete per-frame records; never infer frames from sampled CSV. +#[derive(Default)] +pub struct FrameReader { + path: PathBuf, + offset: u64, + last_timestamp: Option, + cols: Option<(usize, usize)>, + #[cfg(unix)] + identity: Option<(u64, u64)>, +} +impl FrameReader { + pub fn attach(&mut self, path: &Path) -> bool { + let metadata = fs::metadata(path).ok(); + #[cfg(unix)] + let identity = { + use std::os::unix::fs::MetadataExt; + metadata.as_ref().map(|m| (m.dev(), m.ino())) + }; + let mut unchanged = self.path == path && self.cols.is_some() + && metadata.as_ref().is_some_and(|m| m.len() >= self.offset); + #[cfg(unix)] + { unchanged = unchanged && identity == self.identity; } + if unchanged { return false; } + *self = Self { path: path.to_path_buf(), ..Self::default() }; + #[cfg(unix)] + { self.identity = identity; } + if path.parent().is_some_and(|p| p.join("cleanmeter-per-frame").is_file()) { + if let Ok(mut file) = File::open(path) { + let mut header = String::new(); + let _ = file.by_ref().take(4096).read_to_string(&mut header); + self.cols = header.lines().find_map(|line| { + let cols: Vec<_> = line.split(',').map(str::trim).collect(); + Some((cols.iter().position(|v| *v == "elapsed")?, cols.iter().position(|v| *v == "frametime")?)) + }); + self.offset = file.metadata().map(|m| m.len()).unwrap_or(0); + } + } + true + } + pub fn drain(&mut self) -> Vec<(f64, f64)> { + let Some((time_col, frame_col)) = self.cols else { return vec![]; }; + let Ok(mut file) = File::open(&self.path) else { return vec![]; }; + if file.metadata().map(|m| m.len() < self.offset).unwrap_or(true) { + self.cols = None; return vec![]; + } + if file.seek(SeekFrom::Start(self.offset)).is_err() { return vec![]; } + let mut bytes = vec![]; + if file.take(4 * 1024 * 1024).read_to_end(&mut bytes).is_err() { return vec![]; } + let Some(end) = bytes.iter().rposition(|b| *b == b'\n') else { return vec![]; }; + self.offset += end as u64 + 1; + let mut frames = vec![]; + for line in String::from_utf8_lossy(&bytes[..end]).lines() { + let cols: Vec<_> = line.split(',').collect(); + let Some(time) = cols.get(time_col).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite() && *v >= 0.0) else { continue; }; + let Some(ms) = cols.get(frame_col).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite() && *v > 0.0) else { continue; }; + if self.last_timestamp.is_some_and(|last| time <= last) { continue; } + self.last_timestamp = Some(time); + frames.push((time / 1_000_000.0, ms)); + } + frames + } +} + +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] + #[ignore = "requires a live MangoHud game launched by cleanmeter-run"] + fn live_per_frame_capture() { + let root = PathBuf::from(std::env::var("CLEANMETER_TEST_FPS_DIR").expect("FPS directory")); + let sample = samples(&root).into_iter().next().expect("live game"); + let mut reader = FrameReader::default(); reader.attach(&sample.path); + let mut lows = crate::linux_frame_lows::FrameLows::default(); + let mut count = 0; + for _ in 0..80 { + std::thread::sleep(Duration::from_millis(100)); + for (t, ms) in reader.drain() { lows.add(t, ms); count += 1; } + } + let (one, point_one) = lows.values(); + println!("frames={count}, one_percent_low={one}, point_one_percent_low={point_one}"); + assert!(count > 100, "must exceed 100ms sampling frequency"); + assert!(one > 0.0 && point_one > 0.0 && point_one <= one); + } + #[test] + fn frame_reader_consumes_each_complete_row_once_and_requires_marker() { + use std::io::Write; + let root = std::env::temp_dir().join(format!("cleanmeter-stream-{}", SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_nanos())); + fs::create_dir_all(&root).unwrap(); + let path = root.join("game.csv"); + fs::write(&path, "fps,frametime,elapsed\n").unwrap(); + let mut reader = FrameReader::default(); reader.attach(&path); + let mut file = std::fs::OpenOptions::new().append(true).open(&path).unwrap(); + writeln!(file, "100,10,10000000").unwrap(); + assert!(reader.drain().is_empty()); + fs::write(root.join("cleanmeter-per-frame"), "").unwrap(); + reader = FrameReader::default(); reader.attach(&path); + write!(file, "100,10,20000000\n100,10,").unwrap(); + assert_eq!(reader.drain(), vec![(20.0,10.0)]); + assert!(reader.drain().is_empty()); + writeln!(file, "30000000").unwrap(); + assert_eq!(reader.drain(), vec![(30.0,10.0)]); + writeln!(file, "100,10,30000000\n100,NaN,40000000").unwrap(); + assert!(reader.drain().is_empty()); + drop(file); fs::remove_dir_all(root).unwrap(); + } + #[test] + fn frame_reader_recovers_from_late_headers_truncation_and_replacement() { + use std::io::Write; + let root = std::env::temp_dir().join(format!("cleanmeter-rotation-{}", SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_nanos())); + fs::create_dir_all(&root).unwrap(); + fs::write(root.join("cleanmeter-per-frame"), "").unwrap(); + let path = root.join("game.csv"); + fs::write(&path, "").unwrap(); + let mut reader = FrameReader::default(); + assert!(reader.attach(&path)); + fs::write(&path, "fps,frametime,elapsed\n").unwrap(); + assert!(reader.attach(&path)); + assert!(!reader.attach(&path)); + let append = |timestamp| { + let mut file = fs::OpenOptions::new().append(true).open(&path).unwrap(); + writeln!(file, "100,10,{timestamp}").unwrap(); + }; + append(10000000); + assert_eq!(reader.drain(), vec![(10.0, 10.0)]); + fs::write(&path, "fps,frametime,elapsed\n").unwrap(); + assert!(reader.attach(&path)); + append(1000000); + assert_eq!(reader.drain(), vec![(1.0, 10.0)]); + #[cfg(unix)] + { + fs::rename(&path, root.join("old.csv")).unwrap(); + fs::write(&path, "fps,frametime,elapsed\n100,10,1000000\n").unwrap(); + assert!(reader.attach(&path)); + append(2000000); + assert_eq!(reader.drain(), vec![(2.0, 10.0)]); + } + fs::remove_dir_all(root).unwrap(); + } + #[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::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_frame_lows.rs b/tauri-app/src-tauri/src/linux_frame_lows.rs new file mode 100644 index 0000000..acc32c5 --- /dev/null +++ b/tauri-app/src-tauri/src/linux_frame_lows.rs @@ -0,0 +1,95 @@ +//! Frame-time statistics matching the Windows live window and recording histogram. +use std::collections::VecDeque; + +pub struct FrameLows { + live: VecDeque<(f64, f64)>, + buckets: Vec, + total: f64, + mode: u8, + frozen: (f32, f32), +} +impl Default for FrameLows { + fn default() -> Self { + Self { live: VecDeque::new(), buckets: vec![0; 100001], total: 0.0, mode: 2, frozen: (0.0, 0.0) } + } +} +impl FrameLows { + pub fn reset(&mut self) { + self.live.clear(); + if self.total > 0.0 { self.buckets.fill(0); } + self.total = 0.0; + self.frozen = (0.0, 0.0); + } + pub fn set_mode(&mut self, mode: u8) { + if mode == self.mode { return; } + if mode == 0 { self.frozen = self.values(); } + if mode == 1 { self.buckets.fill(0); self.total = 0.0; } + self.mode = mode; + } + pub fn add(&mut self, timestamp_ms: f64, ms: f64) { + if !timestamp_ms.is_finite() || !ms.is_finite() || ms <= 0.0 { return; } + self.live.push_back((timestamp_ms, ms)); + while self.live.front().is_some_and(|(t, _)| timestamp_ms - t > 10000.0) || self.live.len() > 16384 { + self.live.pop_front(); + } + if self.mode == 1 { + let bucket = (ms.min(1000.0) * 100.0).round_ties_even() as usize; + self.buckets[bucket] += 1; + self.total += bucket as f64 / 100.0; + } + } + pub fn values(&self) -> (f32, f32) { + if self.mode == 0 { return self.frozen; } + let compute = |fraction: f64| { + let mut accumulated = 0.0; + if self.mode == 1 { + if self.total < 5000.0 { return 0.0; } + for (i, count) in self.buckets.iter().enumerate().rev() { + accumulated += i as f64 / 100.0 * *count as f64; + if accumulated >= self.total * fraction { return (100000.0 / i as f64) as f32; } + } + } else { + let mut frames: Vec<_> = self.live.iter().map(|(_, ms)| *ms).collect(); + let total: f64 = frames.iter().sum(); + if total < 5000.0 && frames.len() < 16384 { return 0.0; } + frames.sort_by(|a,b| b.total_cmp(a)); + for ms in frames { + accumulated += ms; + if accumulated >= total * fraction { return (1000.0 / ms) as f32; } + } + } + 0.0 + }; + (compute(0.01), compute(0.001)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn time_integral_hitch_matches_windows_and_expires() { + let mut s = FrameLows::default(); + for i in 0..999 { s.add(i as f64 * 8.0, 8.0); } + s.add(8000.0, 200.0); + assert_eq!(s.values(), (5.0, 5.0)); + for i in 0..1400 { s.add(8200.0 + i as f64 * 8.0, 8.0); } + assert_eq!(s.values(), (125.0, 125.0)); + } + #[test] + fn recording_freezes_then_returns_to_live() { + let mut s = FrameLows::default(); s.set_mode(1); + for i in 0..1000 { s.add(i as f64 * 10.0, 10.0); } + s.set_mode(0); + for i in 0..3000 { s.add(10000.0 + i as f64 * 5.0, 5.0); } + assert_eq!(s.values(), (100.0,100.0)); + s.set_mode(2); assert_eq!(s.values(), (200.0,200.0)); + s.set_mode(1); assert_eq!(s.values(), (0.0,0.0)); + } + #[test] + fn invalid_frames_and_warmup_do_not_publish() { + let mut s = FrameLows::default(); + for ms in [f64::NAN, f64::INFINITY, -1.0, 0.0] { s.add(1.0,ms); } + s.add(2.0,16.0); assert_eq!(s.values(), (0.0,0.0)); + } +} 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..53d9df5 --- /dev/null +++ b/tauri-app/src-tauri/src/linux_monitor.rs @@ -0,0 +1,223 @@ +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,clocks.current.graphics,clocks.current.memory","--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 frames = linux_fps::FrameReader::default(); + let mut lows = crate::linux_frame_lows::FrameLows::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![]; + let mut apps_next = Instant::now(); + 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 => { + apps_next = Instant::now(); + next = Instant::now(); + } + PipeCommand::SetLowsMode(mode) => { + for (time, ms) in frames.drain() { lows.add(time, ms); } + lows.set_mode(mode); + } + } + } + if Instant::now() < next { + std::thread::sleep(Duration::from_millis(20)); + continue; + } + let now = Instant::now(); + let elapsed = now.duration_since(previous); + 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); + } + 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(); + // 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() + } else { + samples.iter().find(|s| s.app == target) + }; + if let Some(s) = chosen { + if frames.attach(&s.path) { lows.reset(); } + for (time, ms) in frames.drain() { lows.add(time, ms); } + let (one, point_one) = lows.values(); + for (key, name, value) in [("onepercentlow", "1% Low", one), ("zeropointonepercentlow", "0.1% Low", point_one)] { + if value > 0.0 { if let Some(v) = sensor("/linux/fps", key, name, SensorType::Frequency, value as f64) { data.sensors.push(v); } } + } + 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 chosen.is_none() { + frames = linux_fps::FrameReader::default(); + lows.reset(); + } + 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 }); +} + +/// 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 new file mode 100644 index 0000000..8b68d40 --- /dev/null +++ b/tauri-app/src-tauri/src/linux_sensors.rs @@ -0,0 +1,603 @@ +//! 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, + energy: 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 energy_watts(previous: f64, current: f64, maximum: Option, elapsed: Duration) -> Option { + if elapsed.is_zero() || !previous.is_finite() || !current.is_finite() || previous < 0.0 || current < 0.0 { return None; } + let delta = if current >= previous { current - previous } else { + let maximum = maximum.filter(|m| m.is_finite() && *m > previous && *m > current)?; + maximum - previous + current + }; + let watts = delta / elapsed.as_secs_f64() / 1_000_000.0; + (watts <= 2000.0).then_some(watts) +} +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); + let mut energy = HashMap::new(); + for zone in entries(sys.join("class/powercap")) { + let name = fs::read_to_string(zone.join("name")).unwrap_or_default(); + if !name.trim().starts_with("package-") { continue; } + let Some(current) = number(zone.join("energy_uj")).filter(|v| v.is_finite() && *v >= 0.0) else { continue; }; + if let Some(previous) = self.energy.get(&zone) { + if let Some(watts) = energy_watts(*previous, current, number(zone.join("max_energy_range_uj")), elapsed) { + add(&mut data, "/linux/cpu", &format!("power/{}", name.trim()), + &format!("CPU {}", name.trim()), SensorType::Power, watts); + } + } + energy.insert(zone, current); + } + self.energy = energy; + for core in entries(sys.join("devices/system/cpu")) { + let Some(index) = core.file_name().and_then(|v| v.to_str()) + .and_then(|v| v.strip_prefix("cpu")).and_then(|v| v.parse::().ok()) else { continue }; + if let Some(khz) = number(core.join("cpufreq/scaling_cur_freq")).filter(|v| *v > 0.0) { + add(&mut data, "/linux/cpu", &format!("clock/{index}"), + &format!("CPU Core #{}", index + 1), SensorType::Clock, khz / 1000.0); + } + } + 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" + ) { + if let Some(watts) = number(hw.join("power1_average")) + .or_else(|| number(hw.join("power1_input"))) { + add(&mut data, "/linux/cpu", "power", "CPU Package", SensorType::Power, watts / 1_000_000.0); + } + // 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 vendor.trim() == "0x8086" { + if let Some(mhz) = number(card.join("gt_cur_freq_mhz")).filter(|v| *v > 0.0) { + add(&mut data, &id, "core-clock", "GPU Core", SensorType::Clock, mhz); + } + } + 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")).filter(|v| v.is_finite() && *v >= 0.0) + { + 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.is_finite() && *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")) { + for (file, key, label) in [("freq1_input", "core-clock", "GPU Core"), ("freq2_input", "memory-clock", "GPU Memory")] { + if let Some(hz) = number(hw.join(file)).filter(|v| *v > 0.0) { + add(&mut data, &id, key, label, SensorType::Clock, hz / 1_000_000.0); + } + } + 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 !matches!(v.len(), 7 | 9) || !v[0].starts_with("GPU-") { + continue; + } + let id = format!("/linux/nvidia/{}", v[0]); + hardware(data, &id, v[1], HardwareType::GpuNvidia); + for (index, key, label) in [(7, "core-clock", "GPU Core"), (8, "memory-clock", "GPU Memory")] { + if let Some(mhz) = v.get(index).and_then(|v| v.parse::().ok()).filter(|v| *v > 0.0) { + add(data, &id, key, label, SensorType::Clock, mhz); + } + } + 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 used.is_finite() && used >= 0.0 && total.is_finite() && 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 package_energy_units_rollover_and_invalid_counters() { + assert_eq!(energy_watts(1_000_000.0, 26_000_000.0, None, Duration::from_millis(500)), Some(50.0)); + assert_eq!(energy_watts(90_000_000.0, 10_000_000.0, Some(100_000_000.0), Duration::from_secs(1)), Some(20.0)); + assert_eq!(energy_watts(100.0, 1.0, None, Duration::from_secs(1)), None); + assert_eq!(energy_watts(0.0, 1.0, None, Duration::ZERO), None); + assert_eq!(energy_watts(f64::NAN, 1.0, None, Duration::from_secs(1)), None); + } + #[test] + fn nvidia_clocks_preserve_missing_memory_clock() { + let mut d = HardwareMonitorData { hardwares: vec![], sensors: vec![], last_poll_time: 0 }; + append_nvidia(&mut d, "GPU-test, NVIDIA, 40, 65, 1000, 8000, 90, 1800, N/A"); + let clocks: Vec<_> = d.sensors.iter().filter(|s| s.sensor_type == SensorType::Clock).collect(); + assert_eq!(clocks.len(), 1); + assert_eq!(clocks[0].value, 1800.0); + } + #[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 + ); + 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() { + 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 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/freq1_input", "1600000000"), + ("hwmon/hwmon0/power1_average", "125000000"), + ] { + fs::write(gpu.join(file), value).unwrap(); + } + let cpu_clock = root.join("devices/system/cpu/cpu0/cpufreq"); + fs::create_dir_all(&cpu_clock).unwrap(); + fs::write(cpu_clock.join("scaling_cur_freq"), "3500000").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 Core", SensorType::Clock, 1600.0), + ("CPU Core #1", SensorType::Clock, 3500.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() + .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(); + } +} From c6252d70862281626ecc56c2f6353d3e1daaae84 Mon Sep 17 00:00:00 2001 From: Saad Abdul Hakeem <152530391+saadah7@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:18:09 +0530 Subject: [PATCH 2/8] Integrate Linux desktop lifecycle, Wayland overlays and portal shortcuts --- tauri-app/src-tauri/Cargo.lock | 126 +++++++++++++++--- tauri-app/src-tauri/Cargo.toml | 7 +- tauri-app/src-tauri/src/commands.rs | 30 +++-- .../src-tauri/src/feedback_diagnostics.rs | 12 +- tauri-app/src-tauri/src/lib.rs | 92 ++++++++++++- tauri-app/src-tauri/src/linux_autostart.rs | 80 +++++++++++ tauri-app/src-tauri/src/linux_overlay.rs | 59 ++++++++ .../src-tauri/src/linux_shortcut_trigger.rs | 38 ++++++ tauri-app/src-tauri/src/linux_shortcuts.rs | 93 +++++++++++++ tauri-app/src-tauri/src/main.rs | 25 ++++ tauri-app/src-tauri/src/platform.rs | 63 +++++++++ tauri-app/src-tauri/src/shortcuts.rs | 4 + tauri-app/src-tauri/src/tray.rs | 11 +- tauri-app/src-tauri/tauri.conf.json | 15 +-- tauri-app/src-tauri/tauri.linux.conf.json | 36 +++++ tauri-app/src-tauri/tauri.windows.conf.json | 10 ++ 16 files changed, 651 insertions(+), 50 deletions(-) create mode 100644 tauri-app/src-tauri/src/linux_autostart.rs create mode 100644 tauri-app/src-tauri/src/linux_overlay.rs create mode 100644 tauri-app/src-tauri/src/linux_shortcut_trigger.rs create mode 100644 tauri-app/src-tauri/src/linux_shortcuts.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 diff --git a/tauri-app/src-tauri/Cargo.lock b/tauri-app/src-tauri/Cargo.lock index f8eda64..5b6899f 100644 --- a/tauri-app/src-tauri/Cargo.lock +++ b/tauri-app/src-tauri/Cargo.lock @@ -106,6 +106,20 @@ dependencies = [ "derive_arbitrary", ] +[[package]] +name = "ashpd" +version = "0.13.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb8421aaa9644a5faf26735f258b669b15f063313ef8f8e2bdb28912a1a6f111" +dependencies = [ + "enumflags2", + "futures-util", + "getrandom 0.4.2", + "serde", + "tokio", + "zbus", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -257,7 +271,7 @@ dependencies = [ "glib-sys", "gobject-sys", "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -424,7 +438,7 @@ checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" dependencies = [ "glib-sys", "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -503,7 +517,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" dependencies = [ "smallvec", - "target-lexicon", + "target-lexicon 0.12.16", +] + +[[package]] +name = "cfg-expr" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f" +dependencies = [ + "smallvec", + "target-lexicon 0.13.5", ] [[package]] @@ -534,9 +558,13 @@ dependencies = [ name = "cleanmeter" version = "2.2.19" dependencies = [ + "ashpd", "byteorder", "dirs", "env_logger", + "futures-util", + "gtk", + "gtk-layer-shell", "log", "reqwest 0.12.28", "serde", @@ -1353,7 +1381,7 @@ dependencies = [ "glib-sys", "gobject-sys", "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -1370,7 +1398,7 @@ dependencies = [ "libc", "pango-sys", "pkg-config", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -1384,7 +1412,7 @@ dependencies = [ "gobject-sys", "libc", "pkg-config", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -1410,7 +1438,7 @@ dependencies = [ "gdk-sys", "glib-sys", "libc", - "system-deps", + "system-deps 6.2.2", "x11", ] @@ -1513,7 +1541,7 @@ dependencies = [ "glib-sys", "gobject-sys", "libc", - "system-deps", + "system-deps 6.2.2", "winapi", ] @@ -1561,7 +1589,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" dependencies = [ "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -1596,7 +1624,7 @@ checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" dependencies = [ "glib-sys", "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -1620,6 +1648,34 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "gtk-layer-shell" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc759b3184830a547b31549ab40c4b54450ab702bba79ba23f049bc1d1e3ca98" +dependencies = [ + "bitflags 2.11.0", + "gdk", + "glib", + "glib-sys", + "gtk", + "gtk-layer-shell-sys", + "libc", +] + +[[package]] +name = "gtk-layer-shell-sys" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4eee067e022416d53a70de69d3d3929d8a6e687f3278b8934faa671750fa6eb" +dependencies = [ + "gdk-sys", + "glib-sys", + "gtk-sys", + "libc", + "system-deps 7.0.8", +] + [[package]] name = "gtk-sys" version = "0.18.2" @@ -1635,7 +1691,7 @@ dependencies = [ "gobject-sys", "libc", "pango-sys", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -2065,7 +2121,7 @@ dependencies = [ "glib-sys", "gobject-sys", "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -2080,7 +2136,7 @@ dependencies = [ "portable-atomic", "portable-atomic-util", "serde_core", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2786,7 +2842,7 @@ dependencies = [ "glib-sys", "gobject-sys", "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -4194,7 +4250,7 @@ dependencies = [ "glib-sys", "gobject-sys", "libc", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -4323,13 +4379,26 @@ version = "6.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" dependencies = [ - "cfg-expr", + "cfg-expr 0.15.8", "heck 0.5.0", "pkg-config", "toml 0.8.2", "version-compare", ] +[[package]] +name = "system-deps" +version = "7.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" +dependencies = [ + "cfg-expr 0.20.10", + "heck 0.5.0", + "pkg-config", + "toml 1.0.6+spec-1.1.0", + "version-compare", +] + [[package]] name = "tao" version = "0.35.3" @@ -4398,6 +4467,12 @@ version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + [[package]] name = "tauri" version = "2.11.5" @@ -4908,6 +4983,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", + "tracing", "windows-sys 0.61.2", ] @@ -4972,6 +5048,21 @@ dependencies = [ "winnow 0.7.15", ] +[[package]] +name = "toml" +version = "1.0.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "399b1124a3c9e16766831c6bba21e50192572cdd98706ea114f9502509686ffc" +dependencies = [ + "indexmap 2.13.0", + "serde_core", + "serde_spanned 1.0.4", + "toml_datetime 1.0.0+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + [[package]] name = "toml_datetime" version = "0.6.3" @@ -5563,7 +5654,7 @@ dependencies = [ "libc", "pkg-config", "soup3-sys", - "system-deps", + "system-deps 6.2.2", ] [[package]] @@ -6355,6 +6446,7 @@ dependencies = [ "rustix", "serde", "serde_repr", + "tokio", "tracing", "uds_windows", "uuid", diff --git a/tauri-app/src-tauri/Cargo.toml b/tauri-app/src-tauri/Cargo.toml index 466f7f4..3ef2957 100644 --- a/tauri-app/src-tauri/Cargo.toml +++ b/tauri-app/src-tauri/Cargo.toml @@ -31,9 +31,14 @@ log = "0.4" env_logger = "0.11" dirs = "6" -winreg = "0.55" +[target.'cfg(target_os = "linux")'.dependencies] +gtk = "0.18" +gtk-layer-shell = { version = "0.8.2", features = ["v0_6"] } +ashpd = { version = "0.13.13", default-features = false, features = ["tokio", "global_shortcuts"] } +futures-util = "0.3" [target.'cfg(windows)'.dependencies] +winreg = "0.55" windows = { version = "0.58", features = [ "Win32_Foundation", "Win32_Storage_FileSystem", diff --git a/tauri-app/src-tauri/src/commands.rs b/tauri-app/src-tauri/src/commands.rs index 304bbc9..147f842 100644 --- a/tauri-app/src-tauri/src/commands.rs +++ b/tauri-app/src-tauri/src/commands.rs @@ -162,8 +162,10 @@ pub fn save_preferences(prefs: AppPreferences, settings_mgr: State<'_, SettingsM /// when the flag already matches, since tao's `apply_diff` early-returns on an /// empty flag diff. pub fn apply_overlay_interactive(app: &AppHandle, interactive: bool) { + #[cfg(target_os = "linux")] + if crate::linux_overlay::active() { crate::linux_overlay::interactive(app, interactive); return; } if let Some(overlay) = app.get_webview_window("overlay") { - let _ = overlay.set_ignore_cursor_events(!interactive); + let _ = overlay.set_ignore_cursor_events(!interactive && !crate::platform::native_wayland()); } } @@ -178,7 +180,7 @@ pub fn apply_overlay_interactive(app: &AppHandle, interactive: bool) { /// the interaction destroyed its own precondition. Asking "is any window of ours in /// front" covers both the settings window and the overlay, so a drag completes. #[cfg(windows)] -fn foreground_is_ours() -> bool { +fn foreground_is_ours(_app: &AppHandle) -> bool { use windows::Win32::System::Threading::GetCurrentProcessId; use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId}; unsafe { @@ -192,15 +194,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. @@ -279,6 +275,7 @@ pub fn bring_to_front(window: &tauri::WebviewWindow) { /// everywhere else the plain call is already the right one. #[cfg(not(windows))] pub fn bring_to_front(window: &tauri::WebviewWindow) { + let _ = window.unminimize(); let _ = window.set_focus(); } @@ -299,7 +296,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] @@ -348,6 +345,9 @@ pub fn refresh_overlay_z_order(overlay: &tauri::WebviewWindow) { #[tauri::command] pub fn set_overlay_position(x: i32, y: i32, app: AppHandle) { + #[cfg(target_os = "linux")] + if crate::linux_overlay::active() { crate::linux_overlay::position(&app, x, y); return; } + 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))); } @@ -417,6 +417,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; @@ -478,6 +484,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/feedback_diagnostics.rs b/tauri-app/src-tauri/src/feedback_diagnostics.rs index b460308..42b445e 100644 --- a/tauri-app/src-tauri/src/feedback_diagnostics.rs +++ b/tauri-app/src-tauri/src/feedback_diagnostics.rs @@ -104,7 +104,7 @@ fn open_no_follow(path: &Path) -> std::io::Result { Ok(file) } -// Non-Windows builds are not shipped; a plain pre-check is enough there. +// Linux builds run without elevation; reject linked log paths before reading. #[cfg(not(windows))] fn open_no_follow(path: &Path) -> std::io::Result { if std::fs::symlink_metadata(path)?.file_type().is_symlink() { @@ -136,7 +136,10 @@ fn cpu_name() -> Option { #[cfg(not(windows))] fn cpu_name() -> Option { - std::env::var("PROCESSOR_IDENTIFIER").ok() + std::fs::read_to_string("/proc/cpuinfo").ok()?.lines().find_map(|line| { + let (key, value) = line.split_once(':')?; + matches!(key.trim(), "model name" | "Hardware").then(|| value.trim().to_owned()) + }) } // "Windows 11 25H2 (build 26200) x86_64". ProductName still says "Windows 10" @@ -171,7 +174,10 @@ fn os_name() -> String { #[cfg(not(windows))] fn os_name() -> String { - format!("{} {}", std::env::consts::OS, std::env::consts::ARCH) + let name = std::fs::read_to_string("/etc/os-release").ok().and_then(|text| { + text.lines().find_map(|line| line.strip_prefix("PRETTY_NAME=").map(|v| v.trim_matches('"').to_owned())) + }).unwrap_or_else(|| std::env::consts::OS.to_owned()); + format!("{} {}", name, std::env::consts::ARCH) } #[cfg(test)] diff --git a/tauri-app/src-tauri/src/lib.rs b/tauri-app/src-tauri/src/lib.rs index 9435e39..3a037e3 100644 --- a/tauri-app/src-tauri/src/lib.rs +++ b/tauri-app/src-tauri/src/lib.rs @@ -1,3 +1,20 @@ +#[cfg(any(target_os = "linux", test))] +mod linux_shortcut_trigger; +#[cfg(target_os = "linux")] +mod linux_shortcuts; +#[cfg(target_os = "linux")] +mod linux_overlay; +#[cfg(any(target_os = "linux", test))] +mod linux_frame_lows; +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 feedback_attachment; mod feedback_diagnostics; @@ -257,6 +274,13 @@ 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"); + } // A packaged GUI has no console. Persist connection/spawn diagnostics so // a report can distinguish "server never opened" from a client failure. let mut logger = env_logger::Builder::from_env( @@ -272,14 +296,20 @@ pub fn run() { let _ = std::fs::rename(&path, dir.join("cleanmeter.previous.log")); } if let Ok(file) = std::fs::OpenOptions::new().create(true).append(true).open(path) { + #[cfg(not(target_os = "linux"))] logger.target(env_logger::Target::Pipe(Box::new(file))); + #[cfg(target_os = "linux")] + logger.target(env_logger::Target::Pipe(Box::new(LinuxLog(file)))); } } } let _ = logger.try_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()) @@ -295,6 +325,8 @@ pub fn run() { .setup(|app| { info!("Cleanmeter {} starting (pid {}, executable {:?})", app.package_info().version, std::process::id(), std::env::current_exe()); + #[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 @@ -368,9 +400,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();} } } @@ -385,17 +419,45 @@ 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() && !linux_overlay::setup(app.handle()) { + 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"); + let handle = app.handle().clone(); + let monitor = overlay.clone(); + overlay.on_window_event(move |event| { + if let tauri::WindowEvent::CloseRequested { api, .. } = event { + api.prevent_close(); + let _ = monitor.hide(); + let _ = handle.emit("hotkey", "hide-overlay"); + } + }); + } + } + } // 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 @@ -624,7 +686,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. @@ -670,6 +735,7 @@ pub fn run() { Ok(()) }) .invoke_handler(tauri::generate_handler![ + platform::get_platform_info, commands::get_settings, commands::save_settings, commands::clear_settings, @@ -716,3 +782,21 @@ pub fn run() { } }); } + +/// Print a read-only hardware/FPS snapshot without opening a desktop window. +#[cfg(target_os = "linux")] +pub fn linux_diagnostics() -> Result<(), String> { + linux_monitor::diagnostics() +} + +#[cfg(target_os = "linux")] +struct LinuxLog(std::fs::File); +#[cfg(target_os = "linux")] +impl std::io::Write for LinuxLog { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + let _ = std::io::stderr().write_all(bytes); + self.0.write_all(bytes)?; + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { self.0.flush() } +} 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..414c627 --- /dev/null +++ b/tauri-app/src-tauri/src/linux_autostart.rs @@ -0,0 +1,80 @@ +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"); + 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")) + .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()); + } + + #[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_overlay.rs b/tauri-app/src-tauri/src/linux_overlay.rs new file mode 100644 index 0000000..6451265 --- /dev/null +++ b/tauri-app/src-tauri/src/linux_overlay.rs @@ -0,0 +1,59 @@ +//! Native Wayland layer surface. GTK operations stay on the application thread. +use gtk::prelude::*; +use gtk_layer_shell::{Edge, KeyboardMode, Layer, LayerShell}; +use std::sync::atomic::{AtomicBool, Ordering}; +use tauri::{AppHandle, Manager}; + +static ACTIVE: AtomicBool = AtomicBool::new(false); +pub fn active() -> bool { ACTIVE.load(Ordering::Relaxed) } + +pub fn setup(app: &AppHandle) -> bool { + if !crate::platform::native_wayland() || !gtk_layer_shell::is_supported() { return false; } + let Some(overlay) = app.get_webview_window("overlay") else { return false; }; + let Ok(window) = overlay.gtk_window() else { return false; }; + window.hide(); + if window.is_realized() { window.unrealize(); } + window.init_layer_shell(); + window.set_namespace("cleanmeter-overlay"); + window.set_layer(Layer::Overlay); + window.set_keyboard_mode(KeyboardMode::None); + window.set_exclusive_zone(-1); + window.set_anchor(Edge::Top, true); + window.set_anchor(Edge::Left, true); + ACTIVE.store(true, Ordering::Relaxed); + log::info!("Wayland layer-shell overlay enabled"); + true +} + +pub fn position(app: &AppHandle, x: i32, y: i32) { + let handle = app.clone(); + let _ = app.run_on_main_thread(move || { + let Some(overlay) = handle.get_webview_window("overlay") else { return; }; + let Ok(window) = overlay.gtk_window() else { return; }; + let Some(display) = gtk::gdk::Display::default() else { return; }; + let selected = handle.state::().get_settings().selected_display_index as usize; + let monitors = overlay.available_monitors().unwrap_or_default(); + let index = if selected < monitors.len() { selected } else { 0 }; + let Some(monitor) = display.monitor(index as i32) else { return; }; + let (left, top, scale) = monitors.get(index) + .map(|m| (m.position().x, m.position().y, m.scale_factor())) + .unwrap_or((0, 0, monitor.scale_factor() as f64)); + window.set_monitor(&monitor); + window.set_layer_shell_margin(Edge::Left, ((x - left) as f64 / scale).round().max(0.0) as i32); + window.set_layer_shell_margin(Edge::Top, ((y - top) as f64 / scale).round().max(0.0) as i32); + }); +} + +pub fn interactive(app: &AppHandle, interactive: bool) { + let handle = app.clone(); + let _ = app.run_on_main_thread(move || { + if let Some(overlay) = handle.get_webview_window("overlay") { + if let Ok(window) = overlay.gtk_window() { + if let Some(surface) = window.window() { + if interactive { surface.input_shape_combine_region(>k::cairo::Region::create_rectangle(>k::cairo::RectangleInt::new(0, 0, surface.width(), surface.height())), 0, 0); } + else { surface.input_shape_combine_region(>k::cairo::Region::create(), 0, 0); } + } + } + } + }); +} diff --git a/tauri-app/src-tauri/src/linux_shortcut_trigger.rs b/tauri-app/src-tauri/src/linux_shortcut_trigger.rs new file mode 100644 index 0000000..2471838 --- /dev/null +++ b/tauri-app/src-tauri/src/linux_shortcut_trigger.rs @@ -0,0 +1,38 @@ +//! Translate the shared W3C/global-hotkey key names to XDG shortcut keysyms. +pub fn trigger(accelerator: &str) -> String { + accelerator.split('+').map(|key| { + match key { + "Ctrl" | "Control" => "CTRL", "Alt" => "ALT", "Shift" => "SHIFT", + "Super" | "Meta" | "Cmd" | "Command" => "LOGO", + "Enter" => "Return", "Space" => "space", "Backspace" => "BackSpace", + "CapsLock" => "Caps_Lock", "NumLock" => "Num_Lock", "ScrollLock" => "Scroll_Lock", + "PrintScreen" => "Print", "PageUp" => "Prior", "PageDown" => "Next", + "ArrowUp" => "Up", "ArrowDown" => "Down", "ArrowLeft" => "Left", "ArrowRight" => "Right", + "Backquote" => "grave", "Backslash" => "backslash", "BracketLeft" => "bracketleft", + "BracketRight" => "bracketright", "Comma" => "comma", "Equal" => "equal", + "Minus" => "minus", "Period" => "period", "Quote" => "apostrophe", + "Semicolon" => "semicolon", "Slash" => "slash", "NumpadAdd" => "KP_Add", + "NumpadDecimal" => "KP_Decimal", "NumpadDivide" => "KP_Divide", "NumpadEnter" => "KP_Enter", + "NumpadEqual" => "KP_Equal", "NumpadMultiply" => "KP_Multiply", "NumpadSubtract" => "KP_Subtract", + other => { + if let Some(letter) = other.strip_prefix("Key") { return letter.to_lowercase(); } + if let Some(digit) = other.strip_prefix("Digit") { return digit.to_owned(); } + if let Some(digit) = other.strip_prefix("Numpad") { return format!("KP_{digit}"); } + other + } + }.to_owned() + }).collect::>().join("+") +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn translates_modifiers_letters_punctuation_navigation_and_numpad() { + for (input, expected) in [("Ctrl+Alt+F10", "CTRL+ALT+F10"), ("Super+KeyA", "LOGO+a"), + ("Shift+Digit1", "SHIFT+1"), ("Alt+ArrowUp", "ALT+Up"), ("Ctrl+Numpad7", "CTRL+KP_7"), + ("Ctrl+Semicolon", "CTRL+semicolon"), ("Alt+Enter", "ALT+Return"), ("", "")] { + assert_eq!(trigger(input), expected); + } + } +} diff --git a/tauri-app/src-tauri/src/linux_shortcuts.rs b/tauri-app/src-tauri/src/linux_shortcuts.rs new file mode 100644 index 0000000..e33d465 --- /dev/null +++ b/tauri-app/src-tauri/src/linux_shortcuts.rs @@ -0,0 +1,93 @@ +//! Desktop-mediated shortcuts for native Wayland. The desktop owns consent. +use ashpd::desktop::global_shortcuts::{GlobalShortcuts, NewShortcut}; +use futures_util::StreamExt; +use std::sync::{OnceLock, Mutex, atomic::{AtomicBool, Ordering}}; +use tauri::{AppHandle, Emitter}; +use tokio::sync::watch; + +static AVAILABLE: AtomicBool = AtomicBool::new(false); +static LABELS: Mutex>> = Mutex::new(None); +pub fn labels() -> std::collections::HashMap { LABELS.lock().ok().and_then(|v| v.clone()).unwrap_or_default() } +static CAPTURING: AtomicBool = AtomicBool::new(false); +static UPDATES: OnceLock> = OnceLock::new(); +pub fn available() -> bool { AVAILABLE.load(Ordering::Relaxed) } +pub fn capturing(value: bool) { CAPTURING.store(value, Ordering::Relaxed); } + +pub fn apply(app: &AppHandle, settings: &crate::types::OverlaySettings) { + let requested = [settings.overlay_shortcut.clone(), settings.recording_shortcut.clone()]; + let tx = UPDATES.get_or_init(|| { + let (tx, mut rx) = watch::channel(requested.clone()); + let app = app.clone(); + tauri::async_runtime::spawn(async move { + loop { + let bindings = rx.borrow_and_update().clone(); + if let Err(error) = session(&app, &bindings, &mut rx).await { + log::warn!("Global Shortcuts portal: {error}"); + if let Ok(mut labels) = LABELS.lock() { *labels = None; } + let _ = app.emit("platform-info", crate::platform::get_platform_info()); + let failed: std::collections::HashMap<_, _> = ["overlayShortcut", "recordingShortcut"] + .into_iter().zip(bindings).filter(|(_, value)| !value.is_empty()).collect(); + let _ = app.emit("shortcut-status", failed); + if rx.changed().await.is_err() { break; } + } + } + }); + tx + }); + tx.send_if_modified(|current| { + if *current == requested { false } else { *current = requested; true } + }); +} + +async fn session(app: &AppHandle, bindings: &[String; 2], updates: &mut watch::Receiver<[String; 2]>) -> Result<(), Box> { + let portal = tokio::time::timeout(std::time::Duration::from_secs(5), GlobalShortcuts::new()).await??; + AVAILABLE.store(true, Ordering::Relaxed); + let _ = app.emit("platform-info", crate::platform::get_platform_info()); + let session = tokio::time::timeout(std::time::Duration::from_secs(10), portal.create_session(Default::default())).await??; + let session_path: String = serde_json::from_value(serde_json::to_value(&session)?)?; + let result = async { + let shortcuts: Vec<_> = ["overlay", "recording"].into_iter() + .zip(["Show/hide overlay", "Start/stop FPS lows recording"]) + .zip(bindings).filter(|(_, trigger)| !trigger.is_empty()) + .map(|((id, description), trigger)| NewShortcut::new(id, description).preferred_trigger(crate::linux_shortcut_trigger::trigger(trigger).as_str())) + .collect(); + let mut activated = portal.receive_activated().await?; + let mut closed = session.receive_closed().await?; + let mut changed = portal.receive_shortcuts_changed().await?; + let response = tokio::select! { + result = tokio::time::timeout(std::time::Duration::from_secs(120), portal.bind_shortcuts(&session, &shortcuts, None, Default::default())) => result??.response()?, + _ = updates.changed() => return Ok(()), + }; + let descriptions: std::collections::HashMap<_, _> = response.shortcuts().iter() + .map(|s| (s.id().to_owned(), s.trigger_description().to_owned())).collect(); + log::info!("Global Shortcuts portal bound {} actions", descriptions.len()); + if let Ok(mut labels) = LABELS.lock() { *labels = Some(descriptions); } + let _ = app.emit("platform-info", crate::platform::get_platform_info()); + let _ = app.emit("shortcut-status", std::collections::HashMap::::new()); + loop { + tokio::select! { + _ = updates.changed() => break, + _ = closed.next() => return Err("desktop closed the shortcut session".into()), + event = changed.next() => { + let Some(event) = event else { return Err("shortcut change stream closed".into()); }; + if event.session_handle().as_str() != session_path { continue; } + let descriptions = event.shortcuts().iter().map(|s| (s.id().to_owned(), s.trigger_description().to_owned())).collect(); + if let Ok(mut labels) = LABELS.lock() { *labels = Some(descriptions); } + let _ = app.emit("platform-info", crate::platform::get_platform_info()); + } + event = activated.next() => { + let Some(event) = event else { return Err("shortcut event stream closed".into()); }; + if event.session_handle().as_str() != session_path || CAPTURING.load(Ordering::Relaxed) { continue; } + match event.shortcut_id() { + "overlay" if !bindings[0].is_empty() => { let _ = app.emit("hotkey", "toggle-overlay"); } + "recording" if !bindings[1].is_empty() => crate::shortcuts::toggle_recording(app), + _ => {} + } + } + } + } + Ok::<_, Box>(()) + }.await; + let _ = session.close().await; + result +} diff --git a/tauri-app/src-tauri/src/main.rs b/tauri-app/src-tauri/src/main.rs index 65ab72f..794ba37 100644 --- a/tauri-app/src-tauri/src/main.rs +++ b/tauri-app/src-tauri/src/main.rs @@ -2,5 +2,30 @@ #![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); + 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") + .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..6fa72b7 --- /dev/null +++ b/tauri-app/src-tauri/src/platform.rs @@ -0,0 +1,63 @@ +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 can_auto_update: bool, + pub shortcut_descriptions: std::collections::HashMap, +} +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 || layer_overlay(), + global_shortcuts: !wayland || portal_shortcuts(), + percentile_lows: cfg!(any(windows, target_os = "linux")), + can_auto_update: cfg!(windows) || (cfg!(target_os = "linux") && std::env::var_os("APPIMAGE").is_some()), + shortcut_descriptions: shortcut_descriptions(), + } +} + +fn layer_overlay() -> bool { + #[cfg(target_os = "linux")] + { crate::linux_overlay::active() } + #[cfg(not(target_os = "linux"))] + { false } +} + +fn portal_shortcuts() -> bool { + #[cfg(target_os = "linux")] + { crate::linux_shortcuts::available() } + #[cfg(not(target_os = "linux"))] + { false } +} + +fn shortcut_descriptions() -> std::collections::HashMap { + #[cfg(target_os = "linux")] + { crate::linux_shortcuts::labels() } + #[cfg(not(target_os = "linux"))] + { std::collections::HashMap::new() } +} diff --git a/tauri-app/src-tauri/src/shortcuts.rs b/tauri-app/src-tauri/src/shortcuts.rs index 00bc482..00e7353 100644 --- a/tauri-app/src-tauri/src/shortcuts.rs +++ b/tauri-app/src-tauri/src/shortcuts.rs @@ -213,6 +213,8 @@ 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) { + #[cfg(target_os = "linux")] + if crate::platform::native_wayland() { crate::linux_shortcuts::apply(app, settings); return; } let mut unavailable = HashMap::<&'static str, String>::new(); for (action, accelerator) in [ (ShortcutAction::ToggleOverlay, &settings.overlay_shortcut), @@ -321,6 +323,8 @@ pub fn apply( /// overlay holds Alt+F1/F2/F3/F9/F10 by default) still never reaches us, and /// nothing here can change that. pub fn set_capturing(app: &AppHandle, capturing: bool, settings: &OverlaySettings) { + #[cfg(target_os = "linux")] + if crate::platform::native_wayland() { crate::linux_shortcuts::capturing(capturing); return; } if !capturing { apply_all(app, settings); return; 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 50d86ed..96031e2 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.19", @@ -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..675edc3 --- /dev/null +++ b/tauri-app/src-tauri/tauri.linux.conf.json @@ -0,0 +1,36 @@ +{ + "bundle": { + "targets": [ + "deb", + "rpm", + "appimage" + ], + "createUpdaterArtifacts": false, + "linux": { + "deb": { + "depends": [ + "libwebkit2gtk-4.1-0", + "libgtk-3-0", + "libgtk-layer-shell0", + "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" + } + } + } + }, + "app": { + "trayIcon": null + } +} 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": "./" + } + } +} From bbe81eec5c4f369a65638eb4ab6176e4ea5fc6e9 Mon Sep 17 00:00:00 2001 From: Saad Abdul Hakeem <152530391+saadah7@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:18:09 +0530 Subject: [PATCH 3/8] Adapt the shared settings and overlay UI for Linux capabilities --- tauri-app/src/App.tsx | 12 +++++--- tauri-app/src/OverlayApp.tsx | 10 +++++-- .../src/components/overlay/CpuSection.tsx | 9 ++++-- .../src/components/overlay/FpsSection.tsx | 18 ++++++----- .../src/components/overlay/GpuSection.tsx | 11 ++++--- .../src/components/settings/LinuxSupport.tsx | 20 +++++++++++++ tauri-app/src/components/settings/TopBar.tsx | 6 ++-- .../components/settings/help/FaqSection.tsx | 22 +++++++++++++- .../settings/settings/SettingsTab.tsx | 21 ++++++++++--- .../components/settings/stats/FpsSection.tsx | 25 ++++++++++------ .../settings/style/PositionGrid.tsx | 3 ++ tauri-app/src/components/ui/ShortcutField.tsx | 4 ++- tauri-app/src/hooks/useHotkey.ts | 3 ++ tauri-app/src/hooks/useSensorData.ts | 11 +++++++ tauri-app/src/lib/tauri.ts | 30 ++++++++++++++++++- tauri-app/src/stores/platform-store.ts | 16 ++++++++++ 16 files changed, 182 insertions(+), 39 deletions(-) create mode 100644 tauri-app/src/components/settings/LinuxSupport.tsx create mode 100644 tauri-app/src/stores/platform-store.ts diff --git a/tauri-app/src/App.tsx b/tauri-app/src/App.tsx index 7666c77..9636a14 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"; @@ -19,6 +20,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); @@ -39,7 +41,7 @@ function MonitoringBanner() { }, []); const verdict = monitoringVerdict({ - hasSensorData: !!sensorData, + hasSensorData: !!sensorData && (!linux || !sidecarStatus.spawnError), sidecar: sidecarStatus, graceExpired, hardware: hardwareStatus, @@ -48,13 +50,13 @@ 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" || hardwareStatus) return; + if (verdict !== "failed" || hardwareStatus || linux) return; checkDotnetRuntime() .then((ok) => { if (!ok) setDotnetMissing(true); }) .catch(() => {}); - }, [verdict, hardwareStatus]); + }, [verdict, hardwareStatus, linux]); if (verdict !== "failed") return null; @@ -71,7 +73,7 @@ function MonitoringBanner() { 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 3925595..32f0ffa 100644 --- a/tauri-app/src/OverlayApp.tsx +++ b/tauri-app/src/OverlayApp.tsx @@ -1,4 +1,5 @@ import { pixelShiftOptions, pixelShiftPosition, shiftAxis } from "@/lib/pixel-shift"; +import { usePlatformStore } from "@/stores/platform-store"; import { useEffect, useRef, useState } from "react"; import { OverlayHud } from "@/components/overlay/OverlayHud"; import { useSensorData } from "@/hooks/useSensorData"; @@ -57,6 +58,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); @@ -120,7 +124,7 @@ export default function OverlayApp() { // HUD pixels — never freezes the rest of the desktop. useEffect(() => { const el = hudRef.current; - if (!el || !settingsReady || monitors.length === 0) return; + if (!el || !settingsReady || (canPosition && monitors.length === 0)) return; const monitor = monitors[settings.selectedDisplayIndex] ?? monitors[0]; const apply = () => { @@ -131,6 +135,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; @@ -196,6 +201,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, @@ -241,7 +247,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/CpuSection.tsx b/tauri-app/src/components/overlay/CpuSection.tsx index da8ca00..7c5a229 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 ?? []; @@ -35,6 +37,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 ( @@ -61,14 +64,14 @@ export function CpuSection({ isHorizontal }: CpuSectionProps) { ) : (
- {formatValue(cpuUsageVal)} + {linux && !findSensorById(sensors, cpuUsage.customReadingId) ? "—" : formatValue(cpuUsageVal)} %
@@ -79,7 +82,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 615861d..38e5101 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; @@ -65,16 +67,16 @@ export function FpsSection({ isHorizontal }: FpsSectionProps) { // PresentMon poller, so there is no third-party naming to guess at. const onePercentLowSensor = findSensorById(sensors, onePercentLow.customReadingId) ?? - sensors.find((s) => s.identifier === "/presentmon/onepercentlow"); + sensors.find((s) => (s.identifier === "/presentmon/onepercentlow" || s.identifier === "/linux/fps/onepercentlow")); const zeroPointOneLowSensor = findSensorById(sensors, zeroPointOnePercentLow.customReadingId) ?? - sensors.find((s) => s.identifier === "/presentmon/zeropointonepercentlow"); + sensors.find((s) => (s.identifier === "/presentmon/zeropointonepercentlow" || s.identifier === "/linux/fps/zeropointonepercentlow")); const fpsValue = Math.round(fpsSensor?.value ?? 0); 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 @@ -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, @@ -163,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 868e475..fc9b0a6 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"; @@ -12,6 +13,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 ?? []; @@ -84,6 +86,7 @@ export function GpuSection({ isHorizontal }: GpuSectionProps) { : vramLoadVal; const temp = formatTemperature(gpuTempVal, settings.temperatureUnit); + if (linux && !findSensorById(sensors, gpuTemp.customReadingId)) temp.label = "—"; return ( @@ -110,14 +113,14 @@ export function GpuSection({ isHorizontal }: GpuSectionProps) { ) : (
- {formatValue(gpuUsageVal)} + {linux && !findSensorById(sensors, gpuUsage.customReadingId) ? "—" : formatValue(gpuUsageVal)} %
@@ -132,14 +135,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" : "%"}
diff --git a/tauri-app/src/components/settings/LinuxSupport.tsx b/tauri-app/src/components/settings/LinuxSupport.tsx new file mode 100644 index 0000000..3471f93 --- /dev/null +++ b/tauri-app/src/components/settings/LinuxSupport.tsx @@ -0,0 +1,20 @@ +import { quitApp } from "@/lib/tauri"; +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 ( + <> + + + + ); +} diff --git a/tauri-app/src/components/settings/TopBar.tsx b/tauri-app/src/components/settings/TopBar.tsx index dad42a2..3b7f9bc 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"; @@ -101,6 +102,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. @@ -178,8 +180,8 @@ export function TopBar() { appWindowPromise.then((w) => w.hide())} - title="Close to tray" + onClick={() => appWindowPromise.then((w) => linux ? w.minimize() : w.hide())} + title={linux ? "Minimize" : "Close to tray"} className="hover:bg-destructive hover:text-destructive-foreground" > diff --git a/tauri-app/src/components/settings/help/FaqSection.tsx b/tauri-app/src/components/settings/help/FaqSection.tsx index c088955..4a18eb7 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,29 @@ 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. In Steam launch options, enter:\ncleanmeter-run %command%\n\nFor native games, run cleanmeter-run followed by the game command. With an AppImage, use its full path followed by --run and the game command.", + }, + { + question: "How do FPS lows and recording work?", + answer: "Live lows cover the last 10 seconds and need five seconds to warm up. The recording shortcut starts a run, freezes the results, then returns to live readings. Change the shortcut in Settings.", + }, + { + question: "Why is a reading unavailable?", + answer: "Available readings depend on your hardware and driver. A dash means the reading is unavailable.", + }, + { + question: "What are the current limitations?", + answer: "Fullscreen overlay visibility depends on your desktop. Wayland overlay positioning requires layer-shell support; other desktops use a separate monitor window. Global shortcuts require your desktop?s Global Shortcuts portal. Steam Deck Game Mode support is still being validated.", + }, + ] : 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 3b88539..e09e5aa 100644 --- a/tauri-app/src/components/settings/settings/SettingsTab.tsx +++ b/tauri-app/src/components/settings/settings/SettingsTab.tsx @@ -1,5 +1,7 @@ +import { LinuxSupport } from "../LinuxSupport"; import { settingsActions } from "@/lib/settings-actions"; import { playSound, beginSoundAction } from "@/lib/sound-effects"; +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"; @@ -51,6 +53,7 @@ function SectionCard({ } function GeneralSection() { + const linux = usePlatformStore((s) => s.platform.os === "linux"); const startMinimized = useSettingsStore((s) => s.preferences.startMinimized); const soundEffects = useSettingsStore((s) => s.preferences.soundEffects); const preferencesLoaded = useSettingsStore((s) => s.preferencesLoaded); @@ -93,7 +96,7 @@ function GeneralSection() { disabled={autoStartPending} onCheckedChange={(v) => handleStartWithWindows(v === true)} /> - Start with windows + {linux ? "Start at login" : "Start with Windows"}

+ ); } @@ -175,31 +179,35 @@ function GeneralSection() { * No grey panel: the rows sit directly on the card. */ function ShortcutsSection() { + const platform = usePlatformStore((s) => s.platform); const settings = useSettingsStore((s) => s.settings); const updateSettings = settingsActions.updateSettings; const overlayAccelerator = settings.overlayShortcut ?? OVERLAY_SHORTCUT_DEFAULT; const recordingAccelerator = settings.recordingShortcut ?? RECORDING_SHORTCUT_DEFAULT; + if (!platform.globalShortcuts) return

Your desktop does not provide global shortcuts. Use the visibility control in General.

; return (
updateSettings({ overlayShortcut })} - conflictsWith={{ "Start/stop FPS lows recording": recordingAccelerator }} + conflictsWith={platform.percentileLows ? { "Start/stop FPS lows recording": recordingAccelerator } : {}} className="gap-[var(--spacingL)]" /> - updateSettings({ recordingShortcut })} conflictsWith={{ "Show/hide overlay": overlayAccelerator }} className="gap-[var(--spacingL)]" - /> + />}
); @@ -416,10 +424,15 @@ const DISCORD_INVITE_URL = "https://discord.gg/SCgXtTMNvJ"; // Triggers an in-app update check and reflects the updater status in its label. // The actual "download & install" happens from the floating UpdateBanner. function UpdatesButton() { + const platform = usePlatformStore((s) => s.platform); const status = useUpdaterStore((s) => s.status); const dismissed = useUpdaterStore((s) => s.dismissed); const check = useUpdaterStore((s) => s.check); + if (platform.os === "linux" && !platform.canAutoUpdate) { + return } label="Download Linux updates" href="https://github.com/SupaStellar/Cleanmeter/releases" />; + } + const busy = status === "checking" || status === "downloading" || diff --git a/tauri-app/src/components/settings/stats/FpsSection.tsx b/tauri-app/src/components/settings/stats/FpsSection.tsx index c788d87..d32a4ec 100644 --- a/tauri-app/src/components/settings/stats/FpsSection.tsx +++ b/tauri-app/src/components/settings/stats/FpsSection.tsx @@ -1,4 +1,5 @@ import { settingsActions } from "@/lib/settings-actions"; +import { usePlatformStore } from "@/stores/platform-store"; import { useRef } from "react"; import { Checkbox } from "@/components/shadcn/checkbox"; import { @@ -26,11 +27,13 @@ const FPS_READINGS = [ type FpsReading = (typeof FPS_READINGS)[number]; export function FpsSection() { + const platform = usePlatformStore((s) => s.platform); + const readings = FPS_READINGS.filter((key) => platform.percentileLows || key === "framerate" || key === "frametime"); const settings = useSettingsStore((s) => s.settings); const updateSensor = settingsActions.updateSensor; const presentMonApps = useSettingsStore((s) => s.presentMonApps); const { framerate, frametime, onePercentLow, zeroPointOnePercentLow } = settings.sensors; - const anyEnabled = FPS_READINGS.some((key) => settings.sensors[key].isEnabled); + const anyEnabled = readings.some((key) => settings.sensors[key].isEnabled); const prevState = useRef | null>(null); // `|| ""` guards a settings.json written before targetAppName existed, where // the field is absent at runtime whatever the type says. @@ -46,16 +49,16 @@ export function FpsSection() { onToggle={(enabled) => { if (!enabled) { prevState.current = Object.fromEntries( - FPS_READINGS.map((key) => [key, settings.sensors[key].isEnabled]), + readings.map((key) => [key, settings.sensors[key].isEnabled]), ) as Record; - FPS_READINGS.forEach((key) => updateSensor(key, { isEnabled: false })); + readings.forEach((key) => updateSensor(key, { isEnabled: false })); } else { const prev = prevState.current; // With nothing stored (the card was already off at launch), fall back // to each reading's shipped default rather than switching everything // on: the two percentile lows default to off, and a blanket `true` // here would enable readings the user never asked for. - FPS_READINGS.forEach((key) => + readings.forEach((key) => updateSensor(key, { isEnabled: prev ? prev[key] : DEFAULT_SETTINGS.sensors[key].isEnabled, }), @@ -86,14 +89,16 @@ export function FpsSection() { into two rows that had to stay in sync. */}