preferencesService.ts 26.7 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
import { assign } from 'vs/base/common/objects';
import * as strings from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
13
import { TPromise } from 'vs/base/common/winjs.base';
14 15 16 17 18 19 20
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';
21
import * as nls from 'vs/nls';
22
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
B
Benjamin Pasero 已提交
23
import { IEditorOptions } from 'vs/platform/editor/common/editor';
24
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
25 26
import { FileOperationError, FileOperationResult, IFileService } from 'vs/platform/files/common/files';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
27
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
28
import { ILabelService } from 'vs/platform/label/common/label';
29
import { INotificationService } from 'vs/platform/notification/common/notification';
30 31 32 33 34
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 { IWorkspaceConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
import { IJSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditing';
B
Benjamin Pasero 已提交
35
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
36 37 38 39
import { GroupDirection, IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/group/common/editorGroupsService';
import { DEFAULT_SETTINGS_EDITOR_SETTING, FOLDER_SETTINGS_PATH, getSettingsTargetName, IPreferencesEditorModel, IPreferencesService, ISetting, ISettingsEditorOptions, SettingsEditorOptions } from 'vs/workbench/services/preferences/common/preferences';
import { DefaultPreferencesEditorInput, KeybindingsEditorInput, PreferencesEditorInput, SettingsEditor2Input } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
import { defaultKeybindingsContents, DefaultKeybindingsEditorModel, DefaultSettings, DefaultSettingsEditorModel, Settings2EditorModel, SettingsEditorModel, WorkspaceConfigurationEditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
40

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

43
export class PreferencesService extends Disposable implements IPreferencesService {
44 45

	_serviceBrand: any;
46

47
	private lastOpenedSettingsInput: PreferencesEditorInput = null;
48

M
Matt Bierner 已提交
49
	private readonly _onDispose: Emitter<void> = new Emitter<void>();
50

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

58
	constructor(
59 60
		@IEditorService private editorService: IEditorService,
		@IEditorGroupsService private editorGroupService: IEditorGroupsService,
61 62
		@IFileService private fileService: IFileService,
		@IWorkspaceConfigurationService private configurationService: IWorkspaceConfigurationService,
63
		@INotificationService private notificationService: INotificationService,
64 65 66
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IEnvironmentService private environmentService: IEnvironmentService,
67
		@ITelemetryService private telemetryService: ITelemetryService,
68
		@ITextModelService private textModelResolverService: ITextModelService,
69
		@IKeybindingService keybindingService: IKeybindingService,
70
		@IModelService private modelService: IModelService,
71
		@IJSONEditingService private jsonEditingService: IJSONEditingService,
I
isidor 已提交
72
		@IModeService private modeService: IModeService,
I
isidor 已提交
73
		@ILabelService private labelService: ILabelService
74 75
	) {
		super();
76 77 78 79 80 81 82 83
		// 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.
		keybindingService.onDidUpdateKeybindings(() => {
			const model = modelService.getModel(this.defaultKeybindingsResource);
			if (!model) {
				// model has not been given out => nothing to do
				return;
			}
84
			modelService.updateModel(model, defaultKeybindingsContents(keybindingService));
85
		});
86 87
	}

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

91 92 93 94 95 96 97 98
	get userSettingsResource(): URI {
		return this.getEditableSettingsURI(ConfigurationTarget.USER);
	}

	get workspaceSettingsResource(): URI {
		return this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE);
	}

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

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

A
Alex Dima 已提交
107
	resolveModel(uri: URI): TPromise<ITextModel> {
S
Sandeep Somavarapu 已提交
108
		if (this.isDefaultSettingsResource(uri)) {
S
Sandeep Somavarapu 已提交
109

S
Sandeep Somavarapu 已提交
110
			const target = this.getConfigurationTargetFromDefaultSettingsResource(uri);
111
			const mode = this.modeService.getOrCreateMode('jsonc');
S
Sandeep Somavarapu 已提交
112 113 114 115 116 117 118 119 120 121
			const model = this._register(this.modelService.createModel('', mode, uri));

			let defaultSettings: DefaultSettings;
			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 已提交
122
					defaultSettings = this.getDefaultSettings(target);
123
					this.modelService.updateModel(model, defaultSettings.getContent(true));
124
					defaultSettings._onDidChange.fire();
S
Sandeep Somavarapu 已提交
125 126 127 128 129
				}
			});

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

			return TPromise.as(model);
135 136
		}

S
Sandeep Somavarapu 已提交
137
		if (this.defaultSettingsRawResource.toString() === uri.toString()) {
S
Sandeep Somavarapu 已提交
138
			let defaultSettings: DefaultSettings = this.getDefaultSettings(ConfigurationTarget.USER);
139
			const mode = this.modeService.getOrCreateMode('jsonc');
S
Sandeep Somavarapu 已提交
140 141 142 143
			const model = this._register(this.modelService.createModel(defaultSettings.raw, mode, uri));
			return TPromise.as(model);
		}

144
		if (this.defaultKeybindingsResource.toString() === uri.toString()) {
S
Sandeep Somavarapu 已提交
145
			const defaultKeybindingsEditorModel = this.instantiationService.createInstance(DefaultKeybindingsEditorModel, uri);
146
			const mode = this.modeService.getOrCreateMode('jsonc');
S
Sandeep Somavarapu 已提交
147 148
			const model = this._register(this.modelService.createModel(defaultKeybindingsEditorModel.content, mode, uri));
			return TPromise.as(model);
149 150 151 152 153 154
		}

		return TPromise.as(null);
	}

	createPreferencesEditorModel(uri: URI): TPromise<IPreferencesEditorModel<any>> {
S
Sandeep Somavarapu 已提交
155
		if (this.isDefaultSettingsResource(uri)) {
156
			return this.createDefaultSettingsEditorModel(uri);
157 158
		}

159
		if (this.getEditableSettingsURI(ConfigurationTarget.USER).toString() === uri.toString()) {
160
			return this.createEditableSettingsEditorModel(ConfigurationTarget.USER, uri);
161
		}
162

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

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

172
		return TPromise.wrap<IPreferencesEditorModel<any>>(null);
173 174
	}

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

B
Benjamin Pasero 已提交
179
	openRawUserSettings(): TPromise<IEditor> {
180
		return this.editorService.openEditor({ resource: this.userSettingsResource });
S
Sandeep Somavarapu 已提交
181 182
	}

183 184 185 186 187
	openSettings(jsonEditor?: boolean): TPromise<IEditor> {
		if (!jsonEditor) {
			return this.openSettings2();
		}

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

194
	private openSettings2(): TPromise<IEditor> {
195 196 197
		const input = this.settingsEditor2Input;
		return this.editorGroupService.activeGroup.openEditor(input)
			.then(() => this.editorGroupService.activeGroup.activeControl);
198 199
	}

200 201 202
	openGlobalSettings(jsonEditor?: boolean, options?: IEditorOptions, group?: IEditorGroup): TPromise<IEditor> {
		return jsonEditor ?
			this.openOrSwitchSettings(ConfigurationTarget.USER, this.userSettingsResource, options, group) :
203
			this.openOrSwitchSettings2(ConfigurationTarget.USER, undefined, options, group);
R
Rob Lourens 已提交
204 205
	}

206
	openWorkspaceSettings(jsonEditor?: boolean, options?: IEditorOptions, group?: IEditorGroup): TPromise<IEditor> {
207
		if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
208
			this.notificationService.info(nls.localize('openFolderFirst', "Open a folder first to create workspace settings"));
S
Sandeep Somavarapu 已提交
209
			return TPromise.as(null);
210
		}
211 212 213

		return jsonEditor ?
			this.openOrSwitchSettings(ConfigurationTarget.WORKSPACE, this.workspaceSettingsResource, options, group) :
214
			this.openOrSwitchSettings2(ConfigurationTarget.WORKSPACE, undefined, options, group);
215 216
	}

217 218 219
	openFolderSettings(folder: URI, jsonEditor?: boolean, options?: IEditorOptions, group?: IEditorGroup): TPromise<IEditor> {
		return jsonEditor ?
			this.openOrSwitchSettings(ConfigurationTarget.WORKSPACE_FOLDER, this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE_FOLDER, folder), options, group) :
220
			this.openOrSwitchSettings2(ConfigurationTarget.WORKSPACE_FOLDER, folder, options, group);
221 222
	}

