Elffuss BraidHub

kikocis/continue public

dfc814e4318e · 31.5 KiBRawPermalink
1/* eslint-disable @typescript-eslint/naming-convention */
2import { EXTENSION_NAME } from "core/control-plane/env";
3// @ts-ignore
4import * as vscode from "vscode";
5
6import { DiffChar, DiffLine } from "core";
7import { CodeRenderer } from "core/codeRenderer/CodeRenderer";
8import { myersCharDiff } from "core/diff/myers";
9import { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff";
10import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService";
11import { NextEditProvider } from "core/nextEdit/NextEditProvider";
12import { getThemeString } from "../util/getTheme";
13import {
14 HandlerPriority,
15 SelectionChangeManager,
16} from "./SelectionChangeManager";
17
18export interface TextApplier {
19 applyText(
20 editor: vscode.TextEditor,
21 text: string,
22 position: vscode.Position,
23 finalCursorPos: vscode.Position | null,
24 ): Promise<boolean>;
25}
26
27const SVG_CONFIG = {
28 // stroke: "#999998",
29 stroke: "#666667",
30 strokeWidth: 1,
31 textColor: "#999998",
32 purple: "rgba(112, 114, 209)",
33 blue: "rgba(107, 166, 205)",
34 green: "rgba(136 194 163)",
35 // filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))",
36 // filter: "drop-shadow(0 2px 2px rgba(255,255,255,0.2))",
37 // filter:
38 // "drop-shadow(0 2px 4px rgb(112, 114, 209)) drop-shadow(0 4px 8px rgb(136, 194, 163)) drop-shadow(0 6px 12px rgb(107, 166, 205));",
39 // filter:
40 // "drop-shadow(0 3px 6px rgba(112, 114, 209, 0.4)) drop-shadow(0 3px 6px rgba(136, 194, 163, 0.4)) drop-shadow(0 3px 6px rgba(107, 166, 205, 0.4));",
41 // filter: `drop-shadow(4px 4px 0px rgba(112, 114, 209, 0.4))
42 // drop-shadow(8px 8px 0px rgba(107, 166, 205, 0.3))
43 // drop-shadow(12px 12px 0px rgba(136, 194, 163, 0.2));`,
44 filter: `drop-shadow(4px 4px 0px rgba(112, 114, 209, 0.4))
45 drop-shadow(-2px 4px 0px rgba(107, 166, 205, 0.3))
46 drop-shadow(4px -2px 0px rgba(136, 194, 163, 0.2))
47 drop-shadow(-2px -2px 0px rgba(112, 114, 209, 0.2));`,
48 radius: 3,
49 leftMargin: 40,
50 defaultText: "",
51 lineSpacing: 1.3, // Line spacing multiplier
52 cursorOffset: 4, // Spaces to offset from cursor
53
54 get fontSize() {
55 return Math.ceil(
56 vscode.workspace.getConfiguration("editor").get<number>("fontSize") ?? 14,
57 );
58 },
59 get fontFamily() {
60 return (
61 vscode.workspace.getConfiguration("editor").get<string>("fontFamily") ||
62 "helvetica"
63 );
64 },
65 get paddingX() {
66 return Math.ceil(this.getEstimatedTextWidth(" "));
67 },
68 get paddingY() {
69 return Math.ceil(this.fontSize * 0.3);
70 },
71 get lineHeight() {
72 return Math.ceil(this.fontSize * this.lineSpacing);
73 },
74 getEstimatedTextWidth(text: string): number {
75 return text.length * this.fontSize * 0.6;
76 },
77 getTipWidth(text: string): number {
78 // Find the longest line
79 const lines = text.split("\n");
80 const longestLine = lines.reduce(
81 (longest, line) => (line.length > longest.length ? line : longest),
82 "",
83 );
84
85 return this.getEstimatedTextWidth(longestLine) + this.paddingX * 2;
86 },
87 getTipHeight(text: string): number {
88 // Count the number of lines
89 const lineCount = text.split("\n").length;
90 return this.lineHeight * lineCount + this.paddingY * 2;
91 },
92} as const;
93
94// Command ID - can be used in package.json
95export const HIDE_NEXT_EDIT_SUGGESTION_COMMAND =
96 "continue.nextEditWindow.hideNextEditSuggestion";
97export const ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND =
98 "continue.nextEditWindow.acceptNextEditSuggestion";
99
100/**
101 * This is where we create SVG windows and deletion decorations for non-FIM next edit suggestions.
102 * This class controls the decoration object lifetime.
103 * The syntax highlighting and the actual building of SVG happens inside core/codeRenderer/CodeRenderer.ts.
104 */
105export class NextEditWindowManager {
106 private static instance: NextEditWindowManager | undefined;
107
108 private readonly excludedURIPrefixes = ["output:", "vscode://inline-chat"];
109 private theme: string;
110 private fontSize: number;
111 private fontFamily: string;
112 private codeRenderer: CodeRenderer;
113
114 // Current active decoration
115 private currentDecoration: vscode.TextEditorDecorationType | null = null;
116 // A short-lived checker to determine if the cursor moved because of us accepting the next edit, or not.
117 // Distinguishing the two is necessary to determine if we should log it as an accepted or rejected.
118 private accepted: boolean = false;
119 // Track which editor has the active decoration
120 private activeEditor: vscode.TextEditor | null = null;
121 // Store the current tooltip text for accepting
122 private currentTooltipText: string | null = null;
123 // Track for logging purposes.
124 private loggingService: NextEditLoggingService;
125 private mostRecentCompletionId: string | null = null;
126 // Helps us skip redundant calculations. No need for cleanup because this always gets reassigned with new values at showNextEditWindow, and we don't reuse windows.
127 private editableRegionStartLine: number = 0;
128 private editableRegionEndLine: number = 0;
129
130 // State tracking for key reservation.
131 // By default it is set to free, and is only set to reserved when the transition is done.
132 private keyReservationState: "free" | "reserved" | "transitioning" = "free";
133 private latestOperationId = 0;
134
135 // Disposables
136 private disposables: vscode.Disposable[] = [];
137
138 private textApplier: TextApplier | null = null;
139
140 private finalCursorPos: vscode.Position | null = null;
141
142 private isLineDelete: boolean = false;
143
144 private context: vscode.ExtensionContext | null = null;
145
146 public static getInstance(): NextEditWindowManager {
147 if (!NextEditWindowManager.instance) {
148 NextEditWindowManager.instance = new NextEditWindowManager();
149 }
150 return NextEditWindowManager.instance;
151 }
152
153 public static isInstantiated(): boolean {
154 return !!NextEditWindowManager.instance;
155 }
156
157 public static clearInstance(): void {
158 if (NextEditWindowManager.instance) {
159 NextEditWindowManager.instance.dispose();
160 NextEditWindowManager.instance = undefined;
161 }
162 }
163
164 private constructor() {
165 this.theme = getThemeString();
166
167 console.log(
168 "Next Edit Theme initialized:",
169 this.theme
170 ? `Theme exists: ${JSON.stringify(this.theme)}`
171 : "Theme is undefined",
172 );
173 this.setupListeners();
174 this.codeRenderer = CodeRenderer.getInstance();
175
176 const editorConfig = vscode.workspace.getConfiguration("editor");
177 this.fontSize = editorConfig.get<number>("fontSize") ?? 14;
178 this.fontFamily = editorConfig.get<string>("fontFamily") ?? "monospace";
179
180 this.loggingService = NextEditLoggingService.getInstance();
181 }
182
183 // This is an implementation of last-action-wins.
184 // For each action that fires setKeyReservation, it keeps its own operationId while incrementing latestOperationId.
185 // When an action completes, checking for operationId === latestOperationId will determine which one came last.
186 private async setKeyReservation(reserve: boolean): Promise<void> {
187 // Increment and capture this operation's ID.
188 const operationId = ++this.latestOperationId;
189
190 // Return early when already in desired state.
191 if (
192 (reserve && this.keyReservationState === "reserved") ||
193 (!reserve && this.keyReservationState === "free")
194 ) {
195 return;
196 }
197
198 try {
199 await this.performKeyReservation(reserve);
200
201 // Only update state if we're still the latest operation.
202 if (operationId === this.latestOperationId) {
203 this.keyReservationState = reserve ? "reserved" : "free";
204 }
205 } catch (err) {
206 console.error(`Failed to set nextEditWindowActive to ${reserve}: ${err}`);
207
208 // Only reset to free if we're still the latest operation.
209 if (operationId === this.latestOperationId) {
210 this.keyReservationState = "free";
211 }
212 throw err;
213 }
214 }
215
216 public async resetKeyReservation(): Promise<void> {
217 // Reset internal tracking.
218 this.keyReservationState = "free";
219 this.latestOperationId = 0;
220
221 // Ensure VS Code context matches.
222 try {
223 await this.performKeyReservation(false);
224 } catch (err) {
225 console.error(`Failed to reset nextEditWindowActive context: ${err}`);
226 }
227 }
228
229 private async performKeyReservation(reserve: boolean): Promise<void> {
230 try {
231 await vscode.commands.executeCommand(
232 "setContext",
233 "nextEditWindowActive",
234 reserve,
235 );
236 } catch (err) {
237 console.error(`Failed to set nextEditWindowActive to ${reserve}: ${err}`);
238 throw err;
239 }
240 }
241
242 public static async reserveTabAndEsc() {
243 await NextEditWindowManager.getInstance().setKeyReservation(true);
244 }
245
246 public static async freeTabAndEsc() {
247 await NextEditWindowManager.getInstance().setKeyReservation(false);
248 }
249
250 /**
251 * An async setup function to help us initialize the NextEditWindowManager.
252 * This is necessary because we need some setup to be done asynchronously,
253 * and constructors in TypeScript cannot be async.
254 * Plus, it's generally not recommended to pass arguments to getInstance() of a singleton.
255 * @param context The extension context.
256 * @param textApplier Callback that lets us use external deps such as llms if needed.
257 */
258 public async setupNextEditWindowManager(
259 context: vscode.ExtensionContext,
260 textApplier?: TextApplier,
261 ) {
262 this.context = context;
263
264 // Set nextEditWindowActive to false to free esc and tab,
265 // letting them return to their original behaviors.
266 await this.resetKeyReservation();
267 // await NextEditWindowManager.freeTabAndEsc();
268
269 // Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks.
270 this.registerCommandSafely(HIDE_NEXT_EDIT_SUGGESTION_COMMAND, async () => {
271 console.log(
272 "deleteChain from NextEditWindowManager.ts: hide next edit command",
273 );
274 NextEditProvider.getInstance().deleteChain();
275 await this.hideAllNextEditWindowsAndResetCompletionId();
276 });
277 this.registerCommandSafely(
278 ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND,
279 async () => await this.acceptNextEdit(),
280 );
281
282 // Add this class to context disposables.
283 context.subscriptions.push(this);
284
285 if (textApplier) {
286 this.textApplier = textApplier;
287 }
288
289 await this.codeRenderer.setTheme(this.theme);
290 }
291
292 /**
293 * Update the most recent completion id.
294 * @param completionId The id of current completion request.
295 */
296 public updateCurrentCompletionId(completionId: string) {
297 this.mostRecentCompletionId = completionId;
298 }
299
300 /**
301 * Registers our two custom commands to the extension context.
302 * @param commandId Custom commands to help set up next edit.
303 * @param callback Function to run on command execution.
304 */
305 private registerCommandSafely(
306 commandId:
307 | "continue.nextEditWindow.hideNextEditSuggestion"
308 | "continue.nextEditWindow.acceptNextEditSuggestion",
309 callback: () => Promise<void>,
310 ) {
311 if (!this.context) {
312 console.log("Extension context is not yet set.");
313 return;
314 }
315
316 try {
317 const command = vscode.commands.registerCommand(commandId, callback);
318 this.context.subscriptions.push(command);
319 } catch (error) {
320 console.log(
321 `Command ${commandId} already has an associated callback, skipping registration`,
322 );
323 }
324 }
325
326 /**
327 * Show a tooltip with the given text at the current cursor position.
328 * @param editor The active text editor.
329 * @param text Text to display in the tooltip.
330 */
331 public async showNextEditWindow(
332 editor: vscode.TextEditor,
333 currCursorPos: vscode.Position,
334 editableRegionStartLine: number,
335 editableRegionEndLine: number,
336 oldEditRangeSlice: string,
337 newEditRangeSlice: string,
338 diffLines: DiffLine[],
339 ) {
340 if (!this.shouldRenderTip(editor.document.uri)) {
341 return;
342 }
343
344 // Clear any existing decorations first (very important to prevent overlapping).
345 await this.hideAllNextEditWindows();
346
347 this.activeEditor = editor;
348
349 this.editableRegionStartLine = editableRegionStartLine;
350 this.editableRegionEndLine = editableRegionEndLine;
351
352 // Store the current tooltip text for accepting later.
353 this.currentTooltipText = newEditRangeSlice;
354
355 // Determine if this is a line deletion case
356 // NOTE: A simpler approach might be to just delete the line when newEditRangeSlice is "".
357 // But we opt for the below in case the above note is too naive.
358 this.isLineDelete = false;
359 if (
360 newEditRangeSlice === "" &&
361 editableRegionStartLine === editableRegionEndLine
362 ) {
363 // Check if diffLines contains only deletions (no additions).
364 const onlyDeletions = diffLines.every(
365 (diff) => diff.type === "old" || diff.type === "same",
366 );
367 const hasDeletedLine = diffLines.some((diff) => diff.type === "old");
368
369 if (onlyDeletions && hasDeletedLine) {
370 // Check if the entire line is being deleted (not just characters).
371 const line = editor.document.lineAt(editableRegionStartLine).text;
372 const oldLine = oldEditRangeSlice.trim();
373 if (line.trim() === oldLine || line.trim() === "") {
374 this.isLineDelete = true;
375 }
376 }
377 }
378
379 // How far away is the current line from the start of the editable region?
380 const lineOffsetAtCursorPos =
381 currCursorPos.line - this.editableRegionStartLine;
382
383 // How long is the line at the current cursor position?
384 const lineContentAtCursorPos =
385 newEditRangeSlice.split("\n")[lineOffsetAtCursorPos];
386
387 const offset = getOffsetPositionAtLastNewLine(
388 diffLines,
389 lineContentAtCursorPos,
390 lineOffsetAtCursorPos,
391 );
392
393 // Calculate the final cursor position.
394 if (this.isLineDelete) {
395 // For line deletion, position cursor at the end of the previous line.
396 if (this.editableRegionStartLine > 0) {
397 const prevLine = editor.document.lineAt(
398 this.editableRegionStartLine - 1,
399 );
400 this.finalCursorPos = new vscode.Position(
401 this.editableRegionStartLine - 1,
402 prevLine.text.length,
403 );
404 } else {
405 // If we're deleting the first line, position at the start of the document.
406 this.finalCursorPos = new vscode.Position(0, 0);
407 }
408 } else {
409 // For normal edits, use the standard calculation.
410 this.finalCursorPos = new vscode.Position(
411 this.editableRegionStartLine + offset.line,
412 offset.character,
413 );
414 }
415
416 // Create and apply decoration with the text.
417 if (newEditRangeSlice !== "") {
418 try {
419 await this.renderWindow(
420 editor,
421 currCursorPos,
422 oldEditRangeSlice,
423 newEditRangeSlice,
424 this.editableRegionStartLine,
425 diffLines,
426 );
427 } catch (error) {
428 console.error("Failed to render window:", error);
429 // Clean up and reset state.
430 await this.hideAllNextEditWindows();
431 return;
432 }
433 }
434
435 const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
436
437 this.renderDeletions(editor, diffChars);
438
439 // Reserve tab and esc to either accept or reject the displayed next edit contents.
440 try {
441 await NextEditWindowManager.reserveTabAndEsc();
442 } catch (err) {
443 console.error(
444 `Error reserving Tab/Esc after showing decorations: ${err}`,
445 );
446 await this.hideAllNextEditWindows();
447 return;
448 }
449 }
450
451 /**
452 * Hide all tooltips in all editors.
453 */
454 public async hideAllNextEditWindows() {
455 try {
456 await NextEditWindowManager.freeTabAndEsc();
457 } catch (err) {
458 console.error(`Error freeing Tab/Esc while hiding: ${err}`);
459 }
460
461 if (this.currentDecoration) {
462 vscode.window.visibleTextEditors.forEach((editor) => {
463 editor.setDecorations(this.currentDecoration!, []);
464 });
465
466 // If we know which editor had the decoration, clear it specifically.
467 // This is a bit redundant but ensures we don't leave any decorations behind.
468 if (this.activeEditor) {
469 this.activeEditor.setDecorations(this.currentDecoration, []);
470 this.activeEditor = null;
471 }
472
473 // This prevents memory leaks.
474 this.currentDecoration.dispose();
475 this.currentDecoration = null;
476
477 // Clear the current tooltip text.
478 this.currentTooltipText = null;
479 }
480
481 if (this.disposables.length > 0) {
482 this.disposables.forEach((d) => d.dispose());
483 this.disposables = [];
484 }
485 }
486
487 public async hideAllNextEditWindowsAndResetCompletionId() {
488 await this.hideAllNextEditWindows();
489
490 // Log with accept = false.
491 await vscode.commands.executeCommand(
492 "continue.logNextEditOutcomeReject",
493 this.mostRecentCompletionId,
494 this.loggingService,
495 );
496
497 this.mostRecentCompletionId = null;
498 }
499
500 /**
501 * Accept the current next edit suggestion by inserting it at cursor position.
502 */
503 private async acceptNextEdit() {
504 if (this.activeEditor === null || this.currentTooltipText === null) {
505 return;
506 }
507 this.accepted = true;
508
509 const editor = this.activeEditor;
510 const text = this.currentTooltipText;
511 const position = editor.selection.active;
512
513 let success = false;
514
515 // Hide windows first for a snappier feel.
516 await this.hideAllNextEditWindows();
517
518 if (this.textApplier) {
519 success = await this.textApplier.applyText(
520 editor,
521 text,
522 position,
523 this.finalCursorPos,
524 );
525 } else {
526 // Define the range to replace.
527 const startPos = new vscode.Position(this.editableRegionStartLine, 0);
528 const endPosChar = editor.document.lineAt(this.editableRegionEndLine).text
529 .length;
530
531 const endPos = new vscode.Position(
532 this.editableRegionEndLine,
533 endPosChar,
534 );
535 const editRange = new vscode.Range(startPos, endPos);
536
537 if (this.isLineDelete) {
538 // Handle line deletion - extend the range to include the newline.
539 let lineDeleteRange = editRange;
540
541 // If this isn't the last line, extend to include the newline character.
542 if (this.editableRegionStartLine < editor.document.lineCount - 1) {
543 lineDeleteRange = new vscode.Range(
544 startPos,
545 new vscode.Position(this.editableRegionStartLine + 1, 0),
546 );
547 }
548
549 success = await editor.edit((editBuilder) => {
550 editBuilder.delete(lineDeleteRange);
551 });
552 } else {
553 success = await editor.edit((editBuilder) => {
554 editBuilder.replace(editRange, text);
555 });
556 }
557 }
558
559 if (success && this.finalCursorPos) {
560 // Move cursor to the final position if available.
561 editor.selection = new vscode.Selection(
562 this.finalCursorPos,
563 this.finalCursorPos,
564 );
565 }
566
567 // Log with accept = true.
568 await vscode.commands.executeCommand(
569 "continue.logNextEditOutcomeAccept",
570 this.mostRecentCompletionId,
571 this.loggingService,
572 );
573 this.mostRecentCompletionId = null;
574
575 // Reset to false for future logging.
576 this.accepted = false;
577 }
578
579 /**
580 * Dispose of the NextEditWindowManager.
581 */
582 public dispose() {
583 void this.resetKeyReservation().catch((err) =>
584 console.error(`Failed to reset keys on dispose: ${err}`),
585 );
586
587 // Dispose current decoration.
588 if (this.currentDecoration) {
589 this.currentDecoration.dispose();
590 this.currentDecoration = null;
591 }
592
593 // Dispose all other disposables.
594 this.disposables.forEach((d) => d.dispose());
595 this.disposables = [];
596 }
597
598 /**
599 * Setup listeners for theme, font, and cursor position changes.
600 */
601 private setupListeners() {
602 // Theme change listener.
603 vscode.workspace.onDidChangeConfiguration(async (e) => {
604 if (
605 e.affectsConfiguration("workbench.colorTheme") ||
606 e.affectsConfiguration("editor.fontSize") ||
607 e.affectsConfiguration("editor.fontFamily") ||
608 e.affectsConfiguration("window.autoDetectColorScheme") ||
609 e.affectsConfiguration("window.autoDetectHighContrast") ||
610 e.affectsConfiguration("workbench.preferredDarkColorTheme") ||
611 e.affectsConfiguration("workbench.preferredLightColorTheme") ||
612 e.affectsConfiguration("workbench.preferredHighContrastColorTheme") ||
613 e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme")
614 ) {
615 this.theme = getThemeString();
616 await this.codeRenderer.setTheme(this.theme);
617 console.log(
618 "Theme updated:",
619 this.theme ? "Theme exists" : "Theme is undefined",
620 );
621 const editorConfig = vscode.workspace.getConfiguration("editor");
622 this.fontSize = editorConfig.get<number>("fontSize") ?? 14;
623 this.fontFamily = editorConfig.get<string>("fontFamily") ?? "monospace";
624 }
625 });
626
627 // Listen for active color theme changes.
628 vscode.window.onDidChangeActiveColorTheme(async () => {
629 this.theme = getThemeString();
630 await this.codeRenderer.setTheme(this.theme);
631 console.log(
632 "Active theme changed:",
633 this.theme ? "Theme exists" : "Theme is undefined",
634 );
635 });
636
637 // Listen for editor changes to clean up decorations when editor closes.
638 vscode.window.onDidChangeVisibleTextEditors(async () => {
639 // If our active editor is no longer visible, clear decorations.
640 if (
641 this.activeEditor &&
642 !vscode.window.visibleTextEditors.includes(this.activeEditor)
643 ) {
644 if (this.mostRecentCompletionId) {
645 this.loggingService.cancelRejectionTimeout(
646 this.mostRecentCompletionId,
647 );
648 }
649 await this.hideAllNextEditWindows();
650 }
651 });
652
653 // Listen for selection changes to hide tooltip when cursor moves.
654 vscode.window.onDidChangeTextEditorSelection(async (e) => {
655 // If the selection changed in our active editor, hide the tooltip.
656 if (this.activeEditor && e.textEditor === this.activeEditor) {
657 // If the cursor moved because of something other than accepting next edit, stop logging it.
658 if (!this.accepted && this.mostRecentCompletionId) {
659 this.loggingService.cancelRejectionTimeout(
660 this.mostRecentCompletionId,
661 );
662 }
663 await this.hideAllNextEditWindows();
664 }
665 });
666 }
667
668 private shouldRenderTip(uri: vscode.Uri): boolean {
669 const isAllowedUri =
670 !this.excludedURIPrefixes.some((prefix) =>
671 uri.toString().startsWith(prefix),
672 ) && uri.scheme !== "comment";
673
674 const isEnabled =
675 !!vscode.workspace
676 .getConfiguration(EXTENSION_NAME)
677 .get<boolean>("showInlineTip") === true;
678
679 return isAllowedUri && isEnabled;
680 }
681
682 /**
683 * Create a render of the given code, supporting multiple lines.
684 */
685 private async createCodeRender(
686 text: string,
687 currLineOffsetFromTop: number,
688 newDiffLines: DiffLine[],
689 ): Promise<
690 | { uri: vscode.Uri; dimensions: { width: number; height: number } }
691 | undefined
692 > {
693 try {
694 const tipWidth = SVG_CONFIG.getTipWidth(text);
695 const tipHeight = SVG_CONFIG.getTipHeight(text);
696 const dimensions = {
697 width: tipWidth,
698 height: tipHeight,
699 };
700
701 const uri = await this.codeRenderer.getDataUri(
702 text,
703 "typescript",
704 {
705 imageType: "svg",
706 fontSize: this.fontSize,
707 fontFamily: this.fontFamily,
708 dimensions: dimensions,
709 lineHeight: SVG_CONFIG.lineHeight,
710 },
711 currLineOffsetFromTop,
712 newDiffLines,
713 );
714
715 return {
716 uri: vscode.Uri.parse(uri),
717 dimensions,
718 };
719 } catch (error) {
720 console.error("Error creating SVG tooltip:", error);
721 return undefined;
722 }
723 }
724
725 /**
726 * Create a decoration type with the code render.
727 * @param code: The code to render.
728 * @returns The decoration.
729 */
730 private async createCodeRenderDecoration(
731 originalCode: string,
732 predictedCode: string,
733 position: vscode.Position,
734 editableRegionStartLine: number,
735 newDiffLines: DiffLine[],
736 ): Promise<vscode.TextEditorDecorationType | undefined> {
737 const currLineOffsetFromTop = position.line - editableRegionStartLine;
738 const uriAndDimensions = await this.createCodeRender(
739 predictedCode,
740 currLineOffsetFromTop,
741 newDiffLines,
742 );
743 if (!uriAndDimensions) {
744 return undefined;
745 }
746
747 const { uri, dimensions } = uriAndDimensions;
748 const tipWidth = dimensions.width;
749 const tipHeight = dimensions.height;
750
751 const offsetFromTop =
752 (position.line - editableRegionStartLine) * SVG_CONFIG.lineHeight;
753
754 // Position the decoration with minimal left margin since it's already at line end
755 const marginLeft = SVG_CONFIG.paddingX; // Use consistent padding instead of complex calculation
756
757 return vscode.window.createTextEditorDecorationType({
758 before: {
759 contentIconPath: uri,
760 border: `transparent; position: absolute; z-index: 2147483647;
761 filter: ${SVG_CONFIG.filter};
762 margin-top: ${-1 * offsetFromTop}px;
763 margin-left: ${marginLeft}px;`,
764 width: `${tipWidth}px`,
765 height: `${tipHeight}px`,
766 },
767 rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed,
768 });
769 }
770
771 private buildHideTooltipHoverMsg() {
772 const hoverMarkdown = new vscode.MarkdownString(
773 `[Reject (Esc)](command:${HIDE_NEXT_EDIT_SUGGESTION_COMMAND}) | [Accept (Tab)](command:${ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND})`,
774 );
775
776 hoverMarkdown.isTrusted = true;
777 hoverMarkdown.supportHtml = true;
778 return hoverMarkdown;
779 }
780
781 private isValidRange(
782 editor: vscode.TextEditor,
783 range: vscode.Range,
784 ): boolean {
785 const doc = editor.document;
786
787 // Check if line numbers are valid.
788 if (range.start.line < 0 || range.start.line >= doc.lineCount) {
789 console.log(
790 "Invalid start line:",
791 range.start.line,
792 "doc lines:",
793 doc.lineCount,
794 );
795 return false;
796 }
797
798 if (range.end.line < 0 || range.end.line >= doc.lineCount) {
799 console.log(
800 "Invalid end line:",
801 range.end.line,
802 "doc lines:",
803 doc.lineCount,
804 );
805 return false;
806 }
807
808 // Check if character positions are valid.
809 const startLine = doc.lineAt(range.start.line);
810 const endLine = doc.lineAt(range.end.line);
811
812 if (
813 range.start.character < 0 ||
814 range.start.character > startLine.text.length
815 ) {
816 console.log(
817 "Invalid start character:",
818 range.start.character,
819 "line length:",
820 startLine.text.length,
821 );
822 return false;
823 }
824
825 if (range.end.character < 0 || range.end.character > endLine.text.length) {
826 console.log(
827 "Invalid end character:",
828 range.end.character,
829 "line length:",
830 endLine.text.length,
831 );
832 return false;
833 }
834
835 return true;
836 }
837
838 /**
839 * Calculate a position to the right of the cursor with the specified offset.
840 */
841 private getDecorationOffsetPosition(
842 editor: vscode.TextEditor,
843 position: vscode.Position,
844 ): vscode.Position {
845 // Place decoration at the end of the current line
846 const line = editor.document.lineAt(position.line);
847 return new vscode.Position(position.line, line.text.length);
848 }
849
850 /**
851 * Render a window with the given text at the specified position.
852 */
853 private async renderWindow(
854 editor: vscode.TextEditor,
855 position: vscode.Position,
856 originalCode: string,
857 predictedCode: string,
858 editableRegionStartLine: number,
859 newDiffLines: DiffLine[],
860 ) {
861 // Capture document version to detect changes.
862 const docVersion = editor.document.version;
863
864 // Create a new decoration with the text.
865 const decoration = await this.createCodeRenderDecoration(
866 originalCode,
867 predictedCode,
868 position,
869 editableRegionStartLine,
870 newDiffLines,
871 );
872 if (!decoration) {
873 console.error("Failed to create decoration for text:", predictedCode);
874 return;
875 }
876
877 // Check if document changed during async operation.
878 if (editor.document.version !== docVersion) {
879 console.log("Document changed during decoration creation, aborting");
880 decoration.dispose();
881 return;
882 }
883
884 // Store the decoration and editor.
885 this.currentDecoration = decoration; // TODO: This might be redundant.
886 this.disposables.push(decoration);
887
888 // Calculate how far off to the right of the cursor the decoration should be.
889 const decorationOffsetPosition = this.getDecorationOffsetPosition(
890 editor,
891 position,
892 );
893 const range = new vscode.Range(
894 decorationOffsetPosition,
895 decorationOffsetPosition,
896 );
897
898 // Validate the range before applying.
899 if (!this.isValidRange(editor, range)) {
900 console.error("Invalid range detected, skipping decoration");
901 return;
902 }
903
904 // Apply the decoration at the calculated position.
905 editor.setDecorations(this.currentDecoration, [
906 {
907 range: new vscode.Range(
908 decorationOffsetPosition,
909 decorationOffsetPosition,
910 ),
911 hoverMessage: [this.buildHideTooltipHoverMsg()],
912 },
913 ]);
914
915 // Clear the timeout while SVG is on the editor.
916 if (this.currentDecoration && this.mostRecentCompletionId)
917 this.loggingService.cancelRejectionTimeoutButKeepCompletionId(
918 this.mostRecentCompletionId,
919 );
920 }
921
922 private renderDeletions(editor: vscode.TextEditor, oldDiffChars: DiffChar[]) {
923 const charsToDelete: vscode.DecorationOptions[] = [];
924
925 // const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
926
927 oldDiffChars.forEach((diff) => {
928 // TODO: This check if technically redundant.
929 if (diff.type === "old") {
930 charsToDelete.push({
931 range: new vscode.Range(
932 new vscode.Position(
933 this.editableRegionStartLine + diff.oldLineIndex!,
934 diff.oldCharIndexInLine!,
935 ),
936 new vscode.Position(
937 this.editableRegionStartLine + diff.oldLineIndex!,
938 diff.oldCharIndexInLine! + diff.char.length,
939 ),
940 ),
941 });
942 }
943 });
944
945 const deleteDecorationType = vscode.window.createTextEditorDecorationType({
946 backgroundColor: "rgba(255, 0, 0, 0.5)",
947 textDecoration: "line-through",
948 });
949
950 editor.setDecorations(deleteDecorationType, charsToDelete);
951 this.disposables.push(deleteDecorationType);
952 }
953
954 async getExactCharacterWidth(): Promise<number> {
955 // For VS Code extensions, you can sometimes access the editor's text metrics
956 const activeEditor = vscode.window.activeTextEditor;
957 if (activeEditor) {
958 // VS Code has internal methods to measure text, but they're not all exposed
959 // in the public API. You might need to use reflection or known properties.
960
961 // Example accessing through reflection (this is pseudocode)
962 const editorInstance = activeEditor as any;
963 if (editorInstance._modelData && editorInstance._modelData.viewModel) {
964 const viewModel = editorInstance._modelData.viewModel;
965 return (
966 viewModel.getLineWidth(0) /
967 activeEditor.document.lineAt(0).text.length
968 );
969 }
970 }
971
972 // If all else fails, return a reasonable default
973 return SVG_CONFIG.fontSize * 0.6;
974 }
975
976 public hasAccepted() {
977 return this.accepted;
978 }
979
980 public registerSelectionChangeHandler(): void {
981 const manager = SelectionChangeManager.getInstance();
982
983 manager.registerListener(
984 "nextEditWindowManager",
985 async (e, state) => {
986 if (state.nextEditWindowAccepted) {
987 console.log(
988 "NextEditWindowManager: Edit was just accepted, preserving chain",
989 );
990 return true;
991 }
992 return false;
993 },
994 HandlerPriority.CRITICAL,
995 );
996 }
997}
998
999export default async function setupNextEditWindowManager(
1000 context: vscode.ExtensionContext,
1001 textApplier?: TextApplier,
1002) {
1003 await NextEditWindowManager.getInstance().setupNextEditWindowManager(
1004 context,
1005 textApplier,
1006 );
1007}