-
Notifications
You must be signed in to change notification settings - Fork 34
/
ConanToolWindowControl.xaml.cs
421 lines (344 loc) · 16.5 KB
/
ConanToolWindowControl.xaml.cs
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
using System.Windows;
using System.Windows.Controls;
using System.Collections.Generic;
using System.Linq;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.VCProjectEngine;
using System.IO;
using System.Reflection;
using EnvDTE;
using Microsoft.VisualStudio.Threading;
using System.Windows.Navigation;
using System.Windows.Media;
using Microsoft.VisualStudio.PlatformUI;
namespace conan_vs_extension
{
public class Library
{
public string Description { get; set; }
public List<string> License { get; set; }
public List<string> Versions { get; set; }
}
public class RootObject
{
public Dictionary<string, Library> Libraries { get; set; }
}
public class Requirements
{
public Requirements(string[] requirements)
{
this.requirements = requirements;
}
public Requirements()
{
this.requirements = new string[] { };
}
public string[] requirements { get; set; }
}
/// <summary>
/// Interaction logic for ConanToolWindowControl.
/// </summary>
public partial class ConanToolWindowControl : UserControl
{
private DTE _dte;
private RootObject _jsonData;
/// <summary>
/// Initializes a new instance of the <see cref="ConanToolWindowControl"/> class.
/// </summary>
public ConanToolWindowControl()
{
this.InitializeComponent();
LibraryHeader.Visibility = Visibility.Collapsed;
this.Loaded += ConanToolWindowControl_Loaded;
ToggleUIEnableState(IsConanInitialized());
_ = InitializeAsync();
}
private void ConanToolWindowControl_Loaded(object sender, RoutedEventArgs e)
{
VSColorTheme.ThemeChanged += OnThemeChanged;
UpdateTheme();
}
private void OnThemeChanged(ThemeChangedEventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
UpdateTheme();
}
public void UpdateTheme()
{
ThreadHelper.ThrowIfNotOnUIThread();
var currentThemeColor = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowTextColorKey);
var currentColor = Color.FromRgb(currentThemeColor.R, currentThemeColor.G, currentThemeColor.B);
UpdateForeground(currentColor);
}
public void UpdateForeground(Color color)
{
var brush = new SolidColorBrush(color);
this.Foreground = brush;
ShowPackagesCheckbox.Foreground = brush;
LibraryNameLabel.Foreground = brush;
}
private async Task InitializeAsync()
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
_dte = (DTE)ServiceProvider.GlobalProvider.GetService(typeof(DTE));
if (_dte == null)
{
throw new InvalidOperationException("Cannot access DTE service.");
}
await CopyJsonFileFromResourceIfNeededAsync();
await LoadLibrariesFromJsonAsync();
}
private async Task CopyJsonFileFromResourceIfNeededAsync()
{
string userConanFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".conan-vs-extension");
string jsonFilePath = Path.Combine(userConanFolder, "targets-data.json");
if (!File.Exists(jsonFilePath))
{
if (!Directory.Exists(userConanFolder))
{
Directory.CreateDirectory(userConanFolder);
}
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "conan_vs_extension.Resources.targets-data.json";
using (var stream = assembly.GetManifestResourceStream(resourceName))
using (var reader = new StreamReader(stream))
{
string jsonContent = await reader.ReadToEndAsync();
using (var writer = new StreamWriter(jsonFilePath))
{
await writer.WriteAsync(jsonContent);
}
}
}
}
private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
FilterListView(LibrarySearchTextBox.Text, ShowPackagesCheckbox.IsChecked ?? false);
}
private async Task LoadLibrariesFromJsonAsync()
{
string userConanFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".conan-vs-extension");
string jsonFilePath = Path.Combine(userConanFolder, "targets-data.json");
string json = await Task.Run(() => File.ReadAllText(jsonFilePath));
_jsonData = JsonConvert.DeserializeObject<RootObject>(json);
await ThreadHelper.JoinableTaskFactory.RunAsync(async delegate {
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
PackagesListView.Items.Clear();
foreach (var library in _jsonData.Libraries.Keys)
{
PackagesListView.Items.Add(library);
}
});
}
private void FilterListView(string searchText, bool onlyInstalled)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (_jsonData == null || _jsonData.Libraries == null) return;
PackagesListView.Items.Clear();
var filteredLibraries = _jsonData.Libraries
.Where(kv => kv.Key.Contains(searchText))
.ToList();
Project startupProject = ProjectConfigurationManager.GetStartupProject(_dte);
if (onlyInstalled && startupProject != null && startupProject.Object is VCProject vcProject)
{
string projectFilePath = startupProject.FullName;
string projectDirectory = Path.GetDirectoryName(projectFilePath);
var requirements = ConanFileManager.GetConandataRequirements(projectDirectory);
foreach (var requirement in requirements)
{
string key = requirement.Split('/')[0];
if (filteredLibraries.Any(library => library.Key == key))
{
PackagesListView.Items.Add(key);
}
}
}
else
{
foreach (var library in filteredLibraries)
{
PackagesListView.Items.Add(library.Key);
}
}
}
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (PackagesListView.SelectedItem is string selectedItem)
{
UpdateLibraryInfo(selectedItem);
}
}
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
System.Diagnostics.Process.Start(e.Uri.AbsoluteUri);
e.Handled = true;
}
public void UpdatePanel(string name, string description, string licenses, List<string> versions)
{
ThreadHelper.ThrowIfNotOnUIThread();
LibraryNameLabel.Content = name;
VersionsComboBox.ItemsSource = versions;
VersionsComboBox.SelectedIndex = 0;
DescriptionTextBlock.Text = description ?? "No description available.";
LicenseText.Text = licenses ?? "No description available.";
MoreInfoHyperlink.NavigateUri = new Uri($"https://conan.io/center/recipes/{name}");
GitHubRecipeLink.NavigateUri = new Uri($"https://github.com/conan-io/conan-center-index/tree/master/recipes/{name}");
Project startupProject = ProjectConfigurationManager.GetStartupProject(_dte);
if (startupProject != null && startupProject.Object is VCProject vcProject)
{
string projectFilePath = startupProject.FullName;
string projectDirectory = Path.GetDirectoryName(projectFilePath);
var requirements = ConanFileManager.GetConandataRequirements(projectDirectory);
bool isInstalled = requirements.Any(e => e.StartsWith(name + "/"));
InstallButton.Visibility = isInstalled ? Visibility.Collapsed : Visibility.Visible;
RemoveButton.Visibility = isInstalled ? Visibility.Visible : Visibility.Collapsed;
VersionsComboBox.IsEnabled = !isInstalled;
LibraryHeader.Visibility = Visibility.Visible;
UnsupportedProjectType.Visibility = Visibility.Collapsed;
}
else
{
LibraryHeader.Visibility = Visibility.Collapsed;
UnsupportedProjectType.Visibility = Visibility.Visible;
}
}
private void InstallButton_Click(object sender, RoutedEventArgs e)
{
var selectedLibrary = LibraryNameLabel.Content.ToString();
var selectedVersion = VersionsComboBox.SelectedItem.ToString();
ThreadHelper.ThrowIfNotOnUIThread();
Project startupProject = ProjectConfigurationManager.GetStartupProject(_dte);
if (startupProject.Object is VCProject)
{
string projectFilePath = startupProject.FullName;
string projectDirectory = Path.GetDirectoryName(projectFilePath);
ConanFileManager.ReCreateConanfile(projectDirectory);
string conandataPath = Path.Combine(projectDirectory, "conandata.yml");
if (!File.Exists(conandataPath)) {
ConanFileManager.ReCreateConanData(projectDirectory);
}
if (ConanFileManager.IsFileCommentGuarded(conandataPath)) {
ConanFileManager.WriteNewRequirement(projectDirectory, selectedLibrary + "/" + selectedVersion);
MessageBox.Show($"Requirement {selectedLibrary}/{selectedVersion} added to conandata.yml", "Conan C/C++ Package Manager");
InstallButton.Visibility = Visibility.Collapsed;
RemoveButton.Visibility = Visibility.Visible;
VersionsComboBox.IsEnabled = false;
}
else {
MessageBox.Show($"Requirement {selectedLibrary}/{selectedVersion} could not be added to conandata.yml because it was modified. Please, update the file manually.",
"Conan C/C++ Package Manager",
MessageBoxButton.OK,
MessageBoxImage.Warning);
}
_ = ProjectConfigurationManager.SaveConanPrebuildEventsAllConfigAsync(startupProject);
FilterListView(LibrarySearchTextBox.Text, ShowPackagesCheckbox.IsChecked ?? false);
}
}
private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
var selectedLibrary = LibraryNameLabel.Content.ToString();
var selectedVersion = VersionsComboBox.SelectedItem.ToString();
ThreadHelper.ThrowIfNotOnUIThread();
Array activeSolutionProjects = _dte.ActiveSolutionProjects as Array;
Project activeProject = activeSolutionProjects.GetValue(0) as Project;
string projectFilePath = activeProject.FullName;
string projectDirectory = Path.GetDirectoryName(projectFilePath);
string conandataPath = Path.Combine(projectDirectory, "conandata.yml");
if (ConanFileManager.IsFileCommentGuarded(conandataPath)) {
ConanFileManager.RemoveRequirement(projectDirectory, selectedLibrary + "/" + selectedVersion);
MessageBox.Show($"Removing {selectedLibrary} version {selectedVersion}", "Conan C/C++ Package Manager");
InstallButton.Visibility = Visibility.Visible;
RemoveButton.Visibility = Visibility.Collapsed;
VersionsComboBox.IsEnabled = true;
}
else {
MessageBox.Show($"Requirement {selectedLibrary}/{selectedVersion} could not be removed from conandata.yml because it was modified. Please, update the file manually.",
"Conan C/C++ Package Manager",
MessageBoxButton.OK,
MessageBoxImage.Warning);
}
FilterListView(LibrarySearchTextBox.Text, ShowPackagesCheckbox.IsChecked ?? false);
}
private void UpdateLibraryInfo(string name)
{
if (_jsonData != null && _jsonData.Libraries.ContainsKey(name))
{
var library = _jsonData.Libraries[name];
var versions = library.Versions;
var description = library.Description ?? "No description available.";
var licenses = library.License != null ? string.Join(", ", library.License) : "No license information.";
UpdatePanel(name, description, licenses, versions);
}
}
/// <summary>
/// Handles click on the button by displaying a message box.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void ShowConfigurationDialog()
{
ThreadHelper.ThrowIfNotOnUIThread();
_dte.ExecuteCommand("Tools.Options", GuidList.strConanOptionsPage);
}
private bool IsConanInitialized()
{
return !string.IsNullOrEmpty(GlobalSettings.ConanExecutablePath);
}
private void ToggleUIEnableState(bool enabled)
{
LibrarySearchTextBox.IsEnabled = enabled;
ShowPackagesCheckbox.IsEnabled = enabled;
UpdateButton.IsEnabled = enabled;
PackagesListView.IsEnabled = enabled;
LibraryHeader.IsEnabled = enabled;
if (!enabled)
{
LibrarySearchTextBox.Text = "Click 'configure' to set the Conan path -->";
}
else
{
LibrarySearchTextBox.Text = "";
}
}
private void Configuration_Click(object sender, RoutedEventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
ShowConfigurationDialog();
ToggleUIEnableState(IsConanInitialized());
}
private void ShowPackagesCheckbox_Click(object sender, RoutedEventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
FilterListView(LibrarySearchTextBox.Text, ShowPackagesCheckbox.IsChecked ?? false);
}
private async Task UpdateJsonDataAsync()
{
string jsonUrl = "https://raw.githubusercontent.com/conan-io/conan-clion-plugin/develop2/src/main/resources/conan/targets-data.json";
string userConanFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".conan-vs-extension");
string jsonFilePath = Path.Combine(userConanFolder, "targets-data.json");
try
{
using (var httpClient = new HttpClient())
{
string jsonContent = await httpClient.GetStringAsync(jsonUrl);
File.WriteAllText(jsonFilePath, jsonContent);
MessageBox.Show("ConanCenter libraries data file updated. Please restart Visual Studio for the changes to take effect.", "Conan C/C++ Package Manager", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"Error updating: {ex.Message}", "Error - Conan C/C++ Package Manager", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void Update_Click(object sender, RoutedEventArgs e)
{
_ = UpdateJsonDataAsync();
}
}
}