diff --git a/src/main/index.ts b/src/main/index.ts index 282f3f1..08c0410 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,27 +1,21 @@ -import { app, BrowserWindow, dialog, Menu, nativeImage, shell, Tray, type MenuItemConstructorOptions } from 'electron' +import { app, BrowserWindow, dialog, Menu, nativeImage, shell, Tray } from 'electron' import { join } from 'node:path' import icon from '../../resources/icon.png?asset' -import { workLabel, workText, type AppSettings, type CloseBehavior, type VmWork } from '@shared/ipc' +import type { AppSettings, CloseBehavior } from '@shared/ipc' import { agentCall } from './agent' import { registerIpc, type Backend } from './ipc' import { dataPaths, type DataPaths } from './paths' +import { QuitFlow, trayMenu } from './quitFlow' import { defaultSettings, loadSettings, saveSettings } from './settings' let mainWindow: BrowserWindow | null = null let tray: Tray | null = null let backend: Backend | null = null let settings: AppSettings +// the questions and the waiting behind closing the window and quitting, see quitFlow.ts +let quitFlow: QuitFlow | null = null // set once quitting is decided, so the window's close handler lets it through let quitting = false -// Shut down VMs and quit is waiting for the guests. Closing or quitting again does nothing meanwhile -let shuttingDown = false -// Quit when it's done is waiting for profile or disk work. Ends the wait: true quits right away, false stays -let endWorkWait: ((quit: boolean) => void) | null = null -// the still working question is open. Quit and close don't open a second one meanwhile -let askingAboutWork = false -// a question about running VMs is open (still running, or Force off at the end of a shut down). -// Same rule: no second copy from the tray or the window, and closing the window leaves it up -let askingAboutVms = false // a second copy would start the same VMs again and fight over their disks, so it only // brings this window to the front @@ -81,17 +75,8 @@ function createWindow(): void { // closing the window used to kill every running VM with it // and closing it with only a compact or a profile save going cut that off win.on('close', (e) => { - if (quitting || !backend) return - // a question is already up on this window, it gets answered there. This comes first because - // the last guest can power itself off while the question is up, and closing the window then - // takes the question with it and quits through window-all-closed - if (askingAboutWork || askingAboutVms) return e.preventDefault() - if (backend.runner.runningNames().length === 0 && !hasWork()) return - e.preventDefault() - // already waiting for the guests or the work: just put the window away again - if (shuttingDown || endWorkWait) win.hide() - else if (settings.closeBehavior === 'tray') hideToTray() - else void quitFromClose() + if (quitting || !quitFlow) return + if (quitFlow.onClose()) e.preventDefault() }) // open external links in the real browser, never inside the app @@ -116,43 +101,22 @@ function ensureTray(): void { } function updateTrayMenu(): void { - if (!tray || !backend) return + if (!tray || !backend || !quitFlow) return const runner = backend.runner const names = runner.runningNames() - const work = backend.vmWork() - const vmItems: MenuItemConstructorOptions[] = names.map((n) => { - const status = runner.state(n).status - const w = work[n] - return { - // during a profile save the VM still shows as running until the guest has hibernated - label: `${n} (${w ? workLabel[w].toLowerCase() : status})`, - submenu: [ - // a power button press in the middle of a hibernate can turn it into a plain shutdown. - // Same rule as the toolbar: everything but Force off waits for the work - { label: 'Shut down', enabled: status === 'running' && !w, click: () => void shutDownFromTray(n) }, - { label: 'Force off', click: () => runner.kill(n) } - ] - } + const items = trayMenu({ + names, + status: (n) => runner.state(n).status, + work: backend.vmWork(), + shuttingDown: quitFlow.shuttingDown, + waitingForWork: quitFlow.waitingForWork, + open: showWindow, + shutDown: (n) => void shutDownFromTray(n), + forceOff: (n) => runner.kill(n), + endWait: (q) => quitFlow?.endWait(q), + quit: () => void quitFlow?.requestQuit() }) - tray.setContextMenu( - Menu.buildFromTemplate([ - ...(shuttingDown ? [{ label: 'Shutting down, quits when the VMs are off', enabled: false }, { type: 'separator' as const }] : []), - ...(endWorkWait - ? [ - { label: 'Quits when the work is done', enabled: false }, - { label: 'Quit now', click: () => endWorkWait?.(true) }, - { label: "Don't quit", click: () => endWorkWait?.(false) }, - { type: 'separator' as const } - ] - : []), - { label: 'Open Virtual Machine Manager', click: showWindow }, - { type: 'separator' }, - ...(vmItems.length ? vmItems : [{ label: 'No VMs running', enabled: false }]), - { type: 'separator' }, - // while waiting for the work, Quit now above is the way to quit - ...(endWorkWait ? [] : [{ label: 'Quit', click: () => void requestQuit() }]) - ]) - ) + tray.setContextMenu(Menu.buildFromTemplate(items)) tray.setToolTip(names.length ? `Virtual Machine Manager, ${names.length} running` : 'Virtual Machine Manager') } @@ -179,140 +143,6 @@ function hideToTray(announce = true): void { } } -/** Quit from the tray: same question as closing the window, minus the tray option */ -async function requestQuit(): Promise { - if (shuttingDown || endWorkWait) return - // a question is already up: show it instead of a second copy, so the click isn't a no-op - if (askingAboutWork || askingAboutVms) return showWindow() - if (backend && hasWork() && !(await workFirst())) return - if (!backend || backend.runner.runningNames().length === 0) { - quitting = true - app.quit() - return - } - showWindow() - await askAndQuit(false) -} - -/** closing the window when it doesn't go to the tray */ -async function quitFromClose(): Promise { - if (hasWork() && !(await workFirst())) return - if (backend!.runner.runningNames().length === 0) { - quitting = true - app.quit() - } else if (settings.closeBehavior === 'quit') await shutDownAllAndQuit() - else await askAndQuit(true) -} - -function hasWork(): boolean { - return Object.keys(backend!.vmWork()).length > 0 -} - -/** what quitting in the middle of the work leaves behind */ -const cutOff: Record = { - saving: 'no profile is made and the VM is not started again', - launching: 'the VM may be rolled back to the profile without being started', - removing: 'the profile may not be deleted', - cloning: 'the unfinished copy of the disk stays in the disks folder', - compacting: 'the unfinished compacted copy stays next to the disk until the next compact', - growing: 'the disk may not get its new size' -} - -const WAIT = "Quit when it's done" -const NOW = 'Quit anyway' - -/** - * Asked before quitting while a profile save or disk work runs, none of which survives the app - * quitting. True to go on with the quit (right away, or once the work has finished), false to stay. - */ -async function workFirst(): Promise { - const work = Object.entries(backend!.vmWork()) - const buttons = [WAIT, NOW, 'Cancel'] - const opts = { - type: 'warning' as const, - title: 'Still working', - message: work.map(([n, w]) => `${n} is ${workText[w]}.`).join('\n'), - detail: `If the app quits now, ${[...new Set(work.map(([, w]) => cutOff[w]))].join(', and ')}.`, - buttons, - cancelId: 2, - defaultId: 0, - noLink: true - } - showWindow() - askingAboutWork = true - let choice: string | undefined - try { - const r = mainWindow ? await dialog.showMessageBox(mainWindow, opts) : await dialog.showMessageBox(opts) - choice = buttons[r.response] - } finally { - askingAboutWork = false - } - if (choice === NOW) return true - if (choice !== WAIT) return false - // the work may have finished while the question was up - if (!hasWork()) return true - hideToTray(false) - tray?.displayBalloon({ - title: 'Quitting when the work is done', - content: 'The app quits once it has finished. Right-click the tray icon to quit now or to stay.', - noSound: true - }) - return allWorkDone() -} - -/** resolves true once no VM has work running or Quit now was picked in the tray, false for Don't quit */ -function allWorkDone(): Promise { - return new Promise((resolve) => { - const finish = (quit: boolean) => { - off() - endWorkWait = null - updateTrayMenu() - resolve(quit) - } - const off = backend!.onWork(() => { - if (!hasWork()) finish(true) - }) - endWorkWait = finish - updateTrayMenu() - }) -} - -const KEEP = 'Keep them running in the tray' -const SHUT = 'Shut down VMs and quit' - -async function askAndQuit(fromClose: boolean): Promise { - if (shuttingDown || askingAboutVms) return - // after Quit when it's done the window is in the tray - showWindow() - const names = backend!.runner.runningNames() - const buttons = fromClose ? [KEEP, SHUT, 'Cancel'] : [SHUT, 'Cancel'] - const opts = { - type: 'question' as const, - title: 'VMs are still running', - message: `${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} still running.`, - detail: fromClose - ? 'In the tray they keep running and you can open the app again from the tray icon. Shutting down asks each guest to shut down cleanly first.' - : 'Shutting down asks each guest to shut down cleanly first.', - buttons, - cancelId: buttons.length - 1, - defaultId: 0, - // only when closing: from the tray's Quit there's just one real choice to remember - checkboxLabel: fromClose ? "Don't ask again (change this in Settings)" : undefined, - noLink: true - } - askingAboutVms = true - let r: Electron.MessageBoxReturnValue - try { - r = mainWindow ? await dialog.showMessageBox(mainWindow, opts) : await dialog.showMessageBox(opts) - } finally { - askingAboutVms = false - } - const choice = buttons[r.response] - if (r.checkboxChecked && (choice === KEEP || choice === SHUT)) rememberClose(choice === KEEP ? 'tray' : 'quit') - if (choice === KEEP) return hideToTray() - if (choice === SHUT) return shutDownAllAndQuit() -} - function rememberClose(closeBehavior: CloseBehavior): void { settings = { ...settings, closeBehavior } // with VMM_DATA_ROOT set, settings.dataRoot is the temp folder. The file keeps its own @@ -325,18 +155,6 @@ function rememberClose(closeBehavior: CloseBehavior): void { } } -/** resolves once the VM has no profile operation or disk work running */ -function workDone(name: string): Promise { - return new Promise((resolve) => { - if (!backend!.vmWork()[name]) return resolve() - const off = backend!.onWork(() => { - if (backend!.vmWork()[name]) return - off() - resolve() - }) - }) -} - /** waits until the guest agent answers, up to timeoutMs. Gives up early if the VM goes away */ async function guestBack(name: string, timeoutMs: number): Promise { const runner = backend!.runner @@ -351,91 +169,6 @@ async function guestBack(name: string, timeoutMs: number): Promise { } } -async function shutDownAllAndQuit(): Promise { - const runner = backend!.runner - const names = runner.runningNames() - shuttingDown = true - // the window goes away right away so the click visibly did something. The tray says what's going on - hideToTray(false) // it shows its own balloon below - updateTrayMenu() - tray?.displayBalloon({ - title: 'Shutting down', - content: `Waiting for ${names.length === 1 ? names[0] : `${names.length} VMs`} to shut down, then the app quits.`, - noSound: true - }) - // a paused guest can't react to the power button, so let it run first. A VM in the middle of a - // profile save or delete gets the power button press once that's done, not while the guest hibernates - await Promise.all( - names.map(async (n) => { - const saving = backend!.vmWork()[n] === 'saving' - await workDone(n) - if (!runner.isRunning(n)) return - // a session save boots the VM again right before it ends, and the guest misses a power button - // press while it's still resuming from hibernate. It has the agent, so wait for that to answer - if (saving) await guestBack(n, 120_000) - try { - if (runner.state(n).status === 'paused') await runner.resume(n) - await runner.shutdown(n) - } catch { - // no QMP connection: it ends up in the force off question below - } - }) - ) - if (!(await waitForShutdown(names))) return - quitting = true - app.quit() -} - -const FORCE = 'Force off and quit' -const MORE = 'Wait another minute' -const MINUTE = 60_000 - -/** - * Waits a minute for each guest, then asks about the ones still up. True to go on with the quit, - * false if the user cancelled. A Windows guest installing updates on shutdown regularly needs - * longer than a minute, so the question offers another minute as well as Force off. - */ -async function waitForShutdown(names: string[]): Promise { - const runner = backend!.runner - let waiting = names - // real time, not rounds of the question: it counts a question left unanswered for a while too - const since = Date.now() - for (;;) { - const done = await Promise.all(waiting.map((n) => runner.waitForExit(n, MINUTE))) - waiting = waiting.filter((_n, i) => !done[i]) - if (!waiting.length) return true - const minutes = Math.max(1, Math.round((Date.now() - since) / MINUTE)) - const opts = { - type: 'warning' as const, - title: 'Still running', - message: `${waiting.join(', ')} ${waiting.length === 1 ? 'has' : 'have'} not shut down ${minutes === 1 ? 'within a minute' : `in ${minutes} minutes`}.`, - detail: `A guest installing updates on shutdown can take a few minutes. Force off loses anything unsaved inside ${waiting.length === 1 ? 'it' : 'them'}.`, - buttons: [MORE, FORCE, 'Cancel'], - cancelId: 2, - defaultId: 0, - noLink: true - } - showWindow() - // same as the other questions: closing the window leaves this one up instead of hiding it - askingAboutVms = true - let r: Electron.MessageBoxReturnValue - try { - r = mainWindow ? await dialog.showMessageBox(mainWindow, opts) : await dialog.showMessageBox(opts) - } finally { - askingAboutVms = false - } - const choice = opts.buttons[r.response] - if (choice === FORCE) return true - if (choice !== MORE) { - shuttingDown = false - updateTrayMenu() - return false - } - // back out of the way for the next minute, the tray already says what the app is waiting for - hideToTray(false) - } -} - app.on('second-instance', showWindow) app.whenReady().then(() => { @@ -465,8 +198,28 @@ app.whenReady().then(() => { app.quit() // before-quit still stops the folder watcher and the usage sampler } }) - backend.runner.on('state', updateTrayMenu) - backend.onWork(updateTrayMenu) + const be = backend + quitFlow = new QuitFlow({ + runner: be.runner, + vmWork: () => be.vmWork(), + onWork: (cb) => be.onWork(cb), + ask: (q) => (mainWindow ? dialog.showMessageBox(mainWindow, q) : dialog.showMessageBox(q)), + show: showWindow, + hide: () => mainWindow?.hide(), + toTray: hideToTray, + balloon: (b) => tray?.displayBalloon({ ...b, noSound: true }), + updateTray: updateTrayMenu, + quit: () => { + quitting = true + app.quit() + }, + closeBehavior: () => settings.closeBehavior, + rememberClose, + guestBack, + now: () => Date.now() + }) + be.runner.on('state', updateTrayMenu) + be.onWork(updateTrayMenu) app.on('before-quit', () => { quitting = true backend?.dispose() diff --git a/src/main/quitFlow.ts b/src/main/quitFlow.ts new file mode 100644 index 0000000..e0783d8 --- /dev/null +++ b/src/main/quitFlow.ts @@ -0,0 +1,372 @@ +import { workLabel, workText, type CloseBehavior, type VmWork } from '@shared/ipc' + +/** A message box, the same shape Electron's dialog.showMessageBox takes. */ +export interface Question { + type: 'question' | 'warning' + title: string + message: string + detail?: string + buttons: string[] + cancelId: number + defaultId?: number + checkboxLabel?: string + noLink: true +} + +export interface Answer { + response: number + checkboxChecked?: boolean +} + +/** What the quit flow needs from VmRunner. */ +export interface QuitRunner { + runningNames(): string[] + isRunning(name: string): boolean + state(name: string): { status: string } + resume(name: string): Promise + shutdown(name: string): Promise + waitForExit(name: string, timeoutMs: number): Promise +} + +/** What the quit flow needs from the app around it: the window, the tray and the dialogs. */ +export interface QuitHost { + runner: QuitRunner + /** VMs with a profile operation or disk work running, and which */ + vmWork(): Record + /** called whenever a VM starts or finishes work, returns a function that stops it */ + onWork(cb: () => void): () => void + /** shows a message box on the main window and resolves with the button the user picked */ + ask(q: Question): Promise + /** brings the window up, creating it again if it was closed */ + show(): void + /** hides the window without saying anything about the tray */ + hide(): void + /** hides the window to the tray; announce says where it went, the first time in a run */ + toTray(announce?: boolean): void + balloon(b: { title: string; content: string }): void + /** rebuilds the tray menu, which shows what the app is waiting for */ + updateTray(): void + /** quits for real */ + quit(): void + closeBehavior(): CloseBehavior + /** saves a new close behavior, for the question's Don't ask again */ + rememberClose(b: CloseBehavior): void + /** waits until the guest agent answers again, up to timeoutMs */ + guestBack(name: string, timeoutMs: number): Promise + now(): number +} + +/** what quitting in the middle of the work leaves behind */ +const cutOff: Record = { + saving: 'no profile is made and the VM is not started again', + launching: 'the VM may be rolled back to the profile without being started', + removing: 'the profile may not be deleted', + cloning: 'the unfinished copy of the disk stays in the disks folder', + compacting: 'the unfinished compacted copy stays next to the disk until the next compact', + growing: 'the disk may not get its new size' +} + +const WAIT = "Quit when it's done" +const NOW = 'Quit anyway' +const KEEP = 'Keep them running in the tray' +const SHUT = 'Shut down VMs and quit' +const FORCE = 'Force off and quit' +const MORE = 'Wait another minute' +const MINUTE = 60_000 + +/** + * Closing the window and quitting: the questions about running VMs and unfinished work, the + * waiting that follows, and what the tray offers meanwhile. It keeps no Electron objects of its + * own, so the orderings here (work finishing while a question is open, a guest that never shuts + * down) can be tested with fakes. + */ +export class QuitFlow { + private shutting = false + /** a question is open on the window: no second copy, and closing the window leaves it up */ + private asking = false + /** set while Quit when it's done waits. Ends the wait: true quits right away, false stays */ + private endWorkWait: ((quit: boolean) => void) | null = null + + constructor(private readonly host: QuitHost) {} + + /** true while Shut down VMs and quit is waiting for the guests */ + get shuttingDown(): boolean { + return this.shutting + } + + /** true while Quit when it's done is waiting for profile or disk work */ + get waitingForWork(): boolean { + return this.endWorkWait !== null + } + + /** the tray's Quit now and Don't quit while the work is being waited for */ + endWait(quit: boolean): void { + this.endWorkWait?.(quit) + } + + /** + * The window's close button. True to keep the window (the caller calls preventDefault), false + * to let it close. Anything else that has to happen is started here. + */ + onClose(): boolean { + const host = this.host + // a question is already up on this window, it gets answered there. This comes first because + // the last guest can power itself off while the question is up, and closing the window then + // takes the question with it + if (this.asking) return true + if (host.runner.runningNames().length === 0 && !this.hasWork()) return false + // already waiting for the guests or the work: just put the window away again + if (this.shutting || this.endWorkWait) host.hide() + else if (host.closeBehavior() === 'tray') host.toTray() + else void this.quitFromClose() + return true + } + + /** Quit from the tray: same questions as closing the window, minus the tray option */ + async requestQuit(): Promise { + const host = this.host + if (this.shutting || this.endWorkWait) return + // a question is already up: show it instead of a second copy, so the click isn't a no-op + if (this.asking) return host.show() + if (this.hasWork() && !(await this.workFirst())) return + if (host.runner.runningNames().length === 0) return host.quit() + host.show() + await this.askAndQuit(false) + } + + /** closing the window when it doesn't go to the tray */ + private async quitFromClose(): Promise { + const host = this.host + if (this.hasWork() && !(await this.workFirst())) return + if (host.runner.runningNames().length === 0) return host.quit() + if (host.closeBehavior() === 'quit') return this.shutDownAllAndQuit() + await this.askAndQuit(true) + } + + private hasWork(): boolean { + return Object.keys(this.host.vmWork()).length > 0 + } + + /** asks, and marks a question as open for as long as it is up. Undefined choice: dismissed */ + private async question(q: Question): Promise<{ choice?: string; checked?: boolean }> { + this.asking = true + try { + const r = await this.host.ask(q) + return { choice: q.buttons[r.response], checked: r.checkboxChecked } + } finally { + this.asking = false + } + } + + /** + * Asked before quitting while a profile save or disk work runs, none of which survives the app + * quitting. True to go on with the quit (right away, or once the work has finished), false to stay. + */ + private async workFirst(): Promise { + const host = this.host + const work = Object.entries(host.vmWork()) + host.show() + const { choice } = await this.question({ + type: 'warning', + title: 'Still working', + message: work.map(([n, w]) => `${n} is ${workText[w]}.`).join('\n'), + detail: `If the app quits now, ${[...new Set(work.map(([, w]) => cutOff[w]))].join(', and ')}.`, + buttons: [WAIT, NOW, 'Cancel'], + cancelId: 2, + defaultId: 0, + noLink: true + }) + if (choice === NOW) return true + if (choice !== WAIT) return false + // the work may have finished while the question was up + if (!this.hasWork()) return true + host.toTray(false) + host.balloon({ + title: 'Quitting when the work is done', + content: 'The app quits once it has finished. Right-click the tray icon to quit now or to stay.' + }) + return this.allWorkDone() + } + + /** resolves true once no VM has work running or Quit now was picked in the tray, false for Don't quit */ + private allWorkDone(): Promise { + return new Promise((resolve) => { + const finish = (quit: boolean): void => { + off() + this.endWorkWait = null + this.host.updateTray() + resolve(quit) + } + const off = this.host.onWork(() => { + if (!this.hasWork()) finish(true) + }) + this.endWorkWait = finish + this.host.updateTray() + }) + } + + private async askAndQuit(fromClose: boolean): Promise { + const host = this.host + if (this.shutting || this.asking) return + // after Quit when it's done the window is in the tray + host.show() + const names = host.runner.runningNames() + const { choice, checked } = await this.question({ + type: 'question', + title: 'VMs are still running', + message: `${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} still running.`, + detail: fromClose + ? 'In the tray they keep running and you can open the app again from the tray icon. Shutting down asks each guest to shut down cleanly first.' + : 'Shutting down asks each guest to shut down cleanly first.', + buttons: fromClose ? [KEEP, SHUT, 'Cancel'] : [SHUT, 'Cancel'], + cancelId: fromClose ? 2 : 1, + defaultId: 0, + // only when closing: from the tray's Quit there's just one real choice to remember + checkboxLabel: fromClose ? "Don't ask again (change this in Settings)" : undefined, + noLink: true + }) + if (checked && (choice === KEEP || choice === SHUT)) { + host.rememberClose(choice === KEEP ? 'tray' : 'quit') + } + if (choice === KEEP) return host.toTray() + if (choice === SHUT) return this.shutDownAllAndQuit() + } + + private async shutDownAllAndQuit(): Promise { + const host = this.host + const runner = host.runner + const names = runner.runningNames() + this.shutting = true + // the window goes away right away so the click visibly did something. The tray says what's going on + host.toTray(false) // it shows its own balloon below + host.updateTray() + host.balloon({ + title: 'Shutting down', + content: `Waiting for ${names.length === 1 ? names[0] : `${names.length} VMs`} to shut down, then the app quits.` + }) + // a paused guest can't react to the power button, so let it run first. A VM in the middle of a + // profile save or delete gets the power button press once that's done, not while the guest hibernates + await Promise.all( + names.map(async (n) => { + const saving = host.vmWork()[n] === 'saving' + await this.workDone(n) + if (!runner.isRunning(n)) return + // a session save boots the VM again right before it ends, and the guest misses a power button + // press while it's still resuming from hibernate. It has the agent, so wait for that to answer + if (saving) await host.guestBack(n, 120_000) + try { + if (runner.state(n).status === 'paused') await runner.resume(n) + await runner.shutdown(n) + } catch { + // no QMP connection: it ends up in the force off question below + } + }) + ) + if (!(await this.waitForShutdown(names))) return + host.quit() + } + + /** + * Waits a minute for each guest, then asks about the ones still up. True to go on with the quit, + * false if the user cancelled. A Windows guest installing updates on shutdown regularly needs + * longer than a minute, so the question offers another minute as well as Force off. + */ + private async waitForShutdown(names: string[]): Promise { + const host = this.host + let waiting = names + // real time, not rounds of the question: it counts a question left unanswered for a while too + const since = host.now() + for (;;) { + const done = await Promise.all(waiting.map((n) => host.runner.waitForExit(n, MINUTE))) + waiting = waiting.filter((_n, i) => !done[i]) + if (!waiting.length) return true + const minutes = Math.max(1, Math.round((host.now() - since) / MINUTE)) + host.show() + const { choice } = await this.question({ + type: 'warning', + title: 'Still running', + message: `${waiting.join(', ')} ${waiting.length === 1 ? 'has' : 'have'} not shut down ${minutes === 1 ? 'within a minute' : `in ${minutes} minutes`}.`, + detail: `A guest installing updates on shutdown can take a few minutes. Force off loses anything unsaved inside ${waiting.length === 1 ? 'it' : 'them'}.`, + buttons: [MORE, FORCE, 'Cancel'], + cancelId: 2, + defaultId: 0, + noLink: true + }) + if (choice === FORCE) return true + if (choice !== MORE) { + this.shutting = false + host.updateTray() + return false + } + // back out of the way for the next minute, the tray already says what the app is waiting for + host.toTray(false) + } + } + + /** resolves once the VM has no profile operation or disk work running */ + private workDone(name: string): Promise { + return new Promise((resolve) => { + if (!this.host.vmWork()[name]) return resolve() + const off = this.host.onWork(() => { + if (this.host.vmWork()[name]) return + off() + resolve() + }) + }) + } +} + +/** A tray menu item, the subset of Electron's MenuItemConstructorOptions the tray menu uses. */ +export interface TrayItem { + label?: string + type?: 'separator' + enabled?: boolean + click?: () => void + submenu?: TrayItem[] +} + +/** The tray menu: what the app is waiting for, each running VM, and Quit. */ +export function trayMenu(o: { + names: string[] + status: (name: string) => string + work: Record + shuttingDown: boolean + waitingForWork: boolean + open: () => void + shutDown: (name: string) => void + forceOff: (name: string) => void + endWait: (quit: boolean) => void + quit: () => void +}): TrayItem[] { + const vmItems: TrayItem[] = o.names.map((n) => { + const status = o.status(n) + const w = o.work[n] + return { + // during a profile save the VM still shows as running until the guest has hibernated + label: `${n} (${w ? workLabel[w].toLowerCase() : status})`, + submenu: [ + // a power button press in the middle of a hibernate can turn it into a plain shutdown. + // Same rule as the toolbar: everything but Force off waits for the work + { label: 'Shut down', enabled: status === 'running' && !w, click: () => o.shutDown(n) }, + { label: 'Force off', click: () => o.forceOff(n) } + ] + } + }) + return [ + ...(o.shuttingDown ? [{ label: 'Shutting down, quits when the VMs are off', enabled: false }, { type: 'separator' as const }] : []), + ...(o.waitingForWork + ? [ + { label: 'Quits when the work is done', enabled: false }, + { label: 'Quit now', click: () => o.endWait(true) }, + { label: "Don't quit", click: () => o.endWait(false) }, + { type: 'separator' as const } + ] + : []), + { label: 'Open Virtual Machine Manager', click: o.open }, + { type: 'separator' as const }, + ...(vmItems.length ? vmItems : [{ label: 'No VMs running', enabled: false }]), + { type: 'separator' as const }, + // while waiting for the work, Quit now above is the way to quit + ...(o.waitingForWork ? [] : [{ label: 'Quit', click: o.quit }]) + ] +} diff --git a/tests/quitFlow.test.ts b/tests/quitFlow.test.ts new file mode 100644 index 0000000..94aeddb --- /dev/null +++ b/tests/quitFlow.test.ts @@ -0,0 +1,384 @@ +import { describe, expect, it } from 'vitest' +import type { CloseBehavior, VmWork } from '@shared/ipc' +import { QuitFlow, trayMenu, type Question, type QuitHost } from '../src/main/quitFlow' + +const KEEP = 'Keep them running in the tray' +const SHUT = 'Shut down VMs and quit' +const WAIT = "Quit when it's done" +const NOW = 'Quit anyway' +const MORE = 'Wait another minute' +const FORCE = 'Force off and quit' + +class FakeRunner { + running = new Set() + statuses: Record = {} + /** guests that ignore the power button, so waitForExit times out */ + stuck = new Set() + calls: string[] = [] + + runningNames(): string[] { + return [...this.running] + } + isRunning(name: string): boolean { + return this.running.has(name) + } + state(name: string): { status: string } { + return { status: this.statuses[name] ?? 'running' } + } + async resume(name: string): Promise { + this.calls.push(`resume:${name}`) + this.statuses[name] = 'running' + } + async shutdown(name: string): Promise { + this.calls.push(`shutdown:${name}`) + if (!this.stuck.has(name)) this.running.delete(name) + } + async waitForExit(name: string): Promise { + this.calls.push(`wait:${name}`) + return !this.running.has(name) + } +} + +/** what the answer callback says: the button to click, and the checkbox if there is one */ +type Click = string | { button: string; checked: boolean } + +function setup(o: { running?: string[]; statuses?: Record; work?: Record; closeBehavior?: CloseBehavior; answer?: (q: Question) => Click } = {}) { + const runner = new FakeRunner() + for (const n of o.running ?? []) runner.running.add(n) + Object.assign(runner.statuses, o.statuses ?? {}) + let work: Record = { ...(o.work ?? {}) } + const workCbs = new Set<() => void>() + const asked: Question[] = [] + const log: string[] = [] + let remembered: CloseBehavior | null = null + let now = 0 + const host: QuitHost = { + runner, + vmWork: () => work, + onWork: (cb) => { + workCbs.add(cb) + return () => workCbs.delete(cb) + }, + ask: async (q) => { + asked.push(q) + const click = o.answer?.(q) ?? q.buttons[q.cancelId] + const button = typeof click === 'string' ? click : click.button + const response = q.buttons.indexOf(button) + if (response < 0) throw new Error(`no ${button} button in ${q.buttons.join(' / ')}`) + return { response, checkboxChecked: typeof click === 'string' ? false : click.checked } + }, + show: () => log.push('show'), + hide: () => log.push('hide'), + toTray: (announce) => log.push(`toTray:${announce !== false}`), + balloon: (b) => log.push(`balloon:${b.title}`), + updateTray: () => log.push('updateTray'), + quit: () => log.push('quit'), + closeBehavior: () => o.closeBehavior ?? 'ask', + rememberClose: (b) => { + remembered = b + }, + guestBack: async (name) => void log.push(`guestBack:${name}`), + now: () => now + } + const flow = new QuitFlow(host) + return { + flow, + runner, + asked, + log, + get remembered(): CloseBehavior | null { + return remembered + }, + titles: (): string[] => asked.map((q) => q.title), + /** replaces the work and tells the flow about it, like the IPC layer does */ + setWork(next: Record): void { + work = next + for (const cb of [...workCbs]) cb() + }, + advance(ms: number): void { + now += ms + } + } +} + +/** lets the pending promises inside the flow run */ +const settle = (): Promise => new Promise((r) => setTimeout(r, 0)) + +describe('QuitFlow.onClose', () => { + it('lets the window close when nothing is running and nothing is working', () => { + const t = setup() + expect(t.flow.onClose()).toBe(false) + expect(t.asked).toEqual([]) + }) + + it('hides to the tray without asking when that is the close behavior', () => { + const t = setup({ running: ['win11'], closeBehavior: 'tray' }) + expect(t.flow.onClose()).toBe(true) + expect(t.log).toEqual(['toTray:true']) + expect(t.asked).toEqual([]) + }) + + it('asks about running VMs and does nothing on Cancel', async () => { + const t = setup({ running: ['win11', 'kali'], answer: () => 'Cancel' }) + expect(t.flow.onClose()).toBe(true) + await settle() + expect(t.asked).toHaveLength(1) + expect(t.asked[0].message).toBe('win11, kali are still running.') + expect(t.asked[0].buttons).toEqual([KEEP, SHUT, 'Cancel']) + expect(t.log).not.toContain('quit') + expect(t.runner.calls).toEqual([]) + }) + + it("remembers the close behavior when Don't ask again is ticked", async () => { + const t = setup({ running: ['win11'], answer: () => ({ button: KEEP, checked: true }) }) + t.flow.onClose() + await settle() + expect(t.remembered).toBe('tray') + expect(t.log).toContain('toTray:true') + }) + + it('resumes a paused guest before pressing the power button, then quits', async () => { + const t = setup({ running: ['win11', 'kali'], statuses: { kali: 'paused' }, answer: () => SHUT }) + t.flow.onClose() + await settle() + expect(t.runner.calls).toEqual(['shutdown:win11', 'resume:kali', 'shutdown:kali', 'wait:win11', 'wait:kali']) + expect(t.log).toContain('quit') + }) + + it('shuts down without asking when the close behavior is quit', async () => { + const t = setup({ running: ['win11'], closeBehavior: 'quit' }) + t.flow.onClose() + await settle() + expect(t.asked).toEqual([]) + expect(t.runner.calls).toEqual(['shutdown:win11', 'wait:win11']) + expect(t.log).toContain('quit') + }) + + it('keeps the window and asks only once while a question is open', async () => { + let asks = 0 + const t = setup({ + running: ['win11'], + answer: () => { + asks++ + return 'Cancel' + } + }) + expect(t.flow.onClose()).toBe(true) + expect(t.flow.onClose()).toBe(true) + expect(t.flow.onClose()).toBe(true) + await settle() + expect(asks).toBe(1) + expect(t.log).not.toContain('hide') + }) +}) + +describe('QuitFlow.requestQuit', () => { + it('quits right away with nothing running', async () => { + const t = setup() + await t.flow.requestQuit() + expect(t.asked).toEqual([]) + expect(t.log).toContain('quit') + }) + + it('asks without the tray option', async () => { + const t = setup({ running: ['win11'], answer: () => 'Cancel' }) + await t.flow.requestQuit() + expect(t.asked[0].buttons).toEqual([SHUT, 'Cancel']) + }) + + it('shows the window instead of a second question', async () => { + const t = setup({ running: ['win11'], answer: () => 'Cancel' }) + const closing = t.flow.onClose() + await t.flow.requestQuit() + expect(closing).toBe(true) + expect(t.asked).toHaveLength(1) + expect(t.log.filter((l) => l === 'show').length).toBeGreaterThan(1) + await settle() + }) +}) + +describe('QuitFlow work in progress', () => { + it('names the work and what quitting loses', async () => { + const t = setup({ work: { win11: 'saving', kali: 'compacting' }, answer: () => 'Cancel' }) + await t.flow.requestQuit() + expect(t.asked[0].title).toBe('Still working') + expect(t.asked[0].message).toBe('win11 is saving a profile.\nkali is having its disk compacted.') + expect(t.asked[0].detail).toContain('no profile is made') + expect(t.log).not.toContain('quit') + }) + + it('quits anyway when asked to, without waiting', async () => { + const t = setup({ work: { win11: 'cloning' }, answer: () => NOW }) + await t.flow.requestQuit() + expect(t.log).toContain('quit') + }) + + it('waits for the work, then quits', async () => { + const t = setup({ work: { win11: 'compacting' }, answer: () => WAIT }) + const quitting = t.flow.requestQuit() + await settle() + expect(t.flow.waitingForWork).toBe(true) + expect(t.log).toContain('balloon:Quitting when the work is done') + expect(t.log).not.toContain('quit') + t.setWork({}) + await quitting + expect(t.flow.waitingForWork).toBe(false) + expect(t.log).toContain('quit') + }) + + it('does not wait when the work finished while the question was open', async () => { + // the work ends with the question still up, so there is nothing left to wait for + const t: ReturnType = setup({ + work: { win11: 'compacting' }, + answer: () => { + t.setWork({}) + return WAIT + } + }) + await t.flow.requestQuit() + expect(t.flow.waitingForWork).toBe(false) + expect(t.log).not.toContain('balloon:Quitting when the work is done') + expect(t.log).toContain('quit') + }) + + it("stays when Don't quit is picked in the tray while waiting", async () => { + const t = setup({ work: { win11: 'compacting' }, answer: () => WAIT }) + const quitting = t.flow.requestQuit() + await settle() + t.flow.endWait(false) + await quitting + expect(t.flow.waitingForWork).toBe(false) + expect(t.log).not.toContain('quit') + }) + + it('quits now when the tray says so, with the work still running', async () => { + const t = setup({ running: [], work: { win11: 'compacting' }, answer: () => WAIT }) + const quitting = t.flow.requestQuit() + await settle() + t.flow.endWait(true) + await quitting + expect(t.log).toContain('quit') + }) + + it('presses the power button only once a VM has finished its work', async () => { + // a profile save started while the question was up: a hibernating guest must not get the + // power button in the middle of it + const t: ReturnType = setup({ + running: ['win11'], + answer: () => { + t.setWork({ win11: 'saving' }) + return SHUT + } + }) + t.flow.onClose() + await settle() + expect(t.runner.calls).toEqual([]) + t.setWork({}) + await settle() + // a save boots the VM again at the end, so it waits for the agent before the power button + expect(t.log).toContain('guestBack:win11') + expect(t.runner.calls).toEqual(['shutdown:win11', 'wait:win11']) + expect(t.log).toContain('quit') + }) +}) + +describe('QuitFlow guests that do not shut down', () => { + it('waits another minute and quits when the guest goes away', async () => { + const t = setup({ + running: ['win11'], + closeBehavior: 'quit', + answer: (q) => { + expect(q.title).toBe('Still running') + expect(q.message).toBe('win11 has not shut down within a minute.') + t.runner.running.delete('win11') + return MORE + } + }) + t.runner.stuck.add('win11') + t.flow.onClose() + await settle() + expect(t.asked).toHaveLength(1) + expect(t.runner.calls).toEqual(['shutdown:win11', 'wait:win11', 'wait:win11']) + expect(t.log).toContain('quit') + }) + + it('counts the real wait, not the number of questions', async () => { + const t = setup({ + running: ['win11', 'kali'], + closeBehavior: 'quit', + answer: (q) => { + if (t.asked.length === 1) { + t.advance(4 * 60_000) + return MORE + } + expect(q.message).toBe('win11, kali have not shut down in 4 minutes.') + expect(q.detail).toContain('unsaved inside them') + return FORCE + } + }) + t.runner.stuck.add('win11') + t.runner.stuck.add('kali') + t.flow.onClose() + await settle() + expect(t.asked).toHaveLength(2) + expect(t.log).toContain('quit') + }) + + it('stops the quit on Cancel and puts the tray back', async () => { + const t = setup({ running: ['win11'], closeBehavior: 'quit', answer: () => 'Cancel' }) + t.runner.stuck.add('win11') + t.flow.onClose() + await settle() + expect(t.flow.shuttingDown).toBe(false) + expect(t.log).not.toContain('quit') + expect(t.log.filter((l) => l === 'updateTray').length).toBeGreaterThan(1) + }) +}) + +describe('trayMenu', () => { + const base = { + names: [] as string[], + status: () => 'running', + work: {} as Record, + shuttingDown: false, + waitingForWork: false, + open: () => undefined, + shutDown: () => undefined, + forceOff: () => undefined, + endWait: () => undefined, + quit: () => undefined + } + const labels = (items: ReturnType): string[] => items.filter((i) => i.label).map((i) => i.label as string) + + it('says when no VM is running and offers Quit', () => { + const items = trayMenu(base) + expect(labels(items)).toEqual(['Open Virtual Machine Manager', 'No VMs running', 'Quit']) + }) + + it('disables Shut down for a VM with work running', () => { + const items = trayMenu({ ...base, names: ['win11'], work: { win11: 'saving' } }) + const vm = items.find((i) => i.label?.startsWith('win11')) + expect(vm?.label).toBe('win11 (saving profile)') + expect(vm?.submenu?.map((s) => [s.label, s.enabled])).toEqual([ + ['Shut down', false], + ['Force off', undefined] + ]) + }) + + it('disables Shut down for a paused VM but keeps Force off', () => { + const items = trayMenu({ ...base, names: ['kali'], status: () => 'paused' }) + const vm = items.find((i) => i.label?.startsWith('kali')) + expect(vm?.label).toBe('kali (paused)') + expect(vm?.submenu?.[0].enabled).toBe(false) + }) + + it('replaces Quit with the two ways out of the work wait', () => { + const items = trayMenu({ ...base, waitingForWork: true }) + expect(labels(items)).toEqual(['Quits when the work is done', 'Quit now', "Don't quit", 'Open Virtual Machine Manager', 'No VMs running']) + }) + + it('says it is shutting down and still offers Quit', () => { + const items = trayMenu({ ...base, names: ['win11'], shuttingDown: true }) + expect(labels(items)).toEqual(['Shutting down, quits when the VMs are off', 'Open Virtual Machine Manager', 'win11 (running)', 'Quit']) + }) +})