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
308 lines (269 loc) · 15.1 KB
/
codeCssGenerator.ts
File metadata and controls
308 lines (269 loc) · 15.1 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import { JSONArray, JSONObject, JSONValue } from '@phosphor/coreutils';
import * as fs from 'fs-extra';
import { inject, injectable } from 'inversify';
import * as path from 'path';
import * as stripJsonComments from 'strip-json-comments';
import { IWorkspaceService } from '../common/application/types';
import { IConfigurationService, ILogger } from '../common/types';
import { DefaultTheme, Identifiers } from './constants';
import { ICodeCssGenerator, IThemeFinder } from './types';
// tslint:disable:no-any
const DarkTheme = 'dark';
const LightTheme = 'light';
// These are based on the colors generated by 'Default Light+' and are only set when we
// are ignoring themes.
//tslint:disable:no-multiline-string object-literal-key-quotes
const DefaultCssVars: { [key: string] : string } = {
LightTheme : `
:root {
--override-widget-background: #f3f3f3;
--override-foreground: #000000;
--override-background: #FFFFFF;
--override-selection-background: #add6ff;
--override-watermark-color: #cccedb;
--override-tabs-background: #f3f3f3;
--override-progress-background: #0066bf;
}
`,
DarkTheme : `
:root {
--override-widget-background: #1e1e1e;
--override-foreground: #d4d4d4;
--override-background: #1e1e1e;
--override-selection-background: #264f78;
--override-watermark-color: #3f3f46;
--override-tabs-background: #252526;
--override-progress-background: #0066bf;
}
`
};
// These colors below should match colors that come from either the Default Light+ theme or the Default Dark+ theme.
// They are used when we can't find a theme json file.
const DefaultColors: { [key: string] : string } = {
'light.comment' : '#008000',
'light.constant.numeric': '#09885a',
'light.string' : '#a31515',
'light.keyword.control' : '#AF00DB',
'light.keyword.operator': '#000000',
'light.variable' : '#001080',
'light.entity.name.type': '#267f99',
'light.support.function': '#795E26',
'light.punctuation' : '#000000',
'dark.comment' : '#6A9955',
'dark.constant.numeric' : '#b5cea8',
'dark.string' : '#ce9178',
'dark.keyword.control' : '#C586C0',
'dark.keyword.operator' : '#d4d4d4',
'dark.variable' : '#9CDCFE',
'dark.entity.name.type' : '#4EC9B0',
'dark.support.function' : '#DCDCAA',
'dark.punctuation' : '#1e1e1e'
};
// 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(IThemeFinder) private themeFinder: IThemeFinder,
@inject(IConfigurationService) private configService: IConfigurationService,
@inject(ILogger) private logger: ILogger) {
}
public async generateThemeCss(isDark: boolean, theme: string): Promise<string> {
let css : string = '';
try {
// First compute our current theme.
const workbench = this.workspaceService.getConfiguration('workbench');
const ignoreTheme = this.configService.getSettings().datascience.ignoreVscodeTheme ? true : false;
theme = ignoreTheme ? DefaultTheme : theme;
const terminalCursor = workbench ? workbench.get<string>('terminal.integrated.cursorStyle', 'block') : 'block';
const editor = this.workspaceService.getConfiguration('editor', undefined);
const font = editor ? editor.get<string>('fontFamily', 'Consolas, \'Courier New\', monospace') : 'Consolas, \'Courier New\', monospace';
const fontSize = editor ? editor.get<number>('fontSize', 14) : 14;
// Then we have to find where the theme resources are loaded from
if (theme) {
this.logger.logInformation('Searching for token colors ...');
const tokenColors = await this.findTokenColors(theme);
// The tokens object then contains the necessary data to generate our css
if (tokenColors && font && fontSize) {
this.logger.logInformation('Using colors to generate CSS ...');
css = this.generateCss(theme, tokenColors, font, fontSize, terminalCursor, ignoreTheme ? LightTheme : undefined);
} else if (tokenColors === null && font && fontSize) {
// No colors found. See if we can figure out what type of theme we have
const style = isDark ? DarkTheme : LightTheme ;
css = this.generateCss(theme, null, font, fontSize, terminalCursor, style);
}
}
} catch (err) {
// On error don't fail, just log
this.logger.logError(err);
}
return css;
}
private matchTokenColor(tokenColors: JSONArray, scope: string) : number {
return tokenColors.findIndex((entry: any) => {
if (entry) {
const scopes = entry.scope as JSONValue;
if (scopes) {
const scopeArray = Array.isArray(scope) ? scopes as JSONArray : scopes.toString().split(',');
if (scopeArray.find(v => v !== null && v !== undefined && v.toString().trim() === scope)) {
return true;
}
}
}
return false;
});
}
private getScopeStyle = (tokenColors: JSONArray | null, scope: string, secondary: string, defaultStyle: string | undefined): { color: string; fontStyle: string } => {
// Search through the scopes on the json object
if (tokenColors) {
let match = this.matchTokenColor(tokenColors, scope);
if (match < 0 && secondary) {
match = this.matchTokenColor(tokenColors, secondary);
}
const found = match >= 0 ? tokenColors[match] as any : null;
if (found !== null) {
const settings = found.settings;
if (settings && settings !== null) {
const fontStyle = settings.fontStyle ? settings.fontStyle : 'normal';
const foreground = settings.foreground ? settings.foreground : 'var(--vscode-editor-foreground)';
return { fontStyle, color: foreground };
}
}
}
// Default to editor foreground
return { color: this.getDefaultColor(defaultStyle, scope), fontStyle: 'normal' };
}
private getDefaultColor(style: string | undefined, scope: string) : string {
return style ? DefaultColors[`${style}.${scope}`] : 'var(--override-foreground, var(--vscode-editor-foreground))';
}
// tslint:disable-next-line:max-func-body-length
private generateCss(theme: string, tokenColors: JSONArray | null, fontFamily: string, fontSize: number, cursorType: string, defaultStyle: string | undefined): string {
const escapedThemeName = Identifiers.GeneratedThemeName;
// There's a set of values that need to be found
const commentStyle = this.getScopeStyle(tokenColors, 'comment', 'comment', defaultStyle);
const numericStyle = this.getScopeStyle(tokenColors, 'constant.numeric', 'constant', defaultStyle);
const stringStyle = this.getScopeStyle(tokenColors, 'string', 'string', defaultStyle);
const keywordStyle = this.getScopeStyle(tokenColors, 'keyword.control', 'keyword', defaultStyle);
const operatorStyle = this.getScopeStyle(tokenColors, 'keyword.operator', 'keyword', defaultStyle);
const variableStyle = this.getScopeStyle(tokenColors, 'variable', 'variable', defaultStyle);
const entityTypeStyle = this.getScopeStyle(tokenColors, 'entity.name.type', 'entity.name.type', defaultStyle);
// const atomic = this.getScopeColor(tokenColors, 'atomic');
const builtinStyle = this.getScopeStyle(tokenColors, 'support.function', 'support.function', defaultStyle);
const punctuationStyle = this.getScopeStyle(tokenColors, 'punctuation', 'punctuation', defaultStyle);
const def = 'var(--vscode-editor-foreground)';
// Define our cursor style based on the cursor type
const cursorStyle = cursorType === 'block' ?
`{ border: 1px solid ${def}; background: ${def}; width: 5px; z-index=100; }` : cursorType === 'underline' ?
`{ border-bottom: 1px solid ${def}; z-index=100; width: 5px; }` :
`{ border-left: 1px solid ${def}; border-right: none; z-index=100; }`;
// Use these values to fill in our format string
return `
:root {
--code-comment-color: ${commentStyle.color};
--code-numeric-color: ${numericStyle.color};
--code-string-color: ${stringStyle.color};
--code-variable-color: ${variableStyle.color};
--code-type-color: ${entityTypeStyle.color};
--code-font-family: ${fontFamily};
--code-font-size: ${fontSize}px;
}
${defaultStyle ? DefaultCssVars[defaultStyle] : undefined }
.cm-header, .cm-strong {font-weight: bold;}
.cm-em {font-style: italic;}
.cm-link {text-decoration: underline;}
.cm-strikethrough {text-decoration: line-through;}
.cm-s-${escapedThemeName} span.cm-keyword {color: ${keywordStyle.color}; font-style: ${keywordStyle.fontStyle}; }
.cm-s-${escapedThemeName} span.cm-number {color: ${numericStyle.color}; font-style: ${numericStyle.fontStyle}; }
.cm-s-${escapedThemeName} span.cm-def {color: ${def}; }
.cm-s-${escapedThemeName} span.cm-variable {color: ${variableStyle.color}; font-style: ${variableStyle.fontStyle}; }
.cm-s-${escapedThemeName} span.cm-punctuation {color: ${punctuationStyle.color}; font-style: ${punctuationStyle.fontStyle}; }
.cm-s-${escapedThemeName} span.cm-property,
.cm-s-${escapedThemeName} span.cm-operator {color: ${operatorStyle.color}; font-style: ${operatorStyle.fontStyle}; }
.cm-s-${escapedThemeName} span.cm-variable-2 {color: ${variableStyle.color}; font-style: ${variableStyle.fontStyle}; }
.cm-s-${escapedThemeName} span.cm-variable-3, .cm-s-${theme} .cm-type {color: ${variableStyle.color}; font-style: ${variableStyle.fontStyle}; }
.cm-s-${escapedThemeName} span.cm-comment {color: ${commentStyle.color}; font-style: ${commentStyle.fontStyle}; }
.cm-s-${escapedThemeName} span.cm-string {color: ${stringStyle.color}; font-style: ${stringStyle.fontStyle}; }
.cm-s-${escapedThemeName} span.cm-string-2 {color: ${stringStyle.color}; font-style: ${stringStyle.fontStyle}; }
.cm-s-${escapedThemeName} span.cm-builtin {color: ${builtinStyle.color}; font-style: ${builtinStyle.fontStyle}; }
.cm-s-${escapedThemeName} div.CodeMirror-cursor ${cursorStyle}
.cm-s-${escapedThemeName} div.CodeMirror-selected {background: var(--vscode-editor-selectionBackground) !important;}
`;
}
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(stripJsonComments(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;
}
// Might also have a 'settings' object that equates to token colors
const settings = theme.settings as JSONArray;
if (settings && settings.length > 0) {
return settings;
}
return [];
}
private findTokenColors = async (theme: string): Promise<JSONArray | null> => {
try {
this.logger.logInformation('Attempting search for colors ...');
const themeRoot = await this.themeFinder.findThemeRootJson(theme);
// Use the first result if we have one
if (themeRoot) {
this.logger.logInformation(`Loading colors from ${themeRoot} ...`);
// This should be the path to the file. Load it as a json object
const contents = await fs.readFile(themeRoot, 'utf8');
const json = JSON.parse(stripJsonComments(contents)) as JSONObject;
// There should be a theme colors section
const contributes = json.contributes as JSONObject;
// If no contributes section, see if we have a tokenColors section. This means
// this is a direct token colors file
if (!contributes) {
const tokenColors = json.tokenColors as JSONObject;
if (tokenColors) {
return await this.readTokenColors(themeRoot);
}
}
// 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: any) => {
return e !== null && (e.id === theme || e.name === theme);
});
const found = index >= 0 ? themes[index] as any : 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(themeRoot), found.path);
this.logger.logInformation(`Reading colors from ${themeFile}`);
return await this.readTokenColors(themeFile);
}
} else {
this.logger.logWarning(`Color theme ${theme} not found. Using default colors.`);
}
} catch (err) {
// Swallow any exceptions with searching or parsing
this.logger.logError(err);
}
// Force the colors to the defaults
return null;
}
}