diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 8b27383d..463b650a 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -68,5 +68,25 @@ module.exports = { ], }, }, + { + // Main TypeScript (#67): full typing under non-strict — typed catch, typed exports. + files: ['src/main/**/*.{ts,tsx}', 'src/common/**/*.{ts,tsx}'], + rules: { + '@typescript-eslint/explicit-module-boundary-types': 'error', + 'no-restricted-syntax': [ + 'error', + { + selector: 'CatchClause[param][param.typeAnnotation=undefined]', + message: 'Annotate catch bindings (use unknown).', + }, + { + selector: + 'CatchClause BinaryExpression[operator="instanceof"][right.name="Error"]', + message: + 'Read (error as Error).message; jsdom Error is a different realm from Node throws.', + }, + ], + }, + }, ], }; diff --git a/TODO.md b/TODO.md index 1e1ffb92..7f540c5b 100644 --- a/TODO.md +++ b/TODO.md @@ -1,7 +1,3 @@ Todo: - Option to remove existing files (shell.moveItemToTrash(fullPath)) - Create publish script - -## TypeScript in the Electron main process - -Main, shared modules used by main, `src/constants/ipc`, and `src/settings/*` are `.js`. The shell build is `yarn build` (`electron-vite build`). The page build compiles JSX in `.js` files. A move of those main sources to `.ts` starts from that build. diff --git a/package.json b/package.json index 10be2409..d8bad7c8 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "main": "./out/main/index.js", "scripts": { "start": "electron-vite dev", + "test": "jest --watchAll=false", "react-test": "jest --watchAll=false", "test:e2e": "yarn build && node node_modules/playwright/cli.js test --config e2e/playwright.config.js", "test:docs": "node node_modules/playwright/cli.js test --config e2e/docs/playwright.config.js", diff --git a/scripts/typecheck-baseline.js b/scripts/typecheck-baseline.js index 19938474..32452189 100644 --- a/scripts/typecheck-baseline.js +++ b/scripts/typecheck-baseline.js @@ -16,9 +16,31 @@ function fingerprint(line) { return line.replace(/\(\d+,\d+\): /, ': '); } +/** Pathless tsc continuations belong to the preceding src/ header. */ +function ownedFingerprints(lines) { + let owner = ''; + return lines.map((line) => { + const match = /^(src\/\S+?)\(/.exec(line); + if (match) { + owner = match[1]; + return fingerprint(line); + } + return owner + ? `${owner}|${line}` + : line; + }); +} + function freshLines(actual, known) { - const seen = new Set(known.map(fingerprint)); - return actual.filter((line) => !seen.has(fingerprint(line))); + const seen = new Set(ownedFingerprints(known)); + const actualOwned = ownedFingerprints(actual); + return actual.filter( (line, i) => !seen.has(actualOwned[i]) ); +} + +function unusedLines(known, actual) { + const seen = new Set(ownedFingerprints(actual)); + const knownOwned = ownedFingerprints(known); + return known.filter( (line, i) => !seen.has(knownOwned[i]) ); } function main() { @@ -40,12 +62,16 @@ function main() { console.error(result.error || result.stderr || result.stdout); process.exit(result.status || 1); } - const fresh = freshLines( - diagnosticLines(`${result.stdout || ''}\n${result.stderr || ''}`), - baseline, - ); - if (fresh.length) { - console.error(fresh.join('\n')); + const actual = diagnosticLines(`${result.stdout || ''}\n${result.stderr || ''}`); + const fresh = freshLines(actual, baseline); + const unused = unusedLines(baseline, actual); + if (fresh.length || unused.length) { + if (fresh.length) { + console.error(fresh.join('\n')); + } + if (unused.length) { + console.error('unused baseline:\n' + unused.join('\n')); + } process.exit(1); } } @@ -54,4 +80,4 @@ if (require.main === module) { main(); } -module.exports = { diagnosticLines, freshLines }; +module.exports = { diagnosticLines, freshLines, unusedLines, ownedFingerprints }; diff --git a/scripts/typecheck-baseline.txt b/scripts/typecheck-baseline.txt index f515bd0e..36e907ac 100644 --- a/scripts/typecheck-baseline.txt +++ b/scripts/typecheck-baseline.txt @@ -31,78 +31,6 @@ src/app/store/Run.js(630,5): error TS2554: Expected 5-6 arguments, but got 4. src/app/store/Run.js(662,5): error TS2554: Expected 5-6 arguments, but got 4. src/app/store/Run.js(681,5): error TS2554: Expected 5-6 arguments, but got 3. src/app/store/Run.js(693,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/StoreBase.js(19,13): error TS2365: Operator '>' cannot be applied to types 'boolean' and 'number'. -src/common/utils.js(19,5): error TS2322: Type '"macos"' is not assignable to type 'Platform'. -src/common/utils.js(21,5): error TS2322: Type '"windows"' is not assignable to type 'Platform'. -src/common/utils.js(41,19): error TS2551: Property 'store' does not exist on type 'Window & typeof globalThis'. Did you mean 'Storage'? src/electron.js(5,27): error TS2769: No overload matches this call. The last overload gave the following error. Argument of type 'typeof CrossProcessExports' is not assignable to parameter of type 'string'. -src/main/api.js(33,10): error TS2304: Cannot find name '__static'. -src/main/api.js(87,6): error TS2339: Property 'getCurrentWindow' does not exist on type 'typeof BrowserWindow'. -src/main/api.js(122,52): error TS2769: No overload matches this call. - Overload 1 of 4, '(command: string, options: ExecOptionsWithBufferEncoding): PromiseWithChild<{ stdout: NonSharedBuffer; stderr: NonSharedBuffer; }>', gave the following error. - Argument of type '{ shell?: boolean; cwd: any; }' is not assignable to parameter of type 'ExecOptionsWithBufferEncoding'. - Property 'encoding' is missing in type '{ shell?: boolean; cwd: any; }' but required in type 'ExecOptionsWithBufferEncoding'. - Overload 2 of 4, '(command: string, options: ExecOptionsWithStringEncoding): PromiseWithChild<{ stdout: string; stderr: string; }>', gave the following error. - Argument of type '{ shell?: boolean; cwd: any; }' is not assignable to parameter of type 'ExecOptionsWithStringEncoding'. - Types of property 'shell' are incompatible. - Type 'boolean' is not assignable to type 'string'. - Overload 3 of 4, '(command: string, options: ExecOptions): PromiseWithChild<{ stdout: string | NonSharedBuffer; stderr: string | NonSharedBuffer; }>', gave the following error. - Argument of type '{ shell?: boolean; cwd: any; }' is not assignable to parameter of type 'ExecOptions'. - Types of property 'shell' are incompatible. - Type 'boolean' is not assignable to type 'string'. -src/main/api.js(201,99): error TS2769: No overload matches this call. - Overload 1 of 4, '(command: string, options: ExecOptionsWithBufferEncoding): PromiseWithChild<{ stdout: NonSharedBuffer; stderr: NonSharedBuffer; }>', gave the following error. - Argument of type '{ shell?: boolean; }' is not assignable to parameter of type 'ExecOptionsWithBufferEncoding'. - Property 'encoding' is missing in type '{ shell?: boolean; }' but required in type 'ExecOptionsWithBufferEncoding'. - Overload 2 of 4, '(command: string, options: ExecOptionsWithStringEncoding): PromiseWithChild<{ stdout: string; stderr: string; }>', gave the following error. - Argument of type '{ shell?: boolean; }' is not assignable to parameter of type 'ExecOptionsWithStringEncoding'. - Types of property 'shell' are incompatible. - Type 'boolean' is not assignable to type 'string'. - Overload 3 of 4, '(command: string, options: ExecOptions): PromiseWithChild<{ stdout: string | NonSharedBuffer; stderr: string | NonSharedBuffer; }>', gave the following error. - Argument of type '{ shell?: boolean; }' is not assignable to parameter of type 'ExecOptions'. - Types of property 'shell' are incompatible. - Type 'boolean' is not assignable to type 'string'. -src/main/api.js(363,52): error TS2769: No overload matches this call. - Overload 1 of 4, '(command: string, options: ExecOptionsWithBufferEncoding): PromiseWithChild<{ stdout: NonSharedBuffer; stderr: NonSharedBuffer; }>', gave the following error. - Argument of type '{ shell?: boolean; }' is not assignable to parameter of type 'ExecOptionsWithBufferEncoding'. - Property 'encoding' is missing in type '{ shell?: boolean; }' but required in type 'ExecOptionsWithBufferEncoding'. - Overload 2 of 4, '(command: string, options: ExecOptionsWithStringEncoding): PromiseWithChild<{ stdout: string; stderr: string; }>', gave the following error. - Argument of type '{ shell?: boolean; }' is not assignable to parameter of type 'ExecOptionsWithStringEncoding'. - Types of property 'shell' are incompatible. - Type 'boolean' is not assignable to type 'string'. - Overload 3 of 4, '(command: string, options: ExecOptions): PromiseWithChild<{ stdout: string | NonSharedBuffer; stderr: string | NonSharedBuffer; }>', gave the following error. - Argument of type '{ shell?: boolean; }' is not assignable to parameter of type 'ExecOptions'. - Types of property 'shell' are incompatible. - Type 'boolean' is not assignable to type 'string'. -src/main/api.js(384,52): error TS2769: No overload matches this call. - Overload 1 of 4, '(command: string, options: ExecOptionsWithBufferEncoding): PromiseWithChild<{ stdout: NonSharedBuffer; stderr: NonSharedBuffer; }>', gave the following error. - Argument of type '{ shell?: boolean; }' is not assignable to parameter of type 'ExecOptionsWithBufferEncoding'. - Property 'encoding' is missing in type '{ shell?: boolean; }' but required in type 'ExecOptionsWithBufferEncoding'. - Overload 2 of 4, '(command: string, options: ExecOptionsWithStringEncoding): PromiseWithChild<{ stdout: string; stderr: string; }>', gave the following error. - Argument of type '{ shell?: boolean; }' is not assignable to parameter of type 'ExecOptionsWithStringEncoding'. - Types of property 'shell' are incompatible. - Type 'boolean' is not assignable to type 'string'. - Overload 3 of 4, '(command: string, options: ExecOptions): PromiseWithChild<{ stdout: string | NonSharedBuffer; stderr: string | NonSharedBuffer; }>', gave the following error. - Argument of type '{ shell?: boolean; }' is not assignable to parameter of type 'ExecOptions'. - Types of property 'shell' are incompatible. - Type 'boolean' is not assignable to type 'string'. -src/main/api.js(433,12): error TS2367: This comparison appears to be unintentional because the types 'number' and 'string' have no overlap. -src/main/api.js(486,12): error TS2367: This comparison appears to be unintentional because the types 'number' and 'string' have no overlap. -src/main/menu/index.js(47,26): error TS2345: Argument of type '{ label: string; submenu: ({ label: string; click(): never; type?: undefined; role?: undefined; } | { type: string; label?: undefined; click?: undefined; role?: undefined; } | { role: string; label?: undefined; click?: undefined; type?: undefined; })[]; }' is not assignable to parameter of type '{ label: string; submenu: ({ label: string; accelerator: string; click(): void; submenu?: undefined; } | { label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; accelerator?: undefined; click?: undefined; })[]; } | { ...; } | { ...; }'. - Type '{ label: string; submenu: ({ label: string; click(): never; type?: undefined; role?: undefined; } | { type: string; label?: undefined; click?: undefined; role?: undefined; } | { role: string; label?: undefined; click?: undefined; type?: undefined; })[]; }' is not assignable to type '{ label: string; submenu: { label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; }[]; }'. - Types of property 'submenu' are incompatible. - Type '({ label: string; click(): never; type?: undefined; role?: undefined; } | { type: string; label?: undefined; click?: undefined; role?: undefined; } | { role: string; label?: undefined; click?: undefined; type?: undefined; })[]' is not assignable to type '{ label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; }[]'. - Type '{ label: string; click(): never; type?: undefined; role?: undefined; } | { type: string; label?: undefined; click?: undefined; role?: undefined; } | { role: string; label?: undefined; click?: undefined; type?: undefined; }' is not assignable to type '{ label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; }'. - Property 'submenu' is missing in type '{ label: string; click(): never; type?: undefined; role?: undefined; }' but required in type '{ label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; }'. -src/main/menu/index.js(51,29): error TS2345: Argument of type '{ label: string; submenu: ({ role: string; type?: undefined; } | { type: string; role?: undefined; })[]; }' is not assignable to parameter of type '{ label: string; submenu: ({ label: string; accelerator: string; click(): void; submenu?: undefined; } | { label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; accelerator?: undefined; click?: undefined; })[]; } | { ...; } | { ...; }'. - Type '{ label: string; submenu: ({ role: string; type?: undefined; } | { type: string; role?: undefined; })[]; }' is not assignable to type '{ label: string; submenu: { label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; }[]; }'. - Types of property 'submenu' are incompatible. - Type '({ role: string; type?: undefined; } | { type: string; role?: undefined; })[]' is not assignable to type '{ label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; }[]'. - Type '{ role: string; type?: undefined; } | { type: string; role?: undefined; }' is not assignable to type '{ label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; }'. - Type '{ role: string; type?: undefined; }' is missing the following properties from type '{ label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; }': label, submenu -src/main/menu/index.js(53,42): error TS2345: Argument of type '({ label: string; submenu: ({ label: string; accelerator: string; click(): void; submenu?: undefined; } | { label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; accelerator?: undefined; click?: undefined; })[]; } | { ...; } | { ...; })[]' is not assignable to parameter of type '(MenuItemConstructorOptions | MenuItem)[]'. - Type '{ label: string; submenu: ({ label: string; accelerator: string; click(): void; submenu?: undefined; } | { label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; accelerator?: undefined; click?: undefined; })[]; } | { ...; } | { ...; }' is not assignable to type 'MenuItemConstructorOptions | MenuItem'. - Type '{ label: string; submenu: ({ label: string; accelerator: string; click(): void; submenu?: undefined; } | { label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; accelerator?: undefined; click?: undefined; })[]; }' is not assignable to type 'MenuItemConstructorOptions | MenuItem'. - Type '{ label: string; submenu: ({ label: string; accelerator: string; click(): void; submenu?: undefined; } | { label: string; submenu: { label: string; type: string; checked: boolean; click(): void; }[]; accelerator?: undefined; click?: undefined; })[]; }' is missing the following properties from type 'MenuItem': accelerator, accessibilityLabel, checked, click, and 11 more. diff --git a/src/__static.d.ts b/src/__static.d.ts new file mode 100644 index 00000000..7b81469e --- /dev/null +++ b/src/__static.d.ts @@ -0,0 +1 @@ +declare const __static: string; diff --git a/src/app/paths.test.js b/src/app/paths.test.js index 636dbeff..34b53d54 100644 --- a/src/app/paths.test.js +++ b/src/app/paths.test.js @@ -28,7 +28,7 @@ it( 'joins, names, and quotes a path', () => { } ); it( 'an input file reports the plain name, base, and directory', () => { - const file = new InputFile( { id: 'run-7' }, '/data/primates.fasta' ); + const file = new InputFile( { id: 7 }, '/data/primates.fasta' ); expect( file.name ).toBe( 'primates' ); expect( file.base ).toBe( 'primates.fasta' ); expect( file.filename ).toBe( 'primates.fasta' ); diff --git a/src/app/store/astral.test.js b/src/app/store/astral.test.js index 651ae5e2..bf7b84c8 100644 --- a/src/app/store/astral.test.js +++ b/src/app/store/astral.test.js @@ -28,14 +28,14 @@ function emit( list, payload ) { it( 'startAstral starts ASTRAL', async () => { const startAstral = jest.fn( async () => {} ); bridge( { startAstral } ); - const run = new Run( { onError() {} }, 'run-7' ); + const run = new Run( { onError() {} }, 7 ); run.setOutputDir( '/out' ); await run.startAstral(); expect( run.running ).toBe( true ); expect( startAstral ).toHaveBeenCalledWith( { - id: 'run-7', + id: 7, binaryName: run.binary.value, args: run.args, } ); @@ -43,7 +43,7 @@ it( 'startAstral starts ASTRAL', async () => { it( 'an ASTRAL exit code is recorded for that run', () => { const { listeners, stops } = bridge(); - const run = new Run( { onError() {} }, 'run-7' ); + const run = new Run( { onError() {} }, 7 ); run.running = true; run.setOutputDir( '/out' ); @@ -52,7 +52,7 @@ it( 'an ASTRAL exit code is recorded for that run', () => { expect( run.finished ).toBe( false ); expect( run.running ).toBe( true ); - emit( listeners.success, { id: 'run-7', exitCode: 3 } ); + emit( listeners.success, { id: 7, exitCode: 3 } ); expect( run.exitCode ).toBe( 3 ); expect( run.resultDir ).toBe( '/out' ); expect( run.finished ).toBe( true ); diff --git a/src/app/store/cancelRun.test.js b/src/app/store/cancelRun.test.js index 45bfc996..292c136c 100644 --- a/src/app/store/cancelRun.test.js +++ b/src/app/store/cancelRun.test.js @@ -8,12 +8,12 @@ import Run from './Run'; it( 'the cancel control uses cancelRun', () => { const cancelRun = jest.fn(); window.rendererBridge = { cancelRun }; - const run = new Run( { onError() {} }, 'run-7' ); + const run = new Run( { onError() {} }, 7 ); run.running = true; run.cancel(); - expect( cancelRun ).toHaveBeenCalledWith( 'run-7' ); + expect( cancelRun ).toHaveBeenCalledWith( 7 ); expect( run.running ).toBe( false ); } ); @@ -37,7 +37,7 @@ it( 'cancel before the run is tracked does not start it', async () => { cancelRun, parseAlignment: () => new Promise( () => {} ), }; - const run = new Run( { onError() {} }, 'run-7' ); + const run = new Run( { onError() {} }, 7 ); run.setOutputDir( outputDir ); run.addAlignments( [ { path: '/data/a.fasta' }, @@ -59,7 +59,7 @@ it( 'cancel before the run is tracked does not start it', async () => { waiters.forEach( ( release ) => release() ); await pending; expect( startRun ).not.toHaveBeenCalled(); - expect( cancelRun ).toHaveBeenCalledWith( 'run-7' ); + expect( cancelRun ).toHaveBeenCalledWith( 7 ); } finally { fs.rmSync( outputDir, { recursive: true, force: true } ); } diff --git a/src/app/store/checkOutputName.test.js b/src/app/store/checkOutputName.test.js index 854e0c3b..2d6327a8 100644 --- a/src/app/store/checkOutputName.test.js +++ b/src/app/store/checkOutputName.test.js @@ -12,7 +12,7 @@ it( 'the output-name check uses checkOutput', async () => { resultFilenames: ['tree.raxml.log'], } ) ); window.rendererBridge = { checkOutput }; - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); run.setOutputDir( '/data/out' ); run.setOutputName( 'tree' ); diff --git a/src/app/store/host.test.js b/src/app/store/host.test.js index ff458476..46f15a8f 100644 --- a/src/app/store/host.test.js +++ b/src/app/store/host.test.js @@ -33,8 +33,8 @@ it( 'reads the host once and uses it for Windows 7', () => { cpuModel: 'Intel', } ); const { Run, Alignment } = load(); - const run = new Run( {}, 'run-7' ); - const alignment = new Alignment( { id: 'run-7' }, '/data/primates.fasta' ); + const run = new Run( {}, 7 ); + const alignment = new Alignment( { id: 7 }, '/data/primates.fasta' ); expect( reads() ).toBe( 1 ); expect( run.binary.options.map( ( option ) => option.value ) ).toContain( 'raxmlHPC_Win7.exe' ); @@ -50,8 +50,8 @@ it( 'uses the later Windows binaries when the release is not 6.1', () => { cpuModel: 'Intel', } ); const { Run, Alignment } = load(); - const run = new Run( {}, 'run-7' ); - const alignment = new Alignment( { id: 'run-7' }, '/data/primates.fasta' ); + const run = new Run( {}, 7 ); + const alignment = new Alignment( { id: 7 }, '/data/primates.fasta' ); expect( run.binary.options.map( ( option ) => option.value ) ).toContain( 'raxmlHPC.exe' ); expect( run.binary.options.map( ( option ) => option.value ) ).not.toContain( 'raxmlHPC_Win7.exe' ); @@ -66,7 +66,7 @@ it( 'picks the arm modeltest binary from the arch or the cpu model', () => { cpuModel: 'Intel', } ); let { Run } = load(); - expect( new Run( {}, 'run-7' ).modeltestName ).toBe( 'modeltest-ng-ARM64' ); + expect( new Run( {}, 7 ).modeltestName ).toBe( 'modeltest-ng-ARM64' ); install( { windows: false, @@ -75,7 +75,7 @@ it( 'picks the arm modeltest binary from the arch or the cpu model', () => { cpuModel: 'Apple M4', } ); ( { Run } = load() ); - expect( new Run( {}, 'run-7' ).modeltestName ).toBe( 'modeltest-ng-ARM64' ); + expect( new Run( {}, 7 ).modeltestName ).toBe( 'modeltest-ng-ARM64' ); install( { windows: false, @@ -84,5 +84,5 @@ it( 'picks the arm modeltest binary from the arch or the cpu model', () => { cpuModel: 'Intel', } ); ( { Run } = load() ); - expect( new Run( {}, 'run-7' ).modeltestName ).toBe( 'modeltest-ng' ); + expect( new Run( {}, 7 ).modeltestName ).toBe( 'modeltest-ng' ); } ); diff --git a/src/app/store/loadAlignment.test.js b/src/app/store/loadAlignment.test.js index 57cab74b..719300da 100644 --- a/src/app/store/loadAlignment.test.js +++ b/src/app/store/loadAlignment.test.js @@ -16,7 +16,7 @@ const stayParsed = async () => ( { it( 'the alignment picker adds the chosen alignments', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); const selectAlignment = jest.fn( async () => [ { path: '/data/primates.fasta', name: 'primates.fasta' }, { path: '/data/cats.phy', name: 'cats.phy' }, @@ -25,7 +25,7 @@ it( 'the alignment picker adds the chosen alignments', async () => { await run.loadAlignmentFiles(); - expect( selectAlignment ).toHaveBeenCalledWith( 'run-7' ); + expect( selectAlignment ).toHaveBeenCalledWith( 7 ); expect( run.alignments.map( ( alignment ) => alignment.path ) ).toEqual( [ '/data/primates.fasta', '/data/cats.phy', @@ -33,7 +33,7 @@ it( 'the alignment picker adds the chosen alignments', async () => { } ); it( 'cancel leaves the alignments unchanged', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); window.rendererBridge = { parseAlignment: stayParsed }; run.addAlignments( [{ path: '/data/already.fasta', name: 'already.fasta' }] ); window.rendererBridge = { @@ -43,14 +43,14 @@ it( 'cancel leaves the alignments unchanged', async () => { await run.loadAlignmentFiles(); - expect( window.rendererBridge.selectAlignment ).toHaveBeenCalledWith( 'run-7' ); + expect( window.rendererBridge.selectAlignment ).toHaveBeenCalledWith( 7 ); expect( run.alignments.map( ( alignment ) => alignment.path ) ).toEqual( [ '/data/already.fasta', ] ); } ); it( 'a dialog failure fails the alignment choice', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); window.rendererBridge = { parseAlignment: stayParsed }; run.addAlignments( [{ path: '/data/already.fasta', name: 'already.fasta' }] ); window.rendererBridge = { diff --git a/src/app/store/loadAstralTree.test.js b/src/app/store/loadAstralTree.test.js index 7fcb6fb4..60f40667 100644 --- a/src/app/store/loadAstralTree.test.js +++ b/src/app/store/loadAstralTree.test.js @@ -2,7 +2,7 @@ import Run from './Run'; it( 'the ASTRAL file picker adds the chosen file', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); const selectAstralFile = jest.fn( async () => ( { path: '/data/trees.tre', name: 'trees.tre', @@ -11,12 +11,12 @@ it( 'the ASTRAL file picker adds the chosen file', async () => { await run.loadAstralTree(); - expect( selectAstralFile ).toHaveBeenCalledWith( 'run-7' ); + expect( selectAstralFile ).toHaveBeenCalledWith( 7 ); expect( run.astralTree.path ).toBe( '/data/trees.tre' ); } ); it( 'cancel leaves the ASTRAL file unchanged', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); run.addAstralFiles( { path: '/data/already.tre' } ); window.rendererBridge = { selectAstralFile: jest.fn( async () => null ), @@ -24,12 +24,12 @@ it( 'cancel leaves the ASTRAL file unchanged', async () => { await run.loadAstralTree(); - expect( window.rendererBridge.selectAstralFile ).toHaveBeenCalledWith( 'run-7' ); + expect( window.rendererBridge.selectAstralFile ).toHaveBeenCalledWith( 7 ); expect( run.astralTree.path ).toBe( '/data/already.tre' ); } ); it( 'a dialog failure fails the ASTRAL file choice', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); run.addAstralFiles( { path: '/data/already.tre' } ); window.rendererBridge = { selectAstralFile: async () => { diff --git a/src/app/store/loadPartitionFile.test.js b/src/app/store/loadPartitionFile.test.js index b2e0462a..6d44d587 100644 --- a/src/app/store/loadPartitionFile.test.js +++ b/src/app/store/loadPartitionFile.test.js @@ -2,20 +2,20 @@ import Run from './Run'; it( 'the partition picker uses the chosen file', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); const selectPartitionFile = jest.fn( async () => '/data/genes.part' ); const readFile = jest.fn( async () => 'DNA, gene = 1-100\n' ); window.rendererBridge = { selectPartitionFile, readFile }; await run.loadPartitionFile(); - expect( selectPartitionFile ).toHaveBeenCalledWith( 'run-7' ); + expect( selectPartitionFile ).toHaveBeenCalledWith( 7 ); expect( run.partitionFile ).toBe( '/data/genes.part' ); expect( run.partitionFileContent ).toBe( 'DNA, gene = 1-100\n' ); } ); it( 'cancel leaves the partition unchanged', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); run.partitionFile = '/data/already.part'; run.partitionFileContent = 'kept'; window.rendererBridge = { @@ -24,13 +24,13 @@ it( 'cancel leaves the partition unchanged', async () => { await run.loadPartitionFile(); - expect( window.rendererBridge.selectPartitionFile ).toHaveBeenCalledWith( 'run-7' ); + expect( window.rendererBridge.selectPartitionFile ).toHaveBeenCalledWith( 7 ); expect( run.partitionFile ).toBe( '/data/already.part' ); expect( run.partitionFileContent ).toBe( 'kept' ); } ); it( 'a dialog failure fails the partition choice', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); run.partitionFile = '/data/already.part'; run.partitionFileContent = 'kept'; window.rendererBridge = { diff --git a/src/app/store/loadTree.test.js b/src/app/store/loadTree.test.js index 0bd64ca2..430751ee 100644 --- a/src/app/store/loadTree.test.js +++ b/src/app/store/loadTree.test.js @@ -2,7 +2,7 @@ import Run from './Run'; it( 'each tree picker keeps the chosen file', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); const selectTree = jest.fn() .mockResolvedValueOnce( { type: 'tree', filePath: '/data/start.nwk' } ) .mockResolvedValueOnce( { type: 'backboneConstraint', filePath: '/data/backbone.nwk' } ) @@ -13,16 +13,16 @@ it( 'each tree picker keeps the chosen file', async () => { await run.loadBackboneConstraintFile(); await run.loadMultifurcatingConstraintFile(); - expect( selectTree ).toHaveBeenNthCalledWith( 1, 'run-7', 'tree' ); - expect( selectTree ).toHaveBeenNthCalledWith( 2, 'run-7', 'backboneConstraint' ); - expect( selectTree ).toHaveBeenNthCalledWith( 3, 'run-7', 'multifurcatingConstraint' ); + expect( selectTree ).toHaveBeenNthCalledWith( 1, 7, 'tree' ); + expect( selectTree ).toHaveBeenNthCalledWith( 2, 7, 'backboneConstraint' ); + expect( selectTree ).toHaveBeenNthCalledWith( 3, 7, 'multifurcatingConstraint' ); expect( run.tree.filePath ).toBe( '/data/start.nwk' ); expect( run.backboneConstraint.filePath ).toBe( '/data/backbone.nwk' ); expect( run.multifurcatingConstraint.filePath ).toBe( '/data/multi.nwk' ); } ); it( 'cancel leaves the trees unchanged', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); run.tree.setFilePath( '/data/already.nwk' ); window.rendererBridge = { selectTree: jest.fn( async () => null ), @@ -32,16 +32,16 @@ it( 'cancel leaves the trees unchanged', async () => { await run.loadBackboneConstraintFile(); await run.loadMultifurcatingConstraintFile(); - expect( window.rendererBridge.selectTree ).toHaveBeenCalledWith( 'run-7', 'tree' ); - expect( window.rendererBridge.selectTree ).toHaveBeenCalledWith( 'run-7', 'backboneConstraint' ); - expect( window.rendererBridge.selectTree ).toHaveBeenCalledWith( 'run-7', 'multifurcatingConstraint' ); + expect( window.rendererBridge.selectTree ).toHaveBeenCalledWith( 7, 'tree' ); + expect( window.rendererBridge.selectTree ).toHaveBeenCalledWith( 7, 'backboneConstraint' ); + expect( window.rendererBridge.selectTree ).toHaveBeenCalledWith( 7, 'multifurcatingConstraint' ); expect( run.tree.filePath ).toBe( '/data/already.nwk' ); expect( run.backboneConstraint.filePath ).toBe( '' ); expect( run.multifurcatingConstraint.filePath ).toBe( '' ); } ); it( 'a dialog failure fails the tree choice', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); run.tree.setFilePath( '/data/already.nwk' ); window.rendererBridge = { selectTree: async () => { diff --git a/src/app/store/modelSelection.test.js b/src/app/store/modelSelection.test.js index 1d77ec3d..6194defb 100644 --- a/src/app/store/modelSelection.test.js +++ b/src/app/store/modelSelection.test.js @@ -30,7 +30,7 @@ function emit( list, payload ) { it( 'startModelSelection starts model selection', async () => { const startModelSelection = jest.fn( async () => {} ); bridge( { startModelSelection } ); - const run = new Run( { onError() {} }, 'run-7' ); + const run = new Run( { onError() {} }, 7 ); run.setOutputDir( '/out' ); run.addAlignments( [{ path: '/data/primates.fasta' }] ); const alignment = run.alignments[0]; @@ -41,7 +41,7 @@ it( 'startModelSelection starts model selection', async () => { expect( alignment.modeltestLoading ).toBe( true ); expect( startModelSelection ).toHaveBeenCalledWith( { - id: 'run-7_/data/primates.fasta', + id: '7_/data/primates.fasta', filePath: '/data/primates.fasta', outputDir: '/out', dataType: 'nucleotide', @@ -52,7 +52,7 @@ it( 'startModelSelection starts model selection', async () => { it( 'a model selection result sets the model', () => { const { listeners, stops } = bridge(); - const run = new Run( { onError() {} }, 'run-7' ); + const run = new Run( { onError() {} }, 7 ); run.running = true; run.addAlignments( [{ path: '/data/primates.fasta' }] ); const alignment = run.alignments[0]; @@ -76,20 +76,20 @@ it( 'a model selection result sets the model', () => { it( 'the model-selection cancel control uses cancelModelSelection', () => { const cancelModelSelection = jest.fn(); bridge( { cancelModelSelection } ); - const run = new Run( { onError() {} }, 'run-7' ); + const run = new Run( { onError() {} }, 7 ); run.addAlignments( [{ path: '/data/primates.fasta' }] ); const alignment = run.alignments[0]; alignment.modeltestLoading = true; alignment.cancelModelTest(); - expect( cancelModelSelection ).toHaveBeenCalledWith( 'run-7_/data/primates.fasta' ); + expect( cancelModelSelection ).toHaveBeenCalledWith( '7_/data/primates.fasta' ); expect( alignment.modeltestLoading ).toBe( false ); } ); it( 'a model selection failure shows the error', () => { const { listeners } = bridge(); - const run = new Run( { onError() {} }, 'run-7' ); + const run = new Run( { onError() {} }, 7 ); run.running = true; run.addAlignments( [{ path: '/data/primates.fasta' }] ); const alignment = run.alignments[0]; diff --git a/src/app/store/openPath.test.js b/src/app/store/openPath.test.js index 648ca618..dd704614 100644 --- a/src/app/store/openPath.test.js +++ b/src/app/store/openPath.test.js @@ -2,7 +2,7 @@ import Run from './Run'; it( 'opens a result file through the renderer bridge', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); const openPath = jest.fn( async () => '' ); window.rendererBridge = { openPath }; @@ -12,7 +12,7 @@ it( 'opens a result file through the renderer bridge', async () => { } ); it( 'opens the output directory through the renderer bridge', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); run.setOutputDir( '/data/results' ); const openPath = jest.fn( async () => '' ); window.rendererBridge = { openPath }; diff --git a/src/app/store/parseAlignment.test.js b/src/app/store/parseAlignment.test.js index 3fe7be75..04c8a02c 100644 --- a/src/app/store/parseAlignment.test.js +++ b/src/app/store/parseAlignment.test.js @@ -15,7 +15,7 @@ const alignment = { }; function add( parseAlignment ) { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); let pending; window.rendererBridge = { parseAlignment: ( ...args ) => { @@ -33,7 +33,7 @@ it( 'the alignment load keeps the path when parsing changes nothing', async () = await pending; expect( parseAlignment ).toHaveBeenCalledWith( - 'run-7_/data/primates.fasta', + '7_/data/primates.fasta', '/data/primates.fasta', ); const loaded = run.alignments[0]; diff --git a/src/app/store/readText.test.js b/src/app/store/readText.test.js index f73c89d8..ec8dba01 100644 --- a/src/app/store/readText.test.js +++ b/src/app/store/readText.test.js @@ -2,7 +2,7 @@ import Run from './Run'; it( 'reads a text file through the renderer bridge', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); const readFile = jest.fn( async () => 'DNA, gene = 1-100\n' ); window.rendererBridge = { readFile }; diff --git a/src/app/store/selectOutputDir.test.js b/src/app/store/selectOutputDir.test.js index 96f59922..794d699e 100644 --- a/src/app/store/selectOutputDir.test.js +++ b/src/app/store/selectOutputDir.test.js @@ -2,18 +2,18 @@ import Run from './Run'; it( 'the output-directory picker sets the chosen directory', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); const selectOutputDir = jest.fn( async () => '/data/results' ); window.rendererBridge = { selectOutputDir }; await run.selectOutputDir(); - expect( selectOutputDir ).toHaveBeenCalledWith( 'run-7' ); + expect( selectOutputDir ).toHaveBeenCalledWith( 7 ); expect( run.outputDir ).toBe( '/data/results' ); } ); it( 'cancel leaves the output directory unchanged', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); run.setOutputDir( '/data/already' ); window.rendererBridge = { selectOutputDir: jest.fn( async () => null ), @@ -21,12 +21,12 @@ it( 'cancel leaves the output directory unchanged', async () => { await run.selectOutputDir(); - expect( window.rendererBridge.selectOutputDir ).toHaveBeenCalledWith( 'run-7' ); + expect( window.rendererBridge.selectOutputDir ).toHaveBeenCalledWith( 7 ); expect( run.outputDir ).toBe( '/data/already' ); } ); it( 'a dialog failure fails the output-directory choice', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); run.setOutputDir( '/data/already' ); window.rendererBridge = { selectOutputDir: async () => { diff --git a/src/app/store/showItemInFolder.test.js b/src/app/store/showItemInFolder.test.js index 21303201..ffa6a094 100644 --- a/src/app/store/showItemInFolder.test.js +++ b/src/app/store/showItemInFolder.test.js @@ -3,7 +3,7 @@ import InputFile from './InputFile'; import Run from './Run'; it( 'shows a tree file in its folder', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); run.tree.setFilePath( '/data/start.nwk' ); const showItemInFolder = jest.fn( async () => {} ); window.rendererBridge = { showItemInFolder }; @@ -14,7 +14,7 @@ it( 'shows a tree file in its folder', async () => { } ); it( 'shows an input file in its folder', async () => { - const file = new InputFile( { id: 'run-7' }, '/data/primates.fasta' ); + const file = new InputFile( { id: 7 }, '/data/primates.fasta' ); const showItemInFolder = jest.fn( async () => {} ); window.rendererBridge = { showItemInFolder }; @@ -24,7 +24,7 @@ it( 'shows an input file in its folder', async () => { } ); it( 'shows the concatenated alignment in its folder', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); window.rendererBridge = { parseAlignment: () => new Promise( () => {} ) }; run.addAlignments( [ { path: '/data/a.fasta' } ] ); run.alignments[0].sequences = [ diff --git a/src/app/store/startRun.test.js b/src/app/store/startRun.test.js index 432fcbf2..95ed6cff 100644 --- a/src/app/store/startRun.test.js +++ b/src/app/store/startRun.test.js @@ -42,7 +42,7 @@ it( 'startRun starts the run', async () => { const outputDir = fs.mkdtempSync( path.join( os.tmpdir(), 'raxml-run-' ) ); const startRun = jest.fn( async () => {} ); bridge( { startRun } ); - const run = new Run( { onError() {} }, 'run-7' ); + const run = new Run( { onError() {} }, 7 ); run.addAlignments( [{ path: '/data/primates.fasta' }] ); run.alignments[0].sequences = [ { taxon: 'A' }, @@ -56,12 +56,12 @@ it( 'startRun starts the run', async () => { await run.start(); expect( startRun ).toHaveBeenCalledWith( { - id: 'run-7', + id: 7, args: run.args, binaryName: run.binary.value, outputDir, - outputFilename: 'run-7.tre', - outputName: 'run-7', + outputFilename: '7.tre', + outputName: '7', combinedOutput: false, usesRaxmlNg: run.usesRaxmlNg, usesModeltestNg: run.usesModeltestNg, @@ -74,17 +74,17 @@ it( 'startRun starts the run', async () => { it( 'stdout, stderr, finish, and failure update the run', () => { const { listeners, stops } = bridge(); - const run = new Run( { onError() {} }, 'run-7' ); + const run = new Run( { onError() {} }, 7 ); run.running = true; - emit( listeners.stdout, { id: 'run-7', content: 'tree\n' } ); + emit( listeners.stdout, { id: 7, content: 'tree\n' } ); emit( listeners.stdout, { id: 'other', content: 'nope' } ); - emit( listeners.stderr, { id: 'run-7', content: 'warn\n' } ); + emit( listeners.stderr, { id: 7, content: 'warn\n' } ); expect( run.stdout ).toBe( 'tree\n' ); expect( run.stderr ).toBe( 'warn\n' ); emit( listeners.finished, { - id: 'run-7', + id: 7, resultDir: '/out', resultFilenames: ['primates.tre'], exitCode: 0, @@ -95,7 +95,7 @@ it( 'stdout, stderr, finish, and failure update the run', () => { expect( run.running ).toBe( false ); run.running = true; - emit( listeners.error, { id: 'run-7', error: 'missing binary' } ); + emit( listeners.error, { id: 7, error: 'missing binary' } ); expect( run.error ).toBe( 'missing binary' ); expect( run.running ).toBe( false ); emit( listeners.error, { id: 'other', error: 'ignore' } ); @@ -107,7 +107,7 @@ it( 'stdout, stderr, finish, and failure update the run', () => { it( 'alignment output is appended for that alignment', () => { const { listeners } = bridge(); - const run = new Run( { onError() {} }, 'run-7' ); + const run = new Run( { onError() {} }, 7 ); run.addAlignments( [{ path: '/data/primates.fasta' }] ); const alignment = run.alignments[0]; diff --git a/src/app/store/writeConcatenatedAlignment.test.js b/src/app/store/writeConcatenatedAlignment.test.js index 618330e9..f06655ea 100644 --- a/src/app/store/writeConcatenatedAlignment.test.js +++ b/src/app/store/writeConcatenatedAlignment.test.js @@ -2,7 +2,7 @@ import Run from './Run'; it( 'writes one concatenated FASTA', async () => { - const run = new Run( {}, 'run-7' ); + const run = new Run( {}, 7 ); window.rendererBridge = { parseAlignment: () => new Promise( () => {} ) }; run.addAlignments( [ { path: '/data/a.fasta' }, diff --git a/src/common/errors.js b/src/common/errors.ts similarity index 70% rename from src/common/errors.js rename to src/common/errors.ts index 8e6d9a19..7d72a47a 100644 --- a/src/common/errors.js +++ b/src/common/errors.ts @@ -1,5 +1,7 @@ export default class UserFixError extends Error { - constructor( message ) { + isUserFix: boolean; + + constructor( message: string ) { super( message ); this.isUserFix = true; this.name = 'UserFixError'; diff --git a/src/common/io.js b/src/common/io.ts similarity index 76% rename from src/common/io.js rename to src/common/io.ts index cca48e0c..c814e120 100644 --- a/src/common/io.js +++ b/src/common/io.ts @@ -5,15 +5,25 @@ import phylipParser from './phylipParser'; import fastaParser from './fastaParser'; import typecheckAlignment from './typecheckAlignment'; import UserFixError from './errors'; -export const parseAlignment = async ( filePath ) => { + +interface AlignmentSequence { + taxon: string; + code: string; +} + +interface Alignment { + sequences: AlignmentSequence[]; +} + +export const parseAlignment = async ( filePath: string ): Promise => { return new Promise( ( resolve, reject ) => { const rl = readline.createInterface( { input: fs.createReadStream( filePath ), terminal: false, } ); - const lines = []; - let error = null; - let alignment = null; + const lines: string[] = []; + let error: Error | null = null; + let alignment: Alignment | null = null; rl.on( 'line', ( line ) => { lines.push( line ); } ).on( 'close', () => { @@ -25,10 +35,8 @@ export const parseAlignment = async ( filePath ) => { } else { throw new UserFixError( "Unrecognized input format. RaxmlGUI2 supports the following input types at the moment: 'clustal', 'fasta', 'nbrf', 'nexus', 'mega', 'phylip'." ); } - } catch ( err ) { - const parseError = err instanceof Error - ? err - : new Error( String( err ) ); + } catch ( err: unknown ) { + const parseError = err as Error; parseError.message = `Error parsing file ${filePath}: ${parseError.message}.`; error = parseError; } @@ -40,7 +48,7 @@ export const parseAlignment = async ( filePath ) => { } try { typecheckAlignment( alignment ); - } catch ( err ) { + } catch ( err: unknown ) { console.error( 'Error checking data type:', err ); return reject( err ); } @@ -53,7 +61,8 @@ export const parseAlignment = async ( filePath ) => { } ); } ); }; -export const writeAlignment = async ( filePath, alignment ) => { + +export const writeAlignment = async ( filePath: string, alignment: Alignment ): Promise => { console.log( `Write alignment in FASTA format to ${filePath}` ); console.log( alignment ); const writeStream = fs.createWriteStream( filePath ); @@ -70,7 +79,12 @@ export const writeAlignment = async ( filePath, alignment ) => { await end.call( writeStream ); }; -const io = { +interface Io { + parseAlignment: ( filePath: string ) => Promise; + writeAlignment: ( filePath: string, alignment: Alignment ) => Promise; +} + +const io: Io = { parseAlignment, writeAlignment, }; diff --git a/src/common/utils.js b/src/common/utils.js deleted file mode 100644 index 4bde6e44..00000000 --- a/src/common/utils.js +++ /dev/null @@ -1,74 +0,0 @@ -import electron from 'electron'; -import os from 'os'; -import { serializeError } from 'serialize-error'; -import cleanStack from 'clean-stack'; -import { getActiveState as askActiveState } from '../main/getActiveState'; -const processWithElectron = process; -export const is = { - macos: process.platform === 'darwin', - linux: process.platform === 'linux', - windows: process.platform === 'win32', - main: process.type === 'browser', - renderer: process.type === 'renderer', - development: process.env.NODE_ENV === 'development', - macAppStore: processWithElectron.mas === true, - windowsStore: processWithElectron.windowsStore === true, -}; -export const platform = ( object ) => { - let platformKey = process.platform; - if ( is.macos ) { - platformKey = 'macos'; - } else if ( is.windows ) { - platformKey = 'windows'; - } - const fn = platformKey in object - ? object[platformKey] - : object.default; - return typeof fn === 'function' - ? fn() - : fn; -}; -// TODO: Had to replace this debug info on renderer, because electron remote module is no longer available. -// If needed, one would need to use the context bridge -export const debugInfo = () => is.main - ? `${electron.app.getName()} ${electron.app.getVersion()} -Electron ${process.versions.electron} -${process.platform} ${os.release()} -Locale: ${electron.app.getLocale()} -`.trim() - : `Debug info not available in renderer.`; -export const getActiveState = () => askActiveState(); -export const serializeAndCleanError = ( error ) => { - const err = serializeError( error ); - const stack = error && typeof error.stack === 'string' - ? error.stack - : undefined; - if ( err && typeof err === 'object' && stack ) { - err.stack = cleanStack( stack ); - } - return err; -}; -export function timeout( ms ) { - return new Promise( ( resolve ) => setTimeout( resolve, ms ) ); -} -export const quote = ( dir ) => ( is.windows - ? `"${dir}"` - : dir ); -const stringify = ( json ) => JSON.stringify( json, null, ' ' ); -const createReportBodyForMail = ( error, activeState ) => encodeURI( `Autogenerated report: -${stringify( serializeAndCleanError( error ) )} - -Active state: -${stringify( activeState )} - ---- - -Process: ${is.renderer - ? 'renderer' - : 'main'} -${debugInfo()}` ); -export const getMailtoLinkToReportError = async ( error ) => { - const activeState = await getActiveState(); - const mailtoLinkContent = `mailto:raxmlgui.help@googlemail.com?subject=${encodeURI( error.name )}&body=${createReportBodyForMail( error, activeState )}`; - return mailtoLinkContent; -}; diff --git a/src/common/utils.ts b/src/common/utils.ts new file mode 100644 index 00000000..b7727c2e --- /dev/null +++ b/src/common/utils.ts @@ -0,0 +1,34 @@ +interface Is { + macos: boolean; + linux: boolean; + windows: boolean; + development: boolean; +} + +export const is: Is = { + macos: process.platform === 'darwin', + linux: process.platform === 'linux', + windows: process.platform === 'win32', + development: process.env.NODE_ENV === 'development', +}; + +export const platform = ( + object: { [key: string]: T | ( () => T ) | undefined }, +): T => { + let platformKey: string = process.platform; + if ( is.macos ) { + platformKey = 'macos'; + } else if ( is.windows ) { + platformKey = 'windows'; + } + const fn = platformKey in object + ? object[platformKey] + : object.default; + return typeof fn === 'function' + ? ( fn as () => T )() + : fn as T; +}; + +export const quote = ( dir: string ): string => ( is.windows + ? `"${dir}"` + : dir ); diff --git a/src/constants/ipc.js b/src/constants/ipc.js deleted file mode 100644 index ef210e41..00000000 --- a/src/constants/ipc.js +++ /dev/null @@ -1,49 +0,0 @@ -/* - Strings for ipc -*/ -export const GET_VERSION = 'GET_VERSION'; -export const GET_DARK_MODE = 'GET_DARK_MODE'; -export const SET_DARK_MODE = 'SET_DARK_MODE'; -export const OUTPUT_DIR_SELECT = 'OUTPUT_DIR_SELECT'; -export const TREE_SELECT = 'TREE_SELECT'; -export const PARTITION_FILE_SELECT = 'PARTITION_FILE_SELECT'; -export const RUN_START = 'RUN_START'; -export const RUN_STDOUT = 'RUN_STDOUT'; -export const RUN_STDERR = 'RUN_STDERR'; -export const RUN_FINISHED = 'RUN_FINISHED'; -export const RUN_ERROR = 'RUN_ERROR'; -export const RUN_CANCEL = 'RUN_CANCEL'; -export const OPEN_PATH = 'OPEN_PATH'; -export const FILE_SHOW_IN_FOLDER = 'FILE_SHOW_IN_FOLDER'; -export const OUTPUT_CHECK = 'OUTPUT_CHECK'; -export const ALIGNMENT_SELECT = 'ALIGNMENT_SELECT'; -export const ALIGNMENT_PARSE = 'ALIGNMENT_PARSE'; -export const EXAMPLE_FILES = 'EXAMPLE_FILES'; -export const ALIGNMENT_MODEL_SELECTION_REQUEST = - 'ALIGNMENT_MODEL_SELECTION_REQUEST'; -export const ALIGNMENT_MODEL_SELECTION_CANCEL = - 'ALIGNMENT_MODEL_SELECTION_CANCEL'; -export const ALIGNMENT_MODEL_SELECTION_SUCCESS = - 'ALIGNMENT_MODEL_SELECTION_SUCCESS'; -export const ALIGNMENT_MODEL_SELECTION_FAILURE = - 'ALIGNMENT_MODEL_SELECTION_FAILURE'; -export const UNHANDLED_ERROR = 'UNHANDLED_ERROR'; -export const TOGGLE_BACKBONE_CONSTRAINT = 'TOGGLE_BACKBONE_CONSTRAINT'; -export const TOGGLE_MULTIFURCATING_CONSTRAINT = - 'TOGGLE_MULTIFURCATING_CONSTRAINT'; -export const ADD_RUN = 'ADD_RUN'; -export const REMOVE_RUN = 'REMOVE_RUN'; -export const LIGHT_MODE = 'LIGHT_MODE'; -export const DARK_MODE = 'DARK_MODE'; -export const DEBUG_INFO = 'DEBUG_INFO'; -export const RELOAD = 'RELOAD'; -export const OPEN_EXTERNAL = 'OPEN_EXTERNAL'; -export const ASTRAL_REQUEST = 'ASTRAL_REQUEST'; -export const ASTRAL_SUCCESS = 'ASTRAL_SUCCESS'; -export const ASTRAL_FILE_SELECT = 'ASTRAL_FILE_SELECT'; -export const COPY_TEXT = 'COPY_TEXT'; -export const READ_FILE = 'READ_FILE'; -export const WRITE_FILE = 'WRITE_FILE'; -export const STATE_REPORT = 'STATE_REPORT'; -export const STATE_REPORT_RESULT = 'STATE_REPORT_RESULT'; -export const HOST = 'HOST'; diff --git a/src/constants/ipc.ts b/src/constants/ipc.ts new file mode 100644 index 00000000..1b595871 --- /dev/null +++ b/src/constants/ipc.ts @@ -0,0 +1,49 @@ +/* + Strings for ipc +*/ +export const GET_VERSION = 'GET_VERSION' as const; +export const GET_DARK_MODE = 'GET_DARK_MODE' as const; +export const SET_DARK_MODE = 'SET_DARK_MODE' as const; +export const OUTPUT_DIR_SELECT = 'OUTPUT_DIR_SELECT' as const; +export const TREE_SELECT = 'TREE_SELECT' as const; +export const PARTITION_FILE_SELECT = 'PARTITION_FILE_SELECT' as const; +export const RUN_START = 'RUN_START' as const; +export const RUN_STDOUT = 'RUN_STDOUT' as const; +export const RUN_STDERR = 'RUN_STDERR' as const; +export const RUN_FINISHED = 'RUN_FINISHED' as const; +export const RUN_ERROR = 'RUN_ERROR' as const; +export const RUN_CANCEL = 'RUN_CANCEL' as const; +export const OPEN_PATH = 'OPEN_PATH' as const; +export const FILE_SHOW_IN_FOLDER = 'FILE_SHOW_IN_FOLDER' as const; +export const OUTPUT_CHECK = 'OUTPUT_CHECK' as const; +export const ALIGNMENT_SELECT = 'ALIGNMENT_SELECT' as const; +export const ALIGNMENT_PARSE = 'ALIGNMENT_PARSE' as const; +export const EXAMPLE_FILES = 'EXAMPLE_FILES' as const; +export const ALIGNMENT_MODEL_SELECTION_REQUEST = + 'ALIGNMENT_MODEL_SELECTION_REQUEST' as const; +export const ALIGNMENT_MODEL_SELECTION_CANCEL = + 'ALIGNMENT_MODEL_SELECTION_CANCEL' as const; +export const ALIGNMENT_MODEL_SELECTION_SUCCESS = + 'ALIGNMENT_MODEL_SELECTION_SUCCESS' as const; +export const ALIGNMENT_MODEL_SELECTION_FAILURE = + 'ALIGNMENT_MODEL_SELECTION_FAILURE' as const; +export const UNHANDLED_ERROR = 'UNHANDLED_ERROR' as const; +export const TOGGLE_BACKBONE_CONSTRAINT = 'TOGGLE_BACKBONE_CONSTRAINT' as const; +export const TOGGLE_MULTIFURCATING_CONSTRAINT = + 'TOGGLE_MULTIFURCATING_CONSTRAINT' as const; +export const ADD_RUN = 'ADD_RUN' as const; +export const REMOVE_RUN = 'REMOVE_RUN' as const; +export const LIGHT_MODE = 'LIGHT_MODE' as const; +export const DARK_MODE = 'DARK_MODE' as const; +export const DEBUG_INFO = 'DEBUG_INFO' as const; +export const RELOAD = 'RELOAD' as const; +export const OPEN_EXTERNAL = 'OPEN_EXTERNAL' as const; +export const ASTRAL_REQUEST = 'ASTRAL_REQUEST' as const; +export const ASTRAL_SUCCESS = 'ASTRAL_SUCCESS' as const; +export const ASTRAL_FILE_SELECT = 'ASTRAL_FILE_SELECT' as const; +export const COPY_TEXT = 'COPY_TEXT' as const; +export const READ_FILE = 'READ_FILE' as const; +export const WRITE_FILE = 'WRITE_FILE' as const; +export const STATE_REPORT = 'STATE_REPORT' as const; +export const STATE_REPORT_RESULT = 'STATE_REPORT_RESULT' as const; +export const HOST = 'HOST' as const; diff --git a/src/main/api.js b/src/main/api.js deleted file mode 100644 index a88e1f7e..00000000 --- a/src/main/api.js +++ /dev/null @@ -1,566 +0,0 @@ -/* global __static */ -import { app, ipcMain, shell, dialog, Notification, clipboard } from 'electron'; -import os from 'os'; -import path from 'path'; -import util from 'util'; -import _fs from 'fs'; -import childProcess from 'child_process'; -import { serializeError } from 'serialize-error'; -import parsePath from 'parse-filepath'; -import * as Sentry from '@sentry/electron/main'; -import * as ipc from '../constants/ipc'; -import io from '../common/io'; -import { parseAlignment } from './parseAlignment'; -import { selectAlignment } from './selectAlignment'; -import { selectAstralFile } from './selectAstralFile'; -import { selectOutputDir } from './selectOutputDir'; -import { checkOutput } from './checkOutput'; -import { debugInfo } from './debugInfo'; -import { selectPartitionFile } from './selectPartitionFile'; -import { selectTree } from './selectTree'; -import { appStore } from './appStore'; -import { is, platform, quote } from '../common/utils'; -import UserFixError from '../common/errors'; -import { activeWindow } from './utils/utils'; -import { - beginRun, - cancelRun, - finishedRun, - forgetRun, - runResult, - stillRunning, - stopRun, - trackRun, -} from './cancelRun'; -if ( !is.development ) { - Sentry.init( { - dsn: 'https://d92efa46c2ba43f38250b202c791a2c2@o117148.ingest.sentry.io/6517975', - maxValueLength: 2000, - } ); -} -const fs = _fs.promises; -function getStaticDir() { - if ( process.env.RAXMLGUI_E2E === '1' ) { - return path.join( __dirname, '..', '..', 'static' ); - } - return __static; -} -const get_space_safe_binary_path = ( bin_path ) => { - // For Windows users with spaces in user dir - return is.windows - ? `"${bin_path}"` - : bin_path; -}; -function handleError( title, error ) { - // send error to renderer - console.log( `${title}:`, error ); - const win = activeWindow(); - if ( win ) { - win.webContents.send( ipc.UNHANDLED_ERROR, { - title, - error: serializeError( error ), - } ); - } -} -process.on( 'uncaughtException', ( error ) => { - handleError( 'Unhandled Error', error ); -} ); -process.on( 'unhandledRejection', ( error ) => { - handleError( 'Unhandled Promise Rejection', error ); -} ); -const exec = util.promisify( childProcess.exec ); -const execFile = util.promisify( childProcess.execFile ); -function send( event, channel, data ) { - if ( !data.error ) { - return event.sender.send( channel, data ); - } - return event.sender.send( channel, Object.assign( {}, data, { error: serializeError( data.error ) } ) ); -} -ipcMain.on( ipc.HOST, ( event ) => { - const cpu = os.cpus()[0]; - event.returnValue = { - windows: process.platform === 'win32', - release: os.release(), - arch: os.arch(), - cpuModel: cpu.model, - }; -} ); -ipcMain.handle( ipc.GET_VERSION, () => app.getVersion() ); -ipcMain.handle( ipc.GET_DARK_MODE, () => Boolean( appStore.get( 'darkMode' ) ) ); -ipcMain.handle( ipc.SET_DARK_MODE, ( _event, value ) => { - appStore.set( 'darkMode', !!value ); -} ); -ipcMain.handle( ipc.COPY_TEXT, async ( _event, text ) => { - await clipboard.writeText( text ); -} ); -ipcMain.handle( ipc.READ_FILE, ( _event, filePath ) => { - return fs.readFile( filePath, 'utf-8' ); -} ); -ipcMain.handle( ipc.WRITE_FILE, async ( _event, filePath, text ) => { - await fs.writeFile( filePath, text ); -} ); -ipcMain.handle( ipc.RELOAD, ( event ) => { - event.sender.reload(); -} ); -ipcMain.handle( ipc.DEBUG_INFO, () => { - return debugInfo( { - name: app.getName(), - version: app.getVersion(), - electron: process.versions.electron, - platform: process.platform, - release: os.release(), - locale: app.getLocale(), - } ); -} ); -ipcMain.handle( ipc.OPEN_EXTERNAL, ( _event, url ) => { - return shell.openExternal( url ); -} ); -ipcMain.handle( ipc.OUTPUT_DIR_SELECT, ( _event, _runId ) => { - return selectOutputDir( ( options ) => dialog.showOpenDialog( options ) ); -} ); -ipcMain.handle( ipc.PARTITION_FILE_SELECT, ( _event, _runId ) => { - return selectPartitionFile( ( options ) => dialog.showOpenDialog( options ) ); -} ); -ipcMain.handle( ipc.OPEN_PATH, ( _event, fullPath ) => { - return shell.openPath( fullPath ); -} ); -// Open a file in it's folder with native file explorer -ipcMain.handle( ipc.FILE_SHOW_IN_FOLDER, ( _event, fullPath ) => { - console.debug( ipc.FILE_SHOW_IN_FOLDER, fullPath ); - shell.showItemInFolder( fullPath ); -} ); -// Check if raxml output files already exist with current name -ipcMain.handle( ipc.OUTPUT_CHECK, ( _event, { outputDir, outputName } ) => { - return checkOutput( { outputDir, outputName } ); -} ); -// Function to combine multiple output trees into one file -async function combineOutput( outputDir, outputFilename ) { - // Use type command on windows, cat on Mac or Linux - const command = is.windows - ? 'type' - : 'cat'; - const childCmd = `${command} RAxML_result.${outputFilename}* > combined_results.${outputFilename}`; - const { stdout, stderr } = await exec( childCmd, { - cwd: outputDir, - ...( is.windows - ? { shell: true } - : {} ), - } ); - console.log( stdout, stderr ); -} -const binParentDir = app.isPackaged - ? '' - : platform( { - macos: 'Mac', - windows: 'Windows', - linux: 'Linux', - } ); -const binaryDir = path.join( getStaticDir(), 'bin', binParentDir ); -ipcMain.handle( ipc.RUN_START, async ( event, { id, args, binaryName, outputDir, outputFilename, outputName, combinedOutput, usesRaxmlNg, usesModeltestNg, inputPath } ) => { - const token = beginRun( id ); - stopRun( id ); - const reportError = ( error ) => { - if ( !stillRunning( id, token ) ) { - return; - } - send( event, ipc.RUN_ERROR, { id, error } ); - }; - const binaryPath = path.resolve( binaryDir, binaryName ); - console.log( `Run ${id}:\n output filename id: ${outputFilename}\n output dir: ${outputDir}\n binary: ${binaryName}\n binary path: ${binaryDir}\n args:`, args ); - // Check for deleted input file - try { - await fs.access( inputPath ); - // The check succeeded - } - catch ( err ) { - const error = new UserFixError( `The input file does not exist '${inputPath}': ${err.message}` ); - Sentry.captureException( err ); - reportError( error ); - return; - } - const resultFilePath = path.join( outputDir, outputFilename ); - console.log( `Try writing to output file '${resultFilePath}'...` ); - try { - await fs.writeFile( resultFilePath, 'test' ); - console.log( ` -> writing to output file ok!` ); - } - catch ( err ) { - console.error( 'Error writing to output file:', err ); - const error = new Error( `Error trying to write to output file '${resultFilePath}': ${err.message}` ); - Sentry.captureException( err ); - reportError( error ); - return; - } - finally { - try { - fs.unlink( resultFilePath ); - } - catch ( err ) { - console.error( `Error trying to unlink temporary result file: ${err.message}` ); - } - } - console.log( `Try executing binary by running '"${binaryPath}" -v'...` ); - try { - const { stdout, stderr } = await execFile( get_space_safe_binary_path( binaryPath ), usesModeltestNg - ? ['--version'] - : ['-v'], { - // env: { PATH: binaryDir }, - shell: is.windows, - } ); - console.log( stdout ); - if ( stderr ) { - console.error( 'Error:', stderr ); - } - } - catch ( err ) { - console.error( 'Error executing binary:', err ); - const error = new Error( `Error trying to execute raxml binary '${binaryPath}': ${err.message}` ); - Sentry.captureException( err ); - reportError( error ); - return; - } - // TODO: When packaged, RAxML throws error trying to write the file RAxML_flagCheck: - // "The file RAxML_flagCheck RAxML wants to open for writing or appending can not be opened [mode: wb], exiting ..." - // TODO: this is just skipping a check when raxml-ng is used. Maybe make the "Sanity check" option compulsory here - const checkFlags = is.development && !is.windows && !usesRaxmlNg && !usesModeltestNg; - if ( checkFlags ) { - for ( const arg of args ) { - try { - const { stdout, stderr } = await exec( `"${binaryPath}" ${arg.join( ' ' )} --flag-check`, { - ...( is.windows - ? { shell: true } - : {} ), - } ); - console.log( stdout, stderr ); - } - catch ( err ) { - console.error( 'Flag check run error:', err ); - Sentry.captureException( err ); - reportError( err ); - return; - } - } - } - let exitCode = 0; - for ( const arg of args ) { - try { - console.log( `Run '${binaryName}' with args:`, arg ); - exitCode = await runProcess( id, event, binaryDir, binaryName, arg ); - if ( exitCode !== 0 ) { - break; - } - } - catch ( err ) { - console.error( 'Run error:', err ); - Sentry.captureException( err ); - reportError( err ); - return; - } - } - if ( !stillRunning( id, token ) || !finishedRun( exitCode ) ) { - return; - } - if ( combinedOutput ) { - console.log( 'Combining output...' ); - await combineOutput( outputDir, outputFilename ); - } - // Rename the RAxML_info.\*.tre into RAxML_info.\*.txt - console.log( - `Renaming info file 'RAxML_info.${outputName}.tre' -> 'RAxML_info.${outputName}.txt'...`, - ); - const anyMatch = new RegExp( `RAxML_info\\.${outputName}\\.tre` ); - const filenames = await fs.readdir( outputDir ); - const infoFiles = filenames.filter( ( filename ) => anyMatch.test( filename ) ); - for ( let i = 0; i < infoFiles.length; i++ ) { - const infoPath = path.join( outputDir, infoFiles[i] ); - const newPath = path.join( outputDir, infoFiles[i].replace( '.tre', '.txt' ) ); - await fs.rename( infoPath, newPath ); - } - // Rename the raxml-ng output files to add .tre or .txt extension - if ( usesRaxmlNg ) { - console.log( `Renaming raxml-ng output files to add .tre or .txt extension...` ); - const anyMatch = new RegExp( `${outputName}.raxml` ); - const filenames = await fs.readdir( outputDir ); - const outputFiles = filenames.filter( ( filename ) => anyMatch.test( filename ) ); - const rbaMatch = new RegExp( `${outputName}.raxml.rba` ); - const bestModelMatch = new RegExp( `${outputName}.raxml.bestModel` ); - const logMatch = new RegExp( `${outputName}.raxml.log` ); - const aPMatch = new RegExp( `${outputName}.raxml.ancestralProbs` ); - const aSMatch = new RegExp( `${outputName}.raxml.ancestralStates` ); - let renamedFiles = outputFiles.map( ( f ) => { - if ( rbaMatch.test( f ) ) { - return f; - } - if ( bestModelMatch.test( f ) || - logMatch.test( f ) || - aPMatch.test( f ) || - aSMatch.test( f ) ) { - return ( f += '.txt' ); - } - return ( f += '.tre' ); - } ); - for ( let i = 0; i < outputFiles.length; i++ ) { - const infoPath = path.join( outputDir, outputFiles[i] ); - const newPath = path.join( outputDir, renamedFiles[i] ); - await fs.rename( infoPath, newPath ); - } - } - const nextFilenames = await fs.readdir( outputDir ); - const resultFilenames = nextFilenames.filter( ( filename ) => filename.includes( outputName ) ); - if ( !stillRunning( id, token ) ) { - return; - } - send( event, ipc.RUN_FINISHED, { - id, - resultDir: outputDir, - resultFilenames, - exitCode, - } ); -} ); -ipcMain.handle( ipc.RUN_CANCEL, ( _event, id ) => { - console.log( `Cancel run process ${id}...` ); - cancelRun( id ); -} ); -function spawnProcess( binaryDir, binaryName, args ) { - const binaryPath = path.join( binaryDir, binaryName ); - const proc = childProcess.execFile( get_space_safe_binary_path( binaryPath ), args, { - shell: is.windows, - } ); - return proc; -} -async function runProcess( id, event, binaryDir, binaryName, args, { onStdOut = ( _content ) => { }, onStdErr = ( _content ) => { } } = {} ) { - return new Promise( ( resolve, reject ) => { - stopRun( id ); - try { - const proc = spawnProcess( binaryDir, binaryName, args ); - trackRun( id, proc ); - let exited = false; - proc.stdout.on( 'data', ( buffer ) => { - const content = String( buffer ); - console.log( 'on stdout:', content ); - onStdOut( content ); - send( event, ipc.RUN_STDOUT, { id, content } ); - } ); - proc.stderr.on( 'data', ( buffer ) => { - const content = String( buffer ); - console.error( 'on stderr:', content ); - onStdErr( content ); - send( event, ipc.RUN_STDERR, { id, content } ); - } ); - const onQuit = ( message ) => ( code, signal ) => { - if ( exited ) { - return; - } - console.log( `Process finished with event '${message}' and error/code/signal:`, signal || code ); - exited = true; - forgetRun( id, proc ); - const result = runResult( proc, message, code, signal ); - const win = activeWindow(); - if ( !win || !win.isFocused() ) { - const notification = new Notification( { - title: app.name, - body: 'Calculation finished', - } ); - notification.show(); - } - if ( result === 'SIGTERM' ) { - return resolve( result ); - } - if ( message === 'error' || result instanceof Error ) { - return reject( result ); // code is an error object on 'error' event - } - return resolve( result ); // Add code last to get through code 0 - }; - ['error', 'exit', 'close'].forEach( ( message ) => { - proc.on( message, onQuit( message ) ); - } ); - } - catch ( err ) { - console.log( 'Run catch error:', err ); - reject( err ); - } - } ); -} -// Function to get an alignment format with readal -async function readalGetFormat( alignmentPath ) { - const readalPath = path.resolve( binaryDir, 'readal' ); - const childCmd = `${quote( readalPath )} -in ${quote( alignmentPath )} -type -format`; - const { stdout, stderr } = await exec( childCmd, { - ...( is.windows - ? { shell: true } - : {} ), - } ); - console.log( 'Readal stderr', stderr ); - const replaced = stdout.replace( alignmentPath, '' ); - const formats = ['clustal', 'fasta', 'nbrf', 'nexus', 'mega', 'phylip']; - for ( let i = 0; i < formats.length; i++ ) { - const f = formats[i]; - if ( replaced.includes( f ) ) { - return f; - } - } - return; -} -// Function to convert an alignment to fasta with readal -async function convertAlignment( alignmentPath ) { - const readalPath = path.resolve( binaryDir, 'readal' ); - const newPath = alignmentPath.replace( path.extname( alignmentPath ), '.fas' ); - const childCmd = `${quote( readalPath )} -in ${quote( alignmentPath )} -out ${quote( newPath )} -fasta`; - const { stdout, stderr } = await exec( childCmd, { - ...( is.windows - ? { shell: true } - : {} ), - } ); - console.log( stdout, stderr ); - return newPath; -} -ipcMain.handle( ipc.ALIGNMENT_PARSE, ( _event, id, filePath ) => { - return parseAlignment( id, filePath, { - readFormat: readalGetFormat, - convert: convertAlignment, - parse: io.parseAlignment, - write: io.writeAlignment, - } ); -} ); -// Open a dialog to select alignments -ipcMain.handle( ipc.ALIGNMENT_SELECT, ( _event, _runId ) => { - return selectAlignment( ( options ) => dialog.showOpenDialog( options ) ); -} ); -ipcMain.handle( ipc.ASTRAL_FILE_SELECT, ( _event, _runId ) => { - return selectAstralFile( ( options ) => dialog.showOpenDialog( options ) ); -} ); -ipcMain.handle( ipc.EXAMPLE_FILES, async () => { - const staticDir = getStaticDir(); - const dir = path.join( staticDir, 'example-files' ); - const outdir = path.join( staticDir, 'test-results' ); - // Create outdir if not exists - await fs.mkdir( outdir, { recursive: true } ); - const fastaFiles = await fs.readdir( path.join( dir, 'fasta' ) ); - const phylipFiles = await fs.readdir( path.join( dir, 'phylip' ) ); - return { - fasta: fastaFiles, - phylip: phylipFiles, - dir, - outdir, - }; -} ); -ipcMain.handle( ipc.ASTRAL_REQUEST, async ( event, payload ) => { - const { id, binaryName, args } = payload; - const javaBin = 'java'; - const [arg] = args; - arg.splice( 0, 0, '-jar', quote( path.join( binaryDir, binaryName ) ) ); - let exitCode = 0; - try { - console.log( 'arg', arg ); - console.log( `ASTRAL?` ); - exitCode = await runProcess( id, event, '', javaBin, arg ); - if ( exitCode !== 0 ) { - if ( exitCode === 'SIGTERM' ) { - // Cancelled - return; - } - throw new Error( `Error trying to run ASTRAL, exited with code '${exitCode}'.` ); - } - } - catch ( err ) { - console.error( 'ASTRAL run error:', err ); - send( event, ipc.RUN_ERROR, { id, error: err } ); - return; - } - send( event, ipc.ASTRAL_SUCCESS, { - id, - exitCode, - } ); -} ); -ipcMain.handle( ipc.ALIGNMENT_MODEL_SELECTION_REQUEST, async ( event, payload ) => { - const { id, filePath, outputDir, dataType, numThreads, binaryName } = payload; - const token = beginRun( id ); - const reportFailure = ( error ) => { - if ( !stillRunning( id, token ) ) { - return; - } - send( event, ipc.ALIGNMENT_MODEL_SELECTION_FAILURE, { id, error } ); - }; - const { name } = parsePath( filePath ); - const outputPath = path.join( outputDir, `RAxML_GUI_ModelTest_${name}` ); - try { - // Remove binary checkpoint as that may be invalid - await fs.unlink( `${outputPath}.ckp` ); - } - catch ( err ) { } - const args = []; - if ( dataType === 'nucleotide' ) { - args.push( '-d', 'nt' ); - } - else if ( dataType === 'protein' ) { - args.push( '-d', 'aa' ); - } - // alignment file - args.push( '-i', quote( filePath ) ); - // output path - args.push( '-o', quote( outputPath ) ); - // modeltest throws errors if the output file already exists - args.push( '--force' ); - // Number of processors - args.push( '-p', numThreads ); - console.log( `Alignment '${id}': Run modeltest with args ${args}...` ); - const stdOuts = []; - const onStdOut = ( content ) => { - stdOuts.push( content ); - }; - let exitCode = 0; - try { - if ( !stillRunning( id, token ) ) { - return; - } - console.log( `Run modeltest-ng with args:`, args ); - exitCode = await runProcess( id, event, binaryDir, binaryName, args, { - onStdOut, - } ); - if ( !stillRunning( id, token ) || exitCode === 'SIGTERM' ) { - return; - } - if ( exitCode !== 0 ) { - throw new Error( `Error trying to run modeltest-ng, exited with code '${exitCode}'.` ); - } - } - catch ( err ) { - console.error( 'Modeltest run error:', err ); - reportFailure( err ); - return; - } - // Parse stdout to get the best models - console.log( 'Parse output from modeltest-ng...' ); - const commands = stdOuts.join( '' ).split( '\n' ); - try { - // Each '> [program]' is written three times, for BIC, AIC and AICc respectively. Use AICc. - const cmdRaxml = commands.filter( ( cmd ) => cmd.startsWith( ' > raxmlHPC-SSE3' ) )[2]; - const cmdRaxmlNG = commands.filter( ( cmd ) => cmd.startsWith( ' > raxml-ng' ) )[2]; - const modelRaxml = /-m (\S+)/.exec( cmdRaxml )[1]; - const extraFlag = /--(\S+)/.exec( cmdRaxml )?.[0]; - const modelRaxmlNG = /--model (\S+)/.exec( cmdRaxmlNG )[1]; - console.log( `-> raxml: ${modelRaxml}, extraFlag: ${extraFlag}, raxml-ng: ${modelRaxmlNG}` ); - send( event, ipc.ALIGNMENT_MODEL_SELECTION_SUCCESS, { - id, - result: { - raxml: modelRaxml, - extraFlag, - raxmlNG: modelRaxmlNG, - }, - } ); - } - catch ( err ) { - console.error( `Couldn't parse best models from modeltest-ng output:`, err ); - console.log( 'output:', commands ); - const error = new Error( `Couldn't parse best models from modeltest-ng output. Check alignment log.` ); - error.name = 'Modeltest error'; - reportFailure( error ); - } -} ); -ipcMain.handle( ipc.ALIGNMENT_MODEL_SELECTION_CANCEL, ( _event, id ) => { - console.log( `Cancel modeltest process ${id}...` ); - cancelRun( id ); -} ); -ipcMain.handle( ipc.TREE_SELECT, ( _event, _runId, type ) => { - return selectTree( ( options ) => dialog.showOpenDialog( options ), type ); -} ); diff --git a/src/main/api.ts b/src/main/api.ts new file mode 100644 index 00000000..b77dc46e --- /dev/null +++ b/src/main/api.ts @@ -0,0 +1,196 @@ +import { app, ipcMain, shell, dialog, clipboard } from 'electron'; +import type { IpcMainEvent, IpcMainInvokeEvent, OpenDialogOptions } from 'electron'; +import os from 'os'; +import path from 'path'; +import util from 'util'; +import _fs from 'fs'; +import childProcess from 'child_process'; +import type { ExecOptions } from 'child_process'; +import { serializeError } from 'serialize-error'; +import * as Sentry from '@sentry/electron/main'; +import * as ipc from '../constants/ipc'; +import io from '../common/io'; +import { parseAlignment } from './parseAlignment'; +import { selectAlignment } from './selectAlignment'; +import { selectAstralFile } from './selectAstralFile'; +import { selectOutputDir } from './selectOutputDir'; +import { checkOutput } from './checkOutput'; +import { debugInfo } from './debugInfo'; +import { selectPartitionFile } from './selectPartitionFile'; +import { selectTree } from './selectTree'; +import { appStore } from './appStore'; +import { is, quote } from '../common/utils'; +import { activeWindow } from './utils/utils'; +import { cancelRun } from './cancelRun'; +import { + binaryDir, + getStaticDir, +} from './processHelpers'; +import { startRun } from './startRun'; +import { runModelSelection } from './modelSelection'; +import { runAstral } from './astral'; + +if ( !is.development ) { + Sentry.init( { + dsn: 'https://d92efa46c2ba43f38250b202c791a2c2@o117148.ingest.sentry.io/6517975', + maxValueLength: 2000, + } ); +} +const fs = _fs.promises; +function handleError( title: string, error: unknown ): void { + // send error to renderer + console.log( `${title}:`, error ); + const win = activeWindow(); + if ( win ) { + win.webContents.send( ipc.UNHANDLED_ERROR, { + title, + error: serializeError( error ), + } ); + } +} +process.on( 'uncaughtException', ( error: Error ) => { + handleError( 'Unhandled Error', error ); +} ); +process.on( 'unhandledRejection', ( error: unknown ) => { + handleError( 'Unhandled Promise Rejection', error ); +} ); +const exec = util.promisify( childProcess.exec ); +ipcMain.on( ipc.HOST, ( event: IpcMainEvent ) => { + const cpu = os.cpus()[0]; + event.returnValue = { + windows: process.platform === 'win32', + release: os.release(), + arch: os.arch(), + cpuModel: cpu.model, + }; +} ); +ipcMain.handle( ipc.GET_VERSION, (): string => app.getVersion() ); +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 ); +} ); +ipcMain.handle( ipc.COPY_TEXT, async ( _event: IpcMainInvokeEvent, text: string ): Promise => { + await clipboard.writeText( text ); +} ); +ipcMain.handle( ipc.READ_FILE, ( _event: IpcMainInvokeEvent, filePath: string ): Promise => { + return fs.readFile( filePath, 'utf-8' ); +} ); +ipcMain.handle( ipc.WRITE_FILE, async ( _event: IpcMainInvokeEvent, filePath: string, text: string ): Promise => { + await fs.writeFile( filePath, text ); +} ); +ipcMain.handle( ipc.RELOAD, ( event: IpcMainInvokeEvent ): void => { + event.sender.reload(); +} ); +ipcMain.handle( ipc.DEBUG_INFO, (): string => { + return debugInfo( { + name: app.getName(), + version: app.getVersion(), + electron: process.versions.electron, + platform: process.platform, + release: os.release(), + locale: app.getLocale(), + } ); +} ); +ipcMain.handle( ipc.OPEN_EXTERNAL, ( _event: IpcMainInvokeEvent, url: string ): Promise => { + return shell.openExternal( url ); +} ); +ipcMain.handle( ipc.OUTPUT_DIR_SELECT, ( _event: IpcMainInvokeEvent, _runId: number ) => { + return selectOutputDir( ( options: OpenDialogOptions ) => dialog.showOpenDialog( options ) ); +} ); +ipcMain.handle( ipc.PARTITION_FILE_SELECT, ( _event: IpcMainInvokeEvent, _runId: number ) => { + return selectPartitionFile( ( options: OpenDialogOptions ) => dialog.showOpenDialog( options ) ); +} ); +ipcMain.handle( ipc.OPEN_PATH, ( _event: IpcMainInvokeEvent, fullPath: string ): Promise => { + return shell.openPath( fullPath ); +} ); +// Open a file in it's folder with native file explorer +ipcMain.handle( ipc.FILE_SHOW_IN_FOLDER, ( _event: IpcMainInvokeEvent, fullPath: string ): void => { + console.debug( ipc.FILE_SHOW_IN_FOLDER, fullPath ); + shell.showItemInFolder( fullPath ); +} ); +// Check if raxml output files already exist with current name +ipcMain.handle( ipc.OUTPUT_CHECK, ( _event: IpcMainInvokeEvent, { outputDir, outputName }: { outputDir: string; outputName: string } ) => { + return checkOutput( { outputDir, outputName } ); +} ); +ipcMain.handle( ipc.RUN_START, startRun ); +ipcMain.handle( ipc.RUN_CANCEL, ( _event: IpcMainInvokeEvent, id: number ): void => { + console.log( `Cancel run process ${id}...` ); + cancelRun( id ); +} ); +// Function to get an alignment format with readal +async function readalGetFormat( alignmentPath: string ): Promise { + const readalPath = path.resolve( binaryDir, 'readal' ); + const childCmd = `${quote( readalPath )} -in ${quote( alignmentPath )} -type -format`; + const { stdout, stderr } = await exec( childCmd, { + ...( is.windows + ? { shell: true } + : {} ), + } as unknown as ExecOptions ); + console.log( 'Readal stderr', stderr ); + const replaced = String( stdout ).replace( alignmentPath, '' ); + const formats = ['clustal', 'fasta', 'nbrf', 'nexus', 'mega', 'phylip']; + for ( let i = 0; i < formats.length; i++ ) { + const f = formats[i]; + if ( replaced.includes( f ) ) { + return f; + } + } + return; +} +// Function to convert an alignment to fasta with readal +async function convertAlignment( alignmentPath: string ): Promise { + const readalPath = path.resolve( binaryDir, 'readal' ); + const newPath = alignmentPath.replace( path.extname( alignmentPath ), '.fas' ); + const childCmd = `${quote( readalPath )} -in ${quote( alignmentPath )} -out ${quote( newPath )} -fasta`; + const { stdout, stderr } = await exec( childCmd, { + ...( is.windows + ? { shell: true } + : {} ), + } as unknown as ExecOptions ); + console.log( stdout, stderr ); + return newPath; +} +ipcMain.handle( ipc.ALIGNMENT_PARSE, ( _event: IpcMainInvokeEvent, id: string, filePath: string ) => { + return parseAlignment( id, filePath, { + readFormat: readalGetFormat as ( filePath: string ) => Promise, + convert: convertAlignment, + parse: io.parseAlignment, + write: io.writeAlignment, + } ); +} ); +// Open a dialog to select alignments +ipcMain.handle( ipc.ALIGNMENT_SELECT, ( _event: IpcMainInvokeEvent, _runId: number ) => { + return selectAlignment( ( options: OpenDialogOptions ) => dialog.showOpenDialog( options ) ); +} ); +ipcMain.handle( ipc.ASTRAL_FILE_SELECT, ( _event: IpcMainInvokeEvent, _runId: number ) => { + return selectAstralFile( ( options: OpenDialogOptions ) => dialog.showOpenDialog( options ) ); +} ); +ipcMain.handle( ipc.EXAMPLE_FILES, async (): Promise<{ + fasta: string[]; + phylip: string[]; + dir: string; + outdir: string; +}> => { + const staticDir = getStaticDir(); + const dir = path.join( staticDir, 'example-files' ); + const outdir = path.join( staticDir, 'test-results' ); + // Create outdir if not exists + await fs.mkdir( outdir, { recursive: true } ); + const fastaFiles = await fs.readdir( path.join( dir, 'fasta' ) ); + const phylipFiles = await fs.readdir( path.join( dir, 'phylip' ) ); + return { + fasta: fastaFiles, + phylip: phylipFiles, + dir, + outdir, + }; +} ); +ipcMain.handle( ipc.ASTRAL_REQUEST, runAstral ); +ipcMain.handle( ipc.ALIGNMENT_MODEL_SELECTION_REQUEST, runModelSelection ); +ipcMain.handle( ipc.ALIGNMENT_MODEL_SELECTION_CANCEL, ( _event: IpcMainInvokeEvent, id: string ): void => { + console.log( `Cancel modeltest process ${id}...` ); + cancelRun( id ); +} ); +ipcMain.handle( ipc.TREE_SELECT, ( _event: IpcMainInvokeEvent, _runId: number, type: string ) => { + return selectTree( ( options: OpenDialogOptions ) => dialog.showOpenDialog( options ), type ); +} ); diff --git a/src/main/appStore.js b/src/main/appStore.js deleted file mode 100644 index cac04d87..00000000 --- a/src/main/appStore.js +++ /dev/null @@ -1,3 +0,0 @@ -import Store from 'electron-store'; - -export const appStore = new Store(); diff --git a/src/main/appStore.ts b/src/main/appStore.ts new file mode 100644 index 00000000..7e032e48 --- /dev/null +++ b/src/main/appStore.ts @@ -0,0 +1,7 @@ +import Store from 'electron-store'; + +interface AppStoreSchema { + darkMode?: boolean; +} + +export const appStore: Store = new Store(); diff --git a/src/main/astral.ts b/src/main/astral.ts new file mode 100644 index 00000000..d5766310 --- /dev/null +++ b/src/main/astral.ts @@ -0,0 +1,55 @@ +import path from 'path'; +import type { IpcMainEvent } from 'electron'; +import * as ipc from '../constants/ipc'; +import { quote } from '../common/utils'; +import { + binaryDir, + runProcess, + send, +} from './processHelpers'; + +type RunId = number; + +type ProcessExit = + | 'SIGTERM' + | number + | NodeJS.Signals + | null; + +interface AstralPayload { + id: RunId; + binaryName: string; + args: string[][]; +} + +export async function runAstral( + event: IpcMainEvent, + payload: AstralPayload, +): Promise { + const { id, binaryName, args } = payload; + const javaBin = 'java'; + const [arg] = args; + arg.splice( 0, 0, '-jar', quote( path.join( binaryDir, binaryName ) ) ); + let exitCode: ProcessExit = 0; + try { + console.log( 'arg', arg ); + console.log( `ASTRAL?` ); + exitCode = await runProcess( id, event, '', javaBin, arg ); + if ( exitCode !== 0 ) { + if ( exitCode === 'SIGTERM' ) { + // Cancelled + return; + } + throw new Error( `Error trying to run ASTRAL, exited with code '${exitCode}'.` ); + } + } + catch ( err: unknown ) { + console.error( 'ASTRAL run error:', err ); + send( event, ipc.RUN_ERROR, { id, error: err } ); + return; + } + send( event, ipc.ASTRAL_SUCCESS, { + id, + exitCode, + } ); +} diff --git a/src/main/cancelRun.js b/src/main/cancelRun.js deleted file mode 100644 index 102db0fd..00000000 --- a/src/main/cancelRun.js +++ /dev/null @@ -1,58 +0,0 @@ -const processes = Object.create( null ); -const generation = Object.create( null ); - -export function beginRun( id ) { - const key = String( id ); - const next = ( generation[key] || 0 ) + 1; - generation[key] = next; - return next; -} - -export function stillRunning( id, token ) { - return generation[String( id )] === token; -} - -export function trackRun( id, proc ) { - processes[String( id )] = proc; -} - -export function stopRun( id ) { - const proc = processes[String( id )]; - if ( !proc ) { - return; - } - proc.cancelled = true; - delete processes[String( id )]; - proc.kill(); - console.log( `Killed RAxML process ${id}` ); -} - -export function cancelRun( id ) { - const key = String( id ); - generation[key] = ( generation[key] || 0 ) + 1; - stopRun( id ); -} - -export function forgetRun( id, proc ) { - const key = String( id ); - if ( processes[key] === proc ) { - delete processes[key]; - } -} - -export function runResult( proc, message, code, signal ) { - if ( proc.cancelled ) { - return 'SIGTERM'; - } - if ( message === 'error' ) { - return code; - } - if ( !code ) { - return signal || code; - } - return new Error( `Exited with code ${signal || code}. Check console output for more information.` ); -} - -export function finishedRun( exitCode ) { - return exitCode !== 'SIGTERM'; -} diff --git a/src/main/cancelRun.test.js b/src/main/cancelRun.test.js index 140f0f7f..6286501a 100644 --- a/src/main/cancelRun.test.js +++ b/src/main/cancelRun.test.js @@ -16,9 +16,9 @@ import { it( 'cancelRun stops that run and sends no terminal event', async () => { const proc = spawn( process.execPath, ['-e', 'setTimeout(() => {}, 30000)'] ); - trackRun( 'run-7', proc ); + trackRun( 7, proc ); try { - cancelRun( 'run-7' ); + cancelRun( 7 ); await once( proc, 'exit' ); const exitCode = runResult( proc, 'exit', 1, null ); expect( exitCode ).toBe( 'SIGTERM' ); @@ -33,15 +33,15 @@ it( 'cancelRun stops that run and sends no terminal event', async () => { it( 'a late exit from a cancelled run leaves the next run tracked', () => { const oldProc = { kill() { this.killed = true; } }; const nextProc = { kill() { this.killed = true; } }; - const token = beginRun( 'run-8' ); - trackRun( 'run-8', oldProc ); - cancelRun( 'run-8' ); - expect( stillRunning( 'run-8', token ) ).toBe( false ); - const next = beginRun( 'run-8' ); - trackRun( 'run-8', nextProc ); - forgetRun( 'run-8', oldProc ); - expect( stillRunning( 'run-8', next ) ).toBe( true ); - cancelRun( 'run-8' ); + const token = beginRun( 8 ); + trackRun( 8, oldProc ); + cancelRun( 8 ); + expect( stillRunning( 8, token ) ).toBe( false ); + const next = beginRun( 8 ); + trackRun( 8, nextProc ); + forgetRun( 8, oldProc ); + expect( stillRunning( 8, next ) ).toBe( true ); + cancelRun( 8 ); expect( nextProc.killed ).toBe( true ); } ); @@ -51,10 +51,7 @@ it( 'a finished run still reports its result', () => { } ); it( 'the model selection handler returns before a terminal event once cancelled', () => { - const source = fs.readFileSync( path.join( __dirname, 'api.js' ), 'utf8' ); - const start = source.indexOf( 'ipcMain.handle( ipc.ALIGNMENT_MODEL_SELECTION_REQUEST' ); - const end = source.indexOf( 'ipcMain.handle( ipc.ALIGNMENT_MODEL_SELECTION_CANCEL' ); - const handler = source.slice( start, end ); + const handler = fs.readFileSync( path.join( __dirname, 'modelSelection.ts' ), 'utf8' ); const started = handler.indexOf( 'await runProcess' ); const success = handler.lastIndexOf( 'ipc.ALIGNMENT_MODEL_SELECTION_SUCCESS' ); const failure = handler.indexOf( 'ipc.ALIGNMENT_MODEL_SELECTION_FAILURE' ); @@ -68,16 +65,14 @@ it( 'the model selection handler returns before a terminal event once cancelled' } ); it( 'the run handler returns before a terminal event once the run is no longer current', () => { - const source = fs.readFileSync( path.join( __dirname, 'api.js' ), 'utf8' ); - const start = source.indexOf( 'ipcMain.handle( ipc.RUN_START' ); - const end = source.indexOf( 'ipcMain.handle( ipc.RUN_CANCEL' ); - const handler = source.slice( start, end ); + const handler = fs.readFileSync( path.join( __dirname, 'startRun.ts' ), 'utf8' ); + const helpers = fs.readFileSync( path.join( __dirname, 'processHelpers.ts' ), 'utf8' ); const finished = handler.lastIndexOf( 'ipc.RUN_FINISHED' ); const tail = handler.slice( handler.lastIndexOf( 'await ', finished ), finished ); expect( tail ).toContain( '!stillRunning' ); expect( handler ).toContain( 'reportError( error )' ); expect( handler ).toContain( 'reportError( err )' ); - expect( source ).toContain( 'forgetRun( id, proc )' ); + expect( helpers ).toContain( 'forgetRun( id, proc )' ); } ); it( 'a failed run still reports the exit error', () => { diff --git a/src/main/cancelRun.ts b/src/main/cancelRun.ts new file mode 100644 index 00000000..04d82c6f --- /dev/null +++ b/src/main/cancelRun.ts @@ -0,0 +1,78 @@ +/** Run number, or alignment composite `${run.id}_${path}`. */ +type TrackedId = string | number; + +interface TrackedProcess { + cancelled?: boolean; + kill: () => void; +} + +type RunResult = + | 'SIGTERM' + | number + | NodeJS.Signals + | null + | Error; + +const processes: Record = Object.create( null ) as Record; +const generation: Record = Object.create( null ) as Record; + +export function beginRun( id: TrackedId ): number { + const key = String( id ); + const next = ( generation[key] || 0 ) + 1; + generation[key] = next; + return next; +} + +export function stillRunning( id: TrackedId, token: number ): boolean { + return generation[String( id )] === token; +} + +export function trackRun( id: TrackedId, proc: TrackedProcess ): void { + processes[String( id )] = proc; +} + +export function stopRun( id: TrackedId ): void { + const proc = processes[String( id )]; + if ( !proc ) { + return; + } + proc.cancelled = true; + delete processes[String( id )]; + proc.kill(); + console.log( `Killed RAxML process ${id}` ); +} + +export function cancelRun( id: TrackedId ): void { + const key = String( id ); + generation[key] = ( generation[key] || 0 ) + 1; + stopRun( id ); +} + +export function forgetRun( id: TrackedId, proc: TrackedProcess ): void { + const key = String( id ); + if ( processes[key] === proc ) { + delete processes[key]; + } +} + +export function runResult( + proc: TrackedProcess, + message: string, + code: number | null, + signal: NodeJS.Signals | null, +): RunResult { + if ( proc.cancelled ) { + return 'SIGTERM'; + } + if ( message === 'error' ) { + return code; + } + if ( !code ) { + return signal || code; + } + return new Error( `Exited with code ${signal || code}. Check console output for more information.` ); +} + +export function finishedRun( exitCode: RunResult ): boolean { + return exitCode !== 'SIGTERM'; +} diff --git a/src/main/checkOutput.js b/src/main/checkOutput.ts similarity index 73% rename from src/main/checkOutput.js rename to src/main/checkOutput.ts index 88113af3..e8f1d8c3 100644 --- a/src/main/checkOutput.js +++ b/src/main/checkOutput.ts @@ -1,8 +1,26 @@ import fs from 'fs'; import { serializeError } from 'serialize-error'; +import type { ErrorObject } from 'serialize-error'; import * as ipc from '../constants/ipc'; -export async function checkOutput( { outputDir, outputName } ) { +interface CheckOutputArgs { + outputDir: string; + outputName: string; +} + +interface CheckOutputResult { + outputDir: string; + outputName: string; + ok: boolean; + notice: string; + outputNameUnused: string; + resultFilenames: string[]; + error?: ErrorObject; +} + +export async function checkOutput( + { outputDir, outputName }: CheckOutputArgs, +): Promise { const outputFilename = `${outputName}.tre`; console.log( 'Check unused filename:', outputFilename ); if ( !outputDir ) { @@ -18,7 +36,7 @@ export async function checkOutput( { outputDir, outputName } ) { try { const filenames = await fs.promises.readdir( outputDir ); let outputNameUnused = outputName; - const filterResultFilenames = ( filename ) => filename.startsWith( `${outputNameUnused}.raxml.` ) || + const filterResultFilenames = ( filename: string ): boolean => filename.startsWith( `${outputNameUnused}.raxml.` ) || filename.endsWith( outputNameUnused ) || filename.endsWith( `.${outputNameUnused}.txt` ) || filename.endsWith( `${outputNameUnused}.tre` ); @@ -46,13 +64,13 @@ export async function checkOutput( { outputDir, outputName } ) { outputNameUnused, resultFilenames, }; - } catch ( error ) { + } catch ( error: unknown ) { console.log( ipc.OUTPUT_CHECK, 'error:', error ); return { outputDir, outputName, ok: false, - notice: error.message, + notice: ( error as Error ).message, outputNameUnused: outputName, error: serializeError( error ), resultFilenames: [], diff --git a/src/main/debugInfo.js b/src/main/debugInfo.js deleted file mode 100644 index a6ba603a..00000000 --- a/src/main/debugInfo.js +++ /dev/null @@ -1,6 +0,0 @@ -export function debugInfo( { name, version, electron, platform, release, locale } ) { - return `${name} ${version} -Electron ${electron} -${platform} ${release} -Locale: ${locale}`; -} diff --git a/src/main/debugInfo.ts b/src/main/debugInfo.ts new file mode 100644 index 00000000..e0854807 --- /dev/null +++ b/src/main/debugInfo.ts @@ -0,0 +1,22 @@ +interface DebugInfoInput { + name: string; + version: string; + electron: string; + platform: string; + release: string; + locale: string; +} + +export function debugInfo( { + name, + version, + electron, + platform, + release, + locale, +}: DebugInfoInput ): string { + return `${name} ${version} +Electron ${electron} +${platform} ${release} +Locale: ${locale}`; +} diff --git a/src/main/getActiveState.js b/src/main/getActiveState.ts similarity index 71% rename from src/main/getActiveState.js rename to src/main/getActiveState.ts index 2a30ad97..b646a881 100644 --- a/src/main/getActiveState.js +++ b/src/main/getActiveState.ts @@ -1,17 +1,23 @@ import { ipcMain } from 'electron'; +import type { IpcMainEvent } from 'electron'; import { randomUUID } from 'node:crypto'; import { STATE_REPORT, STATE_REPORT_RESULT } from '../constants/ipc'; import { activeWindow } from './utils/utils'; -export function getActiveState() { +interface StateReportPayload { + id: string; + report: unknown; +} + +export function getActiveState(): Promise { const win = activeWindow(); if ( !win ) { return Promise.resolve( undefined ); } const id = randomUUID(); return new Promise( ( resolve ) => { - const onResult = ( _event, payload ) => { + const onResult = ( _event: IpcMainEvent, payload: StateReportPayload ) => { if ( !payload || payload.id !== id ) { return; } diff --git a/src/main/index.js b/src/main/index.ts similarity index 95% rename from src/main/index.js rename to src/main/index.ts index eddc609c..ea48d439 100644 --- a/src/main/index.js +++ b/src/main/index.ts @@ -1,4 +1,5 @@ import electron, { BrowserWindow } from 'electron'; +import type { BrowserWindowConstructorOptions } from 'electron'; import path from 'path'; import url from 'url'; import log from 'electron-log'; @@ -32,20 +33,20 @@ const isDevMode = is.development && process.argv.indexOf( '--noDevServer' ) === 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 = null; +let mainWindow: BrowserWindow | null = null; listenForUpdates( autoUpdater, dialog ); /** * Add event listeners... */ -function initialize() { +function initialize(): void { // Make this a single instance app const shouldQuit = makeSingleInstance(); if ( shouldQuit ) return app.quit(); - function createMainWindow() { + function createMainWindow(): void { const preloadPath = path.join( __dirname, '../preload/index.js' ); // Window options for the main window - const mainWindowOptions = { + const mainWindowOptions: BrowserWindowConstructorOptions = { width: 1280, minWidth: 960, height: 790, @@ -140,7 +141,7 @@ function initialize() { // // Returns true if the current version of the app should quit instead of // launching. -function makeSingleInstance() { +function makeSingleInstance(): boolean | void { const processWithMas = process; if ( processWithMas.mas ) return false; diff --git a/src/main/menu/index.js b/src/main/menu/index.ts similarity index 77% rename from src/main/menu/index.js rename to src/main/menu/index.ts index e72e030c..015adbfc 100644 --- a/src/main/menu/index.js +++ b/src/main/menu/index.ts @@ -1,9 +1,11 @@ import { app, Menu } from 'electron'; +import type { BrowserWindow, MenuItemConstructorOptions } from 'electron'; import subMenuFile from './subMenuFile'; import subMenuAnalysis from './subMenuAnalysis'; import subMenuDeveloper from './subMenuDeveloper'; import saveScreenshot from '../utils/saveScreenshot'; -const windowMenuSection = { + +const windowMenuSection: MenuItemConstructorOptions = { role: 'window', submenu: [ { role: 'minimize' }, @@ -11,18 +13,20 @@ const windowMenuSection = { { label: 'Save screenshot', accelerator: 'CmdOrCtrl+S', - click() { + click(): void { saveScreenshot(); }, }, ], }; -const baseMenuTemplate = [ + +const baseMenuTemplate: MenuItemConstructorOptions[] = [ subMenuFile, subMenuAnalysis, windowMenuSection, ]; -const darwinAppMenu = { + +const darwinAppMenu: MenuItemConstructorOptions = { label: app.name, submenu: [ { role: 'about' }, @@ -36,12 +40,16 @@ const darwinAppMenu = { { role: 'quit' }, ], }; + export default class MenuBuilder { - constructor( mainWindow ) { + mainWindow: BrowserWindow; + + constructor( mainWindow: BrowserWindow ) { this.mainWindow = mainWindow; } - buildMenu() { - const menuTemplate = [...baseMenuTemplate]; + + buildMenu(): Menu { + const menuTemplate: MenuItemConstructorOptions[] = [...baseMenuTemplate]; if ( process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true' ) { menuTemplate.push( subMenuDeveloper ); @@ -54,7 +62,8 @@ export default class MenuBuilder { Menu.setApplicationMenu( menu ); return menu; } - setupDevelopmentEnvironment() { + + setupDevelopmentEnvironment(): void { this.mainWindow.webContents.openDevTools(); this.mainWindow.webContents.on( 'context-menu', ( _e, props ) => { const { x, y } = props; diff --git a/src/main/menu/subMenuAnalysis.js b/src/main/menu/subMenuAnalysis.ts similarity index 76% rename from src/main/menu/subMenuAnalysis.js rename to src/main/menu/subMenuAnalysis.ts index bc27a29e..cf927b62 100644 --- a/src/main/menu/subMenuAnalysis.js +++ b/src/main/menu/subMenuAnalysis.ts @@ -1,13 +1,16 @@ +import type { MenuItemConstructorOptions } from 'electron'; import * as ipc from '../../constants/ipc'; import { activeWindow } from '../utils/utils'; -const sendToFocusedWindow = ( channel ) => { + +const sendToFocusedWindow = ( channel: string ): void => { const win = activeWindow(); if ( !win ) { return; } win.webContents.send( channel ); }; -const subMenuAnalysis = { + +const subMenuAnalysis: MenuItemConstructorOptions = { label: 'Analysis', submenu: [ { @@ -17,7 +20,7 @@ const subMenuAnalysis = { label: 'Use backbone constraint', type: 'checkbox', checked: false, - click() { + click(): void { sendToFocusedWindow( ipc.TOGGLE_BACKBONE_CONSTRAINT ); }, }, @@ -25,7 +28,7 @@ const subMenuAnalysis = { label: 'Use multifurcating constraint', type: 'checkbox', checked: false, - click() { + click(): void { sendToFocusedWindow( ipc.TOGGLE_MULTIFURCATING_CONSTRAINT ); }, }, @@ -33,4 +36,5 @@ const subMenuAnalysis = { }, ], }; + export default subMenuAnalysis; diff --git a/src/main/menu/subMenuDeveloper.js b/src/main/menu/subMenuDeveloper.ts similarity index 78% rename from src/main/menu/subMenuDeveloper.js rename to src/main/menu/subMenuDeveloper.ts index 0877f133..80805043 100644 --- a/src/main/menu/subMenuDeveloper.js +++ b/src/main/menu/subMenuDeveloper.ts @@ -1,10 +1,12 @@ -const subMenuDeveloper = { +import type { MenuItemConstructorOptions } from 'electron'; + +const subMenuDeveloper: MenuItemConstructorOptions = { // If you see this menu in production sth is wrong label: 'DEVELOPER!!!', submenu: [ { label: 'Force Error', - click() { + click(): void { throw new Error( 'Testing Error' ); }, }, @@ -20,4 +22,5 @@ const subMenuDeveloper = { { role: 'togglefullscreen' }, ], }; + export default subMenuDeveloper; diff --git a/src/main/menu/subMenuFile.js b/src/main/menu/subMenuFile.ts similarity index 81% rename from src/main/menu/subMenuFile.js rename to src/main/menu/subMenuFile.ts index c04b6c4f..eb151602 100644 --- a/src/main/menu/subMenuFile.js +++ b/src/main/menu/subMenuFile.ts @@ -1,28 +1,31 @@ +import type { MenuItemConstructorOptions } from 'electron'; import * as ipc from '../../constants/ipc'; import { appStore } from '../appStore'; import { activeWindow } from '../utils/utils'; + // The page's store class is decorated. This build does not compile decorators. -const sendToFocusedWindow = ( channel ) => { +const sendToFocusedWindow = ( channel: string ): void => { const win = activeWindow(); if ( !win ) { return; } win.webContents.send( channel ); }; -const subMenuFile = { + +const subMenuFile: MenuItemConstructorOptions = { label: 'File', submenu: [ { label: 'New Tab', accelerator: 'CmdOrCtrl+T', - click() { + click(): void { sendToFocusedWindow( ipc.ADD_RUN ); }, }, { label: 'Close Tab', accelerator: 'CmdOrCtrl+W', - click() { + click(): void { sendToFocusedWindow( ipc.REMOVE_RUN ); }, }, @@ -33,7 +36,7 @@ const subMenuFile = { label: 'Light mode', type: 'radio', checked: !appStore.get( 'darkMode' ), - click() { + click(): void { appStore.set( 'darkMode', false ); sendToFocusedWindow( ipc.LIGHT_MODE ); }, @@ -42,7 +45,7 @@ const subMenuFile = { label: 'Dark mode', type: 'radio', checked: Boolean( appStore.get( 'darkMode' ) ), - click() { + click(): void { appStore.set( 'darkMode', true ); sendToFocusedWindow( ipc.DARK_MODE ); }, @@ -51,4 +54,5 @@ const subMenuFile = { }, ], }; + export default subMenuFile; diff --git a/src/main/modelSelection.ts b/src/main/modelSelection.ts new file mode 100644 index 00000000..ccbd0134 --- /dev/null +++ b/src/main/modelSelection.ts @@ -0,0 +1,121 @@ +import path from 'path'; +import _fs from 'fs'; +import parsePath from 'parse-filepath'; +import type { IpcMainEvent } from 'electron'; +import * as ipc from '../constants/ipc'; +import { quote } from '../common/utils'; +import { + beginRun, + stillRunning, +} from './cancelRun'; +import { + binaryDir, + runProcess, + send, +} from './processHelpers'; + +const fs = _fs.promises; + +type ProcessExit = + | 'SIGTERM' + | number + | NodeJS.Signals + | null; + +interface ModelSelectionPayload { + id: string; + filePath: string; + outputDir: string; + dataType: string; + numThreads: number; + binaryName: string; +} + +export async function runModelSelection( + event: IpcMainEvent, + payload: ModelSelectionPayload, +): Promise { + const { id, filePath, outputDir, dataType, numThreads, binaryName } = payload; + const token = beginRun( id ); + const reportFailure = ( error: unknown ): void => { + if ( !stillRunning( id, token ) ) { + return; + } + send( event, ipc.ALIGNMENT_MODEL_SELECTION_FAILURE, { id, error } ); + }; + const { name } = parsePath( filePath ); + const outputPath = path.join( outputDir, `RAxML_GUI_ModelTest_${name}` ); + try { + // Remove binary checkpoint as that may be invalid + await fs.unlink( `${outputPath}.ckp` ); + } + catch ( _err: unknown ) { } + const args = []; + if ( dataType === 'nucleotide' ) { + args.push( '-d', 'nt' ); + } + else if ( dataType === 'protein' ) { + args.push( '-d', 'aa' ); + } + // alignment file + args.push( '-i', quote( filePath ) ); + // output path + args.push( '-o', quote( outputPath ) ); + // modeltest throws errors if the output file already exists + args.push( '--force' ); + // Number of processors + args.push( '-p', numThreads ); + console.log( `Alignment '${id}': Run modeltest with args ${args}...` ); + const stdOuts: string[] = []; + const onStdOut = ( content: string ): void => { + stdOuts.push( content ); + }; + let exitCode: ProcessExit = 0; + try { + if ( !stillRunning( id, token ) ) { + return; + } + console.log( `Run modeltest-ng with args:`, args ); + exitCode = await runProcess( id, event, binaryDir, binaryName, args, { + onStdOut, + } ); + if ( !stillRunning( id, token ) || exitCode === 'SIGTERM' ) { + return; + } + if ( exitCode !== 0 ) { + throw new Error( `Error trying to run modeltest-ng, exited with code '${exitCode}'.` ); + } + } + catch ( err: unknown ) { + console.error( 'Modeltest run error:', err ); + reportFailure( err ); + return; + } + // Parse stdout to get the best models + console.log( 'Parse output from modeltest-ng...' ); + const commands = stdOuts.join( '' ).split( '\n' ); + try { + // Each '> [program]' is written three times, for BIC, AIC and AICc respectively. Use AICc. + const cmdRaxml = commands.filter( ( cmd ) => cmd.startsWith( ' > raxmlHPC-SSE3' ) )[2]; + const cmdRaxmlNG = commands.filter( ( cmd ) => cmd.startsWith( ' > raxml-ng' ) )[2]; + const modelRaxml = /-m (\S+)/.exec( cmdRaxml )[1]; + const extraFlag = /--(\S+)/.exec( cmdRaxml )?.[0]; + const modelRaxmlNG = /--model (\S+)/.exec( cmdRaxmlNG )[1]; + console.log( `-> raxml: ${modelRaxml}, extraFlag: ${extraFlag}, raxml-ng: ${modelRaxmlNG}` ); + send( event, ipc.ALIGNMENT_MODEL_SELECTION_SUCCESS, { + id, + result: { + raxml: modelRaxml, + extraFlag, + raxmlNG: modelRaxmlNG, + }, + } ); + } + catch ( err: unknown ) { + console.error( `Couldn't parse best models from modeltest-ng output:`, err ); + console.log( 'output:', commands ); + const error = new Error( `Couldn't parse best models from modeltest-ng output. Check alignment log.` ); + error.name = 'Modeltest error'; + reportFailure( error ); + } +} diff --git a/src/main/pageWindowPreferences.js b/src/main/pageWindowPreferences.js deleted file mode 100644 index 9f886cdd..00000000 --- a/src/main/pageWindowPreferences.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Web preferences for every shell window. Node stays out of the page. - * @param {{ preloadPath?: string }} [options] - */ -export function pageWindowPreferences( { preloadPath } = {} ) { - return { - backgroundThrottling: false, - nodeIntegration: false, - contextIsolation: true, - sandbox: true, - ...( preloadPath - ? { preload: preloadPath } - : {} ), - allowEval: false, - }; -} diff --git a/src/main/pageWindowPreferences.ts b/src/main/pageWindowPreferences.ts new file mode 100644 index 00000000..e723b278 --- /dev/null +++ b/src/main/pageWindowPreferences.ts @@ -0,0 +1,27 @@ +import type { WebPreferences } from 'electron'; + +interface PageWindowPreferencesOptions { + preloadPath?: string; +} + +type PageWindowPreferencesResult = WebPreferences & { + allowEval: false; +}; + +/** + * Web preferences for every shell window. Node stays out of the page. + */ +export function pageWindowPreferences( + { preloadPath }: PageWindowPreferencesOptions = {}, +): PageWindowPreferencesResult { + return { + backgroundThrottling: false, + nodeIntegration: false, + contextIsolation: true, + sandbox: true, + ...( preloadPath + ? { preload: preloadPath } + : {} ), + allowEval: false, + }; +} diff --git a/src/main/parseAlignment.js b/src/main/parseAlignment.ts similarity index 67% rename from src/main/parseAlignment.js rename to src/main/parseAlignment.ts index af932a48..4e98398f 100644 --- a/src/main/parseAlignment.js +++ b/src/main/parseAlignment.ts @@ -1,27 +1,59 @@ import path from 'path'; -export async function parseAlignment( _id, filePath, tools ) { +interface AlignmentSequence { + taxon: string; +} + +interface Alignment { + sequences: AlignmentSequence[]; +} + +interface AlignmentParseTools { + readFormat: ( filePath: string ) => Promise; + convert: ( filePath: string ) => Promise; + parse: ( filePath: string ) => Promise; + write: ( filePath: string, alignment: Alignment ) => Promise; +} + +interface AlignmentChange { + newFilePath: string; + format: string | undefined; + converted: boolean | undefined; + modified: boolean | undefined; + modificationMessages: string[]; +} + +interface AlignmentParseResult { + alignment: Alignment; + change: AlignmentChange | null; +} + +export async function parseAlignment( + _id: string, + filePath: string, + tools: AlignmentParseTools, +): Promise { console.log( 'Parse alignment', filePath ); const { readFormat, convert, parse, write } = tools; - let format; - let newFilePath; - let converted; - let modified; - const modificationMessages = []; + let format: string | undefined; + let newFilePath: string | undefined; + let converted: boolean | undefined; + let modified: boolean | undefined; + const modificationMessages: string[] = []; try { format = await readFormat( filePath ); if ( format !== 'fasta' && format !== 'phylip' ) { newFilePath = await convert( filePath ); converted = true; } - } catch ( error ) { + } catch ( error: unknown ) { console.log( 'error', error ); } const actualPath = newFilePath ? newFilePath : filePath; const alignment = await parse( actualPath ); - const taxons = new Map(); + const taxons = new Map(); let identicalCounter = 0; alignment.sequences.forEach( ( sequence, index ) => { if ( sequence.taxon.length > 256 ) { diff --git a/src/main/processHelpers.ts b/src/main/processHelpers.ts new file mode 100644 index 00000000..feea07f2 --- /dev/null +++ b/src/main/processHelpers.ts @@ -0,0 +1,143 @@ +import { app, Notification } from 'electron'; +import type { IpcMainEvent } from 'electron'; +import path from 'path'; +import childProcess from 'child_process'; +import type { ChildProcess } from 'child_process'; +import { serializeError } from 'serialize-error'; +import * as ipc from '../constants/ipc'; +import { is, platform } from '../common/utils'; +import { activeWindow } from './utils/utils'; +import { + forgetRun, + runResult, + stopRun, + trackRun, +} from './cancelRun'; + +/** Run number, or alignment composite `${run.id}_${path}`. */ +type TrackedId = string | number; + +type ProcessExit = + | 'SIGTERM' + | number + | NodeJS.Signals + | null; + +interface RunProcessHooks { + onStdOut?: ( content: string ) => void; + onStdErr?: ( content: string ) => void; +} + +export function getStaticDir(): string { + if ( process.env.RAXMLGUI_E2E === '1' ) { + return path.join( __dirname, '..', '..', 'static' ); + } + return __static; +} + +export const get_space_safe_binary_path = ( bin_path: string ): string => { + // For Windows users with spaces in user dir + return is.windows + ? `"${bin_path}"` + : bin_path; +}; + +const binParentDir = app.isPackaged + ? '' + : platform( { + macos: 'Mac', + windows: 'Windows', + linux: 'Linux', + } ); + +export const binaryDir: string = path.join( getStaticDir(), 'bin', binParentDir ); + +export function send( + event: IpcMainEvent, + channel: string, + data: { error?: unknown; [key: string]: unknown }, +): void { + if ( !data.error ) { + event.sender.send( channel, data ); + return; + } + event.sender.send( channel, Object.assign( {}, data, { error: serializeError( data.error ) } ) ); +} + +export function spawnProcess( + binaryDir: string, + binaryName: string, + args: string[], +): ChildProcess { + const binaryPath = path.join( binaryDir, binaryName ); + const proc = childProcess.execFile( get_space_safe_binary_path( binaryPath ), args, { + shell: is.windows, + } ); + return proc; +} + +export async function runProcess( + id: TrackedId, + event: IpcMainEvent, + binaryDir: string, + binaryName: string, + args: string[], + { onStdOut = ( _content: string ) => { }, onStdErr = ( _content: string ) => { } }: RunProcessHooks = {}, +): Promise { + return new Promise( ( resolve, reject ) => { + stopRun( id ); + try { + const proc = spawnProcess( binaryDir, binaryName, args ); + trackRun( id, proc ); + let exited = false; + proc.stdout.on( 'data', ( buffer: string | Buffer ) => { + const content = String( buffer ); + console.log( 'on stdout:', content ); + onStdOut( content ); + send( event, ipc.RUN_STDOUT, { id, content } ); + } ); + proc.stderr.on( 'data', ( buffer: string | Buffer ) => { + const content = String( buffer ); + console.error( 'on stderr:', content ); + onStdErr( content ); + send( event, ipc.RUN_STDERR, { id, content } ); + } ); + const onQuit = ( message: string ) => ( + code: number | Error | null, + signal: NodeJS.Signals | null, + ) => { + if ( exited ) { + return; + } + console.log( `Process finished with event '${message}' and error/code/signal:`, signal || code ); + exited = true; + forgetRun( id, proc ); + const result = runResult( proc, message, code as number | null, signal ); + const win = activeWindow(); + if ( !win || !win.isFocused() ) { + const notification = new Notification( { + title: app.name, + body: 'Calculation finished', + } ); + notification.show(); + } + if ( result === 'SIGTERM' ) { + resolve( result ); + return; + } + if ( message === 'error' || result instanceof Error ) { + reject( result ); // code is an error object on 'error' event + return; + } + resolve( result ); // Add code last to get through code 0 + }; + ( ['error', 'exit', 'close'] as const ).forEach( ( message ) => { + proc.on( message, onQuit( message ) as ( ...args: unknown[] ) => void ); + } ); + } + catch ( err: unknown ) { + console.log( 'Run catch error:', err ); + reject( err ); + } + } ); +} diff --git a/src/main/selectAlignment.js b/src/main/selectAlignment.ts similarity index 55% rename from src/main/selectAlignment.js rename to src/main/selectAlignment.ts index 8c27f67c..6f808914 100644 --- a/src/main/selectAlignment.js +++ b/src/main/selectAlignment.ts @@ -1,6 +1,18 @@ import path from 'path'; +import type { OpenDialogOptions, OpenDialogReturnValue } from 'electron'; -export async function selectAlignment( showOpenDialog ) { +type ShowOpenDialog = ( + options: OpenDialogOptions, +) => Promise; + +interface SelectedAlignment { + path: string; + name: string; +} + +export async function selectAlignment( + showOpenDialog: ShowOpenDialog, +): Promise { try { const result = await showOpenDialog( { title: 'Select an alignment', @@ -14,7 +26,7 @@ export async function selectAlignment( showOpenDialog ) { path: filePath, name: path.basename( filePath ), } ) ); - } catch ( err ) { + } catch ( err: unknown ) { console.debug( 'ALIGNMENT_SELECTED', err ); throw err; } diff --git a/src/main/selectAstralFile.js b/src/main/selectAstralFile.ts similarity index 55% rename from src/main/selectAstralFile.js rename to src/main/selectAstralFile.ts index b83df1be..6778de50 100644 --- a/src/main/selectAstralFile.js +++ b/src/main/selectAstralFile.ts @@ -1,6 +1,18 @@ import path from 'path'; +import type { OpenDialogOptions, OpenDialogReturnValue } from 'electron'; -export async function selectAstralFile( showOpenDialog ) { +type ShowOpenDialog = ( + options: OpenDialogOptions, +) => Promise; + +interface SelectedAstralFile { + path: string; + name: string; +} + +export async function selectAstralFile( + showOpenDialog: ShowOpenDialog, +): Promise { try { const result = await showOpenDialog( { title: 'Select an input trees file', @@ -15,7 +27,7 @@ export async function selectAstralFile( showOpenDialog ) { path: filePath, name: path.basename( filePath ), }; - } catch ( err ) { + } catch ( err: unknown ) { console.debug( 'ASTRAL_FILE_SELECTED', err ); throw err; } diff --git a/src/main/selectOutputDir.js b/src/main/selectOutputDir.ts similarity index 58% rename from src/main/selectOutputDir.js rename to src/main/selectOutputDir.ts index 96d95375..fe8580db 100644 --- a/src/main/selectOutputDir.js +++ b/src/main/selectOutputDir.ts @@ -1,6 +1,13 @@ +import type { OpenDialogOptions, OpenDialogReturnValue } from 'electron'; import * as ipc from '../constants/ipc'; -export async function selectOutputDir( showOpenDialog ) { +type ShowOpenDialog = ( + options: OpenDialogOptions, +) => Promise; + +export async function selectOutputDir( + showOpenDialog: ShowOpenDialog, +): Promise { try { const result = await showOpenDialog( { title: 'Select a directory for RAxML output', @@ -11,7 +18,7 @@ export async function selectOutputDir( showOpenDialog ) { return null; } return result.filePaths[0]; - } catch ( err ) { + } catch ( err: unknown ) { console.debug( ipc.OUTPUT_DIR_SELECT, err ); throw err; } diff --git a/src/main/selectPartitionFile.js b/src/main/selectPartitionFile.ts similarity index 56% rename from src/main/selectPartitionFile.js rename to src/main/selectPartitionFile.ts index 538f9b0d..bbd214b0 100644 --- a/src/main/selectPartitionFile.js +++ b/src/main/selectPartitionFile.ts @@ -1,6 +1,13 @@ +import type { OpenDialogOptions, OpenDialogReturnValue } from 'electron'; import * as ipc from '../constants/ipc'; -export async function selectPartitionFile( showOpenDialog ) { +type ShowOpenDialog = ( + options: OpenDialogOptions, +) => Promise; + +export async function selectPartitionFile( + showOpenDialog: ShowOpenDialog, +): Promise { try { const result = await showOpenDialog( { title: 'Select a partition file', @@ -11,7 +18,7 @@ export async function selectPartitionFile( showOpenDialog ) { return null; } return result.filePaths[0]; - } catch ( err ) { + } catch ( err: unknown ) { console.debug( ipc.PARTITION_FILE_SELECT, err ); throw err; } diff --git a/src/main/selectTree.js b/src/main/selectTree.ts similarity index 50% rename from src/main/selectTree.js rename to src/main/selectTree.ts index a685f088..36e70da7 100644 --- a/src/main/selectTree.js +++ b/src/main/selectTree.ts @@ -1,6 +1,19 @@ +import type { OpenDialogOptions, OpenDialogReturnValue } from 'electron'; import * as ipc from '../constants/ipc'; -export async function selectTree( showOpenDialog, type ) { +type ShowOpenDialog = ( + options: OpenDialogOptions, +) => Promise; + +interface SelectedTree { + type: string; + filePath: string; +} + +export async function selectTree( + showOpenDialog: ShowOpenDialog, + type: string, +): Promise { try { const result = await showOpenDialog( { title: 'Select a tree file', @@ -11,7 +24,7 @@ export async function selectTree( showOpenDialog, type ) { return null; } return { type, filePath: result.filePaths[0] }; - } catch ( err ) { + } catch ( err: unknown ) { console.debug( ipc.TREE_SELECT, err ); throw err; } diff --git a/src/main/startRun.ts b/src/main/startRun.ts new file mode 100644 index 00000000..d4367f02 --- /dev/null +++ b/src/main/startRun.ts @@ -0,0 +1,224 @@ +import path from 'path'; +import util from 'util'; +import _fs from 'fs'; +import childProcess from 'child_process'; +import type { ExecOptions } from 'child_process'; +import type { IpcMainEvent } from 'electron'; +import * as Sentry from '@sentry/electron/main'; +import * as ipc from '../constants/ipc'; +import { is } from '../common/utils'; +import UserFixError from '../common/errors'; +import { + beginRun, + finishedRun, + stillRunning, + stopRun, +} from './cancelRun'; +import { + binaryDir, + get_space_safe_binary_path, + runProcess, + send, +} from './processHelpers'; + +const fs = _fs.promises; +const exec = util.promisify( childProcess.exec ); +const execFile = util.promisify( childProcess.execFile ); + +type RunId = number; + +type ProcessExit = + | 'SIGTERM' + | number + | NodeJS.Signals + | null; + +interface StartRunPayload { + id: RunId; + args: string[][]; + binaryName: string; + outputDir: string; + outputFilename: string; + outputName: string; + combinedOutput: boolean; + usesRaxmlNg: boolean; + usesModeltestNg: boolean; + inputPath: string; +} + +async function combineOutput( outputDir: string, outputFilename: string ): Promise { + // Use type command on windows, cat on Mac or Linux + const command = is.windows + ? 'type' + : 'cat'; + const childCmd = `${command} RAxML_result.${outputFilename}* > combined_results.${outputFilename}`; + const { stdout, stderr } = await exec( childCmd, { + cwd: outputDir, + ...( is.windows + ? { shell: true } + : {} ), + } as unknown as ExecOptions ); + console.log( stdout, stderr ); +} + +export async function startRun( event: IpcMainEvent, { id, args, binaryName, outputDir, outputFilename, outputName, combinedOutput, usesRaxmlNg, usesModeltestNg, inputPath }: StartRunPayload ): Promise { + const token = beginRun( id ); + stopRun( id ); + const reportError = ( error: unknown ): void => { + if ( !stillRunning( id, token ) ) { + return; + } + send( event, ipc.RUN_ERROR, { id, error } ); + }; + const binaryPath = path.resolve( binaryDir, binaryName ); + console.log( `Run ${id}:\n output filename id: ${outputFilename}\n output dir: ${outputDir}\n binary: ${binaryName}\n binary path: ${binaryDir}\n args:`, args ); + // Check for deleted input file + try { + await fs.access( inputPath ); + // The check succeeded + } + catch ( err: unknown ) { + const error = new UserFixError( `The input file does not exist '${inputPath}': ${( err as Error ).message}` ); + Sentry.captureException( err ); + reportError( error ); + return; + } + const resultFilePath = path.join( outputDir, outputFilename ); + console.log( `Try writing to output file '${resultFilePath}'...` ); + try { + await fs.writeFile( resultFilePath, 'test' ); + console.log( ` -> writing to output file ok!` ); + } + catch ( err: unknown ) { + console.error( 'Error writing to output file:', err ); + const error = new Error( `Error trying to write to output file '${resultFilePath}': ${( err as Error ).message}` ); + Sentry.captureException( err ); + reportError( error ); + return; + } + finally { + try { + fs.unlink( resultFilePath ); + } + catch ( err: unknown ) { + console.error( `Error trying to unlink temporary result file: ${( err as Error ).message}` ); + } + } + console.log( `Try executing binary by running '"${binaryPath}" -v'...` ); + try { + const { stdout, stderr } = await execFile( get_space_safe_binary_path( binaryPath ), usesModeltestNg + ? ['--version'] + : ['-v'], { + // env: { PATH: binaryDir }, + shell: is.windows, + } ); + console.log( stdout ); + if ( stderr ) { + console.error( 'Error:', stderr ); + } + } + catch ( err: unknown ) { + console.error( 'Error executing binary:', err ); + const error = new Error( `Error trying to execute raxml binary '${binaryPath}': ${( err as Error ).message}` ); + Sentry.captureException( err ); + reportError( error ); + return; + } + // TODO: When packaged, RAxML throws error trying to write the file RAxML_flagCheck: + // "The file RAxML_flagCheck RAxML wants to open for writing or appending can not be opened [mode: wb], exiting ..." + // TODO: this is just skipping a check when raxml-ng is used. Maybe make the "Sanity check" option compulsory here + const checkFlags = is.development && !is.windows && !usesRaxmlNg && !usesModeltestNg; + if ( checkFlags ) { + for ( const arg of args ) { + try { + const { stdout, stderr } = await exec( `"${binaryPath}" ${arg.join( ' ' )} --flag-check`, { + ...( is.windows + ? { shell: true } + : {} ), + } as unknown as ExecOptions ); + console.log( stdout, stderr ); + } + catch ( err: unknown ) { + console.error( 'Flag check run error:', err ); + Sentry.captureException( err ); + reportError( err ); + return; + } + } + } + let exitCode: ProcessExit = 0; + for ( const arg of args ) { + try { + console.log( `Run '${binaryName}' with args:`, arg ); + exitCode = await runProcess( id, event, binaryDir, binaryName, arg ); + if ( exitCode !== 0 ) { + break; + } + } + catch ( err: unknown ) { + console.error( 'Run error:', err ); + Sentry.captureException( err ); + reportError( err ); + return; + } + } + if ( !stillRunning( id, token ) || !finishedRun( exitCode ) ) { + return; + } + if ( combinedOutput ) { + console.log( 'Combining output...' ); + await combineOutput( outputDir, outputFilename ); + } + // Rename the RAxML_info.\*.tre into RAxML_info.\*.txt + console.log( + `Renaming info file 'RAxML_info.${outputName}.tre' -> 'RAxML_info.${outputName}.txt'...`, + ); + const anyMatch = new RegExp( `RAxML_info\\.${outputName}\\.tre` ); + const filenames = await fs.readdir( outputDir ); + const infoFiles = filenames.filter( ( filename ) => anyMatch.test( filename ) ); + for ( let i = 0; i < infoFiles.length; i++ ) { + const infoPath = path.join( outputDir, infoFiles[i] ); + const newPath = path.join( outputDir, infoFiles[i].replace( '.tre', '.txt' ) ); + await fs.rename( infoPath, newPath ); + } + // Rename the raxml-ng output files to add .tre or .txt extension + if ( usesRaxmlNg ) { + console.log( `Renaming raxml-ng output files to add .tre or .txt extension...` ); + const anyMatch = new RegExp( `${outputName}.raxml` ); + const filenames = await fs.readdir( outputDir ); + const outputFiles = filenames.filter( ( filename ) => anyMatch.test( filename ) ); + const rbaMatch = new RegExp( `${outputName}.raxml.rba` ); + const bestModelMatch = new RegExp( `${outputName}.raxml.bestModel` ); + const logMatch = new RegExp( `${outputName}.raxml.log` ); + const aPMatch = new RegExp( `${outputName}.raxml.ancestralProbs` ); + const aSMatch = new RegExp( `${outputName}.raxml.ancestralStates` ); + let renamedFiles = outputFiles.map( ( f ) => { + if ( rbaMatch.test( f ) ) { + return f; + } + if ( bestModelMatch.test( f ) || + logMatch.test( f ) || + aPMatch.test( f ) || + aSMatch.test( f ) ) { + return ( f += '.txt' ); + } + return ( f += '.tre' ); + } ); + for ( let i = 0; i < outputFiles.length; i++ ) { + const infoPath = path.join( outputDir, outputFiles[i] ); + const newPath = path.join( outputDir, renamedFiles[i] ); + await fs.rename( infoPath, newPath ); + } + } + const nextFilenames = await fs.readdir( outputDir ); + const resultFilenames = nextFilenames.filter( ( filename ) => filename.includes( outputName ) ); + if ( !stillRunning( id, token ) ) { + return; + } + send( event, ipc.RUN_FINISHED, { + id, + resultDir: outputDir, + resultFilenames, + exitCode, + } ); +} diff --git a/src/main/updates.test.js b/src/main/updates.test.js index 8eb91add..d2303937 100644 --- a/src/main/updates.test.js +++ b/src/main/updates.test.js @@ -100,8 +100,8 @@ it( 'a failed update uses the error dialog', () => { it( 'the shell opens no update progress window', () => { const pkg = JSON.parse( fs.readFileSync( path.join( __dirname, '../../package.json' ), 'utf8' ) ); - const main = fs.readFileSync( path.join( __dirname, 'index.js' ), 'utf8' ); - const updates = fs.readFileSync( path.join( __dirname, 'updates.js' ), 'utf8' ); + 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 + updates ).not.toContain( 'electron-progressbar' ); diff --git a/src/main/updates.js b/src/main/updates.ts similarity index 88% rename from src/main/updates.js rename to src/main/updates.ts index 845d31e6..5035720d 100644 --- a/src/main/updates.js +++ b/src/main/updates.ts @@ -1,6 +1,8 @@ import log from 'electron-log'; +import type { Dialog } from 'electron'; +import type { AppUpdater } from 'electron-updater'; -export function listenForUpdates( updater, dialog ) { +export function listenForUpdates( updater: AppUpdater, dialog: Dialog ): void { updater.on( 'checking-for-update', () => { log.info( 'Checking for update...' ); } ); diff --git a/src/main/utils/saveScreenshot.js b/src/main/utils/saveScreenshot.ts similarity index 93% rename from src/main/utils/saveScreenshot.js rename to src/main/utils/saveScreenshot.ts index e769cfac..4456dd77 100644 --- a/src/main/utils/saveScreenshot.js +++ b/src/main/utils/saveScreenshot.ts @@ -2,8 +2,10 @@ import { dialog } from 'electron'; import fs from 'fs'; import util from 'util'; import { activeWindow } from './utils'; + const writeFile = util.promisify( fs.writeFile ); -const saveScreenshot = async () => { + +const saveScreenshot = async (): Promise => { console.log( 'Save screenshot...' ); const win = activeWindow(); if ( !win ) { @@ -33,8 +35,9 @@ const saveScreenshot = async () => { console.log( 'Saved!' ); } } - catch ( err ) { + catch ( err: unknown ) { console.log( err ); } }; + export default saveScreenshot; diff --git a/src/main/utils/utils.js b/src/main/utils/utils.js deleted file mode 100644 index a6c67e32..00000000 --- a/src/main/utils/utils.js +++ /dev/null @@ -1,2 +0,0 @@ -import electron from 'electron'; -export const activeWindow = () => electron.BrowserWindow.getFocusedWindow() ?? null; diff --git a/src/main/utils/utils.ts b/src/main/utils/utils.ts new file mode 100644 index 00000000..9ed02916 --- /dev/null +++ b/src/main/utils/utils.ts @@ -0,0 +1,5 @@ +import electron from 'electron'; +import type { BrowserWindow } from 'electron'; + +export const activeWindow = (): BrowserWindow | null => + electron.BrowserWindow.getFocusedWindow() ?? null; diff --git a/src/preload-proofs/cancelModelSelection.json b/src/preload-proofs/cancelModelSelection.json index 63d818f4..df762aea 100644 --- a/src/preload-proofs/cancelModelSelection.json +++ b/src/preload-proofs/cancelModelSelection.json @@ -1,7 +1,7 @@ { "key": "modelCancelled", "method": "cancelModelSelection", - "args": ["run-7_/data/primates.fasta"], + "args": ["7_/data/primates.fasta"], "channel": "ALIGNMENT_MODEL_SELECTION_CANCEL", "result": null } diff --git a/src/preload-proofs/cancelRun.json b/src/preload-proofs/cancelRun.json index 56c41781..6fb87c80 100644 --- a/src/preload-proofs/cancelRun.json +++ b/src/preload-proofs/cancelRun.json @@ -1,7 +1,7 @@ { "key": "cancelled", "method": "cancelRun", - "args": ["run-7"], + "args": [7], "channel": "RUN_CANCEL", "result": null } diff --git a/src/preload-proofs/onAstralSuccess.json b/src/preload-proofs/onAstralSuccess.json index 240855a2..2124d7fb 100644 --- a/src/preload-proofs/onAstralSuccess.json +++ b/src/preload-proofs/onAstralSuccess.json @@ -4,7 +4,7 @@ "channel": "ASTRAL_SUCCESS", "subscribe": true, "result": { - "id": "run-7", + "id": 7, "exitCode": 0 } } diff --git a/src/preload-proofs/onModelSelectionFailure.json b/src/preload-proofs/onModelSelectionFailure.json index a1791002..fdc25cf8 100644 --- a/src/preload-proofs/onModelSelectionFailure.json +++ b/src/preload-proofs/onModelSelectionFailure.json @@ -4,7 +4,7 @@ "channel": "ALIGNMENT_MODEL_SELECTION_FAILURE", "subscribe": true, "result": { - "id": "run-7_/data/primates.fasta", + "id": "7_/data/primates.fasta", "error": "missing binary" } } diff --git a/src/preload-proofs/onModelSelectionSuccess.json b/src/preload-proofs/onModelSelectionSuccess.json index fdc9a41d..ea14bd7b 100644 --- a/src/preload-proofs/onModelSelectionSuccess.json +++ b/src/preload-proofs/onModelSelectionSuccess.json @@ -4,7 +4,7 @@ "channel": "ALIGNMENT_MODEL_SELECTION_SUCCESS", "subscribe": true, "result": { - "id": "run-7_/data/primates.fasta", + "id": "7_/data/primates.fasta", "result": { "raxml": "GTRGAMMA", "extraFlag": "--HKY85", diff --git a/src/preload-proofs/onRunError.json b/src/preload-proofs/onRunError.json index 30df7527..e82d02e1 100644 --- a/src/preload-proofs/onRunError.json +++ b/src/preload-proofs/onRunError.json @@ -3,5 +3,5 @@ "method": "onRunError", "channel": "RUN_ERROR", "subscribe": true, - "result": { "id": "run-7", "error": "missing binary" } + "result": { "id": 7, "error": "missing binary" } } diff --git a/src/preload-proofs/onRunFinished.json b/src/preload-proofs/onRunFinished.json index 972b4319..b1eaa5af 100644 --- a/src/preload-proofs/onRunFinished.json +++ b/src/preload-proofs/onRunFinished.json @@ -4,7 +4,7 @@ "channel": "RUN_FINISHED", "subscribe": true, "result": { - "id": "run-7", + "id": 7, "resultDir": "/out", "resultFilenames": ["primates.tre"], "exitCode": 0 diff --git a/src/preload-proofs/onRunStderr.json b/src/preload-proofs/onRunStderr.json index 5e0420d3..89d2da1b 100644 --- a/src/preload-proofs/onRunStderr.json +++ b/src/preload-proofs/onRunStderr.json @@ -3,5 +3,5 @@ "method": "onRunStderr", "channel": "RUN_STDERR", "subscribe": true, - "result": { "id": "run-7", "content": "warn\n" } + "result": { "id": 7, "content": "warn\n" } } diff --git a/src/preload-proofs/onRunStdout.json b/src/preload-proofs/onRunStdout.json index 0e0f3571..596e2b65 100644 --- a/src/preload-proofs/onRunStdout.json +++ b/src/preload-proofs/onRunStdout.json @@ -3,5 +3,5 @@ "method": "onRunStdout", "channel": "RUN_STDOUT", "subscribe": true, - "result": { "id": "run-7", "content": "tree\n" } + "result": { "id": 7, "content": "tree\n" } } diff --git a/src/preload-proofs/selectAlignment.json b/src/preload-proofs/selectAlignment.json index 61ee92a9..c187b77c 100644 --- a/src/preload-proofs/selectAlignment.json +++ b/src/preload-proofs/selectAlignment.json @@ -1,7 +1,7 @@ { "key": "alignments", "method": "selectAlignment", - "args": ["run-7"], + "args": [7], "channel": "ALIGNMENT_SELECT", "log": "RUNID", "result": [{ "path": "/data/primates.fasta", "name": "primates.fasta" }] diff --git a/src/preload-proofs/selectAstralFile.json b/src/preload-proofs/selectAstralFile.json index 3bc645e5..6a96f958 100644 --- a/src/preload-proofs/selectAstralFile.json +++ b/src/preload-proofs/selectAstralFile.json @@ -1,7 +1,7 @@ { "key": "astral", "method": "selectAstralFile", - "args": ["run-7"], + "args": [7], "channel": "ASTRAL_FILE_SELECT", "result": { "path": "/data/trees.tre", "name": "trees.tre" } } diff --git a/src/preload-proofs/selectOutputDir.json b/src/preload-proofs/selectOutputDir.json index 093e5280..0dacca3f 100644 --- a/src/preload-proofs/selectOutputDir.json +++ b/src/preload-proofs/selectOutputDir.json @@ -1,7 +1,7 @@ { "key": "outputDir", "method": "selectOutputDir", - "args": ["run-7"], + "args": [7], "channel": "OUTPUT_DIR_SELECT", "result": "/data/results" } diff --git a/src/preload-proofs/selectPartitionFile.json b/src/preload-proofs/selectPartitionFile.json index 339af116..d772aefd 100644 --- a/src/preload-proofs/selectPartitionFile.json +++ b/src/preload-proofs/selectPartitionFile.json @@ -1,7 +1,7 @@ { "key": "partition", "method": "selectPartitionFile", - "args": ["run-7"], + "args": [7], "channel": "PARTITION_FILE_SELECT", "result": "/data/genes.part" } diff --git a/src/preload-proofs/selectTree.json b/src/preload-proofs/selectTree.json index b4540c9e..20f988c4 100644 --- a/src/preload-proofs/selectTree.json +++ b/src/preload-proofs/selectTree.json @@ -1,7 +1,7 @@ { "key": "tree", "method": "selectTree", - "args": ["run-7", "backboneConstraint"], + "args": [7, "backboneConstraint"], "channel": "TREE_SELECT", "result": { "type": "backboneConstraint", "filePath": "/data/backbone.nwk" } } diff --git a/src/preload-proofs/startAstral.json b/src/preload-proofs/startAstral.json index 5ba5bbf0..219f1c41 100644 --- a/src/preload-proofs/startAstral.json +++ b/src/preload-proofs/startAstral.json @@ -3,7 +3,7 @@ "method": "startAstral", "args": [ { - "id": "run-7", + "id": 7, "binaryName": "astral.5.7.8.jar", "args": [["-i", "/data/trees.tre", "-o", "/out/ASTRAL_run-7.tre"]] } diff --git a/src/preload-proofs/startModelSelection.json b/src/preload-proofs/startModelSelection.json index 79066bd1..5f88b084 100644 --- a/src/preload-proofs/startModelSelection.json +++ b/src/preload-proofs/startModelSelection.json @@ -3,7 +3,7 @@ "method": "startModelSelection", "args": [ { - "id": "run-7_/data/primates.fasta", + "id": "7_/data/primates.fasta", "filePath": "/data/primates.fasta", "outputDir": "/out", "dataType": "nucleotide", diff --git a/src/preload-proofs/startRun.json b/src/preload-proofs/startRun.json index 74dd8b58..bb7deba5 100644 --- a/src/preload-proofs/startRun.json +++ b/src/preload-proofs/startRun.json @@ -3,7 +3,7 @@ "method": "startRun", "args": [ { - "id": "run-7", + "id": 7, "args": [["--all"]], "binaryName": "raxml-ng", "outputDir": "/out", diff --git a/src/typecheckBaseline.test.js b/src/typecheckBaseline.test.js index 8603b276..a9b2fe1f 100644 --- a/src/typecheckBaseline.test.js +++ b/src/typecheckBaseline.test.js @@ -1,5 +1,5 @@ // @ts-nocheck — Jest globals. checkJs has no test runner types. -const { freshLines } = require( '../scripts/typecheck-baseline' ); +const { freshLines, unusedLines } = require( '../scripts/typecheck-baseline' ); it( 'reports a diagnostic line that the baseline does not list', () => { const known = ['src/a.js(1,1): error TS1: known']; @@ -14,3 +14,27 @@ it( 'treats the same diagnostic at another line as known', () => { const known = ['src/a.js(1,1): error TS1: known']; expect( freshLines( ['src/a.js(9,4): error TS1: known'], known ) ).toEqual( [] ); } ); + +it( 'reports a src/ baseline line whose diagnostic is gone', () => { + const known = [ + 'src/a.js(1,1): error TS1: known', + 'src/gone.js(2,1): error TS2: gone', + ' Overload 1 of 4, leftover continuation', + ]; + expect( unusedLines( known, ['src/a.js(9,4): error TS1: known'] ) ).toEqual( [ + 'src/gone.js(2,1): error TS2: gone', + ' Overload 1 of 4, leftover continuation', + ] ); +} ); + +it( 'does not let one file\'s continuation shelter another file\'s', () => { + const known = [ + 'src/a.js(1,1): error TS1: known', + ' Overload 1 of 4, same text', + ]; + const actual = [ + 'src/b.js(2,1): error TS1: known', + ' Overload 1 of 4, same text', + ]; + expect( freshLines( actual, known ) ).toEqual( actual ); +} );