diff --git a/src/app/App.tsx b/src/app/App.tsx index ac3dadd4..d1453b1b 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -33,6 +33,7 @@ import CitationModal from './CitationModal'; import ErrorBoundary from './components/ErrorBoundary'; import ErrorDialog from './components/ErrorDialog'; import ModifiedDialog from './components/ModifiedDialog'; +import UpdateDownloadDialog from './components/UpdateDownloadDialog'; const VerticalHeading = styled( Typography )( () => ( { writingMode: 'vertical-rl', @@ -522,6 +523,7 @@ const App = (): React.JSX.Element => { ) : null} + diff --git a/src/app/components/UpdateDownloadDialog.tsx b/src/app/components/UpdateDownloadDialog.tsx new file mode 100644 index 00000000..0618cc95 --- /dev/null +++ b/src/app/components/UpdateDownloadDialog.tsx @@ -0,0 +1,54 @@ +import React from 'react'; +import Dialog from '@mui/material/Dialog'; +import DialogTitle from '@mui/material/DialogTitle'; +import DialogContent from '@mui/material/DialogContent'; +import LinearProgress from '@mui/material/LinearProgress'; +import Typography from '@mui/material/Typography'; +import type { UpdateDownload } from '../../common/rendererBridge'; + +export interface UpdateDownloadDialogProps { + download: UpdateDownload; +} + +function dialogCopy( download: UpdateDownload ): { percent?: number; text: string; detail: string } { + switch ( download.status ) { + case 'connecting': + return { text: 'Starting…', detail: 'Connecting to the update server…' }; + case 'downloading': + case 'restarted': + if ( download.percent < 100 ) { + return { + percent: download.percent, + text: `${Math.round( download.percent )}%`, + detail: download.status === 'restarted' + ? 'Retrying with the full download…' + : 'RAxML-GUI will quit and install when the download finishes.', + }; + } + break; + default: + } + return { percent: 100, text: '100%', detail: 'Download complete. Preparing to install…' }; +} + +export default function UpdateDownloadDialog( { download }: UpdateDownloadDialogProps ): React.JSX.Element | null { + if ( download.status === 'idle' ) { + return null; + } + const { percent, text, detail } = dialogCopy( download ); + return ( + + Downloading update + + + {text} + {detail} + + + ); +} diff --git a/src/app/store/RunList.ts b/src/app/store/RunList.ts index f4878333..9d58b6fc 100644 --- a/src/app/store/RunList.ts +++ b/src/app/store/RunList.ts @@ -1,5 +1,6 @@ import { observable, computed, action, makeObservable } from 'mobx'; import type { StateReport } from '../../main/getActiveState'; +import type { UpdateDownload } from '../../common/rendererBridge'; import Run from './Run'; import AppStore from './AppStore'; import { runEvents } from './StoreBase'; @@ -23,6 +24,8 @@ class RunList extends AppStore { deleteActive: action, onError: action, onUnhandledError: action, + updateDownload: observable, + onUpdateDownload: action, onBackboneConstraint: action, onMultifurcatingConstraint: action, } ); @@ -77,6 +80,12 @@ class RunList extends AppStore { this.error = error; }; + updateDownload: UpdateDownload = { status: 'idle' }; + + onUpdateDownload = ( download: UpdateDownload ): void => { + this.updateDownload = download; + }; + onBackboneConstraint = (): void => { this.activeRun.useBackboneConstraint = !this.activeRun.useBackboneConstraint; @@ -89,6 +98,9 @@ class RunList extends AppStore { listen = (): void => { this.subscribe( runEvents.onUnhandledError, this.onUnhandledError ); + this.subscribe( runEvents.onUpdateDownload, this.onUpdateDownload ); + // A reloaded or reopened page starts mid-download; seed from main's held state. + window.rendererBridge.getUpdateDownload().then( this.onUpdateDownload ); this.subscribe( runEvents.onAddRun, this.addRun ); this.subscribe( runEvents.onRemoveRun, this.deleteActive ); this.subscribe( runEvents.onToggleBackboneConstraint, this.onBackboneConstraint ); diff --git a/src/app/store/StoreBase.ts b/src/app/store/StoreBase.ts index f3c9496f..b0689e00 100644 --- a/src/app/store/StoreBase.ts +++ b/src/app/store/StoreBase.ts @@ -17,6 +17,7 @@ export const runEvents = { onToggleBackboneConstraint: 'onToggleBackboneConstraint', onToggleMultifurcatingConstraint: 'onToggleMultifurcatingConstraint', onUnhandledError: 'onUnhandledError', + onUpdateDownload: 'onUpdateDownload', } as const; export default class StoreBase { diff --git a/src/app/updateDownload.test.tsx b/src/app/updateDownload.test.tsx new file mode 100644 index 00000000..d2a3cde3 --- /dev/null +++ b/src/app/updateDownload.test.tsx @@ -0,0 +1,88 @@ +import { expect, it } from 'vitest'; +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import Page from './index'; +import store from './store'; +import { installBridge } from '../test/setup'; +import type { UpdateDownloadPayload } from '../common/rendererBridge'; + +function title() { + return document.getElementById( 'update-download-title' )?.textContent; +} + +it( 'the page follows the update download in a dialog that cannot be dismissed', () => { + let hear: ( payload: UpdateDownloadPayload ) => void; + installBridge( { + onUpdateDownload( listener ) { + hear = listener; + return () => {}; + }, + } ); + store.listen(); + + const div = document.createElement( 'div' ); + document.body.appendChild( div ); + const root = createRoot( div ); + act( () => { + root.render( ); + } ); + expect( title() ).toBeUndefined(); + + const rows: [UpdateDownloadPayload, string, string][] = [ + [{ id: 'update', status: 'connecting' }, 'Starting…', 'Connecting to the update server…'], + [ + { id: 'update', status: 'downloading', percent: 42 }, + '42%', + 'RAxML-GUI will quit and install when the download finishes.', + ], + [{ id: 'update', status: 'restarted', percent: 10 }, '10%', 'Retrying with the full download…'], + [{ id: 'update', status: 'done' }, '100%', 'Download complete. Preparing to install…'], + ]; + for ( const [payload, percent, status] of rows ) { + act( () => { + hear( payload ); + } ); + expect( title() ).toBe( 'Downloading update' ); + const dialog = document.querySelector( '[role="dialog"]' ); + expect( dialog.textContent ).toContain( percent ); + expect( dialog.textContent ).toContain( status ); + expect( dialog.querySelector( 'button' ) ).toBeNull(); + } + + act( () => { + document.querySelector( '[role="dialog"]' ).dispatchEvent( new KeyboardEvent( 'keydown', { key: 'Escape', bubbles: true } ) ); + document.querySelector( '.MuiBackdrop-root' ).click(); + } ); + expect( title() ).toBe( 'Downloading update' ); + + act( () => { + hear( { id: 'update', status: 'idle' } ); + } ); + expect( title() ).toBeUndefined(); + + act( () => { + root.unmount(); + } ); + div.remove(); +} ); + +it( 'a page that starts mid-download shows the dialog with no event pushed', async () => { + installBridge( { + getUpdateDownload: () => Promise.resolve( { status: 'downloading', percent: 37 } ), + } ); + store.listen(); + + const div = document.createElement( 'div' ); + document.body.appendChild( div ); + const root = createRoot( div ); + await act( async () => { + root.render( ); + } ); + expect( title() ).toBe( 'Downloading update' ); + expect( document.querySelector( '[role="dialog"]' ).textContent ).toContain( '37%' ); + + act( () => { + root.unmount(); + } ); + div.remove(); +} ); diff --git a/src/common/rendererBridge.ts b/src/common/rendererBridge.ts index eeb25b38..5eaf941d 100644 --- a/src/common/rendererBridge.ts +++ b/src/common/rendererBridge.ts @@ -23,6 +23,16 @@ export interface HostInfo { cpuModel: string; } +export type UpdateDownload = + | { status: 'idle' } + | { status: 'connecting' } + | { status: 'downloading'; percent: number } + // a differential download fell back to a full one, so the percent dropped + | { status: 'restarted'; percent: number } + | { status: 'done' }; + +export type UpdateDownloadPayload = UpdateDownload & { id: string }; + // An event payload the page does not read yet; the leaf that reads it tightens it. type Listener = ( payload: unknown ) => void; type Unsubscribe = () => void; @@ -68,6 +78,8 @@ export interface RendererBridge { onToggleBackboneConstraint: ( listener: Listener ) => Unsubscribe; onToggleMultifurcatingConstraint: ( listener: Listener ) => Unsubscribe; onUnhandledError: ( listener: Listener ) => Unsubscribe; + onUpdateDownload: ( listener: ( payload: UpdateDownloadPayload ) => void ) => Unsubscribe; + getUpdateDownload: () => Promise; getPathForFile: ( file: File ) => string; } diff --git a/src/constants/ipc.ts b/src/constants/ipc.ts index 1b595871..4ced0c72 100644 --- a/src/constants/ipc.ts +++ b/src/constants/ipc.ts @@ -28,6 +28,8 @@ export const ALIGNMENT_MODEL_SELECTION_SUCCESS = export const ALIGNMENT_MODEL_SELECTION_FAILURE = 'ALIGNMENT_MODEL_SELECTION_FAILURE' as const; export const UNHANDLED_ERROR = 'UNHANDLED_ERROR' as const; +export const UPDATE_DOWNLOAD = 'UPDATE_DOWNLOAD' as const; +export const GET_UPDATE_DOWNLOAD = 'GET_UPDATE_DOWNLOAD' as const; export const TOGGLE_BACKBONE_CONSTRAINT = 'TOGGLE_BACKBONE_CONSTRAINT' as const; export const TOGGLE_MULTIFURCATING_CONSTRAINT = 'TOGGLE_MULTIFURCATING_CONSTRAINT' as const; diff --git a/src/main/api.ts b/src/main/api.ts index c113d677..24549d18 100644 --- a/src/main/api.ts +++ b/src/main/api.ts @@ -16,6 +16,7 @@ import { selectAstralFile } from './selectAstralFile'; import { selectOutputDir } from './selectOutputDir'; import { checkOutput } from './checkOutput'; import { debugInfo } from './debugInfo'; +import { getUpdateDownload } from './updates'; import { selectPartitionFile } from './selectPartitionFile'; import { selectTree } from './selectTree'; import { appStore } from './appStore'; @@ -71,6 +72,7 @@ ipcMain.on( ipc.HOST, ( event: IpcMainEvent ) => { }; } ); ipcMain.handle( ipc.GET_VERSION, (): string => app.getVersion() ); +ipcMain.handle( ipc.GET_UPDATE_DOWNLOAD, getUpdateDownload ); ipcMain.handle( ipc.GET_DARK_MODE, (): boolean => Boolean( appStore.get( 'darkMode' ) ) ); ipcMain.handle( ipc.SET_DARK_MODE, ( _event: IpcMainInvokeEvent, value: boolean ): void => { appStore.set( 'darkMode', value ); diff --git a/src/main/index.ts b/src/main/index.ts index bc65ea82..fb14ee70 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -8,7 +8,7 @@ import './api'; import MenuBuilder from './menu'; import { is } from '../common/utils'; import { pageWindowPreferences } from './pageWindowPreferences'; -import { checkForUpdates, listenForUpdates } from './updates'; +import { applyUpdateDownloadBar, checkForUpdates, listenForUpdates } from './updates'; // TODO: Have removed electron-debug dependency, because it used remote module. Maybe we need some alternative. //------------------------------------------------------------------- // From https://github.com/iffy/electron-updater-example/blob/master/main.js @@ -34,7 +34,7 @@ const isE2eMode = process.env.RAXMLGUI_E2E === '1'; // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow: BrowserWindow | null = null; -listenForUpdates( autoUpdater, dialog ); +listenForUpdates( autoUpdater, dialog, () => mainWindow ); /** * Add event listeners... */ @@ -62,6 +62,8 @@ function initialize(): void { // Create the browser window. const win = new BrowserWindow( mainWindowOptions ); mainWindow = win; + // a macOS window reopened mid-download gets the bar back + applyUpdateDownloadBar( win ); // and load the index.html of the app. let startUrl = process.env.ELECTRON_RENDERER_URL || url.format( { diff --git a/src/main/updates.test.ts b/src/main/updates.test.ts index c646c05c..55839dd6 100644 --- a/src/main/updates.test.ts +++ b/src/main/updates.test.ts @@ -1,11 +1,21 @@ -import { expect, it, vi } from 'vitest'; +import { afterEach, expect, it, vi } from 'vitest'; import fs from 'fs'; import path from 'path'; -import type { Dialog } from 'electron'; +import log from 'electron-log'; +import type { BrowserWindow, Dialog } from 'electron'; import type { AppUpdater } from 'electron-updater'; -import { checkForUpdates, listenForUpdates } from './updates'; +import { applyUpdateDownloadBar, checkForUpdates, getUpdateDownload, listenForUpdates } from './updates'; -function updater() { +vi.mock( 'electron-log', () => ( { default: { info: vi.fn() } } ) ); + +const { platform } = process; + +afterEach( () => { + Object.defineProperty( process, 'platform', { value: platform } ); + vi.mocked( log.info ).mockClear(); +} ); + +function updater( download: () => Promise = () => Promise.resolve( [] ) ) { const listeners: Record void> = Object.create( null ); return { on( event: string, fn: ( payload?: unknown ) => void ) { @@ -17,11 +27,62 @@ function updater() { fn( payload ); } }, - downloadUpdate: vi.fn(), + has( event: string ) { + return event in listeners; + }, + downloadUpdate: vi.fn( download ), quitAndInstall: vi.fn(), }; } +function fakeWindow() { + return { + setProgressBar: vi.fn<( value: number ) => void>(), + webContents: { send: vi.fn<( channel: string, payload: { status: string } ) => void>() }, + }; +} + +function progress( percent: number ) { + return { percent, bytesPerSecond: 1, transferred: 1, total: 2 }; +} + +function logs() { + return vi.mocked( log.info ).mock.calls.map( ( [line] ) => String( line ) ); +} + +// Listens with a fake window and clicks Yes on Found Updates. +async function startDownload( options: { + win?: ReturnType | null; + download?: () => Promise; +} = {} ) { + const updates = updater( options.download ); + const win = options.win === undefined + ? fakeWindow() + : options.win; + const calls: string[] = []; + win?.setProgressBar.mockImplementation( ( value ) => { + calls.push( `bar ${value}` ); + } ); + win?.webContents.send.mockImplementation( ( _channel, payload ) => { + calls.push( `send ${payload.status}` ); + } ); + const choice = Promise.resolve( { response: 0 } ); + const dialog = { + showMessageBox: vi.fn<( options: unknown ) => Promise<{ response: number }>>( () => choice ), + showErrorBox: vi.fn( () => { + calls.push( 'error box' ); + } ), + }; + listenForUpdates( + updates as unknown as AppUpdater, + dialog as unknown as Dialog, + () => win as unknown as BrowserWindow | null, + ); + updates.emit( 'update-available' ); + await choice; + return { updates, win, dialog, calls }; +} + it( 'No on Found Updates leaves the current version', async () => { const updates = updater(); const choice = Promise.resolve( { response: 1 } ); @@ -29,7 +90,7 @@ it( 'No on Found Updates leaves the current version', async () => { showMessageBox: vi.fn( () => choice ), showErrorBox: vi.fn(), }; - listenForUpdates( updates as unknown as AppUpdater, dialog as unknown as Dialog ); + listenForUpdates( updates as unknown as AppUpdater, dialog as unknown as Dialog, () => null ); updates.emit( 'update-available' ); await choice; expect( dialog.showMessageBox ).toHaveBeenCalledWith( { @@ -41,46 +102,118 @@ it( 'No on Found Updates leaves the current version', async () => { } ); expect( updates.downloadUpdate ).not.toHaveBeenCalled(); expect( updates.quitAndInstall ).not.toHaveBeenCalled(); + expect( getUpdateDownload() ).toEqual( { status: 'idle' } ); } ); -it( 'Yes downloads the update with no window, bar, or percent', async () => { - const updates = updater(); - const choice = Promise.resolve( { response: 0 } ); - const dialog = { - showMessageBox: vi.fn<( options: unknown ) => Promise<{ response: number }>>( () => choice ), - showErrorBox: vi.fn(), - }; - listenForUpdates( updates as unknown as AppUpdater, dialog as unknown as Dialog ); - updates.emit( 'update-available' ); - await choice; +it( 'Yes downloads the update and shows its progress on the icon', async () => { + Object.defineProperty( process, 'platform', { value: 'darwin' } ); + const { updates, win, dialog } = await startDownload(); expect( updates.downloadUpdate ).toHaveBeenCalledWith(); - expect( dialog.showMessageBox ).toHaveBeenCalledTimes( 1 ); - expect( JSON.stringify( dialog.showMessageBox.mock.calls[0][0] ) ).not.toMatch( /%|percent|progress/i ); - updates.emit( 'download-progress', { - percent: 40, - bytesPerSecond: 1, - transferred: 1, - total: 2, - } ); + expect( getUpdateDownload() ).toEqual( { status: 'connecting' } ); + expect( win?.setProgressBar ).toHaveBeenLastCalledWith( 2 ); + updates.emit( 'download-progress', progress( 40 ) ); + expect( getUpdateDownload() ).toEqual( { status: 'downloading', percent: 40 } ); + expect( win?.setProgressBar ).toHaveBeenLastCalledWith( 0.4 ); expect( dialog.showMessageBox ).toHaveBeenCalledTimes( 1 ); expect( dialog.showErrorBox ).not.toHaveBeenCalled(); } ); -it( 'a finished download quits to install', async () => { +it( 'every state change is sent to the page', async () => { + const { updates, win } = await startDownload(); + updates.emit( 'download-progress', progress( 42 ) ); + updates.emit( 'download-progress', progress( 10 ) ); + updates.emit( 'update-downloaded' ); + updates.emit( 'error', new Error( 'network down' ) ); + expect( win?.webContents.send.mock.calls ).toEqual( [ + ['UPDATE_DOWNLOAD', { id: 'update', status: 'connecting' }], + ['UPDATE_DOWNLOAD', { id: 'update', status: 'downloading', percent: 42 }], + ['UPDATE_DOWNLOAD', { id: 'update', status: 'restarted', percent: 10 }], + ['UPDATE_DOWNLOAD', { id: 'update', status: 'done' }], + ['UPDATE_DOWNLOAD', { id: 'update', status: 'idle' }], + ] ); +} ); + +it( 'the download-progress listener is registered before any download starts', () => { const updates = updater(); - const dialog = { - showMessageBox: vi.fn( () => Promise.resolve( { response: 0 } ) ), - showErrorBox: vi.fn(), - }; - listenForUpdates( updates as unknown as AppUpdater, dialog as unknown as Dialog ); + listenForUpdates( updates as unknown as AppUpdater, {} as Dialog, () => null ); + expect( updates.has( 'download-progress' ) ).toBe( true ); +} ); + +it( 'on Linux the indeterminate bar is never sent', async () => { + Object.defineProperty( process, 'platform', { value: 'linux' } ); + const { updates, win } = await startDownload(); + expect( getUpdateDownload() ).toEqual( { status: 'connecting' } ); + updates.emit( 'download-progress', progress( 10 ) ); + expect( win?.setProgressBar.mock.calls ).toEqual( [[0.1]] ); +} ); + +it( 'a lower percent moves the download to restarted, which stays sticky', async () => { + const { updates, win } = await startDownload(); + updates.emit( 'download-progress', progress( 60 ) ); + updates.emit( 'download-progress', progress( 5 ) ); + expect( getUpdateDownload() ).toEqual( { status: 'restarted', percent: 5 } ); + expect( win?.setProgressBar ).toHaveBeenLastCalledWith( 0.05 ); + updates.emit( 'download-progress', progress( 80 ) ); + expect( getUpdateDownload() ).toEqual( { status: 'restarted', percent: 80 } ); + expect( win?.setProgressBar ).toHaveBeenLastCalledWith( 0.8 ); +} ); + +it( 'a finished download clears the bar and quits to install', async () => { + const { updates, win, dialog } = await startDownload(); + updates.emit( 'download-progress', progress( 100 ) ); updates.emit( 'update-downloaded' ); - await dialog.showMessageBox.mock.results[0].value; + expect( getUpdateDownload() ).toEqual( { status: 'done' } ); + expect( win?.setProgressBar ).toHaveBeenLastCalledWith( -1 ); + await dialog.showMessageBox.mock.results[1].value; await new Promise( ( resolve ) => setImmediate( resolve ) ); - expect( dialog.showMessageBox ).toHaveBeenCalledWith( { + expect( dialog.showMessageBox ).toHaveBeenLastCalledWith( { title: 'Install Updates', message: 'Updates downloaded, the application will now quit to update...', } ); expect( updates.quitAndInstall ).toHaveBeenCalledWith(); + expect( logs() ).toEqual( ['Update available.', 'Update download started.', 'Update downloaded'] ); +} ); + +it( 'an error mid-download resets the state, clears the bar, then shows the error box', async () => { + const { updates, calls } = await startDownload(); + updates.emit( 'download-progress', progress( 30 ) ); + calls.length = 0; + updates.emit( 'error', new Error( 'network down' ) ); + expect( getUpdateDownload() ).toEqual( { status: 'idle' } ); + expect( calls ).toEqual( ['send idle', 'bar -1', 'error box'] ); + expect( logs() ).toEqual( [ + 'Update available.', + 'Update download started.', + 'Error in auto-updater. Error: network down', + ] ); +} ); + +it( 'a rejected downloadUpdate produces no unhandled rejection', async () => { + const unhandled = vi.fn(); + process.on( 'unhandledRejection', unhandled ); + try { + await startDownload( { download: () => Promise.reject( new Error( 'net::ERR_FAILED' ) ) } ); + await new Promise( ( resolve ) => setImmediate( resolve ) ); + expect( unhandled ).not.toHaveBeenCalled(); + } finally { + process.off( 'unhandledRejection', unhandled ); + } +} ); + +it( 'with no window nothing throws and the state still advances', async () => { + const { updates } = await startDownload( { win: null } ); + updates.emit( 'download-progress', progress( 20 ) ); + expect( getUpdateDownload() ).toEqual( { status: 'downloading', percent: 20 } ); + updates.emit( 'update-downloaded' ); + expect( getUpdateDownload() ).toEqual( { status: 'done' } ); +} ); + +it( 'a newly created window gets the held bar value', async () => { + const { updates } = await startDownload( { win: null } ); + updates.emit( 'download-progress', progress( 70 ) ); + const reopened = fakeWindow(); + applyUpdateDownloadBar( reopened as unknown as BrowserWindow ); + expect( reopened.setProgressBar ).toHaveBeenCalledWith( 0.7 ); } ); it( 'a failed update uses the error dialog', () => { @@ -89,12 +222,18 @@ it( 'a failed update uses the error dialog', () => { showMessageBox: vi.fn(), showErrorBox: vi.fn(), }; - listenForUpdates( updates as unknown as AppUpdater, dialog as unknown as Dialog ); + const win = fakeWindow(); + listenForUpdates( + updates as unknown as AppUpdater, + dialog as unknown as Dialog, + () => win as unknown as BrowserWindow, + ); const failure = new Error( 'network down' ); updates.emit( 'error', failure ); expect( dialog.showErrorBox ).toHaveBeenCalledWith( 'Error: ', expect.stringContaining( 'network down' ) ); expect( updates.downloadUpdate ).not.toHaveBeenCalled(); expect( updates.quitAndInstall ).not.toHaveBeenCalled(); + expect( win.setProgressBar ).not.toHaveBeenCalled(); } ); it( 'the shell opens no update progress window', () => { @@ -102,10 +241,9 @@ it( 'the shell opens no update progress window', () => { const main = fs.readFileSync( path.join( __dirname, 'index.ts' ), 'utf8' ); const updates = fs.readFileSync( path.join( __dirname, 'updates.ts' ), 'utf8' ); expect( pkg.dependencies['electron-progressbar'] ).toBeUndefined(); - expect( main ).toContain( 'listenForUpdates( autoUpdater, dialog )' ); + expect( main ).toContain( 'listenForUpdates( autoUpdater, dialog, () => mainWindow )' ); expect( main + updates ).not.toContain( 'electron-progressbar' ); - expect( main + updates ).not.toContain( 'ProgressBar' ); - expect( main + updates ).not.toContain( 'download-progress' ); + expect( main + updates ).not.toMatch( /\bProgressBar\b/ ); } ); it( 'an offline update check rejects nothing (the error event already reports it)', async () => { diff --git a/src/main/updates.ts b/src/main/updates.ts index 1a4c39eb..1b6355fa 100644 --- a/src/main/updates.ts +++ b/src/main/updates.ts @@ -1,6 +1,45 @@ import log from 'electron-log'; -import type { Dialog } from 'electron'; -import type { AppUpdater } from 'electron-updater'; +import type { BrowserWindow, Dialog } from 'electron'; +import type { AppUpdater, ProgressInfo } from 'electron-updater'; +import type { UpdateDownload } from '../common/rendererBridge'; +import { UPDATE_DOWNLOAD } from '../constants/ipc'; + +type WindowGetter = () => BrowserWindow | null; + +let download: UpdateDownload = { status: 'idle' }; +let getWindow: WindowGetter = () => null; + +export function getUpdateDownload(): UpdateDownload { + return download; +} + +// Shows the held Update download on the window's Dock or taskbar icon. +export function applyUpdateDownloadBar( win: BrowserWindow | null ): void { + if ( !win ) { + return; + } + switch ( download.status ) { + case 'connecting': + // Linux has no indeterminate mode + if ( process.platform !== 'linux' ) { + win.setProgressBar( 2 ); + } + break; + case 'downloading': + case 'restarted': + win.setProgressBar( download.percent / 100 ); + break; + default: + win.setProgressBar( -1 ); + } +} + +function setDownload( next: UpdateDownload ): void { + download = next; + const win = getWindow(); + win?.webContents.send( UPDATE_DOWNLOAD, { id: 'update', ...next } ); + applyUpdateDownloadBar( win ); +} // checkForUpdates rejects as well as emitting 'error'; the listener already reports it, // so swallow the rejection to avoid an unhandled one (offline users, Sentry 3593287140). @@ -13,7 +52,9 @@ export async function checkForUpdates( updater: AppUpdater ): Promise { } } -export function listenForUpdates( updater: AppUpdater, dialog: Dialog ): void { +export function listenForUpdates( updater: AppUpdater, dialog: Dialog, windowGetter: WindowGetter ): void { + download = { status: 'idle' }; + getWindow = windowGetter; updater.on( 'checking-for-update', () => { log.info( 'Checking for update...' ); } ); @@ -28,7 +69,10 @@ export function listenForUpdates( updater: AppUpdater, dialog: Dialog ): void { } ) .then( ( r ) => { if ( r.response === 0 ) { - updater.downloadUpdate(); + setDownload( { status: 'connecting' } ); + log.info( 'Update download started.' ); + // rejects as well as emitting 'error'; the 'error' listener already reports it + updater.downloadUpdate().catch( () => {} ); } } ); log.info( 'Update available.' ); @@ -36,8 +80,21 @@ export function listenForUpdates( updater: AppUpdater, dialog: Dialog ): void { updater.on( 'update-not-available', () => { log.info( 'Update not available.' ); } ); + updater.on( 'download-progress', ( progress: ProgressInfo ) => { + const restarted = download.status === 'restarted' || + ( download.status === 'downloading' && progress.percent < download.percent ); + setDownload( { + status: restarted + ? 'restarted' + : 'downloading', + percent: progress.percent, + } ); + } ); updater.on( 'error', ( error ) => { log.info( 'Error in auto-updater. ' + error ); + if ( download.status !== 'idle' ) { + setDownload( { status: 'idle' } ); + } const message = error == null ? 'unknown' : error instanceof Error @@ -46,6 +103,7 @@ export function listenForUpdates( updater: AppUpdater, dialog: Dialog ): void { dialog.showErrorBox( 'Error: ', message ); } ); updater.on( 'update-downloaded', () => { + setDownload( { status: 'done' } ); dialog .showMessageBox( { title: 'Install Updates', diff --git a/src/preload-proofs/getUpdateDownload.json b/src/preload-proofs/getUpdateDownload.json new file mode 100644 index 00000000..96a5ff18 --- /dev/null +++ b/src/preload-proofs/getUpdateDownload.json @@ -0,0 +1,10 @@ +{ + "key": "heldUpdateDownload", + "method": "getUpdateDownload", + "args": [], + "channel": "GET_UPDATE_DOWNLOAD", + "result": { + "status": "downloading", + "percent": 42 + } +} diff --git a/src/preload-proofs/onUpdateDownload.json b/src/preload-proofs/onUpdateDownload.json new file mode 100644 index 00000000..d6e84340 --- /dev/null +++ b/src/preload-proofs/onUpdateDownload.json @@ -0,0 +1,11 @@ +{ + "key": "updateDownload", + "method": "onUpdateDownload", + "channel": "UPDATE_DOWNLOAD", + "subscribe": true, + "result": { + "id": "update", + "status": "downloading", + "percent": 42 + } +} diff --git a/src/preload/index.ts b/src/preload/index.ts index 4a7ea142..ae5cc6e2 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -17,6 +17,7 @@ import { FILE_SHOW_IN_FOLDER, GET_DARK_MODE, GET_VERSION, + GET_UPDATE_DOWNLOAD, HOST, SET_DARK_MODE, LIGHT_MODE, @@ -40,9 +41,10 @@ import { TOGGLE_MULTIFURCATING_CONSTRAINT, TREE_SELECT, UNHANDLED_ERROR, + UPDATE_DOWNLOAD, WRITE_FILE, } from '../constants/ipc'; -import type { RendererBridge, HostInfo } from '../common/rendererBridge'; +import type { RendererBridge, HostInfo, UpdateDownloadPayload } from '../common/rendererBridge'; import type { CheckOutputArgs } from '../main/checkOutput'; import type { StateReport } from '../main/getActiveState'; import type { StartRunPayload, RunFinishedPayload, RunErrorPayload } from '../main/startRun'; @@ -191,6 +193,12 @@ const rendererBridge = { onUnhandledError( listener: ( payload: unknown ) => void ) { return onEvent( UNHANDLED_ERROR, listener ); }, + onUpdateDownload( listener: ( payload: UpdateDownloadPayload ) => void ) { + return onEvent( UPDATE_DOWNLOAD, listener ); + }, + getUpdateDownload() { + return ipcRenderer.invoke( GET_UPDATE_DOWNLOAD ); + }, getPathForFile( file: File ): string { return webUtils.getPathForFile( file ); }, diff --git a/src/test/setup.ts b/src/test/setup.ts index 3c630b3e..ef5800d2 100644 --- a/src/test/setup.ts +++ b/src/test/setup.ts @@ -45,6 +45,10 @@ function withBridgeEvents( next: TestBridge ): TestBridge { if ( typeof next.getVersion !== 'function' ) { next.getVersion = () => Promise.resolve( undefined ); } + // The run list seeds the update download when it listens. + if ( typeof next.getUpdateDownload !== 'function' ) { + next.getUpdateDownload = () => Promise.resolve( { status: 'idle' } ); + } // The output panel checks the output name; MobX 6 re-renders it inside the render test when this rejects. if ( typeof next.checkOutput !== 'function' ) { next.checkOutput = ( { outputDir, outputName } ) =>