preferencesService.ts 29.5 KB
Newer Older
1 2 3 4
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
S
Sandeep Somavarapu 已提交
5

6 7 8
import { Emitter } from 'vs/base/common/event';
import { parse } from 'vs/base/common/json';
import { Disposable } from 'vs/base/common/lifecycle';
9
import * as network from 'vs/base/common/network';
10 11 12 13 14 15 16 17 18 19
import { assign } from 'vs/base/common/objects';
import * as strings from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { getCodeEditor, ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { IPosition, Position } from 'vs/editor/common/core/position';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
20
import * as nls from 'vs/nls';
21
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
B
Benjamin Pasero 已提交
22
import { IEditorOptions } from 'vs/platform/editor/common/editor';
23
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
24 25
import { FileOperationError, FileOperationResult, IFileService } from 'vs/platform/files/common/files';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
26
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
27
import { ILabelService } from 'vs/platform/label/common/label';
28
import { INotificationService } from 'vs/platform/notification/common/notification';
29 30 31 32
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { EditorInput, IEditor } from 'vs/workbench/common/editor';
import { IJSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditing';
B
Benjamin Pasero 已提交
33
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
34
import { GroupDirection, IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
35
import { DEFAULT_SETTINGS_EDITOR_SETTING, FOLDER_SETTINGS_PATH, getSettingsTargetName, IPreferencesEditorModel, IPreferencesService, ISetting, ISettingsEditorOptions, SettingsEditorOptions, USE_SPLIT_JSON_SETTING } from 'vs/workbench/services/preferences/common/preferences';
36
import { DefaultPreferencesEditorInput, KeybindingsEditorInput, PreferencesEditorInput, SettingsEditor2Input } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
S
Sandeep Somavarapu 已提交
37
import { defaultKeybindingsContents, DefaultKeybindingsEditorModel, DefaultSettings, DefaultSettingsEditorModel, Settings2EditorModel, SettingsEditorModel, WorkspaceConfigurationEditorModel, DefaultRawSettingsEditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
38
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
39

S
Sandeep Somavarapu 已提交
40 41
const emptyEditableSettingsContent = '{\n}';

42
export class PreferencesService extends Disposable implements IPreferencesService {
43 44

	_serviceBrand: any;
45

46
	private lastOpenedSettingsInput: PreferencesEditorInput | null = null;
47

48
	private readonly _onDispose = this._register(new Emitter<void>());
49

S
Sandeep Somavarapu 已提交
50 51 52 53 54 55
	private _defaultUserSettingsUriCounter = 0;
	private _defaultUserSettingsContentModel: DefaultSettings;
	private _defaultWorkspaceSettingsUriCounter = 0;
	private _defaultWorkspaceSettingsContentModel: DefaultSettings;
	private _defaultFolderSettingsUriCounter = 0;
	private _defaultFolderSettingsContentModel: DefaultSettings;
R
Rob Lourens 已提交
56

57
	constructor(
58 59 60
		@IEditorService private readonly editorService: IEditorService,
		@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService,
		@IFileService private readonly fileService: IFileService,
61
		@IConfigurationService private readonly configurationService: IConfigurationService,
62 63 64 65 66 67
		@INotificationService private readonly notificationService: INotificationService,
		@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IEnvironmentService private readonly environmentService: IEnvironmentService,
		@ITelemetryService private readonly telemetryService: ITelemetryService,
		@ITextModelService private readonly textModelResolverService: ITextModelService,
68
		@IKeybindingService keybindingService: IKeybindingService,
69 70 71 72
		@IModelService private readonly modelService: IModelService,
		@IJSONEditingService private readonly jsonEditingService: IJSONEditingService,
		@IModeService private readonly modeService: IModeService,
		@ILabelService private readonly labelService: ILabelService
73 74
	) {
		super();
75 76
		// The default keybindings.json updates based on keyboard layouts, so here we make sure
		// if a model has been given out we update it accordingly.
77
		this._register(keybindingService.onDidUpdateKeybindings(() => {
78 79 80 81 82
			const model = modelService.getModel(this.defaultKeybindingsResource);
			if (!model) {
				// model has not been given out => nothing to do
				return;
			}
83
			modelService.updateModel(model, defaultKeybindingsContents(keybindingService));
84
		}));
85 86
	}

S
Sandeep Somavarapu 已提交
87
	readonly defaultKeybindingsResource = URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: '/keybindings.json' });
S
Sandeep Somavarapu 已提交
88
	private readonly defaultSettingsRawResource = URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: '/defaultSettings.json' });
89

90
	get userSettingsResource(): URI {
S
Sandeep Somavarapu 已提交
91
		return this.getEditableSettingsURI(ConfigurationTarget.USER)!;
92 93
	}

S
Sandeep Somavarapu 已提交
94
	get workspaceSettingsResource(): URI | null {
95 96 97
		return this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE);
	}