223 224
	switchSettings(target: ConfigurationTarget, resource: URI, jsonEditor?: boolean): TPromise<void> {
		if (!jsonEditor) {
225
			return this.doOpenSettings2(target, resource).then(() => null);
226 227
		}

B
Benjamin Pasero 已提交
228 229
		const activeControl = this.editorService.activeControl;
		if (activeControl && activeControl.input instanceof PreferencesEditorInput) {
230
			return this.doSwitchSettings(target, resource, activeControl.input, activeControl.group).then(() => null);
231
		} else {
232
			return this.doOpenSettings(target, resource).then(() => null);
233
		}
234 235
	}

S
Sandeep Somavarapu 已提交
236
	openGlobalKeybindingSettings(textual: boolean): TPromise<void> {
K
kieferrm 已提交
237
		/* __GDPR__
K
kieferrm 已提交
238
			"openKeybindings" : {
K
kieferrm 已提交
239
				"textual" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
K
kieferrm 已提交
240 241
			}
		*/
242
		this.telemetryService.publicLog('openKeybindings', { textual });
S
Sandeep Somavarapu 已提交
243 244 245
		if (textual) {
			const emptyContents = '// ' + nls.localize('emptyKeybindingsHeader', "Place your key bindings in this file to overwrite the defaults") + '\n[\n]';
			const editableKeybindings = URI.file(this.environmentService.appKeybindingsPath);
N
Nilesh 已提交
246
			const openDefaultKeybindings = !!this.configurationService.getValue('workbench.settings.openDefaultKeybindings');
S
Sandeep Somavarapu 已提交
247 248

			// Create as needed and open in editor
S
Sandeep Somavarapu 已提交
249 250
			return this.createIfNotExists(editableKeybindings, emptyContents).then(() => {
				if (openDefaultKeybindings) {
N
Nilesh 已提交
251 252 253 254 255 256
					const activeEditorGroup = this.editorGroupService.activeGroup;
					const sideEditorGroup = this.editorGroupService.addGroup(activeEditorGroup.id, GroupDirection.RIGHT);
					return TPromise.join([
						this.editorService.openEditor({ resource: this.defaultKeybindingsResource, options: { pinned: true, preserveFocus: true }, label: nls.localize('defaultKeybindings', "Default Keybindings"), description: '' }),
						this.editorService.openEditor({ resource: editableKeybindings, options: { pinned: true } }, sideEditorGroup.id)
					]).then(editors => void 0);
S
Sandeep Somavarapu 已提交
257 258 259
				} else {
					return this.editorService.openEditor({ resource: editableKeybindings, options: { pinned: true } }).then(() => void 0);
				}
S
Sandeep Somavarapu 已提交
260 261
			});
		}
262

N
Nilesh 已提交
263
		return this.editorService.openEditor(this.instantiationService.createInstance(KeybindingsEditorInput), { pinned: true }).then(() => null);
264 265
	}

