-
-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathKeyboardCommandsModal.ts
More file actions
229 lines (203 loc) · 7.11 KB
/
Copy pathKeyboardCommandsModal.ts
File metadata and controls
229 lines (203 loc) · 7.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import { pick, sortedUniq, toPairs } from "lodash-es";
import nearley from "nearley";
import * as vscode from "vscode";
import { CompositeKeyMap, getErrorMessage } from "@cursorless/lib-common";
import type { VscodeApi } from "@cursorless/lib-vscode-common";
import { getTokenTypeKeyMaps } from "./getTokenTypeKeyMaps";
import grammar from "./grammar/generated/grammar";
import { getAcceptableTokenTypes } from "./grammar/getAcceptableTokenTypes";
import { KeyboardCommandHandler } from "./KeyboardCommandHandler";
import { KeyboardCommandsModalLayer } from "./KeyboardCommandsModalLayer";
import type { KeyboardCommandsTargeted } from "./KeyboardCommandsTargeted";
import { KeyboardConfig } from "./KeyboardConfig";
import type { KeyboardHandler } from "./KeyboardHandler";
import type { KeyDescriptor, TokenTypeKeyMapMap } from "./TokenTypeHelpers";
/**
* Defines a mode to use with a modal version of Cursorless keyboard.
*/
export class KeyboardCommandsModal {
/**
* This disposable is returned by {@link KeyboardHandler.pushListener}, and is
* used to relinquich control of the keyboard. If this disposable is
* non-null, then our mode is active.
*/
private inputDisposable: vscode.Disposable | undefined;
/**
* Merged map from all the different sections of the key map (eg actions,
* colors, etc).
*/
private currentLayer!: KeyboardCommandsModalLayer<KeyDescriptor>;
private layerCache = new CompositeKeyMap<
string[],
KeyboardCommandsModalLayer<KeyDescriptor>
>((keys) => keys);
private parser!: nearley.Parser;
private sections!: TokenTypeKeyMapMap;
private keyboardCommandHandler: KeyboardCommandHandler;
private compiledGrammar = nearley.Grammar.fromCompiled(grammar);
private keyboardConfig: KeyboardConfig;
constructor(
private extensionContext: vscode.ExtensionContext,
private targeted: KeyboardCommandsTargeted,
private keyboardHandler: KeyboardHandler,
vscodeApi: VscodeApi,
) {
this.modeOn = this.modeOn.bind(this);
this.modeOff = this.modeOff.bind(this);
this.handleInput = this.handleInput.bind(this);
this.keyboardConfig = new KeyboardConfig(vscodeApi);
this.keyboardCommandHandler = new KeyboardCommandHandler(targeted);
}
init() {
this.extensionContext.subscriptions.push(
vscode.workspace.onDidChangeConfiguration(async (event) => {
if (
event.affectsConfiguration(
"cursorless.experimental.keyboard.modal.keybindings",
)
) {
if (this.isModeOn()) {
await this.modeOff();
await this.modeOn();
}
this.layerCache.clear();
this.processKeyMap();
}
}),
);
}
private processKeyMap() {
this.sections = getTokenTypeKeyMaps(this.keyboardConfig);
this.resetParser();
}
private resetParser() {
this.parser = new nearley.Parser(this.compiledGrammar);
this.computeLayer();
}
/**
* Given the current state of the parser, computes a keyboard layer containing
* only the keys that are currently valid.
*/
private computeLayer() {
const acceptableTokenTypeInfos = getAcceptableTokenTypes(this.parser);
// FIXME: Here's where we'd update sidebar
const acceptableTokenTypes = sortedUniq(
acceptableTokenTypeInfos.map(({ type }) => type).sort(),
);
let layer = this.layerCache.get(acceptableTokenTypes);
if (layer == null) {
layer = new KeyboardCommandsModalLayer(
this.keyboardHandler,
Object.values(pick(this.sections, acceptableTokenTypes)).flatMap(
toPairs<KeyDescriptor>,
),
);
this.layerCache.set(acceptableTokenTypes, layer);
}
this.currentLayer = layer;
}
modeOn = async () => {
if (this.isModeOn()) {
return;
}
if (this.currentLayer == null) {
// Construct keymap lazily for ease of mocking and to save performance
// when the mode is never used
this.processKeyMap();
}
this.inputDisposable = this.keyboardHandler.pushListener({
handleInput: this.handleInput,
displayOptions: {
cursorStyle: this.keyboardConfig.getCursorStyle(),
whenClauseContext: "cursorless.keyboard.modal.mode",
statusBarText: "Listening...",
},
handleCancelled: this.modeOff,
});
// Set target to current selection when we enter the mode
await this.targeted.targetSelection();
};
async handleInput(text: string) {
try {
/**
* The text to feed to the layer. This will be a single character
* initially, when we're called by {@link KeyboardHandler}. We pass it to
* the layer, which will ask for more characters if necessary to complete
* the key sequence for a single parser token.
*
* If the parser wants more tokens, we set this to "" so that the layer
* can ask for characters for the next token from scratch.
*/
let currentText = text;
let previousKeys = "";
while (true) {
const layerOutput = await this.currentLayer.handleInput(currentText, {
previousKeys,
});
if (layerOutput == null) {
throw new KeySequenceCancelledError();
}
this.parser.feed([layerOutput.value]);
if (this.parser.results.length > 0) {
// We've found a valid parse
break;
}
currentText = "";
previousKeys += layerOutput.keysPressed;
this.computeLayer();
}
if (this.parser.results.length > 1) {
console.error("Ambiguous parse:");
console.error(JSON.stringify(this.parser.results, null, 2));
throw new Error("Ambiguous parse; see console output");
}
const nextTokenTypes = getAcceptableTokenTypes(this.parser);
if (nextTokenTypes.length > 0) {
// Because we stop as soon as a valid parse is found, there shouldn't
// be any way to continue
console.error(
"Ambiguous whether parsing is complete. Possible following tokens:",
);
console.error(JSON.stringify(nextTokenTypes, null, 2));
throw new Error("Ambiguous parse; see console output");
}
const [{ type, arg }] = this.parser.results;
// Run the command
void this.keyboardCommandHandler[type as keyof KeyboardCommandHandler](
arg,
);
} catch (error) {
if (!(error instanceof KeySequenceCancelledError)) {
void vscode.window.showErrorMessage(getErrorMessage(error));
throw error;
}
} finally {
// Always reset the parser when we're done
this.resetParser();
}
}
modeOff = async () => {
if (!this.isModeOn()) {
return;
}
this.inputDisposable?.dispose();
this.inputDisposable = undefined;
// Clear target upon exiting mode; this will remove the highlight
await this.targeted.clearTarget();
};
modeToggle = () => {
if (this.isModeOn()) {
return this.modeOff();
}
return this.modeOn();
};
private isModeOn() {
return this.inputDisposable != null;
}
}
class KeySequenceCancelledError extends Error {
constructor() {
super("Key sequence cancelled");
this.name = "KeySequenceCancelledError";
}
}