98 99 100 101
	get settingsEditor2Input(): SettingsEditor2Input {
		return this.instantiationService.createInstance(SettingsEditor2Input);
	}

S
Sandeep Somavarapu 已提交
102
	getFolderSettingsResource(resource: URI): URI | null {
103
		return this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE_FOLDER, resource);
S
Sandeep Somavarapu 已提交
104 105
	}

S
Sandeep Somavarapu 已提交
106
	resolveModel(uri: URI): Promise<ITextModel | null> {
S
Sandeep Somavarapu 已提交
107
		if (this.isDefaultSettingsResource(uri)) {
S
Sandeep Somavarapu 已提交
108

S
Sandeep Somavarapu 已提交
109
			const target = this.getConfigurationTargetFromDefaultSettingsResource(uri);
A
Alex Dima 已提交
110 111
			const languageSelection = this.modeService.create('jsonc');
			const model = this._register(this.modelService.createModel('', languageSelection, uri));
S
Sandeep Somavarapu 已提交
112

113
			let defaultSettings: DefaultSettings | undefined;
S
Sandeep Somavarapu 已提交
114 115 116 117 118 119 120
			this.configurationService.onDidChangeConfiguration(e => {
				if (e.source === ConfigurationTarget.DEFAULT) {
					const model = this.modelService.getModel(uri);
					if (!model) {
						// model has not been given out => nothing to do
						return;
					}
S
Sandeep Somavarapu 已提交
121
					defaultSettings = this.getDefaultSettings(target);
122
					this.modelService.updateModel(model, defaultSettings.getContent(true));
123
					defaultSettings._onDidChange.fire();
S
Sandeep Somavarapu 已提交
124 125 126 127 128
				}
			});

			// Check if Default settings is already created and updated in above promise
			if (!defaultSettings) {
S
Sandeep Somavarapu 已提交
129
				defaultSettings = this.getDefaultSettings(target);
130
				this.modelService.updateModel(model, defaultSettings.getContent(true));
S
Sandeep Somavarapu 已提交
131 132
			}

R
Rob Lourens 已提交
133
			return Promise.resolve(model);
134 135
		}

S
Sandeep Somavarapu 已提交
136
		if (this.defaultSettingsRawResource.toString() === uri.toString()) {
S
Sandeep Somavarapu 已提交
137
			const defaultRawSettingsEditorModel = this.instantiationService.createInstance(DefaultRawSettingsEditorModel, this.getDefaultSettings(ConfigurationTarget.USER));
A
Alex Dima 已提交
138
			const languageSelection = this.modeService.create('jsonc');
S
Sandeep Somavarapu 已提交
139
			const model = this._register(this.modelService.createModel(defaultRawSettingsEditorModel.content, languageSelection, uri));
R
Rob Lourens 已提交
140
			return Promise.resolve(model);
S
Sandeep Somavarapu 已提交
141 142
		}

143
		if (this.defaultKeybindingsResource.toString() === uri.toString()) {
S
Sandeep Somavarapu 已提交
144
			const defaultKeybindingsEditorModel = this.instantiationService.createInstance(DefaultKeybindingsEditorModel, uri);
A
Alex Dima 已提交
145 146
			const languageSelection = this.modeService.create('jsonc');
			const model = this._register(this.modelService.createModel(defaultKeybindingsEditorModel.content, languageSelection, uri));
R
Rob Lourens 已提交
147
			return Promise.resolve(model);
148 149
		}

R
Rob Lourens 已提交
150
		return Promise.resolve(null);
151 152
	}

J
Johannes Rieken 已提交
153
	createPreferencesEditorModel(uri: URI): Promise<IPreferencesEditorModel<any>> {
S
Sandeep Somavarapu 已提交
154
		if (this.isDefaultSettingsResource(uri)) {
155
			return this.createDefaultSettingsEditorModel(uri);
156 157
		}

S
Sandeep Somavarapu 已提交
158
		if (this.userSettingsResource.toString() === uri.toString()) {
159
			return this.createEditableSettingsEditorModel(ConfigurationTarget.USER, uri);
160
		}
161

S
Sandeep Somavarapu 已提交
162
		const workspaceSettingsUri = this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE);
163
		if (workspaceSettingsUri && workspaceSettingsUri.toString() === uri.toString()) {
164
			return this.createEditableSettingsEditorModel(ConfigurationTarget.WORKSPACE, workspaceSettingsUri);
165
		}
166

167
		if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
168
			return this.createEditableSettingsEditorModel(ConfigurationTarget.WORKSPACE_FOLDER, uri);
