-
Notifications
You must be signed in to change notification settings - Fork 307
/
Copy pathApp.cs
287 lines (254 loc) · 9.99 KB
/
App.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
using Infralution.Localization.Wpf;
using NLog;
using Rubberduck.Common;
using Rubberduck.Interaction;
using Rubberduck.Settings;
using Rubberduck.UI.Command.MenuItems;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Rubberduck.Parsing.UIContext;
using Rubberduck.Resources;
using Rubberduck.UI.Command;
using Rubberduck.VBEditor.Utility;
using Rubberduck.VersionCheck;
using Application = System.Windows.Forms.Application;
using Rubberduck.SettingsProvider;
using System.IO.Abstractions;
using Microsoft.Win32;
namespace Rubberduck
{
public sealed class App : IDisposable
{
private readonly IMessageBox _messageBox;
private readonly IConfigurationService<Configuration> _configService;
private readonly IAppMenu _appMenus;
private readonly IRubberduckHooks _hooks;
private readonly IVersionCheckService _version;
private readonly CommandBase _checkVersionCommand;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private Configuration _config;
private IFileSystem _filesystem;
public App(IMessageBox messageBox,
IConfigurationService<Configuration> configService,
IAppMenu appMenus,
IRubberduckHooks hooks,
IVersionCheckService version,
CommandBase checkVersionCommand,
IFileSystem filesystem)
{
_messageBox = messageBox;
_configService = configService;
_appMenus = appMenus;
_hooks = hooks;
_version = version;
_checkVersionCommand = checkVersionCommand;
_configService.SettingsChanged += _configService_SettingsChanged;
_filesystem = filesystem;
UiContextProvider.Initialize();
}
private void _configService_SettingsChanged(object sender, ConfigurationChangedEventArgs e)
{
_config = _configService.Read();
_hooks.HookHotkeys();
UpdateLoggingLevel();
if (e.LanguageChanged)
{
ApplyCultureConfig();
}
}
private void EnsureLogFolderPathExists()
{
try
{
if (!_filesystem.Directory.Exists(ApplicationConstants.LOG_FOLDER_PATH))
{
_filesystem.Directory.CreateDirectory(ApplicationConstants.LOG_FOLDER_PATH);
}
}
catch
{
//Does this need to display some sort of dialog?
}
}
private void EnsureTempPathExists()
{
// This is required by the parser - allow this to throw.
if (!_filesystem.Directory.Exists(ApplicationConstants.RUBBERDUCK_TEMP_PATH))
{
_filesystem.Directory.CreateDirectory(ApplicationConstants.RUBBERDUCK_TEMP_PATH);
}
// The parser swallows the error if deletions fail - clean up any temp files on startup
foreach (var file in _filesystem.DirectoryInfo.FromDirectoryName(ApplicationConstants.RUBBERDUCK_TEMP_PATH).GetFiles())
{
try
{
file.Delete();
}
catch
{
// Yeah, don't care here either.
}
}
}
private void UpdateLoggingLevel()
{
LogLevelHelper.SetMinimumLogLevel(LogLevel.FromOrdinal(_config.UserSettings.GeneralSettings.MinimumLogLevel));
}
/// <summary>
/// Ensure that log level is changed to "none" after a successful
/// run of Rubberduck for first time. By default, we ship with
/// log level set to Trace (0) but once it's installed and has
/// ran without problem, it should be set to None (6)
/// </summary>
private void UpdateLoggingLevelOnShutdown()
{
if (_config.UserSettings.GeneralSettings.UserEditedLogLevel ||
_config.UserSettings.GeneralSettings.MinimumLogLevel != LogLevel.Trace.Ordinal)
{
return;
}
_config.UserSettings.GeneralSettings.MinimumLogLevel = LogLevel.Off.Ordinal;
_configService.Save(_config);
}
public void Startup()
{
EnsureLogFolderPathExists();
EnsureTempPathExists();
ApplyCultureConfig();
LogRubberduckStart();
UpdateLoggingLevel();
CheckForLegacyIndenterSettings();
_appMenus.Initialize();
_hooks.HookHotkeys(); // need to hook hotkeys before we localize menus, to correctly display ShortcutTexts
_appMenus.Localize();
if (_config.UserSettings.GeneralSettings.CanCheckVersion)
{
_checkVersionCommand.Execute(null);
}
}
public void Shutdown()
{
try
{
Debug.WriteLine("App calling Hooks.Detach.");
_hooks.Detach();
UpdateLoggingLevelOnShutdown();
}
catch
{
// Won't matter anymore since we're shutting everything down anyway.
}
}
private void ApplyCultureConfig()
{
_config = _configService.Read();
var currentCulture = Resources.RubberduckUI.Culture;
try
{
CultureManager.UICulture = CultureInfo.GetCultureInfo(_config.UserSettings.GeneralSettings.Language.Code);
LocalizeResources(CultureManager.UICulture);
_appMenus.Localize();
}
catch (CultureNotFoundException exception)
{
Logger.Error(exception, "Error Setting Culture for Rubberduck");
// not accessing resources here, because setting resource culture literally just failed.
_messageBox.NotifyWarn(exception.Message, "Rubberduck");
_config.UserSettings.GeneralSettings.Language.Code = currentCulture.Name;
_configService.Save(_config);
}
}
private static void LocalizeResources(CultureInfo culture)
{
var localizers = AppDomain.CurrentDomain.GetAssemblies()
.SingleOrDefault(assembly => assembly.GetName().Name == "Rubberduck.Resources")
?.DefinedTypes.SelectMany(type => type.DeclaredProperties.Where(prop =>
prop.CanWrite && prop.Name.Equals("Culture") && prop.PropertyType == typeof(CultureInfo) &&
(prop.SetMethod?.IsStatic ?? false)));
if (localizers == null)
{
return;
}
var args = new object[] { culture };
foreach (var localizer in localizers)
{
localizer.SetMethod.Invoke(null, args);
}
}
private void CheckForLegacyIndenterSettings()
{
try
{
Logger.Trace("Checking for legacy Smart Indenter settings.");
if (_config.UserSettings.GeneralSettings.IsSmartIndenterPrompted ||
!_config.UserSettings.IndenterSettings.LegacySettingsExist())
{
return;
}
if (_messageBox.Question(Resources.RubberduckUI.SmartIndenter_LegacySettingPrompt, "Rubberduck"))
{
Logger.Trace("Attempting to load legacy Smart Indenter settings.");
_config.UserSettings.IndenterSettings.LoadLegacyFromRegistry();
}
_config.UserSettings.GeneralSettings.IsSmartIndenterPrompted = true;
_configService.Save(_config);
}
catch
{
//Meh.
}
}
public void LogRubberduckStart()
{
var version = _version.CurrentVersion;
GlobalDiagnosticsContext.Set("RubberduckVersion", version.ToString());
string osProductName = "";
string osReleaseId = "";
try
{
osProductName = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName", "").ToString();
osReleaseId = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ReleaseId", "").ToString();
}
catch
{
Logger.Debug("Failure to read OS version from registry. Logged version will be incomplete.");
}
var headers = new List<string>
{
$"\r\n\tRubberduck version {version} loading:",
$"\tOperating System: {osProductName} {osReleaseId} {(Environment.Is64BitOperatingSystem ? "x64" : "x86")} ({Environment.OSVersion.VersionString})"
};
try
{
headers.AddRange(new []
{
$"\tHost Product: {Application.ProductName} {(Environment.Is64BitProcess ? "x64" : "x86")}",
$"\tHost Version: {Application.ProductVersion}",
$"\tHost Executable: {_filesystem.Path.GetFileName(Application.ExecutablePath).ToUpper()}", // .ToUpper() used to convert ExceL.EXE -> EXCEL.EXE
});
}
catch
{
headers.Add("\tHost could not be determined.");
}
LogLevelHelper.SetDebugInfo(string.Join(Environment.NewLine, headers));
}
private bool _disposed;
public void Dispose()
{
if (_disposed)
{
return;
}
if (_configService != null)
{
_configService.SettingsChanged -= _configService_SettingsChanged;
}
UiDispatcher.Shutdown();
_disposed = true;
}
}
}