Elffuss BraidHub

kikocis/continue public

4e7d29ea58e1 路 13.2 KiBRawPermalink
1import { NextEditProvider } from "core/nextEdit/NextEditProvider";
2import { NextEditOutcome } from "core/nextEdit/types";
3// @ts-ignore
4import svgBuilder from "svg-builder";
5import * as vscode from "vscode";
6import { getTheme } from "../util/getTheme";
7import {
8 HandlerPriority,
9 SelectionChangeManager,
10} from "./SelectionChangeManager";
11
12// Instead of getters that execute immediately, use methods or lazy properties
13const SVG_CONFIG = {
14 stroke: "#999998",
15 strokeWidth: 1,
16 shortcutColor: "#999998",
17 filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))",
18 radius: 3,
19 leftMargin: 40,
20 debounceDelay: 500,
21 label: "馃搷 Press Tab to jump, Esc to cancel",
22
23 // Convert getters to methods that are called when needed
24 getFontSize(): number {
25 return Math.ceil(
26 (vscode.workspace.getConfiguration("editor").get<number>("fontSize") ??
27 14) * 0.8,
28 );
29 },
30
31 getFontFamily(): string {
32 return (
33 vscode.workspace.getConfiguration("editor").get<string>("fontFamily") ||
34 "helvetica"
35 );
36 },
37
38 getPaddingX(): number {
39 return Math.ceil(this.getEstimatedTextWidth(" "));
40 },
41
42 getGap(): number {
43 return this.getFontSize() * 0.5;
44 },
45
46 getTipWidth(): number {
47 return this.getEstimatedTextWidth(this.label) + this.getPaddingX();
48 },
49
50 getTipHeight(): number {
51 return this.getFontSize();
52 },
53
54 getTextY(): number {
55 return (this.getTipHeight() + this.getFontSize()) / 2;
56 },
57
58 getEstimatedTextWidth(text: string): number {
59 return text.length * this.getFontSize() * 0.6;
60 },
61} as const;
62
63export interface CompletionDataForAfterJump {
64 completionId: string;
65 outcome: NextEditOutcome;
66 currentPosition: vscode.Position;
67}
68
69export class JumpManager {
70 private static _instance: JumpManager | undefined;
71
72 // Decoration state.
73 private _jumpIcon: vscode.Uri | undefined;
74 private _jumpDecoration: vscode.TextEditorDecorationType | undefined;
75 private _jumpDecorationVisible = false;
76 private _disposables: vscode.Disposable[] = [];
77 private _theme = getTheme();
78
79 private _jumpInProgress: boolean = false;
80 private _jumpAccepted: boolean = false;
81 private _completionAfterJump: CompletionDataForAfterJump | null = null;
82 private _oldCursorPosition: vscode.Position | undefined;
83
84 private constructor() {
85 // Build the first SVG icon
86 this._createSvgJumpIcon();
87
88 // Re鈥慴uild when the colour theme changes
89 vscode.workspace.onDidChangeConfiguration((e) => {
90 if (e.affectsConfiguration("workbench.colorTheme")) {
91 this._theme = getTheme();
92 this._createSvgJumpIcon();
93 }
94 });
95 }
96
97 initialize() {}
98
99 public static getInstance(): JumpManager {
100 if (!JumpManager._instance) {
101 JumpManager._instance = new JumpManager();
102 }
103 return JumpManager._instance;
104 }
105
106 public static clearInstance() {
107 if (JumpManager._instance) {
108 JumpManager._instance.dispose();
109 JumpManager._instance = undefined;
110 }
111 }
112
113 public dispose() {
114 // Dispose current decoration.
115 this._disposables.forEach((d) => {
116 if (d) d.dispose();
117 });
118 this._disposables = [];
119 }
120
121 private _createSvgJumpIcon() {
122 // if (!this._theme) {
123 // return;
124 // }
125
126 const baseTextConfig = {
127 y: SVG_CONFIG.getTextY(),
128 "font-family": SVG_CONFIG.getFontFamily(),
129 "font-size": SVG_CONFIG.getFontSize(),
130 };
131
132 try {
133 const builder = svgBuilder.newInstance
134 ? svgBuilder.newInstance()
135 : svgBuilder;
136 const svgContent = builder
137 .width(SVG_CONFIG.getTipWidth())
138 .height(SVG_CONFIG.getTipHeight())
139 .text(
140 {
141 ...baseTextConfig,
142 x: 4,
143 fill: this._theme?.colors["editor.foreground"] ?? SVG_CONFIG.stroke,
144 },
145 SVG_CONFIG.label,
146 )
147 .render();
148
149 const dataUri = `data:image/svg+xml;base64,${Buffer.from(
150 svgContent,
151 ).toString("base64")}`;
152 this._jumpIcon = vscode.Uri.parse(dataUri);
153
154 // Dispose the old decoration (if any) and create a fresh one.
155 if (this._jumpDecoration) {
156 this._jumpDecoration.dispose();
157 }
158 this._jumpDecoration = this._createSvgJumpDecoration();
159 } catch (err) {
160 console.error("Error creating SVG jump tooltip:", err);
161 }
162 }
163
164 private _createSvgJumpDecoration(): vscode.TextEditorDecorationType {
165 const backgroundColour =
166 this._theme?.colors["editor.background"] ?? "#333333";
167
168 return vscode.window.createTextEditorDecorationType({
169 after: {
170 contentIconPath: this._jumpIcon,
171 border: `;box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${SVG_CONFIG.getTipHeight()}px ${backgroundColour};
172 border-radius: ${SVG_CONFIG.radius}px;
173 filter: ${SVG_CONFIG.filter}`,
174 margin: `0 0 0 ${SVG_CONFIG.leftMargin}px`,
175 width: `${SVG_CONFIG.getTipWidth()}px`,
176 },
177 });
178 }
179
180 public async suggestJump(
181 currentPosition: vscode.Position,
182 nextJumpLocation: vscode.Position,
183 completionContent?: string,
184 ): Promise<boolean> {
185 // Deduplication logic.
186 // If the content at the next jump location is
187 // identical to the completion content,
188 // then we don't have to jump.
189 if (completionContent !== undefined) {
190 console.log("completionContent is not null");
191 const editor = vscode.window.activeTextEditor;
192
193 if (editor) {
194 try {
195 const completionLines = completionContent.split("\n");
196 console.log("completionLines:", completionLines);
197
198 // Get document content at jump location spanning multiple lines.
199 const document = editor.document;
200 const startLine = nextJumpLocation.line;
201 const endLine = Math.min(
202 startLine + completionLines.length - 1,
203 document.lineCount - 1,
204 );
205
206 // First check if we have enough lines in the document
207 if (endLine - startLine + 1 < completionLines.length) {
208 // Not enough lines in document, so content can't be identical.
209 // Proceed to jump!
210 console.log(
211 "Not enough lines in document to match completion content",
212 );
213 } else {
214 let contentMatches = true;
215
216 // Check all lines for match.
217 for (let i = 0; i < completionLines.length && contentMatches; i++) {
218 const documentLine = startLine + i;
219 const lineText = document.lineAt(documentLine).text;
220 if (lineText !== completionLines[i]) {
221 contentMatches = false;
222 console.log(`Line ${i + 1} doesn't match`);
223 }
224 }
225
226 if (contentMatches) {
227 console.log(
228 "Skipping jump as content is identical at jump location",
229 );
230 return false; // Exit early, don't suggest jump.
231 }
232 }
233 } catch (error) {
234 console.error("Error checking content at jump location:", error);
235 // Continue with jump even if there's an error checking content.
236 }
237 }
238 }
239
240 console.log("this._jumpInProgress");
241 this._jumpInProgress = true;
242 this._oldCursorPosition = currentPosition;
243
244 const editor = vscode.window.activeTextEditor;
245 if (!editor) {
246 console.log("No active editor, cannot suggest jump");
247 this._jumpInProgress = false;
248 return false;
249 }
250
251 const visibleRanges = editor.visibleRanges;
252 if (visibleRanges.length === 0) {
253 console.log("No visible ranges in editor, cannot suggest jump");
254 this._jumpInProgress = false;
255 return false;
256 }
257
258 const visibleRange = visibleRanges[0];
259 const topLineNumber = visibleRange.start.line;
260 const bottomLineNumber = visibleRange.end.line;
261
262 const decorationLine = nextJumpLocation.line;
263
264 // Check if jump location is outside the visible range.
265 if (decorationLine < topLineNumber) {
266 await this.renderTabToJumpDecoration(
267 editor,
268 topLineNumber,
269 nextJumpLocation,
270 );
271 } else if (decorationLine > bottomLineNumber) {
272 await this.renderTabToJumpDecoration(
273 editor,
274 bottomLineNumber,
275 nextJumpLocation,
276 );
277 } else {
278 // No suggestion is made when the decoration is within visibleRange.
279 await this.renderTabToJumpDecoration(
280 editor,
281 decorationLine,
282 nextJumpLocation,
283 );
284 }
285
286 return true;
287 }
288
289 private async renderTabToJumpDecoration(
290 editor: vscode.TextEditor,
291 lineToRenderOn: number,
292 jumpPosition: vscode.Position,
293 ) {
294 // Clean up any existing decoration beforehand.
295 await this.clearJumpDecoration();
296
297 // Create a decoration for jump.
298 // this._jumpDecoration = vscode.window.createTextEditorDecorationType({
299 // before: {
300 // contentText: "馃搷 Press Tab to jump, Esc to cancel",
301 // color: new vscode.ThemeColor("editor.foreground"),
302 // backgroundColor: new vscode.ThemeColor("editorHover.background"),
303 // margin: `0 0 0 4px`,
304 // },
305 // });
306
307 if (!this._jumpDecoration) {
308 this._createSvgJumpIcon(); // makes both the icon & decoration
309 }
310
311 // Apply the decoration.
312 const lastIndexOfLine = editor.document.lineAt(lineToRenderOn).text.length;
313 editor.setDecorations(this._jumpDecoration!, [
314 new vscode.Range(
315 lineToRenderOn,
316 lastIndexOfLine,
317 lineToRenderOn,
318 lastIndexOfLine,
319 ),
320 ]);
321
322 // Set the context key to enable tab/esc shortcuts.
323 await vscode.commands.executeCommand(
324 "setContext",
325 "continue.jumpDecorationVisible",
326 true,
327 );
328 this._jumpDecorationVisible = true;
329
330 // Register the key listeners.
331 await this.registerKeyListeners(editor, jumpPosition);
332 }
333
334 private async clearJumpDecoration() {
335 if (this._jumpDecoration) {
336 this._jumpDecoration.dispose();
337 this._jumpDecoration = undefined;
338 }
339
340 // Dispose any active listeners.
341 this.dispose();
342
343 // Reset the context.
344 await vscode.commands.executeCommand(
345 "setContext",
346 "continue.jumpDecorationVisible",
347 false,
348 );
349 this._jumpDecorationVisible = false;
350 }
351
352 private async registerKeyListeners(
353 editor: vscode.TextEditor,
354 jumpPosition: vscode.Position,
355 ) {
356 const acceptJumpCommand = vscode.commands.registerCommand(
357 "continue.acceptJump",
358 async () => {
359 if (this._jumpDecorationVisible) {
360 this._jumpAccepted = true;
361
362 // Scroll to show the jump location.
363 editor.revealRange(
364 new vscode.Range(jumpPosition.line, 0, jumpPosition.line, 0),
365 vscode.TextEditorRevealType.InCenter,
366 );
367
368 // Move cursor to the jump position.
369 editor.selection = new vscode.Selection(jumpPosition, jumpPosition);
370 await this.clearJumpDecoration();
371
372 this._jumpAccepted = false;
373 vscode.commands.executeCommand("editor.action.inlineSuggest.trigger");
374 }
375 },
376 );
377
378 const rejectJumpCommand = vscode.commands.registerCommand(
379 "continue.rejectJump",
380 async () => {
381 if (this._jumpDecorationVisible) {
382 console.log(
383 "deleteChain from JumpManager.ts: rejectJump and decoration visible",
384 );
385 NextEditProvider.getInstance().deleteChain();
386 await this.clearJumpDecoration();
387 }
388 },
389 );
390
391 // Add a selection change listener to the editor to reject jump when cursor moves.
392 const selectionChangeListener =
393 vscode.window.onDidChangeTextEditorSelection((e) => {
394 // If jump decoration isn't visible, nothing to do.
395 if (!this._jumpDecorationVisible) {
396 return;
397 }
398
399 const currentPosition = e.selections[0].active;
400
401 // If cursor moved to jump position, this is likely the result of acceptJump.
402 if (currentPosition.isEqual(jumpPosition)) {
403 return;
404 }
405
406 // If cursor position changed for any other reason, reject the jump.
407 if (
408 this._oldCursorPosition &&
409 !currentPosition.isEqual(this._oldCursorPosition)
410 ) {
411 vscode.commands.executeCommand("continue.rejectJump");
412 }
413 });
414
415 // This allows us to dispose the command after a jump is completed.
416 this._disposables.push(
417 acceptJumpCommand,
418 rejectJumpCommand,
419 selectionChangeListener,
420 );
421 }
422
423 isJumpInProgress(): boolean {
424 return this._jumpInProgress;
425 }
426
427 setJumpInProgress(jumpInProgress: boolean) {
428 this._jumpInProgress = jumpInProgress;
429 }
430
431 wasJumpJustAccepted(): boolean {
432 return this._jumpAccepted;
433 }
434
435 setCompletionAfterJump(completionData: CompletionDataForAfterJump): void {
436 this._completionAfterJump = completionData;
437 }
438
439 clearCompletionAfterJump(): void {
440 this._completionAfterJump = null;
441 }
442
443 get completionAfterJump() {
444 return this._completionAfterJump;
445 }
446
447 public registerSelectionChangeHandler(): void {
448 const manager = SelectionChangeManager.getInstance();
449
450 manager.registerListener(
451 "jumpManager",
452 async (e, state) => {
453 if (state.jumpInProgress || state.jumpJustAccepted) {
454 console.log(
455 "JumpManager: jump in progress or just accepted, preserving chain",
456 );
457 return true;
458 }
459
460 return false;
461 },
462 HandlerPriority.HIGH,
463 );
464 }
465}