169
		}
170

S
Sandeep Somavarapu 已提交
171
		return Promise.reject(`unknown resource: ${uri.toString()}`);
172 173
	}

J
Johannes Rieken 已提交
174
	openRawDefaultSettings(): Promise<IEditor> {
B
Benjamin Pasero 已提交
175
		return this.editorService.openEditor({ resource: this.defaultSettingsRawResource });
S
Sandeep Somavarapu 已提交
176 177
	}

J
Johannes Rieken 已提交
178
	openRawUserSettings(): Promise<IEditor> {
179
		return this.editorService.openEditor({ resource: this.userSettingsResource });
S
Sandeep Somavarapu 已提交
180 181
	}

J
Johannes Rieken 已提交
182
	openSettings(jsonEditor?: boolean): Promise<IEditor> {
183 184 185 186
		jsonEditor = typeof jsonEditor === 'undefined' ?
			this.configurationService.getValue('workbench.settings.editor') === 'json' :
			jsonEditor;

187 188 189 190
		if (!jsonEditor) {
			return this.openSettings2();
		}

191
		const editorInput = this.getActiveSettingsEditorInput() || this.lastOpenedSettingsInput;
S
Sandeep Somavarapu 已提交
192
		const resource = editorInput ? editorInput.master.getResource()! : this.userSettingsResource;
S
Sandeep Somavarapu 已提交
193
		const target = this.getConfigurationTargetFromSettingsResource(resource);
194
		return this.openOrSwitchSettings(target, resource);
S
Sandeep Somavarapu 已提交
195 196
	}

J
Johannes Rieken 已提交
197
	private openSettings2(): Promise<IEditor> {
198 199
		const input = this.settingsEditor2Input;
		return this.editorGroupService.activeGroup.openEditor(input)
S
Sandeep Somavarapu 已提交
200
			.then(() => this.editorGroupService.activeGroup.activeControl!);
201 202
	}