S
Sandeep Somavarapu 已提交
266
	openDefaultKeybindingsFile(): TPromise<IEditor> {
N
Nilesh 已提交
267 268 269
		return this.editorService.openEditor({ resource: this.defaultKeybindingsResource });
	}

270 271
	configureSettingsForLanguage(language: string): void {
		this.openGlobalSettings()
S
Sandeep Somavarapu 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284
			.then(editor => this.createPreferencesEditorModel(this.userSettingsResource)
				.then((settingsModel: IPreferencesEditorModel<ISetting>) => {
					const codeEditor = getCodeEditor(editor.getControl());
					if (codeEditor) {
						this.getPosition(language, settingsModel, codeEditor)
							.then(position => {
								if (codeEditor) {
									codeEditor.setPosition(position);
									codeEditor.focus();
								}
							});
					}
				}));
285 286
	}

287
	private openOrSwitchSettings(configurationTarget: ConfigurationTarget, resource: URI, options?: IEditorOptions, group: IEditorGroup = this.editorGroupService.activeGroup): TPromise<IEditor> {
B
Benjamin Pasero 已提交
288
		const editorInput = this.getActiveSettingsEditorInput(group);
289
		if (editorInput && editorInput.master.getResource().fsPath !== resource.fsPath) {
B
Benjamin Pasero 已提交
290
			return this.doSwitchSettings(configurationTarget, resource, editorInput, group);
291
		}
B
Benjamin Pasero 已提交
292
		return this.doOpenSettings(configurationTarget, resource, options, group);
293 294
	}

