Elffuss BraidHub

kikocis/continue public

8a9d2f5a43d9 路 10.2 KiBRawPermalink
1import { NextEditProvider } from "core/nextEdit/NextEditProvider";
2import { NextEditOutcome } from "core/nextEdit/types";
3import * as vscode from "vscode";
4
5export interface CompletionDataForAfterJump {
6 completionId: string;
7 outcome: NextEditOutcome;
8 currentPosition: vscode.Position;
9}
10
11export class JumpManager {
12 private static _instance: JumpManager | undefined;
13
14 // Decoration state.
15 private _jumpDecoration: vscode.TextEditorDecorationType | undefined;
16 private _jumpDecorationVisible = false;
17 private _disposables: vscode.Disposable[] = [];
18
19 private _jumpInProgress: boolean = false;
20 private _jumpAccepted: boolean = false;
21 private _completionAfterJump: CompletionDataForAfterJump | null = null;
22 private _oldCursorPosition: vscode.Position | undefined;
23
24 private constructor() {}
25
26 initialize() {}
27
28 public static getInstance(): JumpManager {
29 if (!JumpManager._instance) {
30 JumpManager._instance = new JumpManager();
31 }
32 return JumpManager._instance;
33 }
34
35 public static clearInstance() {
36 if (JumpManager._instance) {
37 JumpManager._instance.dispose();
38 JumpManager._instance = undefined;
39 }
40 }
41
42 public dispose() {
43 // Dispose current decoration.
44 this._disposables.forEach((d) => d.dispose());
45 this._disposables = [];
46 }
47
48 public async suggestJump(
49 currentPosition: vscode.Position,
50 nextJumpLocation: vscode.Position,
51 completionContent?: string,
52 ): Promise<boolean> {
53 // Deduplication logic.
54 // If the content at the next jump location is
55 // identical to the completion content,
56 // then we don't have to jump.
57 if (completionContent !== undefined) {
58 const editor = vscode.window.activeTextEditor;
59
60 if (editor) {
61 try {
62 const completionLines = completionContent.split("\n");
63
64 // Get document content at jump location spanning multiple lines.
65 const document = editor.document;
66 const startLine = nextJumpLocation.line;
67 const endLine = Math.min(
68 startLine + completionLines.length - 1,
69 document.lineCount - 1,
70 );
71
72 // Check if we have enough lines in the document to compare.
73 if (endLine - startLine + 1 < completionLines.length) {
74 // Not enough lines in document, so content can't be identical.
75 // Proceed to jump!
76 } else {
77 // Check the first line first for early exit.
78 const firstLineText = document.lineAt(startLine).text;
79 const firstLineSubstring = firstLineText.substring(
80 nextJumpLocation.character,
81 );
82 const firstCompletionLine = completionLines[0];
83
84 if (!firstLineSubstring.startsWith(firstCompletionLine)) {
85 // First line doesn't match, so proceed to jump.
86 } else {
87 // Check remaining lines if there are any.
88 if (completionLines.length > 1) {
89 let fullMatch = true;
90
91 // Process remaining lines.
92 for (let i = 1; i < completionLines.length; i++) {
93 const documentLine = startLine + i;
94 if (documentLine <= endLine) {
95 const lineText = document.lineAt(documentLine).text;
96 if (lineText !== completionLines[i]) {
97 fullMatch = false;
98 break;
99 }
100 }
101 }
102
103 if (fullMatch) {
104 console.log(
105 "Skipping jump as content is identical at jump location",
106 );
107 return false; // Exit early, don't suggest jump.
108 }
109 } else {
110 // Only one line and it matches.
111 console.log(
112 "Skipping jump as content is identical at jump location",
113 );
114 return false; // Exit early, don't suggest jump.
115 }
116 }
117 }
118 } catch (error) {
119 console.error("Error checking content at jump location:", error);
120 // Continue with jump even if there's an error checking content.
121 }
122 }
123 }
124
125 console.log("this._jumpInProgress");
126 this._jumpInProgress = true;
127 this._oldCursorPosition = currentPosition;
128
129 const editor = vscode.window.activeTextEditor;
130 if (!editor) {
131 console.log("No active editor, cannot suggest jump");
132 this._jumpInProgress = false;
133 return false;
134 }
135
136 const visibleRanges = editor.visibleRanges;
137 if (visibleRanges.length === 0) {
138 console.log("No visible ranges in editor, cannot suggest jump");
139 this._jumpInProgress = false;
140 return false;
141 }
142
143 const visibleRange = visibleRanges[0];
144 const topLineNumber = visibleRange.start.line;
145 const bottomLineNumber = visibleRange.end.line;
146
147 const decorationLine = nextJumpLocation.line;
148
149 // Check if jump location is outside the visible range.
150 if (decorationLine < topLineNumber) {
151 await this.renderTabToJumpDecoration(
152 editor,
153 topLineNumber,
154 nextJumpLocation,
155 );
156 } else if (decorationLine > bottomLineNumber) {
157 await this.renderTabToJumpDecoration(
158 editor,
159 bottomLineNumber,
160 nextJumpLocation,
161 );
162 } else {
163 // No suggestion is made when the decoration is within visibleRange.
164 await this.renderTabToJumpDecoration(
165 editor,
166 decorationLine,
167 nextJumpLocation,
168 );
169 }
170
171 // Scroll to show the jump location.
172 editor.revealRange(
173 new vscode.Range(decorationLine, 0, decorationLine, 0),
174 vscode.TextEditorRevealType.InCenter,
175 );
176
177 // Set up a way to detect when the jump is complete.
178 const disposable = vscode.window.onDidChangeTextEditorSelection(() => {
179 console.log("_jumpInProgress is false");
180 this._jumpInProgress = false;
181 disposable.dispose();
182
183 // If there's a completion waiting to be shown after the jump,
184 // execute the command to show it.
185 if (this._completionAfterJump) {
186 vscode.commands.executeCommand(
187 "continue.showNextEditAfterJump",
188 this._completionAfterJump,
189 );
190 this._completionAfterJump = null;
191 }
192 });
193
194 // Clean up after timeout if no jump has been made.
195 setTimeout(() => {
196 this._jumpInProgress = false;
197 disposable.dispose();
198 }, 10000);
199
200 return true;
201 }
202
203 private async renderTabToJumpDecoration(
204 editor: vscode.TextEditor,
205 lineToRenderOn: number,
206 jumpPosition: vscode.Position,
207 ) {
208 // Clean up any existing decoration beforehand.
209 await this.clearJumpDecoration();
210
211 // Create a decoration for jump.
212 this._jumpDecoration = vscode.window.createTextEditorDecorationType({
213 before: {
214 contentText: "馃 Press Tab to jump, Esc to cancel",
215 color: new vscode.ThemeColor("editorInfo.foreground"),
216 backgroundColor: new vscode.ThemeColor("editorInfo.background"),
217 margin: `0 0 0 4px`,
218 },
219 });
220
221 // Apply the decoration.
222 const lastIndexOfLine = editor.document.lineAt(lineToRenderOn).text.length;
223 editor.setDecorations(this._jumpDecoration, [
224 new vscode.Range(
225 lineToRenderOn,
226 lastIndexOfLine,
227 lineToRenderOn,
228 lastIndexOfLine,
229 ),
230 ]);
231
232 // Set the context key to enable tab/esc shortcuts.
233 await vscode.commands.executeCommand(
234 "setContext",
235 "continue.jumpDecorationVisible",
236 true,
237 );
238 this._jumpDecorationVisible = true;
239
240 // Register the key listeners.
241 await this.registerKeyListeners(editor, jumpPosition);
242 }
243
244 private async clearJumpDecoration() {
245 if (this._jumpDecoration) {
246 this._jumpDecoration.dispose();
247 this._jumpDecoration = undefined;
248 }
249
250 // Dispose any active listeners.
251 this._disposables.forEach((d) => d.dispose());
252 this._disposables = [];
253
254 // Reset the context.
255 await vscode.commands.executeCommand(
256 "setContext",
257 "continue.jumpDecorationVisible",
258 false,
259 );
260 this._jumpDecorationVisible = false;
261 }
262
263 private async registerKeyListeners(
264 editor: vscode.TextEditor,
265 jumpPosition: vscode.Position,
266 ) {
267 const acceptJumpCommand = vscode.commands.registerCommand(
268 "continue.acceptJump",
269 async () => {
270 if (this._jumpDecorationVisible) {
271 this._jumpAccepted = true;
272
273 // Move cursor to the jump position.
274 editor.selection = new vscode.Selection(jumpPosition, jumpPosition);
275 await this.clearJumpDecoration();
276
277 this._jumpAccepted = false;
278 }
279 },
280 );
281
282 const rejectJumpCommand = vscode.commands.registerCommand(
283 "continue.rejectJump",
284 async () => {
285 if (this._jumpDecorationVisible) {
286 console.log(
287 "deleteChain from JumpManager.ts: rejectJump and decoration visible",
288 );
289 NextEditProvider.getInstance().deleteChain();
290 await this.clearJumpDecoration();
291 }
292 },
293 );
294
295 // Add a selection change listener to the editor to reject jump when cursor moves.
296 const selectionChangeListener =
297 vscode.window.onDidChangeTextEditorSelection((e) => {
298 // If jump decoration isn't visible, nothing to do.
299 if (!this._jumpDecorationVisible) {
300 return;
301 }
302
303 const currentPosition = e.selections[0].active;
304
305 // If cursor moved to jump position, this is likely the result of acceptJump.
306 if (currentPosition.isEqual(jumpPosition)) {
307 return;
308 }
309
310 // If cursor position changed for any other reason, reject the jump.
311 if (
312 this._oldCursorPosition &&
313 !currentPosition.isEqual(this._oldCursorPosition)
314 ) {
315 vscode.commands.executeCommand("continue.rejectJump");
316 }
317 });
318
319 // This allows us to dispose the command after a jump is completed.
320 this._disposables.push(
321 acceptJumpCommand,
322 rejectJumpCommand,
323 selectionChangeListener,
324 );
325 }
326
327 isJumpInProgress(): boolean {
328 return this._jumpInProgress;
329 }
330
331 wasJumpJustAccepted(): boolean {
332 return this._jumpAccepted;
333 }
334
335 setCompletionAfterJump(completionData: CompletionDataForAfterJump): void {
336 this._completionAfterJump = completionData;
337 }
338}