keybindingEditing.ts 11.5 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*---------------------------------------------------------------------------------------------
 *  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 { Queue } from 'vs/base/common/async';
import * as json from 'vs/base/common/json';
import { setProperty } from 'vs/base/common/jsonEdit';
A
Alex Dima 已提交
10 11 12 13 14
import { Edit } from 'vs/base/common/jsonFormatter';
import { Disposable, IReference } from 'vs/base/common/lifecycle';
import { isArray } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
15 16 17
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
A
Alex Dima 已提交
18 19 20 21
import { ITextModel } from 'vs/editor/common/model';
import { ITextEditorModel, ITextModelService } from 'vs/editor/common/services/resolverService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
22 23
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IFileService } from 'vs/platform/files/common/files';
A
Alex Dima 已提交
24 25
import { ServiceIdentifier, createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IUserFriendlyKeybinding } from 'vs/platform/keybinding/common/keybinding';
26
import { ResolvedKeybindingItem } from 'vs/platform/keybinding/common/resolvedKeybindingItem';
A
Alex Dima 已提交
27
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
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;
S
Sandeep Somavarapu 已提交
77 78 79 80 81
				const userKeybindingEntries = <IUserFriendlyKeybinding[]>json.parse(model.getValue());
				const userKeybindingEntryIndex = this.findUserKeybindingEntryIndex(keybindingItem, userKeybindingEntries);
				this.updateKeybinding(key, keybindingItem, model, userKeybindingEntryIndex);
				if (keybindingItem.isDefault && keybindingItem.resolvedKeybinding) {
					this.removeDefaultKeybinding(keybindingItem, model);
82 83 84 85 86
				}
				return this.save().then(() => reference.dispose());
			});
	}

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

100 101 102 103 104 105 106 107 108 109 110 111
	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());
			});
	}

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

S
Sandeep Somavarapu 已提交
116
	private updateKeybinding(newKey: string, keybindingItem: ResolvedKeybindingItem, model: ITextModel, userKeybindingEntryIndex: number): void {
A
Alex Dima 已提交
117
		const { tabSize, insertSpaces } = model.getOptions();
118
		const eol = model.getEOL();
119
		if (userKeybindingEntryIndex !== -1) {
120
			// Update the keybinding with new key
121
			this.applyEditsToBuffer(setProperty(model.getValue(), [userKeybindingEntryIndex, 'key'], newKey, { tabSize, insertSpaces, eol })[0], model);
122
		} else {
S
Sandeep Somavarapu 已提交
123
			// Add the new keybinding with new key
124 125 126 127
			this.applyEditsToBuffer(setProperty(model.getValue(), [-1], this.asObject(newKey, keybindingItem.command, keybindingItem.when, false), { tabSize, insertSpaces, eol })[0], model);
		}
	}

A
Alex Dima 已提交
128
	private removeUserKeybinding(keybindingItem: ResolvedKeybindingItem, model: ITextModel): void {
A
Alex Dima 已提交
129
		const { tabSize, insertSpaces } = model.getOptions();
130
		const eol = model.getEOL();
131
		const userKeybindingEntries = <IUserFriendlyKeybinding[]>json.parse(model.getValue());
132 133 134
		const userKeybindingEntryIndex = this.findUserKeybindingEntryIndex(keybindingItem, userKeybindingEntries);
		if (userKeybindingEntryIndex !== -1) {
			this.applyEditsToBuffer(setProperty(model.getValue(), [userKeybindingEntryIndex], void 0, { tabSize, insertSpaces, eol })[0], model);
135 136 137
		}
	}

A
Alex Dima 已提交
138
	private removeDefaultKeybinding(keybindingItem: ResolvedKeybindingItem, model: ITextModel): void {
A
Alex Dima 已提交
139
		const { tabSize, insertSpaces } = model.getOptions();
140
		const eol = model.getEOL();
141
		this.applyEditsToBuffer(setProperty(model.getValue(), [-1], this.asObject(keybindingItem.resolvedKeybinding.getUserSettingsLabel(), keybindingItem.command, keybindingItem.when, true), { tabSize, insertSpaces, eol })[0], model);
142 143
	}

A
Alex Dima 已提交
144
	private removeUnassignedDefaultKeybinding(keybindingItem: ResolvedKeybindingItem, model: ITextModel): void {
A
Alex Dima 已提交
145
		const { tabSize, insertSpaces } = model.getOptions();
146 147
		const eol = model.getEOL();
		const userKeybindingEntries = <IUserFriendlyKeybinding[]>json.parse(model.getValue());
S
Sandeep Somavarapu 已提交
148 149
		const indices = this.findUnassignedDefaultKeybindingEntryIndex(keybindingItem, userKeybindingEntries).reverse();
		for (const index of indices) {
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
			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;
					}
				}
166
			}
167 168 169 170
		}
		return -1;
	}

S
Sandeep Somavarapu 已提交
171
	private findUnassignedDefaultKeybindingEntryIndex(keybindingItem: ResolvedKeybindingItem, userKeybindingEntries: IUserFriendlyKeybinding[]): number[] {
M
Matt Bierner 已提交
172
		const indices: number[] = [];
173 174
		for (let index = 0; index < userKeybindingEntries.length; index++) {
			if (userKeybindingEntries[index].command === `-${keybindingItem.command}`) {
S
Sandeep Somavarapu 已提交
175
				indices.push(index);
176
			}
177
		}
S
Sandeep Somavarapu 已提交
178
		return indices;
179 180 181 182 183 184 185 186 187 188 189 190
	}

	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 已提交
191
	private applyEditsToBuffer(edit: Edit, model: ITextModel): void {
192 193 194 195 196 197 198 199 200 201 202 203
		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 => {
204
				const EOL = this.configurationService.getValue('files', { overrideIdentifier: 'json' })['eol'];
205
				const result = exists ? TPromise.as(null) : this.fileService.updateContent(this.resource, this.getEmptyContent(EOL), { encoding: 'utf8' });
206 207 208 209 210 211 212 213
				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)) {
214
			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.")));
215 216 217 218 219
		}

		return this.resolveModelReference()
			.then(reference => {
				const model = reference.object.textEditorModel;
S
Sandeep Somavarapu 已提交
220 221 222 223
				const EOL = model.getEOL();
				if (model.getValue()) {
					const parsed = this.parse(model);
					if (parsed.parseErrors.length) {
224
						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 已提交
225 226 227
					}
					if (parsed.result) {
						if (!isArray(parsed.result)) {
228
							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 已提交
229 230 231 232 233 234
						}
					} else {
						const content = EOL + '[]';
						this.applyEditsToBuffer({ content, length: content.length, offset: model.getValue().length }, model);
					}
				} else {
235
					const content = this.getEmptyContent(EOL);
S
Sandeep Somavarapu 已提交
236
					this.applyEditsToBuffer({ content, length: content.length, offset: 0 }, model);
237 238 239 240 241
				}
				return reference;
			});
	}

A
Alex Dima 已提交
242
	private parse(model: ITextModel): { result: IUserFriendlyKeybinding[], parseErrors: json.ParseError[] } {
243
		const parseErrors: json.ParseError[] = [];
244
		const result = json.parse(model.getValue(), parseErrors);
S
Sandeep Somavarapu 已提交
245
		return { result, parseErrors };
246
	}
247 248

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