Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions src-tauri/src/updates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ pub struct UpdateInfo {
pub staged: bool,
/// This install can apply a staged build by itself when Stroke quits.
pub apply_on_quit: bool,
/// A package manager owns this install (AUR, a .deb or .rpm): the update
/// goes through it, not through the app.
pub manual: bool,
/// The command that updates it, where there is one (`yay -Syu ...`).
pub manual_command: Option<String>,
}

#[derive(Clone, Serialize)]
Expand Down Expand Up @@ -102,10 +107,17 @@ fn info(update: &Update, staged: bool) -> UpdateInfo {
date: update.date.map(|d| d.unix_timestamp()),
staged,
apply_on_quit: can_apply_on_quit(),
manual: package_managed(),
manual_command: manual_command(),
}
}

fn staged_info(state: &UpdateState) -> Option<UpdateInfo> {
// Nothing is ever staged for a package-managed install; never offer a
// restart that can only fail.
if package_managed() {
return None;
}
lock(&state.staged).as_ref().map(|s| info(&s.update, true))
}

Expand Down Expand Up @@ -151,6 +163,9 @@ pub async fn update_download(
if let Some(staged) = staged_info(&state) {
return Ok(staged);
}
if package_managed() {
return Err(MANAGED_MESSAGE.into());
}
let update = lock(&state.pending)
.clone()
.ok_or("No update to download. Check for updates first.")?;
Expand Down Expand Up @@ -209,6 +224,9 @@ pub fn update_status(state: State<'_, UpdateState>) -> Option<UpdateInfo> {
/// thread, and `restart()` from another thread goes through the normal exit.
#[tauri::command]
pub async fn update_restart(app: AppHandle, state: State<'_, UpdateState>) -> Result<(), String> {
if package_managed() {
return Err(MANAGED_MESSAGE.into());
}
let staged = lock(&state.staged)
.take()
.ok_or("No update is ready to install.")?;
Expand Down Expand Up @@ -288,6 +306,57 @@ pub fn apply_on_quit(app: &AppHandle) {
}
}

// ── Installed by a package manager? ───────────────────────────────────────────

const MANAGED_MESSAGE: &str =
"This copy of Stroke was installed by your package manager, so it updates there.";

/// Linux installs that are not the AppImage: the AUR packages (which unpack
/// the .deb, so the binary reads as a .deb install), a .deb or an .rpm. The
/// release feed ships only the AppImage for Linux, so the plugin tried to
/// install an AppImage as a .deb and failed with "invalid updater binary
/// format". Files under /usr belong to the package manager anyway.
#[cfg(target_os = "linux")]
pub fn package_managed() -> bool {
use tauri::utils::config::BundleType;
!matches!(tauri::utils::platform::bundle_type(), Some(BundleType::AppImage))
|| std::env::var_os("APPIMAGE").is_none()
}

#[cfg(not(target_os = "linux"))]
pub fn package_managed() -> bool {
false
}

/// The update command for an Arch install from the AUR. A .deb or .rpm from
/// the website has no repository to update from: the app links to the
/// download page instead.
#[cfg(target_os = "linux")]
fn manual_command() -> Option<String> {
if !package_managed() {
return None;
}
let local = std::path::Path::new("/var/lib/pacman/local");
let installed = |name: &str| {
std::fs::read_dir(local).ok().is_some_and(|dir| {
dir.flatten().any(|e| {
e.file_name().to_string_lossy().strip_prefix(name).is_some_and(|rest| {
rest.starts_with('-') && rest[1..].starts_with(|c: char| c.is_ascii_digit())
})
})
})
};
["stroke-nightly-bin", "stroke-bin"]
.into_iter()
.find(|p| installed(p))
.map(|p| format!("yay -Syu {p}"))
}

#[cfg(not(target_os = "linux"))]
fn manual_command() -> Option<String> {
None
}

// ── Can this install update itself on quit? ────────────────────────────────────

/// True when a staged build can be installed at quit with nobody watching: no
Expand Down
2 changes: 1 addition & 1 deletion src/lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -2238,7 +2238,7 @@ async function blobToBase64(blob) {
// install can finish on its own (src-tauri/src/updates.rs).

/**
* @typedef {{ version: string, currentVersion: string, notes: string, date: number | null, staged: boolean, applyOnQuit: boolean }} UpdateInfo
* @typedef {{ version: string, currentVersion: string, notes: string, date: number | null, staged: boolean, applyOnQuit: boolean, manual: boolean, manualCommand: string | null }} UpdateInfo
* @typedef {{ event: 'started', data: { contentLength: number | null } } | { event: 'progress', data: { downloaded: number } } | { event: 'finished' }} UpdateDownloadEvent
*/

Expand Down
17 changes: 15 additions & 2 deletions src/lib/components/GateUpdateCheck.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@
import { cn } from '$lib/utils.js'
import { updateCheck, updateDownload, updateRestart, updateStatus } from '$lib/api.js'

/** @type {'idle'|'checking'|'current'|'available'|'downloading'|'ready'|'error'} */
/** @type {'idle'|'checking'|'current'|'available'|'manual'|'downloading'|'ready'|'error'} */
let state = $state('idle')
let version = $state('')
let next = $state('')
let progress = $state(0)
let error = $state('')
/** A package-managed install's update command (`yay -Syu ...`), if any. */
let command = $state(/** @type {string | null} */ (null))

onMount(() => {
import('@tauri-apps/api/app').then((m) => m.getVersion()).then((v) => (version = v)).catch(() => {})
Expand All @@ -38,7 +40,8 @@
error = ''
try {
const info = await updateCheck()
if (info?.staged) { next = info.version; state = 'ready' }
if (info?.manual) { next = info.version; command = info.manualCommand ?? null; state = 'manual' }
else if (info?.staged) { next = info.version; state = 'ready' }
else if (info) { next = info.version; state = 'available' }
else {
state = 'current'
Expand Down Expand Up @@ -82,6 +85,7 @@
state === 'checking' ? 'Checking for updates'
: state === 'current' ? `Stroke is up to date${version ? `, version ${short(version)}` : ''}`
: state === 'available' ? `Stroke ${short(next)} is available`
: state === 'manual' ? `Stroke ${short(next)} is available. Update it with your package manager${command ? `: ${command}` : ''}`
: state === 'downloading' ? `Downloading Stroke ${short(next)}`
: state === 'ready' ? `Stroke ${short(next)} is ready to install`
: state === 'error' ? `Couldn't update: ${error}`
Expand Down Expand Up @@ -110,6 +114,15 @@
{:else if state === 'available'}
<span class="text-foreground">Stroke {short(next)} is available</span>
<button type="button" class={cn(link, 'font-medium text-foreground underline-offset-4 hover:underline')} onclick={install}>Update and restart</button>
{:else if state === 'manual'}
<!-- Installed by a package manager: say where the update comes from. -->
<span class="text-foreground">Stroke {short(next)} is available</span>
{#if command}
<span aria-hidden="true" class="px-1">·</span>
<code class="select-all font-mono text-foreground" title="Run this in a terminal">{command}</code>
{:else}
<a class={cn(link, 'font-medium text-foreground underline-offset-4 hover:underline')} href="https://stroke.click/download" target="_blank" rel="noopener noreferrer">Download page</a>
{/if}
{:else if state === 'downloading'}
<span class="inline-flex h-7 items-center gap-2">
Downloading {short(next)}
Expand Down
50 changes: 48 additions & 2 deletions src/lib/components/UpdateDialog.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@
let releaseNotes = $state('')
/** The downloaded build installs by itself when Stroke quits (updates.rs). */
let applyOnQuit = $state(false)
/** A package manager owns this install (AUR, .deb, .rpm): it updates there. */
let manual = $state(false)
/** The command that updates it, when there is one (`yay -Syu stroke-bin`). */
let manualCommand = $state(/** @type {string | null} */ (null))
let copied = $state(false)
/** The running build, for "You have v…". */
let appVersion = $state('')
/** Settings → Download and install updates automatically, from this window too. */
Expand Down Expand Up @@ -75,7 +80,7 @@
try {
const info = await updateCheck()
if (info?.staged) markReady(info, false)
else if (info && loadSettings().autoUpdate) {
else if (info && loadSettings().autoUpdate && !info.manual) {
// Automatic updates: no window. It downloads in the background and
// says so once, then again when it is ready.
adopt(info)
Expand Down Expand Up @@ -326,6 +331,27 @@
updateVersion = info.version
releaseNotes = info.notes ?? ''
applyOnQuit = info.applyOnQuit
manual = !!info.manual
manualCommand = info.manualCommand ?? null
}

async function copyCommand() {
if (!manualCommand) return
try {
await navigator.clipboard.writeText(manualCommand)
copied = true
setTimeout(() => (copied = false), 1600)
} catch { /* clipboard denied: the command is on screen to select */ }
}

async function openDownloads() {
const url = 'https://stroke.click/download?utm_source=stroke-app&utm_medium=update-dialog'
try {
const { openUrl } = await import('@tauri-apps/plugin-opener')
await openUrl(url)
} catch {
window.open(url, '_blank', 'noopener,noreferrer')
}
}

/**
Expand Down Expand Up @@ -390,7 +416,8 @@
// no window: where it can, the build installs as Stroke quits; elsewhere the
// sidebar's pill offers Restart. With them off, the pill offers Update.
// Neither interrupts what is open.
if (loadSettings().autoUpdate) {
// A package-managed install never downloads here: it only says so.
if (loadSettings().autoUpdate && !info.manual) {
await install(true)
return
}
Expand Down Expand Up @@ -545,8 +572,18 @@
{applyOnQuit ? 'It installs when you quit, so the next start is the new version. Restart now to use it straight away.' : 'Restart Stroke to finish installing it.'}
{:else if status === 'downloading'}
{totalBytes > 0 ? `${fmt(downloadedBytes)} of ${fmt(totalBytes)}` : 'Starting'}. It keeps going if you close this.
{:else if manual}
{manualCommand ? 'Your package manager installed Stroke, so it updates there:' : 'Your package manager installed Stroke, so it updates there. Get the new package from the download page.'}
{/if}
</p>
{#if manual && manualCommand && status === 'available'}
<div class="mt-2 flex items-center gap-1 rounded-md bg-muted/40 py-1 ps-3 pe-1">
<code class="min-w-0 flex-1 truncate font-mono text-ui-xs text-foreground select-all">{manualCommand}</code>
<button type="button" class="inline-flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-ui-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground" onclick={() => void copyCommand()}>
{#if copied}<CheckCircle2 class="size-3.5 shrink-0 text-success" />Copied{:else}Copy{/if}
</button>
</div>
{/if}
{/if}
<button
type="button"
Expand Down Expand Up @@ -582,6 +619,7 @@
{/if}

<div class={cn('flex flex-wrap items-center gap-3 border-t border-border/40 px-6 py-4', status === 'error' && 'mt-5')}>
{#if manual}<span class="min-w-0 flex-1"></span>{:else}
<label class="flex min-w-0 flex-1 cursor-pointer items-center gap-2 text-ui-xs text-muted-foreground">
<input
type="checkbox"
Expand All @@ -591,6 +629,7 @@
/>
<span class="min-w-0">Download and install updates automatically</span>
</label>
{/if}
<div class="flex shrink-0 items-center gap-2">
{#if status === 'error'}
<Button variant="ghost" onclick={() => (dismissed = true)}>Not now</Button>
Expand All @@ -602,6 +641,13 @@
</Button>
{:else if status === 'downloading'}
<Button variant="ghost" onclick={() => (dismissed = true)}>Hide</Button>
{:else if manual}
<Button variant="ghost" onclick={() => (dismissed = true)}>Later</Button>
{#if manualCommand}
<Button onclick={() => void copyCommand()}>{copied ? 'Copied' : 'Copy command'}</Button>
{:else}
<Button onclick={() => void openDownloads()}>Download page<ExternalLink class="size-3.5 shrink-0" /></Button>
{/if}
{:else}
<Button variant="ghost" onclick={() => (dismissed = true)}>Later</Button>
<Button onclick={() => void install()}><Download class="size-3.5 shrink-0" />Install</Button>
Expand Down
Loading