OSDN Git Service

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