J
Johannes Rieken 已提交
203
	openGlobalSettings(jsonEditor?: boolean, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor> {
204 205 206 207
		jsonEditor = typeof jsonEditor === 'undefined' ?
			this.configurationService.getValue('workbench.settings.editor') === 'json' :
			jsonEditor;

208 209
		return jsonEditor ?
			this.openOrSwitchSettings(ConfigurationTarget.USER, this.userSettingsResource, options, group) :
210
			this.openOrSwitchSettings2(ConfigurationTarget.USER, undefined, options, group);
R
Rob Lourens 已提交
211 212
	}

S
Sandeep Somavarapu 已提交
213
	openWorkspaceSettings(jsonEditor?: boolean, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor> {
214 215 216 217
		jsonEditor = typeof jsonEditor === 'undefined' ?
			this.configurationService.getValue('workbench.settings.editor') === 'json' :
			jsonEditor;

S
Sandeep Somavarapu 已提交
218
		if (!this.workspaceSettingsResource) {
219
			this.notificationService.info(nls.localize('openFolderFirst', "Open a folder first to create workspace settings"));
S
Sandeep Somavarapu 已提交
220
			return Promise.reject(null);
221
		}
222 223 224

		return jsonEditor ?
			this.openOrSwitchSettings(ConfigurationTarget.WORKSPACE, this.workspaceSettingsResource, options, group) :
225
			this.openOrSwitchSettings2(ConfigurationTarget.WORKSPACE, undefined, options, group);
226 227
	}

J
Johannes Rieken 已提交
228
	openFolderSettings(folder: URI, jsonEditor?: boolean, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor> {
229 230 231
		jsonEditor = typeof jsonEditor === 'undefined' ?
			this.configurationService.getValue('workbench.settings.editor') === 'json' :
			jsonEditor;
S
Sandeep Somavarapu 已提交
232 233 234 235 236 237 238 239
		const folderSettingsUri = this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE_FOLDER, folder);
		if (jsonEditor) {
			if (folderSettingsUri) {
				return this.openOrSwitchSettings(ConfigurationTarget.WORKSPACE_FOLDER, folderSettingsUri, options, group);
			}
			return Promise.reject(`Invalid folder URI - ${folder.toString()}`);
		}
		return this.openOrSwitchSettings2(ConfigurationTarget.WORKSPACE_FOLDER, folder, options, group);
240 241
	}

J
Johannes Rieken 已提交
242
	switchSettings(target: ConfigurationTarget, resource: URI, jsonEditor?: boolean): Promise<void> {
243
		if (!jsonEditor) {
S
Sandeep Somavarapu 已提交
244
			return this.doOpenSettings2(target, resource).then(() => undefined);
245 246
		}

B
Benjamin Pasero 已提交
247 248
		const activeControl = this.editorService.activeControl;
		if (activeControl && activeControl.input instanceof PreferencesEditorInput) {
S
Sandeep Somavarapu 已提交
249
			return this.doSwitchSettings(target, resource, activeControl.input, activeControl.group).then(() => undefined);
250
		} else {
S
Sandeep Somavarapu 已提交
251
			return this.doOpenSettings(target, resource).then(() => undefined);
252
		}
253 254
	}

J
Johannes Rieken 已提交
255
	openGlobalKeybindingSettings(textual: boolean): Promise<void> {
K
kieferrm 已提交
256
		/* __GDPR__
K
kieferrm 已提交
257
			"openKeybindings" : {
K
kieferrm 已提交
258
				"textual" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
K
kieferrm 已提交
259 260
			}
		*/
261
		this.telemetryService.publicLog('openKeybindings', { textual });
S
Sandeep Somavarapu 已提交
262
		if (textual) {
263
			const emptyContents = '// ' + nls.localize('emptyKeybindingsHeader', "Place your key bindings in this file to override the defaults") + '\n[\n]';
S
Sandeep Somavarapu 已提交
264
			const editableKeybindings = URI.file(this.environmentService.appKeybindingsPath);
N
Nilesh 已提交
265
			const openDefaultKeybindings = !!this.configurationService.getValue('workbench.settings.openDefaultKeybindings');
S
Sandeep Somavarapu 已提交
266 267

			// Create as needed and open in editor
S
Sandeep Somavarapu 已提交
268 269
			return this.createIfNotExists(editableKeybindings, emptyContents).then(() => {
				if (openDefaultKeybindings) {
N
Nilesh 已提交
270 271
					const activeEditorGroup = this.editorGroupService.activeGroup;
					const sideEditorGroup = this.editorGroupService.addGroup(activeEditorGroup.id, GroupDirection.RIGHT);
R
Rob Lourens 已提交
272
					return Promise.all([
S
Sandeep Somavarapu 已提交
273 274
						this.editorService.openEditor({ resource: this.defaultKeybindingsResource, options: { pinned: true, preserveFocus: true, revealIfOpened: true }, label: nls.localize('defaultKeybindings', "Default Keybindings"), description: '' }),
						this.editorService.openEditor({ resource: editableKeybindings, options: { pinned: true, revealIfOpened: true } }, sideEditorGroup.id)
R
Rob Lourens 已提交
275
					]).then(editors => undefined);
S
Sandeep Somavarapu 已提交
276
				} else {
R
Rob Lourens 已提交
277
					return this.editorService.openEditor({ resource: editableKeybindings, options: { pinned: true, revealIfOpened: true } }).then(() => undefined);
S
Sandeep Somavarapu 已提交
278
				}
S
Sandeep Somavarapu 已提交
279 280
			});
		}
281

S
Sandeep Somavarapu 已提交
282
		return this.editorService.openEditor(this.instantiationService.createInstance(KeybindingsEditorInput), { pinned: true, revealIfOpened: true }).then(() => undefined);
283 284
	}

J
Johannes Rieken 已提交
285
	openDefaultKeybindingsFile(): Promise<IEditor> {
286
		return this.editorService.openEditor({ resource: this.defaultKeybindingsResource, label: nls.localize('defaultKeybindings', "Default Keybindings") });
N
Nilesh 已提交
287 288
	}

289
	configureSettingsForLanguage(language: string): void {
290
		this.openGlobalSettings(true)
S
Sandeep Somavarapu 已提交
291 292 293 294
			.then(editor => this.createPreferencesEditorModel(this.userSettingsResource)
				.then((settingsModel: IPreferencesEditorModel<ISetting>) => {
					const codeEditor = getCodeEditor(editor.getControl());
					if (codeEditor) {
S
Sandeep Somavarapu 已提交
295
						this.addLanguageOverrideEntry(language, settingsModel, codeEditor)
S
Sandeep Somavarapu 已提交
296
							.then(position => {
S
Sandeep Somavarapu 已提交
297
								if (codeEditor && position) {
S
Sandeep Somavarapu 已提交
298
									codeEditor.setPosition(position);
299
									codeEditor.revealLine(position.lineNumber);
S
Sandeep Somavarapu 已提交
300 301 302 303 304
									codeEditor.focus();
								}
							});
					}
				}));
305 306
	}

J
Johannes Rieken 已提交
307
	private openOrSwitchSettings(configurationTarget: ConfigurationTarget, resource: URI, options?: ISettingsEditorOptions, group: IEditorGroup = this.editorGroupService.activeGroup): Promise<IEditor> {
B
Benjamin Pasero 已提交
308
		const editorInput = this.getActiveSettingsEditorInput(group);
S
Sandeep Somavarapu 已提交
309 310 311 312 313
		if (editorInput) {
			const editorInputResource = editorInput.master.getResource();
			if (editorInputResource && editorInputResource.fsPath !== resource.fsPath) {
				return this.doSwitchSettings(configurationTarget, resource, editorInput, group, options);
			}
314
		}
B
Benjamin Pasero 已提交
315
		return this.doOpenSettings(configurationTarget, resource, options, group);
316 317
	}

J
Johannes Rieken 已提交
318
	private openOrSwitchSettings2(configurationTarget: ConfigurationTarget, folderUri?: URI, options?: ISettingsEditorOptions, group: IEditorGroup = this.editorGroupService.activeGroup): Promise<IEditor> {
319
		return this.doOpenSettings2(configurationTarget, folderUri, options, group);
320 321
	}

J
Johannes Rieken 已提交
322
	private doOpenSettings(configurationTarget: ConfigurationTarget, resource: URI, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor> {
323 324 325 326 327
		const openSplitJSON = !!this.configurationService.getValue(USE_SPLIT_JSON_SETTING);
		if (openSplitJSON) {
			return this.doOpenSplitJSON(configurationTarget, resource, options, group);
		}

S
Sandeep Somavarapu 已提交
328
		const openDefaultSettings = !!this.configurationService.getValue(DEFAULT_SETTINGS_EDITOR_SETTING);
329

330
		return this.getOrCreateEditableSettingsEditorInput(configurationTarget, resource)
331
			.then(editableSettingsEditorInput => {
332 333 334
				if (!options) {
					options = { pinned: true };
				} else {
335
					options = assign(options, { pinned: true });
336 337
				}

338
				if (openDefaultSettings) {
339 340 341 342 343
					const activeEditorGroup = this.editorGroupService.activeGroup;
					const sideEditorGroup = this.editorGroupService.addGroup(activeEditorGroup.id, GroupDirection.RIGHT);
					return Promise.all([
						this.editorService.openEditor({ resource: this.defaultSettingsRawResource, options: { pinned: true, preserveFocus: true, revealIfOpened: true }, label: nls.localize('defaultSettings', "Default Settings"), description: '' }),
						this.editorService.openEditor(editableSettingsEditorInput, { pinned: true, revealIfOpened: true }, sideEditorGroup.id)
S
Sandeep Somavarapu 已提交
344
					]).then(([defaultEditor, editor]) => editor);
345 346
				} else {
					return this.editorService.openEditor(editableSettingsEditorInput, SettingsEditorOptions.create(options), group);
347
				}
348
			});
349 350
	}

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
	private doOpenSplitJSON(configurationTarget: ConfigurationTarget, resource: URI, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor> {
		return this.getOrCreateEditableSettingsEditorInput(configurationTarget, resource)
			.then(editableSettingsEditorInput => {
				if (!options) {
					options = { pinned: true };
				} else {
					options = assign(options, { pinned: true });
				}

				const defaultPreferencesEditorInput = this.instantiationService.createInstance(DefaultPreferencesEditorInput, this.getDefaultSettingsResource(configurationTarget));
				const preferencesEditorInput = new PreferencesEditorInput(this.getPreferencesEditorInputName(configurationTarget, resource), editableSettingsEditorInput.getDescription(), defaultPreferencesEditorInput, <EditorInput>editableSettingsEditorInput);
				this.lastOpenedSettingsInput = preferencesEditorInput;
				return this.editorService.openEditor(preferencesEditorInput, SettingsEditorOptions.create(options), group);
			});
	}

367 368 369 370
	public createSettings2EditorModel(): Settings2EditorModel {
		return this.instantiationService.createInstance(Settings2EditorModel, this.getDefaultSettings(ConfigurationTarget.USER));
	}

J
Johannes Rieken 已提交
371
	private doOpenSettings2(target: ConfigurationTarget, folderUri: URI | undefined, options?: IEditorOptions, group?: IEditorGroup): Promise<IEditor> {
372 373 374 375 376 377 378 379
		const input = this.settingsEditor2Input;
		const settingsOptions: ISettingsEditorOptions = {
			...options,
			target,
			folderUri
		};

		return this.editorService.openEditor(input, SettingsEditorOptions.create(settingsOptions), group);
380 381
	}

J
Johannes Rieken 已提交
382
	private doSwitchSettings(target: ConfigurationTarget, resource: URI, input: PreferencesEditorInput, group: IEditorGroup, options?: ISettingsEditorOptions): Promise<IEditor> {
S
Sandeep Somavarapu 已提交
383 384 385 386 387
		const settingsURI = this.getEditableSettingsURI(target, resource);
		if (!settingsURI) {
			return Promise.reject(`Invalid settings URI - ${resource.toString()}`);
		}
		return this.getOrCreateEditableSettingsEditorInput(target, settingsURI)
388
			.then(toInput => {
B
Benjamin Pasero 已提交
389 390 391 392 393
				return group.openEditor(input).then(() => {
					const replaceWith = new PreferencesEditorInput(this.getPreferencesEditorInputName(target, resource), toInput.getDescription(), this.instantiationService.createInstance(DefaultPreferencesEditorInput, this.getDefaultSettingsResource(target)), toInput);

					return group.replaceEditors([{
						editor: input,
394
						replacement: replaceWith,
S
Sandeep Somavarapu 已提交
395
						options: options ? SettingsEditorOptions.create(options) : undefined
B
Benjamin Pasero 已提交
396 397
					}]).then(() => {
						this.lastOpenedSettingsInput = replaceWith;
S
Sandeep Somavarapu 已提交
398
						return group.activeControl!;
B
Benjamin Pasero 已提交
399
					});
400 401 402 403
				});
			});
	}

404
	private getActiveSettingsEditorInput(group: IEditorGroup = this.editorGroupService.activeGroup): PreferencesEditorInput {
B
Benjamin Pasero 已提交
405
		return <PreferencesEditorInput>group.editors.filter(e => e instanceof PreferencesEditorInput)[0];
406 407
	}

S
Sandeep Somavarapu 已提交
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
	private getConfigurationTargetFromSettingsResource(resource: URI): ConfigurationTarget {
		if (this.userSettingsResource.toString() === resource.toString()) {
			return ConfigurationTarget.USER;
		}

		const workspaceSettingsResource = this.workspaceSettingsResource;
		if (workspaceSettingsResource && workspaceSettingsResource.toString() === resource.toString()) {
			return ConfigurationTarget.WORKSPACE;
		}

		const folder = this.contextService.getWorkspaceFolder(resource);
		if (folder) {
			return ConfigurationTarget.WORKSPACE_FOLDER;
		}

		return ConfigurationTarget.USER;
	}

S
Sandeep Somavarapu 已提交
426 427 428 429
	private getConfigurationTargetFromDefaultSettingsResource(uri: URI) {
		return this.isDefaultWorkspaceSettingsResource(uri) ? ConfigurationTarget.WORKSPACE : this.isDefaultFolderSettingsResource(uri) ? ConfigurationTarget.WORKSPACE_FOLDER : ConfigurationTarget.USER;
	}

R
Rob Lourens 已提交
430
	private isDefaultSettingsResource(uri: URI): boolean {
S
Sandeep Somavarapu 已提交
431 432 433 434
		return this.isDefaultUserSettingsResource(uri) || this.isDefaultWorkspaceSettingsResource(uri) || this.isDefaultFolderSettingsResource(uri);
	}

	private isDefaultUserSettingsResource(uri: URI): boolean {
435
		return uri.authority === 'defaultsettings' && uri.scheme === network.Schemas.vscode && !!uri.path.match(/\/(\d+\/)?settings\.json$/);
R
Rob Lourens 已提交
436 437
	}

S
Sandeep Somavarapu 已提交
438 439 440 441 442
	private isDefaultWorkspaceSettingsResource(uri: URI): boolean {
		return uri.authority === 'defaultsettings' && uri.scheme === network.Schemas.vscode && !!uri.path.match(/\/(\d+\/)?workspaceSettings\.json$/);
	}

	private isDefaultFolderSettingsResource(uri: URI): boolean {
443
		return uri.authority === 'defaultsettings' && uri.scheme === network.Schemas.vscode && !!uri.path.match(/\/(\d+\/)?resourceSettings\.json$/);
R
Rob Lourens 已提交
444 445
	}

S
Sandeep Somavarapu 已提交
446
	private getDefaultSettingsResource(configurationTarget: ConfigurationTarget): URI {
S
Sandeep Somavarapu 已提交
447 448 449 450 451
		switch (configurationTarget) {
			case ConfigurationTarget.WORKSPACE:
				return URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: `/${this._defaultWorkspaceSettingsUriCounter++}/workspaceSettings.json` });
			case ConfigurationTarget.WORKSPACE_FOLDER:
				return URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: `/${this._defaultFolderSettingsUriCounter++}/resourceSettings.json` });
S
Sandeep Somavarapu 已提交
452
		}
S
Sandeep Somavarapu 已提交
453
		return URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: `/${this._defaultUserSettingsUriCounter++}/settings.json` });
