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