Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,12 @@ function downloadFile(url: string): Promise<string> {
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
resolve(data);
});
}).on('error', (error) => {
reject(error);
});
});
}
export function deactivate() {}
24 changes: 13 additions & 11 deletions patched-vscode/src/vs/base/common/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';

export const LANGUAGE_DEFAULT = 'en';

let _isWindows = false;
Expand Down Expand Up @@ -112,17 +110,21 @@ else if (typeof navigator === 'object' && !isElectronRenderer) {
_isMobile = _userAgent?.indexOf('Mobi') >= 0;
_isWeb = true;

const configuredLocale = nls.getConfiguredDefaultLocale(
// This call _must_ be done in the file that calls `nls.getConfiguredDefaultLocale`
// to ensure that the NLS AMD Loader plugin has been loaded and configured.
// This is because the loader plugin decides what the default locale is based on
// how it's able to resolve the strings.
nls.localize({ key: 'ensureLoaderPluginIsLoaded', comment: ['{Locked}'] }, '_')
);

_locale = configuredLocale || LANGUAGE_DEFAULT;
_locale = LANGUAGE_DEFAULT;
_language = _locale;
_platformLocale = navigator.language;
const el = typeof document !== 'undefined' && document.getElementById('vscode-remote-nls-configuration');
const rawNlsConfig = el && el.getAttribute('data-settings');
if (rawNlsConfig) {
try {
const nlsConfig: NLSConfig = JSON.parse(rawNlsConfig);
const resolved = nlsConfig.availableLanguages['*'];
_locale = nlsConfig.locale;
_platformLocale = nlsConfig.osLocale;
_language = resolved ? resolved : LANGUAGE_DEFAULT;
_translationsConfigFile = nlsConfig._translationsConfigFile;
} catch (error) { /* Oh well. */ }
}
}

// Unknown environment
Expand Down
31 changes: 23 additions & 8 deletions patched-vscode/src/vs/code/browser/workbench/workbench.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
<!-- Workbench Configuration -->
<meta id="vscode-workbench-web-configuration" data-settings="{{WORKBENCH_WEB_CONFIGURATION}}">

<!-- NLS Configuration -->
<meta id="vscode-remote-nls-configuration" data-settings="{{NLS_CONFIGURATION}}">

<!-- Workbench Auth Session -->
<meta id="vscode-workbench-auth-session" data-settings="{{WORKBENCH_AUTH_SESSION}}">

