X-Git-Url: http://git.osdn.net/view?a=blobdiff_plain;f=KancolleSniffer%2FMainForm.cs;h=ec4df4cca2c03504bc127b45f539cfb36354fec6;hb=6f62035b0ae019bb520a324056732938a7d60c26;hp=ca74bcecd4c84e2ed94fd7e0a588368aa5d1f4d5;hpb=bb10052910c222a8627e86b0bfd3885e5d23d874;p=kancollesniffer%2FKancolleSniffer.git diff --git a/KancolleSniffer/MainForm.cs b/KancolleSniffer/MainForm.cs index ca74bce..ec4df4c 100644 --- a/KancolleSniffer/MainForm.cs +++ b/KancolleSniffer/MainForm.cs @@ -14,11 +14,13 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; +using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; @@ -35,20 +37,24 @@ namespace KancolleSniffer private readonly Config _config = new Config(); private readonly ConfigDialog _configDialog; private readonly ProxyManager _proxyManager; + private readonly ResizableToolTip _toolTip = new ResizableToolTip {ShowAlways = true}; + private readonly ResizableToolTip _toolTipQuest = new ResizableToolTip {ShowAlways = true, AutoPopDelay = 10000}; + private readonly ResizableToolTip _tooltipCopy = new ResizableToolTip {AutomaticDelay = 0}; private int _currentFleet; private bool _combinedFleet; private readonly Label[] _labelCheckFleets; - private readonly ShipLabels _shipLabels; + private readonly MainFormLabels _mainLabels; private readonly ListForm _listForm; private readonly NotificationManager _notificationManager; private bool _started; + private bool _timerEnabled; private string _debugLogFile; private IEnumerator _playLog; + private DateTime _prev, _now; + private bool _inSortie; private readonly ErrorDialog _errorDialog = new ErrorDialog(); - private bool _missionFinishTimeMode; - private bool _ndockFinishTimeMode; - private readonly KancolleDb _kancolleDb = new KancolleDb(); + private readonly ErrorLog _errorLog; public MainForm() { @@ -63,25 +69,111 @@ namespace KancolleSniffer CurrentAutoScaleDimensions.Height / 12f); SetupFleetClick(); - _shipLabels = new ShipLabels(); - _shipLabels.CreateAkashiTimers(panelShipInfo); - _shipLabels.CreateShipLabels(panelShipInfo, ShowShipOnShipList); - _shipLabels.CreateCombinedShipLabels(panelCombinedFleet, ShowShipOnShipList); - _shipLabels.CreateNDockLabels(panelDock, labelNDock_Click); + _mainLabels = new MainFormLabels(); + _mainLabels.CreateAkashiTimers(panelShipInfo); + _mainLabels.CreateShipLabels(panelShipInfo, ShowShipOnShipList); + _mainLabels.CreateAkashiTimers7(panel7Ships); + _mainLabels.CreateShipLabels7(panel7Ships, ShowShipOnShipList); + _mainLabels.CreateCombinedShipLabels(panelCombinedFleet, ShowShipOnShipList); + _mainLabels.CreateNDockLabels(panelDock, labelNDock_Click); panelRepairList.CreateLabels(panelRepairList_Click); - labelPresetAkashiTimer.BackColor = ShipLabels.ColumnColors[1]; + labelPresetAkashiTimer.BackColor = ShipLabel.ColumnColors[1]; _listForm = new ListForm(_sniffer, _config) {Owner = this}; - _notificationManager = new NotificationManager(Ring); + _notificationManager = new NotificationManager(Alarm); _config.Load(); _proxyManager = new ProxyManager(_config, this); + _errorLog = new ErrorLog(_sniffer); + _proxyManager.UpdatePacFile(); PerformZoom(); - _shipLabels.AdjustAkashiTimers(); + _mainLabels.AdjustAkashiTimers(); + LoadData(); + _sniffer.RepeatingTimerController = new RepeatingTimerController(_notificationManager, _config); + } + + /// + /// パネルのz-orderがくるうのを避ける + /// https://stackoverflow.com/a/5777090/1429506 + /// + private void MainForm_Shown(object sender, EventArgs e) + { + // ReSharper disable once NotAccessedVariable + IntPtr handle; + foreach (var panel in new[] {panelShipInfo, panel7Ships, panelCombinedFleet}) + // ReSharper disable once RedundantAssignment + handle = panel.Handle; + } + + private readonly FileSystemWatcher _watcher = new FileSystemWatcher + { + Path = AppDomain.CurrentDomain.BaseDirectory, + NotifyFilter = NotifyFilters.LastWrite + }; + + private readonly Timer _watcherTimer = new Timer {Interval = 1000}; + + private void LoadData() + { + var target = ""; _sniffer.LoadState(); + DataLoader.LoadTpSpec(); + _watcher.SynchronizingObject = this; + _watcherTimer.Tick += (sender, ev) => + { + _watcherTimer.Stop(); + switch (target) + { + case "status.xml": + _sniffer.LoadState(); + break; + case "TP.csv": + DataLoader.LoadTpSpec(); + break; + } + }; + _watcher.Changed += (sender, ev) => + { + target = ev.Name; + _watcherTimer.Stop(); + _watcherTimer.Start(); + }; + _watcher.EnableRaisingEvents = true; + } + + private class RepeatingTimerController : Sniffer.IRepeatingTimerController + { + private readonly NotificationManager _manager; + private readonly Config _config; + + public RepeatingTimerController(NotificationManager manager, Config config) + { + _manager = manager; + _config = config; + } + + public void Stop(string key) + { + _manager.StopRepeat(key, + (key == "入渠終了" || key == "遠征終了") && + (_config.Notifications[key].Flags & NotificationType.Cont) != 0); + } + + public void Stop(string key, int fleet) => _manager.StopRepeat(key, fleet); + + public void Suspend() => _manager.SuspendRepeat(); + + public void Resume() => _manager.ResumeRepeat(); + } + + public class ConfigFileException : Exception + { + public ConfigFileException(string message, Exception innerException) : base(message, innerException) + { + } } private void HttpProxy_AfterSessionComplete(HttpProxy.Session session) { - Invoke(new Action(ProcessRequest), session); + BeginInvoke(new Action(ProcessRequest), session); } private void ProcessRequest(HttpProxy.Session session) @@ -96,39 +188,58 @@ namespace KancolleSniffer WriteDebugLog(url, request, response); return; } - if (_config.KancolleDb.On) - _kancolleDb.Send(url, request, response); response = UnescapeString(response.Remove(0, "svdata=".Length)); WriteDebugLog(url, request, response); + ProcessRequestMain(url, request, response); + } + + private void ProcessRequestMain(string url, string request, string response) + { try { UpdateInfo(_sniffer.Sniff(url, request, JsonParser.Parse(response))); + _errorLog.CheckBattleApi(url, request, response); } + catch (RuntimeBinderException e) { if (_errorDialog.ShowDialog(this, - "このバージョンは現在の艦これに対応していません。\r\n新しいバージョンを利用してください。", e.ToString()) == DialogResult.Abort) - Application.Exit(); + "艦これに仕様変更があったか、受信内容が壊れています。", + _errorLog.GenerateErrorLog(url, request, response, e.ToString())) == DialogResult.Abort) + Exit(); } catch (LogIOException e) { // ReSharper disable once PossibleNullReferenceException if (_errorDialog.ShowDialog(this, e.Message, e.InnerException.ToString()) == DialogResult.Abort) - Application.Exit(); + Exit(); + } + catch (BattleResultError) + { + if (_errorDialog.ShowDialog(this, "戦闘結果の計算に誤りがあります。", + _errorLog.GenerateBattleErrorLog()) == DialogResult.Abort) + Exit(); } catch (Exception e) { - if (_errorDialog.ShowDialog(this, "エラーが発生しました。", e.ToString()) == DialogResult.Abort) - Application.Exit(); + if (_errorDialog.ShowDialog(this, "エラーが発生しました。", + _errorLog.GenerateErrorLog(url, request, response, e.ToString())) == DialogResult.Abort) + Exit(); } } + private void Exit() + { + _proxyManager.Shutdown(); + Environment.Exit(1); + } + private void WriteDebugLog(string url, string request, string response) { if (_debugLogFile != null) { File.AppendAllText(_debugLogFile, - $"url: {url}\nrequest: {request}\nresponse: {response ?? "(null)"}\n"); + $"date: {DateTime.Now:g}\nurl: {url}\nrequest: {request}\nresponse: {response ?? "(null)"}\n"); } } @@ -151,12 +262,14 @@ namespace KancolleSniffer if (update == Sniffer.Update.Start) { labelLogin.Visible = false; - labelGuide.Visible = false; + linkLabelGuide.Visible = false; _started = true; return; } if (!_started) return; + if (_now == DateTime.MinValue) + _now = DateTime.Now; if ((update & Sniffer.Update.Item) != 0) UpdateItemInfo(); if ((update & Sniffer.Update.Timer) != 0) @@ -178,12 +291,45 @@ namespace KancolleSniffer RestoreLocation(); if (_config.HideOnMinimized && WindowState == FormWindowState.Minimized) ShowInTaskbar = false; + if (_config.ShowHpInPercent) + _mainLabels.ToggleHpPercent(); + if (_config.ShipList.Visible) + _listForm.Show(); ApplyConfig(); ApplyDebugLogSetting(); ApplyLogSetting(); ApplyProxySetting(); - if (_config.KancolleDb.On) - _kancolleDb.Start(_config.KancolleDb.Token); + CheckVersionUp((current, latest) => + { + if (double.Parse(latest) <= double.Parse(current)) + return; + linkLabelGuide.Text = $"バージョン{latest}があります。"; + linkLabelGuide.LinkArea = new LinkArea(0, linkLabelGuide.Text.Length); + linkLabelGuide.Click += (obj, ev) => + { + Process.Start("https://ja.osdn.net/rel/kancollesniffer/" + latest); + }; + }); + } + + public async void CheckVersionUp(Action action) + { + var current = string.Join(".", Application.ProductVersion.Split('.').Take(2)); + try + { + var latest = (await new WebClient().DownloadStringTaskAsync("http://kancollesniffer.osdn.jp/version")) + .TrimEnd(); + try + { + action(current, latest); + } + catch (InvalidOperationException) + { + } + } + catch (WebException) + { + } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) @@ -202,9 +348,11 @@ namespace KancolleSniffer e.Cancel = false; _sniffer.FlashLog(); _config.Location = (WindowState == FormWindowState.Normal ? Bounds : RestoreBounds).Location; + _config.ShowHpInPercent = _mainLabels.ShowHpInPercent; + _config.ShipList.Visible = _listForm.Visible && _listForm.WindowState == FormWindowState.Normal; _config.Save(); + _sniffer.SaveState(); _proxyManager.Shutdown(); - _kancolleDb.Stop(); } private void MainForm_Resize(object sender, EventArgs e) @@ -233,7 +381,17 @@ namespace KancolleSniffer private void ConfigToolStripMenuItem_Click(object sender, EventArgs e) { if (_configDialog.ShowDialog(this) == DialogResult.OK) + { + _config.Save(); ApplyConfig(); + StopRepeatingTimer(_configDialog.RepeatSettingsChanged); + } + } + + private void StopRepeatingTimer(IEnumerable names) + { + foreach (var name in names) + _notificationManager.StopRepeat(name); } private void PerformZoom() @@ -241,8 +399,19 @@ namespace KancolleSniffer if (_config.Zoom == 100) return; var prev = CurrentAutoScaleDimensions; - foreach (var control in new Control[] {this, _listForm, labelLogin, labelGuide}) + foreach (var control in new Control[] + { + this, _listForm, labelLogin, linkLabelGuide, + _configDialog, _configDialog.NotificationConfigDialog, + contextMenuStripMain, _errorDialog + }) + { control.Font = new Font(control.Font.FontFamily, control.Font.Size * _config.Zoom / 100); + } + foreach (var toolTip in new[]{_toolTip, _toolTipQuest, _tooltipCopy}) + { + toolTip.Font = new Font(toolTip.Font.FontFamily, toolTip.Font.Size * _config.Zoom / 100); + } ShipLabel.LatinFont = new Font("Tahoma", 8f * _config.Zoom / 100); var cur = CurrentAutoScaleDimensions; ShipLabel.ScaleFactor = new SizeF(ShipLabel.ScaleFactor.Width * cur.Width / prev.Width, @@ -253,9 +422,7 @@ namespace KancolleSniffer { if (_config.Location.X == int.MinValue) return; - var newBounds = Bounds; - newBounds.Location = _config.Location; - if (IsVisibleOnAnyScreen(newBounds)) + if (IsTitleBarOnAnyScreen(_config.Location)) Location = _config.Location; } @@ -263,12 +430,12 @@ namespace KancolleSniffer { _listForm.TopMost = TopMost = _config.TopMost; _sniffer.Item.MarginShips = _config.MarginShips; + UpdateNumOfShips(); _sniffer.Item.MarginEquips = _config.MarginEquips; + UpdateNumOfEquips(); _sniffer.Achievement.ResetHours = _config.ResetHours; labelAkashiRepair.Visible = labelAkashiRepairTimer.Visible = labelPresetAkashiTimer.Visible = _config.UsePresetAkashi; - if (_config.KancolleDb.On) - _kancolleDb.Start(_config.KancolleDb.Token); } public void ApplyDebugLogSetting() @@ -284,28 +451,35 @@ namespace KancolleSniffer public void ApplyLogSetting() { LogServer.OutputDir = _config.Log.OutputDir; + LogServer.MaterialHistory = _sniffer.Material.MaterialHistory; _sniffer.EnableLog(_config.Log.On ? LogType.All : LogType.None); _sniffer.MaterialLogInterval = _config.Log.MaterialLogInterval; _sniffer.LogOutputDir = _config.Log.OutputDir; } - public static bool IsVisibleOnAnyScreen(Rectangle rect) + public static bool IsTitleBarOnAnyScreen(Point location) { - return Screen.AllScreens.Any(screen => screen.WorkingArea.IntersectsWith(rect)); + var rect = new Rectangle( + new Point(location.X + SystemInformation.IconSize.Width + SystemInformation.HorizontalFocusThickness, + location.Y + SystemInformation.CaptionHeight), new Size(60, 1)); + return Screen.AllScreens.Any(screen => screen.WorkingArea.Contains(rect)); } private void timerMain_Tick(object sender, EventArgs e) { - if (_started) + if (_timerEnabled) { try { + _now = DateTime.Now; UpdateTimers(); + NotifyTimers(); + _prev = _now; } catch (Exception ex) { if (_errorDialog.ShowDialog(this, "エラーが発生しました。", ex.ToString()) == DialogResult.Abort) - Application.Exit(); + Exit(); } } if (_playLog == null || _configDialog.Visible) @@ -326,16 +500,18 @@ namespace KancolleSniffer var lines = new List(); foreach (var s in new[] {"url: ", "request: ", "response: "}) { - if (!_playLog.MoveNext() || !_playLog.Current.StartsWith(s)) + do { - labelPlayLog.Visible = false; - return; - } + if (!_playLog.MoveNext() || _playLog.Current == null) + { + labelPlayLog.Visible = false; + return; + } + } while (!_playLog.Current.StartsWith(s)); lines.Add(_playLog.Current.Substring(s.Length)); } labelPlayLog.Visible = !labelPlayLog.Visible; - var json = JsonParser.Parse(lines[2]); - UpdateInfo(_sniffer.Sniff(lines[0], lines[1], json)); + ProcessRequestMain(lines[0], lines[1], lines[2]); } private void ShowShipOnShipList(object sender, EventArgs ev) @@ -353,13 +529,14 @@ namespace KancolleSniffer { UpdateNumOfShips(); UpdateNumOfEquips(); + _notificationManager.Flash(); labelNumOfBuckets.Text = _sniffer.Material.MaterialHistory[(int)Material.Bucket].Now.ToString("D"); UpdateBucketHistory(); var ac = _sniffer.Achievement.Value; if (ac >= 10000) ac = 9999; labelAchievement.Text = ac >= 1000 ? ((int)ac).ToString("D") : ac.ToString("F1"); - toolTipAchievement.SetToolTip(labelAchievement, + _toolTip.SetToolTip(labelAchievement, "今月 " + _sniffer.Achievement.ValueOfMonth.ToString("F1") + "\n" + "EO " + _sniffer.ExMap.Achievement); UpdateMaterialHistry(); @@ -372,11 +549,11 @@ namespace KancolleSniffer var item = _sniffer.Item; labelNumOfShips.Text = $"{item.NowShips:D}/{item.MaxShips:D}"; labelNumOfShips.ForeColor = item.TooManyShips ? CUDColor.Red : Color.Black; - if (item.RingShips) + if (item.AlarmShips) { var message = $"残り{_sniffer.Item.MaxShips - _sniffer.Item.NowShips:D}隻"; _notificationManager.Enqueue("艦娘数超過", message); - item.RingShips = false; + item.AlarmShips = false; } } @@ -385,11 +562,11 @@ namespace KancolleSniffer var item = _sniffer.Item; labelNumOfEquips.Text = $"{item.NowEquips:D}/{item.MaxEquips:D}"; labelNumOfEquips.ForeColor = item.TooManyEquips ? CUDColor.Red : Color.Black; - if (item.RingEquips) + if (item.AlarmEquips) { var message = $"残り{_sniffer.Item.MaxEquips - _sniffer.Item.NowEquips:D}個"; _notificationManager.Enqueue("装備数超過", message); - item.RingEquips = false; + item.AlarmEquips = false; } } @@ -426,6 +603,7 @@ namespace KancolleSniffer private void UpdateShipInfo() { + SetCurrentFleet(); UpdatePanelShipInfo(); NotifyDamagedShip(); UpdateChargeInfo(); @@ -434,49 +612,53 @@ namespace KancolleSniffer _listForm.UpdateList(); } + private void SetCurrentFleet() + { + var inSortie = _sniffer.InSortie; + if (_inSortie || !inSortie.Any(x => x)) + { + _inSortie = inSortie.Any(x => x); + return; + } + _inSortie = true; + if (inSortie[0] && inSortie[1]) + { + _combinedFleet = true; + _currentFleet = 0; + } + else + { + _combinedFleet = false; + _currentFleet = Array.FindIndex(inSortie, x => x); + } + } + private void UpdatePanelShipInfo() { var statuses = _sniffer.GetShipStatuses(_currentFleet); - _shipLabels.SetShipLabels(statuses); + panel7Ships.Visible = statuses.Length == 7; + _mainLabels.SetShipLabels(statuses); if (_sniffer.CombinedFleetType == 0) _combinedFleet = false; labelFleet1.Text = _combinedFleet ? "連合" : "第一"; panelCombinedFleet.Visible = _combinedFleet; if (_combinedFleet) - _shipLabels.SetCombinedShipLabels(_sniffer.GetShipStatuses(0), _sniffer.GetShipStatuses(1)); + _mainLabels.SetCombinedShipLabels(_sniffer.GetShipStatuses(0), _sniffer.GetShipStatuses(1)); + for (var i = 0; i < _labelCheckFleets.Length; i++) + _labelCheckFleets[i].Visible = _currentFleet == i; UpdateAkashiTimer(); - UpdateFighterPower(_combinedFleet); + var battle = _sniffer.Battle; + UpdateFighterPower(_combinedFleet && (battle.BattleState == BattleState.None || battle.EnemyIsCombined)); UpdateLoS(); UpdateCondTimers(); } private void NotifyDamagedShip() { - if (_sniffer.BadlyDamagedShips.Any()) - _notificationManager.Enqueue("大破警告", string.Join(" ", _sniffer.BadlyDamagedShips)); - } - - private void NotifyAkashiTimer() - { - var akashi = _sniffer.AkashiTimer; - var msgs = akashi.GetNotice(); - if (msgs.Length == 0) - return; - if (!akashi.CheckReparing() && !(akashi.CheckPresetReparing() && _config.UsePresetAkashi)) + if (!_sniffer.BadlyDamagedShips.Any()) return; - if (msgs[0].Proceeded == "20分経過しました。") - { - _notificationManager.Enqueue("泊地修理20分経過", msgs[0].Proceeded); - msgs[0].Proceeded = ""; - // 修理完了がいるかもしれないので続ける - } - for (var i = 0; i < ShipInfo.FleetCount; i++) - { - if (msgs[i].Proceeded != "") - _notificationManager.Enqueue("泊地修理進行", i, msgs[i].Proceeded); - if (msgs[i].Completed != "") - _notificationManager.Enqueue("泊地修理完了", i, msgs[i].Completed); - } + _notificationManager.Enqueue("大破警告", string.Join(" ", _sniffer.BadlyDamagedShips)); + _notificationManager.Flash(); } public void UpdateFighterPower(bool combined) @@ -490,8 +672,8 @@ namespace KancolleSniffer : _sniffer.GetContactTriggerRate(_currentFleet); var text = "制空: " + (fp[0] == fp[1] ? $"{fp[0]}" : $"{fp[0]}~{fp[1]}") + $" 触接: {cr * 100:f1}"; - toolTipFighterPower.SetToolTip(labelFighterPower, text); - toolTipFighterPower.SetToolTip(labelFighterPowerCaption, text); + _toolTip.SetToolTip(labelFighterPower, text); + _toolTip.SetToolTip(labelFighterPowerCaption, text); } private void UpdateLoS() @@ -499,8 +681,8 @@ namespace KancolleSniffer labelLoS.Text = RoundDown(_sniffer.GetFleetLineOfSights(_currentFleet, 1)).ToString("F1"); var text = $"係数3: {RoundDown(_sniffer.GetFleetLineOfSights(_currentFleet, 3)):F1}\r\n" + $"係数4: {RoundDown(_sniffer.GetFleetLineOfSights(_currentFleet, 4)):F1}"; - toolTipLoS.SetToolTip(labelLoS, text); - toolTipLoS.SetToolTip(labelLoSCaption, text); + _toolTip.SetToolTip(labelLoS, text); + _toolTip.SetToolTip(labelLoSCaption, text); } private double RoundDown(double number) @@ -511,13 +693,14 @@ namespace KancolleSniffer private void UpdateBattleInfo() { ResetBattleInfo(); + _listForm.UpdateBattleResult(); if (_sniffer.Battle.BattleState == BattleState.None) return; panelBattleInfo.BringToFront(); var battle = _sniffer.Battle; - labelFormation.Text = battle.Formation; + labelFormation.Text = new[] {"同航戦", "反航戦", "T字有利", "T字不利"}[battle.Formation[2] - 1]; UpdateBattleFighterPower(); - if (_config.AlwaysShowResultRank) + if ((_config.Spoilers & Spoiler.ResultRank) != 0) ShowResultRank(); if (_sniffer.Battle.BattleState == BattleState.Day) _listForm.UpdateAirBattleResult(); @@ -540,8 +723,8 @@ namespace KancolleSniffer if (power.AirCombat != power.Interception) { var text = "防空: " + power.Interception + power.UnknownMark; - toolTipFighterPower.SetToolTip(labelEnemyFighterPower, text); - toolTipFighterPower.SetToolTip(labelEnemyFighterPowerCaption, text); + _toolTip.SetToolTip(labelEnemyFighterPower, text); + _toolTip.SetToolTip(labelEnemyFighterPowerCaption, text); } UpdateFighterPower(_sniffer.CombinedFleetType > 0 && battle.EnemyIsCombined); labelFighterPower.ForeColor = new[] @@ -575,13 +758,13 @@ namespace KancolleSniffer private void UpdateNDocLabels() { - _shipLabels.SetNDockLabels(_sniffer.NDock); + _mainLabels.SetNDockLabels(_sniffer.NDock); } private void labelNDock_Click(object sender, EventArgs e) { - _ndockFinishTimeMode = !_ndockFinishTimeMode; + _config.ShowEndTime ^= TimerKind.NDock; UpdateTimers(); } @@ -595,54 +778,75 @@ namespace KancolleSniffer private void labelMission_Click(object sender, EventArgs e) { - _missionFinishTimeMode = !_missionFinishTimeMode; + _config.ShowEndTime ^= TimerKind.Mission; UpdateTimers(); } private void UpdateTimers() { - foreach (var entry in - new[] {labelMission1, labelMission2, labelMission3}.Zip(_sniffer.Missions, - (label, mission) => new {label, mission.Name, mission.Timer})) + var mission = new[] {labelMission1, labelMission2, labelMission3}; + for (var i = 0; i < mission.Length; i++) { - entry.Timer.Update(); - SetTimerColor(entry.label, entry.Timer); - entry.label.Text = entry.Timer.ToString(_missionFinishTimeMode); - if (!entry.Timer.NeedRing) - continue; - _notificationManager.Enqueue("遠征終了", entry.Name); - entry.Timer.NeedRing = false; + var entry = _sniffer.Missions[i]; + SetTimerColor(mission[i], entry.Timer, _now); + mission[i].Text = entry.Timer.ToString(_now, (_config.ShowEndTime & TimerKind.Mission) != 0); } for (var i = 0; i < _sniffer.NDock.Length; i++) { var entry = _sniffer.NDock[i]; - entry.Timer.Update(); - _shipLabels.SetNDockTimer(i, entry.Timer, _ndockFinishTimeMode); - if (!entry.Timer.NeedRing) - continue; - _notificationManager.Enqueue("入渠終了", entry.Name); - entry.Timer.NeedRing = false; + _mainLabels.SetNDockTimer(i, entry.Timer, _now, (_config.ShowEndTime & TimerKind.NDock) != 0); } var kdock = new[] {labelConstruct1, labelConstruct2, labelConstruct3, labelConstruct4}; for (var i = 0; i < kdock.Length; i++) { var timer = _sniffer.KDock[i]; - timer.Update(); - SetTimerColor(kdock[i], timer); - - kdock[i].Text = timer.EndTime == DateTime.MinValue ? "" : timer.Rest.ToString(@"hh\:mm\:ss"); - if (!timer.NeedRing) - continue; - _notificationManager.Enqueue("建造完了", $"第{i + 1:D}ドック"); - timer.NeedRing = false; + SetTimerColor(kdock[i], timer, _now); + kdock[i].Text = timer.ToString(_now); } UpdateCondTimers(); UpdateAkashiTimer(); + _timerEnabled = true; } - private void SetTimerColor(Label label, RingTimer timer) + private void NotifyTimers() { - label.ForeColor = timer.IsFinished ? CUDColor.Red : Color.Black; + for (var i = 0; i < _sniffer.Missions.Length; i++) + { + var entry = _sniffer.Missions[i]; + CheckAlarm("遠征終了", entry.Timer, i + 1, entry.Name); + } + for (var i = 0; i < _sniffer.NDock.Length; i++) + { + var entry = _sniffer.NDock[i]; + CheckAlarm("入渠終了", entry.Timer, i, entry.Name); + } + for (var i = 0; i < _sniffer.KDock.Length; i++) + { + var timer = _sniffer.KDock[i]; + CheckAlarm("建造完了", timer, 0, $"第{i + 1:D}ドック"); + } + NotifyCondTimers(); + NotifyAkashiTimer(); + _notificationManager.Flash(); + } + + private void CheckAlarm(string key, AlarmTimer timer, int fleet, string subject) + { + if (timer.CheckAlarm(_prev, _now)) + { + SetNotification(key, fleet, subject); + return; + } + var pre = TimeSpan.FromSeconds(_config.Notifications[key].PreliminaryPeriod); + if (pre == TimeSpan.Zero) + return; + if (timer.CheckAlarm(_prev + pre, _now + pre)) + SetPreNotification(key, fleet, subject); + } + + private void SetTimerColor(Label label, AlarmTimer timer, DateTime now) + { + label.ForeColor = timer.IsFinished(now) ? CUDColor.Red : Color.Black; } private void UpdateCondTimers() @@ -658,32 +862,44 @@ namespace KancolleSniffer { timer = _sniffer.GetConditionTimer(_currentFleet); } - var now = DateTime.Now; if (timer == DateTime.MinValue) { labelCondTimerTitle.Text = ""; labelCondTimer.Text = ""; return; } - var span = TimeSpan.FromSeconds(Ceiling((timer - now).TotalSeconds)); + var span = TimeSpan.FromSeconds(Ceiling((timer - _now).TotalSeconds)); if (span >= TimeSpan.FromMinutes(9)) { labelCondTimerTitle.Text = "cond40まで"; labelCondTimer.Text = (span - TimeSpan.FromMinutes(9)).ToString(@"mm\:ss"); + labelCondTimer.ForeColor = DefaultForeColor; } else { labelCondTimerTitle.Text = "cond49まで"; labelCondTimer.Text = (span >= TimeSpan.Zero ? span : TimeSpan.Zero).ToString(@"mm\:ss"); + labelCondTimer.ForeColor = span <= TimeSpan.Zero ? CUDColor.Red : DefaultForeColor; } - var notice = _sniffer.GetConditionNotice(); - if (notice == null) - return; + } + + private void NotifyCondTimers() + { + var notice = _sniffer.GetConditionNotice(_prev, _now); + var pre = TimeSpan.FromSeconds(_config.Notifications["疲労回復"].PreliminaryPeriod); + var preNotice = pre == TimeSpan.Zero + ? new int[ShipInfo.FleetCount] + : _sniffer.GetConditionNotice(_prev + pre, _now + pre); for (var i = 0; i < ShipInfo.FleetCount; i++) { - if (!_config.NotifyConditions.Contains(notice[i])) - return; - _notificationManager.Enqueue("疲労回復" + notice[i], i, "cond" + notice[i]); + if (_config.NotifyConditions.Contains(notice[i])) + { + SetNotification("疲労回復" + notice[i], i, "cond" + notice[i]); + } + else if (_config.NotifyConditions.Contains(preNotice[i])) + { + SetPreNotification("疲労回復" + preNotice[i], i, "cond" + notice[i]); + } } } @@ -691,20 +907,20 @@ namespace KancolleSniffer { if (_config.UsePresetAkashi) UpdatePresetAkashiTimer(); - _shipLabels.SetAkashiTimer(_sniffer.GetShipStatuses(_currentFleet), + var statuses = _sniffer.GetShipStatuses(_currentFleet); + _mainLabels.SetAkashiTimer(statuses, _sniffer.AkashiTimer.GetTimers(_currentFleet)); - NotifyAkashiTimer(); } private void UpdatePresetAkashiTimer() { var akashi = _sniffer.AkashiTimer; var span = akashi.PresetDeckTimer; - var color = span == TimeSpan.Zero && akashi.CheckPresetReparing() ? CUDColor.Red : DefaultForeColor; + var color = span == TimeSpan.Zero && akashi.CheckPresetRepairing() ? CUDColor.Red : DefaultForeColor; var text = span == TimeSpan.MinValue ? "" : span.ToString(@"mm\:ss"); labelAkashiRepairTimer.ForeColor = color; labelAkashiRepairTimer.Text = text; - if (akashi.CheckPresetReparing() && !akashi.CheckReparing(_currentFleet)) + if (akashi.CheckPresetRepairing() && !akashi.CheckRepairing(_currentFleet)) { labelPresetAkashiTimer.ForeColor = color; labelPresetAkashiTimer.Text = text; @@ -716,6 +932,61 @@ namespace KancolleSniffer } } + private void NotifyAkashiTimer() + { + var akashi = _sniffer.AkashiTimer; + var msgs = akashi.GetNotice(_prev, _now); + if (msgs.Length == 0) + { + _notificationManager.StopRepeat("泊地修理"); + return; + } + if (!akashi.CheckRepairing() && !(akashi.CheckPresetRepairing() && _config.UsePresetAkashi)) + { + _notificationManager.StopRepeat("泊地修理"); + return; + } + var skipPreliminary = false; + if (msgs[0].Proceeded == "20分経過しました。") + { + SetNotification("泊地修理20分経過", msgs[0].Proceeded); + msgs[0].Proceeded = ""; + skipPreliminary = true; + // 修理完了がいるかもしれないので続ける + } + for (var i = 0; i < ShipInfo.FleetCount; i++) + { + if (msgs[i].Proceeded != "") + SetNotification("泊地修理進行", i, msgs[i].Proceeded); + if (msgs[i].Completed != "") + SetNotification("泊地修理完了", i, msgs[i].Completed); + } + var pre = TimeSpan.FromSeconds(_config.Notifications["泊地修理20分経過"].PreliminaryPeriod); + if (skipPreliminary || pre == TimeSpan.Zero) + return; + if ((msgs = akashi.GetNotice(_prev + pre, _now + pre))[0].Proceeded == "20分経過しました。") + SetPreNotification("泊地修理20分経過", 0, msgs[0].Proceeded); + } + + private void SetNotification(string key, string subject) + { + SetNotification(key, 0, subject); + } + + private void SetNotification(string key, int fleet, string subject) + { + var spec = _config.Notifications[_notificationManager.KeyToName(key)]; + _notificationManager.Enqueue(key, fleet, subject, + (spec.Flags & _config.NotificationFlags & NotificationType.Repeat) == 0 ? 0 : spec.RepeatInterval); + } + + private void SetPreNotification(string key, int fleet, string subject) + { + var spec = _config.Notifications[_notificationManager.KeyToName(key)]; + if ((spec.Flags & NotificationType.Preliminary) != 0) + _notificationManager.Enqueue(key, fleet, subject, 0, true); + } + private void UpdateRepairList() { panelRepairList.SetRepairList(_sniffer.RepairList); @@ -729,6 +1000,11 @@ namespace KancolleSniffer labelQuestColor6 }; var name = new[] {labelQuest1, labelQuest2, labelQuest3, labelQuest4, labelQuest5, labelQuest6}; + var count = new[] + { + labelQuestCount1, labelQuestCount2, labelQuestCount3, labelQuestCount4, labelQuestCount5, + labelQuestCount6 + }; var progress = new[] {labelProgress1, labelProgress2, labelProgress3, labelProgress4, labelProgress5, labelProgress6}; var quests = _sniffer.Quests; @@ -739,28 +1015,52 @@ namespace KancolleSniffer category[i].BackColor = quests[i].Color; name[i].Text = quests[i].Name; progress[i].Text = $"{quests[i].Progress:D}%"; + _toolTipQuest.SetToolTip(name[i], quests[i].ToToolTip()); + var c = quests[i].Count; + if (c.Id == 0) + { + count[i].Text = ""; + count[i].ForeColor = Color.Black; + _toolTip.SetToolTip(count[i], ""); + continue; + } + count[i].Text = " " + c; + count[i].ForeColor = c.Cleared ? CUDColor.Green : Color.Black; + _toolTip.SetToolTip(count[i], c.ToToolTip()); } else { category[i].BackColor = DefaultBackColor; - name[i].Text = progress[i].Text = ""; + name[i].Text = count[i].Text = progress[i].Text = ""; + _toolTipQuest.SetToolTip(name[i], ""); + _toolTip.SetToolTip(count[i], ""); } } } - private void Ring(string balloonTitle, string balloonMessage, string name) + private void Alarm(string balloonTitle, string balloonMessage, string name) { - if (_config.FlashWindow && (_config.Notifications[name] & NotificationType.FlashWindow) != 0) + var flags = _config.Notifications[name].Flags; + var effective = _config.NotificationFlags & _config.Notifications[name].Flags; + if ((effective & NotificationType.FlashWindow) != 0) Win32API.FlashWindow(Handle); - if (_config.ShowBaloonTip && (_config.Notifications[name] & NotificationType.ShowBaloonTip) != 0) + if ((effective & NotificationType.ShowBaloonTip) != 0) notifyIconMain.ShowBalloonTip(20000, balloonTitle, balloonMessage, ToolTipIcon.Info); - if (_config.PlaySound && (_config.Notifications[name] & NotificationType.PlaySound) != 0) + if ((effective & NotificationType.PlaySound) != 0) PlaySound(_config.Sounds[name], _config.Sounds.Volume); - if (_config.Pushbullet.On && (_config.Notifications[name] & NotificationType.Pushbullet) != 0) + if (_config.Pushbullet.On && (flags & NotificationType.Push) != 0) + { + Task.Run(() => + { + PushNotification.PushToPushbullet(_config.Pushbullet.Token, balloonTitle, balloonMessage); + }); + } + if (_config.Pushover.On && (flags & NotificationType.Push) != 0) { Task.Run(() => { - PushBullet.PushNote(_config.Pushbullet.Token, balloonTitle, balloonMessage); + PushNotification.PushToPushover(_config.Pushover.ApiKey, _config.Pushover.UserKey, + balloonTitle, balloonMessage); }); } } @@ -826,9 +1126,6 @@ namespace KancolleSniffer } _combinedFleet = false; _currentFleet = fleet; - foreach (var label in _labelCheckFleets) - label.Visible = false; - _labelCheckFleets[fleet].Visible = true; UpdatePanelShipInfo(); } @@ -842,6 +1139,8 @@ namespace KancolleSniffer labelFleet1.Text = _combinedFleet ? "連合" : "第一"; } + private readonly Color _activeButtonColor = Color.FromArgb(152, 179, 208); + private void labelBucketHistoryButton_Click(object sender, EventArgs e) { if (labelBucketHistory.Visible) @@ -853,7 +1152,7 @@ namespace KancolleSniffer { labelBucketHistory.Visible = true; labelBucketHistory.BringToFront(); - labelBucketHistoryButton.BackColor = SystemColors.ActiveCaption; + labelBucketHistoryButton.BackColor = _activeButtonColor; } } @@ -874,7 +1173,7 @@ namespace KancolleSniffer { panelMaterialHistory.Visible = true; panelMaterialHistory.BringToFront(); - labelMaterialHistoryButton.BackColor = SystemColors.ActiveCaption; + labelMaterialHistoryButton.BackColor = _activeButtonColor; } } @@ -901,7 +1200,7 @@ namespace KancolleSniffer { panelRepairList.Visible = true; panelRepairList.BringToFront(); - labelRepairListButton.BackColor = SystemColors.ActiveCaption; + labelRepairListButton.BackColor = _activeButtonColor; } } @@ -925,6 +1224,37 @@ namespace KancolleSniffer Process.Start("http://localhost:" + _config.Proxy.Listen + "/"); } + private void labelClearQuest_Click(object sender, EventArgs e) + { + _sniffer.ClearQuests(); + UpdateQuestList(); + } + + private void labelClearQuest_MouseDown(object sender, MouseEventArgs e) + { + labelClearQuest.BackColor = _activeButtonColor; + } + + private void labelClearQuest_MouseUp(object sender, MouseEventArgs e) + { + labelClearQuest.BackColor = DefaultBackColor; + } + + private void labelQuest_DoubleClick(object sender, EventArgs e) + { + var label = (Label)sender; + if (string.IsNullOrEmpty(label.Text)) + return; + Clipboard.SetText(label.Text); + _tooltipCopy.Active = true; + _tooltipCopy.Show("コピーしました。", label); + Task.Run(async () => + { + await Task.Delay(1000); + _tooltipCopy.Active = false; + }); + } + private void CaptureToolStripMenuItem_Click(object sender, EventArgs e) { try @@ -935,6 +1265,9 @@ namespace KancolleSniffer catch (FileNotFoundException) { } + catch (Win32Exception) + { + } } } } \ No newline at end of file