OSDN Git Service

一覧ウィンドウを複数開けるようにする
[kancollesniffer/KancolleSniffer.git] / KancolleSniffer / MainForm.cs
1 // Copyright (C) 2013, 2014, 2015 Kazuhiro Fujieda <fujieda@users.osdn.me>\r
2 // \r
3 // Licensed under the Apache License, Version 2.0 (the "License");\r
4 // you may not use this file except in compliance with the License.\r
5 // You may obtain a copy of the License at\r
6 //\r
7 //    http://www.apache.org/licenses/LICENSE-2.0\r
8 //\r
9 // Unless required by applicable law or agreed to in writing, software\r
10 // distributed under the License is distributed on an "AS IS" BASIS,\r
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
12 // See the License for the specific language governing permissions and\r
13 // limitations under the License.\r
14 \r
15 using System;\r
16 using System.Collections.Generic;\r
17 using System.ComponentModel;\r
18 using System.Diagnostics;\r
19 using System.Drawing;\r
20 using System.Globalization;\r
21 using System.IO;\r
22 using System.Linq;\r
23 using System.Net;\r
24 using System.Runtime.InteropServices;\r
25 using System.Text;\r
26 using System.Text.RegularExpressions;\r
27 using System.Threading;\r
28 using System.Threading.Tasks;\r
29 using System.Windows.Forms;\r
30 using DynaJson;\r
31 using KancolleSniffer.Log;\r
32 using KancolleSniffer.Model;\r
33 using KancolleSniffer.Net;\r
34 using KancolleSniffer.Util;\r
35 using KancolleSniffer.View;\r
36 using Microsoft.CSharp.RuntimeBinder;\r
37 using static System.Math;\r
38 using Clipboard = KancolleSniffer.Util.Clipboard;\r
39 using Timer = System.Windows.Forms.Timer;\r
40 \r
41 namespace KancolleSniffer\r
42 {\r
43     public partial class MainForm : Form\r
44     {\r
45         private readonly ConfigDialog _configDialog;\r
46         private readonly ProxyManager _proxyManager;\r
47         private readonly ResizableToolTip _toolTip = new ResizableToolTip();\r
48         private readonly ResizableToolTip _tooltipCopy = new ResizableToolTip {ShowAlways = false, AutomaticDelay = 0};\r
49         private int _currentFleet;\r
50         private bool _combinedFleet;\r
51         private readonly MainShipLabels _mainLabels = new MainShipLabels();\r
52         private readonly MainNDockLabels _ndockLabels = new MainNDockLabels();\r
53         private NumberAndHistory _numberAndHistory;\r
54         private readonly ListFormGroup _listFormGroup;\r
55 \r
56         private readonly NotificationManager _notificationManager;\r
57         private bool _started;\r
58         private bool _timerEnabled;\r
59         private string _debugLogFile;\r
60         private IEnumerator<string> _playLog;\r
61         private DateTime _prev, _now;\r
62 \r
63         private readonly ErrorDialog _errorDialog = new ErrorDialog();\r
64         private readonly ErrorLog _errorLog;\r
65 \r
66         public Sniffer Sniffer { get; } = new Sniffer();\r
67         public Config Config { get; } = new Config();\r
68 \r
69         public MainForm()\r
70         {\r
71             InitializeComponent();\r
72             HttpProxy.AfterSessionComplete += HttpProxy_AfterSessionComplete;\r
73             Config.Load();\r
74             _configDialog = new ConfigDialog(this);\r
75             _listFormGroup = new ListFormGroup(this);\r
76             _notificationManager = new NotificationManager(Alarm);\r
77             SetupView(_notificationManager);\r
78             _proxyManager = new ProxyManager(this);\r
79             _proxyManager.UpdatePacFile();\r
80             _errorLog = new ErrorLog(Sniffer);\r
81             LoadData();\r
82             Sniffer.RepeatingTimerController = new RepeatingTimerController(this);\r
83         }\r
84 \r
85         private void SetupView(NotificationManager manager)\r
86         {\r
87             SetScaleFactorOfDpiScaling();\r
88             SetupFleetClick();\r
89             CreateMainLabels();\r
90             CreateNumberAndHistory(manager);\r
91             labelPresetAkashiTimer.BackColor = CustomColors.ColumnColors.Bright;\r
92             SetupQuestPanel();\r
93             panelRepairList.CreateLabels(panelRepairList_Click);\r
94             PerformZoom();\r
95         }\r
96 \r
97         private void SetScaleFactorOfDpiScaling()\r
98         {\r
99             var autoScaleDimensions = new SizeF(6f, 12f); // AutoScaleDimensionの初期値\r
100             Scaler.Factor = new SizeF(CurrentAutoScaleDimensions.Width / autoScaleDimensions.Width,\r
101                 CurrentAutoScaleDimensions.Height / autoScaleDimensions.Height);\r
102         }\r
103 \r
104         private void SetupQuestPanel()\r
105         {\r
106             int prevHeight = questPanel.Height;\r
107             questPanel.CreateLabels(Config.QuestLines, labelQuest_DoubleClick);\r
108             Height += questPanel.Height - prevHeight;\r
109         }\r
110 \r
111         private void CreateMainLabels()\r
112         {\r
113             _mainLabels.CreateAllShipLabels(new MainShipPanels\r
114             {\r
115                 PanelShipInfo = panelShipInfo,\r
116                 Panel7Ships = panel7Ships,\r
117                 PanelCombinedFleet = panelCombinedFleet\r
118             }, ShowShipOnShipList);\r
119             _ndockLabels.Create(panelDock, labelNDock_Click);\r
120         }\r
121 \r
122         private void CreateNumberAndHistory(NotificationManager manager)\r
123         {\r
124             _numberAndHistory = new NumberAndHistory(new NumberAndHistoryLabels\r
125             {\r
126                 NumOfShips = labelNumOfShips,\r
127                 NumOfEquips = labelNumOfEquips,\r
128                 NumOfBuckets = labelNumOfBuckets,\r
129                 BucketHistory = labelBucketHistory,\r
130                 Achievement = labelAchievement,\r
131                 FuelHistory = labelFuelHistory,\r
132                 BulletHistory = labelBulletHistory,\r
133                 SteelHistory = labelSteelHistory,\r
134                 BauxiteHistory = labelBouxiteHistory,\r
135                 ToolTip = _toolTip\r
136             }, Sniffer, new NotifySubmitter(manager));\r
137         }\r
138 \r
139         private class NotifySubmitter : INotifySubmitter\r
140         {\r
141             private readonly NotificationManager _manager;\r
142 \r
143             public NotifySubmitter(NotificationManager manager)\r
144             {\r
145                 _manager = manager;\r
146             }\r
147 \r
148             public void Flash()\r
149             {\r
150                 _manager.Flash();\r
151             }\r
152 \r
153             public void Enqueue(string key, string subject)\r
154             {\r
155                 _manager.Enqueue(key, subject);\r
156             }\r
157         }\r
158 \r
159         /// <summary>\r
160         /// パネルのz-orderがくるうのを避ける\r
161         /// https://stackoverflow.com/a/5777090/1429506\r
162         /// </summary>\r
163         private void MainForm_Shown(object sender, EventArgs e)\r
164         {\r
165             // ReSharper disable once NotAccessedVariable\r
166             IntPtr handle;\r
167             foreach (var panel in new[] {panelShipInfo, panel7Ships, panelCombinedFleet})\r
168                 // ReSharper disable once RedundantAssignment\r
169                 handle = panel.Handle;\r
170         }\r
171 \r
172         private readonly FileSystemWatcher _watcher = new FileSystemWatcher\r
173         {\r
174             Path = AppDomain.CurrentDomain.BaseDirectory,\r
175             NotifyFilter = NotifyFilters.LastWrite\r
176         };\r
177 \r
178         private readonly Timer _watcherTimer = new Timer {Interval = 1000};\r
179 \r
180         private void LoadData()\r
181         {\r
182             var target = "";\r
183             Sniffer.LoadState();\r
184             _watcher.SynchronizingObject = this;\r
185             _watcherTimer.Tick += (sender, ev) =>\r
186             {\r
187                 _watcherTimer.Stop();\r
188                 switch (target)\r
189                 {\r
190                     case "status.xml":\r
191                         Sniffer.LoadState();\r
192                         break;\r
193                     case "TP.csv":\r
194                         Sniffer.AdditionalData.LoadTpSpec();\r
195                         break;\r
196                 }\r
197             };\r
198             _watcher.Changed += (sender, ev) =>\r
199             {\r
200                 target = ev.Name;\r
201                 _watcherTimer.Stop();\r
202                 _watcherTimer.Start();\r
203             };\r
204             _watcher.EnableRaisingEvents = true;\r
205         }\r
206 \r
207         private class RepeatingTimerController : Sniffer.IRepeatingTimerController\r
208         {\r
209             private readonly NotificationManager _manager;\r
210             private readonly Config _config;\r
211 \r
212             public RepeatingTimerController(MainForm main)\r
213             {\r
214                 _manager = main._notificationManager;\r
215                 _config = main.Config;\r
216             }\r
217 \r
218             public void Stop(string key)\r
219             {\r
220                 _manager.StopRepeat(key,\r
221                     (key == "入渠終了" || key == "遠征終了") &&\r
222                     (_config.Notifications[key].Flags & NotificationType.Cont) != 0);\r
223             }\r
224 \r
225             public void Stop(string key, int fleet) => _manager.StopRepeat(key, fleet);\r
226 \r
227             public void Suspend(string exception = null) => _manager.SuspendRepeat(exception);\r
228 \r
229             public void Resume() => _manager.ResumeRepeat();\r
230         }\r
231 \r
232         private void HttpProxy_AfterSessionComplete(HttpProxy.Session session)\r
233         {\r
234             BeginInvoke(new Action<HttpProxy.Session>(ProcessRequest), session);\r
235         }\r
236 \r
237         private void ProcessRequest(HttpProxy.Session session)\r
238         {\r
239             var url = session.Request.PathAndQuery;\r
240             if (!url.Contains("kcsapi/"))\r
241                 return;\r
242             var request = session.Request.BodyAsString;\r
243             var response = session.Response.BodyAsString;\r
244             Privacy.Remove(ref url, ref request, ref response);\r
245             if (response == null || !response.StartsWith("svdata="))\r
246             {\r
247                 WriteDebugLog(url, request, response);\r
248                 return;\r
249             }\r
250             response = UnEscapeString(response.Remove(0, "svdata=".Length));\r
251             WriteDebugLog(url, request, response);\r
252             ProcessRequestMain(url, request, response);\r
253         }\r
254 \r
255         private void ProcessRequestMain(string url, string request, string response)\r
256         {\r
257             try\r
258             {\r
259                 UpdateInfo(Sniffer.Sniff(url, request, JsonObject.Parse(response)));\r
260                 _errorLog.CheckBattleApi(url, request, response);\r
261             }\r
262 \r
263             catch (RuntimeBinderException e)\r
264             {\r
265                 if (_errorDialog.ShowDialog(this,\r
266                         "艦これに仕様変更があったか、受信内容が壊れています。",\r
267                         _errorLog.GenerateErrorLog(url, request, response, e.ToString())) == DialogResult.Abort)\r
268                     Exit();\r
269             }\r
270             catch (LogIOException e)\r
271             {\r
272                 // ReSharper disable once PossibleNullReferenceException\r
273                 if (_errorDialog.ShowDialog(this, e.Message, e.InnerException.ToString()) == DialogResult.Abort)\r
274                     Exit();\r
275             }\r
276             catch (BattleResultError)\r
277             {\r
278                 if (_errorDialog.ShowDialog(this, "戦闘結果の計算に誤りがあります。",\r
279                         _errorLog.GenerateBattleErrorLog()) == DialogResult.Abort)\r
280                     Exit();\r
281             }\r
282             catch (Exception e)\r
283             {\r
284                 if (_errorDialog.ShowDialog(this, "エラーが発生しました。",\r
285                         _errorLog.GenerateErrorLog(url, request, response, e.ToString())) == DialogResult.Abort)\r
286                     Exit();\r
287             }\r
288         }\r
289 \r
290         private void Exit()\r
291         {\r
292             _proxyManager.Shutdown();\r
293             Environment.Exit(1);\r
294         }\r
295 \r
296         private void WriteDebugLog(string url, string request, string response)\r
297         {\r
298             if (_debugLogFile != null)\r
299             {\r
300                 File.AppendAllText(_debugLogFile,\r
301                     $"date: {DateTime.Now:g}\nurl: {url}\nrequest: {request}\nresponse: {response ?? "(null)"}\n");\r
302             }\r
303         }\r
304 \r
305         private string UnEscapeString(string s)\r
306         {\r
307             try\r
308             {\r
309                 var rx = new Regex(@"\\[uU]([0-9A-Fa-f]{4})");\r
310                 return rx.Replace(s,\r
311                     match => ((char)int.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString());\r
312             }\r
313             catch (ArgumentException)\r
314             {\r
315                 return s;\r
316             }\r
317         }\r
318 \r
319         private void UpdateInfo(Sniffer.Update update)\r
320         {\r
321             if (update == Sniffer.Update.Start)\r
322             {\r
323                 labelLogin.Visible = false;\r
324                 linkLabelGuide.Visible = false;\r
325                 _started = true;\r
326                 _notificationManager.StopAllRepeat();\r
327                 return;\r
328             }\r
329             if (!_started)\r
330                 return;\r
331             if (_now == DateTime.MinValue)\r
332                 _now = DateTime.Now;\r
333             if ((update & Sniffer.Update.Item) != 0)\r
334                 UpdateItemInfo();\r
335             if ((update & Sniffer.Update.Timer) != 0)\r
336                 UpdateTimers();\r
337             if ((update & Sniffer.Update.NDock) != 0)\r
338                 UpdateNDocLabels();\r
339             if ((update & Sniffer.Update.Mission) != 0)\r
340                 UpdateMissionLabels();\r
341             if ((update & Sniffer.Update.QuestList) != 0)\r
342                 UpdateQuestList();\r
343             if ((update & Sniffer.Update.Ship) != 0)\r
344                 UpdateShipInfo();\r
345             if ((update & Sniffer.Update.Battle) != 0)\r
346                 UpdateBattleInfo();\r
347             if ((update & Sniffer.Update.Cell) != 0)\r
348                 UpdateCellInfo();\r
349         }\r
350 \r
351         private void MainForm_Load(object sender, EventArgs e)\r
352         {\r
353             SuppressActivate.Start();\r
354             RestoreLocation();\r
355             if (Config.HideOnMinimized && WindowState == FormWindowState.Minimized)\r
356                 ShowInTaskbar = false;\r
357             if (Config.ShowHpInPercent)\r
358                 _mainLabels.ToggleHpPercent();\r
359             if (Config.ShipList.Visible)\r
360                 _listFormGroup.Show();\r
361             ApplyConfig();\r
362             ApplyDebugLogSetting();\r
363             ApplyLogSetting();\r
364             ApplyProxySetting();\r
365             CheckVersionUp((current, latest) =>\r
366             {\r
367                 if (latest == current)\r
368                     return;\r
369                 linkLabelGuide.Text = $"バージョン{latest}があります。";\r
370                 linkLabelGuide.LinkArea = new LinkArea(0, linkLabelGuide.Text.Length);\r
371                 linkLabelGuide.Click += (obj, ev) =>\r
372                 {\r
373                     Process.Start("https://ja.osdn.net/rel/kancollesniffer/" + latest);\r
374                 };\r
375             });\r
376         }\r
377 \r
378         public async void CheckVersionUp(Action<string, string> action)\r
379         {\r
380             var current = string.Join(".", Application.ProductVersion.Split('.').Take(2));\r
381             try\r
382             {\r
383                 var latest = (await new WebClient().DownloadStringTaskAsync("http://kancollesniffer.osdn.jp/version"))\r
384                     .TrimEnd();\r
385                 try\r
386                 {\r
387                     action(current, latest);\r
388                 }\r
389                 catch (InvalidOperationException)\r
390                 {\r
391                 }\r
392             }\r
393             catch (WebException)\r
394             {\r
395             }\r
396         }\r
397 \r
398         private void MainForm_FormClosing(object sender, FormClosingEventArgs e)\r
399         {\r
400             if (!Config.ExitSilently)\r
401             {\r
402                 using var dialog = new ConfirmDialog();\r
403                 if (dialog.ShowDialog(this) != DialogResult.Yes)\r
404                 {\r
405                     e.Cancel = true;\r
406                     return;\r
407                 }\r
408             }\r
409             _listFormGroup.Close();\r
410             Sniffer.FlashLog();\r
411             Config.Location = (WindowState == FormWindowState.Normal ? Bounds : RestoreBounds).Location;\r
412             Config.ShowHpInPercent = _mainLabels.ShowHpInPercent;\r
413             Config.Save();\r
414             Sniffer.SaveState();\r
415             _proxyManager.Shutdown();\r
416         }\r
417 \r
418         private void MainForm_Resize(object sender, EventArgs e)\r
419         {\r
420             if (_listFormGroup == null) // DPIが100%でないときにInitializeComponentから呼ばれるので\r
421                 return;\r
422             SuppressActivate.Start();\r
423             if (WindowState == FormWindowState.Minimized)\r
424             {\r
425                 if (Config.HideOnMinimized)\r
426                     ShowInTaskbar = false;\r
427             }\r
428             _listFormGroup.Main.ChangeWindowState(WindowState);\r
429         }\r
430 \r
431         public TimeOutChecker SuppressActivate = new TimeOutChecker();\r
432 \r
433         private void MainForm_Activated(object sender, EventArgs e)\r
434         {\r
435             if (SuppressActivate.Check())\r
436                 return;\r
437             if (NeedRaise)\r
438                 RaiseBothWindows();\r
439         }\r
440 \r
441         private bool NeedRaise => _listFormGroup.Visible && WindowState != FormWindowState.Minimized;\r
442 \r
443         private void RaiseBothWindows()\r
444         {\r
445             _listFormGroup.Main.Owner = null;\r
446             Owner = _listFormGroup.Main;\r
447             BringToFront();\r
448             Owner = null;\r
449         }\r
450 \r
451         public class TimeOutChecker\r
452         {\r
453             private DateTime _lastCheck;\r
454             private readonly TimeSpan _timeout = TimeSpan.FromMilliseconds(500);\r
455 \r
456             public void Start()\r
457             {\r
458                 _lastCheck = DateTime.Now;\r
459             }\r
460 \r
461             public bool Check()\r
462             {\r
463                 var now = DateTime.Now;\r
464                 var last = _lastCheck;\r
465                 _lastCheck = now;\r
466                 return now - last < _timeout;\r
467             }\r
468         }\r
469 \r
470         private void notifyIconMain_MouseDoubleClick(object sender, MouseEventArgs e)\r
471         {\r
472             NotifyIconOpenToolStripMenuItem_Click(sender, e);\r
473         }\r
474 \r
475         private void NotifyIconOpenToolStripMenuItem_Click(object sender, EventArgs e)\r
476         {\r
477             ShowInTaskbar = true;\r
478             WindowState = FormWindowState.Normal;\r
479             TopMost = _listFormGroup.TopMost = Config.TopMost; // 最前面に表示されなくなることがあるのを回避する\r
480         }\r
481 \r
482         private void ExitToolStripMenuItem_Click(object sender, EventArgs e)\r
483         {\r
484             Close();\r
485         }\r
486 \r
487         private void ConfigToolStripMenuItem_Click(object sender, EventArgs e)\r
488         {\r
489             if (_configDialog.ShowDialog(this) == DialogResult.OK)\r
490             {\r
491                 Config.Save();\r
492                 ApplyConfig();\r
493                 StopRepeatingTimer(_configDialog.RepeatSettingsChanged);\r
494             }\r
495         }\r
496 \r
497         private void StopRepeatingTimer(IEnumerable<string> names)\r
498         {\r
499             foreach (var name in names)\r
500                 _notificationManager.StopRepeat(name);\r
501         }\r
502 \r
503         private void PerformZoom()\r
504         {\r
505             if (Config.Zoom == 100)\r
506             {\r
507                 ShipLabel.Name.BaseFont = Font;\r
508                 ShipLabel.Name.LatinFont = LatinFont();\r
509                 return;\r
510             }\r
511             var prev = CurrentAutoScaleDimensions;\r
512             foreach (var control in new Control[]\r
513             {\r
514                 this, labelLogin, linkLabelGuide,\r
515                 _configDialog, _configDialog.NotificationConfigDialog,\r
516                 contextMenuStripMain, _errorDialog\r
517             })\r
518             {\r
519                 control.Font = ZoomFont(control.Font);\r
520             }\r
521             _listFormGroup.Font = ZoomFont(_listFormGroup.Font);\r
522             foreach (var toolTip in new[] {_toolTip, _tooltipCopy})\r
523             {\r
524                 toolTip.Font = ZoomFont(toolTip.Font);\r
525             }\r
526             ShipLabel.Name.BaseFont = Font;\r
527             ShipLabel.Name.LatinFont = LatinFont();\r
528             var cur = CurrentAutoScaleDimensions;\r
529             Scaler.Factor = Scaler.Scale(cur.Width / prev.Width, cur.Height / prev.Height);\r
530         }\r
531 \r
532         private Font ZoomFont(Font font)\r
533         {\r
534             return new Font(font.FontFamily, font.Size * Config.Zoom / 100);\r
535         }\r
536 \r
537         private Font LatinFont()\r
538         {\r
539             return new Font("Tahoma", 8f * Config.Zoom / 100);\r
540         }\r
541 \r
542         private void RestoreLocation()\r
543         {\r
544             if (Config.Location.X == int.MinValue)\r
545                 return;\r
546             if (IsTitleBarOnAnyScreen(Config.Location))\r
547                 Location = Config.Location;\r
548         }\r
549 \r
550         private void ApplyConfig()\r
551         {\r
552             if (TopMost != Config.TopMost)\r
553                 TopMost = _listFormGroup.TopMost = Config.TopMost;\r
554             Sniffer.ShipCounter.Margin = Config.MarginShips;\r
555             _numberAndHistory.UpdateNumOfShips();\r
556             Sniffer.ItemCounter.Margin = Config.MarginEquips;\r
557             _numberAndHistory.UpdateNumOfEquips();\r
558             Sniffer.Achievement.ResetHours = Config.ResetHours;\r
559             labelAkashiRepair.Visible = labelAkashiRepairTimer.Visible =\r
560                 labelPresetAkashiTimer.Visible = Config.UsePresetAkashi;\r
561             Sniffer.WarnBadDamageWithDameCon = Config.WarnBadDamageWithDameCon;\r
562         }\r
563 \r
564         public void ApplyDebugLogSetting()\r
565         {\r
566             _debugLogFile = Config.DebugLogging ? Config.DebugLogFile : null;\r
567         }\r
568 \r
569         public bool ApplyProxySetting()\r
570         {\r
571             return _proxyManager.ApplyConfig();\r
572         }\r
573 \r
574         public void ApplyLogSetting()\r
575         {\r
576             LogServer.OutputDir = Config.Log.OutputDir;\r
577             LogServer.LogProcessor = new LogProcessor(Sniffer.Material.MaterialHistory, Sniffer.MapDictionary);\r
578             Sniffer.EnableLog(Config.Log.On ? LogType.All : LogType.None);\r
579             Sniffer.MaterialLogInterval = Config.Log.MaterialLogInterval;\r
580             Sniffer.LogOutputDir = Config.Log.OutputDir;\r
581         }\r
582 \r
583         public static bool IsTitleBarOnAnyScreen(Point location)\r
584         {\r
585             var rect = new Rectangle(\r
586                 new Point(location.X + SystemInformation.IconSize.Width + SystemInformation.HorizontalFocusThickness,\r
587                     location.Y + SystemInformation.CaptionHeight), new Size(60, 1));\r
588             return Screen.AllScreens.Any(screen => screen.WorkingArea.Contains(rect));\r
589         }\r
590 \r
591         private void timerMain_Tick(object sender, EventArgs e)\r
592         {\r
593             if (_timerEnabled)\r
594             {\r
595                 try\r
596                 {\r
597                     _now = DateTime.Now;\r
598                     UpdateTimers();\r
599                     NotifyTimers();\r
600                     _prev = _now;\r
601                 }\r
602                 catch (Exception ex)\r
603                 {\r
604                     if (_errorDialog.ShowDialog(this, "エラーが発生しました。", ex.ToString()) == DialogResult.Abort)\r
605                         Exit();\r
606                 }\r
607             }\r
608             if (_playLog == null || _configDialog.Visible)\r
609             {\r
610                 labelPlayLog.Visible = false;\r
611                 return;\r
612             }\r
613             PlayLog();\r
614         }\r
615 \r
616         public void SetPlayLog(string file)\r
617         {\r
618             _playLog = File.ReadLines(file).GetEnumerator();\r
619         }\r
620 \r
621         private void PlayLog()\r
622         {\r
623             var lines = new List<string>();\r
624             foreach (var s in new[] {"url: ", "request: ", "response: "})\r
625             {\r
626                 do\r
627                 {\r
628                     if (!_playLog.MoveNext() || _playLog.Current == null)\r
629                     {\r
630                         labelPlayLog.Visible = false;\r
631                         return;\r
632                     }\r
633                 } while (!_playLog.Current.StartsWith(s));\r
634                 lines.Add(_playLog.Current.Substring(s.Length));\r
635             }\r
636             labelPlayLog.Visible = !labelPlayLog.Visible;\r
637             ProcessRequestMain(lines[0], lines[1], lines[2]);\r
638         }\r
639 \r
640         private void ShowShipOnShipList(object sender, EventArgs ev)\r
641         {\r
642             if (!_listFormGroup.Visible)\r
643                 return;\r
644             var idx = (int)((Control)sender).Tag;\r
645             var ship = (_combinedFleet\r
646                 ? Sniffer.Fleets[0].Ships.Concat(Sniffer.Fleets[1].Ships).ToArray()\r
647                 : Sniffer.Fleets[_currentFleet].Ships)[idx];\r
648             if (!ship.Empty)\r
649                 _listFormGroup.ShowShip(ship.Id);\r
650         }\r
651 \r
652 \r
653         private void UpdateItemInfo()\r
654         {\r
655             _numberAndHistory.Update();\r
656             if (_listFormGroup.Visible)\r
657                 _listFormGroup.UpdateList();\r
658         }\r
659 \r
660         private void UpdateShipInfo()\r
661         {\r
662             SetCurrentFleet();\r
663             SetCombined();\r
664             UpdatePanelShipInfo();\r
665             NotifyDamagedShip();\r
666             UpdateChargeInfo();\r
667             UpdateRepairList();\r
668             UpdateMissionLabels();\r
669             if (_listFormGroup.Visible)\r
670                 _listFormGroup.UpdateList();\r
671         }\r
672 \r
673         private bool _inSortie;\r
674 \r
675         private void SetCurrentFleet()\r
676         {\r
677             var inSortie = Sniffer.InSortie;\r
678             if (_inSortie || inSortie == -1)\r
679             {\r
680                 _inSortie = inSortie != -1;\r
681                 return;\r
682             }\r
683             _inSortie = true;\r
684             if (inSortie == 10)\r
685             {\r
686                 _combinedFleet = true;\r
687                 _currentFleet = 0;\r
688             }\r
689             else\r
690             {\r
691                 _combinedFleet = false;\r
692                 _currentFleet = inSortie;\r
693             }\r
694         }\r
695 \r
696         private bool _prevCombined;\r
697 \r
698         private void SetCombined()\r
699         {\r
700             if (Sniffer.IsCombinedFleet && !_prevCombined)\r
701             {\r
702                 _combinedFleet = true;\r
703                 _currentFleet = 0;\r
704             }\r
705             _prevCombined = Sniffer.IsCombinedFleet;\r
706         }\r
707 \r
708         private void UpdatePanelShipInfo()\r
709         {\r
710             var ships = Sniffer.Fleets[_currentFleet].ActualShips;\r
711             panel7Ships.Visible = ships.Count == 7;\r
712             _mainLabels.SetShipLabels(ships);\r
713             ShowCombinedFleet();\r
714             ShowCurrentFleetNumber();\r
715             UpdateAkashiTimer();\r
716             UpdateFighterPower(IsCombinedFighterPower);\r
717             UpdateLoS();\r
718             UpdateCondTimers();\r
719         }\r
720 \r
721         private void ShowCombinedFleet()\r
722         {\r
723             if (!Sniffer.IsCombinedFleet)\r
724                 _combinedFleet = false;\r
725             labelFleet1.Text = _combinedFleet ? CombinedName : "第一";\r
726             panelCombinedFleet.Visible = _combinedFleet;\r
727             if (_combinedFleet)\r
728                 _mainLabels.SetCombinedShipLabels(Sniffer.Fleets[0].ActualShips, Sniffer.Fleets[1].ActualShips);\r
729         }\r
730 \r
731         private void ShowCurrentFleetNumber()\r
732         {\r
733             var labels = new[] {labelCheckFleet1, labelCheckFleet2, labelCheckFleet3, labelCheckFleet4};\r
734             for (var i = 0; i < labels.Length; i++)\r
735                 labels[i].Visible = _currentFleet == i;\r
736         }\r
737 \r
738         private bool IsCombinedFighterPower => _combinedFleet &&\r
739                                                (Sniffer.Battle.BattleState == BattleState.None ||\r
740                                                 Sniffer.Battle.EnemyIsCombined);\r
741 \r
742         private string CombinedName\r
743         {\r
744             get\r
745             {\r
746                 switch (Sniffer.Fleets[0].CombinedType)\r
747                 {\r
748                     case CombinedType.Carrier:\r
749                         return "機動";\r
750                     case CombinedType.Surface:\r
751                         return "水上";\r
752                     case CombinedType.Transport:\r
753                         return "輸送";\r
754                     default:\r
755                         return "連合";\r
756                 }\r
757             }\r
758         }\r
759 \r
760         private void NotifyDamagedShip()\r
761         {\r
762             _notificationManager.StopRepeat("大破警告");\r
763             if (!Sniffer.BadlyDamagedShips.Any())\r
764                 return;\r
765             SetNotification("大破警告", string.Join(" ", Sniffer.BadlyDamagedShips));\r
766             _notificationManager.Flash();\r
767         }\r
768 \r
769         private void UpdateFighterPower(bool combined)\r
770         {\r
771             var fleets = Sniffer.Fleets;\r
772             var fp = combined\r
773                 ? fleets[0].FighterPower + fleets[1].FighterPower\r
774                 : fleets[_currentFleet].FighterPower;\r
775             labelFighterPower.Text = fp.Min.ToString("D");\r
776             var cr = combined\r
777                 ? fleets[0].ContactTriggerRate + fleets[1].ContactTriggerRate\r
778                 : fleets[_currentFleet].ContactTriggerRate;\r
779             var text = "制空: " + (fp.Diff ? fp.RangeString : fp.Min.ToString()) +\r
780                        $" 触接: {cr * 100:f1}";\r
781             _toolTip.SetToolTip(labelFighterPower, text);\r
782             _toolTip.SetToolTip(labelFighterPowerCaption, text);\r
783         }\r
784 \r
785         private void UpdateLoS()\r
786         {\r
787             var fleet = Sniffer.Fleets[_currentFleet];\r
788             labelLoS.Text = RoundDown(fleet.GetLineOfSights(1)).ToString("F1");\r
789             var text = $"係数2: {RoundDown(fleet.GetLineOfSights(2)):F1}\r\n" +\r
790                        $"係数3: {RoundDown(fleet.GetLineOfSights(3)):F1}\r\n" +\r
791                        $"係数4: {RoundDown(fleet.GetLineOfSights(4)):F1}";\r
792             _toolTip.SetToolTip(labelLoS, text);\r
793             _toolTip.SetToolTip(labelLoSCaption, text);\r
794         }\r
795 \r
796         private double RoundDown(double number)\r
797         {\r
798             return Floor(number * 10) / 10.0;\r
799         }\r
800 \r
801         private void UpdateBattleInfo()\r
802         {\r
803             ResetBattleInfo();\r
804             _listFormGroup.UpdateBattleResult();\r
805             _listFormGroup.UpdateAirBattleResult();\r
806             if (Sniffer.Battle.BattleState == BattleState.None)\r
807                 return;\r
808             panelBattleInfo.BringToFront();\r
809             var battle = Sniffer.Battle;\r
810             labelFormation.Text = new[] {"同航戦", "反航戦", "T字有利", "T字不利"}[battle.Formation[2] - 1];\r
811             UpdateBattleFighterPower();\r
812             if ((Config.Spoilers & Spoiler.ResultRank) != 0)\r
813                 ShowResultRank();\r
814         }\r
815 \r
816         private void UpdateCellInfo()\r
817         {\r
818             _listFormGroup.UpdateCellInfo();\r
819         }\r
820 \r
821         private void ResetBattleInfo()\r
822         {\r
823             labelFormation.Text = "";\r
824             labelEnemyFighterPower.Text = "";\r
825             labelFighterPower.ForeColor = DefaultForeColor;\r
826             labelFighterPowerCaption.Text = "制空";\r
827             labelResultRank.Text = "判定";\r
828             panelBattleInfo.Visible = Sniffer.Battle.BattleState != BattleState.None;\r
829         }\r
830 \r
831         private void UpdateBattleFighterPower()\r
832         {\r
833             UpdateEnemyFighterPower();\r
834             var battle = Sniffer.Battle;\r
835             labelFighterPower.ForeColor = AirControlLevelColor(battle);\r
836             labelFighterPowerCaption.Text = AirControlLevelString(battle);\r
837             if (battle.BattleState == BattleState.AirRaid)\r
838             {\r
839                 UpdateAirRaidFighterPower();\r
840             }\r
841             else\r
842             {\r
843                 UpdateFighterPower(Sniffer.IsCombinedFleet && battle.EnemyIsCombined);\r
844             }\r
845         }\r
846 \r
847         private void UpdateEnemyFighterPower()\r
848         {\r
849             var fp = Sniffer.Battle.EnemyFighterPower;\r
850             labelEnemyFighterPower.Text = fp.AirCombat + fp.UnknownMark;\r
851             var toolTip = fp.AirCombat == fp.Interception ? "" : "防空: " + fp.Interception + fp.UnknownMark;\r
852             _toolTip.SetToolTip(labelEnemyFighterPower, toolTip);\r
853             _toolTip.SetToolTip(labelEnemyFighterPowerCaption, toolTip);\r
854         }\r
855 \r
856         private void UpdateAirRaidFighterPower()\r
857         {\r
858             var fp = Sniffer.Battle.FighterPower;\r
859             labelFighterPower.Text = fp.Min.ToString();\r
860             var toolTop = fp.Diff ? fp.RangeString : "";\r
861             _toolTip.SetToolTip(labelFighterPower, toolTop);\r
862             _toolTip.SetToolTip(labelFighterPowerCaption, toolTop);\r
863         }\r
864 \r
865         private static Color AirControlLevelColor(BattleInfo battle)\r
866         {\r
867             return new[]\r
868                 {DefaultForeColor, DefaultForeColor, CUDColors.Blue, CUDColors.Green, CUDColors.Orange, CUDColors.Red}[\r
869                 battle.BattleState == BattleState.Night ? 0 : battle.AirControlLevel + 1];\r
870         }\r
871 \r
872         private static string AirControlLevelString(BattleInfo battle)\r
873         {\r
874             return new[] {"制空", "拮抗", "確保", "優勢", "劣勢", "喪失"}[\r
875                 battle.BattleState == BattleState.Night ? 0 : battle.AirControlLevel + 1];\r
876         }\r
877 \r
878         private void ShowResultRank()\r
879         {\r
880             var result = new[] {"完全S", "勝利S", "勝利A", "勝利B", "敗北C", "敗北D", "敗北E"};\r
881             labelResultRank.Text = result[(int)Sniffer.Battle.ResultRank];\r
882         }\r
883 \r
884         private void labelResultRank_Click(object sender, EventArgs e)\r
885         {\r
886             ShowResultRank();\r
887         }\r
888 \r
889         private void UpdateChargeInfo()\r
890         {\r
891             var fuelSq = new[] {labelFuelSq1, labelFuelSq2, labelFuelSq3, labelFuelSq4};\r
892             var bullSq = new[] {labelBullSq1, labelBullSq2, labelBullSq3, labelBullSq4};\r
893 \r
894             for (var i = 0; i < fuelSq.Length; i++)\r
895             {\r
896                 var stat = Sniffer.Fleets[i].ChargeStatus;\r
897                 fuelSq[i].ImageIndex = stat.Fuel;\r
898                 bullSq[i].ImageIndex = stat.Bull;\r
899                 var text = stat.Empty ? "" : $"燃{stat.FuelRatio * 100:f1}% 弾{stat.BullRatio * 100:f1}%";\r
900                 _toolTip.SetToolTip(fuelSq[i], text);\r
901                 _toolTip.SetToolTip(bullSq[i], text);\r
902             }\r
903         }\r
904 \r
905         private void UpdateNDocLabels()\r
906         {\r
907             _ndockLabels.SetName(Sniffer.NDock);\r
908             SetNDockLabel();\r
909         }\r
910 \r
911         private void SetNDockLabel()\r
912         {\r
913             labelNDock.Text = (Config.ShowEndTime & TimerKind.NDock) != 0 ? "入渠終了" : "入渠";\r
914         }\r
915 \r
916         private void labelNDock_Click(object sender, EventArgs e)\r
917         {\r
918             Config.ShowEndTime ^= TimerKind.NDock;\r
919             SetNDockLabel();\r
920             UpdateTimers();\r
921         }\r
922 \r
923         private void UpdateMissionLabels()\r
924         {\r
925             var nameLabels = new[] {labelMissionName1, labelMissionName2, labelMissionName3};\r
926             var paramsLabels = new[] {labelMissionParams1, labelMissionParams2, labelMissionParams3};\r
927             var names = Sniffer.Missions.Select(mission => mission.Name).ToArray();\r
928             for (var i = 0; i < ShipInfo.FleetCount - 1; i++)\r
929             {\r
930                 var fleetParams = Sniffer.Fleets[i + 1].MissionParameter;\r
931                 var inPort = string.IsNullOrEmpty(names[i]);\r
932                 paramsLabels[i].Visible = inPort;\r
933                 paramsLabels[i].Text = fleetParams;\r
934                 nameLabels[i].Text = names[i];\r
935                 _toolTip.SetToolTip(nameLabels[i], inPort ? "" : fleetParams);\r
936             }\r
937             SetMissionLabel();\r
938         }\r
939 \r
940         private void SetMissionLabel()\r
941         {\r
942             labelMission.Text = (Config.ShowEndTime & TimerKind.Mission) != 0 ? "遠征終了" : "遠征";\r
943         }\r
944 \r
945         private void labelMission_Click(object sender, EventArgs e)\r
946         {\r
947             Config.ShowEndTime ^= TimerKind.Mission;\r
948             SetMissionLabel();\r
949             UpdateTimers();\r
950         }\r
951 \r
952         private void UpdateTimers()\r
953         {\r
954             var mission = new[] {labelMission1, labelMission2, labelMission3};\r
955             for (var i = 0; i < mission.Length; i++)\r
956             {\r
957                 var entry = Sniffer.Missions[i];\r
958                 SetTimerColor(mission[i], entry.Timer, _now);\r
959                 mission[i].Text = entry.Timer.ToString(_now, (Config.ShowEndTime & TimerKind.Mission) != 0);\r
960             }\r
961             for (var i = 0; i < Sniffer.NDock.Length; i++)\r
962             {\r
963                 var entry = Sniffer.NDock[i];\r
964                 _ndockLabels.SetTimer(i, entry.Timer, _now, (Config.ShowEndTime & TimerKind.NDock) != 0);\r
965             }\r
966             var kdock = new[] {labelConstruct1, labelConstruct2, labelConstruct3, labelConstruct4};\r
967             for (var i = 0; i < kdock.Length; i++)\r
968             {\r
969                 var timer = Sniffer.KDock[i];\r
970                 SetTimerColor(kdock[i], timer, _now);\r
971                 kdock[i].Text = timer.ToString(_now);\r
972             }\r
973             UpdateCondTimers();\r
974             UpdateAkashiTimer();\r
975             _timerEnabled = true;\r
976         }\r
977 \r
978         private void NotifyTimers()\r
979         {\r
980             for (var i = 0; i < Sniffer.Missions.Length; i++)\r
981             {\r
982                 var entry = Sniffer.Missions[i];\r
983                 if (entry.Name == "前衛支援任務" || entry.Name == "艦隊決戦支援任務")\r
984                     continue;\r
985                 CheckAlarm("遠征終了", entry.Timer, i + 1, entry.Name);\r
986             }\r
987             for (var i = 0; i < Sniffer.NDock.Length; i++)\r
988             {\r
989                 var entry = Sniffer.NDock[i];\r
990                 CheckAlarm("入渠終了", entry.Timer, i, entry.Name);\r
991             }\r
992             for (var i = 0; i < Sniffer.KDock.Length; i++)\r
993             {\r
994                 var timer = Sniffer.KDock[i];\r
995                 CheckAlarm("建造完了", timer, i, "");\r
996             }\r
997             NotifyCondTimers();\r
998             NotifyAkashiTimer();\r
999             _notificationManager.Flash();\r
1000         }\r
1001 \r
1002         private void CheckAlarm(string key, AlarmTimer timer, int fleet, string subject)\r
1003         {\r
1004             if (timer.CheckAlarm(_prev, _now))\r
1005             {\r
1006                 SetNotification(key, fleet, subject);\r
1007                 return;\r
1008             }\r
1009             var pre = TimeSpan.FromSeconds(Config.Notifications[key].PreliminaryPeriod);\r
1010             if (pre == TimeSpan.Zero)\r
1011                 return;\r
1012             if (timer.CheckAlarm(_prev + pre, _now + pre))\r
1013                 SetPreNotification(key, fleet, subject);\r
1014         }\r
1015 \r
1016         private void SetTimerColor(Label label, AlarmTimer timer, DateTime now)\r
1017         {\r
1018             label.ForeColor = timer.IsFinished(now) ? CUDColors.Red : Color.Black;\r
1019         }\r
1020 \r
1021         private void UpdateCondTimers()\r
1022         {\r
1023             DateTime timer;\r
1024             if (_combinedFleet)\r
1025             {\r
1026                 var timer1 = Sniffer.GetConditionTimer(0);\r
1027                 var timer2 = Sniffer.GetConditionTimer(1);\r
1028                 timer = timer2 > timer1 ? timer2 : timer1;\r
1029             }\r
1030             else\r
1031             {\r
1032                 timer = Sniffer.GetConditionTimer(_currentFleet);\r
1033             }\r
1034             if (timer == DateTime.MinValue)\r
1035             {\r
1036                 labelCondTimerTitle.Text = "";\r
1037                 labelCondTimer.Text = "";\r
1038                 return;\r
1039             }\r
1040             var span = TimeSpan.FromSeconds(Ceiling((timer - _now).TotalSeconds));\r
1041             if (span >= TimeSpan.FromMinutes(9) && Config.NotifyConditions.Contains(40))\r
1042             {\r
1043                 labelCondTimerTitle.Text = "cond40まで";\r
1044                 labelCondTimer.Text = (span - TimeSpan.FromMinutes(9)).ToString(@"mm\:ss");\r
1045                 labelCondTimer.ForeColor = DefaultForeColor;\r
1046             }\r
1047             else\r
1048             {\r
1049                 labelCondTimerTitle.Text = "cond49まで";\r
1050                 labelCondTimer.Text = (span >= TimeSpan.Zero ? span : TimeSpan.Zero).ToString(@"mm\:ss");\r
1051                 labelCondTimer.ForeColor = span <= TimeSpan.Zero ? CUDColors.Red : DefaultForeColor;\r
1052             }\r
1053         }\r
1054 \r
1055         private void NotifyCondTimers()\r
1056         {\r
1057             var notice = Sniffer.GetConditionNotice(_prev, _now);\r
1058             var pre = TimeSpan.FromSeconds(Config.Notifications["疲労回復"].PreliminaryPeriod);\r
1059             var preNotice = pre == TimeSpan.Zero\r
1060                 ? new int[ShipInfo.FleetCount]\r
1061                 : Sniffer.GetConditionNotice(_prev + pre, _now + pre);\r
1062             for (var i = 0; i < ShipInfo.FleetCount; i++)\r
1063             {\r
1064                 if (Config.NotifyConditions.Contains(notice[i]))\r
1065                 {\r
1066                     SetNotification("疲労回復" + notice[i], i, "cond" + notice[i]);\r
1067                 }\r
1068                 else if (Config.NotifyConditions.Contains(preNotice[i]))\r
1069                 {\r
1070                     SetPreNotification("疲労回復" + preNotice[i], i, "cond" + notice[i]);\r
1071                 }\r
1072             }\r
1073         }\r
1074 \r
1075         private void UpdateAkashiTimer()\r
1076         {\r
1077             if (Config.UsePresetAkashi)\r
1078                 UpdatePresetAkashiTimer();\r
1079             _mainLabels.SetAkashiTimer(Sniffer.Fleets[_currentFleet].ActualShips,\r
1080                 Sniffer.AkashiTimer.GetTimers(_currentFleet, _now));\r
1081         }\r
1082 \r
1083         private void UpdatePresetAkashiTimer()\r
1084         {\r
1085             var akashi = Sniffer.AkashiTimer;\r
1086             var span = akashi.GetPresetDeckTimer(_now);\r
1087             var color = span == TimeSpan.Zero && akashi.CheckPresetRepairing() ? CUDColors.Red : DefaultForeColor;\r
1088             var text = span == TimeSpan.MinValue ? "" : span.ToString(@"mm\:ss");\r
1089             labelAkashiRepairTimer.ForeColor = color;\r
1090             labelAkashiRepairTimer.Text = text;\r
1091             if (akashi.CheckPresetRepairing() && !akashi.CheckRepairing(_currentFleet, _now))\r
1092             {\r
1093                 labelPresetAkashiTimer.ForeColor = color;\r
1094                 labelPresetAkashiTimer.Text = text;\r
1095             }\r
1096             else\r
1097             {\r
1098                 labelPresetAkashiTimer.ForeColor = DefaultForeColor;\r
1099                 labelPresetAkashiTimer.Text = "";\r
1100             }\r
1101         }\r
1102 \r
1103         private void NotifyAkashiTimer()\r
1104         {\r
1105             var akashi = Sniffer.AkashiTimer;\r
1106             var msgs = akashi.GetNotice(_prev, _now);\r
1107             if (msgs.Length == 0)\r
1108             {\r
1109                 _notificationManager.StopRepeat("泊地修理");\r
1110                 return;\r
1111             }\r
1112             if (!akashi.CheckRepairing(_now) && !(akashi.CheckPresetRepairing() && Config.UsePresetAkashi))\r
1113             {\r
1114                 _notificationManager.StopRepeat("泊地修理");\r
1115                 return;\r
1116             }\r
1117             var skipPreliminary = false;\r
1118             if (msgs[0].Proceeded == "20分経過しました。")\r
1119             {\r
1120                 SetNotification("泊地修理20分経過", msgs[0].Proceeded);\r
1121                 msgs[0].Proceeded = "";\r
1122                 skipPreliminary = true;\r
1123                 // 修理完了がいるかもしれないので続ける\r
1124             }\r
1125             for (var i = 0; i < ShipInfo.FleetCount; i++)\r
1126             {\r
1127                 if (msgs[i].Proceeded != "")\r
1128                     SetNotification("泊地修理進行", i, msgs[i].Proceeded);\r
1129                 if (msgs[i].Completed != "")\r
1130                     SetNotification("泊地修理完了", i, msgs[i].Completed);\r
1131             }\r
1132             var pre = TimeSpan.FromSeconds(Config.Notifications["泊地修理20分経過"].PreliminaryPeriod);\r
1133             if (skipPreliminary || pre == TimeSpan.Zero)\r
1134                 return;\r
1135             if ((msgs = akashi.GetNotice(_prev + pre, _now + pre))[0].Proceeded == "20分経過しました。")\r
1136                 SetPreNotification("泊地修理20分経過", 0, msgs[0].Proceeded);\r
1137         }\r
1138 \r
1139         private void SetNotification(string key, string subject)\r
1140         {\r
1141             SetNotification(key, 0, subject);\r
1142         }\r
1143 \r
1144         private void SetNotification(string key, int fleet, string subject)\r
1145         {\r
1146             var spec = Config.Notifications[_notificationManager.KeyToName(key)];\r
1147             _notificationManager.Enqueue(key, fleet, subject,\r
1148                 (spec.Flags & Config.NotificationFlags & NotificationType.Repeat) == 0 ? 0 : spec.RepeatInterval);\r
1149         }\r
1150 \r
1151         private void SetPreNotification(string key, int fleet, string subject)\r
1152         {\r
1153             var spec = Config.Notifications[_notificationManager.KeyToName(key)];\r
1154             if ((spec.Flags & NotificationType.Preliminary) != 0)\r
1155                 _notificationManager.Enqueue(key, fleet, subject, 0, true);\r
1156         }\r
1157 \r
1158         private void UpdateRepairList()\r
1159         {\r
1160             panelRepairList.SetRepairList(Sniffer.RepairList);\r
1161             _toolTip.SetToolTip(label31, new RepairShipCount(Sniffer.RepairList).ToString());\r
1162         }\r
1163 \r
1164         private void UpdateQuestList()\r
1165         {\r
1166             questPanel.Update(Sniffer.Quests);\r
1167             labelQuestCount.Text = Sniffer.Quests.Length.ToString();\r
1168             SetQuestNotification();\r
1169         }\r
1170 \r
1171         private void SetQuestNotification()\r
1172         {\r
1173             Sniffer.GetQuestNotifications(out var notify, out var stop);\r
1174             foreach (var questName in notify)\r
1175                 SetNotification("任務達成", 0, questName);\r
1176             foreach (var questName in stop)\r
1177                 _notificationManager.StopRepeat("任務達成", questName);\r
1178             _notificationManager.Flash();\r
1179         }\r
1180 \r
1181         private void Alarm(string balloonTitle, string balloonMessage, string name)\r
1182         {\r
1183             var flags = Config.Notifications[name].Flags;\r
1184             var effective = Config.NotificationFlags & Config.Notifications[name].Flags;\r
1185             if ((effective & NotificationType.FlashWindow) != 0)\r
1186                 Win32API.FlashWindow(Handle);\r
1187             if ((effective & NotificationType.ShowBaloonTip) != 0)\r
1188                 notifyIconMain.ShowBalloonTip(20000, balloonTitle, balloonMessage, ToolTipIcon.Info);\r
1189             if ((effective & NotificationType.PlaySound) != 0)\r
1190                 PlaySound(Config.Sounds[name], Config.Sounds.Volume);\r
1191             if (Config.Pushbullet.On && (flags & NotificationType.Push) != 0)\r
1192             {\r
1193                 Task.Run(() =>\r
1194                 {\r
1195                     PushNotification.PushToPushbullet(Config.Pushbullet.Token, balloonTitle, balloonMessage);\r
1196                 });\r
1197             }\r
1198             if (Config.Pushover.On && (flags & NotificationType.Push) != 0)\r
1199             {\r
1200                 Task.Run(() =>\r
1201                 {\r
1202                     PushNotification.PushToPushover(Config.Pushover.ApiKey, Config.Pushover.UserKey,\r
1203                         balloonTitle, balloonMessage);\r
1204                 });\r
1205             }\r
1206         }\r
1207 \r
1208         [DllImport("winmm.dll")]\r
1209         private static extern int mciSendString(String command,\r
1210             StringBuilder buffer, int bufferSize, IntPtr hWndCallback);\r
1211 \r
1212 // ReSharper disable InconsistentNaming\r
1213         // ReSharper disable once IdentifierTypo\r
1214         private const int MM_MCINOTIFY = 0x3B9;\r
1215 \r
1216         private const int MCI_NOTIFY_SUCCESSFUL = 1;\r
1217 // ReSharper restore InconsistentNaming\r
1218 \r
1219         public void PlaySound(string file, int volume)\r
1220         {\r
1221             if (!File.Exists(file))\r
1222                 return;\r
1223             mciSendString("close sound", null, 0, IntPtr.Zero);\r
1224             if (mciSendString("open \"" + file + "\" type mpegvideo alias sound", null, 0, IntPtr.Zero) != 0)\r
1225                 return;\r
1226             mciSendString("setaudio sound volume to " + volume * 10, null, 0, IntPtr.Zero);\r
1227             mciSendString("play sound notify", null, 0, Handle);\r
1228         }\r
1229 \r
1230         protected override void WndProc(ref Message m)\r
1231         {\r
1232             if (m.Msg == MM_MCINOTIFY && (int)m.WParam == MCI_NOTIFY_SUCCESSFUL)\r
1233                 mciSendString("close sound", null, 0, IntPtr.Zero);\r
1234             base.WndProc(ref m);\r
1235         }\r
1236 \r
1237         private void SetupFleetClick()\r
1238         {\r
1239             var labels = new[]\r
1240             {\r
1241                 new[] {labelFleet1, labelFleet2, labelFleet3, labelFleet4},\r
1242                 new[] {labelFuelSq1, labelFuelSq2, labelFuelSq3, labelFuelSq4},\r
1243                 new[] {labelBullSq1, labelBullSq2, labelBullSq3, labelBullSq4}\r
1244             };\r
1245             foreach (var a in labels)\r
1246             {\r
1247                 a[0].Tag = 0;\r
1248                 a[0].Click += labelFleet1_Click;\r
1249                 a[0].DoubleClick += labelFleet1_DoubleClick;\r
1250                 for (var fleet = 1; fleet < labels[0].Length; fleet++)\r
1251                 {\r
1252                     a[fleet].Tag = fleet;\r
1253                     a[fleet].Click += labelFleet_Click;\r
1254                     a[fleet].DoubleClick += labelFleet_DoubleClick;\r
1255                 }\r
1256             }\r
1257         }\r
1258 \r
1259         private void labelFleet_Click(object sender, EventArgs e)\r
1260         {\r
1261             if (!_started)\r
1262                 return;\r
1263             var fleet = (int)((Label)sender).Tag;\r
1264             if (_currentFleet == fleet)\r
1265                 return;\r
1266             _combinedFleet = false;\r
1267             _currentFleet = fleet;\r
1268             UpdatePanelShipInfo();\r
1269         }\r
1270 \r
1271         private readonly SemaphoreSlim _clickSemaphore = new SemaphoreSlim(1);\r
1272         private readonly SemaphoreSlim _doubleClickSemaphore = new SemaphoreSlim(0);\r
1273 \r
1274         private async void labelFleet1_Click(object sender, EventArgs e)\r
1275         {\r
1276             if (!_started)\r
1277                 return;\r
1278             if (_currentFleet != 0)\r
1279             {\r
1280                 labelFleet_Click(sender, e);\r
1281                 return;\r
1282             }\r
1283             if (!_clickSemaphore.Wait(0))\r
1284                 return;\r
1285             try\r
1286             {\r
1287                 if (await _doubleClickSemaphore.WaitAsync(SystemInformation.DoubleClickTime))\r
1288                     return;\r
1289             }\r
1290             finally\r
1291             {\r
1292                 _clickSemaphore.Release();\r
1293             }\r
1294             _combinedFleet = Sniffer.IsCombinedFleet && !_combinedFleet;\r
1295             UpdatePanelShipInfo();\r
1296         }\r
1297 \r
1298         private void labelFleet1_MouseHover(object sender, EventArgs e)\r
1299         {\r
1300             labelFleet1.Text = _currentFleet == 0 && Sniffer.IsCombinedFleet && !_combinedFleet ? "連合" : "第一";\r
1301         }\r
1302 \r
1303         private void labelFleet1_MouseLeave(object sender, EventArgs e)\r
1304         {\r
1305             labelFleet1.Text = _combinedFleet ? CombinedName : "第一";\r
1306         }\r
1307 \r
1308         private void labelFleet_DoubleClick(object sender, EventArgs e)\r
1309         {\r
1310             if (!_started)\r
1311                 return;\r
1312             var fleet = (int)((Label)sender).Tag;\r
1313             var text = TextGenerator.GenerateFleetData(Sniffer, fleet);\r
1314             CopyFleetText(text, (Label)sender);\r
1315         }\r
1316 \r
1317         private void labelFleet1_DoubleClick(object sender, EventArgs e)\r
1318         {\r
1319             if (!_started)\r
1320                 return;\r
1321             _doubleClickSemaphore.Release();\r
1322             var text = TextGenerator.GenerateFleetData(Sniffer, 0);\r
1323             if (_combinedFleet)\r
1324                 text += TextGenerator.GenerateFleetData(Sniffer, 1);\r
1325             CopyFleetText(text, (Label)sender);\r
1326         }\r
1327 \r
1328         private void CopyFleetText(string text, Label fleetButton)\r
1329         {\r
1330             if (string.IsNullOrEmpty(text))\r
1331                 return;\r
1332             Clipboard.SetText(text);\r
1333             _tooltipCopy.Active = true;\r
1334             _tooltipCopy.Show("コピーしました。", fleetButton);\r
1335             Task.Run(async () =>\r
1336             {\r
1337                 await Task.Delay(1000);\r
1338                 _tooltipCopy.Active = false;\r
1339             });\r
1340         }\r
1341 \r
1342         private void labelBucketHistoryButton_Click(object sender, EventArgs e)\r
1343         {\r
1344             if (labelBucketHistory.Visible)\r
1345             {\r
1346                 labelBucketHistory.Visible = false;\r
1347                 labelBucketHistoryButton.BackColor = DefaultBackColor;\r
1348             }\r
1349             else\r
1350             {\r
1351                 labelBucketHistory.Visible = true;\r
1352                 labelBucketHistory.BringToFront();\r
1353                 labelBucketHistoryButton.BackColor = CustomColors.ActiveButtonColor;\r
1354             }\r
1355         }\r
1356 \r
1357         private void labelBucketHistory_Click(object sender, EventArgs e)\r
1358         {\r
1359             labelBucketHistory.Visible = false;\r
1360             labelBucketHistoryButton.BackColor = DefaultBackColor;\r
1361         }\r
1362 \r
1363         private void labelMaterialHistoryButton_Click(object sender, EventArgs e)\r
1364         {\r
1365             if (panelMaterialHistory.Visible)\r
1366             {\r
1367                 panelMaterialHistory.Visible = false;\r
1368                 labelMaterialHistoryButton.BackColor = DefaultBackColor;\r
1369             }\r
1370             else\r
1371             {\r
1372                 panelMaterialHistory.Visible = true;\r
1373                 panelMaterialHistory.BringToFront();\r
1374                 labelMaterialHistoryButton.BackColor = CustomColors.ActiveButtonColor;\r
1375             }\r
1376         }\r
1377 \r
1378         private void panelMaterialHistory_Click(object sender, EventArgs e)\r
1379         {\r
1380             panelMaterialHistory.Visible = false;\r
1381             labelMaterialHistoryButton.BackColor = DefaultBackColor;\r
1382         }\r
1383 \r
1384         public void ResetAchievement()\r
1385         {\r
1386             Sniffer.Achievement.Reset();\r
1387             UpdateItemInfo();\r
1388         }\r
1389 \r
1390         private void labelRepairListButton_Click(object sender, EventArgs e)\r
1391         {\r
1392             if (panelRepairList.Visible)\r
1393             {\r
1394                 panelRepairList.Visible = false;\r
1395                 labelRepairListButton.BackColor = DefaultBackColor;\r
1396             }\r
1397             else\r
1398             {\r
1399                 panelRepairList.Visible = true;\r
1400                 panelRepairList.BringToFront();\r
1401                 labelRepairListButton.BackColor = CustomColors.ActiveButtonColor;\r
1402             }\r
1403         }\r
1404 \r
1405         private void panelRepairList_Click(object sender, EventArgs e)\r
1406         {\r
1407             panelRepairList.Visible = false;\r
1408             labelRepairListButton.BackColor = DefaultBackColor;\r
1409         }\r
1410 \r
1411         private void ShipListToolStripMenuItem_Click(object sender, EventArgs e)\r
1412         {\r
1413             _listFormGroup.ShowOrCreate();\r
1414             /*\r
1415             _listForm.UpdateList();\r
1416             _listForm.Show();\r
1417             if (_listForm.WindowState == FormWindowState.Minimized)\r
1418                 _listForm.WindowState = FormWindowState.Normal;\r
1419             _listForm.Activate();\r
1420             */\r
1421         }\r
1422 \r
1423         private void LogToolStripMenuItem_Click(object sender, EventArgs e)\r
1424         {\r
1425             Process.Start("http://localhost:" + Config.Proxy.Listen + "/");\r
1426         }\r
1427 \r
1428         private void labelClearQuest_Click(object sender, EventArgs e)\r
1429         {\r
1430             Sniffer.ClearQuests();\r
1431             UpdateQuestList();\r
1432         }\r
1433 \r
1434         private void labelClearQuest_MouseDown(object sender, MouseEventArgs e)\r
1435         {\r
1436             labelClearQuest.BackColor = CustomColors.ActiveButtonColor;\r
1437         }\r
1438 \r
1439         private void labelClearQuest_MouseUp(object sender, MouseEventArgs e)\r
1440         {\r
1441             labelClearQuest.BackColor = DefaultBackColor;\r
1442         }\r
1443 \r
1444         private void labelQuest_DoubleClick(object sender, EventArgs e)\r
1445         {\r
1446             var label = (Label)sender;\r
1447             if (string.IsNullOrEmpty(label.Text))\r
1448                 return;\r
1449             Clipboard.SetText(label.Text);\r
1450             _tooltipCopy.Active = true;\r
1451             _tooltipCopy.Show("コピーしました。", label);\r
1452             Task.Run(async () =>\r
1453             {\r
1454                 await Task.Delay(1000);\r
1455                 _tooltipCopy.Active = false;\r
1456             });\r
1457         }\r
1458 \r
1459         private void CaptureToolStripMenuItem_Click(object sender, EventArgs e)\r
1460         {\r
1461             try\r
1462             {\r
1463                 var proc = new ProcessStartInfo("BurageSnap.exe") {WorkingDirectory = "Capture"};\r
1464                 Process.Start(proc);\r
1465             }\r
1466             catch (FileNotFoundException)\r
1467             {\r
1468             }\r
1469             catch (Win32Exception)\r
1470             {\r
1471             }\r
1472         }\r
1473     }\r
1474 }