Expand Down Expand Up @@ -46,14 +49,26 @@
// Normalize locale to lowercase because translationServiceUrl is case-sensitive.
// ref: https://github.com/microsoft/vscode/issues/187795
const locale = localStorage.getItem('vscode.nls.locale') || navigator.language.toLowerCase();
if (!locale.startsWith('en')) {
nlsConfig['vs/nls'] = {
availableLanguages: {
'*': locale
},
translationServiceUrl: '{{WORKBENCH_NLS_BASE_URL}}'
};
}
try {
nlsConfig['vs/nls'] = JSON.parse(document.getElementById("vscode-remote-nls-configuration").getAttribute("data-settings"))
if (nlsConfig['vs/nls']._resolvedLanguagePackCoreLocation) {
const bundles = Object.create(null)
nlsConfig['vs/nls'].loadBundle = (bundle, _language, cb) => {
const result = bundles[bundle]
if (result) {
return cb(undefined, result)
}
const path = nlsConfig['vs/nls']._resolvedLanguagePackCoreLocation + "/" + bundle.replace(/\//g, "!") + ".nls.json"
fetch(`{{WORKBENCH_WEB_BASE_URL}}/../vscode-remote-resource?path=${encodeURIComponent(path)}`)
.then((response) => response.json())
.then((json) => {
bundles[bundle] = json
cb(undefined, json)
})
.catch(cb)
}
}
} catch (error) { /* Probably fine. */ }

require.config({
baseUrl: `${baseUrl}/out`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export abstract class AbstractNativeEnvironmentService implements INativeEnviron
return URI.file(join(vscodePortable, 'argv.json'));
}

return joinPath(this.userHome, this.productService.dataFolderName, 'argv.json');
return joinPath(this.appSettingsHome, 'argv.json');
}

@memoize
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,24 @@

import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { URI } from 'vs/base/common/uri';
import { ProxyChannel } from 'vs/base/parts/ipc/common/ipc';
import { IExtensionGalleryService } from 'vs/platform/extensionManagement/common/extensionManagement';
import { IExtensionResourceLoaderService } from 'vs/platform/extensionResourceLoader/common/extensionResourceLoader';
import { ILanguagePackItem, LanguagePackBaseService } from 'vs/platform/languagePacks/common/languagePacks';
import { ILanguagePackItem, ILanguagePackService, LanguagePackBaseService } from 'vs/platform/languagePacks/common/languagePacks';
import { ILogService } from 'vs/platform/log/common/log';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';

export class WebLanguagePacksService extends LanguagePackBaseService {
private readonly languagePackService: ILanguagePackService;

constructor(
@IRemoteAgentService remoteAgentService: IRemoteAgentService,
@IExtensionResourceLoaderService private readonly extensionResourceLoaderService: IExtensionResourceLoaderService,
@IExtensionGalleryService extensionGalleryService: IExtensionGalleryService,
@ILogService private readonly logService: ILogService
) {
super(extensionGalleryService);
this.languagePackService = ProxyChannel.toService<ILanguagePackService>(remoteAgentService.getConnection()!.getChannel('languagePacks'))
}

async getBuiltInExtensionTranslationsUri(id: string, language: string): Promise<URI | undefined> {
Expand Down Expand Up @@ -72,6 +78,6 @@ export class WebLanguagePacksService extends LanguagePackBaseService {

// Web doesn't have a concept of language packs, so we just return an empty array
getInstalledLanguages(): Promise<ILanguagePackItem[]> {
return Promise.resolve([]);
return this.languagePackService.getInstalledLanguages()
}
}
84 changes: 59 additions & 25 deletions patched-vscode/src/vs/server/node/remoteLanguagePacks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,36 +8,30 @@ import { FileAccess } from 'vs/base/common/network';
import * as path from 'vs/base/common/path';

import * as lp from 'vs/base/node/languagePacks';
import product from 'vs/platform/product/common/product';

const metaData = path.join(FileAccess.asFileUri('').fsPath, 'nls.metadata.json');
const _cache: Map<string, Promise<lp.NLSConfiguration>> = new Map();

function exists(file: string) {
return new Promise(c => fs.exists(file, c));
}

export function getNLSConfiguration(language: string, userDataPath: string): Promise<lp.NLSConfiguration> {
return exists(metaData).then((fileExists) => {
if (!fileExists || !product.commit) {
// console.log(`==> MetaData or commit unknown. Using default language.`);
// The OS Locale on the remote side really doesn't matter, so we return the default locale
return Promise.resolve({ locale: 'en', osLocale: 'en', availableLanguages: {} });
}
const key = `${language}||${userDataPath}`;
let result = _cache.get(key);
if (!result) {
// The OS Locale on the remote side really doesn't matter, so we pass in the same language
result = lp.getNLSConfiguration(product.commit, userDataPath, metaData, language, language).then(value => {
if (InternalNLSConfiguration.is(value)) {
value._languagePackSupport = true;
}
return value;
});
_cache.set(key, result);
}
return result;
});
const key = `${language}||${userDataPath}`;
let result = _cache.get(key);
if (!result) {
// The OS Locale on the remote side really doesn't matter, so we pass in the same language
result = lp.getNLSConfiguration("dummy_commit", userDataPath, metaData, language, language).then(value => {
if (InternalNLSConfiguration.is(value)) {
value._languagePackSupport = true;
}
// If the configuration has no results keep trying since code-server
// doesn't restart when a language is installed so this result would
// persist (the plugin might not be installed yet for example).
if (value.locale !== 'en' && value.locale !== 'en-us' && Object.keys(value.availableLanguages).length === 0) {
_cache.delete(key);
}
return value;
});
_cache.set(key, result);
}
return result;
}

export namespace InternalNLSConfiguration {
Expand All @@ -46,3 +40,43 @@ export namespace InternalNLSConfiguration {
return candidate && typeof candidate._languagePackId === 'string';
}
}

/**
* The code below is copied from from src/main.js.
*/

export const getLocaleFromConfig = async (argvResource: string): Promise<string> => {
try {
const content = stripComments(await fs.promises.readFile(argvResource, 'utf8'));
return JSON.parse(content).locale;
} catch (error) {
if (error.code !== "ENOENT") {
console.warn(error)
}
return 'en';
}
};

const stripComments = (content: string): string => {
const regexp = /('(?:[^\\']*(?:\\.)?)*')|('(?:[^\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;

return content.replace(regexp, (match, _m1, _m2, m3, m4) => {
// Only one of m1, m2, m3, m4 matches
if (m3) {
// A block comment. Replace with nothing
return '';
} else if (m4) {
// A line comment. If it ends in \r?\n then keep it.
const length_1 = m4.length;
if (length_1 > 2 && m4[length_1 - 1] === '\n') {
return m4[length_1 - 2] === '\r' ? '\r\n' : '\n';
}
else {
return '';
}
} else {
// We match a string
return match;
}
});
};
4 changes: 4 additions & 0 deletions patched-vscode/src/vs/server/node/serverEnvironmentService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import { URI } from 'vs/base/common/uri';

export const serverOptions: OptionDescriptions<Required<ServerParsedArgs>> = {

'locale': { type: 'string' },

/* ----- server setup ----- */

'host': { type: 'string', cat: 'o', args: 'ip-address', description: nls.localize('host', "The host name or IP address the server should listen to. If not set, defaults to 'localhost'.") },
Expand Down Expand Up @@ -97,6 +99,8 @@ export const serverOptions: OptionDescriptions<Required<ServerParsedArgs>> = {

export interface ServerParsedArgs {

'locale'?: string;

/* ----- server setup ----- */

host?: string;
Expand Down
5 changes: 4 additions & 1 deletion patched-vscode/src/vs/server/node/serverServices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import * as path from 'vs/base/common/path';
import { IURITransformer } from 'vs/base/common/uriIpc';
import { getMachineId, getSqmMachineId, getdevDeviceId } from 'vs/base/node/id';
import { Promises } from 'vs/base/node/pfs';
import { ClientConnectionEvent, IMessagePassingProtocol, IPCServer, StaticRouter } from 'vs/base/parts/ipc/common/ipc';
import { ClientConnectionEvent, IMessagePassingProtocol, IPCServer, ProxyChannel, StaticRouter } from 'vs/base/parts/ipc/common/ipc';
import { ProtocolConstants } from 'vs/base/parts/ipc/common/ipc.net';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ConfigurationService } from 'vs/platform/configuration/common/configurationService';
Expand Down Expand Up @@ -225,6 +225,9 @@ export async function setupServerServices(connectionToken: ServerConnectionToken
const channel = new ExtensionManagementChannel(extensionManagementService, (ctx: RemoteAgentConnectionContext) => getUriTransformer(ctx.remoteAuthority));
socketServer.registerChannel('extensions', channel);

const languagePackChannel = ProxyChannel.fromService<RemoteAgentConnectionContext>(accessor.get(ILanguagePackService), disposables);
socketServer.registerChannel('languagePacks', languagePackChannel);

// clean up extensions folder
remoteExtensionsScanner.whenExtensionsReady().then(() => extensionManagementService.cleanUp());

Expand Down
6 changes: 5 additions & 1 deletion patched-vscode/src/vs/server/node/webClientServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { URI } from 'vs/base/common/uri';
import { streamToBuffer } from 'vs/base/common/buffer';
import { IProductConfiguration } from 'vs/base/common/product';
import { isString } from 'vs/base/common/types';
import { getLocaleFromConfig, getNLSConfiguration } from 'vs/server/node/remoteLanguagePacks';
import { CharCode } from 'vs/base/common/charCode';
import { IExtensionManifest } from 'vs/platform/extensions/common/extensions';

Expand Down Expand Up @@ -362,6 +363,8 @@ export class WebClientServer {
callbackRoute: this._callbackRoute
};

const locale = this._environmentService.args.locale || await getLocaleFromConfig(this._environmentService.argvResource.fsPath);
const nlsConfiguration = await getNLSConfiguration(locale, this._environmentService.userDataPath)
const nlsBaseUrl = this._productService.extensionsGallery?.nlsBaseUrl;
const values: { [key: string]: string } = {
WORKBENCH_WEB_CONFIGURATION: asJSON(workbenchWebConfiguration),
Expand All @@ -370,6 +373,7 @@ export class WebClientServer {
WORKBENCH_NLS_BASE_URL: vscodeBase + (nlsBaseUrl ? `${nlsBaseUrl}${!nlsBaseUrl.endsWith('/') ? '/' : ''}${this._productService.commit}/${this._productService.version}/` : ''),
BASE: base,
VS_BASE: vscodeBase,
NLS_CONFIGURATION: asJSON(nlsConfiguration),
};

if (useTestResolver) {
Expand Down Expand Up @@ -401,7 +405,7 @@ export class WebClientServer {
`frame-src 'self' https://*.vscode-cdn.net data:;`,
'worker-src \'self\' data: blob:;',
'style-src \'self\' \'unsafe-inline\';',
'connect-src \'self\' ws: wss: https://main.vscode-cdn.net http://localhost:* https://localhost:* https://login.microsoftonline.com/ https://update.code.visualstudio.com https://*.vscode-unpkg.net/ https://default.exp-tas.com/vscode/ab https://vscode-sync.trafficmanager.net https://vscode-sync-insiders.trafficmanager.net https://*.gallerycdn.vsassets.io https://marketplace.visualstudio.com https://az764295.vo.msecnd.net https://code.visualstudio.com https://*.gallery.vsassets.io https://*.rel.tunnels.api.visualstudio.com wss://*.rel.tunnels.api.visualstudio.com https://*.servicebus.windows.net/ https://vscode.blob.core.windows.net https://vscode.search.windows.net https://vsmarketplacebadges.dev https://vscode.download.prss.microsoft.com https://download.visualstudio.microsoft.com https://*.vscode-unpkg.net https://open-vsx.org;',
'connect-src \'self\' ws: wss: https://main.vscode-cdn.net http://localhost:* https://localhost:* https://login.microsoftonline.com/ https://update.code.visualstudio.com https://*.vscode-unpkg.net/ https://default.exp-tas.com/vscode/ab https://vscode-sync.trafficmanager.net https://vscode-sync-insiders.trafficmanager.net https://*.gallerycdn.vsassets.io https://marketplace.visualstudio.com https://*.blob.core.windows.net https://az764295.vo.msecnd.net https://code.visualstudio.com https://*.gallery.vsassets.io https://*.rel.tunnels.api.visualstudio.com wss://*.rel.tunnels.api.visualstudio.com https://*.servicebus.windows.net/ https://vscode.blob.core.windows.net https://vscode.search.windows.net https://vsmarketplacebadges.dev https://vscode.download.prss.microsoft.com https://download.visualstudio.microsoft.com https://*.vscode-unpkg.net https://open-vsx.org;',
'font-src \'self\' blob:;',
'manifest-src \'self\';'
].join(' ');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -341,9 +341,6 @@ export class InstallAction extends ExtensionAction {
if (this.extension.isBuiltin) {
return;
}
if (this.extensionsWorkbenchService.canSetLanguage(this.extension)) {
return;
}
if (this.extension.state === ExtensionState.Uninstalled && await this.extensionsWorkbenchService.canInstall(this.extension)) {
this.enabled = this.options.installPreReleaseVersion ? this.extension.hasPreReleaseVersion : this.extension.hasReleaseVersion;
this.updateLabel();
Expand Down Expand Up @@ -614,7 +611,7 @@ export abstract class InstallInOtherServerAction extends ExtensionAction {
}

if (isLanguagePackExtension(this.extension.local.manifest)) {
return true;
return false;
}

// Prefers to run on UI
Expand Down Expand Up @@ -1848,17 +1845,6 @@ export class SetLanguageAction extends ExtensionAction {
update(): void {
this.enabled = false;
this.class = SetLanguageAction.DisabledClass;
if (!this.extension) {
return;
}
if (!this.extensionsWorkbenchService.canSetLanguage(this.extension)) {
return;
}
if (this.extension.gallery && language === getLocale(this.extension.gallery)) {
return;
}
this.enabled = true;
this.class = SetLanguageAction.EnabledClass;
}

override async run(): Promise<any> {
Expand All @@ -1875,7 +1861,6 @@ export class ClearLanguageAction extends ExtensionAction {
private static readonly DisabledClass = `${ClearLanguageAction.EnabledClass} disabled`;

constructor(
@IExtensionsWorkbenchService private readonly extensionsWorkbenchService: IExtensionsWorkbenchService,
@ILocaleService private readonly localeService: ILocaleService,
) {
super(ClearLanguageAction.ID, ClearLanguageAction.TITLE.value, ClearLanguageAction.DisabledClass, false);
Expand All @@ -1885,17 +1870,6 @@ export class ClearLanguageAction extends ExtensionAction {
update(): void {
this.enabled = false;
this.class = ClearLanguageAction.DisabledClass;
if (!this.extension) {
return;
}
if (!this.extensionsWorkbenchService.canSetLanguage(this.extension)) {
return;
}
if (this.extension.gallery && language !== getLocale(this.extension.gallery)) {
return;
}
this.enabled = true;
this.class = ClearLanguageAction.EnabledClass;
}

override async run(): Promise<any> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ class NativeLocaleService implements ILocaleService {
@IProductService private readonly productService: IProductService
) { }

private async validateLocaleFile(): Promise<boolean> {
// Make public just so we do not have to patch all the unused code out.
public async validateLocaleFile(): Promise<boolean> {
try {
const content = await this.textFileService.read(this.environmentService.argvResource, { encoding: 'utf8' });

Expand All @@ -78,9 +79,6 @@ class NativeLocaleService implements ILocaleService {
}

private async writeLocaleValue(locale: string | undefined): Promise<boolean> {
if (!(await this.validateLocaleFile())) {
return false;
}
await this.jsonEditingService.write(this.environmentService.argvResource, [{ path: ['locale'], value: locale }], true);
return true;
}
Expand Down
Loading