Elffuss BraidHub

kikocis/continue public

5810b3f3bf39 · 21.4 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 { DiffLine } from "core";
7import { CodeRenderer } from "core/codeRenderer/CodeRenderer";
8import {
9 NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
10 NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
11} from "core/nextEdit/constants";
12import { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff";
13import { getThemeString } from "../util/getTheme";
14
15export interface TextApplier {
16 applyText(
17 editor: vscode.TextEditor,
18 text: string,
19 position: vscode.Position,
20 finalCursorPos: vscode.Position | null,
21 ): Promise<boolean>;
22}
23
24const SVG_CONFIG = {
25 stroke: "#999998",
26 strokeWidth: 1,
27 textColor: "#999998",
28 filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))",
29 radius: 3,
30 leftMargin: 40,
31 defaultText: "",
32 lineSpacing: 1.2, // Line spacing multiplier
33 cursorOffset: 4, // Spaces to offset from cursor
34
35 get fontSize() {
36 return Math.ceil(
37 vscode.workspace.getConfiguration("editor").get<number>("fontSize") ?? 14,
38 );
39 },
40 get fontFamily() {
41 return (
42 vscode.workspace.getConfiguration("editor").get<string>("fontFamily") ||
43 "helvetica"
44 );
45 },
46 get paddingX() {
47 return Math.ceil(this.getEstimatedTextWidth(" "));
48 },
49 get paddingY() {
50 return Math.ceil(this.fontSize * 0.3);
51 },
52 get lineHeight() {
53 return Math.ceil(this.fontSize * this.lineSpacing);
54 },
55 getEstimatedTextWidth(text: string): number {
56 return text.length * this.fontSize * 0.6;
57 },
58 getTipWidth(text: string): number {
59 // Find the longest line
60 const lines = text.split("\n");
61 const longestLine = lines.reduce(
62 (longest, line) => (line.length > longest.length ? line : longest),
63 "",
64 );
65
66 return this.getEstimatedTextWidth(longestLine) + this.paddingX * 2;
67 },
68 getTipHeight(text: string): number {
69 // Count the number of lines
70 const lineCount = text.split("\n").length;
71 return this.lineHeight * lineCount + this.paddingY * 2;
72 },
73} as const;
74
75// Command ID - can be used in package.json
76export const HIDE_NEXT_EDIT_SUGGESTION_COMMAND =
77 "continue.nextEditWindow.hideNextEditSuggestion";
78export const ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND =
79 "continue.nextEditWindow.acceptNextEditSuggestion";
80
81export class NextEditWindowManager {
82 private static instance: NextEditWindowManager | undefined;
83
84 private readonly excludedURIPrefixes = ["output:", "vscode://inline-chat"];
85 private theme: string;
86 private fontSize: number;
87 private fontFamily: string;
88 private codeRenderer: CodeRenderer;
89
90 // Current active decoration
91 private currentDecoration: vscode.TextEditorDecorationType | null = null;
92 // Track which editor has the active decoration
93 private activeEditor: vscode.TextEditor | null = null;
94 // Store the current tooltip text for accepting
95 private currentTooltipText: string | null = null;
96
97 // Disposables
98 private disposables: vscode.Disposable[] = [];
99
100 private textApplier: TextApplier | null = null;
101
102 private finalCursorPos: vscode.Position | null = null;
103
104 private context: vscode.ExtensionContext | null = null;
105
106 public static getInstance(): NextEditWindowManager {
107 if (!NextEditWindowManager.instance) {
108 NextEditWindowManager.instance = new NextEditWindowManager();
109 }
110 return NextEditWindowManager.instance;
111 }
112
113 public static isInstantiated(): boolean {
114 return !!NextEditWindowManager.instance;
115 }
116
117 public static clearInstance(): void {
118 if (NextEditWindowManager.instance) {
119 NextEditWindowManager.instance.dispose();
120 NextEditWindowManager.instance = undefined;
121 }
122 }
123
124 private constructor() {
125 this.theme = getThemeString();
126
127 console.log(
128 "Next Edit Theme initialized:",
129 this.theme
130 ? `Theme exists: ${JSON.stringify(this.theme)}`
131 : "Theme is undefined",
132 );
133 this.setupListeners();
134 this.codeRenderer = CodeRenderer.getInstance();
135
136 const editorConfig = vscode.workspace.getConfiguration("editor");
137 this.fontSize = editorConfig.get<number>("fontSize") ?? 14;
138 this.fontFamily = editorConfig.get<string>("fontFamily") ?? "monospace";
139 }
140
141 public static async reserveTabAndEsc() {
142 await vscode.commands.executeCommand(
143 "setContext",
144 "nextEditWindowActive",
145 true,
146 );
147 }
148
149 public static async freeTabAndEsc() {
150 await vscode.commands.executeCommand(
151 "setContext",
152 "nextEditWindowActive",
153 false,
154 );
155 }
156
157 /**
158 * An async setup function to help us initialize the NextEditWindowManager.
159 * This is necessary because we need some setup to be done asynchronously,
160 * and constructors in TypeScript cannot be async.
161 * Plus, it's generally not recommended to pass arguments to getInstance() of a singleton.
162 * @param context The extension context.
163 * @param textApplier Callback that lets us use external deps such as llms if needed.
164 */
165 public async setupNextEditWindowManager(
166 context: vscode.ExtensionContext,
167 textApplier?: TextApplier,
168 ) {
169 this.context = context;
170
171 // Set nextEditWindowActive to false to free esc and tab,
172 // letting them return to their original behaviors.
173 await NextEditWindowManager.freeTabAndEsc();
174
175 // Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks.
176 this.registerCommandSafely(
177 HIDE_NEXT_EDIT_SUGGESTION_COMMAND,
178 async () => await this.hideAllNextEditWindows(),
179 );
180 this.registerCommandSafely(
181 ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND,
182 async () => await this.acceptNextEdit(),
183 );
184
185 // Add this class to context disposables.
186 context.subscriptions.push(this);
187
188 if (textApplier) {
189 this.textApplier = textApplier;
190 }
191
192 await this.codeRenderer.setTheme(this.theme);
193 }
194
195 /**
196 * Registers our two custom commands to the extension context.
197 * @param commandId Custom commands to help set up next edit.
198 * @param callback Function to run on command execution.
199 */
200 private registerCommandSafely(
201 commandId:
202 | "continue.nextEditWindow.hideNextEditSuggestion"
203 | "continue.nextEditWindow.acceptNextEditSuggestion",
204 callback: () => Promise<void>,
205 ) {
206 if (!this.context) {
207 console.log("Extension context is not yet set.");
208 return;
209 }
210
211 try {
212 const command = vscode.commands.registerCommand(commandId, callback);
213 this.context.subscriptions.push(command);
214 } catch (error) {
215 console.log(
216 `Command ${commandId} already has an associated callback, skipping registration`,
217 );
218 }
219 }
220
221 /**
222 * Show a tooltip with the given text at the current cursor position.
223 * @param editor The active text editor.
224 * @param text Text to display in the tooltip.
225 */
226 public async showNextEditWindow(
227 editor: vscode.TextEditor,
228 currCursorPos: vscode.Position,
229 editableRegionStartLine: number,
230 newEditRangeSlice: string,
231 diffLines: DiffLine[],
232 ) {
233 if (!newEditRangeSlice || !this.shouldRenderTip(editor.document.uri)) {
234 return;
235 }
236
237 // Clear any existing decorations first (very important to prevent overlapping).
238 await this.hideAllNextEditWindows();
239
240 // Store the current tooltip text for accepting later.
241 this.currentTooltipText = newEditRangeSlice;
242
243 // How far away is the current line from the start of the editable region?
244 const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine;
245
246 // How long is the line at the current cursor position?
247 const lineContentAtCursorPos =
248 newEditRangeSlice.split("\n")[lineOffsetAtCursorPos];
249
250 const offset = getOffsetPositionAtLastNewLine(
251 diffLines,
252 lineContentAtCursorPos,
253 lineOffsetAtCursorPos,
254 );
255
256 // Calculate the actual line number in the editor by adding the startPos offset
257 // to the line number from the diff calculation.
258 this.finalCursorPos = new vscode.Position(
259 editableRegionStartLine + offset.line,
260 offset.character,
261 );
262
263 // Create and apply decoration with the text.
264 await this.renderTooltip(editor, currCursorPos, newEditRangeSlice);
265
266 // Reserve tab and esc to either accept or reject the displayed next edit contents.
267 await NextEditWindowManager.reserveTabAndEsc();
268 }
269
270 /**
271 * Hide all tooltips in all editors.
272 */
273 public async hideAllNextEditWindows() {
274 if (this.currentDecoration) {
275 vscode.window.visibleTextEditors.forEach((editor) => {
276 editor.setDecorations(this.currentDecoration!, []);
277 });
278
279 // If we know which editor had the decoration, clear it specifically.
280 // This is a bit redundant but ensures we don't leave any decorations behind.
281 if (this.activeEditor) {
282 this.activeEditor.setDecorations(this.currentDecoration, []);
283 this.activeEditor = null;
284 }
285
286 // This prevents memory leaks.
287 this.currentDecoration.dispose();
288 this.currentDecoration = null;
289
290 this.disposables.forEach((d) => d.dispose());
291 this.disposables = [];
292
293 // Clear the current tooltip text.
294 this.currentTooltipText = null;
295 }
296
297 await NextEditWindowManager.freeTabAndEsc();
298 }
299
300 /**
301 * Accept the current next edit suggestion by inserting it at cursor position.
302 */
303 private async acceptNextEdit() {
304 if (!this.activeEditor || !this.currentTooltipText) {
305 return;
306 }
307
308 const editor = this.activeEditor;
309 const text = this.currentTooltipText;
310 const position = editor.selection.active;
311
312 let success = false;
313 if (this.textApplier) {
314 success = await this.textApplier.applyText(
315 editor,
316 text,
317 position,
318 this.finalCursorPos,
319 );
320 } else {
321 // Define the editable region.
322 const editableRegionStartLine = Math.max(
323 0,
324 position.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
325 );
326 const editableRegionEndLine = Math.min(
327 editor.document.lineCount - 1,
328 position.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
329 );
330 const startPos = new vscode.Position(editableRegionStartLine, 0);
331 const endPosChar = editor.document.lineAt(editableRegionEndLine).text
332 .length;
333
334 const endPos = new vscode.Position(editableRegionEndLine, endPosChar);
335 const editRange = new vscode.Range(startPos, endPos);
336
337 success = await editor.edit((editBuilder) => {
338 editBuilder.replace(editRange, text);
339 });
340
341 // Disable inline suggestions temporarily.
342 // This prevents the race condition between vscode's inline completion provider
343 // and the next edit window manager's cursor repositioning logic.
344 await vscode.workspace
345 .getConfiguration()
346 .update("editor.inlineSuggest.enabled", false, true);
347 }
348
349 if (success) {
350 // Move cursor to the final position if available.
351 if (this.finalCursorPos) {
352 editor.selection = new vscode.Selection(
353 this.finalCursorPos,
354 this.finalCursorPos,
355 );
356
357 // Reenable inline suggestions after we move the cursor.
358 await vscode.workspace
359 .getConfiguration()
360 .update("editor.inlineSuggest.enabled", true, true);
361
362 await this.hideAllNextEditWindows();
363 }
364 }
365 }
366
367 /**
368 * Dispose of the NextEditWindowManager.
369 */
370 public dispose() {
371 // Dispose current decoration.
372 if (this.currentDecoration) {
373 this.currentDecoration.dispose();
374 this.currentDecoration = null;
375 }
376
377 // Dispose all other disposables.
378 this.disposables.forEach((d) => d.dispose());
379 this.disposables = [];
380 }
381
382 /**
383 * Setup listeners for theme, font, and cursor position changes.
384 */
385 private setupListeners() {
386 // Theme change listener.
387 vscode.workspace.onDidChangeConfiguration((e) => {
388 if (
389 e.affectsConfiguration("workbench.colorTheme") ||
390 e.affectsConfiguration("editor.fontSize") ||
391 e.affectsConfiguration("editor.fontFamily") ||
392 e.affectsConfiguration("window.autoDetectColorScheme") ||
393 e.affectsConfiguration("window.autoDetectHighContrast") ||
394 e.affectsConfiguration("workbench.preferredDarkColorTheme") ||
395 e.affectsConfiguration("workbench.preferredLightColorTheme") ||
396 e.affectsConfiguration("workbench.preferredHighContrastColorTheme") ||
397 e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme")
398 ) {
399 this.theme = getThemeString();
400 this.codeRenderer.setTheme(this.theme);
401 console.log(
402 "Theme updated:",
403 this.theme ? "Theme exists" : "Theme is undefined",
404 );
405 const editorConfig = vscode.workspace.getConfiguration("editor");
406 this.fontSize = editorConfig.get<number>("fontSize") ?? 14;
407 this.fontFamily = editorConfig.get<string>("fontFamily") ?? "monospace";
408 }
409 });
410
411 // Listen for active color theme changes.
412 vscode.window.onDidChangeActiveColorTheme(() => {
413 this.theme = getThemeString();
414 this.codeRenderer.setTheme(this.theme);
415 console.log(
416 "Active theme changed:",
417 this.theme ? "Theme exists" : "Theme is undefined",
418 );
419 });
420
421 // Listen for editor changes to clean up decorations when editor closes.
422 vscode.window.onDidChangeVisibleTextEditors(async () => {
423 // If our active editor is no longer visible, clear decorations.
424 if (
425 this.activeEditor &&
426 !vscode.window.visibleTextEditors.includes(this.activeEditor)
427 ) {
428 await this.hideAllNextEditWindows();
429 }
430 });
431
432 // Listen for selection changes to hide tooltip when cursor moves.
433 vscode.window.onDidChangeTextEditorSelection(async (e) => {
434 // If the selection changed in our active editor, hide the tooltip.
435 if (this.activeEditor && e.textEditor === this.activeEditor) {
436 await this.hideAllNextEditWindows();
437 }
438 });
439 }
440
441 private shouldRenderTip(uri: vscode.Uri): boolean {
442 const isAllowedUri =
443 !this.excludedURIPrefixes.some((prefix) =>
444 uri.toString().startsWith(prefix),
445 ) && uri.scheme !== "comment";
446
447 const isEnabled =
448 !!vscode.workspace
449 .getConfiguration(EXTENSION_NAME)
450 .get<boolean>("showInlineTip") === true;
451
452 return isAllowedUri && isEnabled;
453 }
454
455 /**
456 * Create a render of the given code, supporting multiple lines.
457 */
458 private async createCodeRender(
459 text: string,
460 ): Promise<
461 | { uri: vscode.Uri; dimensions: { width: number; height: number } }
462 | undefined
463 > {
464 try {
465 const tipWidth = SVG_CONFIG.getTipWidth(text);
466 const tipHeight = SVG_CONFIG.getTipHeight(text);
467 const dimensions = {
468 width: tipWidth,
469 height: tipHeight,
470 };
471
472 const uri = await this.codeRenderer.getDataUri(
473 text,
474 "typescript",
475 this.fontSize,
476 this.fontFamily,
477 dimensions,
478 SVG_CONFIG.lineHeight,
479 {
480 imageType: "svg",
481 },
482 );
483
484 return {
485 uri: vscode.Uri.parse(uri),
486 dimensions,
487 };
488 } catch (error) {
489 console.error("Error creating SVG tooltip:", error);
490 return undefined;
491 }
492 }
493
494 /**
495 * Create a decoration type with the code render.
496 * @param code: The code to render.
497 * @returns The decoration.
498 */
499 private async createCodeRenderDecoration(
500 code: string,
501 ): Promise<vscode.TextEditorDecorationType | undefined> {
502 const uriAndDimensions = await this.createCodeRender(code);
503 if (!uriAndDimensions) {
504 return undefined;
505 }
506
507 const { uri, dimensions } = uriAndDimensions;
508 const tipWidth = dimensions.width;
509 const tipHeight = dimensions.height;
510
511 return vscode.window.createTextEditorDecorationType({
512 after: {
513 contentIconPath: uri,
514 // border: `;box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px ${backgroundColour};
515 // border-radius: ${SVG_CONFIG.radius}px;
516 // filter: ${SVG_CONFIG.filter}`,
517 // width: `${tipWidth}px`,
518 // height: `${tipHeight}px`,
519 // border: `transparent; position: absolute; z-index: 1000;
520 // box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke},
521 // inset 0 0 0 ${tipHeight}px ${backgroundColour};
522 // border-radius: ${SVG_CONFIG.radius}px;
523 // filter: ${SVG_CONFIG.filter};
524 // margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`,
525 border: `transparent; position: absolute; z-index: 1000;
526 box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px;
527 filter: ${SVG_CONFIG.filter};
528 border-radius: ${SVG_CONFIG.radius}px;
529 margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`,
530 // border: `solid 1px white; position: absolute; z-index: 1000;
531 // margin-left: ${SVG_CONFIG.cursorOffset * 8}px;
532 // margin-top: 0em;`,
533 // border: `solid 1px white; position: absolute; z-index: 1000;
534 // margin: 0em; padding: 0em;
535 // margin-left: ${SVG_CONFIG.cursorOffset * 8}px;
536 // margin-top: 0em;`,
537 width: `${tipWidth}px`,
538 height: `${tipHeight}px`,
539 // textDecoration: `none; transform: translateY(-100%);`,
540 },
541 // Set a negative margin to make the decoration float if it starts to displace text.
542 // Also use absolute positioning.
543 rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed,
544 });
545 }
546
547 private buildHideTooltipHoverMsg() {
548 const hoverMarkdown = new vscode.MarkdownString(
549 `[Reject (Esc)](command:${HIDE_NEXT_EDIT_SUGGESTION_COMMAND}) | [Accept (Tab)](command:${ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND})`,
550 );
551
552 hoverMarkdown.isTrusted = true;
553 hoverMarkdown.supportHtml = true;
554 return hoverMarkdown;
555 }
556
557 private isValidRange(
558 editor: vscode.TextEditor,
559 range: vscode.Range,
560 ): boolean {
561 const doc = editor.document;
562
563 // Check if line numbers are valid.
564 if (range.start.line < 0 || range.start.line >= doc.lineCount) {
565 console.log(
566 "Invalid start line:",
567 range.start.line,
568 "doc lines:",
569 doc.lineCount,
570 );
571 return false;
572 }
573
574 if (range.end.line < 0 || range.end.line >= doc.lineCount) {
575 console.log(
576 "Invalid end line:",
577 range.end.line,
578 "doc lines:",
579 doc.lineCount,
580 );
581 return false;
582 }
583
584 // Check if character positions are valid.
585 const startLine = doc.lineAt(range.start.line);
586 const endLine = doc.lineAt(range.end.line);
587
588 if (
589 range.start.character < 0 ||
590 range.start.character > startLine.text.length
591 ) {
592 console.log(
593 "Invalid start character:",
594 range.start.character,
595 "line length:",
596 startLine.text.length,
597 );
598 return false;
599 }
600
601 if (range.end.character < 0 || range.end.character > endLine.text.length) {
602 console.log(
603 "Invalid end character:",
604 range.end.character,
605 "line length:",
606 endLine.text.length,
607 );
608 return false;
609 }
610
611 return true;
612 }
613
614 /**
615 * Calculate a position to the right of the cursor with the specified offset.
616 */
617 private getDecorationOffsetPosition(
618 editor: vscode.TextEditor,
619 position: vscode.Position,
620 ): vscode.Position {
621 // Create a position that's offset spaces to the right of the cursor.
622
623 const line = editor.document.lineAt(position.line);
624 const offsetChar = Math.min(
625 position.character + SVG_CONFIG.cursorOffset,
626 line.text.length,
627 );
628 return new vscode.Position(position.line, offsetChar);
629 }
630
631 /**
632 * Render a tooltip with the given text at the specified position.
633 */
634 private async renderTooltip(
635 editor: vscode.TextEditor,
636 position: vscode.Position,
637 text: string,
638 ) {
639 console.log("renderTooltip");
640 // Capture document version to detect changes.
641 const docVersion = editor.document.version;
642
643 // Create a new decoration with the text.
644 const decoration = await this.createCodeRenderDecoration(text);
645 if (!decoration) {
646 console.error("Failed to create decoration for text:", text);
647 return;
648 }
649
650 // Check if document changed during async operation.
651 if (editor.document.version !== docVersion) {
652 console.log("Document changed during decoration creation, aborting");
653 decoration.dispose();
654 return;
655 }
656
657 // Store the decoration and editor.
658 await this.hideAllNextEditWindows();
659 this.currentDecoration = decoration;
660 this.activeEditor = editor;
661
662 // Calculate how far off to the right of the cursor the decoration should be.
663 const decorationOffsetPosition = this.getDecorationOffsetPosition(
664 editor,
665 position,
666 );
667 const range = new vscode.Range(
668 decorationOffsetPosition,
669 decorationOffsetPosition,
670 );
671
672 // Validate the range before applying.
673 if (!this.isValidRange(editor, range)) {
674 console.error("Invalid range detected, skipping decoration");
675 return;
676 }
677
678 // Apply the decoration at the calculated position.
679 editor.setDecorations(this.currentDecoration, [
680 {
681 range: new vscode.Range(
682 decorationOffsetPosition,
683 decorationOffsetPosition,
684 ),
685 hoverMessage: [this.buildHideTooltipHoverMsg()],
686 },
687 ]);
688 }
689}
690
691export default async function setupNextEditWindowManager(
692 context: vscode.ExtensionContext,
693 textApplier?: TextApplier,
694) {
695 await NextEditWindowManager.getInstance().setupNextEditWindowManager(
696 context,
697 textApplier,
698 );
699}