-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathindex.js
623 lines (516 loc) · 21.6 KB
/
index.js
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
var vscode = require('vscode');
var fs = require('mz/fs');
var fsExtra = require('fs-extra');
var path = require('path');
var { pathToFileURL } = require('url')
/**
* @type {(info: string) => string}
*/
const localize = require('./i18n');
/**
* @type {'unknown' | 'win10' | 'macos'}
*/
const os = require('./platform');
var themeStylePaths = {
'Default Dark': '../themes/Default Dark.css',
'Dark (Exclude Tab Line)': '../themes/Dark (Exclude Tab Line).css',
'Dark (Only Subbar)': '../themes/Dark (Only Subbar).css',
'Default Light': '../themes/Default Light.css',
'Light (Only Subbar)': '../themes/Light (Only Subbar).css',
'Tokyo Night Storm': '../themes/Tokyo Night Storm.css',
'Tokyo Night Storm (Outer)': '../themes/Tokyo Night Storm (Outer).css',
'Noir et blanc': '../themes/Noir et blanc.css',
'Solarized Dark+': '../themes/Solarized Dark+.css',
'Catppuccin Mocha': '../themes/Catppuccin Mocha.css',
'GitHub Dark Default': '../themes/GitHub Dark Default.css',
'Custom theme (use imports)': '../themes/Custom Theme.css',
}
const themeConfigPaths = {
'Default Dark': '../themes/Default Dark.json',
'Dark (Exclude Tab Line)': '../themes/Dark (Exclude Tab Line).json',
'Dark (Only Subbar)': '../themes/Dark (Only Subbar).json',
'Default Light': '../themes/Default Light.json',
'Light (Only Subbar)': '../themes/Light (Only Subbar).json',
'Tokyo Night Storm': '../themes/Tokyo Night Storm.json',
'Tokyo Night Storm (Outer)': '../themes/Tokyo Night Storm (Outer).json',
'Noir et blanc': '../themes/Noir et blanc.json',
'Solarized Dark+': '../themes/Solarized Dark+.json',
'Catppuccin Mocha': '../themes/Catppuccin Mocha.json',
'GitHub Dark Default': '../themes/GitHub Dark Default.json',
'Custom theme (use imports)': '../themes/Custom Theme.json',
}
var defaultTheme = 'Default Dark';
function getCurrentTheme(config) {
return config.theme in themeStylePaths ? config.theme : defaultTheme;
}
function checkDarkLightMode(theme) {
const enableAutoTheme = vscode.workspace.getConfiguration().get("vscode_vibrancy.enableAutoTheme");
if (!enableAutoTheme) return;
const currentTheme = theme.kind;
const currentColorTheme = vscode.workspace.getConfiguration().get("vscode_vibrancy.theme");
const preferredDarkColorTheme = vscode.workspace.getConfiguration().get("vscode_vibrancy.preferedDarkTheme");
const preferredLightColorTheme = vscode.workspace.getConfiguration().get("vscode_vibrancy.preferedLightTheme");
let targetVibrancyTheme;
if (currentTheme === vscode.ColorThemeKind.Dark) {
targetVibrancyTheme = preferredDarkColorTheme;
} else if (currentTheme === vscode.ColorThemeKind.Light) {
targetVibrancyTheme = preferredLightColorTheme;}
else {
return;
}
if (currentColorTheme !== targetVibrancyTheme) {
vscode.workspace.getConfiguration("vscode_vibrancy").update("theme", targetVibrancyTheme, vscode.ConfigurationTarget.Global);
}
}
async function changeTerminalRendererType() {
// Check if "terminal.integrated.gpuAcceleration" has a global value
const terminalConfig = vscode.workspace.getConfiguration().inspect("terminal.integrated.gpuAcceleration");
if (terminalConfig?.globalValue === undefined) {
return;
}
// If "terminal.integrated.gpuAcceleration" is not enabled, disable it
if (!terminalConfig.globalValue) {
await vscode.workspace.getConfiguration().update("terminal.integrated.gpuAcceleration", "off", vscode.ConfigurationTarget.Global);
}
}
async function changeTerminalBackground() {
// Get the current terminal color customizations
const terminalColorConfig = vscode.workspace.getConfiguration().inspect("workbench.colorCustomizations");
// Initialize an empty object if "workbench.colorCustomizations" is missing
const currentColorCustomizations = terminalColorConfig?.globalValue || {};
// Get the current terminal.background value
const currentBackground = currentColorCustomizations["terminal.background"];
// Only update if the current terminal.background is not already "#00000000"
if (currentBackground !== "#00000000") {
const newColorCustomization = {
...currentColorCustomizations,
"terminal.background": "#00000000"
};
await vscode.workspace.getConfiguration().update("workbench.colorCustomizations", newColorCustomization, vscode.ConfigurationTarget.Global);
// Get the current applyToAllProfiles setting
const applyToAllProfilesConfig = vscode.workspace.getConfiguration().inspect("workbench.settings.applyToAllProfiles");
const currentApplyToAllProfiles = applyToAllProfilesConfig?.globalValue || [];
// Append "workbench.colorCustomizations" if it's not already in the list
if (!currentApplyToAllProfiles.includes("workbench.colorCustomizations")) {
currentApplyToAllProfiles.push("workbench.colorCustomizations");
await vscode.workspace.getConfiguration().update("workbench.settings.applyToAllProfiles", currentApplyToAllProfiles, vscode.ConfigurationTarget.Global);
}
}
}
async function promptRestart() {
// Store the current value of "window.titleBarStyle"
const titleBarStyle = vscode.workspace.getConfiguration().get("window.titleBarStyle");
// Toggle the value of "window.titleBarStyle" to prompt for a restart
await vscode.workspace.getConfiguration().update("window.titleBarStyle", titleBarStyle === "native" ? "custom" : "native", vscode.ConfigurationTarget.Global);
// Reset the value of "window.titleBarStyle" to its original value
await vscode.workspace.getConfiguration().update("window.titleBarStyle", titleBarStyle, vscode.ConfigurationTarget.Global);
}
async function checkColorTheme() {
// Get the current color theme and target theme from configuration files
const currentTheme = getCurrentTheme(vscode.workspace.getConfiguration("vscode_vibrancy"));
// if theme is "Custom theme (use imports)", skip the check
if (currentTheme === 'Custom theme (use imports)') {
return;
}
const themeConfig = require(path.join(__dirname, themeConfigPaths[currentTheme]));
const targetTheme = themeConfig.colorTheme;
const currentColorTheme = vscode.workspace.getConfiguration().get("workbench.colorTheme");
// Show a message to the user if the current color theme doesn't match the target theme
if (targetTheme !== currentColorTheme) {
const message = localize('messages.recommendedColorTheme')
.replace('%1', currentColorTheme)
.replace('%2', targetTheme);
const result = await vscode.window.showInformationMessage(message, localize('messages.changeColorThemeIde'), localize('messages.noIde'));
// If the user chooses to change the color theme, update the configuration
if (result === localize('messages.changeColorThemeIde')) {
await vscode.workspace.getConfiguration().update("workbench.colorTheme", targetTheme, vscode.ConfigurationTarget.Global);
}
}
}
// Electron 26 changed the available vibrancy types, this ensures that upgrading users switch
async function checkElectronDeprecatedType() {
let electronVersion = process.versions.electron;
let majorVersion = parseInt(electronVersion.split('.')[0]);
if (majorVersion > 25) {
const currentType = vscode.workspace.getConfiguration("vscode_vibrancy").type;
const deprecatedTypes = [
"appearance-based",
"dark",
"ultra-dark",
"light",
"medium-light"
];
if (deprecatedTypes.includes(currentType)) {
vscode.window.showWarningMessage(
localize('messages.electronDeprecatedType').replace('%1', currentType),
{ title: "Default" },
{ title: "Transparent" }
).then(async (msg) => {
if (msg) {
const newType = msg.title === "Default" ? "under-window" : "fullscreen-ui";
await vscode.workspace
.getConfiguration("vscode_vibrancy")
.update("type", newType, vscode.ConfigurationTarget.Global);
}
});
}
}
}
function deepEqual(obj1, obj2) {
if (obj1 === obj2) {
// Objects are the same
return true;
}
if (isPrimitive(obj1) && isPrimitive(obj2)) {
// Compare primitive values
return obj1 === obj2;
}
if (Object.keys(obj1).length !== Object.keys(obj2).length) {
// Objects have different number of properties
return false;
}
// Compare objects with the same number of properties
for (const key in obj1) {
if (!(key in obj2)) {
// Other object doesn't have this property
return false;
}
if (!deepEqual(obj1[key], obj2[key])) {
// Properties are not equal
return false;
}
}
// Objects are equal
return true;
}
//check if value is primitive
function isPrimitive(obj) {
return (obj !== Object(obj));
}
// Check if runtime and asset updates are necessary based on version numbers
function checkRuntimeUpdate(current, last) {
// Split the versions into major and minor numbers
const [currentMajor, currentMinor] = current.split('.').slice(0, 2);
const [lastMajor, lastMinor] = last.split('.').slice(0, 2);
// Convert the numbers to integers and compare them
return (parseInt(currentMajor) !== parseInt(lastMajor)) || (parseInt(currentMinor) !== parseInt(lastMinor));
}
function activate(context) {
console.log('vscode-vibrancy is active!');
var appDir;
try {
appDir = path.dirname(require.main.filename);
} catch {
appDir = _VSCODE_FILE_ROOT;
}
let useEsmRuntime = false;
var JSFile = path.join(appDir, '/main.js');
var ElectronJSFile = path.join(appDir, '/vs/code/electron-main/main.js');
// VSC 1.95 merges these main.js files
if (!fs.existsSync(ElectronJSFile)) {
ElectronJSFile = JSFile;
}
var runtimeVersion = 'v6';
var runtimeDir = path.join(appDir, '/vscode-vibrancy-runtime-' + runtimeVersion);
var runtimeSrcDir = "../runtime-pre-esm"
// VSC 1.94 and forward use Esm path
const workbenchHtmlPath = path.join(appDir, 'vs/code/electron-sandbox/workbench/workbench.html');
const workbenchEsmHtmlPath = path.join(appDir, 'vs/code/electron-sandbox/workbench/workbench.esm.html');
var HTMLFile;
if (fs.existsSync(workbenchHtmlPath)) {
HTMLFile = workbenchHtmlPath;
} else {
HTMLFile = workbenchEsmHtmlPath;
useEsmRuntime = true;
runtimeSrcDir = "../runtime"
}
async function installRuntime() {
// if runtimeDir exists, recurse through it and delete all files
if (fs.existsSync(runtimeDir)) {
fs.rmSync(runtimeDir, { recursive: true, force: true });
}
await fs.mkdir(runtimeDir);
await fsExtra.copy(path.resolve(__dirname, runtimeSrcDir), path.resolve(runtimeDir));
}
async function installRuntimeWin() {
// if runtimeDir exists, recurse through it and delete all files
// BUG: skip all .node files as they're locked by the VSCode process (#58)
if (fs.existsSync(runtimeDir)) {
fs.readdirSync(runtimeDir).forEach((file, index) => {
if (file.endsWith('.node')) {
return;
}
const curPath = path.join(runtimeDir, file);
// if file is a directory, recurse through it and delete all files
if (fs.lstatSync(curPath).isDirectory()) {
fs.rmSync(curPath, { recursive: true, force: true });
return;
}
fs.unlinkSync(curPath);
});
// copy all files from runtime to runtimeDir, skipping .node files
fs.readdirSync(path.resolve(__dirname, runtimeSrcDir)).forEach((file, index) => {
if (file.endsWith('.node')) {
return;
}
// if file is a directory
if (fs.lstatSync(path.join(path.resolve(__dirname, runtimeSrcDir), file)).isDirectory()) {
fsExtra.copySync(path.join(path.resolve(__dirname, runtimeSrcDir), file), path.join(runtimeDir, file));
return;
}
const curPath = path.join(path.resolve(__dirname, runtimeSrcDir), file);
fs.copyFileSync(curPath, path.join(runtimeDir, file));
});
} else {
await fs.mkdir(runtimeDir).catch(() => { });
await fsExtra.copy(path.resolve(__dirname, runtimeSrcDir), path.resolve(runtimeDir));
}
}
async function installJS() {
const config = vscode.workspace.getConfiguration("vscode_vibrancy");
const currentTheme = getCurrentTheme(config);
const themeConfigPath = path.resolve(__dirname, themeConfigPaths[currentTheme]);
const themeConfig = require(themeConfigPath);
const themeStylePath = path.join(__dirname, themeStylePaths[currentTheme]);
const themeCSS = await fs.readFile(themeStylePath, 'utf-8');
const JS = await fs.readFile(JSFile, 'utf-8');
const imports = await generateImports(config);
const injectData = {
os: os,
config: config,
theme: themeConfig,
themeCSS: themeCSS,
imports: imports,
};
const base = __filename;
const newJS = generateNewJS(JS, base, injectData);
await fs.writeFile(JSFile, newJS, 'utf-8');
await modifyElectronJSFile(ElectronJSFile);
}
async function generateImports(config) {
const imports = {
css: "",
js: "",
};
for (let i = 0; i < config.imports.length; i++) {
if (config.imports[i] === "/path/to/file") continue;
try {
const importContent = await fs.readFile(config.imports[i], 'utf-8');
if (config.imports[i].endsWith('.css')) {
imports.css += `<style>${importContent}</style>`;
} else {
imports.js += `<script>${importContent}</script>`;
}
} catch (err) {
vscode.window.showWarningMessage(localize('messages.importError').replace('%1', config.imports[i]));
}
}
return imports;
}
function generateNewJS(JS, base, injectData) {
let runtimePath;
if (useEsmRuntime) {
runtimePath = path.join(runtimeDir, "index.mjs")
} else {
runtimePath = path.join(runtimeDir, "index.cjs")
}
const newJS = JS.replace(/\n\/\* !! VSCODE-VIBRANCY-START !! \*\/[\s\S]*?\/\* !! VSCODE-VIBRANCY-END !! \*\//, '')
+ '\n/* !! VSCODE-VIBRANCY-START !! */\n;(function(){\n'
+ `if (!import('fs').then(fs => fs.existsSync(${JSON.stringify(base)}))) return;\n`
+ `global.vscode_vibrancy_plugin = ${JSON.stringify(injectData)}; try{ import("${pathToFileURL(runtimePath)}"); } catch (err) {console.error(err)}\n`
+ '})()\n/* !! VSCODE-VIBRANCY-END !! */';
return newJS;
}
// BrowserWindow option modification
async function modifyElectronJSFile(ElectronJSFile) {
let ElectronJS = await fs.readFile(ElectronJSFile, 'utf-8');
// add visualEffectState option to enable vibrancy while VSCode is not in focus (macOS only)
if (!ElectronJS.includes('visualEffectState')) {
ElectronJS = ElectronJS.replace(/experimentalDarkMode/g, 'visualEffectState:"active",experimentalDarkMode');
}
// enable frameless window on Windows w/ Electron 27 (bug #122)
const electronMajorVersion = parseInt(process.versions.electron.split('.')[0]);
if (!ElectronJS.includes('frame:false,') && process.platform === 'win32' && electronMajorVersion >= 27) {
ElectronJS = ElectronJS.replace(/experimentalDarkMode/g, 'frame:false,transparent:true,experimentalDarkMode');
}
await fs.writeFile(ElectronJSFile, ElectronJS, 'utf-8');
}
async function installHTML() {
const HTML = await fs.readFile(HTMLFile, 'utf-8');
const metaTagRegex = /<meta\s+http-equiv="Content-Security-Policy"\s+content="([\s\S]+?)">/;
const trustedTypesRegex = /(trusted-types)(\r\n|\r|\n)/;
const metaTagMatch = HTML.match(metaTagRegex);
if (metaTagMatch) {
const currentContent = metaTagMatch[0];
const newContent = currentContent.replace(trustedTypesRegex, "$1 VscodeVibrancy\n");
newHTML = HTML.replace(metaTagRegex, newContent);
}
try {
if (HTML !== newHTML) {
await fs.writeFile(HTMLFile, newHTML, 'utf-8');
}
} catch (ReferenceError) {
throw localize('messages.htmlError');
}
}
async function uninstallJS() {
const JS = await fs.readFile(JSFile, 'utf-8');
const needClean = /\n\/\* !! VSCODE-VIBRANCY-START !! \*\/[\s\S]*?\/\* !! VSCODE-VIBRANCY-END !! \*\//.test(JS);
if (needClean) {
const newJS = JS
.replace(/\n\/\* !! VSCODE-VIBRANCY-START !! \*\/[\s\S]*?\/\* !! VSCODE-VIBRANCY-END !! \*\//, '')
await fs.writeFile(JSFile, newJS, 'utf-8');
}
// remove visualEffectState option
const ElectronJS = await fs.readFile(ElectronJSFile, 'utf-8');
const newElectronJS = ElectronJS
.replace(/frame:false,transparent:true,experimentalDarkMode/g, 'experimentalDarkMode')
.replace(/visualEffectState:"active",experimentalDarkMode/g, 'experimentalDarkMode');
await fs.writeFile(ElectronJSFile, newElectronJS, 'utf-8');
}
async function uninstallHTML() {
const HTML = await fs.readFile(HTMLFile, 'utf-8');
const needClean = /trusted-types VscodeVibrancy/.test(HTML);
if (needClean) {
const newHTML = HTML.replace(/trusted-types VscodeVibrancy(\r\n|\r|\n)/, "trusted-types$1");
await fs.writeFile(HTMLFile, newHTML, 'utf-8');
}
}
function enabledRestart() {
vscode.window.showInformationMessage(localize('messages.enabled'), { title: localize('messages.restartIde') })
.then(function (msg) {
msg && promptRestart();
});
}
function disabledRestart() {
vscode.window.showInformationMessage(localize('messages.disabled'), { title: localize('messages.restartIde') })
.then(function (msg) {
msg && promptRestart();
});
}
// #### main commands ######################################################
async function Install() {
if (os === 'unknown') {
vscode.window.showInformationMessage(localize('messages.unsupported'));
throw new Error('unsupported');
}
// BUG: prevent installation on ARM Windows (#9)
if (process.arch.startsWith("arm") && process.platform === 'win32') {
vscode.window.showInformationMessage(localize('messages.unsupported'));
throw new Error('unsupported');
}
try {
await fs.stat(JSFile);
await fs.stat(HTMLFile);
if (os === 'win10') {
await installRuntimeWin();
} else {
await installRuntime();
}
await installJS();
await installHTML();
await changeTerminalRendererType();
await changeTerminalBackground();
} catch (error) {
if (error && (error.code === 'EPERM' || error.code === 'EACCES')) {
vscode.window.showInformationMessage(localize('messages.admin') + error);
}
else {
vscode.window.showInformationMessage(localize('messages.smthingwrong') + error);
}
throw error;
}
}
async function Uninstall() {
try {
// uninstall old version
await fs.stat(HTMLFile);
await uninstallHTML();
} finally {
}
try {
await fs.stat(JSFile);
await uninstallJS();
} catch (error) {
if (error && (error.code === 'EPERM' || error.code === 'EACCES')) {
vscode.window.showInformationMessage(localize('messages.admin') + error);
}
else {
vscode.window.showInformationMessage(localize('messages.smthingwrong') + error);
}
throw error;
}
}
async function Update() {
await Uninstall();
await Install();
}
var installVibrancy = vscode.commands.registerCommand('extension.installVibrancy', async () => {
await Install();
enabledRestart();
});
var uninstallVibrancy = vscode.commands.registerCommand('extension.uninstallVibrancy', async () => {
await Uninstall()
disabledRestart();
});
var updateVibrancy = vscode.commands.registerCommand('extension.updateVibrancy', async () => {
await Update();
enabledRestart();
});
context.subscriptions.push(installVibrancy);
context.subscriptions.push(uninstallVibrancy);
context.subscriptions.push(updateVibrancy);
const currentVersion = context.extension.packageJSON.version;
let lastVersion = context.globalState.get('lastVersion');
let updateMsg = "messages.updateNeeded"
// Detect first time install
if (!lastVersion) {
lastVersion = '0.0.0';
updateMsg = "messages.firstload"
}
// Check if the current version is a minor update from the last version
if (checkRuntimeUpdate(currentVersion, lastVersion)) {
vscode.window.showInformationMessage(localize(updateMsg), { title: localize('messages.installIde') })
.then(async (msg) => {
if (msg) {
await Update();
await checkColorTheme();
await checkElectronDeprecatedType();
enabledRestart();
}
});
// Update the global state with the current version
context.globalState.update('lastVersion', currentVersion);
}
// Check type compatibility with current Electron
checkElectronDeprecatedType();
// Ensure correct config
changeTerminalBackground();
var lastConfig = vscode.workspace.getConfiguration("vscode_vibrancy");
vscode.workspace.onDidChangeConfiguration(() => {
newConfig = vscode.workspace.getConfiguration("vscode_vibrancy");
if (!deepEqual(lastConfig, newConfig)) {
lastConfig = newConfig;
vscode.window.showInformationMessage(localize('messages.configupdate'), { title: localize('messages.reloadIde') })
.then(async (msg) => {
await checkElectronDeprecatedType();
if (msg) {
await Update();
// if (newConfig.theme !== vscode.workspace.getConfiguration("vscode_vibrancy")) {
// await checkColorTheme();
// }
enabledRestart();
}
});
context.globalState.update('lastVersion', currentVersion);
}
});
checkDarkLightMode(vscode.window.activeColorTheme)
vscode.window.onDidChangeActiveColorTheme((theme) => {
checkDarkLightMode(theme)
});
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() { }
exports.deactivate = deactivate;