Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Open at Login: Quince runs in the background from login

Yashwanth Kamireddi9983463d682c
diff --git a/.uiverify/login-item.mjs b/.uiverify/login-item.mjs
new file mode 100644
index 0000000..c769590
--- /dev/null
+++ b/.uiverify/login-item.mjs
@@ -0,0 +1,44 @@
+// Settings → Open at Login: off until turned on; on a desktop that runs login entries it says
+// what it does; on one that does not (Hyprland without uwsm, Sway), it says so and gives the
+// exact line, selectable whole; a refusal puts the switch back with the reason.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub } from "./stub.mjs";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+for (const scheme of ["light", "dark"]) {
+ const ctx = await b.newContext({ viewport: { width: 1200, height: 900 }, colorScheme: scheme });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+ const page = await ctx.newPage();
+ page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+ await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+ await page.locator(".account-card, [aria-label*='Settings'], .sidebar-foot button").first().click();
+ await page.waitForTimeout(400);
+ const sw = page.getByRole("switch", { name: "Open at Login" });
+ const row = page.locator(".settings-row", { has: sw });
+ ok((await sw.getAttribute("aria-checked")) === "false", `${scheme}: off until turned on`);
+ await sw.click();
+ await page.waitForTimeout(200);
+ ok((await sw.getAttribute("aria-checked")) === "true" && /Starts in the background/.test(await row.innerText()), `${scheme}: on, and says what it does`);
+ ok((await row.locator(".settings-command").count()) === 0, `${scheme}: no command where the desktop runs it`);
+ await sw.click();
+ await page.waitForTimeout(200);
+ // A desktop that runs no login entries: said plainly, with the line to add.
+ await page.evaluate(() => { window.__login = { honoured: false }; });
+ await sw.click();
+ await page.waitForTimeout(200);
+ const cmd = row.locator(".settings-command");
+ ok(/doesn't open apps at login by itself/.test(await row.innerText()) && (await cmd.innerText()) === '"/usr/bin/quince-app" --background', `${scheme}: where it is not run, the exact line to add`);
+ ok((await cmd.evaluate((e) => getComputedStyle(e).userSelect)) === "all", `${scheme}: selectable whole`);
+ const [fg, bg] = await cmd.evaluate((e) => [getComputedStyle(e).color, getComputedStyle(document.body).backgroundColor]);
+ ok(fg !== bg, `${scheme}: readable (${fg} on ${bg})`);
+ await page.screenshot({ path: `${process.env.TMPDIR ?? "/tmp"}/login-item-${scheme}-${process.env.ENGINE}.png` });
+ // Refused (no config folder): back as it was, and why.
+ await page.evaluate(() => { window.__loginRefuse = "There is no configuration folder to keep it in."; });
+ await sw.click();
+ await page.waitForTimeout(200);
+ ok((await sw.getAttribute("aria-checked")) === "true" && /no configuration folder/.test(await page.locator(".settings-error").innerText()), `${scheme}: refused, back as it was with the reason`);
+ await ctx.close();
+}
+await b.close();
+if (failures) process.exitCode = 1;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index e479895..0060622 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -607,6 +607,10 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "auth_send_sms": return null;
case "auth_submit_sms_code": return null;
case "auth_sign_out": sessionStorage.setItem("__signedOut", JSON.stringify(args)); return null;
+ case "login_item_status": return { on: false, command: "\"/usr/bin/quince-app\" --background", honoured: true, ...(window.__login ?? {}) };
+ case "login_item_set":
+ if (window.__loginRefuse) throw window.__loginRefuse;
+ return (window.__login = { ...(window.__login ?? {}), on: args.on, command: "\"/usr/bin/quince-app\" --background", honoured: window.__login?.honoured ?? true });
case "account_unsent": return window.__unsent ?? { changes: 0, files: 0, photos: 0 };
// One refresh covers every service, so there is one command to stub rather than
// a pair per screen.
diff --git a/src-tauri/src/login.rs b/src-tauri/src/login.rs
new file mode 100644
index 0000000..6f0a5ba
--- /dev/null
+++ b/src-tauri/src/login.rs
@@ -0,0 +1,166 @@
+//! Open at Login: Quince started in the background when the person logs in — its window
+//! hidden, everything behind it running — so reminders ring, changes sync and the folders are
+//! up without the window ever being opened. Kept the standard way, as an XDG autostart entry
+//! (`~/.config/autostart`), which the desktops run themselves; nothing of Quince's own runs it.
+//!
+//! Some compositors run no autostart entries (Hyprland, Sway and the like, unless started
+//! through uwsm). There Settings says so, with the one line that does the same in their
+//! own startup — written by the person, never by Quince into their config.
+
+use serde::Serialize;
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, Ordering};
+use tauri::{AppHandle, Manager};
+
+/// Started by the login entry: the window stays hidden unless something needs the person.
+static BACKGROUND: AtomicBool = AtomicBool::new(false);
+/// Whether the first window_ready has been answered: only that one may keep it hidden.
+static ASKED: AtomicBool = AtomicBool::new(false);
+
+/// What the login entry passes to start hidden.
+const FLAG: &str = "--background";
+
+/// Read once at launch, from the command line.
+pub fn note_launch() {
+ BACKGROUND.store(std::env::args().any(|a| a == FLAG), Ordering::SeqCst);
+}
+
+/// Whether this run was started at login, hidden.
+pub fn background() -> bool {
+ BACKGROUND.load(Ordering::SeqCst)
+}
+
+/// Whether the window should stay hidden now: started at login, and nothing needs the person
+/// (a code to enter, a sign-in). Only the first answer can be yes; after that the window
+/// shows as usual.
+pub fn stay_hidden(needs_you: bool) -> bool {
+ background() && !ASKED.swap(true, Ordering::SeqCst) && !needs_you
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LoginItem {
+ pub on: bool,
+ /// The command the entry runs, for a startup file that does not read autostart entries.
+ pub command: String,
+ /// Whether this desktop runs autostart entries at login. `false`: the entry alone does
+ /// nothing here, and `command` has to go in the compositor's own startup.
+ pub honoured: bool,
+}
+
+fn entry(app: &AppHandle) -> Option<PathBuf> {
+ app.path()
+ .config_dir()
+ .ok()
+ .map(|c| c.join("autostart").join("dev.quince.client.desktop"))
+}
+
+/// The command that starts this Quince hidden: the AppImage itself when run from one (its
+/// own binary lives in a mount that is gone after a restart), else the program running now.
+fn command() -> String {
+ let program = std::env::var_os("APPIMAGE")
+ .map(PathBuf::from)
+ .or_else(|| std::env::current_exe().ok())
+ .unwrap_or_else(|| PathBuf::from("quince-app"));
+ format!("{} {FLAG}", quoted(&program.to_string_lossy()))
+}
+
+/// A program path as the Desktop Entry spec wants it in Exec: in double quotes, with `"`,
+/// `` ` ``, `$` and `\` escaped.
+fn quoted(path: &str) -> String {
+ let mut out = String::from("\"");
+ for c in path.chars() {
+ if matches!(c, '"' | '`' | '$' | '\\') {
+ out.push('\\');
+ }
+ out.push(c);
+ }
+ out.push('"');
+ out
+}
+
+fn desktop_file(command: &str) -> String {
+ format!(
+ "[Desktop Entry]\nType=Application\nName=Quince\nComment=Keeps iCloud in sync in the background\nExec={command}\nIcon=dev.quince.client\nTerminal=false\nNoDisplay=true\nX-GNOME-Autostart-enabled=true\n"
+ )
+}
+
+/// Desktops that run autostart entries themselves.
+const RUNS_AUTOSTART: [&str; 10] = [
+ "GNOME",
+ "KDE",
+ "XFCE",
+ "X-Cinnamon",
+ "MATE",
+ "LXQt",
+ "LXDE",
+ "Budgie",
+ "COSMIC",
+ "Unity",
+];
+
+/// Whether autostart entries run at login here: a desktop that runs them, or a session that
+/// started systemd's autostart target (uwsm, and the desktops that use it).
+fn honoured() -> bool {
+ let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();
+ if desktop
+ .split(':')
+ .any(|d| RUNS_AUTOSTART.iter().any(|k| d.eq_ignore_ascii_case(k)))
+ {
+ return true;
+ }
+ std::process::Command::new("systemctl")
+ .args([
+ "--user",
+ "is-active",
+ "--quiet",
+ "xdg-desktop-autostart.target",
+ ])
+ .status()
+ .is_ok_and(|s| s.success())
+}
+
+#[tauri::command]
+pub async fn login_item_status(app: AppHandle) -> Result<LoginItem, String> {
+ let on = entry(&app).is_some_and(|p| p.exists());
+ let honoured = tauri::async_runtime::spawn_blocking(honoured)
+ .await
+ .unwrap_or(false);
+ Ok(LoginItem {
+ on,
+ command: command(),
+ honoured,
+ })
+}
+
+#[tauri::command]
+pub async fn login_item_set(on: bool, app: AppHandle) -> Result<LoginItem, String> {
+ let path = entry(&app).ok_or("There is no configuration folder to keep it in.")?;
+ if on {
+ if let Some(dir) = path.parent() {
+ std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
+ }
+ std::fs::write(&path, desktop_file(&command())).map_err(|e| e.to_string())?;
+ } else if path.exists() {
+ std::fs::remove_file(&path).map_err(|e| e.to_string())?;
+ }
+ login_item_status(app).await
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The Exec line survives any path: spaces quoted, the spec's special characters escaped.
+ #[test]
+ fn the_exec_line_is_quoted_as_the_spec_says() {
+ assert_eq!(
+ quoted("/opt/Quince App/quince"),
+ "\"/opt/Quince App/quince\""
+ );
+ assert_eq!(quoted("/a/$HOME\"x`\\"), "\"/a/\\$HOME\\\"x\\`\\\\\"");
+ let file = desktop_file("\"/usr/bin/quince-app\" --background");
+ assert!(file.contains("Exec=\"/usr/bin/quince-app\" --background\n"));
+ assert!(file.starts_with("[Desktop Entry]\nType=Application\n"));
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 661d56e..369fab0 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -14,6 +14,7 @@ macro_rules! quiet {
mod alerts;
mod cpu;
+mod login;
mod mount;
mod mount_photos;
mod outbox;
@@ -3864,11 +3865,21 @@ fn tiling_compositor() -> bool {
/// painted, and the window appears whole. Shown anyway after a few seconds, so a page that
/// never says so still leaves a window to use.
#[tauri::command]
-fn window_ready(app: tauri::AppHandle) {
+fn window_ready(app: tauri::AppHandle, needs_you: Option<bool>) {
+ // Started at login, with nothing for the person to do: everything runs, the window waits
+ // in the tray.
+ // Never without the tray to come back from.
+ if app.tray_by_id("quince").is_some() && login::stay_hidden(needs_you.unwrap_or(true)) {
+ return;
+ }
show_window(&app);
}
fn show_when_ready(app: &tauri::AppHandle) {
+ // Started at login: the window is the first window_ready's to show, or not.
+ if login::background() {
+ return;
+ }
let app = app.clone();
tauri::async_runtime::spawn(async move {
tokio::time::sleep(Duration::from_secs(3)).await;
@@ -3924,6 +3935,7 @@ fn build_tray(app: &tauri::App) -> tauri::Result<()> {
}
fn main() {
+ login::note_launch();
steady_drawing();
smooth_video();
tauri::Builder::default()
@@ -4166,6 +4178,8 @@ fn main() {
auth_submit_sms_code,
auth_sign_out,
account_unsent,
+ login::login_item_status,
+ login::login_item_set,
account_services,
account_info,
settings_get,
diff --git a/src/App.tsx b/src/App.tsx
index 58ca871..5eb475a 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -18,7 +18,8 @@ export default function App() {
requestAnimationFrame(() =>
requestAnimationFrame(() => {
import("@tauri-apps/api/core")
- .then(({ invoke }) => invoke("window_ready"))
+ // Started at login, the window stays in the tray unless the person is needed here.
+ .then(({ invoke }) => invoke("window_ready", { needsYou: phase !== "library" }))
.catch(() => {});
}),
);
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 3df61e2..ae868a0 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -105,6 +105,9 @@ export const api = {
/** The iCloud Photos folder on this computer: the same, for photos (read-only for now). */
photosFolderStatus: () => invoke<DriveFolder>("photos_folder_status"),
photosFolderSet: (on: boolean) => invoke<DriveFolder>("photos_folder_set", { on }),
+ /** Open at Login: whether it is on, the command it runs, and whether this desktop runs it. */
+ loginItem: () => invoke<LoginItem>("login_item_status"),
+ loginItemSet: (on: boolean) => invoke<LoginItem>("login_item_set", { on }),
photosFolderOpen: () => invoke<void>("photos_folder_open"),
photoPlay: (id: string) => invoke<void>("photo_play", { id }),
/** Where the window's player fetches videos from (a loopback server), or null without one. */
@@ -764,6 +767,8 @@ export function turnStyle(turn: Turn | null | undefined, w: number, h: number):
}
/** The iCloud Drive folder on this computer (see src-tauri/src/mount.rs). */
+export type LoginItem = { on: boolean; command: string; honoured: boolean };
+
export type DriveFolder = {
on: boolean;
path: string;
diff --git a/src/screens/SettingsView.tsx b/src/screens/SettingsView.tsx
index 7b5db11..5084e72 100644
--- a/src/screens/SettingsView.tsx
+++ b/src/screens/SettingsView.tsx
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import { getVersion } from "@tauri-apps/api/app";
-import { api, type DriveFolder, messageOf, type AccountInfo } from "../lib/ipc";
+import { api, type DriveFolder, type LoginItem, messageOf, type AccountInfo } from "../lib/ipc";
import { freshness, useSync } from "../lib/sync";
import { setTheme, storedTheme, type Theme } from "../lib/theme";
import { AppIcon } from "../components/AppIcon";
@@ -124,6 +124,8 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom
const [folderBusy, setFolderBusy] = useState(false);
const [photosFolder, setPhotosFolder] = useState<DriveFolder | null>(null);
const [photosBusy, setPhotosBusy] = useState(false);
+ const [login, setLogin] = useState<LoginItem | null>(null);
+ const [loginBusy, setLoginBusy] = useState(false);
const { report, syncing, refresh } = useSync();
useEffect(() => {
@@ -133,6 +135,7 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom
getVersion().then(setVersion, () => {});
api.driveFolderStatus().then(setFolder, () => {});
api.photosFolderStatus().then(setPhotosFolder, () => {});
+ api.loginItem().then(setLogin, () => {});
}, []);
// While the Drive folder is up, what it has still to send is read every two seconds (a
// local question; nothing asked of Apple), so nothing ever waits unseen.
@@ -304,6 +307,39 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom
<span className="switch-knob" />
</button>
</div>
+ <div className="settings-row">
+ <span className="settings-label settings-stack">
+ Open at Login
+ <span className="settings-hint">
+ {login?.on && !login.honoured
+ ? "This desktop doesn't open apps at login by itself. Add this to its startup:"
+ : "Starts in the background, so reminders ring and changes sync without the window"}
+ </span>
+ {login?.on && !login.honoured && <code className="settings-command">{login.command}</code>}
+ </span>
+ <button
+ className="switch"
+ role="switch"
+ aria-checked={login?.on ?? false}
+ aria-label="Open at Login"
+ disabled={!login || loginBusy}
+ onClick={() => {
+ if (!login) return;
+ const was = login;
+ setLogin({ ...login, on: !login.on });
+ setLoginBusy(true);
+ api
+ .loginItemSet(!was.on)
+ .then(setLogin, (e) => {
+ setLogin(was);
+ setError(messageOf(e));
+ })
+ .finally(() => setLoginBusy(false));
+ }}
+ >
+ <span className="switch-knob" />
+ </button>
+ </div>
</section>
<h2 className="settings-heading">Appearance</h2>
diff --git a/src/styles/app.css b/src/styles/app.css
index ac0bc46..5ce713d 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -2094,4 +2094,8 @@
/* A label with a line under it: what the row is, then where or why. */
.settings-stack { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.settings-stack .settings-hint { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+/* A line to copy into another program's startup: selected whole with one click. */
+.settings-command { display: block; margin-top: 4px; padding: 4px 8px; border-radius: 6px; font-size: var(--t-11);
+ background: color-mix(in srgb, var(--text) 7%, transparent); color: var(--text); user-select: all;
+ white-space: normal; word-break: break-all; cursor: text; }
.settings-hint.is-trouble { color: var(--danger); white-space: normal; }