Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix pdf viewer in code server #3639

Merged
merged 6 commits into from
Jan 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions dev/editviewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
fout.write(
line.replace('''<title>PDF.js viewer</title>''', '''<meta http-equiv="Content-Security-Policy" content="default-src 'self'; base-uri 'none'; connect-src 'self' ws://127.0.0.1:*; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:;">\n <title>PDF.js viewer</title>''')
.replace('''<link rel="stylesheet" href="viewer.css">''', '''<link rel="stylesheet" href="viewer.css">\n <link rel="stylesheet" href="latexworkshop.css">''')
.replace('''<script src="../build/pdf.js"></script>''', '''<script src="/build/pdf.js" defer></script>''')
.replace('''<script src="viewer.js"></script>''', '''<script src="/out/viewer/latexworkshop.js" type="module"></script>''')
.replace('''<script src="../build/pdf.js"></script>''', '''<script src="build/pdf.js" defer></script>''')
.replace('''<script src="viewer.js"></script>''', '''<script src="out/viewer/latexworkshop.js" type="module"></script>''')
)

with open(args.web + '/viewer.js', 'rt') as fin:
Expand Down
9 changes: 8 additions & 1 deletion src/components/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ export class Server {
return portNum
}

async getViewerUrl(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.port}`, true))
const url = origUrl.toString() + (origUrl.toString().endsWith('/') ? '' : '/' ) + `viewer.html?file=${PdfFilePathEncoder.encodePathWithPrefix(pdfUri)}`
return { url, uri: vscode.Uri.parse(url, true) }
}

private get validOrigin(): string {
if (this.validOriginUri) {
return `${this.validOriginUri.scheme}://${this.validOriginUri.authority}`
Expand Down Expand Up @@ -177,7 +184,7 @@ export class Server {
}
return
}
if (request.url === '/config.json') {
if (request.url.endsWith('/config.json')) {
const params = lw.viewer.viewerParams()
const content = JSON.stringify(params)
this.sendOkResponse(response, Buffer.from(content), 'application/json')
Expand Down
12 changes: 5 additions & 7 deletions src/components/viewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import { PdfViewerPanelSerializer, PdfViewerPanelService } from './viewerlib/pdf
import { PdfViewerManagerService } from './viewerlib/pdfviewermanager'
import { ViewerPageLoaded } from './eventbus'
import { getLogger } from './logger'
import { PdfFilePathEncoder } from './serverlib/encodepath'
import { moveActiveEditor } from '../utils/webview'

const logger = getLogger('Viewer')
Expand Down Expand Up @@ -51,14 +50,13 @@ export class Viewer {
}

private async checkViewer(sourceFile: string): Promise<string | undefined> {
const pdfFile = this.tex2pdf(sourceFile)
if (!await lw.lwfs.exists(pdfFile)) {
logger.log(`Cannot find PDF file ${pdfFile}`)
logger.refreshStatus('check', 'statusBar.foreground', `Cannot view file PDF file. File not found: ${pdfFile}`, 'warning')
const pdfUri = this.tex2pdf(sourceFile)
if (!await lw.lwfs.exists(pdfUri)) {
logger.log(`Cannot find PDF file ${pdfUri}`)
logger.refreshStatus('check', 'statusBar.foreground', `Cannot view file PDF file. File not found: ${pdfUri}`, 'warning')
return
}
const url = `http://127.0.0.1:${lw.server.port}/viewer.html?file=${PdfFilePathEncoder.encodePathWithPrefix(pdfFile)}`
return url
return (await lw.server.getViewerUrl(pdfUri)).url
}

/**
Expand Down
20 changes: 6 additions & 14 deletions src/components/viewerlib/pdfviewerpanel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {PdfViewerManagerService} from './pdfviewermanager'
import {ViewerStatusChanged} from '../eventbus'

import { getLogger } from '../logger'
import { PdfFilePathEncoder } from '../serverlib/encodepath'

const logger = getLogger('Viewer', 'Panel')

Expand Down Expand Up @@ -71,10 +70,6 @@ export class PdfViewerPanelSerializer implements vscode.WebviewPanelSerializer {
export class PdfViewerPanelService {
private static alreadyOpened = false

private static encodePathWithPrefix(pdfFileUri: vscode.Uri): string {
return PdfFilePathEncoder.encodePathWithPrefix(pdfFileUri)
}

private static async tweakForCodespaces(url: vscode.Uri) {
if (this.alreadyOpened) {
return
Expand Down Expand Up @@ -119,16 +114,13 @@ export class PdfViewerPanelService {
/**
* Returns the HTML content of the internal PDF viewer.
*
* @param pdfFile The path of a PDF file to be opened.
* @param pdfUri The path of a PDF file to be opened.
*/
static async getPDFViewerContent(pdfFile: vscode.Uri): Promise<string> {
const serverPort = lw.server.port
// viewer/viewer.js automatically requests the file to server.ts, and server.ts decodes the encoded path of PDF file.
const origUrl = `http://127.0.0.1:${serverPort}/viewer.html?file=${this.encodePathWithPrefix(pdfFile)}`
const url = await vscode.env.asExternalUri(vscode.Uri.parse(origUrl, true))
const iframeSrcOrigin = `${url.scheme}://${url.authority}`
const iframeSrcUrl = url.toString(true)
await this.tweakForCodespaces(url)
static async getPDFViewerContent(pdfUri: vscode.Uri): Promise<string> {
const uri = (await lw.server.getViewerUrl(pdfUri)).uri
const iframeSrcOrigin = `${uri.scheme}://${uri.authority}`
const iframeSrcUrl = uri.toString(true)
await this.tweakForCodespaces(uri)
logger.log(`Internal PDF viewer at ${iframeSrcUrl} .`)
const rebroadcast: boolean = this.getKeyboardEventConfig()
return `
Expand Down
3 changes: 2 additions & 1 deletion viewer/components/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ export class WebSocketPort implements IConnectionPort {
constructor(lwApp: ILatexWorkshopPdfViewer) {
this.lwApp = lwApp
const scheme = 'https:' === window.location.protocol ? 'wss' : 'ws'
const server = `${scheme}://${window.location.hostname}:${window.location.port}`
const path = window.location.pathname.substring(0, window.location.pathname.indexOf('viewer.html'))
const server = `${scheme}://${window.location.hostname}:${window.location.port}${path}`
this.server = server
this.socket = new Promise((resolve, reject) => {
const sock = new WebSocket(server)
Expand Down
8 changes: 4 additions & 4 deletions viewer/latexworkshop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ class LateXWorkshopPdfViewer implements ILatexWorkshopPdfViewer {
}

private async fetchParams(): Promise<PdfViewerParams> {
const response = await fetch('/config.json')
const response = await fetch('config.json')
const params = await response.json() as PdfViewerParams
return params
}
Expand All @@ -182,7 +182,7 @@ class LateXWorkshopPdfViewer implements ILatexWorkshopPdfViewer {
}

private async setupAppOptions() {
const workerPort = new Worker('/build/pdf.worker.js')
const workerPort = new Worker('build/pdf.worker.js')
const params = await this.fetchParams()
document.addEventListener('webviewerloaded', () => {
const color = this.isPrefersColorSchemeDark(params.codeColorTheme) ? params.color.dark : params.color.light
Expand All @@ -194,7 +194,7 @@ class LateXWorkshopPdfViewer implements ILatexWorkshopPdfViewer {
sidebarViewOnLoad: 0,
standardFontDataUrl: '/standard_fonts/',
workerPort,
workerSrc: '/build/pdf.worker.js',
workerSrc: 'build/pdf.worker.js',
forcePageColors: true,
...color
}
Expand Down Expand Up @@ -724,4 +724,4 @@ class LateXWorkshopPdfViewer implements ILatexWorkshopPdfViewer {
const extension = new LateXWorkshopPdfViewer()
await extension.waitSetupAppOptionsFinished()
// @ts-expect-error
await import('/viewer.js')
await import('../../viewer/viewer.js')
4 changes: 2 additions & 2 deletions viewer/viewer.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@

<!-- This snippet is used in production (included from viewer.html) -->
<link rel="resource" type="application/l10n" href="locale/locale.properties">
<script src="/build/pdf.js" defer></script>
<script src="build/pdf.js" defer></script>

<script src="/out/viewer/latexworkshop.js" type="module"></script>
<script src="out/viewer/latexworkshop.js" type="module"></script>

</head>

Expand Down