S
Sandeep Somavarapu 已提交
454 455
	}

456 457
	private getPreferencesEditorInputName(target: ConfigurationTarget, resource: URI): string {
		const name = getSettingsTargetName(target, resource, this.contextService);
458
		return target === ConfigurationTarget.WORKSPACE_FOLDER ? nls.localize('folderSettingsName', "{0} (Folder Settings)", name) : name;
459 460
	}

J
Johannes Rieken 已提交
461
	private getOrCreateEditableSettingsEditorInput(target: ConfigurationTarget, resource: URI): Promise<EditorInput> {
462 463
		return this.createSettingsIfNotExists(target, resource)
			.then(() => <EditorInput>this.editorService.createInput({ resource }));
464 465
	}

J
Johannes Rieken 已提交
466
	private createEditableSettingsEditorModel(configurationTarget: ConfigurationTarget, resource: URI): Promise<SettingsEditorModel> {
467
		const settingsUri = this.getEditableSettingsURI(configurationTarget, resource);
468
		if (settingsUri) {
S
Sandeep Somavarapu 已提交
469 470 471 472
			const workspace = this.contextService.getWorkspace();
			if (workspace.configuration && workspace.configuration.toString() === settingsUri.toString()) {
				return this.textModelResolverService.createModelReference(settingsUri)
					.then(reference => this.instantiationService.createInstance(WorkspaceConfigurationEditorModel, reference, configurationTarget));
473
			}
474
			return this.textModelResolverService.createModelReference(settingsUri)
S
Sandeep Somavarapu 已提交
475
				.then(reference => this.instantiationService.createInstance(SettingsEditorModel, reference, configurationTarget));
476
		}
S
Sandeep Somavarapu 已提交
477
		return Promise.reject(`unknown target: ${configurationTarget} and resource: ${resource.toString()}`);
478 479
	}

