-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathClaudeCodeControl.Cleanup.cs
More file actions
359 lines (319 loc) · 14.4 KB
/
ClaudeCodeControl.Cleanup.cs
File metadata and controls
359 lines (319 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/* *******************************************************************************************************************
* Application: ClaudeCodeExtension
*
* Autor: Daniel Carvalho Liedke
*
* Copyright © Daniel Carvalho Liedke 2026
* Usage and reproduction in any manner whatsoever without the written permission of Daniel Carvalho Liedke is strictly forbidden.
*
* Purpose: Resource cleanup and temporary file management
*
* *******************************************************************************************************************/
using System;
using System.IO;
using System.Diagnostics;
using System.Windows;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace ClaudeCodeVS
{
public partial class ClaudeCodeControl
{
#region Temporary Directory Fields
/// <summary>
/// Session-specific temporary directory for storing pasted images
/// </summary>
private string tempImageDirectory;
#endregion
#region Temporary Directory Initialization
/// <summary>
/// Initializes the temporary directory for storing pasted images
/// Cleans up any existing ClaudeCodeVS temp directories first
/// </summary>
private void InitializeTempDirectory()
{
try
{
string sessionRootPath = Path.Combine(Path.GetTempPath(), "ClaudeCodeVS_Session");
tempImageDirectory = Path.Combine(sessionRootPath, Guid.NewGuid().ToString());
Directory.CreateDirectory(tempImageDirectory);
// Cleanup old temp folders in the background so control construction does not stall the UI thread.
_ = System.Threading.Tasks.Task.Run(() => CleanupClaudeCodeVSTempDirectories(tempImageDirectory));
}
catch (Exception ex)
{
Debug.WriteLine($"Error creating temp directory: {ex.Message}");
// Fallback to a simpler path
tempImageDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempImageDirectory);
}
}
/// <summary>
/// Cleans up all ClaudeCodeVS temporary directories from previous sessions
/// </summary>
/// <param name="currentSessionDirectory">Current live session directory to preserve</param>
private void CleanupClaudeCodeVSTempDirectories(string currentSessionDirectory = null)
{
try
{
string tempPath = Path.GetTempPath();
string currentSessionFullPath = string.IsNullOrEmpty(currentSessionDirectory)
? null
: Path.GetFullPath(currentSessionDirectory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
// Clean up old ClaudeCodeVS directories
string claudeCodeVSPath = Path.Combine(tempPath, "ClaudeCodeVS");
if (Directory.Exists(claudeCodeVSPath))
{
Directory.Delete(claudeCodeVSPath, true);
}
// Clean up session directories
string sessionPath = Path.Combine(tempPath, "ClaudeCodeVS_Session");
if (Directory.Exists(sessionPath))
{
foreach (string sessionDirectory in Directory.GetDirectories(sessionPath))
{
string fullSessionPath = Path.GetFullPath(sessionDirectory)
.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (string.Equals(fullSessionPath, currentSessionFullPath, StringComparison.OrdinalIgnoreCase))
{
continue;
}
Directory.Delete(sessionDirectory, true);
}
foreach (string sessionFile in Directory.GetFiles(sessionPath))
{
File.Delete(sessionFile);
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error cleaning up ClaudeCodeVS temp directories: {ex.Message}");
// Continue even if cleanup fails
}
}
#endregion
#region Unload and Cleanup
/// <summary>
/// Handles control unload event - keeps terminal alive for tab switches
/// </summary>
private void ClaudeCodeControl_Unloaded(object sender, RoutedEventArgs e)
{
// Don't save during unload - settings should only be saved when user makes changes
// NOTE: Don't cleanup terminal here - Unloaded fires during tab switches
// Terminal cleanup only happens in Dispose() when VS is actually closing
}
/// <summary>
/// Cleans up all resources including processes and temporary files.
/// UI-bound work (event unsubscription, window closing) runs on the UI thread.
/// Heavy work (process tree termination, temp directory deletion) is offloaded
/// to a background thread to avoid blocking VS during shutdown.
/// </summary>
private void CleanupResources()
{
ThreadHelper.ThrowIfNotOnUIThread();
try
{
// Persist the latest UI state before tearing down the control.
SaveSettings();
// Cleanup diff tracking
CleanupDiffTracking();
// Unsubscribe from theme change events
CleanupThemeEvents();
// Unsubscribe from tool window frame notifications
if (_toolWindow != null)
{
_toolWindow.FrameShow -= OnToolWindowFrameShow;
}
// Uninstall the low-level mouse hook used for zoom tracking
UninstallMouseHook();
// Uninstall the low-level keyboard hook used for F5/Ctrl+F5 interception
UninstallKeyboardHook();
// Cleanup detached terminal window
if (_isTerminalDetached && _detachedTerminalWindow != null)
{
try
{
// Re-parent terminal back to main panel before killing
if (terminalHandle != IntPtr.Zero && IsWindow(terminalHandle) && terminalPanel != null)
{
SetParent(terminalHandle, terminalPanel.Handle);
}
// Unwire events
if (_detachedClosedSubscribed)
{
_detachedTerminalWindow.Closed -= OnDetachedWindowClosed;
_detachedClosedSubscribed = false;
}
if (_detachedVisibilitySubscribed)
{
_detachedTerminalWindow.VisibilityChanged -= OnDetachedVisibilityChanged;
_detachedVisibilitySubscribed = false;
}
if (_detachedTerminalPanel != null)
{
_detachedTerminalPanel.Resize -= DetachedPanel_Resize;
}
// Close the detached window frame
if (_detachedTerminalWindow.Frame is IVsWindowFrame windowFrame)
{
windowFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
}
_detachedTerminalPanel = null;
_detachedTerminalWindow = null;
_isTerminalDetached = false;
}
catch (Exception ex)
{
Debug.WriteLine($"Error cleaning up detached terminal: {ex.Message}");
}
}
// Capture process info while still on UI thread (Win32 calls require it)
int terminalWindowProcessId = 0;
bool isWindowsTerminal = false;
if (terminalHandle != IntPtr.Zero && IsWindow(terminalHandle))
{
GetWindowThreadProcessId(terminalHandle, out uint terminalWindowPid);
terminalWindowProcessId = (int)terminalWindowPid;
isWindowsTerminal = IsWindowsTerminalProcess(terminalWindowProcessId);
PostMessage(terminalHandle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
int cmdProcessId = 0;
Process cmdProcessRef = cmdProcess;
if (cmdProcessRef != null)
{
try
{
cmdProcessId = cmdProcessRef.Id;
}
catch (InvalidOperationException)
{
// Process already exited
}
}
cmdProcess = null;
string tempDir = tempImageDirectory;
// Clear attached images list
attachedImagePaths?.Clear();
// Offload heavy process termination and temp directory cleanup to background thread
int currentVsProcessId = Process.GetCurrentProcess().Id;
_ = System.Threading.Tasks.Task.Run(() =>
{
try
{
var terminatedProcessIds = new System.Collections.Generic.HashSet<int>();
if (cmdProcessId > 0)
{
try
{
TryTerminateProcessTree(cmdProcessId, terminatedProcessIds);
}
catch (Exception ex)
{
Debug.WriteLine($"Error terminating terminal launcher process tree: {ex.Message}");
}
}
if (cmdProcessRef != null)
{
try
{
cmdProcessRef.Dispose();
}
catch (Exception ex)
{
Debug.WriteLine($"Error disposing terminal launcher process: {ex.Message}");
}
}
// Skip killing the WindowsTerminal.exe process tree — it is a shared
// host for ALL WT windows. WM_CLOSE (sent above) closes only our window.
if (terminalWindowProcessId > 0 &&
terminalWindowProcessId != currentVsProcessId &&
!isWindowsTerminal)
{
TryTerminateProcessTree(terminalWindowProcessId, terminatedProcessIds);
}
// Clean up temporary directory
if (!string.IsNullOrEmpty(tempDir) && Directory.Exists(tempDir))
{
try
{
Directory.Delete(tempDir, true);
}
catch (Exception ex)
{
Debug.WriteLine($"Error cleaning temp directory: {ex.Message}");
try
{
foreach (string file in Directory.GetFiles(tempDir))
{
File.Delete(file);
}
}
catch { }
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error during background cleanup: {ex.Message}");
}
});
}
catch (Exception ex)
{
Debug.WriteLine($"Error during cleanup: {ex.Message}");
}
}
/// <summary>
/// Kills a process and all its child processes using ToolHelp32 snapshots.
/// ToolHelp32 is a kernel-level snapshot API (sub-millisecond) and avoids the
/// significant overhead of WMI queries (which can take 1-5 seconds each).
/// </summary>
/// <param name="processId">The process ID to kill</param>
private void KillProcessAndChildren(int processId)
{
try
{
// Use ToolHelp32 snapshot to find child processes (sub-ms, no WMI dependency)
var childPids = GetChildProcessIds((uint)processId);
foreach (uint childPid in childPids)
{
try
{
// Recursively kill children of this child
KillProcessAndChildren((int)childPid);
// Kill the child process
using (var childProcess = Process.GetProcessById((int)childPid))
{
if (!childProcess.HasExited)
{
childProcess.Kill();
}
}
}
catch (ArgumentException)
{
// Process already exited
}
catch (Exception ex)
{
Debug.WriteLine($"Error killing child process {childPid}: {ex.Message}");
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error in KillProcessAndChildren: {ex.Message}");
}
}
/// <summary>
/// Implements IDisposable - disposes of all managed resources
/// </summary>
public void Dispose()
{
ThreadHelper.ThrowIfNotOnUIThread();
CleanupResources();
}
#endregion
}
}