295
	private openOrSwitchSettings2(configurationTarget: ConfigurationTarget, folderUri?: URI, options?: IEditorOptions, group: IEditorGroup = this.editorGroupService.activeGroup): TPromise<IEditor> {
296
		return this.doOpenSettings2(configurationTarget, folderUri, options, group);
297 298
	}

299
	private doOpenSettings(configurationTarget: ConfigurationTarget, resource: URI, options?: IEditorOptions, group?: IEditorGroup): TPromise<IEditor> {
S
Sandeep Somavarapu 已提交
300
		const openDefaultSettings = !!this.configurationService.getValue(DEFAULT_SETTINGS_EDITOR_SETTING);
301
		return this.getOrCreateEditableSettingsEditorInput(configurationTarget, resource)
302
			.then(editableSettingsEditorInput => {
303 304 305
				if (!options) {
					options = { pinned: true };
				} else {
306
					options = assign(options, { pinned: true });
307 308
				}

309
				if (openDefaultSettings) {
S
Sandeep Somavarapu 已提交
310
					const defaultPreferencesEditorInput = this.instantiationService.createInstance(DefaultPreferencesEditorInput, this.getDefaultSettingsResource(configurationTarget));
311
					const preferencesEditorInput = new PreferencesEditorInput(this.getPreferencesEditorInputName(configurationTarget, resource), editableSettingsEditorInput.getDescription(), defaultPreferencesEditorInput, <EditorInput>editableSettingsEditorInput);
312
					this.lastOpenedSettingsInput = preferencesEditorInput;
B
Benjamin Pasero 已提交
313
					return this.editorService.openEditor(preferencesEditorInput, options, group);
314
				}
B
Benjamin Pasero 已提交
315
				return this.editorService.openEditor(editableSettingsEditorInput, options, group);
316
			});
317 318
	}

319 320 321 322 323 324 325 326 327 328 329 330 331 332
	public createSettings2EditorModel(): Settings2EditorModel {
		// TODO
		return this.instantiationService.createInstance(Settings2EditorModel, this.getDefaultSettings(ConfigurationTarget.USER));
	}

	private doOpenSettings2(target: ConfigurationTarget, folderUri: URI | undefined, options?: IEditorOptions, group?: IEditorGroup): TPromise<IEditor> {
		const input = this.settingsEditor2Input;
		const settingsOptions: ISettingsEditorOptions = {
			...options,
			target,
			folderUri
		};

		return this.editorService.openEditor(input, SettingsEditorOptions.create(settingsOptions), group);
333 334
	}

335
	private doSwitchSettings(target: ConfigurationTarget, resource: URI, input: PreferencesEditorInput, group: IEditorGroup): TPromise<IEditor> {
336 337
		return this.getOrCreateEditableSettingsEditorInput(target, this.getEditableSettingsURI(target, resource))
			.then(toInput => {
B
Benjamin Pasero 已提交
338 339 340 341 342 343 344 345 346 347
				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,
						replacement: replaceWith
					}]).then(() => {
						this.lastOpenedSettingsInput = replaceWith;
						return group.activeControl;
					});
348 349 350 351
				});
			});
	}

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

S
Sandeep Somavarapu 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
	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 已提交
374 375 376 377
	private getConfigurationTargetFromDefaultSettingsResource(uri: URI) {
		return this.isDefaultWorkspaceSettingsResource(uri) ? ConfigurationTarget.WORKSPACE : this.isDefaultFolderSettingsResource(uri) ? ConfigurationTarget.WORKSPACE_FOLDER : ConfigurationTarget.USER;
	}

