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