| 1 | import { |
| 2 | EditableRegionStrategy, |
| 3 | getNextEditableRegion, |
| 4 | } from "core/nextEdit/NextEditEditableRegionCalculator"; |
| 5 | import { PrefetchQueue } from "core/nextEdit/NextEditPrefetchQueue"; |
| 6 | import { NextEditProvider } from "core/nextEdit/NextEditProvider"; |
| 7 | import { localPathOrUriToPath } from "core/util/pathToUri"; |
| 8 | import * as vscode from "vscode"; |
| 9 | import { VsCodeIde } from "../VsCodeIde"; |
| 10 | import { JumpManager } from "./JumpManager"; |
| 11 | import { NextEditWindowManager } from "./NextEditWindowManager"; |
| 12 | |
| 13 | export enum HandlerPriority { |
| 14 | CRITICAL = 5, |
| 15 | HIGH = 4, |
| 16 | NORMAL = 3, |
| 17 | LOW = 2, |
| 18 | FALLBACK = 1, |
| 19 | } |
| 20 | |
| 21 | interface StateSnapshot { |
| 22 | nextEditWindowAccepted: boolean; |
| 23 | jumpInProgress: boolean; |
| 24 | jumpJustAccepted: boolean; |
| 25 | lastDocumentChangeTime: number; |
| 26 | isTypingSession: boolean; |
| 27 | document?: vscode.TextDocument; |
| 28 | cursorPosition?: vscode.Position; |
| 29 | } |
| 30 | |
| 31 | type SelectionChangeHandler = ( |
| 32 | e: vscode.TextEditorSelectionChangeEvent, |
| 33 | state: StateSnapshot, |
| 34 | ) => Promise<boolean>; |
| 35 | |
| 36 | interface HandlerRegistration { |
| 37 | id: string; |
| 38 | priority: number; |
| 39 | handler: SelectionChangeHandler; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * SelectionChangeManager handles cursor movement events in a coordinated way |
| 44 | * to prevent race conditions and ensure consistent behavior across features. |
| 45 | * |
| 46 | * Case 1: User just moves the cursor around. |
| 47 | * - vscode fires onDidChangeTextEditorSelection. |
| 48 | * - State is captured. All fields in StateSnapshot are false. |
| 49 | * - All registered handlers return false. |
| 50 | * - Fallback handler runs, deleting the chain. |
| 51 | * |
| 52 | * Case 2: User accepts a next edit suggestion from a window. |
| 53 | * - vscode fires onDidChangeTextEditorSelection. |
| 54 | * - State is captured. nextEditWindowAccepted is true. |
| 55 | * - NextEditWindowManager's handler returns true. |
| 56 | * - No other handlers run, and edit chain is preserved. |
| 57 | * |
| 58 | * Case 3: User accepts a next edit suggestion from a ghost text. |
| 59 | * - vscode fires onDidChangeTextEditorSelection. |
| 60 | * - State is captured with document and cursorPosition. |
| 61 | * - GhostTextTracker's handler checks if ghost text was accepted at that position. |
| 62 | * - If accepted, handler returns true and edit chain is preserved. |
| 63 | * |
| 64 | * Case 4: User is actively typing code. |
| 65 | * - Each keystroke triggers documentChanged() to update lastDocumentChangeTime. |
| 66 | * - When cursor moves due to typing, onDidChangeTextEditorSelection fires. |
| 67 | * - State is captured with isTypingSession=true and recent lastDocumentChangeTime. |
| 68 | * - Typing session handler detects time since last edit is < TYPING_DELAY. |
| 69 | * - Handler returns true, preserving the edit chain during typing. |
| 70 | * |
| 71 | * Case 5: User performs a jump operation. |
| 72 | * - Jump is initiated, setting jumpInProgress to true. |
| 73 | * - When cursor position changes due to jump, onDidChangeTextEditorSelection fires. |
| 74 | * - State is captured with jumpInProgress=true. |
| 75 | * - JumpManager's handler returns true, preserving the edit chain. |
| 76 | * |
| 77 | * Case 6: User just completed a jump operation. |
| 78 | * - Jump completes, setting jumpJustAccepted to true. |
| 79 | * - onDidChangeTextEditorSelection fires for the final position. |
| 80 | * - State is captured with jumpJustAccepted=true. |
| 81 | * - JumpManager's handler returns true, preserving the edit chain. |
| 82 | * |
| 83 | * Case 7: Rapid cursor movements (debouncing). |
| 84 | * - User rapidly moves cursor (e.g., holding an arrow key). |
| 85 | * - Multiple onDidChangeTextEditorSelection events fire in quick succession. |
| 86 | * - Events within DEBOUNCE_DELAY of each other are queued. |
| 87 | * - Only the most recent event in a rapid sequence gets processed. |
| 88 | * - Prevents performance issues from too many events. |
| 89 | * |
| 90 | * Case 8: Event processing timeout. |
| 91 | * - An event handler takes longer than PROCESSING_TIMEOUT. |
| 92 | * - The timeout promise resolves first, throwing an error. |
| 93 | * - Error is caught, processing state is reset to prevent deadlocks. |
| 94 | * - System can continue processing the next event. |
| 95 | * - NOTE: At the current moment, there should not be any deadlocks, but I'm just making sure. |
| 96 | * |
| 97 | * Case 9: Error in handler. |
| 98 | * - One of the handlers throws an exception. |
| 99 | * - The error is caught and logged. |
| 100 | * - Processing continues with the next handler rather than failing completely. |
| 101 | * - Ensures stability even when individual handlers have problems. |
| 102 | * |
| 103 | * Case 10: Multiple queued events. |
| 104 | * - An event is being processed when new events arrive. |
| 105 | * - New events are added to eventQueue. |
| 106 | * - After current event is processed, queued events are handled sequentially. |
| 107 | * - Ensures all events are processed in the order they were received. |
| 108 | * - NOTE: I'm not sure if we even want to queue these events... |
| 109 | * |
| 110 | * Case n: Other cases that I didn't catch. |
| 111 | */ |
| 112 | export class SelectionChangeManager { |
| 113 | private static instance: SelectionChangeManager; |
| 114 | private listeners: HandlerRegistration[] = []; |
| 115 | private ide: VsCodeIde | null = null; |
| 116 | private usingFullFileDiff: boolean = true; |
| 117 | |
| 118 | // Event bus-related attributes. |
| 119 | private eventQueue: vscode.TextEditorSelectionChangeEvent[] = []; |
| 120 | private lastEventTime = 0; |
| 121 | private isProcessingEvent = false; |
| 122 | private processingTimeout: NodeJS.Timeout | null = null; |
| 123 | |
| 124 | // Debounce settings. |
| 125 | private readonly DEBOUNCE_DELAY = 50; |
| 126 | private readonly PROCESSING_TIMEOUT = 500; |
| 127 | |
| 128 | // Track typing session state. |
| 129 | private isTypingSession = false; |
| 130 | private typingTimer: NodeJS.Timeout | null = null; |
| 131 | private lastDocumentChangeTime = 0; |
| 132 | private readonly TYPING_SESSION_TIMEOUT = 2000; // ms |
| 133 | |
| 134 | private constructor() {} |
| 135 | |
| 136 | public static getInstance() { |
| 137 | if (!SelectionChangeManager.instance) { |
| 138 | SelectionChangeManager.instance = new SelectionChangeManager(); |
| 139 | } |
| 140 | return SelectionChangeManager.instance; |
| 141 | } |
| 142 | |
| 143 | public initialize(ide: VsCodeIde, usingFullFileDiff: boolean): void { |
| 144 | this.ide = ide; |
| 145 | this.usingFullFileDiff = usingFullFileDiff; |
| 146 | |
| 147 | // After handling all other listeners, this will delete the chain. |
| 148 | this.registerListener( |
| 149 | "defaultFallbackHandler", |
| 150 | this.defaultFallbackHandler.bind(this), |
| 151 | HandlerPriority.FALLBACK, |
| 152 | ); |
| 153 | } |
| 154 | |
| 155 | /** |
| 156 | * Updates this class's usingFullFileDiff flag. |
| 157 | * @param usingFullFileDiff New value to set. |
| 158 | */ |
| 159 | public updateUsingFullFileDiff(usingFullFileDiff: boolean) { |
| 160 | this.usingFullFileDiff = usingFullFileDiff; |
| 161 | } |
| 162 | |
| 163 | public documentChanged(): void { |
| 164 | this.isTypingSession = true; |
| 165 | this.lastDocumentChangeTime = Date.now(); |
| 166 | this.resetTypingSession(); |
| 167 | } |
| 168 | |
| 169 | private resetTypingSession(): void { |
| 170 | if (this.typingTimer) { |
| 171 | clearTimeout(this.typingTimer); |
| 172 | } |
| 173 | this.typingTimer = setTimeout(() => { |
| 174 | this.isTypingSession = false; |
| 175 | }, this.TYPING_SESSION_TIMEOUT); |
| 176 | } |
| 177 | |
| 178 | /** |
| 179 | * Register a listener for the selection change event. |
| 180 | * @param id Unique id for this handler. |
| 181 | * @param handler Function to handle the event. |
| 182 | * @param priority Higher priority runs first. |
| 183 | * @returns Function to unregister this listener. |
| 184 | */ |
| 185 | public registerListener( |
| 186 | id: string, |
| 187 | handler: SelectionChangeHandler, |
| 188 | priority: HandlerPriority = HandlerPriority.NORMAL, |
| 189 | ): () => void { |
| 190 | // Remove any existing handler with the same id. |
| 191 | this.listeners = this.listeners.filter((l) => l.id !== id); |
| 192 | |
| 193 | // Add the new handler. |
| 194 | this.listeners.push({ id, priority, handler }); |
| 195 | |
| 196 | // Sort by desc priority. |
| 197 | this.listeners.sort((a, b) => b.priority - a.priority); |
| 198 | |
| 199 | // Return the unregister function. |
| 200 | return () => { |
| 201 | this.listeners = this.listeners.filter((l) => l.id !== id); |
| 202 | }; |
| 203 | } |
| 204 | |
| 205 | /** |
| 206 | * Handle a given selection change event. |
| 207 | * @param e THe selection change event. |
| 208 | */ |
| 209 | public async handleSelectionChange( |
| 210 | e: vscode.TextEditorSelectionChangeEvent, |
| 211 | ): Promise<void> { |
| 212 | const now = Date.now(); |
| 213 | |
| 214 | // Simple debouncing logic. |
| 215 | // Ignore events that come too quickly after the previous one. |
| 216 | // TODO: test this. |
| 217 | if (now - this.lastEventTime < this.DEBOUNCE_DELAY) { |
| 218 | // Replace the queued event with the most recent one. |
| 219 | if (this.eventQueue.length > 0) { |
| 220 | this.eventQueue[this.eventQueue.length - 1] = e; |
| 221 | } else { |
| 222 | this.eventQueue.push(e); |
| 223 | } |
| 224 | |
| 225 | return; |
| 226 | } |
| 227 | |
| 228 | this.lastEventTime = now; |
| 229 | |
| 230 | // Queue this event for later if the manager is already processing an event. |
| 231 | // NOTE: Depending on if we want an event bus or not, do an early return instead. |
| 232 | if (this.isProcessingEvent) { |
| 233 | this.eventQueue.push(e); |
| 234 | return; |
| 235 | } |
| 236 | |
| 237 | try { |
| 238 | // Process this event first. |
| 239 | await this.processEventWithTimeout(e); |
| 240 | |
| 241 | // Process remaining queued events sequentially. |
| 242 | // NOTE: Depending on if we want an event bus or not, skip this. |
| 243 | while (this.eventQueue.length > 0) { |
| 244 | const nextEvent = this.eventQueue.shift()!; |
| 245 | await this.processEventWithTimeout(nextEvent); |
| 246 | } |
| 247 | } catch (err) { |
| 248 | console.error("Error processing selection change event:", err); |
| 249 | this.isProcessingEvent = false; |
| 250 | if (this.processingTimeout) { |
| 251 | clearTimeout(this.processingTimeout); |
| 252 | this.processingTimeout = null; |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | /** |
| 258 | * Process a given event with a timeout. |
| 259 | * This is in attempt to prevent deadlocks between events. |
| 260 | * @param e The selection change event. |
| 261 | */ |
| 262 | private async processEventWithTimeout( |
| 263 | e: vscode.TextEditorSelectionChangeEvent, |
| 264 | ): Promise<void> { |
| 265 | this.isProcessingEvent = true; |
| 266 | |
| 267 | // Set up a timeout to prevent deadlocks. |
| 268 | const timeoutPromise = new Promise<void>((_, reject) => { |
| 269 | this.processingTimeout = setTimeout(() => { |
| 270 | reject(new Error("Selection change event processing timed out")); |
| 271 | }, this.PROCESSING_TIMEOUT); |
| 272 | }); |
| 273 | |
| 274 | try { |
| 275 | await Promise.race([this.processEvent(e), timeoutPromise]); |
| 276 | } finally { |
| 277 | // Clean up. |
| 278 | if (this.processingTimeout) { |
| 279 | clearTimeout(this.processingTimeout); |
| 280 | this.processingTimeout = null; |
| 281 | } |
| 282 | |
| 283 | this.isProcessingEvent = false; |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | /** |
| 288 | * Core event processing logic. |
| 289 | * @param e The selection change event. |
| 290 | */ |
| 291 | private async processEvent( |
| 292 | e: vscode.TextEditorSelectionChangeEvent, |
| 293 | ): Promise<void> { |
| 294 | const snapshot = this.captureState(e); |
| 295 | |
| 296 | for (const { handler } of this.listeners) { |
| 297 | try { |
| 298 | if (await handler(e, snapshot)) { |
| 299 | return; |
| 300 | } |
| 301 | } catch (err) { |
| 302 | console.error("Error in selection change handler:", err); |
| 303 | // Don't break just yet -- go to next handler. |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | private captureState( |
| 309 | e: vscode.TextEditorSelectionChangeEvent, |
| 310 | ): StateSnapshot { |
| 311 | return { |
| 312 | nextEditWindowAccepted: |
| 313 | NextEditWindowManager.isInstantiated() && |
| 314 | NextEditWindowManager.getInstance().hasAccepted(), |
| 315 | jumpInProgress: JumpManager.getInstance().isJumpInProgress(), |
| 316 | jumpJustAccepted: JumpManager.getInstance().wasJumpJustAccepted(), |
| 317 | lastDocumentChangeTime: this.lastDocumentChangeTime, |
| 318 | isTypingSession: this.isTypingSession, |
| 319 | document: e.textEditor.document, |
| 320 | cursorPosition: e.selections[0].active, |
| 321 | }; |
| 322 | } |
| 323 | |
| 324 | private async defaultFallbackHandler( |
| 325 | e: vscode.TextEditorSelectionChangeEvent, |
| 326 | state: StateSnapshot, |
| 327 | ): Promise<boolean> { |
| 328 | if (!this.ide) { |
| 329 | console.error("IDE not initialized in SelectionChangeManager"); |
| 330 | return false; |
| 331 | } |
| 332 | |
| 333 | console.log( |
| 334 | "defaultFallbackHandler: deleteChain called from onDidChangeTextEditorSelection", |
| 335 | ); |
| 336 | await NextEditProvider.getInstance().deleteChain(); |
| 337 | |
| 338 | if (!this.usingFullFileDiff) { |
| 339 | const nextEditableRegions = |
| 340 | (await getNextEditableRegion(EditableRegionStrategy.Static, { |
| 341 | cursorPosition: e.selections[0].anchor, |
| 342 | filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), |
| 343 | ide: this.ide, |
| 344 | })) ?? []; |
| 345 | // (await getNextEditableRegion(EditableRegionStrategy.Sliding, { |
| 346 | // filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), |
| 347 | // fileLines: e.textEditor.document.getText().split("\n"), |
| 348 | // })) ?? []; |
| 349 | |
| 350 | nextEditableRegions.forEach((region) => { |
| 351 | PrefetchQueue.getInstance().enqueueUnprocessed(region); |
| 352 | }); |
| 353 | } |
| 354 | |
| 355 | return true; |
| 356 | } |
| 357 | } |