R
Rob Lourens 已提交
378
	private isDefaultSettingsResource(uri: URI): boolean {
S
Sandeep Somavarapu 已提交
379 380 381 382
		return this.isDefaultUserSettingsResource(uri) || this.isDefaultWorkspaceSettingsResource(uri) || this.isDefaultFolderSettingsResource(uri);
	}

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

S
Sandeep Somavarapu 已提交
386 387 388 389 390
	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 {
391
		return uri.authority === 'defaultsettings' && uri.scheme === network.Schemas.vscode && !!uri.path.match(/\/(\d+\/)?resourceSettings\.json$/);
R
Rob Lourens 已提交
392 393
	}

S
Sandeep Somavarapu 已提交
394
	private getDefaultSettingsResource(configurationTarget: ConfigurationTarget): URI {
S
Sandeep Somavarapu 已提交
395 396 397 398 399
		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 已提交
400
		}
S
Sandeep Somavarapu 已提交
401
		return URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: `/${this._defaultUserSettingsUriCounter++}/settings.json` });
S
Sandeep Somavarapu 已提交
402 403
	}

404 405
	private getPreferencesEditorInputName(target: ConfigurationTarget, resource: URI): string {
		const name = getSettingsTargetName(target, resource, this.contextService);
406
		return target === ConfigurationTarget.WORKSPACE_FOLDER ? nls.localize('folderSettingsName', "{0} (Folder Settings)", name) : name;
407 408
	}

409 410 411
	private getOrCreateEditableSettingsEditorInput(target: ConfigurationTarget, resource: URI): TPromise<EditorInput> {
		return this.createSettingsIfNotExists(target, resource)
			.then(() => <EditorInput>this.editorService.createInput({ resource }));
412 413
	}

414 415
	private createEditableSettingsEditorModel(configurationTarget: ConfigurationTarget, resource: URI): TPromise<SettingsEditorModel> {
		const settingsUri = this.getEditableSettingsURI(configurationTarget, resource);
416
		if (settingsUri) {
S
Sandeep Somavarapu 已提交
417 418 419 420
			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));
421
			}
422
			return this.textModelResolverService.createModelReference(settingsUri)
S
Sandeep Somavarapu 已提交
423
				.then(reference => this.instantiationService.createInstance(SettingsEditorModel, reference, configurationTarget));
424
		}
425
		return TPromise.wrap<SettingsEditorModel>(null);
426 427
	}

428 429 430
	private createDefaultSettingsEditorModel(defaultSettingsUri: URI): TPromise<DefaultSettingsEditorModel> {
		return this.textModelResolverService.createModelReference(defaultSettingsUri)
			.then(reference => {
S
Sandeep Somavarapu 已提交
431 432
				const target = this.getConfigurationTargetFromDefaultSettingsResource(defaultSettingsUri);
				return this.instantiationService.createInstance(DefaultSettingsEditorModel, defaultSettingsUri, reference, this.getDefaultSettings(target));
433 434 435
			});
	}

S
Sandeep Somavarapu 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
	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);
451
		}
S
Sandeep Somavarapu 已提交
452
		return this._defaultUserSettingsContentModel;
453 454
	}

455
	private getEditableSettingsURI(configurationTarget: ConfigurationTarget, resource?: URI): URI {
456 457 458 459
		switch (configurationTarget) {
			case ConfigurationTarget.USER:
				return URI.file(this.environmentService.appSettingsPath);
			case ConfigurationTarget.WORKSPACE:
460
				if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
461 462
					return null;
				}
463
				const workspace = this.contextService.getWorkspace();
464
				return workspace.configuration || workspace.folders[0].toResource(FOLDER_SETTINGS_PATH);
465
			case ConfigurationTarget.WORKSPACE_FOLDER:
S
Sandeep Somavarapu 已提交
466
				const folder = this.contextService.getWorkspaceFolder(resource);
467
				return folder ? folder.toResource(FOLDER_SETTINGS_PATH) : null;
468
		}
469
		return null;
470 471
	}

