Elffuss BraidHub

kikocis/continue public

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