-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathClaudeCodeExtensionPackage.cs
More file actions
304 lines (268 loc) · 12.7 KB
/
ClaudeCodeExtensionPackage.cs
File metadata and controls
304 lines (268 loc) · 12.7 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
/* *******************************************************************************************************************
* 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: Main package class for the Claude Code extension for VS.NET
*
* *******************************************************************************************************************/
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio;
using Newtonsoft.Json;
using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Task = System.Threading.Tasks.Task;
namespace ClaudeCodeExtension
{
/// <summary>
/// This is the class that implements the package exposed by this assembly.
/// </summary>
/// <remarks>
/// <para>
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell. These attributes tell the pkgdef creation
/// utility what data to put into .pkgdef file.
/// </para>
/// <para>
/// To get loaded into VS, the package must be referred by <Asset Type="Microsoft.VisualStudio.VsPackage" ...> in .vsixmanifest file.
/// </para>
/// </remarks>
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExists_string, PackageAutoLoadFlags.BackgroundLoad)]
[ProvideToolWindow(typeof(ClaudeCodeVS.ClaudeCodeToolWindow))]
[ProvideToolWindow(typeof(ClaudeCodeVS.DiffViewerToolWindow), Transient = true)]
[ProvideToolWindow(typeof(ClaudeCodeVS.DetachedTerminalToolWindow), Transient = true)]
[ProvideToolWindow(typeof(ClaudeCodeVS.ClaudeUsageToolWindow), Transient = true)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[Guid(ClaudeCodeExtensionPackage.PackageGuidString)]
public sealed class ClaudeCodeExtensionPackage : AsyncPackage
{
/// <summary>
/// ClaudeCodeExtensionPackage GUID string.
/// </summary>
public const string PackageGuidString = "3fa29425-3add-418f-82f6-0c9b7419b2ca";
/// <summary>
/// Command set GUID and command IDs.
/// </summary>
public static readonly Guid CommandSet = new Guid("11111111-2222-3333-4444-555555555555");
public const int ClaudeCodeToolWindowCommandId = 0x0100;
public const int EditorSendSelectionCommandId = 0x0201;
private const string ConfigurationFileName = "claudecode-settings.json";
private static readonly string ConfigurationPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"ClaudeCodeExtension",
ConfigurationFileName);
private ClaudeCodeVS.ClaudeUsageToolWindow _autoReopenedUsageWindow;
#region Package Members
/// <summary>
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initialization code that rely on services provided by VisualStudio.
/// </summary>
/// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param>
/// <param name="progress">A provider for progress updates.</param>
/// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns>
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
// When initialized asynchronously, the current thread may be a background thread at this point.
// Do any initialization that requires the UI thread after switching to the UI thread.
await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
// Add command handler for the tool window
var commandService = await GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
if (commandService != null)
{
var menuCommandID = new CommandID(CommandSet, ClaudeCodeToolWindowCommandId);
var menuItem = new MenuCommand(this.ShowToolWindow, menuCommandID);
commandService.AddCommand(menuItem);
// Add command handler for "Send Selection to Claude Code" editor context menu
var editorCmdId = new CommandID(CommandSet, EditorSendSelectionCommandId);
var editorMenuItem = new OleMenuCommand(this.OnEditorSendSelection, editorCmdId);
editorMenuItem.BeforeQueryStatus += OnEditorSendSelectionQueryStatus;
commandService.AddCommand(editorMenuItem);
}
ScheduleUsageWindowRestore(cancellationToken);
}
private void ScheduleUsageWindowRestore(CancellationToken cancellationToken)
{
var settings = LoadSettingsForStartup();
if (settings?.UsageWindowOpened != true)
{
return;
}
#pragma warning disable VSSDK007 // Fire-and-forget is intentional; startup restore should not block package load
_ = JoinableTaskFactory.RunAsync(async delegate
{
try
{
await Task.Delay(750, cancellationToken);
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
_autoReopenedUsageWindow = FindToolWindow(
typeof(ClaudeCodeVS.ClaudeUsageToolWindow),
0,
true) as ClaudeCodeVS.ClaudeUsageToolWindow;
if (_autoReopenedUsageWindow?.Frame == null)
{
return;
}
if (_autoReopenedUsageWindow.UsageControl != null)
{
_autoReopenedUsageWindow.UsageControl.ApplyAutoRefreshSeconds(settings.UsageAutoRefreshSeconds);
}
_autoReopenedUsageWindow.ClosedByUser -= OnAutoReopenedUsageWindowClosed;
_autoReopenedUsageWindow.ClosedByUser += OnAutoReopenedUsageWindowClosed;
var frame = (IVsWindowFrame)_autoReopenedUsageWindow.Frame;
ErrorHandler.ThrowOnFailure(frame.Show());
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
Debug.WriteLine("Error restoring Claude usage window: " + ex);
}
});
#pragma warning restore VSSDK007
}
private void OnAutoReopenedUsageWindowClosed(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
try
{
var settings = LoadSettingsForStartup();
if (settings == null || !settings.UsageWindowOpened)
{
return;
}
settings.UsageWindowOpened = false;
SaveSettingsFromPackage(settings);
}
catch (Exception ex)
{
Debug.WriteLine("Error saving Claude usage close state: " + ex);
}
}
private static ClaudeCodeVS.ClaudeCodeSettings LoadSettingsForStartup()
{
try
{
if (!File.Exists(ConfigurationPath))
{
return null;
}
string json = File.ReadAllText(ConfigurationPath);
var settings = JsonConvert.DeserializeObject<ClaudeCodeVS.ClaudeCodeSettings>(json);
if (settings == null)
{
return null;
}
if (!Enum.IsDefined(typeof(ClaudeCodeVS.AiProvider), settings.SelectedProvider))
{
settings.SelectedProvider = ClaudeCodeVS.AiProvider.ClaudeCode;
}
return settings;
}
catch (Exception ex)
{
Debug.WriteLine("Error loading Claude usage startup settings: " + ex);
return null;
}
}
private static void SaveSettingsFromPackage(ClaudeCodeVS.ClaudeCodeSettings settings)
{
try
{
string directory = Path.GetDirectoryName(ConfigurationPath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string json = JsonConvert.SerializeObject(settings, Formatting.Indented);
File.WriteAllText(ConfigurationPath, json);
}
catch (Exception ex)
{
Debug.WriteLine("Error saving Claude usage startup settings: " + ex);
}
}
/// <summary>
/// Checks if there is a text selection in the active editor to enable/disable the context menu item.
/// </summary>
private void OnEditorSendSelectionQueryStatus(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
var cmd = (OleMenuCommand)sender;
try
{
var dte = GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
var sel = dte?.ActiveDocument?.Selection as EnvDTE.TextSelection;
bool hasSelection = sel != null && !string.IsNullOrEmpty(sel.Text);
cmd.Visible = true;
cmd.Enabled = hasSelection;
}
catch
{
cmd.Visible = true;
cmd.Enabled = false;
}
}
/// <summary>
/// Handles the "Send Selection to Claude Code" editor context menu command.
/// Extracts the selected text, file path, and line numbers, then inserts into the prompt.
/// </summary>
private void OnEditorSendSelection(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
try
{
var dte = GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
var sel = dte?.ActiveDocument?.Selection as EnvDTE.TextSelection;
if (sel == null || string.IsNullOrEmpty(sel.Text))
return;
string code = sel.Text;
string filePath = dte.ActiveDocument.FullName;
int startLine = sel.TopLine;
int endLine = sel.BottomLine;
// Ensure tool window is visible
ToolWindowPane window = FindToolWindow(typeof(ClaudeCodeVS.ClaudeCodeToolWindow), 0, true);
if (window?.Frame == null)
return;
IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());
// Insert snippet into the prompt
var toolWindow = window as ClaudeCodeVS.ClaudeCodeToolWindow;
toolWindow?.InsertCodeSnippet(code, filePath, startLine, endLine);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error sending selection to Claude Code: {ex.Message}");
}
}
/// <summary>
/// Shows the tool window when the menu item is clicked.
/// </summary>
private void ShowToolWindow(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
// Get the instance of the tool window
ToolWindowPane window = FindToolWindow(typeof(ClaudeCodeVS.ClaudeCodeToolWindow), 0, true);
if ((null == window) || (null == window.Frame))
{
throw new NotSupportedException("Cannot create tool window");
}
IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());
}
#endregion
}
}