keybindingEditing.ts 9.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*---------------------------------------------------------------------------------------------
 *  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 * as strings from 'vs/base/common/strings';
import URI from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
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';
import * as editorCommon from 'vs/editor/common/editorCommon';
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 22 23 24 25
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { ITextModelResolverService, ITextEditorModel } from 'vs/editor/common/services/resolverService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IFileService } from 'vs/platform/files/common/files';
import { createDecorator, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation';
26 27
import { ResolvedKeybindingItem } from 'vs/platform/keybinding/common/resolvedKeybindingItem';

28 29 30 31 32 33 34

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

export interface IKeybindingEditingService {

	_serviceBrand: ServiceIdentifier<any>;

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

37
	removeKeybinding(keybindingItem: ResolvedKeybindingItem): TPromise<void>;
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
}

export class KeybindingsEditingService extends Disposable implements IKeybindingEditingService {

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

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

	constructor(
		@ITextModelResolverService private textModelResolverService: ITextModelResolverService,
		@ITextFileService private textFileService: ITextFileService,
		@IFileService private fileService: IFileService,
		@IEnvironmentService private environmentService: IEnvironmentService
	) {
		super();
		this.queue = new Queue<void>();
	}

57
	editKeybinding(key: string, keybindingItem: ResolvedKeybindingItem): TPromise<void> {
58 59 60
		return this.queue.queue(() => this.doEditKeybinding(key, keybindingItem)); // queue up writes to prevent race conditions
	}

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

65
	private doEditKeybinding(key: string, keybindingItem: ResolvedKeybindingItem): TPromise<void> {
66 67 68 69
		return this.resolveAndValidate()
			.then(reference => {
				key = new RegExp(/\\/g).test(key) ? key.slice(0, -1) + '\\\\' : key;
				const model = reference.object.textEditorModel;
70
				if (keybindingItem.isDefault) {
71
					this.updateDefaultKeybinding(key, keybindingItem, model);
72 73
				} else {
					this.updateUserKeybinding(key, keybindingItem, model);
74 75 76 77 78
				}
				return this.save().then(() => reference.dispose());
			});
	}

79
	private doRemoveKeybinding(keybindingItem: ResolvedKeybindingItem): TPromise<void> {
80 81 82
		return this.resolveAndValidate()
			.then(reference => {
				const model = reference.object.textEditorModel;
83
				if (keybindingItem.isDefault) {
84
					this.removeDefaultKeybinding(keybindingItem, model);
85 86
				} else {
					this.removeUserKeybinding(keybindingItem, model);
87 88 89 90 91 92
				}
				return this.save().then(() => reference.dispose());
			});
	}

	private save(): TPromise<any> {
93
		return this.textFileService.save(this.resource);
94 95
	}

96
	private updateUserKeybinding(newKey: string, keybindingItem: ResolvedKeybindingItem, model: editorCommon.IModel): void {
97 98 99 100 101 102 103 104 105
		const {tabSize, insertSpaces} = model.getOptions();
		const eol = model.getEOL();
		const userKeybindingEntries = <IUserFriendlyKeybinding[]>json.parse(model.getValue());
		const userKeybindingEntry = this.findUserKeybindingEntry(keybindingItem, userKeybindingEntries);
		if (userKeybindingEntry) {
			this.applyEditsToBuffer(setProperty(model.getValue(), [userKeybindingEntries.indexOf(userKeybindingEntry), 'key'], newKey, { tabSize, insertSpaces, eol })[0], model);
		}
	}

106
	private updateDefaultKeybinding(newKey: string, keybindingItem: ResolvedKeybindingItem, model: editorCommon.IModel): void {
107 108 109 110 111 112 113 114 115 116 117
		const {tabSize, insertSpaces} = model.getOptions();
		const eol = model.getEOL();
		const userKeybindingEntries = <IUserFriendlyKeybinding[]>json.parse(model.getValue());
		const userKeybindingEntry = this.findUserKeybindingEntry(keybindingItem, userKeybindingEntries);
		if (userKeybindingEntry) {
			// Update the keybinding with new key
			this.applyEditsToBuffer(setProperty(model.getValue(), [userKeybindingEntries.indexOf(userKeybindingEntry), 'key'], newKey, { tabSize, insertSpaces, eol })[0], model);
		} 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);
		}
118
		if (keybindingItem.resolvedKeybinding) {
119
			// Unassign the default keybinding
120
			this.applyEditsToBuffer(setProperty(model.getValue(), [-1], this.asObject(keybindingItem.resolvedKeybinding.getUserSettingsLabel(), keybindingItem.command, keybindingItem.when, true), { tabSize, insertSpaces, eol })[0], model);
121 122 123
		}
	}

124
	private removeUserKeybinding(keybindingItem: ResolvedKeybindingItem, model: editorCommon.IModel): void {
125 126 127 128 129 130 131 132 133
		const {tabSize, insertSpaces} = model.getOptions();
		const userKeybindingEntries = <IUserFriendlyKeybinding[]>json.parse(model.getValue());
		const userKeybindingEntry = this.findUserKeybindingEntry(keybindingItem, userKeybindingEntries);
		if (userKeybindingEntry) {
			userKeybindingEntries.splice(userKeybindingEntries.indexOf(userKeybindingEntry), 1);
			model.setValue(JSON.stringify(userKeybindingEntries, null, insertSpaces ? strings.repeat(' ', tabSize) : '\t'));
		}
	}

134
	private removeDefaultKeybinding(keybindingItem: ResolvedKeybindingItem, model: editorCommon.IModel): void {
135 136
		const {tabSize, insertSpaces} = model.getOptions();
		const eol = model.getEOL();
137
		this.applyEditsToBuffer(setProperty(model.getValue(), [-1], this.asObject(keybindingItem.resolvedKeybinding.getUserSettingsLabel(), keybindingItem.command, keybindingItem.when, true), { tabSize, insertSpaces, eol })[0], model);
138 139
	}

140
	private findUserKeybindingEntry(keybindingItem: ResolvedKeybindingItem, userKeybindingEntries: IUserFriendlyKeybinding[]): IUserFriendlyKeybinding {
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
		return userKeybindingEntries.filter(keybinding => {
			if (keybinding.command !== keybindingItem.command) {
				return false;
			}
			if (!keybinding.when && !keybindingItem.when) {
				return true;
			}
			if (keybinding.when && keybindingItem.when) {
				return ContextKeyExpr.deserialize(keybinding.when).serialize() === keybindingItem.when.serialize();
			}
			return false;
		})[0];
	}

	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;
	}


	private applyEditsToBuffer(edit: Edit, model: editorCommon.IModel): void {
		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 => {
				const result = exists ? TPromise.as(null) : this.fileService.updateContent(this.resource, '{}', { encoding: 'utf8' });
				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)) {
			return TPromise.wrapError(localize('errorKeybindingsFileDirty', "Unable to write because the file is dirty. Please save the **Keybindings** file and try again."));
		}

		return this.resolveModelReference()
			.then(reference => {
				const model = reference.object.textEditorModel;
				if (this.hasParseErrors(model)) {
					return TPromise.wrapError(localize('errorInvalidConfiguration', "Unable to write keybindings. Please open **Keybindings file** to correct errors/warnings in the file and try again."));
				}
				return reference;
			});
	}

	private hasParseErrors(model: editorCommon.IModel): boolean {
		const parseErrors: json.ParseError[] = [];
		json.parse(model.getValue(), parseErrors, { allowTrailingComma: true });
		return parseErrors.length > 0;
	}
}