Elffuss BraidHub

kikocis/continue public

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