forked from irinazheltisheva/vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreview.ts
More file actions
266 lines (221 loc) · 8.41 KB
/
preview.ts
File metadata and controls
266 lines (221 loc) · 8.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import { Disposable } from './dispose';
import { SizeStatusBarEntry } from './sizeStatusBarEntry';
import { Scale, ZoomStatusBarEntry } from './zoomStatusBarEntry';
import { BinarySizeStatusBarEntry } from './binarySizeStatusBarEntry';
const localize = nls.loadMessageBundle();
export class PreviewManager implements vscode.CustomReadonlyEditorProvider {
public static readonly viewType = 'imagePreview.previewEditor';
private readonly _previews = new Set<Preview>();
private _activePreview: Preview | undefined;
constructor(
private readonly extensionRoot: vscode.Uri,
private readonly sizeStatusBarEntry: SizeStatusBarEntry,
private readonly binarySizeStatusBarEntry: BinarySizeStatusBarEntry,
private readonly zoomStatusBarEntry: ZoomStatusBarEntry,
) { }
public async openCustomDocument(uri: vscode.Uri) {
return { uri, dispose: () => { } };
}
public async resolveCustomEditor(
document: vscode.CustomDocument,
webviewEditor: vscode.WebviewPanel,
): Promise<void> {
const preview = new Preview(this.extensionRoot, document.uri, webviewEditor, this.sizeStatusBarEntry, this.binarySizeStatusBarEntry, this.zoomStatusBarEntry);
this._previews.add(preview);
this.setActivePreview(preview);
webviewEditor.onDidDispose(() => { this._previews.delete(preview); });
webviewEditor.onDidChangeViewState(() => {
if (webviewEditor.active) {
this.setActivePreview(preview);
} else if (this._activePreview === preview && !webviewEditor.active) {
this.setActivePreview(undefined);
}
});
}
public get activePreview() { return this._activePreview; }
private setActivePreview(value: Preview | undefined): void {
this._activePreview = value;
this.setPreviewActiveContext(!!value);
}
private setPreviewActiveContext(value: boolean) {
vscode.commands.executeCommand('setContext', 'imagePreviewFocus', value);
}
}
const enum PreviewState {
Disposed,
Visible,
Active,
}
class Preview extends Disposable {
private readonly id: string = `${Date.now()}-${Math.random().toString()}`;
private _previewState = PreviewState.Visible;
private _imageSize: string | undefined;
private _imageBinarySize: number | undefined;
private _imageZoom: Scale | undefined;
private readonly emptyPngDataUri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR42gEFAPr/AP///wAI/AL+Sr4t6gAAAABJRU5ErkJggg==';
constructor(
private readonly extensionRoot: vscode.Uri,
private readonly resource: vscode.Uri,
private readonly webviewEditor: vscode.WebviewPanel,
private readonly sizeStatusBarEntry: SizeStatusBarEntry,
private readonly binarySizeStatusBarEntry: BinarySizeStatusBarEntry,
private readonly zoomStatusBarEntry: ZoomStatusBarEntry,
) {
super();
const resourceRoot = resource.with({
path: resource.path.replace(/\/[^\/]+?\.\w+$/, '/'),
});
webviewEditor.webview.options = {
enableScripts: true,
localResourceRoots: [
resourceRoot,
extensionRoot,
]
};
this._register(webviewEditor.webview.onDidReceiveMessage(message => {
switch (message.type) {
case 'size':
{
this._imageSize = message.value;
this.update();
break;
}
case 'zoom':
{
this._imageZoom = message.value;
this.update();
break;
}
case 'reopen-as-text':
{
vscode.commands.executeCommand('vscode.openWith', resource, 'default', webviewEditor.viewColumn);
break;
}
}
}));
this._register(zoomStatusBarEntry.onDidChangeScale(e => {
if (this._previewState === PreviewState.Active) {
this.webviewEditor.webview.postMessage({ type: 'setScale', scale: e.scale });
}
}));
this._register(webviewEditor.onDidChangeViewState(() => {
this.update();
this.webviewEditor.webview.postMessage({ type: 'setActive', value: this.webviewEditor.active });
}));
this._register(webviewEditor.onDidDispose(() => {
if (this._previewState === PreviewState.Active) {
this.sizeStatusBarEntry.hide(this.id);
this.binarySizeStatusBarEntry.hide(this.id);
this.zoomStatusBarEntry.hide(this.id);
}
this._previewState = PreviewState.Disposed;
}));
const watcher = this._register(vscode.workspace.createFileSystemWatcher(resource.fsPath));
this._register(watcher.onDidChange(e => {
if (e.toString() === this.resource.toString()) {
this.render();
}
}));
this._register(watcher.onDidDelete(e => {
if (e.toString() === this.resource.toString()) {
this.webviewEditor.dispose();
}
}));
vscode.workspace.fs.stat(resource).then(({ size }) => {
this._imageBinarySize = size;
this.update();
});
this.render();
this.update();
this.webviewEditor.webview.postMessage({ type: 'setActive', value: this.webviewEditor.active });
}
public zoomIn() {
if (this._previewState === PreviewState.Active) {
this.webviewEditor.webview.postMessage({ type: 'zoomIn' });
}
}
public zoomOut() {
if (this._previewState === PreviewState.Active) {
this.webviewEditor.webview.postMessage({ type: 'zoomOut' });
}
}
private async render() {
if (this._previewState !== PreviewState.Disposed) {
this.webviewEditor.webview.html = await this.getWebviewContents();
}
}
private update() {
if (this._previewState === PreviewState.Disposed) {
return;
}
if (this.webviewEditor.active) {
this._previewState = PreviewState.Active;
this.sizeStatusBarEntry.show(this.id, this._imageSize || '');
this.binarySizeStatusBarEntry.show(this.id, this._imageBinarySize);
this.zoomStatusBarEntry.show(this.id, this._imageZoom || 'fit');
} else {
if (this._previewState === PreviewState.Active) {
this.sizeStatusBarEntry.hide(this.id);
this.binarySizeStatusBarEntry.hide(this.id);
this.zoomStatusBarEntry.hide(this.id);
}
this._previewState = PreviewState.Visible;
}
}
private async getWebviewContents(): Promise<string> {
const version = Date.now().toString();
const settings = {
isMac: process.platform === 'darwin',
src: await this.getResourcePath(this.webviewEditor, this.resource, version),
};
const nonce = Date.now().toString();
return /* html */`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- Disable pinch zooming -->
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<title>Image Preview</title>
<link rel="stylesheet" href="${escapeAttribute(this.extensionResource('/media/main.css'))}" type="text/css" media="screen" nonce="${nonce}">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' data: ${this.webviewEditor.webview.cspSource}; script-src 'nonce-${nonce}'; style-src 'self' 'nonce-${nonce}';">
<meta id="image-preview-settings" data-settings="${escapeAttribute(JSON.stringify(settings))}">
</head>
<body class="container image scale-to-fit loading">
<div class="loading-indicator"></div>
<div class="image-load-error">
<p>${localize('preview.imageLoadError', "An error occurred while loading the image.")}</p>
<a href="#" class="open-file-link">${localize('preview.imageLoadErrorLink', "Open file using VS Code's standard text/binary editor?")}</a>
</div>
<script src="${escapeAttribute(this.extensionResource('/media/main.js'))}" nonce="${nonce}"></script>
</body>
</html>`;
}
private async getResourcePath(webviewEditor: vscode.WebviewPanel, resource: vscode.Uri, version: string): Promise<string> {
if (resource.scheme === 'git') {
const stat = await vscode.workspace.fs.stat(resource);
if (stat.size === 0) {
return this.emptyPngDataUri;
}
}
// Avoid adding cache busting if there is already a query string
if (resource.query) {
return webviewEditor.webview.asWebviewUri(resource).toString();
}
return webviewEditor.webview.asWebviewUri(resource).with({ query: `version=${version}` }).toString();
}
private extensionResource(path: string) {
return this.webviewEditor.webview.asWebviewUri(this.extensionRoot.with({
path: this.extensionRoot.path + path
}));
}
}
function escapeAttribute(value: string | vscode.Uri): string {
return value.toString().replace(/"/g, '"');
}