keybindingEditing.ts 12.3 KB
Newer Older
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import { localize } from 'vs/nls';
import URI from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
S
Sandeep Somavarapu 已提交
9
import { isArray } from 'vs/base/common/types';
10 11 12 13 14 15
import { Queue } from 'vs/base/common/async';
import { IReference, Disposable } from 'vs/base/common/lifecycle';
import * as json from 'vs/base/common/json';
import { Edit } from 'vs/base/common/jsonFormatter';
import { setProperty } from 'vs/base/common/jsonEdit';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
16
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
17 18 19
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
20
import { IUserFriendlyKeybinding } from 'vs/platform/keybinding/common/keybinding';
21
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
22
import { ITextModelService, ITextEditorModel } from 'vs/editor/common/services/resolverService';
23 24
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IFileService } from 'vs/platform/files/common/files';
25
import { createDecorator, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation';
26
import { ResolvedKeybindingItem } from 'vs/platform/keybinding/common/resolvedKeybindingItem';
A
Alex Dima 已提交
27
import { ITextModel } from 'vs/editor/common/model';
28

29 30 31 32 33 34 35 36 37 38 39 40 41 42

export const IKeybindingEditingService = createDecorator<IKeybindingEditingService>('keybindingEditingService');

export interface IKeybindingEditingService {

	_serviceBrand: ServiceIdentifier<any>;

	editKeybinding(key: string, keybindingItem: ResolvedKeybindingItem): TPromise<void>;

	removeKeybinding(keybindingItem: ResolvedKeybindingItem): TPromise<void>;

	resetKeybinding(keybindingItem: ResolvedKeybindingItem): TPromise<void>;
}

43 44 45 46 47 48 49 50
export class KeybindingsEditingService extends Disposable implements IKeybindingEditingService {

	public _serviceBrand: any;
	private queue: Queue<void>;

	private resource: URI = URI.file(this.environmentService.appKeybindingsPath);

	constructor(
51
		@ITextModelService private textModelResolverService: ITextModelService,
52 53
		@ITextFileService private textFileService: ITextFileService,
		@IFileService private fileService: IFileService,
54
		@IConfigurationService private configurationService: IConfigurationService,
55 56 57 58 59 60
		@IEnvironmentService private environmentService: IEnvironmentService
	) {
		super();
		this.queue = new Queue<void>();
	}

61
	editKeybinding(key: string, keybindingItem: ResolvedKeybindingItem): TPromise<void> {
62 63 64
		return this.queue.queue(() => this.doEditKeybinding(key, keybindingItem)); // queue up writes to prevent race conditions
	}

65 66 67 68
	resetKeybinding(keybindingItem: ResolvedKeybindingItem): TPromise<void> {
		return this.queue.queue(() => this.doResetKeybinding(keybindingItem)); // queue up writes to prevent race conditions
	}

69
	removeKeybinding(keybindingItem: ResolvedKeybindingItem): TPromise<void> {
70 71 72
		return this.queue.queue(() => this.doRemoveKeybinding(keybindingItem)); // queue up writes to prevent race conditions
	}

73
	private doEditKeybinding(key: string, keybindingItem: ResolvedKeybindingItem): TPromise<void> {
74 75 76
		return this.resolveAndValidate()
			.then(reference => {
				const model = reference.object.textEditorModel;
77
				if (keybindingItem.isDefault) {
78
					this.updateDefaultKeybinding(key, keybindingItem, model);
79 80
				} else {
					this.updateUserKeybinding(key, keybindingItem, model);
81 82 83 84 85
				}
				return this.save().then(() => reference.dispose());
			});
	}

86
	private doRemoveKeybinding(keybindingItem: ResolvedKeybindingItem): TPromise<void> {
87 88 89
		return this.resolveAndValidate()
			.then(reference => {
				const model = reference.object.textEditorModel;
90
				if (keybindingItem.isDefault) {
91
					this.removeDefaultKeybinding(keybindingItem, model);
92 93
				} else {
					this.removeUserKeybinding(keybindingItem, model);
94 95 96 97 98
				}
				return this.save().then(() => reference.dispose());
			});
	}

99 100 101 102 103 104 105 106 107 108 109 110
	private doResetKeybinding(keybindingItem: ResolvedKeybindingItem): TPromise<void> {
		return this.resolveAndValidate()
			.then(reference => {
				const model = reference.object.textEditorModel;
				if (!keybindingItem.isDefault) {
					this.removeUserKeybinding(keybindingItem, model);
					this.removeUnassignedDefaultKeybinding(keybindingItem, model);
				}
				return this.save().then(() => reference.dispose());
			});
	}

111
	private save(): TPromise<any> {
112
		return this.textFileService.save(this.resource);
113 114
	}

A
Alex Dima 已提交
115
	private updateUserKeybinding(newKey: string, keybindingItem: ResolvedKeybindingItem, model: ITextModel): void {
A
Alex Dima 已提交
116
		const { tabSize, insertSpaces } = model.getOptions();
117 118
		const eol = model.getEOL();
		const userKeybindingEntries = <IUserFriendlyKeybinding[]>json.parse(model.getValue());
119 120 121
		const userKeybindingEntryIndex = this.findUserKeybindingEntryIndex(keybindingItem, userKeybindingEntries);
		if (userKeybindingEntryIndex !== -1) {
			this.applyEditsToBuffer(setProperty(model.getValue(), [userKeybindingEntryIndex, 'key'], newKey, { tabSize, insertSpaces, eol })[0], model);
122 123 124
		}
	}

A
Alex Dima 已提交
125
	private updateDefaultKeybinding(newKey: string, keybindingItem: ResolvedKeybindingItem, model: ITextModel): void {
A
Alex Dima 已提交
126
		const { tabSize, insertSpaces } = model.getOptions();
127 128
		const eol = model.getEOL();
		const userKeybindingEntries = <IUserFriendlyKeybinding[]>json.parse(model.getValue());
129 130
		const userKeybindingEntryIndex = this.findUserKeybindingEntryIndex(keybindingItem, userKeybindingEntries);
		if (userKeybindingEntryIndex !== -1) {
131
			// Update the keybinding with new key
132
			this.applyEditsToBuffer(setProperty(model.getValue(), [userKeybindingEntryIndex, 'key'], newKey, { tabSize, insertSpaces, eol })[0], model);
133 134 135 136
		} else {
			// Add the new keybinidng with new key
			this.applyEditsToBuffer(setProperty(model.getValue(), [-1], this.asObject(newKey, keybindingItem.command, keybindingItem.when, false), { tabSize, insertSpaces, eol })[0], model);
		}
137
		if (keybindingItem.resolvedKeybinding) {
138
			// Unassign the default keybinding
139
			this.applyEditsToBuffer(setProperty(model.getValue(), [-1], this.asObject(keybindingItem.resolvedKeybinding.getUserSettingsLabel(), keybindingItem.command, keybindingItem.when, true), { tabSize, insertSpaces, eol })[0], model);
140 141 142
		}
	}

A
Alex Dima 已提交
143
	private removeUserKeybinding(keybindingItem: ResolvedKeybindingItem, model: ITextModel): void {
A
Alex Dima 已提交
144
		const { tabSize, insertSpaces } = model.getOptions();
145
		const eol = model.getEOL();
146
		const userKeybindingEntries = <IUserFriendlyKeybinding[]>json.parse(model.getValue());
147 148 149
		const userKeybindingEntryIndex = this.findUserKeybindingEntryIndex(keybindingItem, userKeybindingEntries);
		if (userKeybindingEntryIndex !== -1) {
			this.applyEditsToBuffer(setProperty(model.getValue(), [userKeybindingEntryIndex], void 0, { tabSize, insertSpaces, eol })[0], model);
150 151 152
		}
	}

A
Alex Dima 已提交
153
	private removeDefaultKeybinding(keybindingItem: ResolvedKeybindingItem, model: ITextModel): void {
A
Alex Dima 已提交
154
		const { tabSize, insertSpaces } = model.getOptions();
155
		const eol = model.getEOL();
156
		this.applyEditsToBuffer(setProperty(model.getValue(), [-1], this.asObject(keybindingItem.resolvedKeybinding.getUserSettingsLabel(), keybindingItem.command, keybindingItem.when, true), { tabSize, insertSpaces, eol })[0], model);
157 158
	}

A
Alex Dima 已提交
159
	private removeUnassignedDefaultKeybinding(keybindingItem: ResolvedKeybindingItem, model: ITextModel): void {
A
Alex Dima 已提交
160
		const { tabSize, insertSpaces } = model.getOptions();
161 162
		const eol = model.getEOL();
		const userKeybindingEntries = <IUserFriendlyKeybinding[]>json.parse(model.getValue());
S
Sandeep Somavarapu 已提交
163 164
		const indices = this.findUnassignedDefaultKeybindingEntryIndex(keybindingItem, userKeybindingEntries).reverse();
		for (const index of indices) {
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
			this.applyEditsToBuffer(setProperty(model.getValue(), [index], void 0, { tabSize, insertSpaces, eol })[0], model);
		}
	}

	private findUserKeybindingEntryIndex(keybindingItem: ResolvedKeybindingItem, userKeybindingEntries: IUserFriendlyKeybinding[]): number {
		for (let index = 0; index < userKeybindingEntries.length; index++) {
			const keybinding = userKeybindingEntries[index];
			if (keybinding.command === keybindingItem.command) {
				if (!keybinding.when && !keybindingItem.when) {
					return index;
				}
				if (keybinding.when && keybindingItem.when) {
					if (ContextKeyExpr.deserialize(keybinding.when).serialize() === keybindingItem.when.serialize()) {
						return index;
					}
				}
181
			}
182 183 184 185
		}
		return -1;
	}

S
Sandeep Somavarapu 已提交
186 187
	private findUnassignedDefaultKeybindingEntryIndex(keybindingItem: ResolvedKeybindingItem, userKeybindingEntries: IUserFriendlyKeybinding[]): number[] {
		const indices = [];
188 189
		for (let index = 0; index < userKeybindingEntries.length; index++) {
			if (userKeybindingEntries[index].command === `-${keybindingItem.command}`) {
S
Sandeep Somavarapu 已提交
190
				indices.push(index);
191
			}
192
		}
S
Sandeep Somavarapu 已提交
193
		return indices;
194 195 196 197 198 199 200 201 202 203 204 205
	}

	private asObject(key: string, command: string, when: ContextKeyExpr, negate: boolean): any {
		const object = { key };
		object['command'] = negate ? `-${command}` : command;
		if (when) {
			object['when'] = when.serialize();
		}
		return object;
	}


A
Alex Dima 已提交
206
	private applyEditsToBuffer(edit: Edit, model: ITextModel): void {
207 208 209 210 211 212 213 214 215 216 217 218
		const startPosition = model.getPositionAt(edit.offset);
		const endPosition = model.getPositionAt(edit.offset + edit.length);
		const range = new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
		let currentText = model.getValueInRange(range);
		const editOperation = currentText ? EditOperation.replace(range, edit.content) : EditOperation.insert(startPosition, edit.content);
		model.pushEditOperations([new Selection(startPosition.lineNumber, startPosition.column, startPosition.lineNumber, startPosition.column)], [editOperation], () => []);
	}


	private resolveModelReference(): TPromise<IReference<ITextEditorModel>> {
		return this.fileService.existsFile(this.resource)
			.then(exists => {
219
				const EOL = this.configurationService.getValue('files', { overrideIdentifier: 'json' })['eol'];
220
				const result = exists ? TPromise.as(null) : this.fileService.updateContent(this.resource, this.getEmptyContent(EOL), { encoding: 'utf8' });
221 222 223 224 225 226 227 228
				return result.then(() => this.textModelResolverService.createModelReference(this.resource));
			});
	}

	private resolveAndValidate(): TPromise<IReference<ITextEditorModel>> {

		// Target cannot be dirty if not writing into buffer
		if (this.textFileService.isDirty(this.resource)) {
229
			return TPromise.wrapError<IReference<ITextEditorModel>>(new Error(localize('errorKeybindingsFileDirty', "Unable to write because the keybindings configuration file is dirty. Please save it first and then try again.")));
230 231 232 233 234
		}

		return this.resolveModelReference()
			.then(reference => {
				const model = reference.object.textEditorModel;
S
Sandeep Somavarapu 已提交
235 236 237 238
				const EOL = model.getEOL();
				if (model.getValue()) {
					const parsed = this.parse(model);
					if (parsed.parseErrors.length) {
239
						return TPromise.wrapError<IReference<ITextEditorModel>>(new Error(localize('parseErrors', "Unable to write to the keybindings configuration file. Please open it to correct errors/warnings in the file and try again.")));
S
Sandeep Somavarapu 已提交
240 241 242
					}
					if (parsed.result) {
						if (!isArray(parsed.result)) {
243
							return TPromise.wrapError<IReference<ITextEditorModel>>(new Error(localize('errorInvalidConfiguration', "Unable to write to the keybindings configuration file. It has an object which is not of type Array. Please open the file to clean up and try again.")));
S
Sandeep Somavarapu 已提交
244 245 246 247 248 249
						}
					} else {
						const content = EOL + '[]';
						this.applyEditsToBuffer({ content, length: content.length, offset: model.getValue().length }, model);
					}
				} else {
250
					const content = this.getEmptyContent(EOL);
S
Sandeep Somavarapu 已提交
251
					this.applyEditsToBuffer({ content, length: content.length, offset: 0 }, model);
252 253 254 255 256
				}
				return reference;
			});
	}

A
Alex Dima 已提交
257
	private parse(model: ITextModel): { result: IUserFriendlyKeybinding[], parseErrors: json.ParseError[] } {
258
		const parseErrors: json.ParseError[] = [];
259
		const result = json.parse(model.getValue(), parseErrors);
S
Sandeep Somavarapu 已提交
260
		return { result, parseErrors };
261
	}
262 263 264 265

	private getEmptyContent(EOL: string): string {
		return '// ' + localize('emptyKeybindingsHeader', "Place your key bindings in this file to overwrite the defaults") + EOL + '[]';
	}
266
}