| 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 { CodeRenderer } from "core/codeRenderer/CodeRenderer"; |
| 7 | import { myersDiff } from "core/diff/myers"; |
| 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 { getThemeString } from "../util/getTheme"; |
| 14 | |
| 15 | export 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 | |
| 24 | const 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 |
| 76 | export const HIDE_NEXT_EDIT_SUGGESTION_COMMAND = |
| 77 | "continue.nextEditWindow.hideNextEditSuggestion"; |
| 78 | export const ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND = |
| 79 | "continue.nextEditWindow.acceptNextEditSuggestion"; |
| 80 | |
| 81 | export 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 | newEditRangeSlice: string, |
| 229 | ) { |
| 230 | if (!newEditRangeSlice || !this.shouldRenderTip(editor.document.uri)) { |
| 231 | return; |
| 232 | } |
| 233 | |
| 234 | // Clear any existing decorations first (very important to prevent overlapping). |
| 235 | await this.hideAllNextEditWindows(); |
| 236 | |
| 237 | // Store the current tooltip text for accepting later. |
| 238 | this.currentTooltipText = newEditRangeSlice; |
| 239 | |
| 240 | // Get the contents of the old (current) editable region. |
| 241 | const currCursorPos = editor.selection.active; |
| 242 | const editableRegionStartLine = Math.max( |
| 243 | currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, |
| 244 | 0, |
| 245 | ); |
| 246 | const editableRegionEndLine = Math.min( |
| 247 | currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, |
| 248 | editor.document.lineCount - 1, |
| 249 | ); |
| 250 | const oldEditRangeSlice = editor.document |
| 251 | .getText() |
| 252 | .split("\n") |
| 253 | .slice(editableRegionStartLine, editableRegionEndLine + 1) |
| 254 | .join("\n"); |
| 255 | |
| 256 | // We don't need to show the next edit window under these conditions: |
| 257 | // - There are no predicted edits. |
| 258 | // - The predicted edits are identical to the previous version. |
| 259 | if (newEditRangeSlice === "" || oldEditRangeSlice === newEditRangeSlice) |
| 260 | return; |
| 261 | |
| 262 | const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); |
| 263 | |
| 264 | // How far away is the current line from the start of the editable region? |
| 265 | const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine; |
| 266 | |
| 267 | // How long is the line at the current cursor position? |
| 268 | const lineContentAtCursorPos = |
| 269 | newEditRangeSlice.split("\n")[lineOffsetAtCursorPos]; |
| 270 | |
| 271 | const offset = getOffsetPositionAtLastNewLine( |
| 272 | diffLines, |
| 273 | lineContentAtCursorPos, |
| 274 | lineOffsetAtCursorPos, |
| 275 | ); |
| 276 | |
| 277 | // Calculate the actual line number in the editor by adding the startPos offset |
| 278 | // to the line number from the diff calculation. |
| 279 | this.finalCursorPos = new vscode.Position( |
| 280 | editableRegionStartLine + offset.line, |
| 281 | offset.character, |
| 282 | ); |
| 283 | |
| 284 | // Create and apply decoration with the text. |
| 285 | await this.renderTooltip(editor, currCursorPos, newEditRangeSlice); |
| 286 | |
| 287 | // Reserve tab and esc to either accept or reject the displayed next edit contents. |
| 288 | await NextEditWindowManager.reserveTabAndEsc(); |
| 289 | } |
| 290 | |
| 291 | /** |
| 292 | * Hide all tooltips in all editors. |
| 293 | */ |
| 294 | public async hideAllNextEditWindows() { |
| 295 | if (this.currentDecoration) { |
| 296 | vscode.window.visibleTextEditors.forEach((editor) => { |
| 297 | editor.setDecorations(this.currentDecoration!, []); |
| 298 | }); |
| 299 | |
| 300 | // If we know which editor had the decoration, clear it specifically. |
| 301 | // This is a bit redundant but ensures we don't leave any decorations behind. |
| 302 | if (this.activeEditor) { |
| 303 | this.activeEditor.setDecorations(this.currentDecoration, []); |
| 304 | this.activeEditor = null; |
| 305 | } |
| 306 | |
| 307 | // This prevents memory leaks. |
| 308 | this.currentDecoration.dispose(); |
| 309 | this.currentDecoration = null; |
| 310 | |
| 311 | this.disposables.forEach((d) => d.dispose()); |
| 312 | this.disposables = []; |
| 313 | |
| 314 | // Clear the current tooltip text. |
| 315 | this.currentTooltipText = null; |
| 316 | } |
| 317 | |
| 318 | await NextEditWindowManager.freeTabAndEsc(); |
| 319 | } |
| 320 | |
| 321 | /** |
| 322 | * Accept the current next edit suggestion by inserting it at cursor position. |
| 323 | */ |
| 324 | private async acceptNextEdit() { |
| 325 | if (!this.activeEditor || !this.currentTooltipText) { |
| 326 | return; |
| 327 | } |
| 328 | |
| 329 | const editor = this.activeEditor; |
| 330 | const text = this.currentTooltipText; |
| 331 | const position = editor.selection.active; |
| 332 | |
| 333 | let success = false; |
| 334 | if (this.textApplier) { |
| 335 | success = await this.textApplier.applyText( |
| 336 | editor, |
| 337 | text, |
| 338 | position, |
| 339 | this.finalCursorPos, |
| 340 | ); |
| 341 | } else { |
| 342 | // Define the editable region. |
| 343 | const editableRegionStartLine = Math.max( |
| 344 | 0, |
| 345 | position.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, |
| 346 | ); |
| 347 | const editableRegionEndLine = Math.min( |
| 348 | editor.document.lineCount - 1, |
| 349 | position.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, |
| 350 | ); |
| 351 | const startPos = new vscode.Position(editableRegionStartLine, 0); |
| 352 | const endPosChar = editor.document.lineAt(editableRegionEndLine).text |
| 353 | .length; |
| 354 | |
| 355 | const endPos = new vscode.Position(editableRegionEndLine, endPosChar); |
| 356 | const editRange = new vscode.Range(startPos, endPos); |
| 357 | |
| 358 | success = await editor.edit((editBuilder) => { |
| 359 | editBuilder.replace(editRange, text); |
| 360 | }); |
| 361 | |
| 362 | // Disable inline suggestions temporarily. |
| 363 | // This prevents the race condition between vscode's inline completion provider |
| 364 | // and the next edit window manager's cursor repositioning logic. |
| 365 | await vscode.workspace |
| 366 | .getConfiguration() |
| 367 | .update("editor.inlineSuggest.enabled", false, true); |
| 368 | } |
| 369 | |
| 370 | if (success) { |
| 371 | // Move cursor to the final position if available. |
| 372 | if (this.finalCursorPos) { |
| 373 | editor.selection = new vscode.Selection( |
| 374 | this.finalCursorPos, |
| 375 | this.finalCursorPos, |
| 376 | ); |
| 377 | |
| 378 | // Reenable inline suggestions after we move the cursor. |
| 379 | await vscode.workspace |
| 380 | .getConfiguration() |
| 381 | .update("editor.inlineSuggest.enabled", true, true); |
| 382 | |
| 383 | await this.hideAllNextEditWindows(); |
| 384 | } |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | /** |
| 389 | * Dispose of the NextEditWindowManager. |
| 390 | */ |
| 391 | public dispose() { |
| 392 | // Dispose current decoration. |
| 393 | if (this.currentDecoration) { |
| 394 | this.currentDecoration.dispose(); |
| 395 | this.currentDecoration = null; |
| 396 | } |
| 397 | |
| 398 | // Dispose all other disposables. |
| 399 | this.disposables.forEach((d) => d.dispose()); |
| 400 | this.disposables = []; |
| 401 | } |
| 402 | |
| 403 | /** |
| 404 | * Setup listeners for theme, font, and cursor position changes. |
| 405 | */ |
| 406 | private setupListeners() { |
| 407 | // Theme change listener. |
| 408 | vscode.workspace.onDidChangeConfiguration((e) => { |
| 409 | if ( |
| 410 | e.affectsConfiguration("workbench.colorTheme") || |
| 411 | e.affectsConfiguration("editor.fontSize") || |
| 412 | e.affectsConfiguration("editor.fontFamily") || |
| 413 | e.affectsConfiguration("window.autoDetectColorScheme") || |
| 414 | e.affectsConfiguration("window.autoDetectHighContrast") || |
| 415 | e.affectsConfiguration("workbench.preferredDarkColorTheme") || |
| 416 | e.affectsConfiguration("workbench.preferredLightColorTheme") || |
| 417 | e.affectsConfiguration("workbench.preferredHighContrastColorTheme") || |
| 418 | e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme") |
| 419 | ) { |
| 420 | this.theme = getThemeString(); |
| 421 | this.codeRenderer.setTheme(this.theme); |
| 422 | console.log( |
| 423 | "Theme updated:", |
| 424 | this.theme ? "Theme exists" : "Theme is undefined", |
| 425 | ); |
| 426 | const editorConfig = vscode.workspace.getConfiguration("editor"); |
| 427 | this.fontSize = editorConfig.get<number>("fontSize") ?? 14; |
| 428 | this.fontFamily = editorConfig.get<string>("fontFamily") ?? "monospace"; |
| 429 | } |
| 430 | }); |
| 431 | |
| 432 | // Listen for active color theme changes. |
| 433 | vscode.window.onDidChangeActiveColorTheme(() => { |
| 434 | this.theme = getThemeString(); |
| 435 | this.codeRenderer.setTheme(this.theme); |
| 436 | console.log( |
| 437 | "Active theme changed:", |
| 438 | this.theme ? "Theme exists" : "Theme is undefined", |
| 439 | ); |
| 440 | }); |
| 441 | |
| 442 | // Listen for editor changes to clean up decorations when editor closes. |
| 443 | vscode.window.onDidChangeVisibleTextEditors(async () => { |
| 444 | // If our active editor is no longer visible, clear decorations. |
| 445 | if ( |
| 446 | this.activeEditor && |
| 447 | !vscode.window.visibleTextEditors.includes(this.activeEditor) |
| 448 | ) { |
| 449 | await this.hideAllNextEditWindows(); |
| 450 | } |
| 451 | }); |
| 452 | |
| 453 | // Listen for selection changes to hide tooltip when cursor moves. |
| 454 | vscode.window.onDidChangeTextEditorSelection(async (e) => { |
| 455 | // If the selection changed in our active editor, hide the tooltip. |
| 456 | if (this.activeEditor && e.textEditor === this.activeEditor) { |
| 457 | await this.hideAllNextEditWindows(); |
| 458 | } |
| 459 | }); |
| 460 | } |
| 461 | |
| 462 | private shouldRenderTip(uri: vscode.Uri): boolean { |
| 463 | const isAllowedUri = |
| 464 | !this.excludedURIPrefixes.some((prefix) => |
| 465 | uri.toString().startsWith(prefix), |
| 466 | ) && uri.scheme !== "comment"; |
| 467 | |
| 468 | const isEnabled = |
| 469 | !!vscode.workspace |
| 470 | .getConfiguration(EXTENSION_NAME) |
| 471 | .get<boolean>("showInlineTip") === true; |
| 472 | |
| 473 | return isAllowedUri && isEnabled; |
| 474 | } |
| 475 | |
| 476 | /** |
| 477 | * Create a render of the given code, supporting multiple lines. |
| 478 | */ |
| 479 | private async createCodeRender( |
| 480 | text: string, |
| 481 | ): Promise< |
| 482 | | { uri: vscode.Uri; dimensions: { width: number; height: number } } |
| 483 | | undefined |
| 484 | > { |
| 485 | try { |
| 486 | const tipWidth = SVG_CONFIG.getTipWidth(text); |
| 487 | const tipHeight = SVG_CONFIG.getTipHeight(text); |
| 488 | const dimensions = { |
| 489 | width: tipWidth, |
| 490 | height: tipHeight, |
| 491 | }; |
| 492 | |
| 493 | const uri = await this.codeRenderer.getDataUri( |
| 494 | text, |
| 495 | "typescript", |
| 496 | this.fontSize, |
| 497 | this.fontFamily, |
| 498 | dimensions, |
| 499 | SVG_CONFIG.lineHeight, |
| 500 | { |
| 501 | imageType: "svg", |
| 502 | }, |
| 503 | ); |
| 504 | |
| 505 | return { |
| 506 | uri: vscode.Uri.parse(uri), |
| 507 | dimensions, |
| 508 | }; |
| 509 | } catch (error) { |
| 510 | console.error("Error creating SVG tooltip:", error); |
| 511 | return undefined; |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | /** |
| 516 | * Create a decoration type with the code render. |
| 517 | * @param code: The code to render. |
| 518 | * @returns The decoration. |
| 519 | */ |
| 520 | private async createCodeRenderDecoration( |
| 521 | code: string, |
| 522 | ): Promise<vscode.TextEditorDecorationType | undefined> { |
| 523 | const uriAndDimensions = await this.createCodeRender(code); |
| 524 | if (!uriAndDimensions) { |
| 525 | return undefined; |
| 526 | } |
| 527 | |
| 528 | const { uri, dimensions } = uriAndDimensions; |
| 529 | const tipWidth = dimensions.width; |
| 530 | const tipHeight = dimensions.height; |
| 531 | |
| 532 | return vscode.window.createTextEditorDecorationType({ |
| 533 | after: { |
| 534 | contentIconPath: uri, |
| 535 | // border: `;box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px ${backgroundColour}; |
| 536 | // border-radius: ${SVG_CONFIG.radius}px; |
| 537 | // filter: ${SVG_CONFIG.filter}`, |
| 538 | // width: `${tipWidth}px`, |
| 539 | // height: `${tipHeight}px`, |
| 540 | // border: `transparent; position: absolute; z-index: 1000; |
| 541 | // box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, |
| 542 | // inset 0 0 0 ${tipHeight}px ${backgroundColour}; |
| 543 | // border-radius: ${SVG_CONFIG.radius}px; |
| 544 | // filter: ${SVG_CONFIG.filter}; |
| 545 | // margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`, |
| 546 | border: `transparent; position: absolute; z-index: 1000; |
| 547 | box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px; |
| 548 | filter: ${SVG_CONFIG.filter}; |
| 549 | border-radius: ${SVG_CONFIG.radius}px; |
| 550 | margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`, |
| 551 | // border: `solid 1px white; position: absolute; z-index: 1000; |
| 552 | // margin-left: ${SVG_CONFIG.cursorOffset * 8}px; |
| 553 | // margin-top: 0em;`, |
| 554 | // border: `solid 1px white; position: absolute; z-index: 1000; |
| 555 | // margin: 0em; padding: 0em; |
| 556 | // margin-left: ${SVG_CONFIG.cursorOffset * 8}px; |
| 557 | // margin-top: 0em;`, |
| 558 | width: `${tipWidth}px`, |
| 559 | height: `${tipHeight}px`, |
| 560 | // textDecoration: `none; transform: translateY(-100%);`, |
| 561 | }, |
| 562 | // Set a negative margin to make the decoration float if it starts to displace text. |
| 563 | // Also use absolute positioning. |
| 564 | rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed, |
| 565 | }); |
| 566 | } |
| 567 | |
| 568 | private buildHideTooltipHoverMsg() { |
| 569 | const hoverMarkdown = new vscode.MarkdownString( |
| 570 | `[Reject (Esc)](command:${HIDE_NEXT_EDIT_SUGGESTION_COMMAND}) | [Accept (Tab)](command:${ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND})`, |
| 571 | ); |
| 572 | |
| 573 | hoverMarkdown.isTrusted = true; |
| 574 | hoverMarkdown.supportHtml = true; |
| 575 | return hoverMarkdown; |
| 576 | } |
| 577 | |
| 578 | private isValidRange( |
| 579 | editor: vscode.TextEditor, |
| 580 | range: vscode.Range, |
| 581 | ): boolean { |
| 582 | const doc = editor.document; |
| 583 | |
| 584 | // Check if line numbers are valid. |
| 585 | if (range.start.line < 0 || range.start.line >= doc.lineCount) { |
| 586 | console.log( |
| 587 | "Invalid start line:", |
| 588 | range.start.line, |
| 589 | "doc lines:", |
| 590 | doc.lineCount, |
| 591 | ); |
| 592 | return false; |
| 593 | } |
| 594 | |
| 595 | if (range.end.line < 0 || range.end.line >= doc.lineCount) { |
| 596 | console.log( |
| 597 | "Invalid end line:", |
| 598 | range.end.line, |
| 599 | "doc lines:", |
| 600 | doc.lineCount, |
| 601 | ); |
| 602 | return false; |
| 603 | } |
| 604 | |
| 605 | // Check if character positions are valid. |
| 606 | const startLine = doc.lineAt(range.start.line); |
| 607 | const endLine = doc.lineAt(range.end.line); |
| 608 | |
| 609 | if ( |
| 610 | range.start.character < 0 || |
| 611 | range.start.character > startLine.text.length |
| 612 | ) { |
| 613 | console.log( |
| 614 | "Invalid start character:", |
| 615 | range.start.character, |
| 616 | "line length:", |
| 617 | startLine.text.length, |
| 618 | ); |
| 619 | return false; |
| 620 | } |
| 621 | |
| 622 | if (range.end.character < 0 || range.end.character > endLine.text.length) { |
| 623 | console.log( |
| 624 | "Invalid end character:", |
| 625 | range.end.character, |
| 626 | "line length:", |
| 627 | endLine.text.length, |
| 628 | ); |
| 629 | return false; |
| 630 | } |
| 631 | |
| 632 | return true; |
| 633 | } |
| 634 | |
| 635 | /** |
| 636 | * Calculate a position to the right of the cursor with the specified offset. |
| 637 | */ |
| 638 | private getDecorationOffsetPosition( |
| 639 | editor: vscode.TextEditor, |
| 640 | position: vscode.Position, |
| 641 | ): vscode.Position { |
| 642 | // Create a position that's offset spaces to the right of the cursor. |
| 643 | |
| 644 | const line = editor.document.lineAt(position.line); |
| 645 | const offsetChar = Math.min( |
| 646 | position.character + SVG_CONFIG.cursorOffset, |
| 647 | line.text.length, |
| 648 | ); |
| 649 | return new vscode.Position(position.line, offsetChar); |
| 650 | } |
| 651 | |
| 652 | /** |
| 653 | * Render a tooltip with the given text at the specified position. |
| 654 | */ |
| 655 | private async renderTooltip( |
| 656 | editor: vscode.TextEditor, |
| 657 | position: vscode.Position, |
| 658 | text: string, |
| 659 | ) { |
| 660 | console.log("renderTooltip"); |
| 661 | // Capture document version to detect changes. |
| 662 | const docVersion = editor.document.version; |
| 663 | |
| 664 | // Create a new decoration with the text. |
| 665 | const decoration = await this.createCodeRenderDecoration(text); |
| 666 | if (!decoration) { |
| 667 | console.error("Failed to create decoration for text:", text); |
| 668 | return; |
| 669 | } |
| 670 | |
| 671 | // Check if document changed during async operation. |
| 672 | if (editor.document.version !== docVersion) { |
| 673 | console.log("Document changed during decoration creation, aborting"); |
| 674 | decoration.dispose(); |
| 675 | return; |
| 676 | } |
| 677 | |
| 678 | // Store the decoration and editor. |
| 679 | await this.hideAllNextEditWindows(); |
| 680 | this.currentDecoration = decoration; |
| 681 | this.activeEditor = editor; |
| 682 | |
| 683 | // Calculate how far off to the right of the cursor the decoration should be. |
| 684 | const decorationOffsetPosition = this.getDecorationOffsetPosition( |
| 685 | editor, |
| 686 | position, |
| 687 | ); |
| 688 | const range = new vscode.Range( |
| 689 | decorationOffsetPosition, |
| 690 | decorationOffsetPosition, |
| 691 | ); |
| 692 | |
| 693 | // Validate the range before applying. |
| 694 | if (!this.isValidRange(editor, range)) { |
| 695 | console.error("Invalid range detected, skipping decoration"); |
| 696 | return; |
| 697 | } |
| 698 | |
| 699 | // Apply the decoration at the calculated position. |
| 700 | editor.setDecorations(this.currentDecoration, [ |
| 701 | { |
| 702 | range: new vscode.Range( |
| 703 | decorationOffsetPosition, |
| 704 | decorationOffsetPosition, |
| 705 | ), |
| 706 | hoverMessage: [this.buildHideTooltipHoverMsg()], |
| 707 | }, |
| 708 | ]); |
| 709 | } |
| 710 | } |
| 711 | |
| 712 | export default async function setupNextEditWindowManager( |
| 713 | context: vscode.ExtensionContext, |
| 714 | textApplier?: TextApplier, |
| 715 | ) { |
| 716 | await NextEditWindowManager.getInstance().setupNextEditWindowManager( |
| 717 | context, |
| 718 | textApplier, |
| 719 | ); |
| 720 | } |