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
331 changes: 42 additions & 289 deletions src/main/index.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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')
}

Expand All @@ -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<void> {
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<void> {
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<VmWork, string> = {
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<boolean> {
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<boolean> {
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<void> {
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
Expand All @@ -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<void> {
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<void> {
const runner = backend!.runner
Expand All @@ -351,91 +169,6 @@ async function guestBack(name: string, timeoutMs: number): Promise<void> {
}
}

async function shutDownAllAndQuit(): Promise<void> {
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<boolean> {
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(() => {
Expand Down Expand Up @@ -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()
Expand Down
Loading
Loading