Skip to content

Commit

Permalink
Merge pull request #3639 from modaresimr/fix-pdf-viewer-in-code-server
Browse files Browse the repository at this point in the history
Fix pdf viewer in code server
  • Loading branch information
James-Yu authored Jan 23, 2023
2 parents 1ca4bc8 + cd49ae2 commit c4c37f8
Show file tree
Hide file tree
Showing 7 changed files with 29 additions and 31 deletions.
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

0 comments on commit c4c37f8

Please sign in to comment.