| 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 | export class SelectionChangeManager { |
| 111 | private static instance: SelectionChangeManager; |
| 112 | private listeners: HandlerRegistration[] = []; |
| 113 | private ide: VsCodeIde | null = null; |
| 114 | private usingFullFileDiff: boolean = true; |
| 115 | |
| 116 | // Event bus-related attributes. |
| 117 | private eventQueue: vscode.TextEditorSelectionChangeEvent[] = []; |
| 118 | private lastEventTime = 0; |
| 119 | private isProcessingEvent = false; |
| 120 | private processingTimeout: NodeJS.Timeout | null = null; |
| 121 | |
| 122 | // Debounce settings. |
| 123 | private readonly DEBOUNCE_DELAY = 50; |
| 124 | private readonly PROCESSING_TIMEOUT = 500; |
| 125 | |
| 126 | // Track typing session state. |
| 127 | private isTypingSession = false; |
| 128 | private typingTimer: NodeJS.Timeout | null = null; |
| 129 | private lastDocumentChangeTime = 0; |
| 130 | private readonly TYPING_SESSION_TIMEOUT = 2000; // ms |
| 131 | |
| 132 | private constructor() {} |
| 133 | |
| 134 | public static getInstance() { |
| 135 | if (!SelectionChangeManager.instance) { |
| 136 | SelectionChangeManager.instance = new SelectionChangeManager(); |
| 137 | } |
| 138 | return SelectionChangeManager.instance; |
| 139 | } |
| 140 | |
| 141 | public initialize(ide: VsCodeIde, usingFullFileDiff: boolean): void { |
| 142 | this.ide = ide; |
| 143 | this.usingFullFileDiff = usingFullFileDiff; |
| 144 | |
| 145 | // After handling all other listeners, this will delete the chain. |
| 146 | this.registerListener( |
| 147 | "defaultFallbackHandler", |
| 148 | this.defaultFallbackHandler.bind(this), |
| 149 | HandlerPriority.FALLBACK, |
| 150 | ); |
| 151 | } |
| 152 | |
| 153 | public documentChanged(): void { |
| 154 | this.isTypingSession = true; |
| 155 | this.lastDocumentChangeTime = Date.now(); |
| 156 | this.resetTypingSession(); |
| 157 | } |
| 158 | |
| 159 | private resetTypingSession(): void { |
| 160 | if (this.typingTimer) { |
| 161 | clearTimeout(this.typingTimer); |
| 162 | } |
| 163 | this.typingTimer = setTimeout(() => { |
| 164 | this.isTypingSession = false; |
| 165 | }, this.TYPING_SESSION_TIMEOUT); |
| 166 | } |
| 167 | |
| 168 | /** |
| 169 | * Register a listener for the selection change event. |
| 170 | * @param id Unique id for this handler. |
| 171 | * @param handler Function to handle the event. |
| 172 | * @param priority Higher priority runs first. |
| 173 | * @returns Function to unregister this listener. |
| 174 | */ |
| 175 | public registerListener( |
| 176 | id: string, |
| 177 | handler: SelectionChangeHandler, |
| 178 | priority: HandlerPriority = HandlerPriority.NORMAL, |
| 179 | ): () => void { |
| 180 | // Remove any existing handler with the same id. |
| 181 | this.listeners = this.listeners.filter((l) => l.id !== id); |
| 182 | |
| 183 | // Add the new handler. |
| 184 | this.listeners.push({ id, priority, handler }); |
| 185 | |
| 186 | // Sort by desc priority. |
| 187 | this.listeners.sort((a, b) => b.priority - a.priority); |
| 188 | |
| 189 | // Return the unregister function. |
| 190 | return () => { |
| 191 | this.listeners = this.listeners.filter((l) => l.id !== id); |
| 192 | }; |
| 193 | } |
| 194 | |
| 195 | /** |
| 196 | * Handle a given selection change event. |
| 197 | * @param e THe selection change event. |
| 198 | */ |
| 199 | public async handleSelectionChange( |
| 200 | e: vscode.TextEditorSelectionChangeEvent, |
| 201 | ): Promise<void> { |
| 202 | const now = Date.now(); |
| 203 | |
| 204 | // Simple debouncing logic. |
| 205 | // Ignore events that come too quickly after the previous one. |
| 206 | // TODO: test this. |
| 207 | if (now - this.lastEventTime < this.DEBOUNCE_DELAY) { |
| 208 | // Replace the queued event with the most recent one. |
| 209 | if (this.eventQueue.length > 0) { |
| 210 | this.eventQueue[this.eventQueue.length - 1] = e; |
| 211 | } else { |
| 212 | this.eventQueue.push(e); |
| 213 | } |
| 214 | |
| 215 | return; |
| 216 | } |
| 217 | |
| 218 | this.lastEventTime = now; |
| 219 | |
| 220 | // Queue this event for later if the manager is already processing an event. |
| 221 | // NOTE: Depending on if we want an event bus or not, do an early return instead. |
| 222 | if (this.isProcessingEvent) { |
| 223 | this.eventQueue.push(e); |
| 224 | return; |
| 225 | } |
| 226 | |
| 227 | try { |
| 228 | // Process this event first. |
| 229 | await this.processEventWithTimeout(e); |
| 230 | |
| 231 | // Process remaining queued events sequentially. |
| 232 | // NOTE: Depending on if we want an event bus or not, skip this. |
| 233 | while (this.eventQueue.length > 0) { |
| 234 | const nextEvent = this.eventQueue.shift()!; |
| 235 | await this.processEventWithTimeout(nextEvent); |
| 236 | } |
| 237 | } catch (err) { |
| 238 | console.error("Error processing selection change event:", err); |
| 239 | this.isProcessingEvent = false; |
| 240 | if (this.processingTimeout) { |
| 241 | clearTimeout(this.processingTimeout); |
| 242 | this.processingTimeout = null; |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | /** |
| 248 | * Process a given event with a timeout. |
| 249 | * This is in attempt to prevent deadlocks between events. |
| 250 | * @param e The selection change event. |
| 251 | */ |
| 252 | private async processEventWithTimeout( |
| 253 | e: vscode.TextEditorSelectionChangeEvent, |
| 254 | ): Promise<void> { |
| 255 | this.isProcessingEvent = true; |
| 256 | |
| 257 | // Set up a timeout to prevent deadlocks. |
| 258 | const timeoutPromise = new Promise<void>((_, reject) => { |
| 259 | this.processingTimeout = setTimeout(() => { |
| 260 | reject(new Error("Selection change event processing timed out")); |
| 261 | }, this.PROCESSING_TIMEOUT); |
| 262 | }); |
| 263 | |
| 264 | try { |
| 265 | await Promise.race([this.processEvent(e), timeoutPromise]); |
| 266 | } finally { |
| 267 | // Clean up. |
| 268 | if (this.processingTimeout) { |
| 269 | clearTimeout(this.processingTimeout); |
| 270 | this.processingTimeout = null; |
| 271 | } |
| 272 | |
| 273 | this.isProcessingEvent = false; |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | /** |
| 278 | * Core event processing logic. |
| 279 | * @param e The selection change event. |
| 280 | */ |
| 281 | private async processEvent( |
| 282 | e: vscode.TextEditorSelectionChangeEvent, |
| 283 | ): Promise<void> { |
| 284 | const snapshot = this.captureState(e); |
| 285 | |
| 286 | for (const { handler } of this.listeners) { |
| 287 | try { |
| 288 | if (await handler(e, snapshot)) { |
| 289 | return; |
| 290 | } |
| 291 | } catch (err) { |
| 292 | console.error("Error in selection change handler:", err); |
| 293 | // Don't break just yet -- go to next handler. |
| 294 | } |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | private captureState( |
| 299 | e: vscode.TextEditorSelectionChangeEvent, |
| 300 | ): StateSnapshot { |
| 301 | return { |
| 302 | nextEditWindowAccepted: |
| 303 | NextEditWindowManager.isInstantiated() && |
| 304 | NextEditWindowManager.getInstance().hasAccepted(), |
| 305 | jumpInProgress: JumpManager.getInstance().isJumpInProgress(), |
| 306 | jumpJustAccepted: JumpManager.getInstance().wasJumpJustAccepted(), |
| 307 | lastDocumentChangeTime: this.lastDocumentChangeTime, |
| 308 | isTypingSession: this.isTypingSession, |
| 309 | document: e.textEditor.document, |
| 310 | cursorPosition: e.selections[0].active, |
| 311 | }; |
| 312 | } |
| 313 | |
| 314 | private async defaultFallbackHandler( |
| 315 | e: vscode.TextEditorSelectionChangeEvent, |
| 316 | state: StateSnapshot, |
| 317 | ): Promise<boolean> { |
| 318 | if (!this.ide) { |
| 319 | console.error("IDE not initialized in SelectionChangeManager"); |
| 320 | return false; |
| 321 | } |
| 322 | |
| 323 | console.log( |
| 324 | "defaultFallbackHandler: deleteChain called from onDidChangeTextEditorSelection", |
| 325 | ); |
| 326 | await NextEditProvider.getInstance().deleteChain(); |
| 327 | |
| 328 | if (!this.usingFullFileDiff) { |
| 329 | const nextEditableRegions = |
| 330 | (await getNextEditableRegion(EditableRegionStrategy.Static, { |
| 331 | cursorPosition: e.selections[0].anchor, |
| 332 | filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), |
| 333 | ide: this.ide, |
| 334 | })) ?? []; |
| 335 | // (await getNextEditableRegion(EditableRegionStrategy.Sliding, { |
| 336 | // filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), |
| 337 | // fileLines: e.textEditor.document.getText().split("\n"), |
| 338 | // })) ?? []; |
| 339 | |
| 340 | nextEditableRegions.forEach((region) => { |
| 341 | PrefetchQueue.getInstance().enqueueUnprocessed(region); |
| 342 | }); |
| 343 | } |
| 344 | |
| 345 | return true; |
| 346 | } |
| 347 | } |