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