472
	private createSettingsIfNotExists(target: ConfigurationTarget, resource: URI): TPromise<void> {
473
		if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE && target === ConfigurationTarget.WORKSPACE) {
S
Sandeep Somavarapu 已提交
474 475 476 477 478 479 480
			return this.fileService.resolveContent(this.contextService.getWorkspace().configuration)
				.then(content => {
					if (Object.keys(parse(content.value)).indexOf('settings') === -1) {
						return this.jsonEditingService.write(resource, { key: 'settings', value: {} }, true).then(null, () => { });
					}
					return null;
				});
481
		}
S
Sandeep Somavarapu 已提交
482
		return this.createIfNotExists(resource, emptyEditableSettingsContent).then(() => { });
483 484
	}

R
Ron Buckton 已提交
485
	private createIfNotExists(resource: URI, contents: string): TPromise<any> {
486
		return this.fileService.resolveContent(resource, { acceptTextOnly: true }).then(null, error => {
487
			if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
488
				return this.fileService.updateContent(resource, contents).then(null, error => {
I
isidor 已提交
489
					return TPromise.wrapError(new Error(nls.localize('fail.createSettings', "Unable to create '{0}' ({1}).", this.labelService.getUriLabel(resource, true), error)));
490 491 492
				});
			}

R
Ron Buckton 已提交
493
			return TPromise.wrapError(error);
494 495 496
		});
	}

497 498
	private getMostCommonlyUsedSettings(): string[] {
		return [
S
Sandeep Somavarapu 已提交
499
			'files.autoSave',
500
			'editor.fontSize',
S
Sandeep Somavarapu 已提交
501 502 503
			'editor.fontFamily',
			'editor.tabSize',
			'editor.renderWhitespace',
S
Sandeep Somavarapu 已提交
504
			'editor.cursorStyle',
505
			'editor.multiCursorModifier',
S
Sandeep Somavarapu 已提交
506
			'editor.insertSpaces',
507
			'editor.wordWrap',
508
			'files.exclude',
S
Sandeep Somavarapu 已提交
509
			'files.associations'
510
		];
S
Sandeep Somavarapu 已提交
511
	}
512

S
Sandeep Somavarapu 已提交
513 514 515 516 517 518 519 520 521 522 523 524 525 526
	private getPosition(language: string, settingsModel: IPreferencesEditorModel<ISetting>, codeEditor: ICodeEditor): TPromise<IPosition> {
		const languageKey = `[${language}]`;
		let setting = settingsModel.getPreference(languageKey);
		const model = codeEditor.getModel();
		const configuration = this.configurationService.getValue<{ editor: { tabSize: number; insertSpaces: boolean }, files: { eol: string } }>();
		const eol = configuration.files && configuration.files.eol;
		if (setting) {
			if (setting.overrides.length) {
				const lastSetting = setting.overrides[setting.overrides.length - 1];
				let content;
				if (lastSetting.valueRange.endLineNumber === setting.range.endLineNumber) {
					content = ',' + eol + this.spaces(2, configuration.editor) + eol + this.spaces(1, configuration.editor);
				} else {
					content = ',' + eol + this.spaces(2, configuration.editor);
527
				}
S
Sandeep Somavarapu 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
				const editOperation = EditOperation.insert(new Position(lastSetting.valueRange.endLineNumber, lastSetting.valueRange.endColumn), content);
				model.pushEditOperations([], [editOperation], () => []);
				return TPromise.as({ lineNumber: lastSetting.valueRange.endLineNumber + 1, column: model.getLineMaxColumn(lastSetting.valueRange.endLineNumber + 1) });
			}
			return TPromise.as({ lineNumber: setting.valueRange.startLineNumber, column: setting.valueRange.startColumn + 1 });
		}
		return this.configurationService.updateValue(languageKey, {}, ConfigurationTarget.USER)
			.then(() => {
				setting = settingsModel.getPreference(languageKey);
				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) };
543 544 545
			});
	}

A
Alex Dima 已提交
546
	private spaces(count: number, { tabSize, insertSpaces }: { tabSize: number; insertSpaces: boolean }): string {
547 548 549
		return insertSpaces ? strings.repeat(' ', tabSize * count) : strings.repeat('\t', count);
	}

550
	public dispose(): void {
551
		this._onDispose.fire();
552 553
		super.dispose();
	}
554
}