Skip to content

Commit

Permalink
Modularize event.ts, previous event-bus
Browse files Browse the repository at this point in the history
  • Loading branch information
James-Yu committed Nov 23, 2023
1 parent 185db13 commit 007fb2e
Show file tree
Hide file tree
Showing 17 changed files with 110 additions and 166 deletions.
11 changes: 5 additions & 6 deletions src/compile/build.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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))
}

/**
Expand All @@ -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()
Expand Down Expand Up @@ -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
}
Expand All @@ -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)
}
}
5 changes: 2 additions & 3 deletions src/completion/completer/citation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
Expand All @@ -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) {
Expand Down
3 changes: 1 addition & 2 deletions src/core/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -200,7 +199,7 @@ async function refreshCache(filePath: string, rootPath?: string): Promise<Promis
lw.dupLabelDetector.run()
cachingFilesCount--
promises.delete(filePath)
lw.eventBus.fire(eventbus.FileParsed, filePath)
lw.event.fire(lw.event.FileParsed, filePath)

if (cachingFilesCount === 0) {
void lw.structureViewer.reconstruct()
Expand Down
107 changes: 0 additions & 107 deletions src/core/event-bus.ts

This file was deleted.

64 changes: 64 additions & 0 deletions src/core/event.ts
Original file line number Diff line number Diff line change
@@ -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<T extends keyof EventArgs>(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
}
7 changes: 3 additions & 4 deletions src/core/root.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down Expand Up @@ -59,7 +58,7 @@ async function find(): Promise<undefined> {
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()
Expand All @@ -72,12 +71,12 @@ async function find(): Promise<undefined> {
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
}

Expand Down
9 changes: 4 additions & 5 deletions src/core/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down Expand Up @@ -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)
}

/**
Expand Down Expand Up @@ -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)
}
}

Expand All @@ -201,7 +200,7 @@ class Watcher {
this.disposeWatcher(folder)
}

lw.eventBus.fire(eventbus.FileRemoved, filePath)
lw.event.fire(lw.event.FileRemoved, filePath)
}

/**
Expand Down Expand Up @@ -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)
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/lw.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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'
Expand All @@ -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,
Expand Down
Loading

0 comments on commit 007fb2e

Please sign in to comment.