J
Johannes Rieken 已提交
480
	private createDefaultSettingsEditorModel(defaultSettingsUri: URI): Promise<DefaultSettingsEditorModel> {
481 482
		return this.textModelResolverService.createModelReference(defaultSettingsUri)
			.then(reference => {
S
Sandeep Somavarapu 已提交
483 484
				const target = this.getConfigurationTargetFromDefaultSettingsResource(defaultSettingsUri);
				return this.instantiationService.createInstance(DefaultSettingsEditorModel, defaultSettingsUri, reference, this.getDefaultSettings(target));
485 486 487
			});
	}

S
Sandeep Somavarapu 已提交
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
	private getDefaultSettings(target: ConfigurationTarget): DefaultSettings {
		if (target === ConfigurationTarget.WORKSPACE) {
			if (!this._defaultWorkspaceSettingsContentModel) {
				this._defaultWorkspaceSettingsContentModel = new DefaultSettings(this.getMostCommonlyUsedSettings(), target);
			}
			return this._defaultWorkspaceSettingsContentModel;
		}
		if (target === ConfigurationTarget.WORKSPACE_FOLDER) {
			if (!this._defaultFolderSettingsContentModel) {
				this._defaultFolderSettingsContentModel = new DefaultSettings(this.getMostCommonlyUsedSettings(), target);
			}
			return this._defaultFolderSettingsContentModel;
		}
		if (!this._defaultUserSettingsContentModel) {
			this._defaultUserSettingsContentModel = new DefaultSettings(this.getMostCommonlyUsedSettings(), target);
503
		}
S
Sandeep Somavarapu 已提交
504
		return this._defaultUserSettingsContentModel;
505 506
	}

