| 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 { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff"; |
| 10 | import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; |
| 11 | import { NextEditProvider } from "core/nextEdit/NextEditProvider"; |
| 12 | import { getThemeString } from "../util/getTheme"; |
| 13 | import { |
| 14 | HandlerPriority, |
| 15 | SelectionChangeManager, |
| 16 | } from "./SelectionChangeManager"; |
| 17 | |
| 18 | export interface TextApplier { |
| 19 | applyText( |
| 20 | editor: vscode.TextEditor, |
| 21 | text: string, |
| 22 | position: vscode.Position, |
| 23 | finalCursorPos: vscode.Position | null, |
| 24 | ): Promise<boolean>; |
| 25 | } |
| 26 | |
| 27 | const SVG_CONFIG = { |
| 28 | // stroke: "#999998", |
| 29 | stroke: "#666667", |
| 30 | strokeWidth: 1, |
| 31 | textColor: "#999998", |
| 32 | purple: "rgba(112, 114, 209)", |
| 33 | blue: "rgba(107, 166, 205)", |
| 34 | green: "rgba(136 194 163)", |
| 35 | // filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))", |
| 36 | // filter: "drop-shadow(0 2px 2px rgba(255,255,255,0.2))", |
| 37 | // filter: |
| 38 | // "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));", |
| 39 | // filter: |
| 40 | // "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));", |
| 41 | // filter: `drop-shadow(4px 4px 0px rgba(112, 114, 209, 0.4)) |
| 42 | // drop-shadow(8px 8px 0px rgba(107, 166, 205, 0.3)) |
| 43 | // drop-shadow(12px 12px 0px rgba(136, 194, 163, 0.2));`, |
| 44 | // filter: `drop-shadow(4px 4px 0px rgba(112, 114, 209, 0.4)) |
| 45 | // drop-shadow(-2px 4px 0px rgba(107, 166, 205, 0.3)) |
| 46 | // drop-shadow(4px -2px 0px rgba(136, 194, 163, 0.2)) |
| 47 | // drop-shadow(-2px -2px 0px rgba(112, 114, 209, 0.2));`, |
| 48 | filter: "none", |
| 49 | radius: 3, |
| 50 | leftMargin: 40, |
| 51 | defaultText: "", |
| 52 | lineSpacing: 1.3, // Line spacing multiplier |
| 53 | cursorOffset: 4, // Spaces to offset from cursor |
| 54 | |
| 55 | get fontSize() { |
| 56 | return Math.ceil( |
| 57 | vscode.workspace.getConfiguration("editor").get<number>("fontSize") ?? 14, |
| 58 | ); |
| 59 | }, |
| 60 | get fontFamily() { |
| 61 | return ( |
| 62 | vscode.workspace.getConfiguration("editor").get<string>("fontFamily") || |
| 63 | "helvetica" |
| 64 | ); |
| 65 | }, |
| 66 | get paddingX() { |
| 67 | return Math.ceil(this.getEstimatedTextWidth(" ")); |
| 68 | }, |
| 69 | get paddingY() { |
| 70 | return Math.ceil(this.fontSize * 0.3); |
| 71 | }, |
| 72 | get lineHeight() { |
| 73 | return Math.ceil(this.fontSize * this.lineSpacing); |
| 74 | }, |
| 75 | getEstimatedTextWidth(text: string): number { |
| 76 | return text.length * this.fontSize * 0.6; |
| 77 | }, |
| 78 | getTipWidth(text: string): number { |
| 79 | // Find the longest line |
| 80 | const lines = text.split("\n"); |
| 81 | const longestLine = lines.reduce( |
| 82 | (longest, line) => (line.length > longest.length ? line : longest), |
| 83 | "", |
| 84 | ); |
| 85 | |
| 86 | return this.getEstimatedTextWidth(longestLine) + this.paddingX * 2; |
| 87 | }, |
| 88 | getTipHeight(text: string): number { |
| 89 | // Count the number of lines |
| 90 | const lineCount = text.split("\n").length; |
| 91 | return this.lineHeight * lineCount + this.paddingY * 2; |
| 92 | }, |
| 93 | } as const; |
| 94 | |
| 95 | // Command ID - can be used in package.json |
| 96 | export const HIDE_NEXT_EDIT_SUGGESTION_COMMAND = |
| 97 | "continue.nextEditWindow.hideNextEditSuggestion"; |
| 98 | export const ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND = |
| 99 | "continue.nextEditWindow.acceptNextEditSuggestion"; |
| 100 | |
| 101 | /** |
| 102 | * This is where we create SVG windows and deletion decorations for non-FIM next edit suggestions. |
| 103 | * This class controls the decoration object lifetime. |
| 104 | * The syntax highlighting and the actual building of SVG happens inside core/codeRenderer/CodeRenderer.ts. |
| 105 | */ |
| 106 | export class NextEditWindowManager { |
| 107 | private static instance: NextEditWindowManager | undefined; |
| 108 | |
| 109 | private readonly excludedURIPrefixes = ["output:", "vscode://inline-chat"]; |
| 110 | private theme: string; |
| 111 | private fontSize: number; |
| 112 | private fontFamily: string; |
| 113 | private codeRenderer: CodeRenderer; |
| 114 | |
| 115 | // Current active decoration |
| 116 | private currentDecoration: vscode.TextEditorDecorationType | null = null; |
| 117 | // A short-lived checker to determine if the cursor moved because of us accepting the next edit, or not. |
| 118 | // Distinguishing the two is necessary to determine if we should log it as an accepted or rejected. |
| 119 | private accepted: boolean = false; |
| 120 | // Track which editor has the active decoration |
| 121 | private activeEditor: vscode.TextEditor | null = null; |
| 122 | // Store the current tooltip text for accepting |
| 123 | private currentTooltipText: string | null = null; |
| 124 | // Track for logging purposes. |
| 125 | private loggingService: NextEditLoggingService; |
| 126 | private mostRecentCompletionId: string | null = null; |
| 127 | // Helps us skip redundant calculations. No need for cleanup because this always gets reassigned with new values at showNextEditWindow, and we don't reuse windows. |
| 128 | private editableRegionStartLine: number = 0; |
| 129 | private editableRegionEndLine: number = 0; |
| 130 | |
| 131 | // State tracking for key reservation. |
| 132 | // By default it is set to free, and is only set to reserved when the transition is done. |
| 133 | private keyReservationState: "free" | "reserved" | "transitioning" = "free"; |
| 134 | private latestOperationId = 0; |
| 135 | |
| 136 | // Disposables |
| 137 | private disposables: vscode.Disposable[] = []; |
| 138 | |
| 139 | private textApplier: TextApplier | null = null; |
| 140 | |
| 141 | private finalCursorPos: vscode.Position | null = null; |
| 142 | |
| 143 | private isLineDelete: boolean = false; |
| 144 | |
| 145 | private context: vscode.ExtensionContext | null = null; |
| 146 | |
| 147 | public static getInstance(): NextEditWindowManager { |
| 148 | if (!NextEditWindowManager.instance) { |
| 149 | NextEditWindowManager.instance = new NextEditWindowManager(); |
| 150 | } |
| 151 | return NextEditWindowManager.instance; |
| 152 | } |
| 153 | |
| 154 | public static isInstantiated(): boolean { |
| 155 | return !!NextEditWindowManager.instance; |
| 156 | } |
| 157 | |
| 158 | public static clearInstance(): void { |
| 159 | if (NextEditWindowManager.instance) { |
| 160 | NextEditWindowManager.instance.dispose(); |
| 161 | NextEditWindowManager.instance = undefined; |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | private constructor() { |
| 166 | this.theme = getThemeString(); |
| 167 | |
| 168 | console.log( |
| 169 | "Next Edit Theme initialized:", |
| 170 | this.theme |
| 171 | ? `Theme exists: ${JSON.stringify(this.theme)}` |
| 172 | : "Theme is undefined", |
| 173 | ); |
| 174 | this.setupListeners(); |
| 175 | this.codeRenderer = CodeRenderer.getInstance(); |
| 176 | |
| 177 | const editorConfig = vscode.workspace.getConfiguration("editor"); |
| 178 | this.fontSize = editorConfig.get<number>("fontSize") ?? 14; |
| 179 | this.fontFamily = editorConfig.get<string>("fontFamily") ?? "monospace"; |
| 180 | |
| 181 | this.loggingService = NextEditLoggingService.getInstance(); |
| 182 | } |
| 183 | |
| 184 | // This is an implementation of last-action-wins. |
| 185 | // For each action that fires setKeyReservation, it keeps its own operationId while incrementing latestOperationId. |
| 186 | // When an action completes, checking for operationId === latestOperationId will determine which one came last. |
| 187 | private async setKeyReservation(reserve: boolean): Promise<void> { |
| 188 | // Increment and capture this operation's ID. |
| 189 | const operationId = ++this.latestOperationId; |
| 190 | |
| 191 | // Return early when already in desired state. |
| 192 | if ( |
| 193 | (reserve && this.keyReservationState === "reserved") || |
| 194 | (!reserve && this.keyReservationState === "free") |
| 195 | ) { |
| 196 | return; |
| 197 | } |
| 198 | |
| 199 | try { |
| 200 | await this.performKeyReservation(reserve); |
| 201 | |
| 202 | // Only update state if we're still the latest operation. |
| 203 | if (operationId === this.latestOperationId) { |
| 204 | this.keyReservationState = reserve ? "reserved" : "free"; |
| 205 | } |
| 206 | } catch (err) { |
| 207 | console.error(`Failed to set nextEditWindowActive to ${reserve}: ${err}`); |
| 208 | |
| 209 | // Only reset to free if we're still the latest operation. |
| 210 | if (operationId === this.latestOperationId) { |
| 211 | this.keyReservationState = "free"; |
| 212 | } |
| 213 | throw err; |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | public async resetKeyReservation(): Promise<void> { |
| 218 | // Reset internal tracking. |
| 219 | this.keyReservationState = "free"; |
| 220 | this.latestOperationId = 0; |
| 221 | |
| 222 | // Ensure VS Code context matches. |
| 223 | try { |
| 224 | await this.performKeyReservation(false); |
| 225 | } catch (err) { |
| 226 | console.error(`Failed to reset nextEditWindowActive context: ${err}`); |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | private async performKeyReservation(reserve: boolean): Promise<void> { |
| 231 | try { |
| 232 | await vscode.commands.executeCommand( |
| 233 | "setContext", |
| 234 | "nextEditWindowActive", |
| 235 | reserve, |
| 236 | ); |
| 237 | } catch (err) { |
| 238 | console.error(`Failed to set nextEditWindowActive to ${reserve}: ${err}`); |
| 239 | throw err; |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | public static async reserveTabAndEsc() { |
| 244 | await NextEditWindowManager.getInstance().setKeyReservation(true); |
| 245 | } |
| 246 | |
| 247 | public static async freeTabAndEsc() { |
| 248 | await NextEditWindowManager.getInstance().setKeyReservation(false); |
| 249 | } |
| 250 | |
| 251 | /** |
| 252 | * An async setup function to help us initialize the NextEditWindowManager. |
| 253 | * This is necessary because we need some setup to be done asynchronously, |
| 254 | * and constructors in TypeScript cannot be async. |
| 255 | * Plus, it's generally not recommended to pass arguments to getInstance() of a singleton. |
| 256 | * @param context The extension context. |
| 257 | * @param textApplier Callback that lets us use external deps such as llms if needed. |
| 258 | */ |
| 259 | public async setupNextEditWindowManager( |
| 260 | context: vscode.ExtensionContext, |
| 261 | textApplier?: TextApplier, |
| 262 | ) { |
| 263 | this.context = context; |
| 264 | |
| 265 | // Set nextEditWindowActive to false to free esc and tab, |
| 266 | // letting them return to their original behaviors. |
| 267 | await this.resetKeyReservation(); |
| 268 | // await NextEditWindowManager.freeTabAndEsc(); |
| 269 | |
| 270 | // Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks. |
| 271 | this.registerCommandSafely(HIDE_NEXT_EDIT_SUGGESTION_COMMAND, async () => { |
| 272 | console.log( |
| 273 | "deleteChain from NextEditWindowManager.ts: hide next edit command", |
| 274 | ); |
| 275 | NextEditProvider.getInstance().deleteChain(); |
| 276 | await this.hideAllNextEditWindowsAndResetCompletionId(); |
| 277 | }); |
| 278 | this.registerCommandSafely( |
| 279 | ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND, |
| 280 | async () => await this.acceptNextEdit(), |
| 281 | ); |
| 282 | |
| 283 | // Add this class to context disposables. |
| 284 | context.subscriptions.push(this); |
| 285 | |
| 286 | if (textApplier) { |
| 287 | this.textApplier = textApplier; |
| 288 | } |
| 289 | |
| 290 | await this.codeRenderer.setTheme(this.theme); |
| 291 | } |
| 292 | |
| 293 | /** |
| 294 | * Update the most recent completion id. |
| 295 | * @param completionId The id of current completion request. |
| 296 | */ |
| 297 | public updateCurrentCompletionId(completionId: string) { |
| 298 | this.mostRecentCompletionId = completionId; |
| 299 | } |
| 300 | |
| 301 | /** |
| 302 | * Registers our two custom commands to the extension context. |
| 303 | * @param commandId Custom commands to help set up next edit. |
| 304 | * @param callback Function to run on command execution. |
| 305 | */ |
| 306 | private registerCommandSafely( |
| 307 | commandId: |
| 308 | | "continue.nextEditWindow.hideNextEditSuggestion" |
| 309 | | "continue.nextEditWindow.acceptNextEditSuggestion", |
| 310 | callback: () => Promise<void>, |
| 311 | ) { |
| 312 | if (!this.context) { |
| 313 | console.log("Extension context is not yet set."); |
| 314 | return; |
| 315 | } |
| 316 | |
| 317 | try { |
| 318 | const command = vscode.commands.registerCommand(commandId, callback); |
| 319 | this.context.subscriptions.push(command); |
| 320 | } catch (error) { |
| 321 | console.log( |
| 322 | `Command ${commandId} already has an associated callback, skipping registration`, |
| 323 | ); |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | /** |
| 328 | * Show a tooltip with the given text at the current cursor position. |
| 329 | * @param editor The active text editor. |
| 330 | * @param text Text to display in the tooltip. |
| 331 | */ |
| 332 | public async showNextEditWindow( |
| 333 | editor: vscode.TextEditor, |
| 334 | currCursorPos: vscode.Position, |
| 335 | editableRegionStartLine: number, |
| 336 | editableRegionEndLine: number, |
| 337 | oldEditRangeSlice: string, |
| 338 | newEditRangeSlice: string, |
| 339 | diffLines: DiffLine[], |
| 340 | ) { |
| 341 | if (!this.shouldRenderTip(editor.document.uri)) { |
| 342 | return; |
| 343 | } |
| 344 | |
| 345 | // Clear any existing decorations first (very important to prevent overlapping). |
| 346 | await this.hideAllNextEditWindows(); |
| 347 | |
| 348 | this.activeEditor = editor; |
| 349 | |
| 350 | this.editableRegionStartLine = editableRegionStartLine; |
| 351 | this.editableRegionEndLine = editableRegionEndLine; |
| 352 | |
| 353 | // Store the current tooltip text for accepting later. |
| 354 | this.currentTooltipText = newEditRangeSlice; |
| 355 | |
| 356 | // Determine if this is a line deletion case |
| 357 | // NOTE: A simpler approach might be to just delete the line when newEditRangeSlice is "". |
| 358 | // But we opt for the below in case the above note is too naive. |
| 359 | this.isLineDelete = false; |
| 360 | if ( |
| 361 | newEditRangeSlice === "" && |
| 362 | editableRegionStartLine === editableRegionEndLine |
| 363 | ) { |
| 364 | // Check if diffLines contains only deletions (no additions). |
| 365 | const onlyDeletions = diffLines.every( |
| 366 | (diff) => diff.type === "old" || diff.type === "same", |
| 367 | ); |
| 368 | const hasDeletedLine = diffLines.some((diff) => diff.type === "old"); |
| 369 | |
| 370 | if (onlyDeletions && hasDeletedLine) { |
| 371 | // Check if the entire line is being deleted (not just characters). |
| 372 | const line = editor.document.lineAt(editableRegionStartLine).text; |
| 373 | const oldLine = oldEditRangeSlice.trim(); |
| 374 | if (line.trim() === oldLine || line.trim() === "") { |
| 375 | this.isLineDelete = true; |
| 376 | } |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | // How far away is the current line from the start of the editable region? |
| 381 | const lineOffsetAtCursorPos = |
| 382 | currCursorPos.line - this.editableRegionStartLine; |
| 383 | |
| 384 | // How long is the line at the current cursor position? |
| 385 | const lineContentAtCursorPos = |
| 386 | newEditRangeSlice.split("\n")[lineOffsetAtCursorPos]; |
| 387 | |
| 388 | const offset = getOffsetPositionAtLastNewLine( |
| 389 | diffLines, |
| 390 | lineContentAtCursorPos, |
| 391 | lineOffsetAtCursorPos, |
| 392 | ); |
| 393 | |
| 394 | // Calculate the final cursor position. |
| 395 | if (this.isLineDelete) { |
| 396 | // For line deletion, position cursor at the end of the previous line. |
| 397 | if (this.editableRegionStartLine > 0) { |
| 398 | const prevLine = editor.document.lineAt( |
| 399 | this.editableRegionStartLine - 1, |
| 400 | ); |
| 401 | this.finalCursorPos = new vscode.Position( |
| 402 | this.editableRegionStartLine - 1, |
| 403 | prevLine.text.length, |
| 404 | ); |
| 405 | } else { |
| 406 | // If we're deleting the first line, position at the start of the document. |
| 407 | this.finalCursorPos = new vscode.Position(0, 0); |
| 408 | } |
| 409 | } else { |
| 410 | // For normal edits, use the standard calculation. |
| 411 | this.finalCursorPos = new vscode.Position( |
| 412 | this.editableRegionStartLine + offset.line, |
| 413 | offset.character, |
| 414 | ); |
| 415 | } |
| 416 | |
| 417 | const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice); |
| 418 | |
| 419 | // Create and apply decoration with the text. |
| 420 | if (newEditRangeSlice !== "") { |
| 421 | try { |
| 422 | await this.renderWindow( |
| 423 | editor, |
| 424 | currCursorPos, |
| 425 | oldEditRangeSlice, |
| 426 | newEditRangeSlice, |
| 427 | this.editableRegionStartLine, |
| 428 | diffLines, |
| 429 | diffChars, |
| 430 | ); |
| 431 | } catch (error) { |
| 432 | console.error("Failed to render window:", error); |
| 433 | // Clean up and reset state. |
| 434 | await this.hideAllNextEditWindows(); |
| 435 | return; |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | this.renderDeletions(editor, diffChars); |
| 440 | |
| 441 | // Reserve tab and esc to either accept or reject the displayed next edit contents. |
| 442 | try { |
| 443 | await NextEditWindowManager.reserveTabAndEsc(); |
| 444 | } catch (err) { |
| 445 | console.error( |
| 446 | `Error reserving Tab/Esc after showing decorations: ${err}`, |
| 447 | ); |
| 448 | await this.hideAllNextEditWindows(); |
| 449 | return; |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | /** |
| 454 | * Hide all tooltips in all editors. |
| 455 | */ |
| 456 | public async hideAllNextEditWindows() { |
| 457 | try { |
| 458 | await NextEditWindowManager.freeTabAndEsc(); |
| 459 | } catch (err) { |
| 460 | console.error(`Error freeing Tab/Esc while hiding: ${err}`); |
| 461 | } |
| 462 | |
| 463 | if (this.currentDecoration) { |
| 464 | vscode.window.visibleTextEditors.forEach((editor) => { |
| 465 | editor.setDecorations(this.currentDecoration!, []); |
| 466 | }); |
| 467 | |
| 468 | // If we know which editor had the decoration, clear it specifically. |
| 469 | // This is a bit redundant but ensures we don't leave any decorations behind. |
| 470 | if (this.activeEditor) { |
| 471 | this.activeEditor.setDecorations(this.currentDecoration, []); |
| 472 | this.activeEditor = null; |
| 473 | } |
| 474 | |
| 475 | // This prevents memory leaks. |
| 476 | this.currentDecoration.dispose(); |
| 477 | this.currentDecoration = null; |
| 478 | |
| 479 | // Clear the current tooltip text. |
| 480 | this.currentTooltipText = null; |
| 481 | } |
| 482 | |
| 483 | if (this.disposables.length > 0) { |
| 484 | this.disposables.forEach((d) => d.dispose()); |
| 485 | this.disposables = []; |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | public async hideAllNextEditWindowsAndResetCompletionId() { |
| 490 | await this.hideAllNextEditWindows(); |
| 491 | |
| 492 | // Log with accept = false. |
| 493 | await vscode.commands.executeCommand( |
| 494 | "continue.logNextEditOutcomeReject", |
| 495 | this.mostRecentCompletionId, |
| 496 | this.loggingService, |
| 497 | ); |
| 498 | |
| 499 | this.mostRecentCompletionId = null; |
| 500 | } |
| 501 | |
| 502 | /** |
| 503 | * Accept the current next edit suggestion by inserting it at cursor position. |
| 504 | */ |
| 505 | private async acceptNextEdit() { |
| 506 | if (this.activeEditor === null || this.currentTooltipText === null) { |
| 507 | return; |
| 508 | } |
| 509 | this.accepted = true; |
| 510 | |
| 511 | const editor = this.activeEditor; |
| 512 | const text = this.currentTooltipText; |
| 513 | const position = editor.selection.active; |
| 514 | |
| 515 | let success = false; |
| 516 | |
| 517 | // Hide windows first for a snappier feel. |
| 518 | await this.hideAllNextEditWindows(); |
| 519 | |
| 520 | if (this.textApplier) { |
| 521 | success = await this.textApplier.applyText( |
| 522 | editor, |
| 523 | text, |
| 524 | position, |
| 525 | this.finalCursorPos, |
| 526 | ); |
| 527 | } else { |
| 528 | // Define the range to replace. |
| 529 | const startPos = new vscode.Position(this.editableRegionStartLine, 0); |
| 530 | const endPosChar = editor.document.lineAt(this.editableRegionEndLine).text |
| 531 | .length; |
| 532 | |
| 533 | const endPos = new vscode.Position( |
| 534 | this.editableRegionEndLine, |
| 535 | endPosChar, |
| 536 | ); |
| 537 | const editRange = new vscode.Range(startPos, endPos); |
| 538 | |
| 539 | if (this.isLineDelete) { |
| 540 | // Handle line deletion - extend the range to include the newline. |
| 541 | let lineDeleteRange = editRange; |
| 542 | |
| 543 | // If this isn't the last line, extend to include the newline character. |
| 544 | if (this.editableRegionStartLine < editor.document.lineCount - 1) { |
| 545 | lineDeleteRange = new vscode.Range( |
| 546 | startPos, |
| 547 | new vscode.Position(this.editableRegionStartLine + 1, 0), |
| 548 | ); |
| 549 | } |
| 550 | |
| 551 | success = await editor.edit((editBuilder) => { |
| 552 | editBuilder.delete(lineDeleteRange); |
| 553 | }); |
| 554 | } else { |
| 555 | success = await editor.edit((editBuilder) => { |
| 556 | editBuilder.replace(editRange, text); |
| 557 | }); |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | if (success && this.finalCursorPos) { |
| 562 | // Move cursor to the final position if available. |
| 563 | editor.selection = new vscode.Selection( |
| 564 | this.finalCursorPos, |
| 565 | this.finalCursorPos, |
| 566 | ); |
| 567 | } |
| 568 | |
| 569 | // Log with accept = true. |
| 570 | await vscode.commands.executeCommand( |
| 571 | "continue.logNextEditOutcomeAccept", |
| 572 | this.mostRecentCompletionId, |
| 573 | this.loggingService, |
| 574 | ); |
| 575 | this.mostRecentCompletionId = null; |
| 576 | |
| 577 | // Reset to false for future logging. |
| 578 | this.accepted = false; |
| 579 | } |
| 580 | |
| 581 | /** |
| 582 | * Dispose of the NextEditWindowManager. |
| 583 | */ |
| 584 | public dispose() { |
| 585 | void this.resetKeyReservation().catch((err) => |
| 586 | console.error(`Failed to reset keys on dispose: ${err}`), |
| 587 | ); |
| 588 | |
| 589 | // Dispose current decoration. |
| 590 | if (this.currentDecoration) { |
| 591 | this.currentDecoration.dispose(); |
| 592 | this.currentDecoration = null; |
| 593 | } |
| 594 | |
| 595 | // Dispose all other disposables. |
| 596 | this.disposables.forEach((d) => d.dispose()); |
| 597 | this.disposables = []; |
| 598 | } |
| 599 | |
| 600 | /** |
| 601 | * Setup listeners for theme, font, and cursor position changes. |
| 602 | */ |
| 603 | private setupListeners() { |
| 604 | // Theme change listener. |
| 605 | vscode.workspace.onDidChangeConfiguration(async (e) => { |
| 606 | if ( |
| 607 | e.affectsConfiguration("workbench.colorTheme") || |
| 608 | e.affectsConfiguration("editor.fontSize") || |
| 609 | e.affectsConfiguration("editor.fontFamily") || |
| 610 | e.affectsConfiguration("window.autoDetectColorScheme") || |
| 611 | e.affectsConfiguration("window.autoDetectHighContrast") || |
| 612 | e.affectsConfiguration("workbench.preferredDarkColorTheme") || |
| 613 | e.affectsConfiguration("workbench.preferredLightColorTheme") || |
| 614 | e.affectsConfiguration("workbench.preferredHighContrastColorTheme") || |
| 615 | e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme") |
| 616 | ) { |
| 617 | this.theme = getThemeString(); |
| 618 | await this.codeRenderer.setTheme(this.theme); |
| 619 | console.log( |
| 620 | "Theme updated:", |
| 621 | this.theme ? "Theme exists" : "Theme is undefined", |
| 622 | ); |
| 623 | const editorConfig = vscode.workspace.getConfiguration("editor"); |
| 624 | this.fontSize = editorConfig.get<number>("fontSize") ?? 14; |
| 625 | this.fontFamily = editorConfig.get<string>("fontFamily") ?? "monospace"; |
| 626 | } |
| 627 | }); |
| 628 | |
| 629 | // Listen for active color theme changes. |
| 630 | vscode.window.onDidChangeActiveColorTheme(async () => { |
| 631 | this.theme = getThemeString(); |
| 632 | await this.codeRenderer.setTheme(this.theme); |
| 633 | console.log( |
| 634 | "Active theme changed:", |
| 635 | this.theme ? "Theme exists" : "Theme is undefined", |
| 636 | ); |
| 637 | }); |
| 638 | |
| 639 | // Listen for editor changes to clean up decorations when editor closes. |
| 640 | vscode.window.onDidChangeVisibleTextEditors(async () => { |
| 641 | // If our active editor is no longer visible, clear decorations. |
| 642 | if ( |
| 643 | this.activeEditor && |
| 644 | !vscode.window.visibleTextEditors.includes(this.activeEditor) |
| 645 | ) { |
| 646 | if (this.mostRecentCompletionId) { |
| 647 | this.loggingService.cancelRejectionTimeout( |
| 648 | this.mostRecentCompletionId, |
| 649 | ); |
| 650 | } |
| 651 | await this.hideAllNextEditWindows(); |
| 652 | } |
| 653 | }); |
| 654 | |
| 655 | // Listen for selection changes to hide tooltip when cursor moves. |
| 656 | vscode.window.onDidChangeTextEditorSelection(async (e) => { |
| 657 | // If the selection changed in our active editor, hide the tooltip. |
| 658 | if (this.activeEditor && e.textEditor === this.activeEditor) { |
| 659 | // If the cursor moved because of something other than accepting next edit, stop logging it. |
| 660 | if (!this.accepted && this.mostRecentCompletionId) { |
| 661 | this.loggingService.cancelRejectionTimeout( |
| 662 | this.mostRecentCompletionId, |
| 663 | ); |
| 664 | } |
| 665 | await this.hideAllNextEditWindows(); |
| 666 | } |
| 667 | }); |
| 668 | } |
| 669 | |
| 670 | private shouldRenderTip(uri: vscode.Uri): boolean { |
| 671 | const isAllowedUri = |
| 672 | !this.excludedURIPrefixes.some((prefix) => |
| 673 | uri.toString().startsWith(prefix), |
| 674 | ) && uri.scheme !== "comment"; |
| 675 | |
| 676 | const isEnabled = |
| 677 | !!vscode.workspace |
| 678 | .getConfiguration(EXTENSION_NAME) |
| 679 | .get<boolean>("showInlineTip") === true; |
| 680 | |
| 681 | return isAllowedUri && isEnabled; |
| 682 | } |
| 683 | |
| 684 | /** |
| 685 | * Create a render of the given code, supporting multiple lines. |
| 686 | */ |
| 687 | private async createCodeRender( |
| 688 | text: string, |
| 689 | currLineOffsetFromTop: number, |
| 690 | newDiffLines: DiffLine[], |
| 691 | diffChars: DiffChar[], |
| 692 | ): Promise< |
| 693 | | { uri: vscode.Uri; dimensions: { width: number; height: number } } |
| 694 | | undefined |
| 695 | > { |
| 696 | try { |
| 697 | const tipWidth = SVG_CONFIG.getTipWidth(text); |
| 698 | const tipHeight = SVG_CONFIG.getTipHeight(text); |
| 699 | const dimensions = { |
| 700 | width: tipWidth, |
| 701 | height: tipHeight, |
| 702 | }; |
| 703 | |
| 704 | const uri = await this.codeRenderer.getDataUri( |
| 705 | text, |
| 706 | "typescript", |
| 707 | { |
| 708 | imageType: "svg", |
| 709 | fontSize: this.fontSize, |
| 710 | fontFamily: this.fontFamily, |
| 711 | dimensions: dimensions, |
| 712 | lineHeight: SVG_CONFIG.lineHeight, |
| 713 | }, |
| 714 | currLineOffsetFromTop, |
| 715 | newDiffLines, |
| 716 | diffChars, |
| 717 | ); |
| 718 | |
| 719 | return { |
| 720 | uri: vscode.Uri.parse(uri), |
| 721 | dimensions, |
| 722 | }; |
| 723 | } catch (error) { |
| 724 | console.error("Error creating SVG tooltip:", error); |
| 725 | return undefined; |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | /** |
| 730 | * Create a decoration type with the code render. |
| 731 | * @param code: The code to render. |
| 732 | * @returns The decoration. |
| 733 | */ |
| 734 | private async createCodeRenderDecoration( |
| 735 | originalCode: string, |
| 736 | predictedCode: string, |
| 737 | position: vscode.Position, |
| 738 | editableRegionStartLine: number, |
| 739 | newDiffLines: DiffLine[], |
| 740 | diffChars: DiffChar[], |
| 741 | ): Promise<vscode.TextEditorDecorationType | undefined> { |
| 742 | const currLineOffsetFromTop = position.line - editableRegionStartLine; |
| 743 | const uriAndDimensions = await this.createCodeRender( |
| 744 | predictedCode, |
| 745 | currLineOffsetFromTop, |
| 746 | newDiffLines, |
| 747 | diffChars, |
| 748 | ); |
| 749 | if (!uriAndDimensions) { |
| 750 | return undefined; |
| 751 | } |
| 752 | |
| 753 | const { uri, dimensions } = uriAndDimensions; |
| 754 | const tipWidth = dimensions.width; |
| 755 | const tipHeight = dimensions.height; |
| 756 | |
| 757 | const offsetFromTop = |
| 758 | (position.line - editableRegionStartLine) * SVG_CONFIG.lineHeight; |
| 759 | |
| 760 | // Position the decoration with minimal left margin since it's already at line end |
| 761 | const marginLeft = SVG_CONFIG.paddingX; // Use consistent padding instead of complex calculation |
| 762 | |
| 763 | return vscode.window.createTextEditorDecorationType({ |
| 764 | before: { |
| 765 | contentIconPath: uri, |
| 766 | border: `transparent; position: absolute; z-index: 2147483647; |
| 767 | filter: ${SVG_CONFIG.filter}; |
| 768 | margin-top: ${-1 * offsetFromTop}px; |
| 769 | margin-left: ${marginLeft}px;`, |
| 770 | width: `${tipWidth}px`, |
| 771 | height: `${tipHeight}px`, |
| 772 | }, |
| 773 | rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed, |
| 774 | }); |
| 775 | } |
| 776 | |
| 777 | private buildHideTooltipHoverMsg() { |
| 778 | const hoverMarkdown = new vscode.MarkdownString( |
| 779 | `[Reject (Esc)](command:${HIDE_NEXT_EDIT_SUGGESTION_COMMAND}) | [Accept (Tab)](command:${ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND})`, |
| 780 | ); |
| 781 | |
| 782 | hoverMarkdown.isTrusted = true; |
| 783 | hoverMarkdown.supportHtml = true; |
| 784 | return hoverMarkdown; |
| 785 | } |
| 786 | |
| 787 | private isValidRange( |
| 788 | editor: vscode.TextEditor, |
| 789 | range: vscode.Range, |
| 790 | ): boolean { |
| 791 | const doc = editor.document; |
| 792 | |
| 793 | // Check if line numbers are valid. |
| 794 | if (range.start.line < 0 || range.start.line >= doc.lineCount) { |
| 795 | console.log( |
| 796 | "Invalid start line:", |
| 797 | range.start.line, |
| 798 | "doc lines:", |
| 799 | doc.lineCount, |
| 800 | ); |
| 801 | return false; |
| 802 | } |
| 803 | |
| 804 | if (range.end.line < 0 || range.end.line >= doc.lineCount) { |
| 805 | console.log( |
| 806 | "Invalid end line:", |
| 807 | range.end.line, |
| 808 | "doc lines:", |
| 809 | doc.lineCount, |
| 810 | ); |
| 811 | return false; |
| 812 | } |
| 813 | |
| 814 | // Check if character positions are valid. |
| 815 | const startLine = doc.lineAt(range.start.line); |
| 816 | const endLine = doc.lineAt(range.end.line); |
| 817 | |
| 818 | if ( |
| 819 | range.start.character < 0 || |
| 820 | range.start.character > startLine.text.length |
| 821 | ) { |
| 822 | console.log( |
| 823 | "Invalid start character:", |
| 824 | range.start.character, |
| 825 | "line length:", |
| 826 | startLine.text.length, |
| 827 | ); |
| 828 | return false; |
| 829 | } |
| 830 | |
| 831 | if (range.end.character < 0 || range.end.character > endLine.text.length) { |
| 832 | console.log( |
| 833 | "Invalid end character:", |
| 834 | range.end.character, |
| 835 | "line length:", |
| 836 | endLine.text.length, |
| 837 | ); |
| 838 | return false; |
| 839 | } |
| 840 | |
| 841 | return true; |
| 842 | } |
| 843 | |
| 844 | /** |
| 845 | * Calculate a position to the right of the cursor with the specified offset. |
| 846 | */ |
| 847 | private getDecorationOffsetPosition( |
| 848 | editor: vscode.TextEditor, |
| 849 | position: vscode.Position, |
| 850 | ): vscode.Position { |
| 851 | // Place decoration at the end of the current line |
| 852 | const line = editor.document.lineAt(position.line); |
| 853 | return new vscode.Position(position.line, line.text.length); |
| 854 | } |
| 855 | |
| 856 | /** |
| 857 | * Render a window with the given text at the specified position. |
| 858 | */ |
| 859 | private async renderWindow( |
| 860 | editor: vscode.TextEditor, |
| 861 | position: vscode.Position, |
| 862 | originalCode: string, |
| 863 | predictedCode: string, |
| 864 | editableRegionStartLine: number, |
| 865 | newDiffLines: DiffLine[], |
| 866 | diffChars: DiffChar[], |
| 867 | ) { |
| 868 | // Capture document version to detect changes. |
| 869 | const docVersion = editor.document.version; |
| 870 | |
| 871 | // Create a new decoration with the text. |
| 872 | const decoration = await this.createCodeRenderDecoration( |
| 873 | originalCode, |
| 874 | predictedCode, |
| 875 | position, |
| 876 | editableRegionStartLine, |
| 877 | newDiffLines, |
| 878 | diffChars, |
| 879 | ); |
| 880 | if (!decoration) { |
| 881 | console.error("Failed to create decoration for text:", predictedCode); |
| 882 | return; |
| 883 | } |
| 884 | |
| 885 | // Check if document changed during async operation. |
| 886 | if (editor.document.version !== docVersion) { |
| 887 | console.log("Document changed during decoration creation, aborting"); |
| 888 | decoration.dispose(); |
| 889 | return; |
| 890 | } |
| 891 | |
| 892 | // Store the decoration and editor. |
| 893 | this.currentDecoration = decoration; // TODO: This might be redundant. |
| 894 | this.disposables.push(decoration); |
| 895 | |
| 896 | // Calculate how far off to the right of the cursor the decoration should be. |
| 897 | const decorationOffsetPosition = this.getDecorationOffsetPosition( |
| 898 | editor, |
| 899 | position, |
| 900 | ); |
| 901 | const range = new vscode.Range( |
| 902 | decorationOffsetPosition, |
| 903 | decorationOffsetPosition, |
| 904 | ); |
| 905 | |
| 906 | // Validate the range before applying. |
| 907 | if (!this.isValidRange(editor, range)) { |
| 908 | console.error("Invalid range detected, skipping decoration"); |
| 909 | return; |
| 910 | } |
| 911 | |
| 912 | // Apply the decoration at the calculated position. |
| 913 | editor.setDecorations(this.currentDecoration, [ |
| 914 | { |
| 915 | range: new vscode.Range( |
| 916 | decorationOffsetPosition, |
| 917 | decorationOffsetPosition, |
| 918 | ), |
| 919 | hoverMessage: [this.buildHideTooltipHoverMsg()], |
| 920 | }, |
| 921 | ]); |
| 922 | |
| 923 | // Clear the timeout while SVG is on the editor. |
| 924 | if (this.currentDecoration && this.mostRecentCompletionId) |
| 925 | this.loggingService.cancelRejectionTimeoutButKeepCompletionId( |
| 926 | this.mostRecentCompletionId, |
| 927 | ); |
| 928 | } |
| 929 | |
| 930 | private renderDeletions(editor: vscode.TextEditor, oldDiffChars: DiffChar[]) { |
| 931 | const charsToDelete: vscode.DecorationOptions[] = []; |
| 932 | |
| 933 | // const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice); |
| 934 | |
| 935 | oldDiffChars.forEach((diff) => { |
| 936 | // TODO: This check if technically redundant. |
| 937 | if (diff.type === "old") { |
| 938 | charsToDelete.push({ |
| 939 | range: new vscode.Range( |
| 940 | new vscode.Position( |
| 941 | this.editableRegionStartLine + diff.oldLineIndex!, |
| 942 | diff.oldCharIndexInLine!, |
| 943 | ), |
| 944 | new vscode.Position( |
| 945 | this.editableRegionStartLine + diff.oldLineIndex!, |
| 946 | diff.oldCharIndexInLine! + diff.char.length, |
| 947 | ), |
| 948 | ), |
| 949 | }); |
| 950 | } |
| 951 | }); |
| 952 | |
| 953 | const deleteDecorationType = vscode.window.createTextEditorDecorationType({ |
| 954 | backgroundColor: "rgba(255, 0, 0, 0.5)", |
| 955 | }); |
| 956 | |
| 957 | editor.setDecorations(deleteDecorationType, charsToDelete); |
| 958 | this.disposables.push(deleteDecorationType); |
| 959 | } |
| 960 | |
| 961 | async getExactCharacterWidth(): Promise<number> { |
| 962 | // For VS Code extensions, you can sometimes access the editor's text metrics |
| 963 | const activeEditor = vscode.window.activeTextEditor; |
| 964 | if (activeEditor) { |
| 965 | // VS Code has internal methods to measure text, but they're not all exposed |
| 966 | // in the public API. You might need to use reflection or known properties. |
| 967 | |
| 968 | // Example accessing through reflection (this is pseudocode) |
| 969 | const editorInstance = activeEditor as any; |
| 970 | if (editorInstance._modelData && editorInstance._modelData.viewModel) { |
| 971 | const viewModel = editorInstance._modelData.viewModel; |
| 972 | return ( |
| 973 | viewModel.getLineWidth(0) / |
| 974 | activeEditor.document.lineAt(0).text.length |
| 975 | ); |
| 976 | } |
| 977 | } |
| 978 | |
| 979 | // If all else fails, return a reasonable default |
| 980 | return SVG_CONFIG.fontSize * 0.6; |
| 981 | } |
| 982 | |
| 983 | public hasAccepted() { |
| 984 | return this.accepted; |
| 985 | } |
| 986 | |
| 987 | public registerSelectionChangeHandler(): void { |
| 988 | const manager = SelectionChangeManager.getInstance(); |
| 989 | |
| 990 | manager.registerListener( |
| 991 | "nextEditWindowManager", |
| 992 | async (e, state) => { |
| 993 | if (state.nextEditWindowAccepted) { |
| 994 | console.log( |
| 995 | "NextEditWindowManager: Edit was just accepted, preserving chain", |
| 996 | ); |
| 997 | return true; |
| 998 | } |
| 999 | return false; |
| 1000 | }, |
| 1001 | HandlerPriority.CRITICAL, |
| 1002 | ); |
| 1003 | } |
| 1004 | } |
| 1005 | |
| 1006 | export default async function setupNextEditWindowManager( |
| 1007 | context: vscode.ExtensionContext, |
| 1008 | textApplier?: TextApplier, |
| 1009 | ) { |
| 1010 | await NextEditWindowManager.getInstance().setupNextEditWindowManager( |
| 1011 | context, |
| 1012 | textApplier, |
| 1013 | ); |
| 1014 | } |