This repository was archived by the owner on Apr 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
282 lines (240 loc) · 12.8 KB
/
App.xaml.cs
File metadata and controls
282 lines (240 loc) · 12.8 KB
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
namespace TVRemotePlus_Launcher
{
using System.Windows;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.WindowsAPICodePack.Dialogs;
/// <summary>
/// App.xaml の相互作用ロジック
/// 参考: https://garafu.blogspot.com/2015/06/dev-tasktray-residentapplication.html
/// </summary>
public partial class App : Application
{
private NotifyIconWrapper notifyIcon;
private ObservableCollection<string> Log;
private Process Apache;
private string CurrentFolder;
private string CurrentFilePath;
private string CurrentFileName;
private string CurrentFileNameWithoutExtension;
/// <summary>
/// System.Windows.Application.Startup イベント を発生させます。
/// </summary>
/// <param name="e">イベントデータ を格納している StartupEventArgs</param>
protected override void OnStartup(StartupEventArgs e)
{
Debug.WriteLine("Event: OnStartup");
// 実行ファイル名を取得
this.CurrentFilePath = Assembly.GetExecutingAssembly().Location;
this.CurrentFileName = Path.GetFileName(this.CurrentFilePath);
this.CurrentFileNameWithoutExtension = Path.GetFileNameWithoutExtension(this.CurrentFilePath);
// 現在のフォルダを取得
this.CurrentFolder = Directory.GetParent(this.CurrentFilePath).FullName;
// ログのコレクションを作成
this.Log = new ObservableCollection<string>();
// ---------- 多重起動を防止 ----------
// 同じ実行ファイル名のプロセスを取得
Process[] processes = Process.GetProcessesByName(this.CurrentFileNameWithoutExtension);
// 自分自身と同じパスのプロセスを探す
var count = 0;
foreach (var process in processes)
{
// 自分自身と同じパスのプロセス
if (process.MainModule.FileName == this.CurrentFilePath)
{
if (count > 0) // 自分自身はカウントに含めない
{
// エラーダイアログ
var dialog = new TaskDialog();
dialog.Caption = "エラー";
dialog.InstructionText = "同じサーバー (Apache) を複数起動することはできません";
dialog.Text = "複数の TVRemotePlus を起動したい場合は、フォルダを別にした上で Apache のポートが衝突しないように設定してください。";
dialog.Icon = TaskDialogStandardIcon.Error;
dialog.StandardButtons = TaskDialogStandardButtons.Ok;
dialog.Show();
// 現在のアプリケーションを終了
Application.Current.Shutdown();
return;
}
count++;
}
}
// ---------- 起動処理 ----------
base.OnStartup(e);
this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
// ---------- Apache の設定を取得 ----------
try
{
// httpd.conf を開く
StreamReader sr = new StreamReader(this.CurrentFolder + "\\bin\\Apache\\conf\\httpd.conf", Encoding.GetEncoding("UTF-8"));
string httpd_conf = sr.ReadToEnd();
// Apache の設定を取得
// Apache のサーバールート
Application.Current.Properties["ServerRoot"] = Regex.Match(httpd_conf, @"Define SRVROOT\s""(?<SRVROOT>.*)""").Groups["SRVROOT"].Value;
// Apache の html ルート (/htdocs 付き)
Application.Current.Properties["DocumentRoot"] = Application.Current.Properties["ServerRoot"].ToString().TrimEnd('/') + Regex.Match(httpd_conf, @"DocumentRoot ""\$\{SRVROOT\}(?<FOLDER>.*)""").Groups["FOLDER"].Value;
// Apache のローカル IP アドレス
Application.Current.Properties["ServerIP"] = Regex.Match(httpd_conf, @"Define SRVIP\s""(?<SRVIP>.*)""").Groups["SRVIP"].Value;
// Apache の HTTP ポート
Application.Current.Properties["ServerHTTPPort"] = Regex.Match(httpd_conf, @"Define HTTP_PORT\s""(?<HTTP_PORT>.*)""").Groups["HTTP_PORT"].Value;
// Apache の HTTPS ポート
Application.Current.Properties["ServerHTTPSPort"] = Regex.Match(httpd_conf, @"Define HTTPS_PORT\s""(?<HTTPS_PORT>.*)""").Groups["HTTPS_PORT"].Value;
Debug.WriteLine("ServerIP: " + Application.Current.Properties["ServerIP"]);
Debug.WriteLine("ServerHTTPPort: " + Application.Current.Properties["ServerHTTPPort"]);
Debug.WriteLine("ServerHTTPSPort: " + Application.Current.Properties["ServerHTTPSPort"]);
Debug.WriteLine("ServerRoot: " + Application.Current.Properties["ServerRoot"]);
Debug.WriteLine("DocumentRoot: " + Application.Current.Properties["DocumentRoot"]);
}
catch (FileNotFoundException) // httpd.conf が存在しない
{
// エラーダイアログ
var dialog = new TaskDialog();
dialog.Caption = "エラー";
dialog.InstructionText = "サーバー (Apache) の設定ファイルが存在しません";
dialog.Text = "httpd.conf が存在しません。TVRemotePlus が正常にインストールされていない可能性があります。";
dialog.Icon = TaskDialogStandardIcon.Error;
dialog.StandardButtons = TaskDialogStandardButtons.Ok;
dialog.Show();
// 現在のアプリケーションを終了
Application.Current.Shutdown();
return;
}
// タスクトレイにアイコンを表示
// Apache の設定が格納されるのを待ってから
this.notifyIcon = new NotifyIconWrapper();
// ---------- Apache を起動 ----------
// Process オブジェクトを作成
this.Apache = new Process();
// 実行するファイル
this.Apache.StartInfo.FileName = this.CurrentFolder + "\\bin\\Apache\\bin\\httpd.exe";
// 引数
this.Apache.StartInfo.Arguments = "-e debug";
// 作業フォルダ
this.Apache.StartInfo.WorkingDirectory = this.CurrentFolder + "\\bin\\Apache\\bin";
// コンソールウインドウを開くか
this.Apache.StartInfo.CreateNoWindow = true;
// シェル機能を使うか
this.Apache.StartInfo.UseShellExecute = false;
// 出力をストリームに書き込む
this.Apache.StartInfo.RedirectStandardOutput = true;
this.Apache.StartInfo.RedirectStandardError = true;
this.Apache.StartInfo.RedirectStandardInput = false;
// プロセスの終了時にイベントを送る
this.Apache.EnableRaisingEvents = true;
this.Apache.Exited += new EventHandler(OnProcessExited);
// イベントハンドラーを登録
this.Apache.OutputDataReceived += OnOutputDataReceived;
this.Apache.ErrorDataReceived += OnErrorDataReceived;
try
{
// Apache を起動
this.Apache.Start();
//非同期で出力の読み取りを開始
this.Apache.BeginOutputReadLine();
this.Apache.BeginErrorReadLine();
this.Log.Add("サーバー (Apache) を起動しました。 開始時刻: " + this.Apache.StartTime);
Application.Current.Properties["Log"] = this.Log;
}
catch (System.ComponentModel.Win32Exception Exception)
{
// httpd.exe が存在しないなど、プロセスを開始できない場合
Debug.WriteLine("Error: " + Exception.Message);
if (Exception.Message != "" && Exception.Message != null) // 空でないなら
{
this.Log.Add("サーバー (Apache) を起動できませんでした。 " + Exception.Message);
// ログを全てのページで見られるように保存
Application.Current.Properties["Log"] = this.Log;
}
}
}
/// <summary>
/// Process.OutputDataReceived のイベントハンドラー。
// 行が出力されるたびに呼び出されます。
/// </summary>
protected void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
{
// 出力された文字列を表示する
Debug.WriteLine("Apache: " + e.Data + "");
// ログを追加
if (e.Data != "" && e.Data != null) // 空でないなら
{
this.Log.Add(e.Data);
}
// ログを全てのページで見られるように保存
Application.Current.Properties["Log"] = this.Log;
}
/// <summary>
/// Process.ErrorDataReceived のイベントハンドラー。
// エラー行が出力されるたびに呼び出されます。
/// </summary>
protected void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
{
// 出力された文字列を表示する
// 本来はエラーのみ出力されるはずだが Apache の場合はなぜか普通のメッセージも入る
Debug.WriteLine("Apache: " + e.Data + "");
// ログを追加
if (e.Data != "" && e.Data != null) // 空でないなら
{
this.Log.Add(e.Data);
}
// ログを全てのページで見られるように保存
Application.Current.Properties["Log"] = this.Log;
}
/// <summary>
/// Process.Exited のイベントハンドラー。
// プロセスが終了したときに呼び出されます。
/// </summary>
public void OnProcessExited(object sender, System.EventArgs e)
{
Debug.WriteLine(
$"Exit time : {this.Apache.ExitTime}\n" +
$"Exit code : {this.Apache.ExitCode}\n" +
$"Elapsed time : {Math.Round((this.Apache.ExitTime - this.Apache.StartTime).TotalMilliseconds)}");
// ログを全てのページで見られるように保存
if (this.Log != null && Application.Current != null) // 正常終了時に行わない
{
// エラーダイアログ
var dialog = new TaskDialog();
dialog.Caption = "エラー";
dialog.InstructionText = "サーバー (Apache) が異常終了しました";
dialog.Text = "サーバー (Apache) の設定を開き、ログを確認してください。";
dialog.Icon = TaskDialogStandardIcon.Error;
dialog.StandardButtons = TaskDialogStandardButtons.Ok;
dialog.Show();
this.Log.Add("サーバー (Apache) が異常終了しました。 " +
"終了コード: " + this.Apache.ExitCode + " 終了時刻: " + this.Apache.ExitTime + " " +
"経過時間: " + Math.Round((this.Apache.ExitTime - this.Apache.StartTime).TotalMilliseconds) + "ms");
Application.Current.Properties["Log"] = this.Log;
}
}
/// <summary>
/// System.Windows.Application.Exit イベント を発生させます。
/// </summary>
/// <param name="e">イベントデータ を格納している ExitEventArgs</param>
protected override void OnExit(ExitEventArgs e)
{
Debug.WriteLine("Event: OnExit");
base.OnExit(e);
if (this.notifyIcon != null && this.Apache != null)
{
this.notifyIcon.Dispose();
try
{
// Apache を(強制的に)終了
this.Apache.Kill();
}
catch (InvalidOperationException Exception)
{
// Apache がエラーなどで既に終了している場合にスローされる
Debug.WriteLine("Error: " + Exception.Message);
}
}
}
}
}