S
Sandeep Somavarapu 已提交
507
	private getEditableSettingsURI(configurationTarget: ConfigurationTarget, resource?: URI): URI | null {
508 509 510 511
		switch (configurationTarget) {
			case ConfigurationTarget.USER:
				return URI.file(this.environmentService.appSettingsPath);
			case ConfigurationTarget.WORKSPACE:
512
				if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
513 514
					return null;
				}
515
				const workspace = this.contextService.getWorkspace();
516
				return workspace.configuration || workspace.folders[0].toResource(FOLDER_SETTINGS_PATH);
517
			case ConfigurationTarget.WORKSPACE_FOLDER:
S
Sandeep Somavarapu 已提交
518 519 520 521
				if (resource) {
					const folder = this.contextService.getWorkspaceFolder(resource);
					return folder ? folder.toResource(FOLDER_SETTINGS_PATH) : null;
				}
522
		}
523
		return null;
524 525
	}

J
Johannes Rieken 已提交
526
	private createSettingsIfNotExists(target: ConfigurationTarget, resource: URI): Promise<void> {
527
		if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE && target === ConfigurationTarget.WORKSPACE) {
R
Rob Lourens 已提交
528 529
			const workspaceConfig = this.contextService.getWorkspace().configuration;
			if (!workspaceConfig) {
R
Rob Lourens 已提交
530
				return Promise.resolve(undefined);
R
Rob Lourens 已提交
531 532 533
			}

			return this.fileService.resolveContent(workspaceConfig)
S
Sandeep Somavarapu 已提交
534 535
				.then(content => {
					if (Object.keys(parse(content.value)).indexOf('settings') === -1) {
R
Rob Lourens 已提交
536
						return this.jsonEditingService.write(resource, { key: 'settings', value: {} }, true).then(undefined, () => { });
S
Sandeep Somavarapu 已提交
537
					}
S
Sandeep Somavarapu 已提交
538
					return undefined;
S
Sandeep Somavarapu 已提交
539
				});
540
		}
