mirror of
https://github.com/storytold/craft-launcher.git
synced 2026-11-16 15:14:56 +00:00
Merge pull request #1235 from mergenchik/feat/single-approve-update-all
Update all apps behind one permission prompt (Linux pkexec, Windows UAC)
This commit is contained in:
26 files changed
+1244
-87
No files matched your search
@@ -67,6 +67,17 @@ fn main() -> ExitCode {
|
||||
println!("artcraft-launcher {}", env!("CARGO_PKG_VERSION"));
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
// An elevated copy running one batch of MSI installs ("update all" behind one permission
|
||||
// prompt): no window, log file or single-instance claim, like the self-update helper above.
|
||||
#[cfg(windows)]
|
||||
if let Some(at) = args.iter().position(|a| a == "--install-msis")
|
||||
&& let Some(manifest) = args.get(at + 1)
|
||||
{
|
||||
return match artcraft_launcher_native::install::msi_session::run_elevated(std::path::Path::new(manifest)) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(_) => ExitCode::FAILURE,
|
||||
};
|
||||
}
|
||||
let mut hidden = args.iter().any(|a| a == login::HIDDEN_FLAG);
|
||||
|
||||
let wake: Wake = Arc::new(OnceLock::new());
|
||||
|
||||
@@ -29,6 +29,12 @@ pub enum Command {
|
||||
Install {
|
||||
app: String,
|
||||
},
|
||||
/// Install or update every app in `apps` together: their downloads run as for [`Command::Install`],
|
||||
/// but where the platform needs a permission prompt (polkit on Linux, elevation on Windows)
|
||||
/// the batch shares one prompt instead of one per app. Apps already running a job are left out.
|
||||
InstallAll {
|
||||
apps: Vec<String>,
|
||||
},
|
||||
/// `Install`, writing over what [`Event::Occupied`] reported. `path` is the path the user
|
||||
/// agreed to overwrite: if the install would now write somewhere else, nothing is replaced and
|
||||
/// the user is asked again.
|
||||
|
||||
@@ -46,7 +46,8 @@ winreg = "0.55"
|
||||
# Resolves junctions/symlinks without forcing short MSI paths into the verbatim namespace.
|
||||
dunce = "1"
|
||||
zip = { version = "9", default-features = false, features = ["deflate"] }
|
||||
# Safe wrappers for waiting for another process, reading a file's VERSIONINFO and this account's SID.
|
||||
winsafe = { version = "0.0.29", features = ["kernel", "version", "advapi"] }
|
||||
# Safe wrappers for waiting for another process, reading a file's VERSIONINFO, this account's
|
||||
# SID and the one elevation prompt a batch of installs shares (ShellExecuteEx).
|
||||
winsafe = { version = "0.0.29", features = ["kernel", "version", "advapi", "shell"] }
|
||||
# Authenticode checks through WinTrust: the update helper installs only files from the launcher's publisher.
|
||||
verifysign = "1"
|
||||
@@ -419,19 +419,20 @@ impl NativeBackend {
|
||||
});
|
||||
}
|
||||
|
||||
/// Starts an install, update, or uninstall job for `app_id` on a background thread.
|
||||
fn start_job(&self, app_id: &str, work: Work) {
|
||||
/// Starts the job, or returns `false` without starting one: the app is unknown, doesn't run
|
||||
/// on this platform, is already running a job, or the launcher is restarting into an update.
|
||||
fn start_job(&self, app_id: &str, work: Work) -> bool {
|
||||
let uninstall = matches!(work, Work::Uninstall);
|
||||
let Some(app) = CraftApp::by_id(app_id) else { return };
|
||||
let Some(app) = CraftApp::by_id(app_id) else { return false };
|
||||
if self.platform.is_some_and(|p| !app.runs_on(p.os)) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
log::info!("{}: starting {} job", app.name, if uninstall { "uninstall" } else { "install/update" });
|
||||
let stop = Arc::new(Stop::default());
|
||||
let restarting = {
|
||||
let mut jobs = self.shared.jobs.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if jobs.contains_key(app.id) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
let restarting = self.shared.restarting.load(Ordering::SeqCst);
|
||||
if !restarting {
|
||||
@@ -442,7 +443,7 @@ impl NativeBackend {
|
||||
if restarting {
|
||||
let result = Err("ArtCraft Launcher is restarting to finish its update. Try again once it's back.".into());
|
||||
self.shared.emit(Event::JobFinished { app: app.id.to_string(), result });
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
let shared = self.shared.clone();
|
||||
let job = JobGuard { shared: shared.clone(), app_id: app.id.to_string() };
|
||||
@@ -469,6 +470,11 @@ impl NativeBackend {
|
||||
None => Err(format!("{} isn't installed", app.name)),
|
||||
}
|
||||
} else {
|
||||
let (approved, batch) = match &work {
|
||||
Work::Replace(path) => (Some(path.as_str()), None),
|
||||
Work::Install(batch) => (None, batch.clone()),
|
||||
Work::Uninstall => (None, None),
|
||||
};
|
||||
let r = run_install(
|
||||
app,
|
||||
&shared,
|
||||
@@ -479,11 +485,9 @@ impl NativeBackend {
|
||||
existing.as_ref(),
|
||||
record.as_ref(),
|
||||
&stop,
|
||||
match &work {
|
||||
Work::Replace(path) => Some(path.as_str()),
|
||||
Work::Install | Work::Uninstall => None,
|
||||
},
|
||||
approved,
|
||||
source.as_deref(),
|
||||
batch,
|
||||
);
|
||||
// Stopped by the connection rather than by the user: say so, and how to go on.
|
||||
match r {
|
||||
@@ -514,6 +518,41 @@ impl NativeBackend {
|
||||
drop(job);
|
||||
shared.emit(Event::JobFinished { app: app.id.to_string(), result });
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// Starts one install per app, together (see [`Command::InstallAll`]): where the platform
|
||||
/// needs a permission prompt, the batch shares one — each member waits for the others'
|
||||
/// downloads before the system installer is asked once. Apps unknown or already running a
|
||||
/// job are left out; a batch of one installs the same as a single [`Command::Install`].
|
||||
fn install_all(&self, apps: &[String]) {
|
||||
let running = self.shared.jobs.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut ids: Vec<&str> = Vec::new();
|
||||
for id in apps {
|
||||
let Some(app) = CraftApp::by_id(id) else { continue };
|
||||
if running.contains_key(app.id) || ids.contains(&app.id) {
|
||||
continue;
|
||||
}
|
||||
ids.push(app.id);
|
||||
}
|
||||
drop(running);
|
||||
#[cfg(any(target_os = "linux", windows))]
|
||||
let batch = (!ids.is_empty()).then(|| install::INSTALLER.gather(ids.len()));
|
||||
#[cfg(not(any(target_os = "linux", windows)))]
|
||||
let batch = None;
|
||||
let mut started = 0;
|
||||
for id in &ids {
|
||||
if self.start_job(id, Work::Install(batch.clone())) {
|
||||
started += 1;
|
||||
}
|
||||
}
|
||||
// Members that could not start after all (another job raced in for them) are not coming:
|
||||
// their places in the batch are given back, so the rest don't wait for them.
|
||||
for _ in started..ids.len() {
|
||||
if let Some(batch) = &batch {
|
||||
batch.leave();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads the newer launcher, puts it in place and asks the UI to quit so it can start.
|
||||
@@ -574,7 +613,9 @@ impl NativeBackend {
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
enum Work {
|
||||
Install,
|
||||
/// Install or update. Carries the batch this job is part of, if any (see
|
||||
/// [`Command::InstallAll`]): where the platform needs a permission prompt, the batch shares one.
|
||||
Install(Option<crate::queue::Gather>),
|
||||
/// Install over the path the user agreed to overwrite (see [`Command::Replace`]).
|
||||
Replace(String),
|
||||
Uninstall,
|
||||
@@ -712,7 +753,12 @@ fn run_install(
|
||||
stop: &Stop,
|
||||
approved: Option<&str>,
|
||||
source: Option<&dyn ReleaseSource>,
|
||||
batch: Option<crate::queue::Gather>,
|
||||
) -> Result<String, String> {
|
||||
// The ways out below that never reach the installer (a repository-managed Flatpak, a missing
|
||||
// release, the overwrite question, a paused download) free the rest of the batch at once;
|
||||
// from `install_at` on, the same guard does it there.
|
||||
let mut batch = install::BatchPlace(batch);
|
||||
if let Some(update) = repository_update(app, existing, options) {
|
||||
let inst = update?;
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -791,7 +837,17 @@ fn run_install(
|
||||
last_emit = Instant::now();
|
||||
shared.emit(Event::Progress { app: app.id.to_string(), phase: p });
|
||||
};
|
||||
let mut job = Job { http, paths, stop, phase: &mut phase, install_locations: &options.install_locations, replace, approved_path, downgrade };
|
||||
let mut job = Job {
|
||||
http,
|
||||
paths,
|
||||
stop,
|
||||
phase: &mut phase,
|
||||
install_locations: &options.install_locations,
|
||||
replace,
|
||||
approved_path,
|
||||
downgrade,
|
||||
batch: batch.take(),
|
||||
};
|
||||
let mut commit_record = |record: &crate::manifest::Record| {
|
||||
let mut manifest = shared.manifest.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut updated = manifest.clone();
|
||||
@@ -1456,9 +1512,16 @@ impl Backend for NativeBackend {
|
||||
shared.emit(Event::Versions { app, result });
|
||||
});
|
||||
}
|
||||
Command::Install { app } => self.start_job(&app, Work::Install),
|
||||
Command::Replace { app, path } => self.start_job(&app, Work::Replace(path)),
|
||||
Command::Uninstall { app } => self.start_job(&app, Work::Uninstall),
|
||||
Command::Install { app } => {
|
||||
self.start_job(&app, Work::Install(None));
|
||||
}
|
||||
Command::InstallAll { apps } => self.install_all(&apps),
|
||||
Command::Replace { app, path } => {
|
||||
self.start_job(&app, Work::Replace(path));
|
||||
}
|
||||
Command::Uninstall { app } => {
|
||||
self.start_job(&app, Work::Uninstall);
|
||||
}
|
||||
Command::Pause { app } => {
|
||||
if let Some(stop) = self.shared.jobs.lock().unwrap_or_else(PoisonError::into_inner).get(&app) {
|
||||
stop.pause();
|
||||
@@ -1575,6 +1638,20 @@ mod tests {
|
||||
|
||||
use crate::source::Answer;
|
||||
|
||||
/// A member of a batch that ends before it ever reaches the installer — its download failed,
|
||||
/// or it turned out to need none of the batch's prompts — frees the rest of the batch at
|
||||
/// once, rather than holding them back until the batch's wait runs out.
|
||||
#[cfg(any(target_os = "linux", windows))]
|
||||
#[test]
|
||||
fn a_batch_member_that_never_reaches_the_installer_frees_the_rest() {
|
||||
let gather = install::INSTALLER.gather(1);
|
||||
{
|
||||
let _place = install::BatchPlace(Some(gather.clone()));
|
||||
assert!(!gather.open(), "the place is held while the job is on its way");
|
||||
}
|
||||
assert!(gather.open(), "dropping the place on the way out opens the gate");
|
||||
}
|
||||
|
||||
fn tagged(v: &str) -> Release {
|
||||
Release { tag: format!("v{v}"), version: version::parse(v), ..Default::default() }
|
||||
}
|
||||
|
||||
+201
-35
@@ -46,6 +46,30 @@ pub struct Job<'a> {
|
||||
pub approved_path: Option<&'a Path>,
|
||||
/// Set only when the person chose this older version by name over a newer installed copy.
|
||||
pub downgrade: Option<Downgrade<'a>>,
|
||||
/// The batch of installs this one belongs to (an "update all"): where the platform needs a
|
||||
/// permission prompt, the whole batch shares one. `None` for a job on its own.
|
||||
pub batch: Option<crate::queue::Gather>,
|
||||
}
|
||||
|
||||
/// A job's place in its batch (see [`Job::batch`]): the installer queue takes it where the batch
|
||||
/// shares one call ([`crate::queue::Queue::batched_when`]); a job that ends before that — failed,
|
||||
/// cancelled, or needing no prompt at all — gives the place back on its way out, so the rest of
|
||||
/// the batch never waits for it. [`install_at`](fn@install_at) takes it for the installer routes;
|
||||
/// the backend holds it the same way for every earlier way out of a job.
|
||||
pub(crate) struct BatchPlace(pub(crate) Option<crate::queue::Gather>);
|
||||
|
||||
impl BatchPlace {
|
||||
pub(crate) fn take(&mut self) -> Option<crate::queue::Gather> {
|
||||
self.0.take()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BatchPlace {
|
||||
fn drop(&mut self) {
|
||||
if let Some(gather) = self.0.take() {
|
||||
gather.leave();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a downgrade the person chose is undone if it fails.
|
||||
@@ -113,6 +137,9 @@ pub fn install_at(
|
||||
let mut commit = commit;
|
||||
#[cfg(not(windows))]
|
||||
let _ = commit;
|
||||
// Every early way out below gives the job's place in its batch back (see [`BatchPlace`]).
|
||||
#[cfg_attr(not(any(target_os = "linux", windows)), allow(unused_mut, unused_variables))]
|
||||
let mut batch = BatchPlace(job.batch.take());
|
||||
#[allow(unused_variables)]
|
||||
let destination = destination(app, kind, existing, previous, job.install_locations)?;
|
||||
#[cfg(windows)]
|
||||
@@ -204,7 +231,15 @@ pub fn install_at(
|
||||
job.stop,
|
||||
&mut *job.phase,
|
||||
),
|
||||
None => windows::run_msi(&file, destination.as_deref(), msi_scope, job.stop, &mut *job.phase),
|
||||
None => windows::run_msi(
|
||||
app,
|
||||
windows::Package { file: &file, sha256: &sha256, version: &version },
|
||||
destination.as_deref(),
|
||||
msi_scope,
|
||||
batch.take(),
|
||||
job.stop,
|
||||
&mut *job.phase,
|
||||
),
|
||||
}
|
||||
.map(|_| None)
|
||||
}
|
||||
@@ -222,17 +257,21 @@ pub fn install_at(
|
||||
.map(Some)
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
PackageKind::Deb | PackageKind::Rpm | PackageKind::ArchPkg | PackageKind::Flatpak => {
|
||||
linux::install_package(kind, &file, existing.and_then(|installed| installed.installation.as_deref()), job.stop, &mut *job.phase).map(
|
||||
|_| {
|
||||
if kind == PackageKind::Flatpak {
|
||||
linux::configure_bundle_lookaside(app, existing.and_then(|installed| installed.installation.as_deref()));
|
||||
linux::retire_former_flatpak(app, existing);
|
||||
}
|
||||
None
|
||||
},
|
||||
)
|
||||
}
|
||||
PackageKind::Deb | PackageKind::Rpm | PackageKind::ArchPkg | PackageKind::Flatpak => linux::install_package(
|
||||
kind,
|
||||
&file,
|
||||
existing.and_then(|installed| installed.installation.as_deref()),
|
||||
batch.take(),
|
||||
job.stop,
|
||||
&mut *job.phase,
|
||||
)
|
||||
.map(|_| {
|
||||
if kind == PackageKind::Flatpak {
|
||||
linux::configure_bundle_lookaside(app, existing.and_then(|installed| installed.installation.as_deref()));
|
||||
linux::retire_former_flatpak(app, existing);
|
||||
}
|
||||
None
|
||||
}),
|
||||
#[cfg(target_os = "linux")]
|
||||
PackageKind::AppImage => {
|
||||
linux::install_appimage(&file, &asset.name, destination.as_deref(), previous, job.replace).map(|(path, replaced)| {
|
||||
@@ -474,7 +513,7 @@ fn msi_folder_argument(path: &Path) -> Result<String, String> {
|
||||
/// HKLM registrations; a per-user one must not silently become a second, per-machine copy (or
|
||||
/// the other way round). A fresh install is always `PerMachine`.
|
||||
#[cfg(any(windows, test))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum MsiScope {
|
||||
PerUser,
|
||||
PerMachine,
|
||||
@@ -1038,9 +1077,10 @@ pub fn failed_in_shared_call(error: &str) -> bool {
|
||||
cfg!(target_os = "linux") && error.ends_with(SHARED_CALL)
|
||||
}
|
||||
|
||||
/// The system's installer runs one job at a time; the others wait their turn here.
|
||||
/// The system's installer runs one job at a time; the others wait their turn here. The backend
|
||||
/// starts each batch of installs (an "update all") with [`Queue::gather`] on it.
|
||||
#[cfg(any(target_os = "linux", windows))]
|
||||
static INSTALLER: crate::queue::Queue = crate::queue::Queue::new();
|
||||
pub(crate) static INSTALLER: crate::queue::Queue = crate::queue::Queue::new();
|
||||
|
||||
/// For [`INSTALLER`]: reports [`JobPhase::Waiting`] while a job waits, then `working` again.
|
||||
#[cfg(any(target_os = "linux", windows))]
|
||||
@@ -1085,19 +1125,22 @@ pub(crate) mod linux {
|
||||
const SYSTEM: Root<'static> = Root { queue: &INSTALLER, run: &run_as_root };
|
||||
|
||||
/// Runs `command target` as root. Jobs waiting for the same command go into one call
|
||||
/// (`apt-get install a.deb b.deb`), so the password is asked for once.
|
||||
/// (`apt-get install a.deb b.deb`), so the password is asked for once; a job with a `batch`
|
||||
/// also waits for the rest of that batch first, so the call covers all of them.
|
||||
fn as_root(
|
||||
root: &Root<'_>,
|
||||
command: &[&str],
|
||||
target: &OsStr,
|
||||
batch: Option<crate::queue::Gather>,
|
||||
stop: &Stop,
|
||||
phase: &mut dyn FnMut(JobPhase),
|
||||
working: JobPhase,
|
||||
) -> Result<(), String> {
|
||||
let command = command.iter().map(OsString::from).collect();
|
||||
root.queue.batched(command, target.to_os_string(), &cancelled(stop), &mut turn(phase, working), &|command, targets| {
|
||||
root.queue.batched_when(batch, command, target.to_os_string(), &cancelled(stop), &mut turn(phase, working), &|command, targets| {
|
||||
let args: Vec<&OsStr> = command.iter().chain(targets).map(OsString::as_os_str).collect();
|
||||
shared_outcome((root.run)(&args), targets.len())
|
||||
let outcome = shared_outcome((root.run)(&args), targets.len());
|
||||
vec![outcome; targets.len()]
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1201,16 +1244,26 @@ pub(crate) mod linux {
|
||||
kind: PackageKind,
|
||||
file: &Path,
|
||||
installation: Option<&str>,
|
||||
batch: Option<crate::queue::Gather>,
|
||||
stop: &Stop,
|
||||
phase: &mut dyn FnMut(JobPhase),
|
||||
) -> Result<(), String> {
|
||||
if kind == PackageKind::Deb && system_tool("apt-get").is_none() {
|
||||
return Err("this system has no apt-get to install a Debian package with".into());
|
||||
let missing = if kind == PackageKind::Deb && system_tool("apt-get").is_none() {
|
||||
Some("this system has no apt-get to install a Debian package with")
|
||||
} else if kind == PackageKind::ArchPkg && system_tool("pacman").is_none() {
|
||||
Some("this system has no pacman to install an Arch package with")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(error) = missing {
|
||||
// This member never reaches the shared prompt: its place in the batch goes back at
|
||||
// once, so the rest don't wait for it (see [`Gather::leave`]).
|
||||
if let Some(gather) = batch {
|
||||
gather.leave();
|
||||
}
|
||||
return Err(error.into());
|
||||
}
|
||||
if kind == PackageKind::ArchPkg && system_tool("pacman").is_none() {
|
||||
return Err("this system has no pacman to install an Arch package with".into());
|
||||
}
|
||||
install_package_via(&SYSTEM, kind, file, installation, stop, phase)
|
||||
install_package_via(&SYSTEM, kind, file, installation, batch, stop, phase)
|
||||
}
|
||||
|
||||
pub fn install_package_via(
|
||||
@@ -1218,12 +1271,18 @@ pub(crate) mod linux {
|
||||
kind: PackageKind,
|
||||
file: &Path,
|
||||
installation: Option<&str>,
|
||||
batch: Option<crate::queue::Gather>,
|
||||
stop: &Stop,
|
||||
phase: &mut dyn FnMut(JobPhase),
|
||||
) -> Result<(), String> {
|
||||
let f = file.as_os_str();
|
||||
if let Some(command) = install_command(kind) {
|
||||
return as_root(root, command, f, stop, phase, JobPhase::Installing);
|
||||
return as_root(root, command, f, batch, stop, phase, JobPhase::Installing);
|
||||
}
|
||||
// This kind runs without the batch's shared prompt (Flatpak asks for itself, or not at
|
||||
// all): its place in the batch is given back right away.
|
||||
if let Some(gather) = batch {
|
||||
gather.leave();
|
||||
}
|
||||
match kind {
|
||||
PackageKind::Flatpak => {
|
||||
@@ -1257,7 +1316,7 @@ pub(crate) mod linux {
|
||||
}
|
||||
|
||||
pub fn remove_package(app: &CraftApp, installed: &Installed, stop: &Stop, phase: &mut dyn FnMut(JobPhase)) -> Result<(), String> {
|
||||
let mut remove = |command: &[&str], package: &str| as_root(&SYSTEM, command, OsStr::new(package), stop, phase, JobPhase::Removing);
|
||||
let mut remove = |command: &[&str], package: &str| as_root(&SYSTEM, command, OsStr::new(package), None, stop, phase, JobPhase::Removing);
|
||||
let package = installed.package.as_deref().unwrap_or(app.id);
|
||||
match installed.source {
|
||||
// The package detected (photocraft, or ai.storyteller.photocraft).
|
||||
@@ -2096,6 +2155,10 @@ mod msi_downgrade;
|
||||
/// Helpers for Windows Installer PowerShell scripts running under elevation.
|
||||
#[cfg(any(windows, test))]
|
||||
mod msi_batch;
|
||||
/// One permission prompt for a batch of per-machine packages: the launcher's own exe, elevated
|
||||
/// once, running Windows Installer on each checked package.
|
||||
#[cfg(any(windows, test))]
|
||||
pub mod msi_session;
|
||||
/// Builds the Windows Installer command separately so its package argument can be checked
|
||||
/// without starting an installer.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
@@ -2132,24 +2195,74 @@ pub mod windows {
|
||||
|
||||
use super::{
|
||||
CraftApp, INSTALLER, JobPhase, MsiScope, Path, PathBuf, Stop, cancelled, explain, msi_batch, msi_command, msi_downgrade, msi_folder_argument,
|
||||
msi_log, msi_scope_arguments, process, turn,
|
||||
msi_log, msi_scope_arguments, msi_session, process, turn,
|
||||
};
|
||||
|
||||
fn msiexec() -> PathBuf {
|
||||
pub(super) fn msiexec() -> PathBuf {
|
||||
std::env::var_os("SystemRoot").map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from).join(r"System32\msiexec.exe")
|
||||
}
|
||||
|
||||
/// Runs an MSI with a progress window and no restart. Windows asks for permission itself.
|
||||
/// `scope`, from the copy being replaced's registration, keeps the update in the same
|
||||
/// Windows Installer context (see [`MsiScope`]).
|
||||
pub fn run_msi(
|
||||
msi: &Path,
|
||||
/// Windows Installer context (see [`MsiScope`]). A per-machine package with a `batch` joins
|
||||
/// it instead: the whole batch shares one permission prompt ([`run_batched`]). Only
|
||||
/// [`install_at`](super::install_at) calls it, so it stays as private as its [`Package`].
|
||||
pub(super) fn run_msi(
|
||||
app: &CraftApp,
|
||||
package: Package<'_>,
|
||||
destination: Option<&Path>,
|
||||
scope: Option<MsiScope>,
|
||||
batch: Option<crate::queue::Gather>,
|
||||
stop: &Stop,
|
||||
phase: &mut dyn FnMut(JobPhase),
|
||||
) -> Result<(), String> {
|
||||
in_turn(stop, phase, JobPhase::Installing, || run_direct(msi, destination, scope))
|
||||
if let Some(gather) = batch {
|
||||
if scope == Some(MsiScope::PerMachine) {
|
||||
return run_batched(Batched { app, package, destination, scope }, gather, stop, phase);
|
||||
}
|
||||
// A per-user install asks Windows for nothing: its place in the batch goes back at
|
||||
// once, so the per-machine members don't wait for it.
|
||||
gather.leave();
|
||||
}
|
||||
in_turn(stop, phase, JobPhase::Installing, || run_direct(package.file, destination, scope))
|
||||
}
|
||||
|
||||
/// One app's install, as the batch session runs it.
|
||||
struct Batched<'a> {
|
||||
app: &'a CraftApp,
|
||||
package: Package<'a>,
|
||||
destination: Option<&'a Path>,
|
||||
scope: Option<MsiScope>,
|
||||
}
|
||||
|
||||
/// One permission prompt for a batch of per-machine packages: the members meet in one call
|
||||
/// of the installer queue, the one whose call it is starts the elevated session
|
||||
/// ([`msi_session`]), and every member hears its own installer's exit code. A declined
|
||||
/// prompt cancels the whole batch; a session that cannot start sends the members back to
|
||||
/// installing one by one, the way a single app always installs.
|
||||
fn run_batched(job: Batched<'_>, gather: crate::queue::Gather, stop: &Stop, phase: &mut dyn FnMut(JobPhase)) -> Result<(), String> {
|
||||
let Batched { app, package, destination, scope } = job;
|
||||
let target = match msi_session::entry(app, &package, destination, scope) {
|
||||
Ok(target) => target,
|
||||
Err(e) => {
|
||||
log::warn!("{}: {e}; installing it by itself", app.name);
|
||||
gather.leave();
|
||||
return in_turn(stop, phase, JobPhase::Installing, || run_direct(package.file, destination, scope));
|
||||
}
|
||||
};
|
||||
let outcome = INSTALLER.batched_when(
|
||||
Some(gather),
|
||||
msi_session::command(),
|
||||
target,
|
||||
&cancelled(stop),
|
||||
&mut turn(phase, JobPhase::Installing),
|
||||
&msi_session::call,
|
||||
);
|
||||
if outcome.as_ref().err().is_some_and(|e| e == msi_session::NO_SESSION) {
|
||||
log::warn!("{}: the batch session could not start; installing it by itself", app.name);
|
||||
return in_turn(stop, phase, JobPhase::Installing, || run_direct(package.file, destination, scope));
|
||||
}
|
||||
outcome
|
||||
}
|
||||
|
||||
/// Runs one MSI by itself: `msiexec` asks for permission itself, and the prompt names the package's
|
||||
@@ -2738,6 +2851,7 @@ mod tests {
|
||||
replace: false,
|
||||
approved_path: None,
|
||||
downgrade: Some(Downgrade::Reinstall { previous: &newer, asset: &newer_msi }),
|
||||
batch: None,
|
||||
};
|
||||
install(app, &older, &older_msi, PackageKind::Msi, Some(&portable), None, &mut job).unwrap_err()
|
||||
};
|
||||
@@ -2852,6 +2966,7 @@ mod tests {
|
||||
replace: false,
|
||||
approved_path: None,
|
||||
downgrade,
|
||||
batch: None,
|
||||
};
|
||||
install(app, &release, &asset, kind, Some(&installed), previous, &mut job).unwrap_err()
|
||||
};
|
||||
@@ -2891,6 +3006,7 @@ mod tests {
|
||||
replace: false,
|
||||
approved_path: None,
|
||||
downgrade: None,
|
||||
batch: None,
|
||||
};
|
||||
let err = install(app, &release, &asset, kind, None, None, &mut job).unwrap_err();
|
||||
assert!(err.contains("isn't supported"), "{err}");
|
||||
@@ -2924,6 +3040,7 @@ mod tests {
|
||||
replace: false,
|
||||
approved_path: None,
|
||||
downgrade: None,
|
||||
batch: None,
|
||||
};
|
||||
let error = install(app, &release, &asset, PackageKind::AppImage, None, None, &mut job).unwrap_err();
|
||||
assert!(error.contains("folder is unavailable") || (process::in_sandbox() && error.contains("aren't supported")), "{error}");
|
||||
@@ -2956,6 +3073,7 @@ mod tests {
|
||||
replace: false,
|
||||
approved_path: None,
|
||||
downgrade: None,
|
||||
batch: None,
|
||||
};
|
||||
let err = install(app, &release, &asset, kind, None, None, &mut job).unwrap_err();
|
||||
assert!(err.contains("publishes no checksum"), "{err}");
|
||||
@@ -3235,7 +3353,7 @@ mod tests {
|
||||
waiting.send(()).unwrap();
|
||||
}
|
||||
};
|
||||
linux::install_package_via(root, PackageKind::Deb, Path::new(file), None, &Stop::default(), &mut phase)
|
||||
linux::install_package_via(root, PackageKind::Deb, Path::new(file), None, None, &Stop::default(), &mut phase)
|
||||
})
|
||||
});
|
||||
waits.recv().unwrap();
|
||||
@@ -3276,6 +3394,45 @@ mod tests {
|
||||
assert_eq!(results, vec![Err(error.to_string()); 2]);
|
||||
}
|
||||
|
||||
/// An "update all" of two `.deb` apps whose downloads finish one after the other, on an idle
|
||||
/// system: with a batch, the first to finish holds back from the installer until the second
|
||||
/// arrives, so the password is asked for once — without the batch, each gets its own call.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn two_gathered_debs_share_one_password_prompt_without_a_busy_installer() {
|
||||
use std::sync::Mutex;
|
||||
|
||||
let queue = crate::queue::Queue::new();
|
||||
let ran = Mutex::new(Vec::new());
|
||||
let run = |args: &[&std::ffi::OsStr]| {
|
||||
ran.lock().unwrap().push(args.iter().map(|a| a.to_string_lossy().into_owned()).collect::<Vec<_>>());
|
||||
root_outcome(Some(0))
|
||||
};
|
||||
let root = linux::Root { queue: &queue, run: &run };
|
||||
let gather = queue.gather(2);
|
||||
let results = std::thread::scope(|scope| {
|
||||
let root = &root;
|
||||
let jobs: Vec<_> = ["/downloads/a.deb", "/downloads/b.deb"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(at, file)| {
|
||||
let gather = gather.clone();
|
||||
scope.spawn(move || {
|
||||
std::thread::sleep(std::time::Duration::from_millis(30 * at as u64));
|
||||
linux::install_package_via(root, PackageKind::Deb, Path::new(file), None, Some(gather), &Stop::default(), &mut |_| ())
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
jobs.into_iter().map(|job| job.join().unwrap()).collect::<Vec<_>>()
|
||||
});
|
||||
let calls = ran.into_inner().unwrap();
|
||||
assert_eq!(calls.len(), 1, "one call for the whole batch: {calls:?}");
|
||||
let mut files = calls[0].split_at(6).1.to_vec();
|
||||
files.sort();
|
||||
assert_eq!(files, ["/downloads/a.deb", "/downloads/b.deb"]);
|
||||
assert_eq!(results, vec![Ok(()), Ok(())]);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn flatpak_bundle_install_failure_reports_clean_error() {
|
||||
@@ -3284,8 +3441,15 @@ mod tests {
|
||||
}
|
||||
let queue = crate::queue::Queue::new();
|
||||
let root = linux::Root { queue: &queue, run: &|_| Ok(()) };
|
||||
let result =
|
||||
linux::install_package_via(&root, PackageKind::Flatpak, Path::new("/nonexistent/file.flatpak"), None, &Stop::default(), &mut |_| ());
|
||||
let result = linux::install_package_via(
|
||||
&root,
|
||||
PackageKind::Flatpak,
|
||||
Path::new("/nonexistent/file.flatpak"),
|
||||
None,
|
||||
None,
|
||||
&Stop::default(),
|
||||
&mut |_| (),
|
||||
);
|
||||
assert!(result.is_err());
|
||||
let err = result.unwrap_err();
|
||||
assert!(err.starts_with("Flatpak couldn't install the bundle: "), "unexpected error: {err}");
|
||||
@@ -3591,6 +3755,7 @@ mod tests {
|
||||
replace: false,
|
||||
approved_path: None,
|
||||
downgrade: None,
|
||||
batch: None,
|
||||
};
|
||||
let result = install_at(app, &release, &asset, PackageKind::AppImage, Some(&installed), None, &mut job, None);
|
||||
assert!(result.is_err());
|
||||
@@ -3623,6 +3788,7 @@ mod tests {
|
||||
replace: false,
|
||||
approved_path: None,
|
||||
downgrade: None,
|
||||
batch: None,
|
||||
};
|
||||
let result = install_at(app, &release, &asset, PackageKind::AppImage, None, None, &mut job, None);
|
||||
assert!(result.is_err(), "mismatched artifact version must be rejected");
|
||||
|
||||
@@ -115,6 +115,16 @@ pub(super) fn hold(msi: &Path, sha256: &str) -> Result<Held, String> {
|
||||
Ok(Held { _file: file })
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl Held {
|
||||
/// A file already opened for reading only (no re-check): the batch session's manifest, held
|
||||
/// the same way its packages are (see [`hold`]).
|
||||
#[cfg(windows)]
|
||||
pub(super) fn keep(file: std::fs::File) -> Held {
|
||||
Held { _file: file }
|
||||
}
|
||||
}
|
||||
|
||||
/// The base64 form of `script` that `-EncodedCommand` takes: UTF-16 little-endian, so no quoting
|
||||
/// can go wrong however odd a path is.
|
||||
pub(super) fn encoded(script: &str) -> String {
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
//! One permission prompt for a batch of per-machine Windows Installer packages.
|
||||
//!
|
||||
//! [`super::windows::run_batched`] gathers the members of an "update all" into one call of the
|
||||
//! installer queue; the one whose call it is writes what the session is to do into a manifest
|
||||
//! beside the checked packages and starts the launcher's own exe elevated (`ShellExecuteEx`,
|
||||
//! verb `runas`). No PowerShell, nothing encoded, nothing hidden: the one prompt names ArtCraft
|
||||
//! Launcher and its signed publisher, and each package still shows its own installer progress
|
||||
//! window. A hidden, elevated, encoded PowerShell route did this before and was withdrawn after
|
||||
//! behavioural antivirus flagged it (see `docs/incident-2026-10-windows-antivirus.md`).
|
||||
//!
|
||||
//! The elevated copy re-checks every package against the checksum its release published — with
|
||||
//! the file held open, so the checked bytes are the installed ones (CWE-367) — builds each
|
||||
//! installer's arguments from that held package itself (the manifest says where and in which
|
||||
//! context a package installs, never *which* file installs), runs Windows Installer on each in
|
||||
//! turn, and writes each app's exit code to a results file beside the manifest. A declined
|
||||
//! prompt cancels the whole batch; a session that cannot start sends the members back to
|
||||
//! installing one by one, the way a single app always installs.
|
||||
//!
|
||||
//! The trust chain: the manifest is created anew (`create_new`) and then held open unmodified for
|
||||
//! the whole session, so its checksums are the launcher's own; the elevated side re-hashes every
|
||||
//! package through a held handle before Windows Installer touches it, and runs the installer on
|
||||
//! that same held file. The results file is bound to its session by a random token (written as
|
||||
//! the file's first line), so no leftover or planted file can pass for a session's report; the
|
||||
//! launcher's own re-detection after each job is the backstop against a report that lies. And
|
||||
//! the waiting side falls back to one-by-one installs only when the elevated session is *shown*
|
||||
//! to be over — its process waited out or its process id gone — never while it may still be
|
||||
//! installing.
|
||||
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use super::MsiScope;
|
||||
|
||||
/// What a member hears when the batch's one session could not run at all: install it by itself
|
||||
/// (see [`super::windows::run_batched`], which recognises this and does exactly that). Never
|
||||
/// shown to anyone.
|
||||
pub(super) const NO_SESSION: &str = "no batch session";
|
||||
|
||||
/// How long the waiting side looks for the elevated copy's first act, writing its process id.
|
||||
/// A behavioural antivirus may hold a start-up up for minutes; falling back before the elevated
|
||||
/// copy has even begun would race its installers, so the wait is patient and the failure is an
|
||||
/// error (never a fallback — see [`wait_until_done`]).
|
||||
#[cfg(windows)]
|
||||
const STARTED_WITHIN: std::time::Duration = std::time::Duration::from_secs(300);
|
||||
|
||||
/// How long a process id that cannot be opened is given the benefit of the doubt: opening a
|
||||
/// just-started elevated process can fail for a moment, and "cannot open" must never be read as
|
||||
/// "not running" while it keeps failing.
|
||||
#[cfg(windows)]
|
||||
const OPEN_GRACE: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
/// One package of the batch, as both sides of the session see it. It carries no command line:
|
||||
/// the elevated side builds the installer's arguments from the held package itself
|
||||
/// ([`run_elevated`]), so the file Windows Installer runs is always the file that was checked.
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub(crate) struct Entry {
|
||||
/// The app the package belongs to: its key in the results.
|
||||
app: String,
|
||||
/// The checked package, in the launcher's downloads folder.
|
||||
msi: PathBuf,
|
||||
/// The SHA-256 the package was downloaded against; the elevated side checks it again before
|
||||
/// Windows Installer touches the file.
|
||||
sha256: String,
|
||||
/// Where the package installs, when a single install passes a folder (`INSTALLFOLDER`).
|
||||
destination: Option<PathBuf>,
|
||||
/// The Windows Installer context to keep; `None` takes the package's own default.
|
||||
scope: Option<MsiScope>,
|
||||
}
|
||||
|
||||
/// What the elevated copy is to do, written beside the packages and held unchanged while the
|
||||
/// session runs. The results and the process id arrive in files beside it (see [`sibling`]).
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Manifest {
|
||||
/// Binds the results file to this session: the elevated copy writes it as the results'
|
||||
/// first line, so no file from any other session (left over, or put in place) can pass as
|
||||
/// this one's report.
|
||||
token: String,
|
||||
msis: Vec<Entry>,
|
||||
}
|
||||
|
||||
/// The command every per-machine batch member waits under: the installer queue's merging key
|
||||
/// for the one call the batch shares.
|
||||
pub(super) fn command() -> Vec<OsString> {
|
||||
vec![OsString::from("msiexec")]
|
||||
}
|
||||
|
||||
/// One member's place in the session, as the installer queue's `target`. `Err` for a package the
|
||||
/// session cannot express (a package path that cannot be resolved); the member then installs by
|
||||
/// itself.
|
||||
#[cfg(windows)]
|
||||
pub(super) fn entry(
|
||||
app: &super::CraftApp,
|
||||
package: &super::windows::Package<'_>,
|
||||
destination: Option<&Path>,
|
||||
scope: Option<MsiScope>,
|
||||
) -> Result<OsString, String> {
|
||||
let entry = Entry {
|
||||
app: app.id.to_string(),
|
||||
msi: super::msi_path(package.file)?,
|
||||
sha256: package.sha256.to_string(),
|
||||
destination: destination.map(Path::to_path_buf),
|
||||
scope,
|
||||
};
|
||||
serde_json::to_string(&entry).map(OsString::from).map_err(|e| format!("couldn't describe the package for a shared prompt ({e})"))
|
||||
}
|
||||
|
||||
/// The queue's `target` back into an [`Entry`].
|
||||
fn parse(target: &OsStr) -> Option<Entry> {
|
||||
target.to_str().and_then(|text| serde_json::from_str(text).ok())
|
||||
}
|
||||
|
||||
/// Where the session keeps a file beside its manifest.
|
||||
fn sibling(manifest: &Path, extension: &str) -> PathBuf {
|
||||
manifest.with_extension(extension)
|
||||
}
|
||||
|
||||
/// The one call the batch shares: what the member whose turn it is runs. Every `target` is an
|
||||
/// [`entry`]. One prompt is asked; every member then hears its own installer's exit code, a
|
||||
/// declined prompt cancels the batch, and a session that cannot start sends the members back to
|
||||
/// installing one by one.
|
||||
#[cfg(windows)]
|
||||
pub(super) fn call(_command: &[OsString], targets: &[OsString]) -> Vec<Result<(), String>> {
|
||||
use artcraft_launcher_core::protocol::CANCELLED;
|
||||
|
||||
use super::msi_batch;
|
||||
|
||||
// A member joins the session only if its package is held and checks out again; anything
|
||||
// else falls back to installing by itself, or hears its own error.
|
||||
let mut outcomes: Vec<Result<(), String>> = Vec::with_capacity(targets.len());
|
||||
let mut joined: Vec<(usize, Entry)> = Vec::new();
|
||||
let mut held: Vec<msi_batch::Held> = Vec::new();
|
||||
for (at, target) in targets.iter().enumerate() {
|
||||
match parse(target.as_os_str()) {
|
||||
Some(entry) => match msi_batch::hold(&entry.msi, &entry.sha256) {
|
||||
Ok(file) => {
|
||||
held.push(file);
|
||||
outcomes.push(Ok(()));
|
||||
joined.push((at, entry));
|
||||
}
|
||||
Err(e) => outcomes.push(Err(e)),
|
||||
},
|
||||
None => outcomes.push(Err(NO_SESSION.into())),
|
||||
}
|
||||
}
|
||||
let Some((_, first)) = joined.first() else {
|
||||
return outcomes;
|
||||
};
|
||||
let Some(dir) = first.msi.parent() else {
|
||||
return without_session(outcomes, &joined);
|
||||
};
|
||||
let (manifest, token) = match prepare(&joined, dir, &mut held) {
|
||||
Ok(prepared) => prepared,
|
||||
Err(e) => {
|
||||
log::warn!("the shared install session could not be prepared ({e}); installing one by one");
|
||||
return without_session(outcomes, &joined);
|
||||
}
|
||||
};
|
||||
let (results, pid_file) = (sibling(&manifest, "results"), sibling(&manifest, "pid"));
|
||||
match ask_once(dir, &manifest, joined.len()) {
|
||||
Prompt::Declined => {
|
||||
log::info!("the shared permission prompt was declined");
|
||||
for (at, _) in &joined {
|
||||
outcomes[*at] = Err(CANCELLED.to_string());
|
||||
}
|
||||
}
|
||||
Prompt::Failed(e) => {
|
||||
log::warn!("the elevated session could not start ({e}); installing one by one");
|
||||
outcomes = without_session(outcomes, &joined);
|
||||
}
|
||||
Prompt::Given => match wait_until_done(&pid_file, &results, &token) {
|
||||
SessionEnd::Done(codes) => {
|
||||
for (at, entry) in &joined {
|
||||
outcomes[*at] = match codes.iter().find(|(app, _)| app == &entry.app) {
|
||||
// A negative code is "no exit code" (see [`run_installer`]): no installer
|
||||
// ran, so there is no log to point at.
|
||||
Some((_, code)) => super::explain(Some(*code)).map_err(|e| {
|
||||
if *code == 1602 || *code < 0 { e } else { format!("{e}. Its log is at {}", super::msi_log(&entry.msi).display()) }
|
||||
}),
|
||||
None => Err(format!("the shared install session never reported {}'s result", entry.app)),
|
||||
};
|
||||
}
|
||||
}
|
||||
// The session is over and said nothing: nothing of it is running, so the members may
|
||||
// safely install one by one.
|
||||
SessionEnd::OverWithoutReport => {
|
||||
log::warn!("the elevated session ended without reporting; installing one by one");
|
||||
outcomes = without_session(outcomes, &joined);
|
||||
}
|
||||
// The session was launched and cannot be shown to be over: falling back would race
|
||||
// whatever it may still install, so the members hear an error instead.
|
||||
SessionEnd::Unknown => {
|
||||
log::warn!("the elevated session could not be watched; nothing was retried here");
|
||||
for (at, _) in &joined {
|
||||
outcomes[*at] = Err("the shared install session couldn't be watched. Try again.".into());
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
// The held files close before the session's own are removed: an open handle would keep the
|
||||
// manifest undeletable on Windows (its share mode allows reading only).
|
||||
drop(held);
|
||||
for file in [&manifest, &pid_file, &results] {
|
||||
let _ = std::fs::remove_file(file);
|
||||
}
|
||||
outcomes
|
||||
}
|
||||
|
||||
/// Writes the manifest the elevated copy reads, holding it and every package unchanged for as
|
||||
/// long as the session runs. The name is only taken once its results and process-id files are
|
||||
/// free too: a leftover of another session must never be mistaken for this one's.
|
||||
#[cfg(windows)]
|
||||
fn prepare(joined: &[(usize, Entry)], dir: &Path, held: &mut Vec<super::msi_batch::Held>) -> Result<(PathBuf, String), String> {
|
||||
use std::io::Write as _;
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
|
||||
/// Others may read a held file, but not write, rename or delete it (see [`msi_batch::hold`]).
|
||||
const FILE_SHARE_READ: u32 = 0x1;
|
||||
|
||||
let base = format!("batch-{}-{}", std::process::id(), crate::now());
|
||||
let manifest = (0..)
|
||||
.map(|n| dir.join(format!("{base}{}.json", if n == 0 { String::new() } else { n.to_string() })))
|
||||
.find(|manifest| [manifest, &sibling(manifest, "results"), &sibling(manifest, "pid")].iter().all(|p| !p.exists()))
|
||||
.ok_or("no free name for the batch manifest")?;
|
||||
let token = session_token();
|
||||
let text = serde_json::to_string(&Manifest { token: token.clone(), msis: joined.iter().map(|(_, entry)| entry.clone()).collect() })
|
||||
.map_err(|e| format!("couldn't describe the batch ({e})"))?;
|
||||
let mut file = std::fs::File::options()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.share_mode(FILE_SHARE_READ)
|
||||
.open(&manifest)
|
||||
.map_err(|e| format!("couldn't write the batch manifest ({e})"))?;
|
||||
file.write_all(text.as_bytes()).map_err(|e| format!("couldn't write the batch manifest ({e})"))?;
|
||||
held.push(super::msi_batch::Held::keep(file));
|
||||
Ok((manifest, token))
|
||||
}
|
||||
|
||||
/// This session's unguessable name for its results, so a file from any other session (or put in
|
||||
/// one's place) cannot pass for this one's report.
|
||||
fn session_token() -> String {
|
||||
let random = getrandom::u64().unwrap_or_else(|_| (std::process::id() as u64) ^ ((crate::now() as u64) << 32));
|
||||
format!("{random:016x}")
|
||||
}
|
||||
|
||||
/// The members of the session are told it never happened: each installs by itself, the way a
|
||||
/// single app always installs.
|
||||
#[cfg(windows)]
|
||||
fn without_session(mut outcomes: Vec<Result<(), String>>, joined: &[(usize, Entry)]) -> Vec<Result<(), String>> {
|
||||
for (at, _) in joined {
|
||||
outcomes[*at] = Err(NO_SESSION.into());
|
||||
}
|
||||
outcomes
|
||||
}
|
||||
|
||||
/// What asking for the one prompt came to.
|
||||
#[cfg(windows)]
|
||||
enum Prompt {
|
||||
Given,
|
||||
/// The person answered the prompt with No.
|
||||
Declined,
|
||||
/// The elevated copy could not be started at all.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// Starts the launcher's own exe elevated on the manifest: the one prompt of the batch.
|
||||
#[cfg(windows)]
|
||||
fn ask_once(dir: &Path, manifest: &Path, apps: usize) -> Prompt {
|
||||
use winsafe::SHELLEXECUTEINFO;
|
||||
use winsafe::ShellExecuteEx;
|
||||
use winsafe::co;
|
||||
|
||||
let exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("artcraft-launcher.exe"));
|
||||
let (Some(exe), Some(manifest), Some(dir)) = (super::msi_batch::text(&exe).ok(), super::msi_batch::text(manifest).ok(), dir.to_str()) else {
|
||||
return Prompt::Failed("unusual characters in a path".into());
|
||||
};
|
||||
let parameters = format!("--install-msis \"{manifest}\"");
|
||||
log::info!("asking once for permission to install {apps} apps together");
|
||||
match ShellExecuteEx(&SHELLEXECUTEINFO {
|
||||
verb: Some("runas"),
|
||||
file: exe,
|
||||
parameters: Some(parameters.as_str()),
|
||||
directory: Some(dir),
|
||||
show: co::SW::SHOW,
|
||||
..Default::default()
|
||||
}) {
|
||||
Ok(()) => Prompt::Given,
|
||||
Err(e) if e == co::ERROR::CANCELLED => Prompt::Declined,
|
||||
Err(e) => Prompt::Failed(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// How the elevated session ended, as far as the waiting side can tell.
|
||||
#[cfg(windows)]
|
||||
enum SessionEnd {
|
||||
/// It finished and reported; each app's installer exit code is here.
|
||||
Done(Vec<(String, i32)>),
|
||||
/// It is definitely over (its process is gone) but said nothing: the members may safely
|
||||
/// install one by one, because nothing of the session is running any more.
|
||||
OverWithoutReport,
|
||||
/// It was launched and cannot be shown to be over. Falling back here would race whatever it
|
||||
/// may still install, so the members hear an error instead.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Waits for the elevated copy: it writes its process id as its first act and its results as its
|
||||
/// last, so waiting for the process to end is waiting for the results. Only a session that is
|
||||
/// *shown* to be over (its process waited out, or its process id gone) lets the members fall
|
||||
/// back to installing one by one; one that merely cannot be seen is never fallen back from.
|
||||
#[cfg(windows)]
|
||||
fn wait_until_done(pid_file: &Path, results: &Path, token: &str) -> SessionEnd {
|
||||
use winsafe::HPROCESS;
|
||||
use winsafe::co;
|
||||
|
||||
let deadline = std::time::Instant::now() + STARTED_WITHIN;
|
||||
let pid = loop {
|
||||
if let Ok(text) = std::fs::read_to_string(pid_file)
|
||||
&& let Ok(pid) = text.trim().parse::<u32>()
|
||||
{
|
||||
break pid;
|
||||
}
|
||||
if std::time::Instant::now() > deadline {
|
||||
// The prompt was answered and the copy launched, but it never even said it had
|
||||
// started: whether a slow antivirus still has it, or it died at once, is not ours
|
||||
// to guess. Falling back is not safe either way.
|
||||
return SessionEnd::Unknown;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(500));
|
||||
};
|
||||
// The copy exists; its handle may not be ours at once. "Cannot open" that keeps failing past
|
||||
// the grace means the session is there but cannot be watched — never that it is gone.
|
||||
let opened_by = std::time::Instant::now() + OPEN_GRACE;
|
||||
loop {
|
||||
match HPROCESS::OpenProcess(co::PROCESS::SYNCHRONIZE, false, pid) {
|
||||
Ok(process) => {
|
||||
// None is INFINITE: the session ends when its last progress window closes.
|
||||
if !process.WaitForSingleObject(None).is_ok_and(|wait| wait == co::WAIT::OBJECT_0) {
|
||||
log::warn!("waiting for the elevated session failed");
|
||||
return SessionEnd::Unknown;
|
||||
}
|
||||
break;
|
||||
}
|
||||
// ERROR_INVALID_PARAMETER is what a process id that no longer exists answers.
|
||||
Err(e) if e == co::ERROR::INVALID_PARAMETER => break,
|
||||
Err(e) if std::time::Instant::now() > opened_by => {
|
||||
log::warn!("the elevated session could not be opened to be waited for ({e})");
|
||||
return SessionEnd::Unknown;
|
||||
}
|
||||
Err(_) => std::thread::sleep(std::time::Duration::from_millis(500)),
|
||||
}
|
||||
}
|
||||
match std::fs::read_to_string(results) {
|
||||
Ok(reported) => match parse_results(&reported, token) {
|
||||
codes if codes.is_empty() => SessionEnd::OverWithoutReport,
|
||||
codes => SessionEnd::Done(codes),
|
||||
},
|
||||
Err(_) => SessionEnd::OverWithoutReport,
|
||||
}
|
||||
}
|
||||
|
||||
/// The results file: the session's token, then one app and its installer's exit code per line.
|
||||
/// A file whose first line is not this session's token is not this session's and is ignored.
|
||||
fn parse_results(text: &str, token: &str) -> Vec<(String, i32)> {
|
||||
let Some((first, rest)) = text.split_once('\n') else { return Vec::new() };
|
||||
if first != token {
|
||||
return Vec::new();
|
||||
}
|
||||
rest.lines()
|
||||
.filter_map(|line| {
|
||||
let (app, code) = line.split_once('\t')?;
|
||||
let code = code.trim().parse::<i32>().ok()?;
|
||||
(!app.is_empty()).then(|| (app.to_string(), code))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Writes the results file, never over anything that already exists.
|
||||
fn write_results(path: &Path, token: &str, codes: &[(String, i32)]) -> Result<(), String> {
|
||||
use std::io::Write as _;
|
||||
|
||||
let mut text = String::from(token);
|
||||
for (app, code) in codes {
|
||||
text.push_str(&format!("\n{app}\t{code}"));
|
||||
}
|
||||
let mut file = std::fs::File::options().write(true).create_new(true).open(path).map_err(|e| format!("couldn't write the batch results ({e})"))?;
|
||||
file.write_all(text.as_bytes()).map_err(|e| format!("couldn't write the batch results ({e})"))
|
||||
}
|
||||
|
||||
/// The elevated half of the session: what the launcher runs as `--install-msis <manifest>`.
|
||||
/// Re-checks every package against its published checksum (held open, so the checked bytes are
|
||||
/// the installed ones), builds each installer's arguments from that held package, runs Windows
|
||||
/// Installer on each in turn, and writes each app's exit code to the results file beside the
|
||||
/// manifest — every app's, however the others went, so one failed member never sends the whole
|
||||
/// batch back to one-by-one installs and their prompts. `Ok` means the session ran, whatever the
|
||||
/// installers themselves decided: their outcomes are the codes in the file.
|
||||
#[cfg(windows)]
|
||||
pub fn run_elevated(manifest: &Path) -> Result<(), String> {
|
||||
let text = std::fs::read_to_string(manifest).map_err(|e| format!("couldn't read the batch manifest ({e})"))?;
|
||||
let session: Manifest = serde_json::from_str(&text).map_err(|e| format!("couldn't understand the batch manifest ({e})"))?;
|
||||
let dir = manifest.parent().ok_or("the batch manifest has no folder")?;
|
||||
// The session only ever touches packages beside its own manifest, in the launcher's
|
||||
// downloads folder.
|
||||
for entry in &session.msis {
|
||||
if entry.msi.parent() != Some(dir) {
|
||||
return Err(format!("{} is not beside the batch manifest", entry.msi.display()));
|
||||
}
|
||||
}
|
||||
let pid_file = sibling(manifest, "pid");
|
||||
std::fs::write(&pid_file, std::process::id().to_string()).map_err(|e| format!("couldn't say the batch session had started ({e})"))?;
|
||||
let mut codes = Vec::new();
|
||||
for entry in &session.msis {
|
||||
codes.push((entry.app.clone(), install_one(entry)));
|
||||
}
|
||||
write_results(&sibling(manifest, "results"), &session.token, &codes)?;
|
||||
let _ = std::fs::remove_file(&pid_file);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One package of the session, held while its installer runs. The installer's arguments are
|
||||
/// built here, from the held package itself: a manifest can say where and in which context the
|
||||
/// checked file installs, never which file installs. A package that cannot be held, checked or
|
||||
/// described reports "no exit code" ([`run_installer`]'s `-1`); the rest of the session carries
|
||||
/// on under the one prompt.
|
||||
#[cfg(windows)]
|
||||
fn install_one(entry: &Entry) -> i32 {
|
||||
let installed = (|| -> Result<i32, String> {
|
||||
// The hold is the point: it keeps the package unchanged through the installer run, so
|
||||
// the checked bytes are the installed ones. Its name is never read — the file staying
|
||||
// open until the end of this closure is the whole job.
|
||||
let _held = super::msi_batch::hold(&entry.msi, &entry.sha256)?;
|
||||
let line = super::msi_batch::line(&entry.msi, entry.destination.as_deref(), entry.scope)?;
|
||||
log::info!("{}: installing under the shared prompt", entry.app);
|
||||
run_installer(&line)
|
||||
})();
|
||||
match installed {
|
||||
Ok(status) => status,
|
||||
Err(e) => {
|
||||
log::warn!("{}: {e}", entry.app);
|
||||
-1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows Installer on one package of the session: a progress window and no restart, the same
|
||||
/// arguments a single install runs. `Err` only when it couldn't be started at all.
|
||||
#[cfg(windows)]
|
||||
fn run_installer(line: &str) -> Result<i32, String> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
|
||||
let status = crate::process::command(super::windows::msiexec())
|
||||
.raw_arg(line)
|
||||
.status()
|
||||
.map_err(|e| format!("couldn't start the Windows Installer ({e})"))?;
|
||||
Ok(status.code().unwrap_or(-1))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn entry(app: &str, msi: &Path) -> Entry {
|
||||
Entry {
|
||||
app: app.to_string(),
|
||||
msi: msi.to_path_buf(),
|
||||
sha256: "abc123".into(),
|
||||
destination: Some(Path::new(r"C:\Program Files\Photocraft").to_path_buf()),
|
||||
scope: Some(MsiScope::PerMachine),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_survives_the_queue_as_json() {
|
||||
let entry = entry("photocraft", Path::new(r"C:\Downloads\photocraft.msi"));
|
||||
let target = serde_json::to_string(&entry).unwrap();
|
||||
// An entry carries where and in which context to install, never a command line: the
|
||||
// elevated side builds the installer's arguments from the held package itself.
|
||||
assert!(!target.contains("line"));
|
||||
let back = parse(&OsString::from(target)).unwrap();
|
||||
assert_eq!(back.app, entry.app);
|
||||
assert_eq!(back.msi, entry.msi);
|
||||
assert_eq!(back.sha256, entry.sha256);
|
||||
assert_eq!(back.destination, entry.destination);
|
||||
assert_eq!(back.scope, entry.scope);
|
||||
assert!(parse(&OsString::from("not json")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_results_survive_their_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let results = dir.path().join("batch.results");
|
||||
let token = "0123456789abcdef";
|
||||
let codes = vec![
|
||||
(String::from("photocraft"), 0),
|
||||
(String::from("lightcraft"), 1603),
|
||||
(String::from("filmcraft"), 3010),
|
||||
(String::from("wordcraft"), -1),
|
||||
];
|
||||
write_results(&results, token, &codes).unwrap();
|
||||
assert_eq!(parse_results(&std::fs::read_to_string(&results).unwrap(), token), codes);
|
||||
// A results file is never written over anything: a second session with the same name
|
||||
// refuses rather than report for it.
|
||||
assert!(write_results(&results, token, &codes).is_err());
|
||||
assert_eq!(
|
||||
parse_results("photocraft\t0\n\njunk\nlightcraft\t3010\n", token),
|
||||
Vec::<(String, i32)>::new(),
|
||||
"a report without this session's token is not this session's"
|
||||
);
|
||||
// A leftover from another session (a different token) is never read as this one's.
|
||||
assert_eq!(parse_results(&std::fs::read_to_string(&results).unwrap(), "ffffffffffffffff"), Vec::<(String, i32)>::new());
|
||||
assert_eq!(
|
||||
parse_results(&format!("{token}\nphotocraft\t0\n\njunk\nlightcraft\t3010\n"), token),
|
||||
vec![(String::from("photocraft"), 0), (String::from("lightcraft"), 3010)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_tokens_differ() {
|
||||
let seen: std::collections::HashSet<String> = (0..64).map(|_| session_token()).collect();
|
||||
assert_eq!(seen.len(), 64, "every session's token is its own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_session_files_sit_beside_the_manifest() {
|
||||
let manifest = Path::new(r"C:\Cache\downloads\batch-123-45.json");
|
||||
assert_eq!(sibling(manifest, "results"), Path::new(r"C:\Cache\downloads\batch-123-45.results"));
|
||||
assert_eq!(sibling(manifest, "pid"), Path::new(r"C:\Cache\downloads\batch-123-45.pid"));
|
||||
}
|
||||
}
|
||||
+337
-27
@@ -4,15 +4,80 @@
|
||||
//! while another runs fails. Jobs wait their turn here instead. Where the installer takes
|
||||
//! several packages, the jobs waiting for the same command share one call, so the password is
|
||||
//! asked for once.
|
||||
//!
|
||||
//! Jobs started together by one "update all" also *arrive* together: each waits for the others'
|
||||
//! downloads ([`Gather`]) before the queue makes its call, so one call covers the whole batch.
|
||||
//! Without that, a call goes out as soon as the first download finishes and every app gets its
|
||||
//! own password prompt.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
|
||||
use std::sync::Arc;
|
||||
use std::sync::Condvar;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::MutexGuard;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use artcraft_launcher_core::protocol::CANCELLED;
|
||||
|
||||
type Outcome = Result<(), String>;
|
||||
|
||||
/// What one installer call does with its command and the targets sharing it: one outcome per
|
||||
/// target, in their order.
|
||||
type Exec<'a> = dyn Fn(&[OsString], &[OsString]) -> Vec<Outcome> + 'a;
|
||||
|
||||
/// What a job of a call that never reported hears (the call's job died mid-call).
|
||||
const INTERRUPTED: &str = "the system installer was interrupted";
|
||||
|
||||
/// How long a gathered job waits for the rest of its batch. The gate opens then even if a
|
||||
/// member is still nowhere near the installer, so a stuck download can't hold the others back
|
||||
/// indefinitely.
|
||||
const GATHER_TIMEOUT: Duration = Duration::from_secs(600);
|
||||
|
||||
/// The members of one batch (an "update all") that share a single permission prompt.
|
||||
///
|
||||
/// Every member counts down exactly once: [`Queue::batched_when`] does it when the member
|
||||
/// reaches the installer queue, and [`Gather::leave`] when a member ends before that (its
|
||||
/// download failed, it was cancelled, or its install needs no prompt at all). While anyone is
|
||||
/// still on the way, the members already waiting hold back from starting the installer call;
|
||||
/// once the count reaches zero — or [`GATHER_TIMEOUT`] passes — the call goes out with every
|
||||
/// waiting member of the batch in it.
|
||||
#[derive(Clone)]
|
||||
pub struct Gather {
|
||||
remaining: Arc<AtomicUsize>,
|
||||
until: Instant,
|
||||
}
|
||||
|
||||
/// The same batch, not two batches that happen to count the same: the handle a job carries is
|
||||
/// its batch's identity (see [`Queue::gather`], whose members all share one).
|
||||
impl PartialEq for Gather {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
Arc::ptr_eq(&self.remaining, &other.remaining)
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Gather {}
|
||||
|
||||
impl Gather {
|
||||
/// A member that will not reach the installer queue after all: its download failed, it was
|
||||
/// cancelled, or its install needs no prompt. The rest of the batch must not wait for it.
|
||||
pub fn leave(&self) {
|
||||
self.step();
|
||||
}
|
||||
|
||||
/// One member is accounted for: waiting at the queue (arrived) or gone for good (left).
|
||||
fn step(&self) {
|
||||
let _ = self.remaining.try_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1));
|
||||
}
|
||||
|
||||
/// Whether the batch may make its call: everyone has arrived or left, or the wait is over.
|
||||
pub(crate) fn open(&self) -> bool {
|
||||
self.remaining.load(Ordering::SeqCst) == 0 || Instant::now() >= self.until
|
||||
}
|
||||
}
|
||||
|
||||
struct Waiting {
|
||||
id: u64,
|
||||
command: Vec<OsString>,
|
||||
@@ -33,12 +98,13 @@ pub struct Queue {
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
/// Frees the installer when a call ends (even by unwinding) and hands its outcome to the other
|
||||
/// jobs of the call.
|
||||
/// Frees the installer when a call ends (even by unwinding) and hands each of the other jobs of
|
||||
/// the call its outcome.
|
||||
struct Turn<'a> {
|
||||
queue: &'a Queue,
|
||||
others: Vec<u64>,
|
||||
outcome: Outcome,
|
||||
/// The other jobs of the call and the outcome each is to hear: the call's per-job results
|
||||
/// once it ended, or the failure each was given here if it never reported.
|
||||
others: Vec<(u64, Outcome)>,
|
||||
}
|
||||
|
||||
impl Drop for Turn<'_> {
|
||||
@@ -46,8 +112,8 @@ impl Drop for Turn<'_> {
|
||||
let mut state = self.queue.lock();
|
||||
state.busy = false;
|
||||
state.running.clear();
|
||||
for id in self.others.drain(..) {
|
||||
state.finished.push((id, self.outcome.clone()));
|
||||
for (id, outcome) in self.others.drain(..) {
|
||||
state.finished.push((id, outcome));
|
||||
}
|
||||
self.queue.changed.notify_all();
|
||||
}
|
||||
@@ -65,6 +131,18 @@ impl Queue {
|
||||
Self { state: Mutex::new(state), changed: Condvar::new() }
|
||||
}
|
||||
|
||||
/// A batch of `members` jobs that will install behind one permission prompt (see
|
||||
/// [`Gather`]). The count is the jobs actually started: members already running their own
|
||||
/// job are not part of the batch.
|
||||
pub fn gather(&self, members: usize) -> Gather {
|
||||
self.gather_within(members, GATHER_TIMEOUT)
|
||||
}
|
||||
|
||||
/// [`gather`](Self::gather) with the wait cap spelled out (the tests take a short one).
|
||||
fn gather_within(&self, members: usize, within: Duration) -> Gather {
|
||||
Gather { remaining: Arc::new(AtomicUsize::new(members)), until: Instant::now() + within }
|
||||
}
|
||||
|
||||
fn lock(&self) -> MutexGuard<'_, State> {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
@@ -101,28 +179,39 @@ impl Queue {
|
||||
if waited {
|
||||
turn(false);
|
||||
}
|
||||
let _turn = Turn { queue: self, others: Vec::new(), outcome: Ok(()) };
|
||||
let _turn = Turn { queue: self, others: Vec::new() };
|
||||
Some(work())
|
||||
}
|
||||
|
||||
/// Runs `exec(command, targets)` once no other installer is running, with the targets of
|
||||
/// every job waiting for the same `command`, and gives each of those jobs its outcome.
|
||||
/// `turn(true)` says the job has to wait, `turn(false)` that its call has started.
|
||||
/// every job waiting for the same `command`, and gives each of those jobs its own outcome
|
||||
/// from the call. `turn(true)` says the job has to wait, `turn(false)` that its call has
|
||||
/// started.
|
||||
///
|
||||
/// A job that is waiting leaves with [`CANCELLED`] once `cancelled` (asked a few times a
|
||||
/// second, so it must not block) says so; once its call has started it sees it through.
|
||||
pub fn batched(
|
||||
///
|
||||
/// `exec` returns one outcome per target, in their order.
|
||||
pub fn batched_when(
|
||||
&self,
|
||||
gather: Option<Gather>,
|
||||
command: Vec<OsString>,
|
||||
target: OsString,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
turn: &mut dyn FnMut(bool),
|
||||
exec: &dyn Fn(&[OsString], &[OsString]) -> Outcome,
|
||||
exec: &Exec<'_>,
|
||||
) -> Outcome {
|
||||
let mut state = self.lock();
|
||||
let id = state.next_id;
|
||||
state.next_id = state.next_id.wrapping_add(1);
|
||||
state.waiting.push(Waiting { id, command: command.clone(), target });
|
||||
drop(state);
|
||||
// Arrived: the rest of the batch is no longer held back by this one. The waiting entry
|
||||
// is in place first, so whoever finds the gate open finds every arrived member waiting.
|
||||
if let Some(gather) = &gather {
|
||||
gather.step();
|
||||
}
|
||||
let mut state = self.lock();
|
||||
let (mut waited, mut started) = (false, false);
|
||||
loop {
|
||||
if let Some(at) = state.finished.iter().position(|(done, _)| *done == id) {
|
||||
@@ -134,7 +223,10 @@ impl Queue {
|
||||
state.waiting.retain(|w| w.id != id);
|
||||
return Err(CANCELLED.into());
|
||||
}
|
||||
if !running && !state.busy {
|
||||
// An unopened gather holds the job back even on an idle queue: the call must cover
|
||||
// the whole batch, so it goes out only once everyone has arrived or left.
|
||||
let held_back = gather.as_ref().is_some_and(|gather| !gather.open());
|
||||
if !running && !state.busy && !held_back {
|
||||
break;
|
||||
}
|
||||
let tell = if running { waited && !started } else { !waited };
|
||||
@@ -156,12 +248,33 @@ impl Queue {
|
||||
if waited {
|
||||
turn(false);
|
||||
}
|
||||
let others = batch.iter().map(|w| w.id).filter(|other| *other != id).collect();
|
||||
let targets: Vec<OsString> = batch.into_iter().map(|w| w.target).collect();
|
||||
let mut call = Turn { queue: self, others, outcome: Err("the system installer was interrupted".into()) };
|
||||
let outcome = exec(&command, &targets);
|
||||
call.outcome.clone_from(&outcome);
|
||||
outcome
|
||||
let mine = batch.iter().position(|w| w.id == id);
|
||||
let others = batch.iter().filter(|w| w.id != id).map(|w| (w.id, Err(INTERRUPTED.to_string()))).collect();
|
||||
let mut call = Turn { queue: self, others };
|
||||
let targets: Vec<OsString> = batch.iter().map(|w| w.target.clone()).collect();
|
||||
let outcomes = exec(&command, &targets);
|
||||
for (at, waiting) in batch.iter().enumerate() {
|
||||
if waiting.id != id
|
||||
&& let Some(outcome) = outcomes.get(at)
|
||||
&& let Some(heard) = call.others.iter_mut().find(|(other, _)| *other == waiting.id)
|
||||
{
|
||||
heard.1.clone_from(outcome);
|
||||
}
|
||||
}
|
||||
mine.and_then(|at| outcomes.get(at)).cloned().unwrap_or_else(|| Err(INTERRUPTED.to_string()))
|
||||
}
|
||||
|
||||
/// [`batched_when`](Self::batched_when) for a job on its own: the call's one outcome is
|
||||
/// what every job of it hears.
|
||||
pub fn batched(
|
||||
&self,
|
||||
command: Vec<OsString>,
|
||||
target: OsString,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
turn: &mut dyn FnMut(bool),
|
||||
exec: &dyn Fn(&[OsString], &[OsString]) -> Outcome,
|
||||
) -> Outcome {
|
||||
self.batched_when(None, command, target, cancelled, turn, &|command, targets| vec![exec(command, targets); targets.len()])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,14 +318,26 @@ mod tests {
|
||||
calls.sort();
|
||||
calls
|
||||
}
|
||||
|
||||
/// Up to `secs` for the first call to be made, checked every 10 ms.
|
||||
fn soon(&self, secs: u64) -> bool {
|
||||
(0..secs * 100).any(|_| {
|
||||
if !self.0.lock().unwrap().is_empty() {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts `jobs` (command, target) while an install is running, so they all wait; lets that
|
||||
/// install finish once every one of them has said it is waiting. Returns their outcomes.
|
||||
#[allow(clippy::type_complexity)] // one shared installer call, spelled out for the threads
|
||||
fn behind_a_running_install(
|
||||
queue: &Queue,
|
||||
jobs: &[(Vec<OsString>, &str)],
|
||||
exec: &(dyn Fn(&[OsString], &[OsString]) -> Outcome + Sync),
|
||||
exec: &(dyn Fn(&[OsString], &[OsString]) -> Vec<Outcome> + Sync),
|
||||
) -> Vec<Option<Outcome>> {
|
||||
let (started, has_started) = mpsc::channel();
|
||||
let (release, released) = mpsc::channel::<()>();
|
||||
@@ -235,7 +360,7 @@ mod tests {
|
||||
turned.send(()).unwrap();
|
||||
}
|
||||
};
|
||||
queue.batched(command.clone(), os(target), &|| false, &mut turn, exec)
|
||||
queue.batched_when(None, command.clone(), os(target), &|| false, &mut turn, &|command, targets| exec(command, targets))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -254,12 +379,27 @@ mod tests {
|
||||
let jobs = [(install(), "a.deb"), (install(), "b.deb"), (remove(), "photocraft"), (install(), "c.deb")];
|
||||
let results = behind_a_running_install(&queue, &jobs, &|command, targets| {
|
||||
calls.record(command, targets);
|
||||
Ok(())
|
||||
vec![Ok(()); targets.len()]
|
||||
});
|
||||
assert_eq!(results, vec![Some(Ok(())); 4]);
|
||||
assert_eq!(calls.taken(), [line(&["apt-get", "install", "-y", "a.deb", "b.deb", "c.deb"]), line(&["apt-get", "remove", "-y", "photocraft"])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_job_of_a_call_hears_its_own_outcome() {
|
||||
let queue = Queue::new();
|
||||
let calls = Calls::default();
|
||||
let jobs = [(install(), "a.deb"), (install(), "b.deb")];
|
||||
let results = behind_a_running_install(&queue, &jobs, &|command, targets| {
|
||||
calls.record(command, targets);
|
||||
targets.iter().map(|t| if t == &os("b.deb") { Err("b.deb failed".to_string()) } else { Ok(()) }).collect()
|
||||
});
|
||||
// b.deb failed; a.deb, in the same call, did not.
|
||||
assert!(results.contains(&Some(Err("b.deb failed".to_string()))), "{results:?}");
|
||||
assert!(results.contains(&Some(Ok(()))), "{results:?}");
|
||||
assert_eq!(calls.taken().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installers_never_run_at_the_same_time() {
|
||||
let queue = Queue::new();
|
||||
@@ -379,7 +519,7 @@ mod tests {
|
||||
let jobs = [(install(), "a.deb"), (install(), "b.deb"), (install(), "c.deb")];
|
||||
let results = behind_a_running_install(&queue, &jobs, &|command, targets| {
|
||||
calls.record(command, targets);
|
||||
Err("cancelled".into())
|
||||
vec![Err("cancelled".into()); targets.len()]
|
||||
});
|
||||
assert_eq!(calls.taken().len(), 1);
|
||||
assert_eq!(results, vec![Some(Err("cancelled".to_string())); 3]);
|
||||
@@ -404,14 +544,21 @@ mod tests {
|
||||
has_started.recv().unwrap();
|
||||
let exec = |command: &[OsString], targets: &[OsString]| {
|
||||
calls.record(command, targets);
|
||||
Ok(())
|
||||
vec![Ok(()); targets.len()]
|
||||
};
|
||||
let turned_too = turned.clone();
|
||||
let leaving = scope.spawn(move || {
|
||||
queue.batched(install(), os("a.deb"), &|| cancel.load(Ordering::SeqCst), &mut |waiting| turned.send(waiting).unwrap(), &exec)
|
||||
queue.batched_when(
|
||||
None,
|
||||
install(),
|
||||
os("a.deb"),
|
||||
&|| cancel.load(Ordering::SeqCst),
|
||||
&mut |waiting| turned.send(waiting).unwrap(),
|
||||
&exec,
|
||||
)
|
||||
});
|
||||
let staying =
|
||||
scope.spawn(move || queue.batched(install(), os("b.deb"), &|| false, &mut |waiting| turned_too.send(waiting).unwrap(), &exec));
|
||||
let staying = scope
|
||||
.spawn(move || queue.batched_when(None, install(), os("b.deb"), &|| false, &mut |waiting| turned_too.send(waiting).unwrap(), &exec));
|
||||
assert!(turns.recv().unwrap() && turns.recv().unwrap());
|
||||
cancel.store(true, Ordering::SeqCst);
|
||||
// It leaves while the other install is still running, without waiting for its turn.
|
||||
@@ -509,4 +656,167 @@ mod tests {
|
||||
assert!(results.contains(&Some(Err("the system installer was interrupted".to_string()))), "{results:?}");
|
||||
assert_eq!(queue.batched(install(), os("c.deb"), &|| false, &mut |_| {}, &|_, _| Ok(())), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gate_opens_once_every_member_has_arrived_or_left() {
|
||||
let queue = Queue::new();
|
||||
let gather = queue.gather(3);
|
||||
gather.leave();
|
||||
assert!(!gather.open(), "two members are still on the way");
|
||||
gather.leave();
|
||||
assert!(!gather.open(), "one member is still on the way");
|
||||
gather.leave();
|
||||
assert!(gather.open(), "the last one left before reaching the installer");
|
||||
let single = queue.gather(1);
|
||||
single.leave();
|
||||
// One member, counted twice by mistake, still leaves an open gate.
|
||||
single.leave();
|
||||
assert!(single.open());
|
||||
}
|
||||
|
||||
/// Starts one gathered job per entry, `stagger` milliseconds apart, on an idle queue. The
|
||||
/// first would run at once if the gather didn't hold it back.
|
||||
#[allow(clippy::type_complexity)] // one shared installer call, spelled out for the threads
|
||||
fn gathered(
|
||||
queue: &Queue,
|
||||
gather: &Gather,
|
||||
jobs: &[(Vec<OsString>, &str)],
|
||||
stagger: u64,
|
||||
exec: &(dyn Fn(&[OsString], &[OsString]) -> Vec<Outcome> + Sync),
|
||||
) -> Vec<Option<Outcome>> {
|
||||
std::thread::scope(|scope| {
|
||||
let handles: Vec<_> = jobs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(at, (command, target))| {
|
||||
let gather = gather.clone();
|
||||
scope.spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(stagger * at as u64));
|
||||
queue.batched_when(Some(gather), command.clone(), os(target), &|| false, &mut |_| {}, &|command, targets| {
|
||||
exec(command, targets)
|
||||
})
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles.into_iter().map(|h| h.join().ok()).collect()
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gathered_batch_makes_one_call_even_when_arrivals_are_staggered() {
|
||||
let queue = Queue::new();
|
||||
let calls = Calls::default();
|
||||
let gather = queue.gather(3);
|
||||
let jobs = [(install(), "a.deb"), (install(), "b.deb"), (install(), "c.deb")];
|
||||
let results = gathered(&queue, &gather, &jobs, 30, &|command, targets| {
|
||||
calls.record(command, targets);
|
||||
vec![Ok(()); targets.len()]
|
||||
});
|
||||
assert_eq!(results, vec![Some(Ok(())); 3]);
|
||||
assert_eq!(calls.taken(), [line(&["apt-get", "install", "-y", "a.deb", "b.deb", "c.deb"])], "all three in one call, not one each");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_that_never_arrives_does_not_hold_the_batch_back() {
|
||||
let queue = Queue::new();
|
||||
let calls = Calls::default();
|
||||
// The wait cap is an hour: only the missing member's `leave` can open the gate.
|
||||
let gather = queue.gather_within(2, Duration::from_secs(3600));
|
||||
let arrived = std::thread::scope(|scope| {
|
||||
let job = scope.spawn(|| {
|
||||
queue.batched_when(Some(gather.clone()), install(), os("a.deb"), &|| false, &mut |_| {}, &|command, targets| {
|
||||
calls.record(command, targets);
|
||||
vec![Ok(()); targets.len()]
|
||||
})
|
||||
});
|
||||
// The other member's download failed before it ever reached the queue.
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
gather.leave();
|
||||
job.join().unwrap()
|
||||
});
|
||||
assert_eq!(arrived, Ok(()));
|
||||
assert!(calls.soon(5), "the call went out once the missing member left");
|
||||
assert_eq!(calls.taken(), [line(&["apt-get", "install", "-y", "a.deb"])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gather_opens_after_its_wait_is_over() {
|
||||
let queue = Queue::new();
|
||||
let calls = Calls::default();
|
||||
let gather = queue.gather_within(2, Duration::from_millis(100));
|
||||
std::thread::scope(|scope| {
|
||||
scope.spawn(|| {
|
||||
queue.batched_when(Some(gather), install(), os("a.deb"), &|| false, &mut |_| {}, &|command, targets| {
|
||||
calls.record(command, targets);
|
||||
vec![Ok(()); targets.len()]
|
||||
})
|
||||
});
|
||||
// The second member never shows up; the cap lets the first go after 100 ms.
|
||||
assert!(calls.soon(5), "the call went out once the wait was over");
|
||||
});
|
||||
assert_eq!(calls.taken(), [line(&["apt-get", "install", "-y", "a.deb"])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_member_of_a_gather_lets_the_rest_go() {
|
||||
let queue = Queue::new();
|
||||
let calls = Calls::default();
|
||||
let gather = queue.gather(2);
|
||||
let cancel = AtomicBool::new(false);
|
||||
let (started, has_started) = mpsc::channel();
|
||||
let (release, released) = mpsc::channel::<()>();
|
||||
let (turned, turns) = mpsc::channel();
|
||||
std::thread::scope(|scope| {
|
||||
let (queue, calls, cancel, gather) = (&queue, &calls, &cancel, &gather);
|
||||
scope.spawn(move || {
|
||||
queue.alone(&|| false, &mut |_| {}, || {
|
||||
started.send(()).unwrap();
|
||||
released.recv().unwrap();
|
||||
});
|
||||
});
|
||||
has_started.recv().unwrap();
|
||||
let exec = |command: &[OsString], targets: &[OsString]| {
|
||||
calls.record(command, targets);
|
||||
vec![Ok(()); targets.len()]
|
||||
};
|
||||
let staying_gather = gather.clone();
|
||||
let turned_too = turned.clone();
|
||||
let staying = scope.spawn(move || {
|
||||
queue.batched_when(
|
||||
Some(staying_gather),
|
||||
install(),
|
||||
os("a.deb"),
|
||||
&|| false,
|
||||
&mut |waiting| {
|
||||
if waiting {
|
||||
turned_too.send(()).unwrap();
|
||||
}
|
||||
},
|
||||
&exec,
|
||||
)
|
||||
});
|
||||
let leaving = scope.spawn(move || {
|
||||
queue.batched_when(
|
||||
Some(gather.clone()),
|
||||
install(),
|
||||
os("b.deb"),
|
||||
&|| cancel.load(Ordering::SeqCst),
|
||||
&mut |waiting| {
|
||||
if waiting {
|
||||
turned.send(()).unwrap();
|
||||
}
|
||||
},
|
||||
&exec,
|
||||
)
|
||||
});
|
||||
// Both have said they are waiting (behind the running install), then one is called off.
|
||||
turns.recv().unwrap();
|
||||
turns.recv().unwrap();
|
||||
cancel.store(true, Ordering::SeqCst);
|
||||
assert_eq!(leaving.join().unwrap(), Err("cancelled".to_string()));
|
||||
release.send(()).unwrap();
|
||||
assert_eq!(staying.join().unwrap(), Ok(()));
|
||||
});
|
||||
assert_eq!(calls.taken(), [line(&["apt-get", "install", "-y", "a.deb"])], "the cancelled member is not in the call");
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,7 @@ fn uncertain_msi_updates_do_not_download_or_start_an_installer() {
|
||||
replace: false,
|
||||
approved_path: None,
|
||||
downgrade: None,
|
||||
batch: None,
|
||||
};
|
||||
let result = install::install(app, &release, &asset, PackageKind::Msi, Some(&existing), None, &mut job);
|
||||
assert!(matches!(&result, Err(error) if error.contains("could not confirm who this app is installed for")), "{result:?}");
|
||||
|
||||
@@ -755,10 +755,18 @@ impl LauncherUi {
|
||||
if self.auto_update_attempted.contains(&(e.app.id.to_string(), v.clone())) { None } else { Some((e.app.id.to_string(), v)) }
|
||||
})
|
||||
.collect();
|
||||
for (id, version) in to_update {
|
||||
log::info!("auto-update: queuing update for {id} to {version}");
|
||||
self.auto_update_attempted.insert((id.clone(), version));
|
||||
self.send(Command::Install { app: id });
|
||||
if self.settings.batch_updates && !to_update.is_empty() {
|
||||
log::info!("auto-update: queuing {} updates together behind one prompt", to_update.len());
|
||||
for (id, version) in &to_update {
|
||||
self.auto_update_attempted.insert((id.clone(), version.clone()));
|
||||
}
|
||||
self.send(Command::InstallAll { apps: to_update.into_iter().map(|(id, _)| id).collect() });
|
||||
} else {
|
||||
for (id, version) in to_update {
|
||||
log::info!("auto-update: queuing update for {id} to {version}");
|
||||
self.auto_update_attempted.insert((id.clone(), version));
|
||||
self.send(Command::Install { app: id });
|
||||
}
|
||||
}
|
||||
if self.caps.self_update
|
||||
&& let Some(r) = &self.launcher_update
|
||||
|
||||
@@ -86,6 +86,7 @@
|
||||
ArtCraft Launcher {version} ArtCraft Launcher {version}
|
||||
Only when I ask Pouze na vyžádání
|
||||
Automatically download and install updates Automaticky stahovat a instalovat aktualizace
|
||||
Ask for permission once when updating all apps Při aktualizaci všech aplikací požádat o oprávnění pouze jednou
|
||||
Notify me when an installed app has an update Upozornit, když má nainstalovaná aplikace aktualizaci
|
||||
Include pre-releases (betas and release candidates) Zahrnout předběžná vydání (beta verze a kandidáty na vydání)
|
||||
Installing on Linux Instalace v Linuxu
|
||||
|
||||
|
@@ -99,6 +99,7 @@
|
||||
ArtCraft Launcher {version} ArtCraft Launcher {version}
|
||||
Only when I ask Nur manuell
|
||||
Automatically download and install updates Updates automatisch herunterladen und installieren
|
||||
Ask for permission once when updating all apps Beim Aktualisieren aller Apps nur einmal nach Berechtigung fragen
|
||||
Notify me when an installed app has an update Benachrichtigen, wenn es für eine installierte App ein Update gibt
|
||||
Include pre-releases (betas and release candidates) Vorabversionen einbeziehen (Betas und Release Candidates)
|
||||
Installing on Linux Installation unter Linux
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 11 and column 16.
|
@@ -99,6 +99,7 @@
|
||||
ArtCraft Launcher {version} ArtCraft Launcher {version}
|
||||
Only when I ask Solo cuando lo pida
|
||||
Automatically download and install updates Descargar e instalar actualizaciones automáticamente
|
||||
Ask for permission once when updating all apps Pedir permiso una sola vez al actualizar todas las aplicaciones
|
||||
Notify me when an installed app has an update Avisarme cuando una aplicación instalada tenga una actualización
|
||||
Include pre-releases (betas and release candidates) Incluir versiones preliminares (betas y versiones candidatas)
|
||||
Installing on Linux Instalación en Linux
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 5 and column 48.
|
@@ -97,6 +97,7 @@
|
||||
ArtCraft Launcher {version} ArtCraft Launcher {version}
|
||||
Only when I ask Seulement à ma demande
|
||||
Automatically download and install updates Télécharger et installer les mises à jour automatiquement
|
||||
Ask for permission once when updating all apps Demander l'autorisation une seule fois lors de la mise à jour de toutes les applications
|
||||
Notify me when an installed app has an update Me prévenir quand une application installée a une mise à jour
|
||||
Include pre-releases (betas and release candidates) Inclure les préversions (bêtas et versions candidates)
|
||||
Installing on Linux Installation sous Linux
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 5 and column 50.
|
@@ -99,6 +99,7 @@
|
||||
ArtCraft Launcher {version} ArtCraft Launcher {version}
|
||||
Only when I ask Csak kézi kereséskor
|
||||
Automatically download and install updates Frissítések automatikus letöltése és telepítése
|
||||
Ask for permission once when updating all apps Engedély kérése csak egyszer az összes alkalmazás frissítésekor
|
||||
Notify me when an installed app has an update Értesítés a telepített alkalmazásokhoz elérhető frissítésekről
|
||||
Include pre-releases (betas and release candidates) Előzetes kiadások engedélyezése (béta- és kiadásra jelölt verziók)
|
||||
Installing on Linux Telepítés Linuxon
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 11 and column 16.
|
@@ -101,6 +101,7 @@
|
||||
ArtCraft Launcher {version} ArtCraft Launcher {version}
|
||||
Only when I ask 手動で確認したときのみ
|
||||
Automatically download and install updates 更新を自動でダウンロードしてインストール
|
||||
Ask for permission once when updating all apps すべてのアプリを更新するときは権限を一度だけ求める
|
||||
Notify me when an installed app has an update インストール済みアプリに更新があるときに通知する
|
||||
Include pre-releases (betas and release candidates) プレリリース(ベータ版とリリース候補)を含める
|
||||
Installing on Linux Linux へのインストール
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 14 and column 44.
|
@@ -95,6 +95,7 @@
|
||||
ArtCraft Launcher {version} ArtCraft Launcher {version}
|
||||
Only when I ask მხოლოდ მოთხოვნისას
|
||||
Automatically download and install updates განახლებების ავტომატური ჩამოტვირთვა და ინსტალაცია
|
||||
Ask for permission once when updating all apps ყველა აპლიკაციის განახლებისას ნებართვის მოთხოვნა მხოლოდ ერთხელ
|
||||
Notify me when an installed app has an update შეტყობინება, როცა დაინსტალირებულ აპლიკაციას განახლება აქვს
|
||||
Include pre-releases (betas and release candidates) წინასწარი ვერსიების ჩართვა (ბეტა-ვერსიები და გამოშვების კანდიდატები)
|
||||
Installing on Linux ინსტალაცია Linux-ზე
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 13 and column 18.
|
@@ -100,6 +100,7 @@
|
||||
ArtCraft Launcher {version} ArtCraft Launcher {version}
|
||||
Only when I ask Tylko kiedy zapytam
|
||||
Automatically download and install updates Automatycznie pobieraj i instaluj aktualizacje
|
||||
Ask for permission once when updating all apps Pytaj o uprawnienia tylko raz przy aktualizacji wszystkich aplikacji
|
||||
Notify me when an installed app has an update Powiadom mnie o aktualizacjach dla zainstalowanych aplikacji
|
||||
Include pre-releases (betas and release candidates) Uwzględnij wersje przedpremierowe (beta i wersje kandydujące)
|
||||
Installing on Linux Instalowanie w systemie Linux
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 11 and column 15.
|
@@ -87,6 +87,7 @@
|
||||
ArtCraft Launcher {version} ArtCraft Launcher {version}
|
||||
Only when I ask Apenas quando eu pedir
|
||||
Automatically download and install updates Baixar e instalar atualizações automaticamente
|
||||
Ask for permission once when updating all apps Pedir permissão uma única vez ao atualizar todos os aplicativos
|
||||
Notify me when an installed app has an update Notificar quando um aplicativo instalado tiver atualização
|
||||
Include pre-releases (betas and release candidates) Incluir versões de pré-lançamento (betas e RC)
|
||||
Installing on Linux Instalação no Linux
|
||||
|
||||
|
@@ -97,6 +97,7 @@
|
||||
ArtCraft Launcher {version} ArtCraft Launcher {version}
|
||||
Only when I ask Только по запросу
|
||||
Automatically download and install updates Автоматически скачивать и устанавливать обновления
|
||||
Ask for permission once when updating all apps Запрашивать разрешение один раз при обновлении всех приложений
|
||||
Notify me when an installed app has an update Уведомлять, когда у установленного приложения есть обновление
|
||||
Include pre-releases (betas and release candidates) Включать предварительные релизы (бета и RC)
|
||||
Installing on Linux Установка в Linux
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 13 and column 44.
|
@@ -81,6 +81,7 @@
|
||||
ArtCraft Launcher {version} ArtCraft Launcher {version}
|
||||
Only when I ask 仅手动检查
|
||||
Automatically download and install updates 自动下载并安装更新
|
||||
Ask for permission once when updating all apps 更新所有应用时仅请求一次授权
|
||||
Notify me when an installed app has an update 已安装应用有更新时通知我
|
||||
Include pre-releases (betas and release candidates) 包含预发布版本(测试版和候选版)
|
||||
Installing on Linux Linux 安装设置
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 3.
|
@@ -75,6 +75,7 @@
|
||||
ArtCraft Launcher {version} ArtCraft Launcher {version}
|
||||
Only when I ask 僅在我要求時
|
||||
Automatically download and install updates 自動下載並安裝更新
|
||||
Ask for permission once when updating all apps 更新所有應用程式時僅請求一次權限
|
||||
Notify me when an installed app has an update 已安裝的應用程式有更新時通知我
|
||||
Include pre-releases (betas and release candidates) 包含預先發行版(Beta 版與候選發行版)
|
||||
Installing on Linux 在 Linux 上安裝
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 3.
|
@@ -105,6 +105,10 @@ pub struct Settings {
|
||||
/// Automatically download and install updates when found.
|
||||
#[serde(default)]
|
||||
pub auto_update: bool,
|
||||
/// Update all apps together behind one permission prompt where the platform asks for one
|
||||
/// (Linux and Windows); off, each app's update asks on its own.
|
||||
#[serde(default)]
|
||||
pub batch_updates: bool,
|
||||
/// Show a system notification when an installed app has an update.
|
||||
pub notify: bool,
|
||||
pub prereleases: bool,
|
||||
@@ -253,6 +257,7 @@ impl Default for Settings {
|
||||
show_on_current_desktop: true,
|
||||
check_every: CheckEvery::Hour,
|
||||
auto_update: false,
|
||||
batch_updates: false,
|
||||
notify: true,
|
||||
prereleases: false,
|
||||
versions: BTreeMap::new(),
|
||||
|
||||
@@ -192,6 +192,9 @@ impl LauncherUi {
|
||||
{
|
||||
self.trigger_auto_updates();
|
||||
}
|
||||
if self.caps.manage_apps {
|
||||
ui.checkbox(&mut self.settings.batch_updates, tl!("Ask for permission once when updating all apps"));
|
||||
}
|
||||
ui.checkbox(&mut self.settings.notify, tl!("Notify me when an installed app has an update"));
|
||||
ui.checkbox(&mut self.settings.prereleases, tl!("Include pre-releases (betas and release candidates)"));
|
||||
row(ui, tl!("Launcher version"), 200.0, &mut |ui, label| {
|
||||
|
||||
@@ -379,13 +379,20 @@ impl LauncherUi {
|
||||
.accessible_name(tl!("Sort"));
|
||||
}
|
||||
|
||||
/// Update every eligible app; used in the compact and full-width toolbars.
|
||||
/// Update every eligible app; used in the compact and full-width toolbars. With batched
|
||||
/// updates on, one command installs them together: behind one permission prompt where the
|
||||
/// platform asks for one, instead of one prompt per app.
|
||||
fn update_all_button(&mut self, ui: &mut Ui, updates: usize) {
|
||||
let label = if updates == 1 { tl!("Update 1 app").to_string() } else { fmt(tl!("Update all ({count})"), &[("count", &updates.to_string())]) };
|
||||
if widgets::button(ui, &label, Kind::Primary, 0.0).clicked() {
|
||||
let ids: Vec<&str> = self.entries.iter().filter(|e| self.in_filter(e, Filter::Updates) && e.job.is_none()).map(|e| e.app.id).collect();
|
||||
for id in ids {
|
||||
self.act_command(Command::Install { app: id.to_string() });
|
||||
let ids: Vec<String> =
|
||||
self.entries.iter().filter(|e| self.in_filter(e, Filter::Updates) && e.job.is_none()).map(|e| e.app.id.to_string()).collect();
|
||||
if self.settings.batch_updates {
|
||||
self.act_command(Command::InstallAll { apps: ids });
|
||||
} else {
|
||||
for id in ids {
|
||||
self.act_command(Command::Install { app: id });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,6 +92,12 @@ the route.
|
||||
- **All-users downgrades:** `downgrade_elevated` still uses the same elevated PowerShell script,
|
||||
and the command strings are still in the binary. Anyone downgrading an all-users app could trigger
|
||||
the same detection.
|
||||
- **The one-prompt batch route returns, differently (#1083):** "Update all" again asks once for a
|
||||
batch of all-users apps, but by elevating the launcher's own signed exe with `ShellExecuteEx`
|
||||
(`runas` verb) — no PowerShell, nothing encoded, nothing hidden — and every package is still held
|
||||
and re-hashed before `msiexec` runs it with its own visible progress window
|
||||
(`crates/native/src/install/msi_session.rs`). It owes the same behavioural-antivirus confirmation
|
||||
test below before it ships in a release.
|
||||
- **Release:** no release includes #1077 yet.
|
||||
- **Confirmation:** test on a Windows VM with Kaspersky and behaviour detection on. Run Update all
|
||||
with two or more outdated all-users apps on an affected build, then on a build with #1077. The
|
||||
|
||||
Reference in new issue
Block a user