diff --git a/README.md b/README.md index 50baceb..f129c09 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ The app lists other NZXT devices as "no driver yet". If you have one, *Settings The app checks for a new release each time it starts and shows *Update available* under the service in the sidebar. *Update* there, or in *Settings → About*, installs it. Uninstall camless from *Settings → Apps* in Windows. It keeps your settings in `%APPDATA%\camless` unless you choose to delete them. -CPU temperature also needs [PawnIO](https://pawnio.eu) and its signed module for your CPU in `%LOCALAPPDATA%\Programs\camless`: `IntelMSR.bin` on Intel, `AMDFamily17.bin` on AMD Ryzen. Both are in the zip of the latest [PawnIO.Modules release](https://github.com/namazso/PawnIO.Modules/releases/latest). Without them, curves on CPU temperature hold the failsafe duty. The Kraken's liquid temperature needs none of this, so new curves use it by default. +CPU temperature also needs [PawnIO](https://pawnio.eu) and its signed module for your CPU in `%LOCALAPPDATA%\Programs\camless`: `IntelMSR.bin` on Intel, `AMDFamily17.bin` on AMD Ryzen. Both are in the zip of the latest [PawnIO.Modules release](https://github.com/namazso/PawnIO.Modules/releases/latest). Without them, curves on CPU temperature hold the failsafe duty. When they are missing, the app says so when it starts, with the file this CPU needs, and *Settings → Software from elsewhere* shows what camless found. CPU temperature starts within seconds of putting them in place. The Kraken's liquid temperature needs none of this, so new curves use it by default. GPU temperature, load and power come from NVIDIA's driver (NVML) on an NVIDIA card. Any other card, such as AMD's or Intel's, gives the temperature and load that Task Manager shows, which Windows keeps for every card. An AMD card's power comes from AMD's driver (ADL), from the log the driver keeps, as LibreHardwareMonitor reads it, or else from a reading of the moment; an Intel card has none. If an AMD card shows no power, or power that jumps, `camless report` says which way it was read and what it read over the last minute. diff --git a/core/src/status.rs b/core/src/status.rs index ab5b50f..f6a7076 100644 --- a/core/src/status.rs +++ b/core/src/status.rs @@ -43,6 +43,39 @@ pub struct ServiceInfo { /// Why games have no frame rates, when they have none. #[serde(default)] pub fps_error: Option, + /// Software camless uses that Windows or the Linux desktop may not come with, + /// and whether this PC has it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub requirements: Vec, +} + +/// A program or file camless needs from elsewhere for one thing it does. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)] +pub struct Requirement { + /// Stable, for the app to remember that it asked about it: `pawnio`. + pub id: String, + pub name: String, + /// What camless does with it: "CPU temperature and power". + pub used_for: String, + /// What camless found that needs it, such as the CPU's maker; none when nothing + /// on this PC needs it now. + pub needed_because: Option, + pub installed: bool, + /// How to get it, in a sentence or two. + pub how: String, + /// A page the app opens for it, by a name the app knows: `pawnio`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub link: Option, + /// The file goes in camless's own folder, which the app can open. + #[serde(default)] + pub in_app_folder: bool, +} + +impl Requirement { + /// Needed on this PC, and not there. + pub fn missing(&self) -> bool { + self.needed_because.is_some() && !self.installed + } } /// One way of reading the GPU's power, and what it read over the last minute. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 8bb2533..da5020f 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -8,6 +8,16 @@ The app starts the service if it is not running. On Windows, it asks for adminis *Settings → Service → Start as administrator without asking* stops the prompts. It is off until you turn it on, and Windows asks once then. The app sets up a scheduled task, `camless ()`, that runs `camless-gui.exe --start-service` with your full rights, and from then on starts the service through it, also at logon with *Start with Windows*. The task has no trigger of its own. You may run and delete it without administrator rights, so turning the switch off and uninstalling need none. The trade-off: camless sits in a folder you can write to, so any program you run could replace it and use the task to get administrator rights without a prompt. On a standard account the switch refuses: a task that runs as you could not give the service administrator rights. +## Software from elsewhere + +Some of what camless does needs software that Windows or a Linux desktop may not come with. The service checks for it every 5 seconds and lists it in its status. *Settings → Software from elsewhere* shows each one, what it is for, and whether this PC needs and has it: +- **PawnIO**, on Windows: the driver that lets a program read the CPU's sensors. FanControl and LibreHardwareMonitor install the same one. Found at `C:\Program Files\PawnIO\PawnIOLib.dll`. +- **`IntelMSR.bin` or `AMDFamily17.bin`**, on Windows: PawnIO's signed module for this CPU's maker, which the service reads from its own folder (or `pawnio_module` in `camless.toml`). The CPU's maker comes from the registry, so the app says which file this PC needs. +- **A Chromium browser**, needed only while an LCD shows a [web page](#web-pages-on-the-lcd). +- **curl**, on Linux, for [updates](#installs-and-updates). The app checks this one itself. + +When something this PC needs is missing, the app opens a dialog once each time it starts, with what camless found that needs it and how to get it. *Don't ask again* stops the dialog for that item; Settings still lists it. When CPU temperature is off and the list changes, the service tries PawnIO again every 5 seconds for 30 seconds, while the setup starts the driver, so CPU temperature starts once PawnIO and its module are in place, without a restart. Administrator rights are still needed on top. `camless report` names what is missing, without the folders. + ## Fan control - **Curves a device can run by itself are stored on it.** This means a fixed duty, or a graph on the device's own sensor (a Kraken's liquid temperature). The Kraken keeps running them if camless stops. The fan's offset and limits are folded in. Smoothing and hysteresis are host-only. diff --git a/gui/src/backend.rs b/gui/src/backend.rs index 88541a6..1a3730c 100644 --- a/gui/src/backend.rs +++ b/gui/src/backend.rs @@ -135,7 +135,7 @@ impl Backend { ("POST", "update/check") => update::check(update::channel(&self.path())).map(|_| json!({})).map_err(Refused::from), ("POST", "update/install") => self.install_update(), ("POST", "update/notes") => self.release_notes(), - ("POST", "open-folder") => self.open_folder(), + ("POST", "open-folder") => self.open_folder(body), ("POST", "report") => report::start(&self.path()).map(|_| json!(report::state())).map_err(Refused::from), ("GET", "report") => Ok(json!(report::state())), ("POST", "report/issue") => self.report_issue(body), @@ -212,6 +212,8 @@ impl Backend { "admin_task_error": task.error, "update": update::state(), "sandbox": self.sandbox, + // The service lists what it needs; these are the app's own. + "requirements": app_requirements(), }) } @@ -447,20 +449,41 @@ impl Backend { Ok(json!({})) } - fn open_folder(&self) -> Answer { + /// The config's folder, or with `{"app": true}` camless's own, where PawnIO's + /// module goes. + fn open_folder(&self, body: &[u8]) -> Answer { + #[derive(Deserialize)] + struct Which { + #[serde(default)] + app: bool, + } + let Which { app } = parse(body)?; if self.sandbox { bail_refused("the sandbox does not open Explorer")?; } - let path = self.path(); - let dir = path.parent().filter(|d| d.exists()).ok_or_else(|| anyhow!("{} has no folder yet", path.display()))?; + let dir = if app { + let exe = std::env::current_exe().context("finding camless's folder")?; + exe.parent().map(Path::to_path_buf).ok_or_else(|| anyhow!("{} has no folder", exe.display()))? + } else { + let path = self.path(); + path.parent().filter(|d| d.exists()).map(Path::to_path_buf).ok_or_else(|| anyhow!("{} has no folder yet", path.display()))? + }; #[cfg(windows)] - std::process::Command::new("explorer.exe").arg(dir).spawn().context("starting Explorer")?; + std::process::Command::new("explorer.exe").arg(&dir).spawn().context("starting Explorer")?; #[cfg(not(windows))] report::open_url(&dir.to_string_lossy())?; Ok(json!({})) } } +/// What the app itself needs from elsewhere: curl for updates, on Linux. +fn app_requirements() -> Vec { + #[cfg(target_os = "linux")] + return vec![crate::http::requirement()]; + #[cfg(not(target_os = "linux"))] + Vec::new() +} + #[derive(Deserialize)] struct Name { name: String, @@ -470,6 +493,9 @@ struct Name { fn link(name: &str) -> Option<&'static str> { Some(match name { "krakendial" => "https://github.com/kleju13/krakendial", + // What the service lists as missing names these. + "pawnio" => "https://pawnio.eu", + "pawnio-modules" => "https://github.com/namazso/PawnIO.Modules/releases/latest", _ => return None, }) } @@ -658,6 +684,11 @@ mod tests { let (b, _) = fixture("camless-gui-links"); assert_eq!(call(&b, "POST", "/api/open-link", json!({ "name": "https://example.com" })).0, 400); assert_eq!(call(&b, "POST", "/api/open-link", json!({ "name": "krakendial" })).0, 409, "the sandbox opens no browser"); + // src/requirements.rs links to these. + for name in ["pawnio", "pawnio-modules"] { + assert!(link(name).is_some_and(|u| u.starts_with("https://")), "{name}"); + } + assert_eq!(call(&b, "POST", "/api/open-folder", json!({ "app": true })).0, 409, "the sandbox opens no folder"); } #[test] diff --git a/gui/src/http_curl.rs b/gui/src/http_curl.rs index 8758834..0d1fd13 100644 --- a/gui/src/http_curl.rs +++ b/gui/src/http_curl.rs @@ -12,6 +12,21 @@ const AGENT: &str = concat!("camless/", env!("CARGO_PKG_VERSION")); /// Larger answers are not a release of camless. const MAX_BODY: usize = 64 << 20; +/// curl, which not every desktop comes with, and whether it is on the PATH. +pub fn requirement() -> camless_core::status::Requirement { + let installed = std::env::var_os("PATH").is_some_and(|p| std::env::split_paths(&p).any(|d| d.join("curl").is_file())); + camless_core::status::Requirement { + id: "curl".into(), + name: "curl".into(), + used_for: "Updates".into(), + needed_because: Some("The app checks GitHub for a new camless and downloads it with curl".into()), + installed, + how: "Install the curl package from your distribution, such as sudo apt install curl.".into(), + link: None, + in_app_folder: false, + } +} + /// The body of `url`, which must be https, if it answers 200. pub fn get(url: &str) -> Result> { let rest = url.strip_prefix("https://").with_context(|| format!("{url} is not an https URL"))?; diff --git a/gui/ui/app.css b/gui/ui/app.css index 8991135..bc8b889 100644 --- a/gui/ui/app.css +++ b/gui/ui/app.css @@ -156,6 +156,7 @@ body.light { background: #f7f6fa; } .cam-status { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 500; color: var(--t3); } .cam-status::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--green); } .cam-status.off::before { background: var(--t4); } +.cam-status.warn::before { background: var(--amber); } .cam-alert { position: sticky; top: 0; z-index: 5; display: flex; align-items: flex-start; gap: 10px; margin: 0 0 14px; padding: 9px 12px; border-radius: var(--radius); background: var(--alert-bg); border: 1px solid rgba(255, 2, 45, .45); color: var(--t1); font-size: 13px; backdrop-filter: blur(10px); } .cam-alert svg.i { color: var(--alert); width: 18px; height: 18px; margin-top: 1px; } diff --git a/gui/ui/app.js b/gui/ui/app.js index 6ad241d..e570aa5 100644 --- a/gui/ui/app.js +++ b/gui/ui/app.js @@ -323,6 +323,7 @@ nav.appendChild(serviceBadge()); nav.appendChild(updateBadge()); nav.appendChild(verifyBadge()); + S.on('state', askRequirements); const navItems = () => nav.querySelectorAll('a[data-id]').forEach((a) => { a.hidden = !navShown(a.dataset.id); }); S.on('config', navItems); navItems(); @@ -427,6 +428,90 @@ return el; } + /* Software from elsewhere that camless needs: PawnIO and the module for this CPU for + CPU temperature on Windows, a browser for web pages on the LCD, curl for updates on + Linux. The service lists its own and checks again every few seconds; the app adds + what it needs itself. */ + const requirements = () => [].concat((S.status && S.status.service && S.status.service.requirements) || [], (S.server && S.server.requirements) || []); + const missing = (r) => !!r.needed_because && !r.installed; + const askKey = (r) => `${r.id}:${r.name}`; + const lowerFirst = (t) => (/^[A-Z][a-z]/.test(t) ? t[0].toLowerCase() + t.slice(1) : t); + let askedRequirements = false; + + function requirementStatus(r) { + const [text, tone] = r.installed ? ['Installed', ''] : r.needed_because ? ['Missing', ' warn'] : ['Not installed', ' off']; + return h(`${text}`); + } + + // Get it opens the page the service names, through the app's own list of links. + function requirementButtons(r) { + const out = []; + if (r.installed) return out; + if (r.link) out.push(button('Get it', { small: true, onClick: () => act('open-link', { name: r.link }) })); + if (r.in_app_folder && !S.server.sandbox) out.push(button('Open folder', { small: true, onClick: () => act('open-folder', { app: true }) })); + return out; + } + + function requirementHint(r) { + const why = r.needed_because ? `${esc(sentence(r.needed_because))}` : 'Nothing on this PC needs it now.'; + return `For ${esc(lowerFirst(r.used_for))}. ${why}${r.installed ? '' : ` ${esc(r.how)}`}`; + } + + const cpuNote = (list) => (list.some((r) => r.id.startsWith('pawnio')) + ? `Until then, curves on CPU temperature hold the failsafe speed, ${failsafe()}%. The Kraken’s liquid temperature needs none of this. camless looks again every few seconds and starts reading the CPU once everything is in place, without a restart.` + : 'camless looks again every few seconds, so there is nothing to restart.'); + + // Once each time the app starts, while something this PC needs is missing, unless the + // person said not to ask about it again. + function requirementsDialog(list) { + modal({ + title: list.length > 1 ? 'camless needs software from elsewhere' : `camless needs ${list[0].name}`, + render(body) { + body.appendChild(h(`

camless found something on this PC that needs ${list.length > 1 ? 'these, and they are' : 'this, and it is'} not installed.

`)); + const rows = h('
'); + for (const r of list) rows.appendChild(row(r.name, requirementHint(r), requirementButtons(r))); + body.appendChild(rows); + body.appendChild(Object.assign(h('

'), { textContent: `${cpuNote(list)} Settings lists all of it under Software from elsewhere.` })); + }, + actions: [ + { label: 'Don’t ask again', onClick: () => { K.setPref('requirementsAsked', [...new Set([...(K.prefs.requirementsAsked || []), ...list.map(askKey)])]); toast('camless will not ask about it again. Settings still lists it.'); } }, + { label: 'Later', primary: true }, + ], + }); + } + + // Only once the service answers, so the dialog has the whole list. + function askRequirements() { + if (askedRequirements || !S.status || busy()) return; + const done = K.prefs.requirementsAsked || []; + const list = requirements().filter((r) => missing(r) && !done.includes(askKey(r))); + if (!list.length) return; + askedRequirements = true; + requirementsDialog(list); + } + + // The Settings panel: every program and file camless uses from elsewhere, read again + // with each state. + function requirementsPanel(host) { + const s = K.section(host, 'Software from elsewhere'); + const p = h('
'); + s.appendChild(p); + s.appendChild(Object.assign(h('

'), { textContent: 'What camless uses that Windows or a Linux desktop may not come with. camless looks again every few seconds.' })); + let key = null; + const upd = () => { + const list = requirements(); + const k = JSON.stringify([list, !!S.status]); + if (k === key) return; + key = k; + p.replaceChildren(); + for (const r of list) p.appendChild(row(r.name, requirementHint(r), [...requirementButtons(r), requirementStatus(r)])); + if (!S.status) p.appendChild(row('The service is not running', 'Start it to see what it needs, such as PawnIO for CPU temperature on Windows.', null)); + }; + track(S.on('state', upd)); + upd(); + return s; + } + function go() { built = layoutKey(); let id = decodeURIComponent(location.hash.slice(1)) || K.prefs.page || 'cooling'; @@ -3566,6 +3651,7 @@ track(S.on('state', () => { if (!autoT.dataset.busy) autoT.set(S.server.autostart); autoRow.hint(autoHint()); })); panel('Service', [serviceRow(), autoRow, linux() ? null : adminRow()]); + requirementsPanel(host); const general = panel('General', [ row('Temperature display', null, choice({ options: [{ value: 'c', label: 'Celsius' }, { value: 'f', label: 'Fahrenheit' }], value: K.prefs.unit, label: 'Temperature display', onChange: (v) => K.setPref('unit', v) })), diff --git a/src/daemon.rs b/src/daemon.rs index 4c7cdb8..65b0d8a 100644 --- a/src/daemon.rs +++ b/src/daemon.rs @@ -16,7 +16,7 @@ use crate::web; use camless_core::config::{self, Config, Lcd, LcdMode}; use camless_core::curve::{DeviceCurve, Duty, Engine}; use camless_core::lighting::Light; -use camless_core::status::{CurveValue, Device, FanValue, Sensor, ServiceInfo, Status, Unit, Unsupported, WebState}; +use camless_core::status::{CurveValue, Device, FanValue, Requirement, Sensor, ServiceInfo, Status, Unit, Unsupported, WebState}; use hidapi::HidApi; use std::collections::{HashMap, HashSet}; use std::path::PathBuf; @@ -26,6 +26,11 @@ use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; const RESCAN_EVERY: Duration = Duration::from_secs(5); +/// How often the service looks for software from elsewhere it needs: a few file +/// checks. +const REQUIREMENTS_EVERY: Duration = Duration::from_secs(5); +/// Tries at CPU temperature after the list changed, one per check: 30 s. +const CPU_RETRIES: u8 = 6; /// Duties are sent again now and then, in case a device reset without a USB event. const RESEND_EVERY: Duration = Duration::from_secs(60); /// An LCD in frames or web mode goes back to its own screen when frames stop for @@ -155,6 +160,11 @@ pub struct Daemon { history: Arc>, /// The game in front and its frame rate. games: Games, + /// Software from elsewhere this PC needs, as last checked. + requirements: Vec, + next_requirements: Instant, + /// Tries at CPU temperature left since the list last changed. + cpu_retries: u8, } struct Rendering { @@ -199,6 +209,9 @@ impl Daemon { pages: HashMap::new(), history, games, + requirements: Vec::new(), + next_requirements: Instant::now(), + cpu_retries: 0, }; let mut daemon = daemon; daemon.warn_missing_sensors(); @@ -261,6 +274,7 @@ impl Daemon { let dt = self.last_tick.map_or(interval, |t| now.duration_since(t).as_secs_f32()).min(5.0); self.last_tick = Some(now); self.reload(); + self.check_requirements(); self.scan(); self.open_devices(); for i in 0..self.slots.len() { @@ -299,6 +313,42 @@ impl Daemon { self.publish(readings, sensors); } + /// Looks again for what camless needs from elsewhere. When something changed and + /// CPU temperature is off, it tries PawnIO again for a while: the setup may still be + /// starting the driver when its files appear. + fn check_requirements(&mut self) { + let now = Instant::now(); + if now < self.next_requirements { + return; + } + self.next_requirements = now + REQUIREMENTS_EVERY; + let found = crate::requirements::check(&self.cfg); + if found != self.requirements { + let first = self.requirements.is_empty(); + self.requirements = found; + for r in self.requirements.iter().filter(|r| r.missing()) { + self.log(&format!("missing {}, for {}", r.name, r.used_for)); + } + if !first { + self.cpu_retries = CPU_RETRIES; + } + } + if self.cpu_retries == 0 || self.sensors.has_cpu_temp() { + self.cpu_retries = 0; + return; + } + self.cpu_retries -= 1; + if self.sensors.retry_cpu(crate::sensors::pawnio_module(self.cfg.pawnio_module.as_ref())) { + self.cpu_retries = 0; + self.log("cpu temperature on"); + self.warn_missing_sensors(); + } else if self.cpu_retries == 0 { + if let Some(e) = &self.sensors.cpu_error { + self.log(&format!("cpu temperature still off: {e}")); + } + } + } + /// Every sensor, the speed and duty of every fan on a device that answers, and the /// frame rate of the game in front. fn record(&self, sensors: &[Sensor], fps: Option) { @@ -822,6 +872,7 @@ impl Daemon { gpu_power_error: self.sensors.gpu_power_error.clone(), gpu_power_sources: self.sensors.gpu_power_sources(), fps_error: if self.cfg.games.enabled { self.games.error() } else { None }, + requirements: self.requirements.clone(), }), game: self.games.now(), }; diff --git a/src/main.rs b/src/main.rs index 64f8bbe..e96f74d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ mod history; mod mcp; mod q565; mod report; +mod requirements; mod sensors; mod web; @@ -177,28 +178,8 @@ fn main() -> Result<()> { } } -#[cfg(windows)] -fn beside_exe(name: &str) -> PathBuf { - std::env::current_exe() - .ok() - .and_then(|p| p.parent().map(|d| d.join(name))) - .unwrap_or_else(|| PathBuf::from(name)) -} - -#[cfg(windows)] -fn pawnio_module(configured: Option<&PathBuf>) -> std::result::Result, String> { - let path = configured.cloned().unwrap_or_else(|| beside_exe(sensors::pawnio_module_file())); - std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display())) -} - -/// PawnIO is Windows only; Linux reads CPU temperature from hwmon. -#[cfg(not(windows))] -fn pawnio_module(_configured: Option<&PathBuf>) -> std::result::Result, String> { - Err("PawnIO is for Windows".into()) -} - fn sensors() -> Result<()> { - let mut s = sensors::Sensors::open(pawnio_module(None)); + let mut s = sensors::Sensors::open(sensors::pawnio_module(None)); s.read(); std::thread::sleep(Duration::from_secs(1)); let r = s.read(); @@ -414,7 +395,7 @@ fn status(config: &Path) -> Result<()> { for u in &unsupported { println!("{:04x}:{:04x} {}: no driver yet (see CONTRIBUTING.md)", u.vid, u.pid, u.product); } - let mut s = sensors::Sensors::open(pawnio_module(None)); + let mut s = sensors::Sensors::open(sensors::pawnio_module(None)); s.read(); std::thread::sleep(Duration::from_millis(500)); for x in s.read().list(s.gpu_name.is_some()) { @@ -499,7 +480,7 @@ fn run(path: PathBuf, verbose: bool, demo: bool, limit: Option) -> Res .context("starting the local API")?; eprintln!("camless: api on http://{}", cfg.api.listen); } - let sensors = sensors::Sensors::open(pawnio_module(cfg.pawnio_module.as_ref())); + let sensors = sensors::Sensors::open(sensors::pawnio_module(cfg.pawnio_module.as_ref())); if demo { eprintln!("camless: demo mode, simulated devices only"); } diff --git a/src/report.rs b/src/report.rs index d46a68d..02075a7 100644 --- a/src/report.rs +++ b/src/report.rs @@ -369,6 +369,11 @@ fn render(f: &Facts) -> String { } } let _ = writeln!(s, "{}", parts.join(", ")); + // Names only: how to get them names folders with the user's name. + let missing: Vec = st.service.iter().flat_map(|sv| &sv.requirements).filter(|r| r.missing()).map(|r| format!("{} ({})", r.name, r.used_for)).collect(); + if !missing.is_empty() { + let _ = writeln!(s, "Missing: {}", missing.join(", ")); + } if let Some(sv) = st.service.as_ref().filter(|sv| !sv.gpu_power_sources.is_empty()) { let _ = writeln!(s, "\n**GPU power sources** (the last minute, in watts)"); for p in &sv.gpu_power_sources { @@ -628,6 +633,7 @@ fn scrub_facts(f: &mut Facts) { if let Some(sv) = &mut st.service { sv.cpu_sensor_error.iter_mut().chain(sv.gpu_sensor_error.iter_mut()).chain(sv.gpu_power_error.iter_mut()).for_each(clean); sv.gpu_power_sources.iter_mut().flat_map(|p| p.error.iter_mut().chain(p.detail.iter_mut())).for_each(clean); + sv.requirements.iter_mut().flat_map(|r| [&mut r.name, &mut r.used_for]).for_each(clean); } } Err(e) => clean(e), @@ -939,6 +945,26 @@ about the table" assert_eq!(title(&f), "Hardware: Kraken Elite (2024)"); } + #[test] + fn names_what_is_missing_without_where_it_goes() { + let mut f = facts(); + assert!(!render(&f).contains("Missing:")); + let Ok(st) = &mut f.service else { unreachable!() }; + let req = |name: &str, needed: bool, installed| camless_core::status::Requirement { + id: name.into(), + name: name.into(), + used_for: "CPU temperature and power".into(), + needed_because: needed.then(|| "camless found an Intel CPU".into()), + installed, + how: r"Copy it into C:\Users\Example\AppData\Local\Programs\camless.".into(), + ..Default::default() + }; + st.service.as_mut().unwrap().requirements = vec![req("PawnIO", true, true), req("IntelMSR.bin", true, false), req("Chromium", false, false)]; + let text = render(&f); + assert!(text.contains("\nMissing: IntelMSR.bin (CPU temperature and power)\n"), "{text}"); + assert!(!text.contains("AppData")); + } + #[test] fn says_whether_there_are_gpu_readings_and_why_not() { let mut f = facts(); diff --git a/src/requirements.rs b/src/requirements.rs new file mode 100644 index 0000000..ee92279 --- /dev/null +++ b/src/requirements.rs @@ -0,0 +1,145 @@ +//! Software camless uses that Windows or a Linux desktop may not come with: what it +//! is for, whether something on this PC needs it, and whether it is there. The +//! service checks again every few seconds, so the app sees an install without a +//! restart, and CPU temperature starts once PawnIO and its module are in place. + +use camless_core::config::{Config, LcdMode}; +use camless_core::status::Requirement; +#[cfg(windows)] +use std::path::Path; + +/// What camless needs from elsewhere on this PC, in the order the app lists it. +pub fn check(cfg: &Config) -> Vec { + let web_lcd = cfg.lcds.iter().any(|l| l.mode == LcdMode::Web); + let browser = browser(web_lcd, crate::web::browser_name().is_some()); + #[cfg(windows)] + { + let module = crate::sensors::pawnio_module_path(cfg.pawnio_module.as_ref()); + let cpu = crate::sensors::cpu_name(); + vec![ + pawnio(Path::new(crate::sensors::PAWNIO_LIB).is_file()), + pawnio_module( + crate::sensors::cpu_maker(), + cpu.as_deref(), + crate::sensors::pawnio_module_file(), + module.is_file(), + cfg.pawnio_module.as_deref(), + ), + browser, + ] + } + #[cfg(not(windows))] + vec![browser] +} + +/// The driver Windows needs before a program can read the CPU's temperature. +/// LibreHardwareMonitor and FanControl install the same one. +#[cfg_attr(not(windows), allow(dead_code))] +fn pawnio(installed: bool) -> Requirement { + Requirement { + id: "pawnio".into(), + name: "PawnIO".into(), + used_for: "CPU temperature and power".into(), + needed_because: Some("Windows lets programs read the CPU’s sensors only through a driver".into()), + installed, + how: "Install it with the setup from pawnio.eu. FanControl and LibreHardwareMonitor use the same driver, so with one of them it is already there.".into(), + link: Some("pawnio".into()), + in_app_folder: false, + } +} + +/// The signed module PawnIO runs for this maker's CPU. `configured` is the path in +/// camless.toml, when it names one. +#[cfg_attr(not(windows), allow(dead_code))] +fn pawnio_module(maker: &str, cpu: Option<&str>, file: &str, installed: bool, configured: Option<&std::path::Path>) -> Requirement { + let found = match cpu { + Some(name) if !name.is_empty() => format!("camless found an {maker} CPU, {name}"), + _ => format!("camless found an {maker} CPU"), + }; + let how = match configured { + Some(path) => format!( + "It is in the zip of the latest PawnIO.Modules release. camless.toml says to read it from {}.", + path.display() + ), + None => format!("It is in the zip of the latest PawnIO.Modules release. Copy {file} from it into camless’s folder."), + }; + Requirement { + id: "pawnio-module".into(), + name: file.into(), + used_for: format!("CPU temperature and power on {maker} CPUs, through PawnIO"), + needed_because: Some(found), + installed, + how, + link: Some("pawnio-modules".into()), + in_app_folder: configured.is_none(), + } +} + +/// A Chromium browser, which renders the web pages camless shows on an LCD. +fn browser(needed: bool, installed: bool) -> Requirement { + let (name, how) = if cfg!(windows) { + ("Microsoft Edge or Google Chrome", "Windows comes with Microsoft Edge. If it was removed, install Edge or Chrome again.") + } else { + ("Google Chrome, Chromium, Microsoft Edge or Brave", "Install one from your distribution’s packages or from the browser’s site.") + }; + Requirement { + id: "browser".into(), + name: name.into(), + used_for: "Web pages on the LCD".into(), + needed_because: needed.then(|| "An LCD is set to show a web page".into()), + installed, + how: how.into(), + link: None, + in_app_folder: false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::Path; + + #[test] + fn pawnio_is_needed_on_every_windows_pc() { + assert!(pawnio(false).missing()); + assert!(!pawnio(true).missing()); + } + + #[test] + fn the_module_says_which_cpu_needs_it() { + let r = pawnio_module("Intel", Some("Intel(R) Core(TM) i7-14700K"), "IntelMSR.bin", false, None); + assert_eq!(r.name, "IntelMSR.bin"); + assert!(r.missing()); + assert!(r.in_app_folder); + assert!(r.needed_because.unwrap().contains("Intel CPU, Intel(R) Core(TM) i7-14700K")); + assert!(r.how.contains("Copy IntelMSR.bin")); + let r = pawnio_module("AMD", None, "AMDFamily17.bin", true, None); + assert_eq!(r.needed_because.as_deref(), Some("camless found an AMD CPU")); + assert!(!r.missing()); + } + + #[test] + fn a_module_from_the_config_is_not_in_the_app_folder() { + let r = pawnio_module("AMD", None, "AMDFamily17.bin", false, Some(Path::new(r"D:\pawn\AMDFamily17.bin"))); + assert!(!r.in_app_folder); + assert!(r.how.contains(r"D:\pawn\AMDFamily17.bin")); + } + + #[test] + fn a_browser_is_needed_only_for_a_web_page() { + assert!(!browser(false, false).missing()); + assert!(browser(false, false).needed_because.is_none()); + assert!(browser(true, false).missing()); + assert!(!browser(true, true).missing()); + } + + #[test] + fn every_link_is_one_the_app_opens() { + // gui/src/backend.rs `link` names the same pages. + for r in [pawnio(false), pawnio_module("Intel", None, "IntelMSR.bin", false, None), browser(true, false)] { + if let Some(l) = r.link.as_deref() { + assert!(["pawnio", "pawnio-modules"].contains(&l), "{l}"); + } + } + } +} diff --git a/src/sensors.rs b/src/sensors.rs index f43bff3..71d85f5 100644 --- a/src/sensors.rs +++ b/src/sensors.rs @@ -17,9 +17,35 @@ mod os; #[path = "sensors/windows.rs"] mod os; #[cfg(windows)] -pub use os::{pawnio_module_file, reg_dword, reg_string}; +pub use os::{cpu_maker, pawnio_module_file, reg_dword, reg_string, PAWNIO_LIB}; pub use os::{cpu_name, NO_CPU_TEMP}; +/// Where camless reads the signed PawnIO module from: the config's path, or the +/// module for this CPU next to camless.exe. +#[cfg(windows)] +pub fn pawnio_module_path(configured: Option<&std::path::PathBuf>) -> std::path::PathBuf { + configured.cloned().unwrap_or_else(|| { + let file = pawnio_module_file(); + std::env::current_exe() + .ok() + .and_then(|p| p.parent().map(|d| d.join(file))) + .unwrap_or_else(|| file.into()) + }) +} + +/// The signed PawnIO module's bytes, or why there are none. +#[cfg(windows)] +pub fn pawnio_module(configured: Option<&std::path::PathBuf>) -> std::result::Result, String> { + let path = pawnio_module_path(configured); + std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display())) +} + +/// PawnIO is Windows only; Linux reads CPU temperature from hwmon. +#[cfg(not(windows))] +pub fn pawnio_module(_configured: Option<&std::path::PathBuf>) -> std::result::Result, String> { + Err("PawnIO is for Windows".into()) +} + #[derive(Clone, Debug, Default, Serialize)] pub struct Readings { pub cpu_temp_c: Option, @@ -161,6 +187,25 @@ impl Sensors { } } + /// Opens CPU temperature again, after what it needs was installed. Keeps it if it + /// already reads. + pub fn retry_cpu(&mut self, pawnio_module: std::result::Result, String>) -> bool { + if self.cpu.is_some() { + return true; + } + match os::cpu(pawnio_module) { + Ok(cpu) => { + self.cpu = Some(cpu); + self.cpu_error = None; + true + } + Err(e) => { + self.cpu_error = Some(e); + false + } + } + } + pub fn has_cpu_temp(&self) -> bool { self.cpu.is_some() } diff --git a/src/sensors/windows.rs b/src/sensors/windows.rs index 5e44e12..a3e5494 100644 --- a/src/sensors/windows.rs +++ b/src/sensors/windows.rs @@ -34,6 +34,17 @@ pub fn cpu(pawnio_module: std::result::Result, String>) -> std::result:: pub type Cpu = PawnCpu; +/// Where PawnIO's setup puts the library camless loads it through. +pub const PAWNIO_LIB: &str = r"C:\Program Files\PawnIO\PawnIOLib.dll"; + +/// "Intel" or "AMD": the maker whose module [`pawnio_module_file`] names. +pub fn cpu_maker() -> &'static str { + match maker() { + Maker::Intel => "Intel", + Maker::Amd => "AMD", + } +} + /// The signed PawnIO module for this CPU, which camless reads next to camless.exe. /// Each refuses to load on the other maker's CPUs. pub fn pawnio_module_file() -> &'static str { @@ -151,8 +162,7 @@ impl Pawn { /// `file` only names the module in errors. fn load(module: &[u8], file: &str) -> Result { unsafe { - let lib = Library::new(r"C:\Program Files\PawnIO\PawnIOLib.dll") - .context("PawnIO is not installed")?; + let lib = Library::new(PAWNIO_LIB).context("PawnIO is not installed")?; let open: unsafe extern "system" fn(*mut HANDLE) -> i32 = *lib.get(b"pawnio_open\0")?; let load: unsafe extern "system" fn(HANDLE, *const u8, usize) -> i32 = *lib.get(b"pawnio_load\0")?; diff --git a/src/web.rs b/src/web.rs index 65f2546..dc35c5b 100644 --- a/src/web.rs +++ b/src/web.rs @@ -419,6 +419,11 @@ const NO_BROWSER: &str = "rendering a web page needs Microsoft Edge or Google Ch #[cfg(not(windows))] const NO_BROWSER: &str = "rendering a web page needs Google Chrome, Chromium, Microsoft Edge or Brave, and none is installed"; +/// The browser a web page on the LCD would render in, if one is installed. +pub fn browser_name() -> Option<&'static str> { + find_browser().map(|b| b.name) +} + /// `%LOCALAPPDATA%\camless\browser`. #[cfg(windows)] fn find_browser() -> Option {