S
Sandeep Somavarapu 已提交
541
		return this.createIfNotExists(resource, emptyEditableSettingsContent).then(() => { });
542 543
	}

J
Johannes Rieken 已提交
544
	private createIfNotExists(resource: URI, contents: string): Promise<any> {
R
Rob Lourens 已提交
545
		return this.fileService.resolveContent(resource, { acceptTextOnly: true }).then(undefined, error => {
546
			if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
R
Rob Lourens 已提交
547
				return this.fileService.updateContent(resource, contents).then(undefined, error => {
R
Rob Lourens 已提交
548
					return Promise.reject(new Error(nls.localize('fail.createSettings', "Unable to create '{0}' ({1}).", this.labelService.getUriLabel(resource, { relative: true }), error)));
549 550 551
				});
			}

R
Rob Lourens 已提交
552
			return Promise.reject(error);
553 554 555
		});
	}

556 557
	private getMostCommonlyUsedSettings(): string[] {
		return [
S
Sandeep Somavarapu 已提交
558
			'files.autoSave',
559
			'editor.fontSize',
S
Sandeep Somavarapu 已提交
560 561 562
			'editor.fontFamily',
			'editor.tabSize',
			'editor.renderWhitespace',
S
Sandeep Somavarapu 已提交
563
			'editor.cursorStyle',
564
			'editor.multiCursorModifier',
S
Sandeep Somavarapu 已提交
565
			'editor.insertSpaces',
566
			'editor.wordWrap',
567
			'files.exclude',
S
Sandeep Somavarapu 已提交
568
			'files.associations'
569
		];
S
Sandeep Somavarapu 已提交
570
	}
571

S
Sandeep Somavarapu 已提交
572
	private addLanguageOverrideEntry(language: string, settingsModel: IPreferencesEditorModel<ISetting>, codeEditor: ICodeEditor): Promise<IPosition | null> {
S
Sandeep Somavarapu 已提交
573 574 575
		const languageKey = `[${language}]`;
		let setting = settingsModel.getPreference(languageKey);
		const model = codeEditor.getModel();
S
Sandeep Somavarapu 已提交
576 577 578 579 580 581 582 583 584
		if (model) {
			const configuration = this.configurationService.getValue<{ editor: { tabSize: number; insertSpaces: boolean } }>();
			const eol = model.getEOL();
			if (setting) {
				if (setting.overrides && setting.overrides.length) {
					const lastSetting = setting.overrides[setting.overrides.length - 1];
					return Promise.resolve({ lineNumber: lastSetting.valueRange.endLineNumber, column: model.getLineMaxColumn(lastSetting.valueRange.endLineNumber) });
				}
				return Promise.resolve({ lineNumber: setting.valueRange.startLineNumber, column: setting.valueRange.startColumn + 1 });
S
Sandeep Somavarapu 已提交
585
			}
S
Sandeep Somavarapu 已提交
586 587 588 589 590 591 592 593 594 595 596 597 598
			return this.configurationService.updateValue(languageKey, {}, ConfigurationTarget.USER)
				.then(() => {
					setting = settingsModel.getPreference(languageKey);
					if (setting) {
						let content = eol + this.spaces(2, configuration.editor) + eol + this.spaces(1, configuration.editor);
						let editOperation = EditOperation.insert(new Position(setting.valueRange.endLineNumber, setting.valueRange.endColumn - 1), content);
						model.pushEditOperations([], [editOperation], () => []);
						let lineNumber = setting.valueRange.endLineNumber + 1;
						settingsModel.dispose();
						return { lineNumber, column: model.getLineMaxColumn(lineNumber) };
					}
					return null;
				});
S
Sandeep Somavarapu 已提交
599
		}
S
Sandeep Somavarapu 已提交
600
		return Promise.resolve(null);
601 602
	}

A
Alex Dima 已提交
603
	private spaces(count: number, { tabSize, insertSpaces }: { tabSize: number; insertSpaces: boolean }): string {
604 605 606
		return insertSpaces ? strings.repeat(' ', tabSize * count) : strings.repeat('\t', count);
	}

607
	public dispose(): void {
608
		this._onDispose.fire();
609 610
		super.dispose();
	}
611
}
612 613

registerSingleton(IPreferencesService, PreferencesService);