| 1 | import { NextEditProvider } from "core/nextEdit/NextEditProvider"; |
| 2 | import { NextEditOutcome } from "core/nextEdit/types"; |
| 3 | // @ts-ignore |
| 4 | import svgBuilder from "svg-builder"; |
| 5 | import * as vscode from "vscode"; |
| 6 | import { getTheme } from "../util/getTheme"; |
| 7 | import { |
| 8 | HandlerPriority, |
| 9 | SelectionChangeManager, |
| 10 | } from "./SelectionChangeManager"; |
| 11 | |
| 12 | // Instead of getters that execute immediately, use methods or lazy properties |
| 13 | const SVG_CONFIG = { |
| 14 | stroke: "#999998", |
| 15 | strokeWidth: 1, |
| 16 | shortcutColor: "#999998", |
| 17 | filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))", |
| 18 | radius: 3, |
| 19 | leftMargin: 40, |
| 20 | debounceDelay: 500, |
| 21 | label: "馃搷 Press Tab to jump, Esc to cancel", |
| 22 | |
| 23 | // Convert getters to methods that are called when needed |
| 24 | getFontSize(): number { |
| 25 | return Math.ceil( |
| 26 | (vscode.workspace.getConfiguration("editor").get<number>("fontSize") ?? |
| 27 | 14) * 0.8, |
| 28 | ); |
| 29 | }, |
| 30 | |
| 31 | getFontFamily(): string { |
| 32 | return ( |
| 33 | vscode.workspace.getConfiguration("editor").get<string>("fontFamily") || |
| 34 | "helvetica" |
| 35 | ); |
| 36 | }, |
| 37 | |
| 38 | getPaddingX(): number { |
| 39 | return Math.ceil(this.getEstimatedTextWidth(" ")); |
| 40 | }, |
| 41 | |
| 42 | getGap(): number { |
| 43 | return this.getFontSize() * 0.5; |
| 44 | }, |
| 45 | |
| 46 | getTipWidth(): number { |
| 47 | return this.getEstimatedTextWidth(this.label) + this.getPaddingX(); |
| 48 | }, |
| 49 | |
| 50 | getTipHeight(): number { |
| 51 | return this.getFontSize(); |
| 52 | }, |
| 53 | |
| 54 | getTextY(): number { |
| 55 | return (this.getTipHeight() + this.getFontSize()) / 2; |
| 56 | }, |
| 57 | |
| 58 | getEstimatedTextWidth(text: string): number { |
| 59 | return text.length * this.getFontSize() * 0.6; |
| 60 | }, |
| 61 | } as const; |
| 62 | |
| 63 | export interface CompletionDataForAfterJump { |
| 64 | completionId: string; |
| 65 | outcome: NextEditOutcome; |
| 66 | currentPosition: vscode.Position; |
| 67 | } |
| 68 | |
| 69 | export class JumpManager { |
| 70 | private static _instance: JumpManager | undefined; |
| 71 | |
| 72 | // Decoration state. |
| 73 | private _jumpIcon: vscode.Uri | undefined; |
| 74 | private _jumpDecoration: vscode.TextEditorDecorationType | undefined; |
| 75 | private _jumpDecorationVisible = false; |
| 76 | private _disposables: vscode.Disposable[] = []; |
| 77 | private _theme = getTheme(); |
| 78 | |
| 79 | private _jumpInProgress: boolean = false; |
| 80 | private _jumpAccepted: boolean = false; |
| 81 | private _completionAfterJump: CompletionDataForAfterJump | null = null; |
| 82 | private _oldCursorPosition: vscode.Position | undefined; |
| 83 | |
| 84 | private constructor() { |
| 85 | // Build the first SVG icon |
| 86 | this._createSvgJumpIcon(); |
| 87 | |
| 88 | // Re鈥慴uild when the colour theme changes |
| 89 | vscode.workspace.onDidChangeConfiguration((e) => { |
| 90 | if (e.affectsConfiguration("workbench.colorTheme")) { |
| 91 | this._theme = getTheme(); |
| 92 | this._createSvgJumpIcon(); |
| 93 | } |
| 94 | }); |
| 95 | } |
| 96 | |
| 97 | initialize() {} |
| 98 | |
| 99 | public static getInstance(): JumpManager { |
| 100 | if (!JumpManager._instance) { |
| 101 | JumpManager._instance = new JumpManager(); |
| 102 | } |
| 103 | return JumpManager._instance; |
| 104 | } |
| 105 | |
| 106 | public static clearInstance() { |
| 107 | if (JumpManager._instance) { |
| 108 | JumpManager._instance.dispose(); |
| 109 | JumpManager._instance = undefined; |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | public dispose() { |
| 114 | // Dispose current decoration. |
| 115 | this._disposables.forEach((d) => { |
| 116 | if (d) d.dispose(); |
| 117 | }); |
| 118 | this._disposables = []; |
| 119 | } |
| 120 | |
| 121 | private _createSvgJumpIcon() { |
| 122 | // if (!this._theme) { |
| 123 | // return; |
| 124 | // } |
| 125 | |
| 126 | const baseTextConfig = { |
| 127 | y: SVG_CONFIG.getTextY(), |
| 128 | "font-family": SVG_CONFIG.getFontFamily(), |
| 129 | "font-size": SVG_CONFIG.getFontSize(), |
| 130 | }; |
| 131 | |
| 132 | try { |
| 133 | const svgContent = svgBuilder |
| 134 | .width(SVG_CONFIG.getTipWidth()) |
| 135 | .height(SVG_CONFIG.getTipHeight()) |
| 136 | .text( |
| 137 | { |
| 138 | ...baseTextConfig, |
| 139 | x: 4, |
| 140 | fill: this._theme?.colors["editor.foreground"] ?? SVG_CONFIG.stroke, |
| 141 | }, |
| 142 | SVG_CONFIG.label, |
| 143 | ) |
| 144 | .render(); |
| 145 | |
| 146 | const dataUri = `data:image/svg+xml;base64,${Buffer.from( |
| 147 | svgContent, |
| 148 | ).toString("base64")}`; |
| 149 | this._jumpIcon = vscode.Uri.parse(dataUri); |
| 150 | |
| 151 | // Dispose the old decoration (if any) and create a fresh one. |
| 152 | if (this._jumpDecoration) { |
| 153 | this._jumpDecoration.dispose(); |
| 154 | } |
| 155 | this._jumpDecoration = this._createSvgJumpDecoration(); |
| 156 | } catch (err) { |
| 157 | console.error("Error creating SVG jump tooltip:", err); |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | private _createSvgJumpDecoration(): vscode.TextEditorDecorationType { |
| 162 | const backgroundColour = |
| 163 | this._theme?.colors["editor.background"] ?? "#333333"; |
| 164 | |
| 165 | return vscode.window.createTextEditorDecorationType({ |
| 166 | after: { |
| 167 | contentIconPath: this._jumpIcon, |
| 168 | border: `;box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${SVG_CONFIG.getTipHeight()}px ${backgroundColour}; |
| 169 | border-radius: ${SVG_CONFIG.radius}px; |
| 170 | filter: ${SVG_CONFIG.filter}`, |
| 171 | margin: `0 0 0 ${SVG_CONFIG.leftMargin}px`, |
| 172 | width: `${SVG_CONFIG.getTipWidth()}px`, |
| 173 | }, |
| 174 | }); |
| 175 | } |
| 176 | |
| 177 | public async suggestJump( |
| 178 | currentPosition: vscode.Position, |
| 179 | nextJumpLocation: vscode.Position, |
| 180 | completionContent?: string, |
| 181 | ): Promise<boolean> { |
| 182 | // Deduplication logic. |
| 183 | // If the content at the next jump location is |
| 184 | // identical to the completion content, |
| 185 | // then we don't have to jump. |
| 186 | if (completionContent !== undefined) { |
| 187 | console.log("completionContent is not null"); |
| 188 | const editor = vscode.window.activeTextEditor; |
| 189 | |
| 190 | if (editor) { |
| 191 | try { |
| 192 | const completionLines = completionContent.split("\n"); |
| 193 | console.log("completionLines:", completionLines); |
| 194 | |
| 195 | // Get document content at jump location spanning multiple lines. |
| 196 | const document = editor.document; |
| 197 | const startLine = nextJumpLocation.line; |
| 198 | const endLine = Math.min( |
| 199 | startLine + completionLines.length - 1, |
| 200 | document.lineCount - 1, |
| 201 | ); |
| 202 | |
| 203 | // First check if we have enough lines in the document |
| 204 | if (endLine - startLine + 1 < completionLines.length) { |
| 205 | // Not enough lines in document, so content can't be identical. |
| 206 | // Proceed to jump! |
| 207 | console.log( |
| 208 | "Not enough lines in document to match completion content", |
| 209 | ); |
| 210 | } else { |
| 211 | let contentMatches = true; |
| 212 | |
| 213 | // Check all lines for match. |
| 214 | for (let i = 0; i < completionLines.length && contentMatches; i++) { |
| 215 | const documentLine = startLine + i; |
| 216 | const lineText = document.lineAt(documentLine).text; |
| 217 | if (lineText !== completionLines[i]) { |
| 218 | contentMatches = false; |
| 219 | console.log(`Line ${i + 1} doesn't match`); |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | if (contentMatches) { |
| 224 | console.log( |
| 225 | "Skipping jump as content is identical at jump location", |
| 226 | ); |
| 227 | return false; // Exit early, don't suggest jump. |
| 228 | } |
| 229 | } |
| 230 | } catch (error) { |
| 231 | console.error("Error checking content at jump location:", error); |
| 232 | // Continue with jump even if there's an error checking content. |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | console.log("this._jumpInProgress"); |
| 238 | this._jumpInProgress = true; |
| 239 | this._oldCursorPosition = currentPosition; |
| 240 | |
| 241 | const editor = vscode.window.activeTextEditor; |
| 242 | if (!editor) { |
| 243 | console.log("No active editor, cannot suggest jump"); |
| 244 | this._jumpInProgress = false; |
| 245 | return false; |
| 246 | } |
| 247 | |
| 248 | const visibleRanges = editor.visibleRanges; |
| 249 | if (visibleRanges.length === 0) { |
| 250 | console.log("No visible ranges in editor, cannot suggest jump"); |
| 251 | this._jumpInProgress = false; |
| 252 | return false; |
| 253 | } |
| 254 | |
| 255 | const visibleRange = visibleRanges[0]; |
| 256 | const topLineNumber = visibleRange.start.line; |
| 257 | const bottomLineNumber = visibleRange.end.line; |
| 258 | |
| 259 | const decorationLine = nextJumpLocation.line; |
| 260 | |
| 261 | // Check if jump location is outside the visible range. |
| 262 | if (decorationLine < topLineNumber) { |
| 263 | await this.renderTabToJumpDecoration( |
| 264 | editor, |
| 265 | topLineNumber, |
| 266 | nextJumpLocation, |
| 267 | ); |
| 268 | } else if (decorationLine > bottomLineNumber) { |
| 269 | await this.renderTabToJumpDecoration( |
| 270 | editor, |
| 271 | bottomLineNumber, |
| 272 | nextJumpLocation, |
| 273 | ); |
| 274 | } else { |
| 275 | // No suggestion is made when the decoration is within visibleRange. |
| 276 | await this.renderTabToJumpDecoration( |
| 277 | editor, |
| 278 | decorationLine, |
| 279 | nextJumpLocation, |
| 280 | ); |
| 281 | } |
| 282 | |
| 283 | return true; |
| 284 | } |
| 285 | |
| 286 | private async renderTabToJumpDecoration( |
| 287 | editor: vscode.TextEditor, |
| 288 | lineToRenderOn: number, |
| 289 | jumpPosition: vscode.Position, |
| 290 | ) { |
| 291 | // Clean up any existing decoration beforehand. |
| 292 | await this.clearJumpDecoration(); |
| 293 | |
| 294 | // Create a decoration for jump. |
| 295 | // this._jumpDecoration = vscode.window.createTextEditorDecorationType({ |
| 296 | // before: { |
| 297 | // contentText: "馃搷 Press Tab to jump, Esc to cancel", |
| 298 | // color: new vscode.ThemeColor("editor.foreground"), |
| 299 | // backgroundColor: new vscode.ThemeColor("editorHover.background"), |
| 300 | // margin: `0 0 0 4px`, |
| 301 | // }, |
| 302 | // }); |
| 303 | |
| 304 | if (!this._jumpDecoration) { |
| 305 | this._createSvgJumpIcon(); // makes both the icon & decoration |
| 306 | } |
| 307 | |
| 308 | // Apply the decoration. |
| 309 | const lastIndexOfLine = editor.document.lineAt(lineToRenderOn).text.length; |
| 310 | editor.setDecorations(this._jumpDecoration!, [ |
| 311 | new vscode.Range( |
| 312 | lineToRenderOn, |
| 313 | lastIndexOfLine, |
| 314 | lineToRenderOn, |
| 315 | lastIndexOfLine, |
| 316 | ), |
| 317 | ]); |
| 318 | |
| 319 | // Set the context key to enable tab/esc shortcuts. |
| 320 | await vscode.commands.executeCommand( |
| 321 | "setContext", |
| 322 | "continue.jumpDecorationVisible", |
| 323 | true, |
| 324 | ); |
| 325 | this._jumpDecorationVisible = true; |
| 326 | |
| 327 | // Register the key listeners. |
| 328 | await this.registerKeyListeners(editor, jumpPosition); |
| 329 | } |
| 330 | |
| 331 | private async clearJumpDecoration() { |
| 332 | if (this._jumpDecoration) { |
| 333 | this._jumpDecoration.dispose(); |
| 334 | this._jumpDecoration = undefined; |
| 335 | } |
| 336 | |
| 337 | // Dispose any active listeners. |
| 338 | this.dispose(); |
| 339 | |
| 340 | // Reset the context. |
| 341 | await vscode.commands.executeCommand( |
| 342 | "setContext", |
| 343 | "continue.jumpDecorationVisible", |
| 344 | false, |
| 345 | ); |
| 346 | this._jumpDecorationVisible = false; |
| 347 | } |
| 348 | |
| 349 | private async registerKeyListeners( |
| 350 | editor: vscode.TextEditor, |
| 351 | jumpPosition: vscode.Position, |
| 352 | ) { |
| 353 | const acceptJumpCommand = vscode.commands.registerCommand( |
| 354 | "continue.acceptJump", |
| 355 | async () => { |
| 356 | if (this._jumpDecorationVisible) { |
| 357 | this._jumpAccepted = true; |
| 358 | |
| 359 | // Scroll to show the jump location. |
| 360 | editor.revealRange( |
| 361 | new vscode.Range(jumpPosition.line, 0, jumpPosition.line, 0), |
| 362 | vscode.TextEditorRevealType.InCenter, |
| 363 | ); |
| 364 | |
| 365 | // Move cursor to the jump position. |
| 366 | editor.selection = new vscode.Selection(jumpPosition, jumpPosition); |
| 367 | await this.clearJumpDecoration(); |
| 368 | |
| 369 | this._jumpAccepted = false; |
| 370 | vscode.commands.executeCommand("editor.action.inlineSuggest.trigger"); |
| 371 | } |
| 372 | }, |
| 373 | ); |
| 374 | |
| 375 | const rejectJumpCommand = vscode.commands.registerCommand( |
| 376 | "continue.rejectJump", |
| 377 | async () => { |
| 378 | if (this._jumpDecorationVisible) { |
| 379 | console.log( |
| 380 | "deleteChain from JumpManager.ts: rejectJump and decoration visible", |
| 381 | ); |
| 382 | NextEditProvider.getInstance().deleteChain(); |
| 383 | await this.clearJumpDecoration(); |
| 384 | } |
| 385 | }, |
| 386 | ); |
| 387 | |
| 388 | // Add a selection change listener to the editor to reject jump when cursor moves. |
| 389 | const selectionChangeListener = |
| 390 | vscode.window.onDidChangeTextEditorSelection((e) => { |
| 391 | // If jump decoration isn't visible, nothing to do. |
| 392 | if (!this._jumpDecorationVisible) { |
| 393 | return; |
| 394 | } |
| 395 | |
| 396 | const currentPosition = e.selections[0].active; |
| 397 | |
| 398 | // If cursor moved to jump position, this is likely the result of acceptJump. |
| 399 | if (currentPosition.isEqual(jumpPosition)) { |
| 400 | return; |
| 401 | } |
| 402 | |
| 403 | // If cursor position changed for any other reason, reject the jump. |
| 404 | if ( |
| 405 | this._oldCursorPosition && |
| 406 | !currentPosition.isEqual(this._oldCursorPosition) |
| 407 | ) { |
| 408 | vscode.commands.executeCommand("continue.rejectJump"); |
| 409 | } |
| 410 | }); |
| 411 | |
| 412 | // This allows us to dispose the command after a jump is completed. |
| 413 | this._disposables.push( |
| 414 | acceptJumpCommand, |
| 415 | rejectJumpCommand, |
| 416 | selectionChangeListener, |
| 417 | ); |
| 418 | } |
| 419 | |
| 420 | isJumpInProgress(): boolean { |
| 421 | return this._jumpInProgress; |
| 422 | } |
| 423 | |
| 424 | setJumpInProgress(jumpInProgress: boolean) { |
| 425 | this._jumpInProgress = jumpInProgress; |
| 426 | } |
| 427 | |
| 428 | wasJumpJustAccepted(): boolean { |
| 429 | return this._jumpAccepted; |
| 430 | } |
| 431 | |
| 432 | setCompletionAfterJump(completionData: CompletionDataForAfterJump): void { |
| 433 | this._completionAfterJump = completionData; |
| 434 | } |
| 435 | |
| 436 | clearCompletionAfterJump(): void { |
| 437 | this._completionAfterJump = null; |
| 438 | } |
| 439 | |
| 440 | get completionAfterJump() { |
| 441 | return this._completionAfterJump; |
| 442 | } |
| 443 | |
| 444 | public registerSelectionChangeHandler(): void { |
| 445 | const manager = SelectionChangeManager.getInstance(); |
| 446 | |
| 447 | manager.registerListener( |
| 448 | "jumpManager", |
| 449 | async (e, state) => { |
| 450 | if (state.jumpInProgress || state.jumpJustAccepted) { |
| 451 | console.log( |
| 452 | "JumpManager: jump in progress or just accepted, preserving chain", |
| 453 | ); |
| 454 | return true; |
| 455 | } |
| 456 | |
| 457 | return false; |
| 458 | }, |
| 459 | HandlerPriority.HIGH, |
| 460 | ); |
| 461 | } |
| 462 | } |