Elffuss BraidHub

kikocis/continue public

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