Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! RustCordSetup.exe: installs RustCord for the current user.
//!
//! Double-click it for a window that asks where to install and whether to add
//! a desktop shortcut, shows its progress, asks whether RustCord should keep
//! itself up to date and offers to start it; or run it from a script:
//! RustCordSetup.exe /S [--dir <folder>] [--no-desktop] [--no-launch]
//! [--auto-update | --no-auto-update]
//! Running it again over an existing install updates it. The window closes a
//! running RustCord first; a silent update leaves it open, and the new
//! version starts the next time RustCord does.
#![cfg_attr(windows, windows_subsystem = "windows")]
#[cfg(not(windows))]
fn main() {
eprintln!("RustCord's installer is for Windows.");
}
#[cfg(all(windows, not(has_payload)))]
fn main() {
rustcord_setup::error("This installer has no RustCord inside it", "Build it with build-installer.cmd, which builds RustCord and the uninstaller first and packs them into the installer.");
std::process::exit(2);
}
#[cfg(all(windows, has_payload))]
mod setup {
use rustcord_setup::*;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
/// The programs to install, gzip-compressed by rustcord-pack.
const RUSTCORD_GZ: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/release/rustcord.exe.gz"));
const UNINSTALL_GZ: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/release/rustcord-uninstall.exe.gz"));
/// How large a .gz file's contents are (its last four bytes say).
fn unpacked_len(gz: &[u8]) -> u64 {
gz.last_chunk::<4>().map_or(0, |b| u32::from_le_bytes(*b) as u64)
}
enum Failure {
Cancelled,
Error(String),
}
/// An install in progress, shared between the thread doing it and the window.
#[derive(Default)]
struct Job {
/// 0 to 1000.
progress: AtomicU32,
cancel: AtomicBool,
result: Mutex<Option<Result<(), Failure>>>,
}
/// Unpack `gz` to `path`, moving the job's progress from `from` to `to`.
/// The file is written next to `path` first and swapped in when complete,
/// so a failure leaves the installed one as it was. A file that is in use
/// (RustCord is running) can't be replaced but can be renamed: it is moved
/// aside as `.old` and cleaned up by a later install.
fn unpack(gz: &[u8], path: &Path, job: &Job, (from, to): (u32, u32), cancellable: bool) -> Result<(), Failure> {
let failed = |e: std::io::Error| Failure::Error(format!("Couldn't write {}: {e}", path.display()));
let new = path.with_extension("new");
let write = || -> Result<(), Failure> {
let total = unpacked_len(gz).max(1);
let mut source = flate2::read::GzDecoder::new(gz);
let mut file = std::fs::File::create(&new).map_err(failed)?;
let mut buf = vec![0u8; 256 * 1024];
let mut done = 0u64;
loop {
if cancellable && job.cancel.load(Ordering::Relaxed) {
return Err(Failure::Cancelled);
}
// (A damaged installer shows up here: gzip carries a checksum.)
let n = source.read(&mut buf).map_err(|e| Failure::Error(format!("This installer is damaged ({e}). Download it again.")))?;
if n == 0 {
break;
}
file.write_all(&buf[..n]).map_err(failed)?;
done += n as u64;
job.progress.store(from + ((to - from) as u64 * done.min(total) / total) as u32, Ordering::Relaxed);
}
file.flush().map_err(failed)
};
let swap = || -> std::io::Result<()> {
let old = path.with_extension("old");
let _ = std::fs::remove_file(&old);
if path.exists() && std::fs::remove_file(path).is_err() {
std::fs::rename(path, &old)?;
}
std::fs::rename(&new, path)
};
let result = write().and_then(|()| swap().map_err(failed));
if result.is_err() {
let _ = std::fs::remove_file(&new);
}
result
}
fn install(dir: &Path, desktop: bool, close_rustcord: bool, job: &Job) -> Result<(), Failure> {
let updating = dir.join(EXE).exists();
let result = (|| {
std::fs::create_dir_all(dir).map_err(|e| Failure::Error(format!("Couldn't create {}: {e}", dir.display())))?;
if close_rustcord {
// (If it won't close, its file is moved aside instead.)
close_running(dir);
}
let exe = dir.join(EXE);
unpack(RUSTCORD_GZ, &exe, job, (0, 950), true)?;
unpack(UNINSTALL_GZ, &dir.join(UNINSTALLER), job, (950, 980), false)?;
let start = start_menu_link().ok_or(Failure::Error("Couldn't find the Start menu folder.".into()))?;
create_shortcut(&start, &exe).map_err(|e| Failure::Error(format!("Couldn't create the Start menu shortcut: {e}")))?;
if desktop {
// An extra, not part of the install: a desktop that can't be
// written to (Controlled Folder Access blocks unsigned
// programs) mustn't undo the rest.
if let Some(link) = desktop_link() {
let _ = create_shortcut(&link, &exe);
}
}
let size_kb = ((unpacked_len(RUSTCORD_GZ) + unpacked_len(UNINSTALL_GZ)) / 1024) as u32;
register_uninstaller(dir, size_kb).map_err(|e| Failure::Error(format!("Couldn't add RustCord to Installed apps: {e}")))?;
refresh_icons();
job.progress.store(1000, Ordering::Relaxed);
Ok(())
})();
if result.is_err() && !updating {
// A first install that didn't finish leaves nothing behind (the
// folder itself only if it holds nothing else).
for name in [EXE, UNINSTALLER] {
let _ = std::fs::remove_file(dir.join(name));
}
if let Some(link) = start_menu_link() {
let _ = std::fs::remove_file(link);
}
let _ = std::fs::remove_dir(dir);
}
result
}
const INSTALL: i32 = 100;
const BROWSE: i32 = 101;
const FINISH: i32 = 102;
const CLOSE: i32 = 103;
const LAUNCH: i32 = 104;
enum Stage {
Asking,
Installing(Arc<Job>),
Done,
Failed,
}
struct Wizard {
dir: PathBuf,
updating: bool,
desktop: bool,
/// RustCord updates itself (asked on the last page).
auto_update: bool,
/// Offer to start RustCord at the end.
offer_launch: bool,
stage: Stage,
}
impl Wizard {
fn asking(&self) -> Page {
let mb = (unpacked_len(RUSTCORD_GZ) + unpacked_len(UNINSTALL_GZ)).div_ceil(1024 * 1024);
let folder = format!("Folder: {}", self.dir.display());
let (heading, text, go) = if self.updating {
let running = if running_from(&self.dir).is_empty() { "" } else { "
RustCord is open: it is closed first." };
let kept = "Your settings and login are kept.";
// What is there now decides what this is: an update, the same
// version again, or (worth a warning) a step back.
let (heading, about, go) = match installed_version(&self.dir) {
Some(old) if older(&old, VERSION) => (format!("Update {APP} to version {VERSION}"), format!("Version {old} is installed here. {kept}"), "Update"),
Some(old) if older(VERSION, &old) => {
(format!("Go back to {APP} {VERSION}?"), format!("A newer version, {old}, is installed here. This setup replaces it with the older {VERSION}. {kept}"), "Replace")
}
Some(_) => (format!("Reinstall {APP} {VERSION}"), format!("This version is already installed here; its files are replaced. {kept}"), "Reinstall"),
None => (format!("Update {APP} to version {VERSION}"), format!("{APP} is already installed here. {kept}"), "Update"),
};
(heading, format!("{about}
{folder}{running}"), go)
} else {
(
format!("Install {APP} {VERSION}"),
format!("{APP} is installed for your Windows account only, so no administrator rights are needed. It takes {mb} MB.\n\n{folder}"),
"Install",
)
};
Page::new(Icon::App, heading, text).button(INSTALL, go).button(BROWSE, "Change folder…").button(CANCEL, "Cancel").checkbox("Add a desktop shortcut", self.desktop)
}
fn finished(&self) -> Page {
let heading = format!("{APP} {VERSION} is installed");
let text = if self.desktop { "You'll find it in the Start menu and on your desktop." } else { "You'll find it in the Start menu." };
let page = Page::new(Icon::App, heading, text);
let page = if self.offer_launch { page.button(LAUNCH, &format!("Start {APP}")).button(FINISH, "Close") } else { page.button(FINISH, "Finish") };
page.checkbox(&format!("Keep {APP} up to date automatically"), self.auto_update)
}
}
impl Handler for Wizard {
fn clicked(&mut self, ui: &Ui, button: i32) -> bool {
match (&self.stage, button) {
(Stage::Asking, INSTALL) => {
let job = Arc::new(Job::default());
let (dir, desktop, worker) = (self.dir.clone(), self.desktop, job.clone());
std::thread::spawn(move || {
init_com();
let result = install(&dir, desktop, true, &worker);
*worker.result.lock().unwrap() = Some(result);
});
self.stage = Stage::Installing(job);
let heading = if self.updating { format!("Updating {APP}…") } else { format!("Installing {APP}…") };
ui.navigate(Page::new(Icon::App, heading, format!("Copying files to {}", self.dir.display())).progress().button(CANCEL, "Cancel"));
false
}
(Stage::Asking, BROWSE) => {
if let Some(mut picked) = pick_folder(ui.hwnd(), &self.dir) {
// RustCord gets a folder of its own, not a place among
// other files (unless that is where it already is).
let own = picked.file_name().is_some_and(|n| n.to_string_lossy().eq_ignore_ascii_case(APP));
if !own && !picked.join(EXE).exists() {
picked.push(APP);
}
self.dir = picked;
self.updating = self.dir.join(EXE).exists();
ui.navigate(self.asking());
}
false
}
(Stage::Installing(job), CANCEL) => {
// The install thread stops at its next step; `tick` sees the result.
job.cancel.store(true, Ordering::Relaxed);
ui.enable(CANCEL, false);
false
}
_ => true,
}
}
fn checkbox(&mut self, ticked: bool) {
match self.stage {
Stage::Asking => self.desktop = ticked,
Stage::Done => self.auto_update = ticked,
_ => {}
}
}
fn tick(&mut self, ui: &Ui) {
let Stage::Installing(job) = &self.stage else { return };
ui.set_progress(job.progress.load(Ordering::Relaxed));
let Some(result) = job.result.lock().unwrap().take() else { return };
let not_done = if self.updating { format!("{APP} wasn't updated") } else { format!("{APP} wasn't installed") };
match result {
Ok(()) => {
self.stage = Stage::Done;
ui.navigate(self.finished());
}
Err(Failure::Cancelled) => {
self.stage = Stage::Failed;
let text = if self.updating { "Setup was cancelled. The installed version is unchanged." } else { "Setup was cancelled. Nothing was installed." };
ui.navigate(Page::new(Icon::Info, not_done, text).button(CLOSE, "Close"));
}
Err(Failure::Error(e)) => {
self.stage = Stage::Failed;
ui.navigate(Page::new(Icon::Error, not_done, e).button(CLOSE, "Close"));
}
}
}
}
pub fn main() {
system_dlls_only();
let opts = Options::from_args();
init_com();
// Where it goes: where the script says, else where it already is, else the usual place.
let installed = registered_dir().filter(|d| d.join(EXE).exists());
let Some(dir) = opts.dir.clone().or(installed).or_else(default_dir) else {
if !opts.silent {
error(&format!("{APP} can't be installed"), "Couldn't find your local Programs folder.");
}
std::process::exit(1);
};
let updating = dir.join(EXE).exists();
// An update doesn't bring back a desktop shortcut that was deleted.
let desktop = !opts.no_desktop && (!updating || desktop_link().is_some_and(|l| l.exists()));
if opts.silent {
// (RustCord's own updates come this way: what was chosen before is kept.)
let installed = install(&dir, desktop, false, &Job::default());
if let (Ok(()), Some(on)) = (&installed, opts.auto_update) {
let _ = set_auto_update(on);
}
std::process::exit(if installed.is_ok() { 0 } else { 1 });
}
let auto_update = opts.auto_update.unwrap_or_else(auto_update);
let mut wizard = Wizard { dir, updating, desktop, auto_update, offer_launch: !opts.no_launch, stage: Stage::Asking };
let first = wizard.asking();
let (button, _) = run(first, &mut wizard);
match wizard.stage {
Stage::Done => {
// Saved before RustCord starts: it reads this as it opens.
let _ = set_auto_update(wizard.auto_update);
if button == LAUNCH {
let _ = std::process::Command::new(wizard.dir.join(EXE)).current_dir(&wizard.dir).spawn();
}
}
Stage::Failed => std::process::exit(1),
_ => {}
}
}
}
#[cfg(all(windows, has_payload))]
fn main() {
setup::main();
}