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.
11 // This file is part of OpenTween.
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)
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
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.
29 using System.Collections.Generic;
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;
45 internal class MyApplication
47 public static readonly CultureInfo[] SupportedUICulture = new[]
49 new CultureInfo("en"), // 先頭のカルチャはフォールバック先として使用される
50 new CultureInfo("ja"),
54 /// 起動時に指定されたオプションを取得します
56 public static IDictionary<string, string> StartupOptions { get; private set; }
59 /// アプリケーションのメイン エントリ ポイントです。
62 static int Main(string[] args)
64 WarnIfRunAsAdministrator();
66 if (!CheckRuntimeVersion())
68 var message = string.Format(Properties.Resources.CheckRuntimeVersion_Error, ".NET Framework 4.5.1");
69 MessageBox.Show(message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
73 StartupOptions = ParseArguments(args);
75 if (!SetConfigDirectoryPath())
78 SettingManager.LoadAll();
82 // 同じ設定ファイルを使用する OpenTween プロセスの二重起動を防止する
83 string pt = MyCommon.settingPath.Replace("\\", "/") + "/" + Application.ProductName;
84 using (Mutex mt = new Mutex(false, pt))
86 if (!mt.WaitOne(0, false))
88 var text = string.Format(MyCommon.ReplaceAppName(Properties.Resources.StartupText1), MyCommon.GetAssemblyName());
89 MessageBox.Show(text, MyCommon.ReplaceAppName(Properties.Resources.StartupText2), MessageBoxButtons.OK, MessageBoxIcon.Information);
91 TryActivatePreviousWindow();
95 TaskScheduler.UnobservedTaskException += (s, e) =>
98 OnUnhandledException(e.Exception.Flatten());
100 Application.ThreadException += (s, e) => OnUnhandledException(e.Exception);
101 AppDomain.CurrentDomain.UnhandledException += (s, e) => OnUnhandledException((Exception)e.ExceptionObject);
103 Application.EnableVisualStyles();
104 Application.SetCompatibleTextRenderingDefault(false);
105 Application.Run(new TweenMain());
114 /// OpenTween が管理者権限で実行されている場合に警告を表示します
116 private static void WarnIfRunAsAdministrator()
118 // UAC が無効なシステムでは警告を表示しない
119 using (var lmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
120 using (var systemKey = lmKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\"))
122 var enableLUA = (int?)systemKey?.GetValue("EnableLUA");
127 using (var currentIdentity = WindowsIdentity.GetCurrent())
129 var principal = new WindowsPrincipal(currentIdentity);
130 if (principal.IsInRole(WindowsBuiltInRole.Administrator))
132 var message = string.Format(Properties.Resources.WarnIfRunAsAdministrator_Message, Application.ProductName);
133 MessageBox.Show(message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
139 /// 動作中の .NET Framework のバージョンが適切かチェックします
141 private static bool CheckRuntimeVersion()
143 // Mono 上で動作している場合はバージョンチェックを無視します
144 if (Type.GetType("Mono.Runtime", false) != null)
147 // .NET Framework 4.5.1 以降で動作しているかチェックする
148 // 参照: http://msdn.microsoft.com/en-us/library/hh925568%28v=vs.110%29.aspx
150 using (var lmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
151 using (var ndpKey = lmKey.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"))
153 var releaseKey = (int)ndpKey.GetValue("Release");
154 return releaseKey >= 378675;
159 /// “/key:value”形式の起動オプションを解釈し IDictionary に変換する
162 /// 不正な形式のオプションは除外されます。
163 /// また、重複したキーのオプションが入力された場合は末尾に書かれたオプションが採用されます。
165 internal static IDictionary<string, string> ParseArguments(IEnumerable<string> arguments)
167 var optionPattern = new Regex(@"^/(.+?)(?::(.*))?$");
169 return arguments.Select(x => optionPattern.Match(x))
170 .Where(x => x.Success)
171 .GroupBy(x => x.Groups[1].Value)
172 .ToDictionary(x => x.Key, x => x.Last().Groups[2].Value);
175 private static void TryActivatePreviousWindow()
177 // 実行中の同じアプリケーションのウィンドウ・ハンドルの取得
178 var prevProcess = GetPreviousProcess();
179 if (prevProcess == null)
184 IntPtr windowHandle = NativeMethods.GetWindowHandle((uint)prevProcess.Id, Application.ProductName);
185 if (windowHandle != IntPtr.Zero)
187 NativeMethods.SetActiveWindow(windowHandle);
191 private static Process GetPreviousProcess()
193 var currentProcess = Process.GetCurrentProcess();
196 return Process.GetProcessesByName(currentProcess.ProcessName)
197 .Where(p => p.Id != currentProcess.Id)
198 .FirstOrDefault(p => p.MainModule.FileName.Equals(currentProcess.MainModule.FileName, StringComparison.OrdinalIgnoreCase));
206 private static void OnUnhandledException(Exception ex)
208 if (CheckIgnorableError(ex))
211 if (MyCommon.ExceptionOut(ex))
218 /// 無視しても問題のない既知の例外であれば true を返す
220 private static bool CheckIgnorableError(Exception ex)
225 if (ex is AggregateException aggregated)
227 if (aggregated.InnerExceptions.Count != 1)
230 ex = aggregated.InnerExceptions.Single();
235 case System.Net.WebException webEx:
236 // SSL/TLS のネゴシエーションに失敗した場合に発生する。なぜかキャッチできない例外
237 // https://osdn.net/ticket/browse.php?group_id=6526&tid=37432
238 if (webEx.Status == System.Net.WebExceptionStatus.SecureChannelFailure)
241 case System.Threading.Tasks.TaskCanceledException cancelEx:
242 // ton.twitter.com の画像でタイムアウトした場合、try-catch で例外がキャッチできない
243 // https://osdn.net/ticket/browse.php?group_id=6526&tid=37433
244 var stackTrace = new System.Diagnostics.StackTrace(cancelEx);
245 var lastFrameMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1).GetMethod();
246 if (lastFrameMethod.ReflectedType == typeof(Connection.TwitterApiConnection) &&
247 lastFrameMethod.Name == nameof(Connection.TwitterApiConnection.GetStreamAsync))
256 public static void InitCulture()
258 var currentCulture = CultureInfo.CurrentUICulture;
260 var settingCultureStr = SettingManager.Common.Language;
261 if (settingCultureStr != "OS")
265 currentCulture = new CultureInfo(settingCultureStr);
267 catch (CultureNotFoundException) { }
270 var preferredCulture = GetPreferredCulture(currentCulture);
271 CultureInfo.DefaultThreadCurrentUICulture = preferredCulture;
272 Thread.CurrentThread.CurrentUICulture = preferredCulture;
276 /// サポートしているカルチャの中から、指定されたカルチャに対して適切なカルチャを選択して返します
278 public static CultureInfo GetPreferredCulture(CultureInfo culture)
280 if (SupportedUICulture.Any(x => x.Contains(culture)))
283 return SupportedUICulture[0];
286 private static bool SetConfigDirectoryPath()
288 if (StartupOptions.TryGetValue("configDir", out var configDir) && !string.IsNullOrEmpty(configDir))
290 // 起動オプション /configDir で設定ファイルの参照先を変更できます
291 if (!Directory.Exists(configDir))
293 var text = string.Format(Properties.Resources.ConfigDirectoryNotExist, configDir);
294 MessageBox.Show(text, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
298 MyCommon.settingPath = Path.GetFullPath(configDir);
302 // OpenTween.exe と同じディレクトリに設定ファイルを配置する
303 MyCommon.settingPath = Application.StartupPath;
305 SettingManager.LoadAll();
309 // 設定ファイルが書き込み可能な状態であるかテストする
310 SettingManager.SaveAll();
312 catch (UnauthorizedAccessException)
314 // 書き込みに失敗した場合 (Program Files 以下に配置されている場合など)
316 // 通常は C:\Users\ユーザー名\AppData\Roaming\OpenTween\ となる
317 var roamingDir = Path.Combine(new[]
319 Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
320 Application.ProductName,
322 Directory.CreateDirectory(roamingDir);
324 MyCommon.settingPath = roamingDir;
327 * 書き込みが制限されたディレクトリ内で起動された場合の設定ファイルの扱い
329 * (A) StartupPath に存在する設定ファイル
330 * (B) Roaming に存在する設定ファイル
335 * 2. A が存在し、B が存在しない場合
336 * => A の内容を B にコピーする (警告を表示)
338 * 3. A が存在せず、B が存在する場合
341 * 4. A も B も存在するが、A の方が更新日時が新しい場合
342 * => A の内容を B にコピーする (警告を表示)
344 * 5. A も B も存在するが、B の方が更新日時が新しい場合
347 var startupDirFile = new FileInfo(Path.Combine(Application.StartupPath, "SettingCommon.xml"));
348 var roamingDirFile = new FileInfo(Path.Combine(roamingDir, "SettingCommon.xml"));
350 if (roamingDirFile.Exists && (!startupDirFile.Exists || startupDirFile.LastWriteTime <= roamingDirFile.LastWriteTime))
352 // 既に Roaming に設定ファイルが存在し、Roaming 内のファイルの方が新しい場合は
353 // StartupPath に設定ファイルが存在しても無視する
354 SettingManager.LoadAll();
358 if (startupDirFile.Exists)
360 // StartupPath に設定ファイルが存在し、Roaming 内のファイルよりも新しい場合のみ警告を表示する
361 var message = string.Format(Properties.Resources.SettingPath_Relocation, Application.StartupPath, MyCommon.settingPath);
362 MessageBox.Show(message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
365 // Roaming に設定ファイルを作成 (StartupPath に読み込みに成功した設定ファイルがあれば内容がコピーされる)
366 SettingManager.SaveAll();