-
Notifications
You must be signed in to change notification settings - Fork 309
/
Copy pathExtension.cs
333 lines (301 loc) · 12 KB
/
Extension.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
using Castle.Windsor;
using Extensibility;
using NLog;
using Rubberduck.Common.WinAPI;
using Rubberduck.Resources;
using Rubberduck.Resources.Registration;
using Rubberduck.Root;
using Rubberduck.Runtime;
using Rubberduck.Settings;
using Rubberduck.SettingsProvider;
using Rubberduck.UI;
using Rubberduck.VBEditor.ComManagement;
using Rubberduck.VBEditor.ComManagement.TypeLibs;
using Rubberduck.VBEditor.Events;
using Rubberduck.VBEditor.SafeComWrappers.Abstract;
using Rubberduck.VBEditor.VbeRuntime;
using Rubberduck.VersionCheck;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO.Abstractions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Threading;
namespace Rubberduck
{
/// <remarks>
/// Special thanks to Carlos Quintero (MZ-Tools) for providing the general structure here.
/// </remarks>
[
ComVisible(true),
Guid(RubberduckGuid.ExtensionGuid),
ProgId(RubberduckProgId.ExtensionProgId),
ClassInterface(ClassInterfaceType.None),
ComDefaultInterface(typeof(IDTExtensibility2)),
EditorBrowsable(EditorBrowsableState.Never)
]
// ReSharper disable once InconsistentNaming // note: underscore prefix hides class from COM API
public class _Extension : IDTExtensibility2
{
private IVBE _vbe;
private IAddIn _addin;
private IVbeNativeApi _vbeNativeApi;
private IBeepInterceptor _beepInterceptor;
private IFileSystem _fileSystem;
private bool _isInitialized;
private bool _isBeginShutdownExecuted;
private GeneralSettings _initialSettings;
private IWindsorContainer _container;
private App _app;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public void OnAddInsUpdate(ref Array custom) { }
[SuppressMessage("ReSharper", "InconsistentNaming")]
public void OnConnection(object Application, ext_ConnectMode ConnectMode, object AddInInst, ref Array custom)
{
try
{
_vbe = RootComWrapperFactory.GetVbeWrapper(Application);
_addin = RootComWrapperFactory.GetAddInWrapper(AddInInst);
_addin.Object = this;
_vbeNativeApi = new VbeNativeApiAccessor();
_beepInterceptor = new BeepInterceptor(_vbeNativeApi);
_fileSystem = new FileSystem();
VbeProvider.Initialize(_vbe, _vbeNativeApi, _beepInterceptor);
VbeNativeServices.HookEvents(_vbe);
SetAddInObject();
switch (ConnectMode)
{
case ext_ConnectMode.ext_cm_Startup:
// normal execution path - don't initialize just yet, wait for OnStartupComplete to be called by the host.
break;
case ext_ConnectMode.ext_cm_AfterStartup:
_isBeginShutdownExecuted = false; //When we reconnect after having been unloaded, the variable might no longer have its initial value.
InitializeAddIn();
break;
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
[Conditional("DEBUG")]
private void SetAddInObject()
{
// FOR DEBUGGING/DEVELOPMENT PURPOSES, ALLOW ACCESS TO SOME VBETypeLibsAPI FEATURES FROM VBA
_addin.Object = new VBETypeLibsAPI_Object(_vbe);
}
private Assembly LoadFromSameFolder(object sender, ResolveEventArgs args)
{
var folderPath = _fileSystem.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty;
var assemblyPath = _fileSystem.Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll");
if (!_fileSystem.File.Exists(assemblyPath))
{
return null;
}
var assembly = Assembly.LoadFile(assemblyPath);
return assembly;
}
public void OnStartupComplete(ref Array custom)
{
InitializeAddIn();
}
public void OnBeginShutdown(ref Array custom)
{
_isBeginShutdownExecuted = true;
ShutdownAddIn();
}
// ReSharper disable InconsistentNaming
public void OnDisconnection(ext_DisconnectMode RemoveMode, ref Array custom)
{
switch (RemoveMode)
{
case ext_DisconnectMode.ext_dm_UserClosed:
ShutdownAddIn();
break;
case ext_DisconnectMode.ext_dm_HostShutdown:
if (_isBeginShutdownExecuted)
{
// this is the normal case: nothing to do here, we already ran ShutdownAddIn.
}
else
{
// some hosts do not call OnBeginShutdown: this mitigates it.
ShutdownAddIn();
}
break;
}
}
private void InitializeAddIn()
{
Splash2021 splash = null;
try
{
if (_isInitialized)
{
// The add-in is already initialized. See:
// The strange case of the add-in initialized twice
// http://msmvps.com/blogs/carlosq/archive/2013/02/14/the-strange-case-of-the-add-in-initialized-twice.aspx
return;
}
var pathProvider = PersistencePathProvider.Instance;
var configLoader = new XmlPersistenceService<GeneralSettings>(pathProvider, _fileSystem);
var configProvider = new GeneralConfigProvider(configLoader);
_initialSettings = configProvider.Read();
if (_initialSettings != null)
{
try
{
var cultureInfo = CultureInfo.GetCultureInfo(_initialSettings.Language.Code);
Dispatcher.CurrentDispatcher.Thread.CurrentUICulture = cultureInfo;
}
catch (CultureNotFoundException)
{
}
try
{
if (_initialSettings.SetDpiUnaware)
{
SHCore.SetProcessDpiAwareness(PROCESS_DPI_AWARENESS.Process_DPI_Unaware);
}
}
catch (Exception)
{
Debug.Assert(false, "Could not set DPI awareness.");
}
}
else
{
Debug.Assert(false, "Settings could not be initialized.");
}
if (_initialSettings?.CanShowSplash ?? false)
{
splash = new Splash2021(string.Format(RubberduckUI.Rubberduck_AboutBuild, Assembly.GetExecutingAssembly().GetName().Version.ToString(3)));
splash.Show();
splash.Refresh();
}
Startup();
}
catch (Win32Exception)
{
System.Windows.Forms.MessageBox.Show(Resources.RubberduckUI.RubberduckReloadFailure_Message,
RubberduckUI.RubberduckReloadFailure_Title,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
catch (Exception exception)
{
_logger.Fatal(exception);
// TODO Use Rubberduck Interaction instead and provide exception stack trace as
// an optional "more info" collapsible section to eliminate the conditional.
MessageBox.Show(
#if DEBUG
exception.ToString(),
#else
exception.Message.ToString(),
#endif
RubberduckUI.RubberduckLoadFailure, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
splash?.Dispose();
}
}
private void Startup()
{
try
{
var currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += HandleAppDomainException;
currentDomain.AssemblyResolve += LoadFromSameFolder;
_container = new WindsorContainer().Install(new RubberduckIoCInstaller(_vbe, _addin, _initialSettings, _vbeNativeApi, _beepInterceptor));
_container.Resolve<InstanceProvider>();
_app = _container.Resolve<App>();
_app.Startup();
_isInitialized = true;
}
catch (Exception e)
{
_logger.Fatal(e, "Startup sequence threw an unexpected exception.");
throw new Exception("Rubberduck's startup sequence threw an unexpected exception. Please check the Rubberduck logs for more information and report an issue if necessary", e);
}
}
private void HandleAppDomainException(object sender, UnhandledExceptionEventArgs e)
{
var message = e.IsTerminating
? "An unhandled exception occurred. The runtime is shutting down."
: "An unhandled exception occurred. The runtime continues running.";
if (e.ExceptionObject is Exception exception)
{
_logger.Fatal(exception, message);
}
else
{
_logger.Fatal(message);
}
}
private void ShutdownAddIn()
{
var currentDomain = AppDomain.CurrentDomain;
try
{
_logger.Info("Rubberduck is shutting down.");
_logger.Trace("Unhooking VBENativeServices events...");
VbeNativeServices.UnhookEvents();
VbeProvider.Terminate();
_logger.Trace("Releasing dockable hosts...");
using (var windows = _vbe.Windows)
{
windows.ReleaseDockableHosts();
}
if (_app != null)
{
_logger.Trace("Initiating App.Shutdown...");
_app.Shutdown();
_app = null;
}
if (_container != null)
{
_logger.Trace("Disposing IoC container...");
_container.Dispose();
_container = null;
}
}
catch (Exception e)
{
_logger.Error(e);
_logger.Warn("Exception is swallowed.");
//throw; // <<~ uncomment to crash the process
}
finally
{
try
{
_logger.Trace("Disposing COM safe...");
ComSafeManager.DisposeAndResetComSafe();
_addin = null;
_vbe = null;
_isInitialized = false;
_logger.Info("No exceptions were thrown.");
}
catch (Exception e)
{
_logger.Error(e);
_logger.Warn("Exception disposing the ComSafe has been swallowed.");
//throw; // <<~ uncomment to crash the process
}
finally
{
_logger.Trace("Unregistering AppDomain handlers....");
currentDomain.AssemblyResolve -= LoadFromSameFolder;
currentDomain.UnhandledException -= HandleAppDomainException;
_logger.Trace("Done. Main Shutdown completed. Toolwindows follow. Quack!");
_isInitialized = false;
}
}
}
}
}