OSDN Git Service

C# 8.0 のnull許容参照型を有効化
[opentween/open-tween.git] / OpenTween / ApplicationEvents.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2012 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 //           (c) 2008-2012 Moz (@syo68k)
4 //           (c) 2008-2012 takeshik (@takeshik) <http://www.takeshik.org/>
5 //           (c) 2010-2012 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 //           (c) 2010-2012 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 //           (c) 2012      Egtra (@egtra) <http://dev.activebasic.com/egtra/>
8 //           (c) 2012      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
9 // All rights reserved.
10 // 
11 // This file is part of OpenTween.
12 // 
13 // This program is free software; you can redistribute it and/or modify it
14 // under the terms of the GNU General public License as published by the Free
15 // Software Foundation; either version 3 of the License, or (at your option)
16 // any later version.
17 // 
18 // This program is distributed in the hope that it will be useful, but
19 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
20 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
21 // for more details.
22 // 
23 // You should have received a copy of the GNU General public License along
24 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
25 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
26 // Boston, MA 02110-1301, USA.
27
28 #nullable enable
29
30 using System;
31 using System.Collections.Generic;
32 using System.IO;
33 using System.Linq;
34 using System.Diagnostics;
35 using System.Windows.Forms;
36 using System.Text.RegularExpressions;
37 using System.Threading;
38 using System.Threading.Tasks;
39 using System.Globalization;
40 using System.Reflection;
41 using Microsoft.Win32;
42 using OpenTween.Setting;
43 using System.Security.Principal;
44
45 namespace OpenTween
46 {
47     internal class MyApplication
48     {
49         public static readonly CultureInfo[] SupportedUICulture = new[]
50         {
51             new CultureInfo("en"), // 先頭のカルチャはフォールバック先として使用される
52             new CultureInfo("ja"),
53         };
54
55         /// <summary>
56         /// 起動時に指定されたオプションを取得します
57         /// </summary>
58         public static IDictionary<string, string> StartupOptions { get; private set; }
59
60         /// <summary>
61         /// アプリケーションのメイン エントリ ポイントです。
62         /// </summary>
63         [STAThread]
64         static int Main(string[] args)
65         {
66             WarnIfRunAsAdministrator();
67
68             if (!CheckRuntimeVersion())
69             {
70                 var message = string.Format(Properties.Resources.CheckRuntimeVersion_Error, ".NET Framework 4.7.2");
71                 MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
72                 return 1;
73             }
74
75             StartupOptions = ParseArguments(args);
76
77             if (!SetConfigDirectoryPath())
78                 return 1;
79
80             SettingManager.LoadAll();
81
82             InitCulture();
83
84             {
85                 // 同じ設定ファイルを使用する OpenTween プロセスの二重起動を防止する
86                 var pt = MyCommon.settingPath.Replace("\\", "/") + "/" + ApplicationSettings.AssemblyName;
87                 using var mt = new Mutex(false, pt);
88
89                 if (!mt.WaitOne(0, false))
90                 {
91                     var text = string.Format(MyCommon.ReplaceAppName(Properties.Resources.StartupText1), ApplicationSettings.AssemblyName);
92                     MessageBox.Show(text, MyCommon.ReplaceAppName(Properties.Resources.StartupText2), MessageBoxButtons.OK, MessageBoxIcon.Information);
93
94                     TryActivatePreviousWindow();
95                     return 1;
96                 }
97
98                 TaskScheduler.UnobservedTaskException += (s, e) =>
99                 {
100                     e.SetObserved();
101                     OnUnhandledException(e.Exception.Flatten());
102                 };
103                 Application.ThreadException += (s, e) => OnUnhandledException(e.Exception);
104                 AppDomain.CurrentDomain.UnhandledException += (s, e) => OnUnhandledException((Exception)e.ExceptionObject);
105
106                 Application.EnableVisualStyles();
107                 Application.SetCompatibleTextRenderingDefault(false);
108                 Application.Run(new TweenMain());
109
110                 mt.ReleaseMutex();
111             }
112
113             return 0;
114         }
115
116         /// <summary>
117         /// OpenTween が管理者権限で実行されている場合に警告を表示します
118         /// </summary>
119         private static void WarnIfRunAsAdministrator()
120         {
121             // UAC が無効なシステムでは警告を表示しない
122             using var lmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
123             using var systemKey = lmKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\");
124
125             var enableLUA = (int?)systemKey?.GetValue("EnableLUA");
126             if (enableLUA != 1)
127                 return;
128
129             using var currentIdentity = WindowsIdentity.GetCurrent();
130             var principal = new WindowsPrincipal(currentIdentity);
131             if (principal.IsInRole(WindowsBuiltInRole.Administrator))
132             {
133                 var message = string.Format(Properties.Resources.WarnIfRunAsAdministrator_Message, ApplicationSettings.ApplicationName);
134                 MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
135             }
136         }
137
138         /// <summary>
139         /// 動作中の .NET Framework のバージョンが適切かチェックします
140         /// </summary>
141         private static bool CheckRuntimeVersion()
142         {
143             // Mono 上で動作している場合はバージョンチェックを無視します
144             if (Type.GetType("Mono.Runtime", false) != null)
145                 return true;
146
147             // .NET Framework 4.7.2 以降で動作しているかチェックする
148             // 参照: https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed
149
150             using var lmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
151             using var ndpKey = lmKey.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\");
152
153             var releaseKey = (int)ndpKey.GetValue("Release");
154             return releaseKey >= 461808;
155         }
156
157         /// <summary>
158         /// “/key:value”形式の起動オプションを解釈し IDictionary に変換する
159         /// </summary>
160         /// <remarks>
161         /// 不正な形式のオプションは除外されます。
162         /// また、重複したキーのオプションが入力された場合は末尾に書かれたオプションが採用されます。
163         /// </remarks>
164         internal static IDictionary<string, string> ParseArguments(IEnumerable<string> arguments)
165         {
166             var optionPattern = new Regex(@"^/(.+?)(?::(.*))?$");
167
168             return arguments.Select(x => optionPattern.Match(x))
169                 .Where(x => x.Success)
170                 .GroupBy(x => x.Groups[1].Value)
171                 .ToDictionary(x => x.Key, x => x.Last().Groups[2].Value);
172         }
173
174         private static void TryActivatePreviousWindow()
175         {
176             // 実行中の同じアプリケーションのウィンドウ・ハンドルの取得
177             var prevProcess = GetPreviousProcess();
178             if (prevProcess == null)
179             {
180                 return;
181             }
182
183             var windowHandle = NativeMethods.GetWindowHandle((uint)prevProcess.Id, ApplicationSettings.ApplicationName);
184             if (windowHandle != IntPtr.Zero)
185             {
186                 NativeMethods.SetActiveWindow(windowHandle);
187             }
188         }
189
190         private static Process? GetPreviousProcess()
191         {
192             var currentProcess = Process.GetCurrentProcess();
193             try
194             {
195                 return Process.GetProcessesByName(currentProcess.ProcessName)
196                     .Where(p => p.Id != currentProcess.Id)
197                     .FirstOrDefault(p => p.MainModule.FileName.Equals(currentProcess.MainModule.FileName, StringComparison.OrdinalIgnoreCase));
198             }
199             catch
200             {
201                 return null;
202             }
203         }
204
205         private static void OnUnhandledException(Exception ex)
206         {
207             if (CheckIgnorableError(ex))
208                 return;
209
210             if (MyCommon.ExceptionOut(ex))
211             {
212                 Application.Exit();
213             }
214         }
215
216         /// <summary>
217         /// 無視しても問題のない既知の例外であれば true を返す
218         /// </summary>
219         private static bool CheckIgnorableError(Exception ex)
220         {
221 #if DEBUG
222             return false;
223 #else
224             if (ex is AggregateException aggregated)
225             {
226                 if (aggregated.InnerExceptions.Count != 1)
227                     return false;
228
229                 ex = aggregated.InnerExceptions.Single();
230             }
231
232             switch (ex)
233             {
234                 case System.Net.WebException webEx:
235                     // SSL/TLS のネゴシエーションに失敗した場合に発生する。なぜかキャッチできない例外
236                     // https://osdn.net/ticket/browse.php?group_id=6526&tid=37432
237                     if (webEx.Status == System.Net.WebExceptionStatus.SecureChannelFailure)
238                         return true;
239                     break;
240                 case System.Threading.Tasks.TaskCanceledException cancelEx:
241                     // ton.twitter.com の画像でタイムアウトした場合、try-catch で例外がキャッチできない
242                     // https://osdn.net/ticket/browse.php?group_id=6526&tid=37433
243                     var stackTrace = new System.Diagnostics.StackTrace(cancelEx);
244                     var lastFrameMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1).GetMethod();
245                     if (lastFrameMethod.ReflectedType == typeof(Connection.TwitterApiConnection) &&
246                         lastFrameMethod.Name == nameof(Connection.TwitterApiConnection.GetStreamAsync))
247                         return true;
248                     break;
249             }
250
251             return false;
252 #endif
253         }
254
255         public static void InitCulture()
256         {
257             var currentCulture = CultureInfo.CurrentUICulture;
258
259             var settingCultureStr = SettingManager.Common.Language;
260             if (settingCultureStr != "OS")
261             {
262                 try
263                 {
264                     currentCulture = new CultureInfo(settingCultureStr);
265                 }
266                 catch (CultureNotFoundException) { }
267             }
268
269             var preferredCulture = GetPreferredCulture(currentCulture);
270             CultureInfo.DefaultThreadCurrentUICulture = preferredCulture;
271             Thread.CurrentThread.CurrentUICulture = preferredCulture;
272         }
273
274         /// <summary>
275         /// サポートしているカルチャの中から、指定されたカルチャに対して適切なカルチャを選択して返します
276         /// </summary>
277         public static CultureInfo GetPreferredCulture(CultureInfo culture)
278         {
279             if (SupportedUICulture.Any(x => x.Contains(culture)))
280                 return culture;
281
282             return SupportedUICulture[0];
283         }
284
285         private static bool SetConfigDirectoryPath()
286         {
287             if (StartupOptions.TryGetValue("configDir", out var configDir) && !string.IsNullOrEmpty(configDir))
288             {
289                 // 起動オプション /configDir で設定ファイルの参照先を変更できます
290                 if (!Directory.Exists(configDir))
291                 {
292                     var text = string.Format(Properties.Resources.ConfigDirectoryNotExist, configDir);
293                     MessageBox.Show(text, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
294                     return false;
295                 }
296
297                 MyCommon.settingPath = Path.GetFullPath(configDir);
298             }
299             else
300             {
301                 // OpenTween.exe と同じディレクトリに設定ファイルを配置する
302                 MyCommon.settingPath = Application.StartupPath;
303
304                 SettingManager.LoadAll();
305
306                 try
307                 {
308                     // 設定ファイルが書き込み可能な状態であるかテストする
309                     SettingManager.SaveAll();
310                 }
311                 catch (UnauthorizedAccessException)
312                 {
313                     // 書き込みに失敗した場合 (Program Files 以下に配置されている場合など)
314
315                     // 通常は C:\Users\ユーザー名\AppData\Roaming\OpenTween\ となる
316                     var roamingDir = Path.Combine(new[]
317                     {
318                         Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
319                         ApplicationSettings.ApplicationName,
320                     });
321                     Directory.CreateDirectory(roamingDir);
322
323                     MyCommon.settingPath = roamingDir;
324
325                     /*
326                      * 書き込みが制限されたディレクトリ内で起動された場合の設定ファイルの扱い
327                      *
328                      *  (A) StartupPath に存在する設定ファイル
329                      *  (B) Roaming に存在する設定ファイル
330                      *
331                      *  1. A も B も存在しない場合
332                      *    => B を新規に作成する
333                      *
334                      *  2. A が存在し、B が存在しない場合
335                      *    => A の内容を B にコピーする (警告を表示)
336                      *
337                      *  3. A が存在せず、B が存在する場合
338                      *    => B を使用する
339                      *
340                      *  4. A も B も存在するが、A の方が更新日時が新しい場合
341                      *    => A の内容を B にコピーする (警告を表示)
342                      *
343                      *  5. A も B も存在するが、B の方が更新日時が新しい場合
344                      *    => B を使用する
345                      */
346                     var startupDirFile = new FileInfo(Path.Combine(Application.StartupPath, "SettingCommon.xml"));
347                     var roamingDirFile = new FileInfo(Path.Combine(roamingDir, "SettingCommon.xml"));
348
349                     if (roamingDirFile.Exists && (!startupDirFile.Exists || startupDirFile.LastWriteTime <= roamingDirFile.LastWriteTime))
350                     {
351                         // 既に Roaming に設定ファイルが存在し、Roaming 内のファイルの方が新しい場合は
352                         // StartupPath に設定ファイルが存在しても無視する
353                         SettingManager.LoadAll();
354                     }
355                     else
356                     {
357                         if (startupDirFile.Exists)
358                         {
359                             // StartupPath に設定ファイルが存在し、Roaming 内のファイルよりも新しい場合のみ警告を表示する
360                             var message = string.Format(Properties.Resources.SettingPath_Relocation, Application.StartupPath, MyCommon.settingPath);
361                             MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
362                         }
363
364                         // Roaming に設定ファイルを作成 (StartupPath に読み込みに成功した設定ファイルがあれば内容がコピーされる)
365                         SettingManager.SaveAll();
366                     }
367                 }
368             }
369
370             return true;
371         }
372     }
373 }