Skip to content

Commit

Permalink
Merge pull request #4408 from James-Yu/viewer-unit-test
Browse files Browse the repository at this point in the history
Viewer unit test
  • Loading branch information
James-Yu authored Sep 24, 2024
2 parents 19aa34a + 5b593df commit fef1a6b
Show file tree
Hide file tree
Showing 21 changed files with 906 additions and 109 deletions.
40 changes: 36 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 10 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -1504,7 +1504,7 @@
],
"markdownDescription": "PDF viewer used for [View on PDF] link on \\ref."
},
"latex-workshop.viewer.pdf.internal.port": {
"latex-workshop.view.pdf.internal.port": {
"scope": "window",
"type": "number",
"default": 0,
Expand All @@ -1520,7 +1520,7 @@
],
"markdownDescription": " Which keybinding to use for the internal viewer for reverse synctex. `ctrl`/`cmd` + click (default) or double click."
},
"latex-workshop.viewer.pdf.internal.keyboardEvent": {
"latex-workshop.view.pdf.internal.keyboardEvent": {
"scope": "window",
"type": "string",
"default": "auto",
Expand Down Expand Up @@ -1597,6 +1597,12 @@
"default": false,
"markdownDescription": "Define if the hand tool is enabled by default in the PDF viewer."
},
"latex-workshop.view.pdf.invert": {
"scope": "window",
"type": "number",
"default": 0,
"markdownDescription": " Define the CSS invert filter level of the PDF viewer. This config can invert the color of PDF. Possible values are from 0 to 1."
},
"latex-workshop.view.pdf.invertMode.enabled": {
"scope": "window",
"type": "string",
Expand All @@ -1615,12 +1621,6 @@
"Disable the invert filter"
]
},
"latex-workshop.view.pdf.invert": {
"scope": "window",
"type": "number",
"default": 0,
"markdownDescription": " Define the CSS invert filter level of the PDF viewer. This config can invert the color of PDF. Possible values are from 0 to 1."
},
"latex-workshop.view.pdf.invertMode.brightness": {
"scope": "window",
"type": "number",
Expand Down Expand Up @@ -2653,6 +2653,7 @@
"@types/micromatch": "^4.0.9",
"@types/mocha": "^10.0.8",
"@types/node": "^18.15.3",
"@types/node-fetch": "^2.6.11",
"@types/sinon": "^17.0.3",
"@types/tmp": "^0.2.6",
"@types/vscode": "^1.88.0",
Expand All @@ -2669,6 +2670,7 @@
"esbuild": "^0.23.1",
"eslint": "^9.10.0",
"mocha": "^10.7.3",
"node-fetch": "^2.7.0",
"rimraf": "^6.0.1",
"sinon": "^19.0.2",
"textmate-bailout": "^1.1.0",
Expand Down
2 changes: 1 addition & 1 deletion src/compile/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ async function afterSuccessfulBuilt(lastStep: Step, skipped: boolean) {
if (configuration.get('view.pdf.viewer') === 'external' && configuration.get('synctex.afterBuild.enabled')) {
const pdfFile = lw.file.getPdfPath(lastStep.rootFile)
logger.log('SyncTex after build invoked.')
lw.locate.synctex.toPDF(undefined, undefined, pdfFile)
lw.locate.synctex.toPDF(pdfFile)
}
if (['onSucceeded', 'onBuilt'].includes(configuration.get('latex.autoClean.run') as string)) {
logger.log('Auto Clean invoked.')
Expand Down
4 changes: 2 additions & 2 deletions src/core/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export function synctex() {
} else if (lw.root.file.path !== undefined) {
pdfFile = lw.file.getPdfPath(lw.root.file.path)
}
lw.locate.synctex.toPDF(undefined, undefined, pdfFile)
lw.locate.synctex.toPDF(pdfFile)
}

export function synctexonref(line: number, filePath: string) {
Expand Down Expand Up @@ -176,7 +176,7 @@ export async function gotoSection(filePath: string, lineNumber: number) {
if (vscode.window.activeTextEditor) {
vscode.window.activeTextEditor.selection = new vscode.Selection(new vscode.Position(lineNumber, 0), new vscode.Position(lineNumber, 0))
if (vscode.workspace.getConfiguration('latex-workshop').get('view.outline.sync.viewer') as boolean) {
lw.locate.synctex.toPDF({ line: lineNumber, filePath: doc.fileName })
lw.locate.synctex.toPDF(undefined, { line: lineNumber, filePath: doc.fileName })
}
}
}
Expand Down
15 changes: 11 additions & 4 deletions src/core/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,8 @@ function getBibPath(bib: string, baseDir: string): string[] {
* function will rethrow the caught error, making the calling code responsible
* for handling the exception.
*
* @param {string} filePath - The path to the file to be read.
* @param {string | vscode.Uri} filePath - The path / Uri to the file to be
* read.
* @param {boolean} [raise=false] - A flag indicating whether to rethrow an
* error if the file read operation fails.
* @returns {Promise<string | undefined>} - A promise that resolves to the file
Expand All @@ -472,11 +473,17 @@ function getBibPath(bib: string, baseDir: string): string[] {
* @throws Will throw an error if the file read operation fails and `raise` is
* `true`.
*/
async function read(filePath: string, raise: boolean = false): Promise<string | undefined> {
async function read(fileUri: vscode.Uri, raise?: boolean): Promise<string | undefined>
async function read(filePath: string, raise?: boolean): Promise<string | undefined>
async function read(filePathOrUri: string | vscode.Uri, raise?: boolean): Promise<string | undefined> {
try {
return (await vscode.workspace.fs.readFile(vscode.Uri.file(filePath))).toString()
if (filePathOrUri instanceof vscode.Uri) {
return (await vscode.workspace.fs.readFile(filePathOrUri)).toString()
} else {
return (await vscode.workspace.fs.readFile(vscode.Uri.file(filePathOrUri))).toString()
}
} catch (err) {
if (raise === false) {
if (raise === undefined || raise === false) {
return undefined
}
throw err
Expand Down
10 changes: 5 additions & 5 deletions src/locate/synctex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,14 +182,14 @@ function parseToPDFList(result: string): SyncTeXRecordToPDFAll[] {
* document and cursor position. The forward SyncTeX can be executed with a
* specific PDF viewer, and the PDF file can be specified.
*
* @param pdfFile - The path of a PDF File compiled from the filePath of args.
* If undefined, it is automatically detected.
* @param args - The arguments of forward SyncTeX. If undefined, the document
* and cursor position of activeTextEditor are used.
* @param forcedViewer - Indicates a PDF viewer with which SyncTeX is executed
* ('auto', 'tabOrBrowser', or 'external').
* @param pdfFile - The path of a PDF File compiled from the filePath of args.
* If undefined, it is automatically detected.
*/
function toPDF(args?: {line: number, filePath: string}, forcedViewer: 'auto' | 'tabOrBrowser' | 'external' = 'auto', pdfFile?: string) {
function toPDF(pdfFile?: string, args?: {line: number, filePath: string}, forcedViewer: 'auto' | 'tabOrBrowser' | 'external' = 'auto') {
let line: number
let filePath: string
let character = 0
Expand Down Expand Up @@ -338,9 +338,9 @@ function toPDFFromRef(args: {line: number, filePath: string}) {
const viewer = configuration.get('view.pdf.ref.viewer') as 'auto' | 'tabOrBrowser' | 'external'
args.line += 1
if (viewer) {
toPDF(args, viewer)
toPDF(undefined, args, viewer)
} else {
toPDF(args)
toPDF(undefined, args)
}
}

Expand Down
36 changes: 19 additions & 17 deletions src/preview/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import * as vscode from 'vscode'
import * as http from 'http'
import type { AddressInfo } from 'net'
import ws from 'ws'
import * as fs from 'fs'
import * as path from 'path'
import { lw } from '../lw'

Expand Down Expand Up @@ -74,7 +73,7 @@ function getPort(): number {

async function getUrl(pdfUri?: vscode.Uri): Promise<{url: string, uri: vscode.Uri}> {
// viewer/viewer.js automatically requests the file to server.ts, and server.ts decodes the encoded path of PDF file.
const origUrl = await vscode.env.asExternalUri(vscode.Uri.parse(`http://127.0.0.1:${lw.server.getPort()}`, true))
const origUrl = await vscode.env.asExternalUri(vscode.Uri.parse(`http://127.0.0.1:${getPort()}`, true))
const url =
(origUrl.toString().endsWith('/') ? origUrl.toString().slice(0, -1) : origUrl.toString()) +
(pdfUri ? ('/viewer.html?file=' + encodePathWithPrefix(pdfUri)) : '')
Expand All @@ -96,11 +95,14 @@ function getValidOrigin(): string {
function initialize(hostname?: string): http.Server {
if (hostname) { // We must have created one.
state.httpServer.close()
state.address = undefined
}
const httpServer = http.createServer((request, response) => handler(request, response))
const configuration = vscode.workspace.getConfiguration('latex-workshop')
const viewerPort = configuration.get('viewer.pdf.internal.port') as number
const viewerPort = configuration.get('view.pdf.internal.port') as number
httpServer.listen(viewerPort, hostname ?? '127.0.0.1', undefined, async () => {
// Double set state to ensure the server is set
state.httpServer = httpServer
const address = state.httpServer.address()
if (address && typeof address !== 'string') {
state.address = address
Expand Down Expand Up @@ -197,11 +199,13 @@ async function handler(request: http.IncomingMessage, response: http.ServerRespo
const fileUri = decodePathWithPrefix(s)
if (!lw.viewer.isViewing(fileUri)) {
logger.log(`Invalid PDF request: ${fileUri.toString(true)}`)
response.writeHead(404)
response.end()
return
}
try {
const buf: Buffer = Buffer.from(await vscode.workspace.fs.readFile(fileUri))
sendOkResponse(response, buf, 'application/pdf')
const content = await vscode.workspace.fs.readFile(fileUri)
sendOkResponse(response, Buffer.from(content), 'application/pdf')
logger.log(`Preview PDF file: ${fileUri.toString(true)}`)
} catch (e) {
logger.logError(`Error reading PDF ${fileUri.toString(true)}`, e)
Expand All @@ -212,8 +216,7 @@ async function handler(request: http.IncomingMessage, response: http.ServerRespo
}
if (request.url.endsWith('/config.json')) {
const params = lw.viewer.getParams()
const content = JSON.stringify(params)
sendOkResponse(response, Buffer.from(content), 'application/json')
sendOkResponse(response, Buffer.from(JSON.stringify(params)), 'application/json')
return
}
let root: string
Expand Down Expand Up @@ -283,18 +286,17 @@ async function handler(request: http.IncomingMessage, response: http.ServerRespo
break
}
}
fs.readFile(fileName, (err, content) => {
if (err) {
if (err.code === 'ENOENT') {
response.writeHead(404)
} else {
response.writeHead(500)
}
response.end()
try {
const content = await vscode.workspace.fs.readFile(vscode.Uri.file(fileName))
sendOkResponse(response, Buffer.from(content), contentType, false)
} catch (err) {
if (typeof (err as any).code === 'string' && (err as any).code === 'FileNotFound') {
response.writeHead(404)
} else {
sendOkResponse(response, content, contentType, false)
response.writeHead(500)
}
})
response.end()
}
}

/**
Expand Down
Loading

0 comments on commit fef1a6b

Please sign in to comment.