forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodeCssGenerator.ts
More file actions
323 lines (277 loc) · 11.3 KB
/
codeCssGenerator.ts
File metadata and controls
323 lines (277 loc) · 11.3 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import { JSONArray, JSONObject, JSONValue } from '@phosphor/coreutils';
import { FindOptions } from 'file-matcher';
import * as fs from 'fs-extra';
import { inject, injectable } from 'inversify';
import * as path from 'path';
import { IWorkspaceService } from '../common/application/types';
import { ICurrentProcess, ILogger } from '../common/types';
import { EXTENSION_ROOT_DIR } from '../constants';
import { ICodeCssGenerator } from './types';
// This class generates css using the current theme in order to colorize code.
//
// NOTE: This is all a big hack. It's relying on the theme json files to have a certain format
// in order for this to work.
// See this vscode issue for the real way we think this should happen:
// https://github.com/Microsoft/vscode/issues/32813
@injectable()
export class CodeCssGenerator implements ICodeCssGenerator {
constructor(
@inject(IWorkspaceService) private workspaceService: IWorkspaceService,
@inject(ICurrentProcess) private currentProcess: ICurrentProcess,
@inject(ILogger) private logger: ILogger) {
}
public generateThemeCss = async (): Promise<string> => {
try {
// First compute our current theme.
const workbench = this.workspaceService.getConfiguration('workbench');
const theme = workbench.get<string>('colorTheme');
const editor = this.workspaceService.getConfiguration('editor', undefined);
const font = editor.get<string>('fontFamily');
const fontSize = editor.get<number>('fontSize');
// Then we have to find where the theme resources are loaded from
if (theme) {
const tokenColors = await this.findTokenColors(theme);
// The tokens object then contains the necessary data to generate our css
if (tokenColors && font && fontSize) {
return this.generateCss(tokenColors, font, fontSize);
}
}
} catch (err) {
// On error don't fail, just log
this.logger.logError(err);
}
return '';
}
private getScopeColor = (tokenColors: JSONArray, scope: string): string => {
// Search through the scopes on the json object
const match = tokenColors.findIndex(entry => {
if (entry) {
const scopes = entry['scope'] as JSONValue;
if (scopes && Array.isArray(scopes)) {
if (scopes.find(v => v !== null && v.toString() === scope)) {
return true;
}
} else if (scopes && scopes.toString() === scope) {
return true;
}
}
return false;
});
const found = match >= 0 ? tokenColors[match] : null;
if (found !== null) {
const settings = found['settings'];
if (settings && settings !== null) {
return settings['foreground'];
}
}
// Default to editor foreground
return 'var(--vscode-editor-foreground)';
}
// tslint:disable-next-line:max-func-body-length
private generateCss = (tokenColors: JSONArray, fontFamily: string, fontSize: number): string => {
// There's a set of values that need to be found
const comment = this.getScopeColor(tokenColors, 'comment');
const numeric = this.getScopeColor(tokenColors, 'constant.numeric');
const stringColor = this.getScopeColor(tokenColors, 'string');
const keyword = this.getScopeColor(tokenColors, 'keyword');
const operator = this.getScopeColor(tokenColors, 'keyword.operator');
const variable = this.getScopeColor(tokenColors, 'variable');
const def = 'var(--vscode-editor-foreground)';
// Use these values to fill in our format string
return `
:root {
--comment-color: ${comment}
}
code[class*="language-"],
pre[class*="language-"] {
color: ${def};
background: none;
text-shadow: none;
font-family: ${fontFamily};
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
font-size: ${fontSize}px;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
}
pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection,
code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection {
text-shadow: none;
background: var(--vscode-editor-selectionBackground);
}
pre[class*="language-"]::selection, pre[class*="language-"] ::selection,
code[class*="language-"]::selection, code[class*="language-"] ::selection {
text-shadow: none;
background: var(--vscode-editor-selectionBackground);
}
@media print {
code[class*="language-"],
pre[class*="language-"] {
text-shadow: none;
}
}
/* Code blocks */
pre[class*="language-"] {
padding: 1em;
margin: .5em 0;
overflow: auto;
}
:not(pre) > code[class*="language-"],
pre[class*="language-"] {
background: transparent;
}
/* Inline code */
:not(pre) > code[class*="language-"] {
padding: .1em;
border-radius: .3em;
white-space: normal;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: ${comment};
}
.token.punctuation {
color: ${def};
}
.namespace {
opacity: .7;
}
.token.property,
.token.tag,
.token.boolean,
.token.number,
.token.constant,
.token.symbol,
.token.deleted {
color: ${numeric};
}
.token.selector,
.token.attr-name,
.token.string,
.token.char,
.token.builtin,
.token.inserted {
color: ${stringColor};
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string {
color: ${operator};
background: transparent;
}
.token.atrule,
.token.attr-value,
.token.keyword {
color: ${keyword};
}
.token.function,
.token.class-name {
color: ${keyword};
}
.token.regex,
.token.important,
.token.variable {
color: ${variable};
}
.token.important,
.token.bold {
font-weight: bold;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}
`;
}
private mergeColors = (colors1: JSONArray, colors2: JSONArray): JSONArray => {
return [...colors1, ...colors2];
}
private readTokenColors = async (themeFile: string): Promise<JSONArray> => {
const tokenContent = await fs.readFile(themeFile, 'utf8');
const theme = JSON.parse(tokenContent) as JSONObject;
const tokenColors = theme['tokenColors'] as JSONArray;
if (tokenColors && tokenColors.length > 0) {
// This theme may include others. If so we need to combine the two together
const include = theme ? theme['include'] : undefined;
if (include && include !== null) {
const includePath = path.join(path.dirname(themeFile), include.toString());
const includedColors = await this.readTokenColors(includePath);
return this.mergeColors(tokenColors, includedColors);
}
// Theme is a root, don't need to include others
return tokenColors;
}
return [];
}
private findTokenColors = async (theme: string): Promise<JSONArray> => {
const currentExe = this.currentProcess.execPath;
let currentPath = path.dirname(currentExe);
// Should be somewhere under currentPath/resources/app/extensions inside of a json file
let extensionsPath = path.join(currentPath, 'resources', 'app', 'extensions');
if (!(await fs.pathExists(extensionsPath))) {
// Might be on mac or linux. try a different path
currentPath = path.resolve(currentPath, '../../../..');
extensionsPath = path.join(currentPath, 'resources', 'app', 'extensions');
}
// Search through all of the json files for the theme name
const escapedThemeName = theme.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
const searchOptions: FindOptions = {
path: extensionsPath,
recursiveSearch: true,
fileFilter: {
fileNamePattern: '**/*.json',
content: new RegExp(`id[',"]:\\s*[',"]${escapedThemeName}[',"]`)
}
};
// tslint:disable-next-line:no-require-imports
const fm = require('file-matcher') as typeof import('file-matcher');
const matcher = new fm.FileMatcher();
try {
const results = await matcher.find(searchOptions);
// Use the first result if we have one
if (results && results.length > 0) {
// This should be the path to the file. Load it as a json object
const contents = await fs.readFile(results[0], 'utf8');
const json = JSON.parse(contents) as JSONObject;
// There should be a contributes section
const contributes = json['contributes'] as JSONObject;
// This should have a themes section
const themes = contributes['themes'] as JSONArray;
// One of these (it's an array), should have our matching theme entry
const index = themes.findIndex(e => {
return e !== null && e['id'] === theme;
});
const found = index >= 0 ? themes[index] : null;
if (found !== null) {
// Then the path entry should contain a relative path to the json file with
// the tokens in it
const themeFile = path.join(path.dirname(results[0]), found['path']);
return await this.readTokenColors(themeFile);
}
}
} catch (err) {
// Swallow any exceptions with searching or parsing
this.logger.logError(err);
}
// We should return a default. The vscode-light theme
const defaultThemeFile = path.join(EXTENSION_ROOT_DIR, 'resources', 'defaultTheme.json');
return this.readTokenColors(defaultThemeFile);
}
}