Elffuss BraidHub

kikocis/continue public

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