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
|
// CompositionManager.cs
//
// Author:
// Kirill Osenkov <https://github.com/KirillOsenkov>
//
// Copyright (c) 2017 Microsoft
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Composition;
using Mono.Addins;
using MonoDevelop.Core;
using MonoDevelop.Core.AddIns;
using MonoDevelop.Core.Instrumentation;
namespace MonoDevelop.Ide.Composition
{
/// <summary>
/// The host of the MonoDevelop MEF composition. Uses https://github.com/Microsoft/vs-mef.
/// </summary>
[DefaultServiceImplementation]
public partial class CompositionManager: Service
{
static CompositionManager instance;
static readonly Resolver StandardResolver = Resolver.DefaultInstance;
static readonly PartDiscovery Discovery = PartDiscovery.Combine (
new AttributedPartDiscoveryV1 (StandardResolver),
new AttributedPartDiscovery (StandardResolver, true));
public static CompositionManager Instance {
get {
if (instance == null) {
var task = Runtime.GetService<CompositionManager> ();
if (!task.IsCompleted && Runtime.IsMainThread) {
LoggingService.LogWarning ("UI thread queried MEF while it was still being built:{0}{1}", Environment.NewLine, Environment.StackTrace);
}
instance = task.WaitAndGetResult ();
}
return instance;
}
}
protected override Task OnInitialize (ServiceProvider serviceProvider)
{
Runtime.AssertMainThread ();
var timings = new Dictionary<string, long> ();
var metadata = new CompositionLoadMetadata (timings);
var timer = Counters.CompositionLoad.BeginTiming (metadata);
var stepTimer = System.Diagnostics.Stopwatch.StartNew ();
var mefAssemblies = ReadAssembliesFromAddins (timer);
timings ["ReadFromAddins"] = stepTimer.ElapsedMilliseconds;
return Task.Run (() => InitializeInstanceAsync (timer, mefAssemblies));
}
/// <summary>
/// Returns an instance of type T that is exported by some composition part. The instance is shared (singleton).
/// </summary>
public T GetExportedValue<T> () => ExportProvider.GetExportedValue<T> ();
/// <summary>
/// Returns all instances of type T that are exported by some composition part. The instances are shared (singletons).
/// </summary>
public IEnumerable<T> GetExportedValues<T> () => ExportProvider.GetExportedValues<T> ();
/// <summary>
/// Returns a lazy holding the instance of type T that is exported by some composition part. The instance is shared (singleton).
/// </summary>
public static Lazy<T> GetExport<T> () => new Lazy<T> (() => Instance.ExportProvider.GetExportedValue<T> ());
/// <summary>
/// Returns a lazy holding all instances of type T that are exported by some composition part. The instances are shared (singletons).
/// </summary>
public static Lazy<IEnumerable<T>> GetExports<T> () => new Lazy<IEnumerable<T>> (() => Instance.ExportProvider.GetExportedValues<T> ());
public RuntimeComposition RuntimeComposition { get; private set; }
public IExportProviderFactory ExportProviderFactory { get; private set; }
public ExportProvider ExportProvider { get; private set; }
public HostServices HostServices { get; private set; }
internal CompositionManager ()
{
}
async Task InitializeInstanceAsync (ITimeTracker<CompositionLoadMetadata> timer, HashSet<Assembly> mefAssemblies)
{
var metadata = timer.Metadata;
var fullTimer = System.Diagnostics.Stopwatch.StartNew ();
var stepTimer = System.Diagnostics.Stopwatch.StartNew ();
var caching = new Caching (mefAssemblies, new IdeRuntimeCompositionExceptionHandler ());
// Try to use cached MEF data
using (timer) {
var canUse = metadata.ValidCache = caching.CanUse ();
if (canUse) {
LoggingService.LogInfo ("Creating MEF composition from cache");
RuntimeComposition = await TryCreateRuntimeCompositionFromCache (caching);
}
metadata.Timings ["LoadFromCache"] = stepTimer.ElapsedMilliseconds;
stepTimer.Restart ();
// Otherwise fallback to runtime discovery.
if (RuntimeComposition == null) {
LoggingService.LogInfo ("Creating MEF composition from runtime");
var (runtimeComposition, catalog) = await CreateRuntimeCompositionFromDiscovery (caching, timer);
RuntimeComposition = runtimeComposition;
CachedComposition cacheManager = new CachedComposition ();
caching.Write (RuntimeComposition, catalog, cacheManager).Ignore ();
}
metadata.Timings ["LoadRuntimeComposition"] = stepTimer.ElapsedMilliseconds;
stepTimer.Restart ();
ExportProviderFactory = RuntimeComposition.CreateExportProviderFactory ();
ExportProvider = ExportProviderFactory.CreateExportProvider ();
HostServices = Microsoft.VisualStudio.LanguageServices.VisualStudioMefHostServices.Create (ExportProvider);
metadata.Timings ["CreateServices"] = stepTimer.ElapsedMilliseconds;
metadata.Duration = fullTimer.ElapsedMilliseconds;
}
}
internal static async Task<RuntimeComposition> TryCreateRuntimeCompositionFromCache (Caching caching)
{
var cacheManager = new CachedComposition ();
try {
using (var cacheStream = caching.OpenCacheStream ()) {
return await cacheManager.LoadRuntimeCompositionAsync (cacheStream, StandardResolver);
}
} catch (Exception ex) {
LoggingService.LogError ("Could not deserialize MEF cache", ex);
caching.DeleteFiles ();
}
return null;
}
internal static async Task<(RuntimeComposition, ComposableCatalog)> CreateRuntimeCompositionFromDiscovery (Caching caching, ITimeTracker timer = null)
{
var parts = await Discovery.CreatePartsAsync (caching.MefAssemblies);
timer?.Trace ("Composition parts discovered");
ComposableCatalog catalog = ComposableCatalog.Create (StandardResolver)
.WithCompositionService ()
.AddParts (parts);
var discoveryErrors = catalog.DiscoveredParts.DiscoveryErrors;
if (!discoveryErrors.IsEmpty) {
foreach (var error in discoveryErrors) {
LoggingService.LogInfo ("MEF discovery error", error);
}
// throw new ApplicationException ("MEF discovery errors");
}
CompositionConfiguration configuration = CompositionConfiguration.Create (catalog);
if (!configuration.CompositionErrors.IsEmpty) {
// capture the errors in an array for easier debugging
var errors = configuration.CompositionErrors.SelectMany (e => e).ToArray ();
foreach (var error in errors) {
LoggingService.LogInfo ("MEF composition error: " + error.Message);
}
// For now while we're still transitioning to VSMEF it's useful to work
// even if the composition has some errors. TODO: re-enable this.
//configuration.ThrowOnErrors ();
}
timer?.Trace ("Composition configured");
var runtimeComposition = RuntimeComposition.CreateRuntimeComposition (configuration);
timer?.Trace ("Composition created");
return (runtimeComposition, catalog);
}
internal static HashSet<Assembly> ReadAssembliesFromAddins (ITimeTracker<CompositionLoadMetadata> timer = null)
{
var readAssemblies = new HashSet<Assembly> ();
timer?.Trace ("Start: reading assemblies");
ReadAssemblies (readAssemblies, "/MonoDevelop/Ide/TypeService/PlatformMefHostServices");
ReadAssemblies (readAssemblies, "/MonoDevelop/Ide/TypeService/MefHostServices");
ReadAssemblies (readAssemblies, "/MonoDevelop/Ide/Composition");
timer?.Trace ("Start: end reading assemblies");
return readAssemblies;
void ReadAssemblies (HashSet<Assembly> assemblies, string extensionPath)
{
foreach (var node in AddinManager.GetExtensionNodes (extensionPath)) {
if (node is AssemblyExtensionNode assemblyNode) {
try {
string id = assemblyNode.Addin.Id;
string assemblyName = assemblyNode.FileName;
// Make sure the add-in that registered the assembly is loaded, since it can bring other
// other assemblies required to load this one
AddinManager.LoadAddin (null, id);
var assemblyFilePath = assemblyNode.Addin.GetFilePath (assemblyNode.FileName);
var assembly = Runtime.LoadAssemblyFrom (assemblyFilePath);
assemblies.Add (assembly);
} catch (Exception e) {
LoggingService.LogError ("Composition can't load assembly: " + assemblyNode.FileName, e);
}
}
}
}
}
sealed class IdeRuntimeCompositionExceptionHandler : RuntimeCompositionExceptionHandler
{
static class Strings
{
public static string Quit = GettextCatalog.GetString ("Quit");
public static string Restart = GettextCatalog.GetString ("Restart");
}
public override void HandleException (string message, Exception e)
{
base.HandleException (message, e);
if (e is IOException)
return;
if (!IdeApp.IsInitialized) {
Console.WriteLine (e);
return;
}
var text = GettextCatalog.GetString ("There was a problem loading one or more extensions and {0} needs to be restarted.", BrandingService.ApplicationName);
var quitButton = new AlertButton (Strings.Quit);
var restartButton = new AlertButton (Strings.Restart);
var result = MessageService.GenericAlert (
IdeServices.DesktopService.GetFocusedTopLevelWindow (),
Gui.Stock.Error,
text,
secondaryText: null,
defaultButton: 1,
quitButton,
restartButton
);
if (result == restartButton)
IdeApp.Restart (false).Ignore ();
else
IdeApp.Exit ().Ignore ();
}
}
}
}
|