Elffuss BraidHub

kikocis/continue public

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