diff --git a/src/compile/build.ts b/src/compile/build.ts index 9688026d6..848d21b26 100644 --- a/src/compile/build.ts +++ b/src/compile/build.ts @@ -1,7 +1,6 @@ import * as vscode from 'vscode' import * as path from 'path' import * as cs from 'cross-spawn' -import { AutoBuildInitiated, AutoCleaned, BuildDone } from '../core/event-bus' import { pickRootPath } from '../utils/quick-pick' import { parser } from '../parse/parser' @@ -38,7 +37,7 @@ function autoBuild(file: string, type: 'onFileChange' | 'onSave', bibChanged: bo return } logger.log('Auto build started' + (type === 'onFileChange' ? 'detecting the change of a file' : 'on saving file') + `: ${file} .`) - lw.eventBus.fire(AutoBuildInitiated, {type, file}) + lw.event.fire(lw.event.AutoBuildInitiated, {type, file}) if (!canAutoBuild()) { logger.log('Autobuild temporarily disabled.') return @@ -353,7 +352,7 @@ function handleRetryError(step: RecipeStep) { logger.log('Cleaning auxiliary files and retrying build after toolchain error.') queue.prepend(step) - void lw.cleaner.clean(step.rootFile).then(() => lw.eventBus.fire(AutoCleaned)) + void lw.cleaner.clean(step.rootFile).then(() => lw.event.fire(lw.event.AutoCleaned)) } /** @@ -368,7 +367,7 @@ function handleRetryError(step: RecipeStep) { function handleNoRetryError(configuration: vscode.WorkspaceConfiguration, step: RecipeStep) { logger.refreshStatus('x', 'errorForeground') if (['onFailed', 'onBuilt'].includes(configuration.get('latex.autoClean.run') as string)) { - void lw.cleaner.clean(step.rootFile).then(() => lw.eventBus.fire(AutoCleaned)) + void lw.cleaner.clean(step.rootFile).then(() => lw.event.fire(lw.event.AutoCleaned)) } void logger.showErrorMessageWithCompilerLogButton('Recipe terminated with error.') queue.clear() @@ -411,7 +410,7 @@ async function afterSuccessfulBuilt(lastStep: Step, skipped: boolean) { } logger.log(`Successfully built ${lastStep.rootFile} .`) logger.refreshStatus('check', 'statusBar.foreground', 'Recipe succeeded.') - lw.eventBus.fire(BuildDone) + lw.event.fire(lw.event.BuildDone) if (!lastStep.isExternal && skipped) { return } @@ -428,6 +427,6 @@ async function afterSuccessfulBuilt(lastStep: Step, skipped: boolean) { if (['onSucceeded', 'onBuilt'].includes(configuration.get('latex.autoClean.run') as string)) { logger.log('Auto Clean invoked.') await lw.cleaner.clean(lastStep.rootFile) - lw.eventBus.fire(AutoCleaned) + lw.event.fire(lw.event.AutoCleaned) } } diff --git a/src/completion/completer/citation.ts b/src/completion/completer/citation.ts index 68fd832b6..3de84829d 100644 --- a/src/completion/completer/citation.ts +++ b/src/completion/completer/citation.ts @@ -4,7 +4,6 @@ import { bibtexParser } from 'latex-utensils' import { lw } from '../../lw' import type { FileCache } from '../../types' -import * as eventbus from '../../core/event-bus' import {trimMultiLineString} from '../../utils/utils' import {computeFilteringRange} from './completerutils' import type { IProvider, ICompletionItem, IProviderArgs } from '../latex' @@ -309,7 +308,7 @@ export class Citation implements IProvider { const ast = await parser.parseBibTeX(bibtex) if (ast === undefined) { logger.log(`Parsed 0 bib entries from ${fileName}.`) - lw.eventBus.fire(eventbus.FileParsed, fileName) + lw.event.fire(lw.event.FileParsed, fileName) return } const abbreviations = parseAbbrevations(ast) @@ -336,7 +335,7 @@ export class Citation implements IProvider { this.bibEntries.set(fileName, newEntry) logger.log(`Parsed ${newEntry.length} bib entries from ${fileName} .`) void lw.structureViewer.reconstruct() - lw.eventBus.fire(eventbus.FileParsed, fileName) + lw.event.fire(lw.event.FileParsed, fileName) } removeEntriesInFile(file: string) { diff --git a/src/core/cache.ts b/src/core/cache.ts index ef4dff311..dd4c4140c 100644 --- a/src/core/cache.ts +++ b/src/core/cache.ts @@ -9,7 +9,6 @@ import { lw } from '../lw' import type { FileCache } from '../types' import * as utils from '../utils/utils' -import * as eventbus from './event-bus' import { InputFileRegExp } from '../utils/inputfilepath' import { parser } from '../parse/parser' @@ -200,7 +199,7 @@ async function refreshCache(filePath: string, rootPath?: string): Promise(eventName: T, arg: EventArgs[T]): void - fire(eventName: EventName): void - fire(eventName: EventName, arg?: any): void { - if (![DocumentChanged, ViewerStatusChanged].includes(eventName)) { - logger.log(eventName + (arg ? `: ${JSON.stringify(arg)}` : '')) - } - this.eventEmitter.emit(eventName, arg) - } - - // onDidChangeRootFile(cb: (rootFile: EventArgTypeMap[typeof RootFileChanged]) => void): Disposable { - // return this.registerListener(RootFileChanged, cb) - // } - - // onDidEndFindRootFile(cb: () => void): Disposable { - // return this.registerListener(RootFileSearched, cb) - // } - - // onDidFileParsed(cb: () => void): Disposable { - // return this.registerListener(FileParsed, cb) - // } - - // onDidChangePdfViewerStatus(cb: (status: EventArgTypeMap[typeof ViewerStatusChanged]) => void): Disposable { - // return this.registerListener(ViewerStatusChanged, cb) - // } - - // private registerListener( - // eventName: T, - // cb: (arg: EventArgTypeMap[T]) => void - // ): Disposable - // private registerListener( - // eventName: T, - // cb: () => void - // ): Disposable - // private registerListener( - // eventName: T, - // cb: (arg?: any) => void - // ): Disposable - // { - // this.eventEmitter.on(eventName, cb) - // const disposable = { - // dispose: () => { this.eventEmitter.removeListener(eventName, cb) } - // } - // return disposable - // } - - on(eventName: EventName, cb: (arg?: any) => void): Disposable { - this.eventEmitter.on(eventName, cb) - const disposable = { - dispose: () => { this.eventEmitter.removeListener(eventName, cb) } - } - return disposable - } - -} diff --git a/src/core/event.ts b/src/core/event.ts new file mode 100644 index 000000000..0a461ca3c --- /dev/null +++ b/src/core/event.ts @@ -0,0 +1,64 @@ +import { EventEmitter } from 'events' +import type { PdfViewerState } from '../../types/latex-workshop-protocol-types/index' +import type { Disposable } from 'vscode' + +import { lw } from '../lw' + +const logger = lw.log('Event') + +export enum Events { + BuildDone = 'BUILD_DONE', + AutoBuildInitiated = 'AUTO_BUILD_INITIATED', + RootFileChanged = 'ROOT_FILE_CHANGED', + RootFileSearched = 'ROOT_FILE_SEARCHED', + FileParsed = 'FILE_PARSED', + ViewerPageLoaded = 'VIEWER_PAGE_LOADED', + ViewerStatusChanged = 'VIEWER_STATUS_CHANGED', + FileWatched = 'FILE_WATCHED', + FileChanged = 'FILE_CHANGED', + FileRemoved = 'FILE_REMOVED', + DocumentChanged = 'DOCUMENT_CHANGED', + StructureUpdated = 'STRUCTURE_UPDATED', + AutoCleaned = 'AUTO_CLEANED' +} + +export const event = { + ...Events, + on, + fire, + dispose +} + +export type EventArgs = { + [Events.AutoBuildInitiated]: {type: 'onFileChange' | 'onSave', file: string}, + [Events.RootFileChanged]: string, + [Events.FileParsed]: string, + [Events.ViewerStatusChanged]: PdfViewerState, + [Events.FileWatched]: string, + [Events.FileChanged]: string, + [Events.FileRemoved]: string +} + +const eventEmitter = new EventEmitter() + +function dispose() { + eventEmitter.removeAllListeners() +} + + +function fire(eventName: T, arg: EventArgs[T]): void +function fire(eventName: Events): void +function fire(eventName: Events, arg?: any): void { + if (![Events.DocumentChanged, Events.ViewerStatusChanged].includes(eventName)) { + logger.log(eventName + (arg ? `: ${JSON.stringify(arg)}` : '')) + } + eventEmitter.emit(eventName, arg) +} + +function on(eventName: Events, cb: (arg?: any) => void): Disposable { + eventEmitter.on(eventName, cb) + const disposable = { + dispose: () => { eventEmitter.removeListener(eventName, cb) } + } + return disposable +} diff --git a/src/core/root.ts b/src/core/root.ts index 46d006f1b..a3183bb99 100644 --- a/src/core/root.ts +++ b/src/core/root.ts @@ -4,7 +4,6 @@ import * as fs from 'fs' import { lw } from '../lw' import * as utils from '../utils/utils' -import * as eventbus from './event-bus' const logger = lw.log('Root') @@ -59,7 +58,7 @@ async function find(): Promise { root.file.langId = lw.file.getLangId(rootFilePath) root.dir.path = path.dirname(rootFilePath) logger.log(`Root file changed: from ${root.file.path} to ${rootFilePath}, langID ${root.file.langId} . Refresh dependencies`) - lw.eventBus.fire(eventbus.RootFileChanged, rootFilePath) + lw.event.fire(lw.event.RootFileChanged, rootFilePath) // We also clean the completions from the old project lw.completer.input.reset() @@ -72,12 +71,12 @@ async function find(): Promise { await lw.cache.loadFlsFile(rootFilePath) }) } - lw.eventBus.fire(eventbus.RootFileSearched) + lw.event.fire(lw.event.RootFileSearched) return } logger.log('No root file found.') void lw.structureViewer.refresh() - lw.eventBus.fire(eventbus.RootFileSearched) + lw.event.fire(lw.event.RootFileSearched) return } diff --git a/src/core/watcher.ts b/src/core/watcher.ts index f985f896f..511536fa0 100644 --- a/src/core/watcher.ts +++ b/src/core/watcher.ts @@ -2,7 +2,6 @@ import * as vscode from 'vscode' import * as fs from 'fs' import * as path from 'path' import { lw } from '../lw' -import * as eventbus from './event-bus' const logger = lw.log('Cacher', 'Watcher') @@ -113,7 +112,7 @@ class Watcher { const filePath = uri.fsPath logger.log(`"${event}" emitted on ${filePath}.`) this.onChangeHandlers.forEach(handler => handler(filePath)) - lw.eventBus.fire(eventbus.FileChanged, filePath) + lw.event.fire(lw.event.FileChanged, filePath) } /** @@ -174,7 +173,7 @@ class Watcher { clearInterval(interval) delete this.polling[filePath] this.onChangeHandlers.forEach(handler => handler(filePath)) - lw.eventBus.fire(eventbus.FileChanged, filePath) + lw.event.fire(lw.event.FileChanged, filePath) } } @@ -201,7 +200,7 @@ class Watcher { this.disposeWatcher(folder) } - lw.eventBus.fire(eventbus.FileRemoved, filePath) + lw.event.fire(lw.event.FileRemoved, filePath) } /** @@ -242,7 +241,7 @@ class Watcher { this.onCreateHandlers.forEach(handler => handler(filePath)) logger.log(`Watched ${filePath} .`) } - lw.eventBus.fire(eventbus.FileWatched, filePath) + lw.event.fire(lw.event.FileWatched, filePath) } /** diff --git a/src/lw.ts b/src/lw.ts index dbe82dae8..165f1fbda 100644 --- a/src/lw.ts +++ b/src/lw.ts @@ -1,5 +1,6 @@ import * as vscode from 'vscode' import type { getLogger } from './utils/logging/logger' +import type { event } from './core/event' import type { file } from './core/file' import type { watcher } from './core/watcher' import type { cache } from './core/cache' @@ -11,7 +12,6 @@ import type { LaTeXCommanderTreeView } from './extras/activity-bar' import type { Configuration } from './utils/logging/log-config' import type { Counter } from './extras/counter' import type { EnvPair } from './locate/environment' -import type { EventBus } from './core/event-bus' import type { Linter } from './lint/latex-linter' import type { Locator } from './locate/synctex' import type { LwFileSystem } from './core/file-system' @@ -36,12 +36,12 @@ export const lw = { extensionRoot: '', constant: {} as typeof constant, log: {} as typeof getLogger, + event: {} as typeof event, file: {} as typeof file, watcher: {} as typeof watcher, cache: {} as typeof cache, root: {} as typeof root, compile: {} as typeof compile, - eventBus: Object.create(null) as EventBus, configuration: Object.create(null) as Configuration, lwfs: Object.create(null) as LwFileSystem, viewer: Object.create(null) as Viewer, diff --git a/src/main.ts b/src/main.ts index 81118ff2a..47c1d331b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -4,6 +4,8 @@ import { lw, registerDisposable } from './lw' import { getLogger } from './utils/logging/logger' lw.log = getLogger +import { event } from './core/event' +lw.event = event import { file } from './core/file' lw.file = file import { watcher } from './core/watcher' @@ -26,7 +28,6 @@ import { latexFormatterProvider } from './lint/latex-formatter' import { FoldingProvider, WeaveFoldingProvider } from './language/folding' import { SelectionRangeProvider } from './language/selection' import { bibtexFormat, bibtexFormatterProvider } from './lint/bibtex-formatter' -import { DocumentChanged } from './core/event-bus' import { Cleaner } from './extras/cleaner' import { LaTeXCommanderTreeView } from './extras/activity-bar' @@ -34,7 +35,6 @@ import { Configuration } from './utils/logging/log-config' import { Counter } from './extras/counter' import { dupLabelDetector } from './lint/duplicate-label' import { EnvPair } from './locate/environment' -import { EventBus } from './core/event-bus' import { Linter } from './lint/latex-linter' import { Locator } from './locate/synctex' import { LwFileSystem } from './core/file-system' @@ -59,7 +59,6 @@ const logger = lw.log('Extension') function initialize(extensionContext: vscode.ExtensionContext) { lw.extensionContext = extensionContext lw.extensionRoot = path.resolve(`${__dirname}/../../`) - lw.eventBus = new EventBus() lw.configuration = new Configuration() lw.lwfs = new LwFileSystem() lw.viewer = new Viewer() @@ -175,7 +174,7 @@ export function activate(extensionContext: vscode.ExtensionContext) { !lw.file.hasDtxLangId(e.document.languageId)) { return } - lw.eventBus.fire(DocumentChanged) + lw.event.fire(lw.event.DocumentChanged) lw.linter.lintActiveFileIfEnabledAfterInterval(e.document) lw.cache.refreshCacheAggressive(e.document.fileName) })) diff --git a/src/outline/project.ts b/src/outline/project.ts index d386e575b..fbcf0ac6d 100644 --- a/src/outline/project.ts +++ b/src/outline/project.ts @@ -1,6 +1,5 @@ import * as vscode from 'vscode' import { lw } from '../lw' -import { StructureUpdated } from '../core/event-bus' import { construct as constructLaTeX } from './structurelib/latex' import { buildBibTeX } from './structurelib/bibtex' import { construct as constructDocTeX } from './structurelib/doctex' @@ -104,7 +103,7 @@ export class StructureView implements vscode.TreeDataProvider { async reconstruct() { this.structure = await this.build(true) this.structureChanged.fire(undefined) - lw.eventBus.fire(StructureUpdated) + lw.event.fire(lw.event.StructureUpdated) return this.structure } @@ -112,7 +111,7 @@ export class StructureView implements vscode.TreeDataProvider { this.structure = await this.build(false) if (fireChangedEvent) { this.structureChanged.fire(undefined) - lw.eventBus.fire(StructureUpdated) + lw.event.fire(lw.event.StructureUpdated) } return this.structure } diff --git a/src/preview/viewer.ts b/src/preview/viewer.ts index d0e0b447e..9ecb92e46 100644 --- a/src/preview/viewer.ts +++ b/src/preview/viewer.ts @@ -10,7 +10,6 @@ import type { ClientRequest, PdfViewerParams, PdfViewerState } from '../../types import { Client } from './viewerlib/client' import { createPdfViewerPanel } from './viewerlib/pdfviewerpanel' import { viewerManager } from './viewerlib/pdfviewermanager' -import { ViewerPageLoaded } from '../core/event-bus' import { getLogger } from '../utils/logging/logger' import { moveActiveEditor } from '../utils/webview' @@ -290,7 +289,7 @@ export class Viewer { break } case 'loaded': { - lw.eventBus.fire(ViewerPageLoaded) + lw.event.fire(lw.event.ViewerPageLoaded) const configuration = vscode.workspace.getConfiguration('latex-workshop') if (configuration.get('synctex.afterBuild.enabled') as boolean) { logger.log('SyncTex after build invoked.') diff --git a/src/preview/viewerlib/pdfviewerpanel.ts b/src/preview/viewerlib/pdfviewerpanel.ts index 7a125a2d8..30ceee044 100644 --- a/src/preview/viewerlib/pdfviewerpanel.ts +++ b/src/preview/viewerlib/pdfviewerpanel.ts @@ -4,7 +4,6 @@ import { lw } from '../../lw' import type { PanelRequest, PdfViewerState } from '../../../types/latex-workshop-protocol-types/index' import { escapeHtml, sleep } from '../../utils/utils' import { viewerManager } from './pdfviewermanager' -import { ViewerStatusChanged } from '../../core/event-bus' import { getLogger } from '../../utils/logging/logger' @@ -22,7 +21,7 @@ export class PdfViewerPanel { switch(msg.type) { case 'state': { this.viewerState = msg.state - lw.eventBus.fire(ViewerStatusChanged, msg.state) + lw.event.fire(lw.event.ViewerStatusChanged, msg.state) break } default: { diff --git a/test/suites/01_build.test.ts b/test/suites/01_build.test.ts index 9b478f043..b0d6eee8f 100644 --- a/test/suites/01_build.test.ts +++ b/test/suites/01_build.test.ts @@ -4,7 +4,6 @@ import * as path from 'path' import * as assert from 'assert' import { lw } from '../../src/lw' import * as test from './utils' -import { BuildDone } from '../../src/core/event-bus' suite('Build TeX files test suite', () => { test.suite.name = path.basename(__filename).replace('.test.js', '') @@ -189,7 +188,7 @@ suite('Build TeX files test suite', () => { ], {local: 1, skipCache: true}) await test.build(fixture, 'sub/s.tex', undefined, async () => { - const event = test.wait(BuildDone) + const event = test.wait(lw.event.BuildDone) void lw.commands.build() await test.sleep(500) await vscode.commands.executeCommand('workbench.action.acceptSelectedQuickOpenItem') @@ -205,7 +204,7 @@ suite('Build TeX files test suite', () => { {src: 'subfile_sub.tex', dst: 'sub/s.tex'} ], {local: 1, skipCache: true}) await test.build(fixture, 'sub/s.tex', undefined, async () => { - const event = test.wait(BuildDone) + const event = test.wait(lw.event.BuildDone) void lw.commands.build() await test.sleep(500) await vscode.commands.executeCommand('workbench.action.quickOpenSelectNext') diff --git a/test/suites/05_viewer.test.ts b/test/suites/05_viewer.test.ts index 0c76e3782..f709dc5bd 100644 --- a/test/suites/05_viewer.test.ts +++ b/test/suites/05_viewer.test.ts @@ -3,7 +3,6 @@ import * as path from 'path' import * as assert from 'assert' import { lw } from '../../src/lw' import * as test from './utils' -import { BuildDone } from '../../src/core/event-bus' suite('PDF viewer test suite', () => { test.suite.name = path.basename(__filename).replace('.test.js', '') @@ -108,7 +107,7 @@ suite('PDF viewer test suite', () => { ], {local: 1, skipCache: true}) await test.build(fixture, 'sub/s.tex', undefined, async () => { - const event = test.wait(BuildDone) + const event = test.wait(lw.event.BuildDone) void lw.commands.build() await test.sleep(500) await vscode.commands.executeCommand('workbench.action.acceptSelectedQuickOpenItem') @@ -128,7 +127,7 @@ suite('PDF viewer test suite', () => { ], {local: 1, skipCache: true}) await test.build(fixture, 'sub/s.tex', undefined, async () => { - const event = test.wait(BuildDone) + const event = test.wait(lw.event.BuildDone) void lw.commands.build() await test.sleep(500) await vscode.commands.executeCommand('workbench.action.quickOpenSelectNext') diff --git a/test/suites/10_cleaner.test.ts b/test/suites/10_cleaner.test.ts index 4a24f5a3c..eff3851f4 100644 --- a/test/suites/10_cleaner.test.ts +++ b/test/suites/10_cleaner.test.ts @@ -4,7 +4,6 @@ import * as path from 'path' import * as assert from 'assert' import { lw } from '../../src/lw' import * as test from './utils' -import { AutoCleaned } from '../../src/core/event-bus' suite('Cleaner test suite', () => { test.suite.name = path.basename(__filename).replace('.test.js', '') @@ -102,7 +101,7 @@ suite('Cleaner test suite', () => { {src: 'invalid_cmd.tex', dst: 'main.tex'} ], {skipCache: true}) await lw.cleaner.clean() // Clean up previous remainders to ensure next build to fail - const cleaned = test.wait(AutoCleaned).then(() => true) + const cleaned = test.wait(lw.event.AutoCleaned).then(() => true) await test.build(fixture, 'main.tex') const result = await Promise.any([cleaned, test.sleep(1000)]) assert.ok(!result) @@ -114,7 +113,7 @@ suite('Cleaner test suite', () => { {src: 'base.tex', dst: 'main.tex'} ], {skipCache: true}) await lw.cleaner.clean() - const cleaned = test.wait(AutoCleaned).then(() => true) + const cleaned = test.wait(lw.event.AutoCleaned).then(() => true) await test.build(fixture, 'main.tex') const result = await Promise.any([cleaned, test.sleep(1000)]) assert.ok(!result) @@ -129,7 +128,7 @@ suite('Cleaner test suite', () => { {src: 'invalid_cmd.tex', dst: 'main.tex'} ], {skipCache: true}) await lw.cleaner.clean() // Clean up previous remainders to ensure next build to fail - let cleaned = test.wait(AutoCleaned).then(() => true) + let cleaned = test.wait(lw.event.AutoCleaned).then(() => true) await test.build(fixture, 'main.tex') let result = await Promise.any([cleaned, test.sleep(1000)]) assert.ok(result) @@ -138,7 +137,7 @@ suite('Cleaner test suite', () => { {src: 'base.tex', dst: 'main.tex'} ], {skipCache: true}) await lw.cleaner.clean() // Clean up previous remainders to ensure next build to fail - cleaned = test.wait(AutoCleaned).then(() => true) + cleaned = test.wait(lw.event.AutoCleaned).then(() => true) await test.build(fixture, 'main.tex') result = await Promise.any([cleaned, test.sleep(1000)]) assert.ok(!result) @@ -153,7 +152,7 @@ suite('Cleaner test suite', () => { {src: 'invalid_cmd.tex', dst: 'main.tex'} ], {skipCache: true}) await lw.cleaner.clean() // Clean up previous remainders to ensure next build to fail - let cleaned = test.wait(AutoCleaned).then(() => true) + let cleaned = test.wait(lw.event.AutoCleaned).then(() => true) await test.build(fixture, 'main.tex') let result = await Promise.any([cleaned, test.sleep(1000)]) assert.ok(result) @@ -162,7 +161,7 @@ suite('Cleaner test suite', () => { {src: 'base.tex', dst: 'main.tex'} ], {skipCache: true}) await lw.cleaner.clean() - cleaned = test.wait(AutoCleaned).then(() => true) + cleaned = test.wait(lw.event.AutoCleaned).then(() => true) await test.build(fixture, 'main.tex') result = await Promise.any([cleaned, test.sleep(1000)]) assert.ok(result) @@ -177,14 +176,14 @@ suite('Cleaner test suite', () => { {src: 'invalid_cmd.tex', dst: 'main.tex'} ], {skipCache: true}) await lw.cleaner.clean() // Clean up previous remainders to ensure next build to fail - let cleaned = test.wait(AutoCleaned).then(() => true) + let cleaned = test.wait(lw.event.AutoCleaned).then(() => true) await test.build(fixture, 'main.tex') let result = await Promise.any([cleaned, test.sleep(1000)]) assert.ok(!result) await vscode.workspace.getConfiguration('latex-workshop').update('latex.autoBuild.cleanAndRetry.enabled', true) await lw.cleaner.clean() - cleaned = test.wait(AutoCleaned).then(() => true) + cleaned = test.wait(lw.event.AutoCleaned).then(() => true) await test.build(fixture, 'main.tex') result = await Promise.any([cleaned, test.sleep(1000)]) assert.ok(result) diff --git a/test/suites/11_snippet.test.ts b/test/suites/11_snippet.test.ts index c9ad11427..3f90144df 100644 --- a/test/suites/11_snippet.test.ts +++ b/test/suites/11_snippet.test.ts @@ -2,9 +2,9 @@ import * as vscode from 'vscode' import * as path from 'path' import * as assert from 'assert' import * as test from './utils' +import { lw } from '../../src/lw' import { SurroundCommand } from '../../src/completion/completer/commandlib/surround' import { ICompletionItem } from '../../src/completion/latex' -import { DocumentChanged } from '../../src/core/event-bus' suite('Snippet test suite', () => { test.suite.name = path.basename(__filename).replace('.test.js', '') @@ -35,7 +35,7 @@ suite('Snippet test suite', () => { kind: 2 }] SurroundCommand.surround(items) - const promise = test.wait(DocumentChanged) + const promise = test.wait(lw.event.DocumentChanged) await test.sleep(500) await vscode.commands.executeCommand('workbench.action.acceptSelectedQuickOpenItem') await vscode.commands.executeCommand('editor.action.formatDocument') diff --git a/test/suites/utils.ts b/test/suites/utils.ts index 67ec7105a..09734c491 100644 --- a/test/suites/utils.ts +++ b/test/suites/utils.ts @@ -5,8 +5,7 @@ import { glob } from 'glob' import * as os from 'os' import {ok, strictEqual} from 'assert' import { lw } from '../../src/lw' -import { AutoBuildInitiated, DocumentChanged, EventArgs, ViewerPageLoaded, ViewerStatusChanged } from '../../src/core/event-bus' -import type { EventName } from '../../src/core/event-bus' +import type { EventArgs, Events } from '../../src/core/event' import { getCachedLog, getLogger, resetCachedLog } from '../../src/utils/logging/logger' let testIndex = 0 @@ -100,9 +99,9 @@ function log(fixtureName: string, testName: string, counter: string) { vscode.window.activeTextEditor?.document.getText()) } -export async function wait(event: T | EventName, arg?: EventArgs[T]) { +export async function wait(event: T | Events, arg?: EventArgs[T]) { return new Promise((resolve, _) => { - const disposable = lw.eventBus.on(event, (eventArg: EventArgs[T] | undefined) => { + const disposable = lw.event.on(event, (eventArg: EventArgs[T] | undefined) => { if (arg && (JSON.stringify(arg) !== JSON.stringify(eventArg))) { return } @@ -172,7 +171,7 @@ export async function build(fixture: string, openFile: string, ws?: string, acti } export async function auto(fixture: string, editFile: string, noBuild = false, save = false, ws?: string): Promise<{type: 'onFileChange' | 'onSave', file: string}> { - const done = wait(AutoBuildInitiated) + const done = wait(lw.event.AutoBuildInitiated) if (save) { logger.log(`Save ${editFile}.`) await open(path.resolve(getWsFixture(fixture, ws), editFile)) @@ -188,7 +187,7 @@ export async function auto(fixture: string, editFile: string, noBuild = false, s return {type: 'onFileChange', file: ''} } logger.log('Wait for auto-build.') - const result = await Promise.any([done, sleep(3000)]) as EventArgs[typeof AutoBuildInitiated] + const result = await Promise.any([done, sleep(3000)]) as EventArgs[Events.AutoBuildInitiated] ok(result) ok(result.type) ok(result.file) @@ -214,8 +213,8 @@ export async function view(fixture: string, pdfName: string, postAction?: () => logger.log(`Asserting viewer for ${pdfName} .`) await sleep(250) const promise = Promise.all([ - wait(ViewerPageLoaded), - wait(ViewerStatusChanged) + wait(lw.event.ViewerPageLoaded), + wait(lw.event.ViewerStatusChanged) ]) void lw.commands.view() if (postAction) { @@ -229,7 +228,7 @@ export async function view(fixture: string, pdfName: string, postAction?: () => } export async function format() { - const promise = wait(DocumentChanged) + const promise = wait(lw.event.DocumentChanged) await vscode.commands.executeCommand('editor.action.formatDocument') await promise const formatted = vscode.window.activeTextEditor?.document.getText()