-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
1212 lines (1024 loc) · 48.9 KB
/
MainWindow.xaml.cs
File metadata and controls
1212 lines (1024 loc) · 48.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using ModernWpf.Controls.Primitives;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using XColumn.Models;
// 曖昧さ回避
using Button = System.Windows.Controls.Button;
using Keyboard = System.Windows.Input.Keyboard;
namespace XColumn
{
/// <summary>
/// アプリケーションのメインウィンドウ。
/// 全体的な状態管理、UIイベント、設定の適用、およびウィンドウレベルの入力制御を行います。
/// </summary>
public partial class MainWindow : Window
{
/// <summary>
/// UIに表示されるカラムのコレクション。
/// </summary>
public ObservableCollection<ColumnData> Columns { get; } = new ObservableCollection<ColumnData>();
// 現在アクティブ(選択中)のカラムデータ
private ColumnData? _activeColumnData;
/// <summary>
/// メモリ上に保持されている拡張機能リスト。
/// </summary>
private List<ExtensionItem> _extensionList = new List<ExtensionItem>();
// アプリがアクティブな時にタイマーを停止するかどうか
public static readonly DependencyProperty StopTimerWhenActiveProperty =
DependencyProperty.Register(nameof(StopTimerWhenActive), typeof(bool), typeof(MainWindow),
new PropertyMetadata(true, OnStopTimerWhenActiveChanged));
// 現在アクティブなプロファイル名
private string? _startupProfileName;
// サーバー監視間隔(分)
private int _serverCheckIntervalMinutes = 5;
// カラム追加時に左端に追加するかどうか
private bool _addColumnToLeft = false;
// --- 設定値保持用フィールド ---
private bool _hideMenuInNonHome = false;
private bool _hideMenuInHome = false;
private bool _hideListHeader = false;
private bool _hideRightSidebar = false;
// 動作設定
private bool _useSoftRefresh = true;
private bool _keepUnreadPosition = false;
private string _customCss = "";
private double _appVolume = 0.5;
// 自動シャットダウン設定
private bool _autoShutdownEnabled = false;
private int _autoShutdownMinutes = 30;
private DateTime? _lastDeactivatedTime = null;
// リスト自動遷移の待機時間
private int _listAutoNavDelay = 2000;
// メディアクリック時にフォーカスモードへ遷移しないかどうか
private bool _disableFocusModeOnMediaClick = false;
// ポスト(ツイート)クリック時にフォーカスモードへ遷移しないかどうか
private bool _disableFocusModeOnTweetClick = false;
// フォント設定
private string _appFontFamily = "Meiryo";
private int _appFontSize = 15;
// テーマ設定
private string _appTheme = "System";
// NGワードリスト
private List<string> _ngWords = new List<string>();
// 言語設定
private string _appLanguage = "ja-JP";
// 起動時のプロファイル設定
private string _startupProfileSetting = "";
// DevTools有効化フラグ
private bool _enableDevTools = false;
// GPU無効化フラグ
private bool _disableGpu = false;
// 自動再生強制無効化フラグ
private bool _forceDisableAutoPlay = false;
// 絶対時間表示フラグ
private bool _showAbsoluteTime = false;
// スクロールトリガーの許容範囲
private int _scrollTopTolerance = 50;
// カラムURL表示用の依存関係プロパティ
public static readonly DependencyProperty ShowColumnUrlProperty =
DependencyProperty.Register(nameof(ShowColumnUrl), typeof(bool), typeof(MainWindow),
new PropertyMetadata(true));
public bool ShowColumnUrl
{
get => (bool)GetValue(ShowColumnUrlProperty);
set => SetValue(ShowColumnUrlProperty, value);
}
// --- 内部状態管理 ---
private Microsoft.Web.WebView2.Core.CoreWebView2Environment? _webViewEnvironment;
private readonly DispatcherTimer _countdownTimer;
private bool _isFocusMode = false;
private bool _isAppActive = true;
private ColumnData? _focusedColumnData = null;
/// <summary>
/// 再起動処理中フラグ(終了時の二重保存防止用)。
/// </summary>
internal bool _isRestarting = false;
private readonly string _userDataFolder;
private readonly string _profilesFolder;
private readonly string _appConfigPath;
/// <summary>
/// メインウィンドウのコンストラクタ(プロファイル名指定なし)。
/// </summary>
public MainWindow() : this(null, false) { }
/// <summary>
/// メインウィンドウのコンストラクタ。
/// </summary>
/// <param name="profileName">起動時に指定されたプロファイル名</param>
public MainWindow(string? profileName, bool enableDevTools = false, bool disableGpu = false)
{
InitializeComponent();
_startupProfileName = profileName;
_enableDevTools = enableDevTools;
_disableGpu = disableGpu;
// ModernWpfのモダンウィンドウスタイルを適用
WindowHelper.SetUseModernWindowStyle(this, true);
// ユーザーデータフォルダとプロファイルフォルダの初期化
_userDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "XColumn");
_profilesFolder = Path.Combine(_userDataFolder, "Profiles");
_appConfigPath = Path.Combine(_userDataFolder, "app_config.json");
Directory.CreateDirectory(_profilesFolder);
ColumnItemsControl.ItemsSource = Columns;
// カラムリストの変更監視(プロパティ変更検知のため)
Columns.CollectionChanged += OnColumnsCollectionChanged;
InitializeProfilesUI();
_countdownTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
_countdownTimer.Tick += CountdownTimer_Tick;
this.Closing += MainWindow_Closing;
this.Activated += MainWindow_Activated;
this.Deactivated += MainWindow_Deactivated;
}
/// <summary>
/// カラムコレクションの変更監視ハンドラ。
/// </summary>
private void OnColumnsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
// 追加されたアイテムのイベント購読
if (e.NewItems != null)
{
foreach (ColumnData item in e.NewItems)
{
item.PropertyChanged += OnColumnPropertyChanged;
}
// カラム追加時も設定保存
SaveSettings(_activeProfileName);
}
// 削除されたアイテムのイベント解除
if (e.OldItems != null)
{
foreach (ColumnData item in e.OldItems)
{
item.PropertyChanged -= OnColumnPropertyChanged;
}
// カラム削除時も設定保存
SaveSettings(_activeProfileName);
}
}
/// <summary>
/// カラムのプロパティが変更されたときの処理。
/// </summary>
private void OnColumnPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
// 保存すべきプロパティが変更された場合に設定を保存
if (e.PropertyName == nameof(ColumnData.RefreshIntervalSeconds) ||
e.PropertyName == nameof(ColumnData.IsAutoRefreshEnabled) ||
e.PropertyName == nameof(ColumnData.IsRetweetHidden) ||
e.PropertyName == nameof(ColumnData.IsReplyHidden) ||
e.PropertyName == nameof(ColumnData.Url) ||
e.PropertyName == nameof(ColumnData.MediaScalePercentage))
{
// TextBoxはLostFocusで更新されるようになったため、ここでは即時保存で問題ない。
SaveSettings(_activeProfileName);
}
}
public bool StopTimerWhenActive
{
get => (bool)GetValue(StopTimerWhenActiveProperty);
set => SetValue(StopTimerWhenActiveProperty, value);
}
/// <summary>
/// 設定変更時に即座にタイマー状態を更新します。
/// </summary>
private static void OnStopTimerWhenActiveChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is MainWindow window && window._isAppActive)
{
bool shouldStop = (bool)e.NewValue;
if (shouldStop) window.StopAllTimers();
else window.StartAllTimers(resume: true);
}
}
// 各カラムの基本幅(固定幅モード時)
public static readonly DependencyProperty ColumnWidthProperty =
DependencyProperty.Register(nameof(ColumnWidth), typeof(double), typeof(MainWindow),
new PropertyMetadata(380.0));
/// <summary>
/// 各カラムの基本幅(固定幅モード時)。
/// </summary>
public double ColumnWidth
{
get => (double)GetValue(ColumnWidthProperty);
set => SetValue(ColumnWidthProperty, value);
}
// ウィンドウ幅に合わせてカラムを等分割するかどうか
public static readonly DependencyProperty UseUniformGridProperty =
DependencyProperty.Register(nameof(UseUniformGrid), typeof(bool), typeof(MainWindow),
new PropertyMetadata(false));
/// <summary>
/// ウィンドウ幅に合わせてカラムを等分割するかどうか。
/// </summary>
public bool UseUniformGrid
{
get => (bool)GetValue(UseUniformGridProperty);
set => SetValue(UseUniformGridProperty, value);
}
/// <summary>
/// ツールバーのボタンクリック時にドロップダウンメニューを表示する汎用ハンドラ。
/// </summary>
private void OpenMenu_Click(object sender, RoutedEventArgs e)
{
if (sender is Button btn && btn.ContextMenu != null)
{
// ボタンの直下にメニューを表示
btn.ContextMenu.PlacementTarget = btn;
btn.ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
btn.ContextMenu.IsOpen = true;
}
}
/// <summary>
/// ビジュアルツリーを遡って特定の親要素を探すヘルパーメソッド
/// </summary>
private static T? FindVisualParent<T>(DependencyObject child) where T : DependencyObject
{
while (child != null)
{
if (child is T parent) return parent;
child = System.Windows.Media.VisualTreeHelper.GetParent(child);
}
return null;
}
private void Window_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
{
// Shiftキーが押されている場合のみ横スクロールとして処理
if (System.Windows.Input.Keyboard.Modifiers == System.Windows.Input.ModifierKeys.Shift)
{
PerformHorizontalScroll(e.Delta);
// イベントを処理済みに設定して、縦スクロールを防止
e.Handled = true;
}
}
/// <summary>
/// キーボードショートカットの処理。
/// WebView以外にフォーカスがある場合のナビゲーションを担当します。
/// </summary>
private void Window_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
// 1. 入力欄(TextBox)での誤動作防止
if (e.OriginalSource is System.Windows.Controls.TextBox ||
e.OriginalSource is System.Windows.Controls.PasswordBox ||
e.OriginalSource is ModernWpf.Controls.NumberBox)
{
return;
}
// フォーカスモード時はアプリ側での左右キー処理は行わない
if (_isFocusMode)
{
return;
}
// 2. アクティブなカラムの状態を確認し、入力中や画像表示中なら処理をスキップ(Web側に任せる)
if (_activeColumnData != null)
{
// A. 入力中なら処理しない
if (_activeColumnData.IsInputActive)
{
return;
}
// B. 画像/動画ビューアが開いているかチェック (URLで判定)
string currentUrl = _activeColumnData.Url;
// 念のため、WebViewから直接最新のURL取得を試みる
if (_activeColumnData.AssociatedWebView?.CoreWebView2 != null)
{
try { currentUrl = _activeColumnData.AssociatedWebView.CoreWebView2.Source; }
catch { /* 無視 */ }
}
// URLに /photo/ や /video/ が含まれている場合、左右キーは画像送りに使うためアプリ側では処理しない
bool isMediaView = !string.IsNullOrEmpty(currentUrl) &&
(currentUrl.Contains("/photo/") || currentUrl.Contains("/video/"));
if (isMediaView && (e.Key == Key.Left || e.Key == Key.Right))
{
return;
}
}
if (Columns.Count == 0) return;
// Ctrlキーが押されているかチェック
bool isCtrl = (System.Windows.Input.Keyboard.Modifiers & System.Windows.Input.ModifierKeys.Control) == System.Windows.Input.ModifierKeys.Control;
bool handled = true;
switch (e.Key)
{
case Key.Left: MoveColumnFocus(-1); break;
case Key.Right: MoveColumnFocus(1); break;
case Key.PageUp: ScrollSelectedColumnVertical(true); break;
case Key.PageDown: ScrollSelectedColumnVertical(false); break;
// 1-9キー
case Key.D1: if (isCtrl) JumpToColumn(0); else handled = false; break;
case Key.D2: if (isCtrl) JumpToColumn(1); else handled = false; break;
case Key.D3: if (isCtrl) JumpToColumn(2); else handled = false; break;
case Key.D4: if (isCtrl) JumpToColumn(3); else handled = false; break;
case Key.D5: if (isCtrl) JumpToColumn(4); else handled = false; break;
case Key.D6: if (isCtrl) JumpToColumn(5); else handled = false; break;
case Key.D7: if (isCtrl) JumpToColumn(6); else handled = false; break;
case Key.D8: if (isCtrl) JumpToColumn(7); else handled = false; break;
case Key.D9: if (isCtrl) JumpToColumn(8); else handled = false; break;
// テンキー
case Key.NumPad1: if (isCtrl) JumpToColumn(0); else handled = false; break;
case Key.NumPad2: if (isCtrl) JumpToColumn(1); else handled = false; break;
case Key.NumPad3: if (isCtrl) JumpToColumn(2); else handled = false; break;
case Key.NumPad4: if (isCtrl) JumpToColumn(3); else handled = false; break;
case Key.NumPad5: if (isCtrl) JumpToColumn(4); else handled = false; break;
case Key.NumPad6: if (isCtrl) JumpToColumn(5); else handled = false; break;
case Key.NumPad7: if (isCtrl) JumpToColumn(6); else handled = false; break;
case Key.NumPad8: if (isCtrl) JumpToColumn(7); else handled = false; break;
case Key.NumPad9: if (isCtrl) JumpToColumn(8); else handled = false; break;
default: handled = false; break;
}
if (handled) e.Handled = true;
}
/// <summary>
/// 現在画面の中央付近にある(メインで見ている)カラムを特定し、
/// そのカラムのWebViewに対してスクロール命令を送ります。
/// </summary>
/// <param name="scrollDown">trueなら下へ、falseなら上へスクロール</param>
private void ScrollActiveColumn(bool scrollDown)
{
// フォーカスモード(シングルビュー)の場合は FocusWebView を操作
if (_isFocusMode && FocusWebView != null && FocusWebView.CoreWebView2 != null)
{
ExecuteScrollScript(FocusWebView.CoreWebView2, scrollDown);
return;
}
// 通常モード: ScrollViewerの現在位置から、中心にあるカラムを特定
var scrollViewer = ColumnItemsControl.Template.FindName("MainScrollViewer", ColumnItemsControl) as ScrollViewer;
if (scrollViewer == null || Columns.Count == 0) return;
// 現在のスクロール位置 + 画面幅の半分 = 中心座標
double centerOffset = scrollViewer.HorizontalOffset + (scrollViewer.ViewportWidth / 2);
int index = -1;
if (UseUniformGrid)
{
// 等分割モードの場合
double widthPerCol = scrollViewer.ViewportWidth / Columns.Count;
index = (int)(centerOffset / widthPerCol);
if (index < 0 || index >= Columns.Count) index = 0;
}
else
{
// 固定幅モードの場合
index = (int)(centerOffset / ColumnWidth);
}
// 範囲チェック
if (index >= 0 && index < Columns.Count)
{
var targetColumn = Columns[index];
if (targetColumn.AssociatedWebView?.CoreWebView2 != null)
{
ExecuteScrollScript(targetColumn.AssociatedWebView.CoreWebView2, scrollDown);
}
}
}
/// <summary>
/// WebView2に対してJSを実行し、スクロールさせます。
/// </summary>
private void ExecuteScrollScript(Microsoft.Web.WebView2.Core.CoreWebView2 webView, bool scrollDown)
{
// 画面の80%分をスクロール
string direction = scrollDown ? "1" : "-1";
string script = $"window.scrollBy(0, window.innerHeight * 0.8 * {direction});";
webView.ExecuteScriptAsync(script);
}
/// <summary>
/// 指定されたスクロール量に基づいて、メインのScrollViewerを水平方向にスクロールさせます。
/// </summary>
/// <param name="delta">スクロール量(ピクセル単位に近い値)</param>
public void PerformHorizontalScroll(double delta)
{
// Template内にあるScrollViewerを名前で検索して取得
var scrollViewer = ColumnItemsControl.Template.FindName("MainScrollViewer", ColumnItemsControl) as ScrollViewer;
if (scrollViewer != null)
{
// ガタガタ対策 & 方向修正:
// Windows標準: deltaが正(右操作)ならOffsetを増やす(右へ)、負なら減らす(左へ)
double currentOffset = scrollViewer.HorizontalOffset;
double newOffset = currentOffset + delta;
scrollViewer.ScrollToHorizontalOffset(newOffset);
}
}
/// <summary>
/// 「設定」ボタンクリック時の処理。
/// </summary>
private void OpenSettings_Click(object sender, RoutedEventArgs e)
{
// AppConfig (言語設定用) の読み込み
AppConfig currentAppConfig = new AppConfig();
if (File.Exists(_appConfigPath))
{
try
{
currentAppConfig = JsonSerializer.Deserialize<AppConfig>(File.ReadAllText(_appConfigPath)) ?? new AppConfig();
}
catch { }
}
// 現在の設定を読み込んで渡す
AppSettings current = ReadSettingsFromFile(_activeProfileName);
current.StopTimerWhenActive = StopTimerWhenActive;
current.UseSoftRefresh = _useSoftRefresh;
current.EnableWindowSnap = _enableWindowSnap;
current.KeepUnreadPosition = _keepUnreadPosition;
current.ScrollTopTolerance = _scrollTopTolerance;
current.CustomCss = _customCss;
current.AppVolume = _appVolume;
current.DisableFocusModeOnMediaClick = _disableFocusModeOnMediaClick;
current.DisableFocusModeOnTweetClick = _disableFocusModeOnTweetClick;
current.AddColumnToLeft = _addColumnToLeft;
current.ColumnWidth = ColumnWidth;
current.UseUniformGrid = UseUniformGrid;
current.HideRightSidebar = _hideRightSidebar;
current.ShowColumnUrl = ShowColumnUrl;
current.AppFontFamily = _appFontFamily;
current.AppFontSize = _appFontSize;
current.AppTheme = _appTheme;
current.ServerCheckIntervalMinutes = _serverCheckIntervalMinutes;
current.AutoShutdownEnabled = _autoShutdownEnabled;
current.AutoShutdownMinutes = _autoShutdownMinutes;
current.CheckForUpdates = _checkForUpdates;
// リスト自動遷移待機時間
current.ListAutoNavDelay = _listAutoNavDelay;
// NGワードをセット
current.NgWords = new List<string>(_ngWords);
var dlg = new SettingsWindow(current, currentAppConfig, _appConfigPath) { Owner = this };
if (dlg.ShowDialog() == true)
{
// 設定を反映
AppSettings newSettings = dlg.Settings;
// 言語設定が変更されたかどうかはSettingsWindow内で処理・保存済み
// Main側に反映(次回起動時のロード用にメモリ更新)
if (currentAppConfig.Language != null)
{
_appLanguage = currentAppConfig.Language;
}
// 起動時プロファイル設定をMain側にも反映して保持する
if (currentAppConfig.StartupProfile != null)
{
_startupProfileSetting = currentAppConfig.StartupProfile;
}
StopTimerWhenActive = newSettings.StopTimerWhenActive;
_hideMenuInNonHome = newSettings.HideMenuInNonHome;
_hideMenuInHome = newSettings.HideMenuInHome;
_hideListHeader = newSettings.HideListHeader;
_hideRightSidebar = newSettings.HideRightSidebar;
_appFontFamily = newSettings.AppFontFamily;
_appFontSize = newSettings.AppFontSize;
_appTheme = newSettings.AppTheme;
_useSoftRefresh = newSettings.UseSoftRefresh;
_keepUnreadPosition = newSettings.KeepUnreadPosition;
_enableWindowSnap = newSettings.EnableWindowSnap;
_scrollTopTolerance = newSettings.ScrollTopTolerance;
_customCss = newSettings.CustomCss;
_disableFocusModeOnMediaClick = newSettings.DisableFocusModeOnMediaClick;
_disableFocusModeOnTweetClick = newSettings.DisableFocusModeOnTweetClick;
// 設定画面からの値をメインウィンドウのフィールドに反映
_forceDisableAutoPlay = newSettings.ForceDisableAutoPlay;
// リスト自動遷移待機時間
_listAutoNavDelay = newSettings.ListAutoNavDelay;
_addColumnToLeft = newSettings.AddColumnToLeft;
// 変更検知:設定画面を開く前の値(ColumnWidth)と新しい値(newSettings.ColumnWidth)を比較
bool isWidthChanged = Math.Abs(ColumnWidth - newSettings.ColumnWidth) > 0.01;
ColumnWidth = newSettings.ColumnWidth;
UseUniformGrid = newSettings.UseUniformGrid;
// 設定画面で指定された幅が変更された場合のみ全カラムに適用
if (!UseUniformGrid && isWidthChanged)
{
foreach (var col in Columns)
{
col.Width = ColumnWidth;
}
}
ShowColumnUrl = newSettings.ShowColumnUrl;
_autoShutdownEnabled = newSettings.AutoShutdownEnabled;
_autoShutdownMinutes = newSettings.AutoShutdownMinutes;
_checkForUpdates = newSettings.CheckForUpdates;
// 絶対時間表示の設定を反映
_showAbsoluteTime = newSettings.ShowAbsoluteTime;
ApplyAbsoluteTimeSettingsToAll();
foreach (var col in Columns)
{
col.UseSoftRefresh = _useSoftRefresh;
}
_serverCheckIntervalMinutes = newSettings.ServerCheckIntervalMinutes;
// NGワードの更新と反映
_ngWords = newSettings.NgWords ?? new List<string>();
// 設定保存 (NGワード含む)
SaveSettings(_activeProfileName);
// テーマの適用
ApplyTheme(_appTheme);
// 開いている全WebViewにCSSを再適用
ApplyCssToAllColumns();
// NGワードスクリプトの再適用
ApplyNgWordsToAllColumns(_ngWords);
// サーバー監視タイマーの間隔を更新
UpdateStatusCheckTimer(newSettings.ServerCheckIntervalMinutes);
}
}
/// <summary>
/// 音量スライダー変更時の処理。
/// </summary>
private void VolumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
_appVolume = e.NewValue / 100.0;
// WebView内にJSを流し込むのではなく、プロセス音量を直接変更する
SetWebView2Volume(_appVolume);
}
/// <summary>
/// 「拡張機能」メニュークリック時の処理。
/// </summary>
private void ManageExtensions_Click(object sender, RoutedEventArgs e)
{
var dlg = new ExtensionWindow(_extensionList) { Owner = this };
if (dlg.ShowDialog() == true)
{
_extensionList = new List<ExtensionItem>(dlg.Extensions);
SaveSettings(_activeProfileName);
if (MessageWindow.Show(this, Properties.Resources.Msg_RestartConfirm,
Properties.Resources.Settings_Title, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
PerformProfileSwitch(_activeProfileName);
}
}
}
/// <summary>
/// カラムごとの「RT非表示」チェックボックスクリック時の処理。
/// </summary>
private void RetweetHidden_Click(object sender, RoutedEventArgs e)
{
if (sender is FrameworkElement element && element.Tag is ColumnData col)
{
if (col.AssociatedWebView?.CoreWebView2 != null)
{
ApplyCustomCss(col.AssociatedWebView.CoreWebView2, col.Url, col);
}
SaveSettings(_activeProfileName);
}
}
/// <summary>
/// カラムごとの「リプライ非表示」チェックボックスクリック時の処理
/// </summary>
private void ReplyHidden_Click(object sender, RoutedEventArgs e)
{
if (sender is FrameworkElement element && element.Tag is ColumnData col)
{
if (col.AssociatedWebView?.CoreWebView2 != null)
{
// カラム個別にCSSを再適用
ApplyCustomCss(col.AssociatedWebView.CoreWebView2, col.Url, col);
}
SaveSettings(_activeProfileName);
}
}
/// <summary>
/// ウィンドウロード時の初期化処理。
/// </summary>
private async void Window_Loaded(object? sender, RoutedEventArgs e)
{
try
{
if (!string.IsNullOrEmpty(_startupProfileName))
{
_activeProfileName = _startupProfileName;
var existing = _profileNames.FirstOrDefault(p => p.Name == _activeProfileName);
if (existing == null) _profileNames.Add(new ProfileItem { Name = _activeProfileName, IsActive = true });
else foreach (var p in _profileNames) p.IsActive = (p.Name == _activeProfileName);
ProfileComboBox.SelectedItem = _profileNames.FirstOrDefault(p => p.Name == _activeProfileName);
}
// ウィンドウタイトル更新
UpdateWindowTitle();
// 念のため選択状態を保証
if (ProfileComboBox.SelectedItem == null)
{
ProfileComboBox.SelectedItem = _profileNames.FirstOrDefault(p => p.Name == _activeProfileName);
}
AppSettings settings = ReadSettingsFromFile(_activeProfileName);
ApplySettingsToWindow(settings);
// WebView環境初期化
await InitializeWebViewEnvironmentAsync();
// カラム復元
LoadColumnsFromSettings(settings);
// アップデート確認
_ = CheckForUpdatesAsync(settings.SkippedVersion);
// 接続監視機能の初期化
InitializeStatusChecker();
}
catch (Exception ex)
{
string msg = string.Format(Properties.Resources.Err_InitFailed, ex.Message);
MessageWindow.Show(msg, Properties.Resources.Common_Error, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
/// <summary>
/// 終了時の保存処理。
/// </summary>
private void MainWindow_Closing(object? sender, CancelEventArgs e)
{
DisableWindowSnap();
if (_isRestarting) return;
SaveSettings(_activeProfileName);
SaveAppConfig();
_countdownTimer.Stop();
foreach (var col in Columns) col.StopAndDisposeTimer();
}
/// <summary>
/// アプリがアクティブになった時の処理。
/// </summary>
private void MainWindow_Activated(object? sender, EventArgs e)
{
_isAppActive = true;
// 自動シャットダウン用の時間記録をクリア
_lastDeactivatedTime = null;
if (StopTimerWhenActive) StopAllTimers();
// アクティブ化されたとき、スナップしている他のウィンドウも前面に持ってくる
BringSnappedWindowsToFront();
}
/// <summary>
/// アプリが非アクティブになった時の処理。
/// </summary>
private void MainWindow_Deactivated(object? sender, EventArgs e)
{
_isAppActive = false;
// 自動シャットダウン用の時間を記録
_lastDeactivatedTime = DateTime.Now;
if (_isFocusMode) return;
if (StopTimerWhenActive) StartAllTimers(resume: true);
}
/// <summary>
/// タイマーをすべて停止します。
/// </summary>
private void StopAllTimers()
{
_countdownTimer.Stop();
foreach (var col in Columns) col.Timer?.Stop();
}
/// <summary>
/// タイマーをすべて開始または再開します。
/// </summary>
/// <param name="resume"></param>
private void StartAllTimers(bool resume)
{
_countdownTimer.Start();
foreach (var col in Columns) col.UpdateTimer(!resume);
}
/// <summary>
/// 1秒ごとに呼び出されるカウントダウンタイマーの処理。
/// </summary>
private void CountdownTimer_Tick(object? sender, EventArgs e)
{
foreach (var column in Columns)
{
if (column.IsAutoRefreshEnabled && column.RemainingSeconds > 0)
column.RemainingSeconds--;
}
// 自動シャットダウン判定
if (_autoShutdownEnabled && !_isAppActive && _lastDeactivatedTime.HasValue)
{
var elapsed = DateTime.Now - _lastDeactivatedTime.Value;
if (elapsed.TotalMinutes >= _autoShutdownMinutes)
{
// 念のためタイマーを止めてから終了
_countdownTimer.Stop();
Close();
}
}
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
EnableWindowSnap();
}
/// <summary>
/// アプリ終了
/// </summary>
private void Exit_Click(object sender, RoutedEventArgs e)
{
Close();
}
/// <summary>
/// バージョン情報表示
/// </summary>
private void About_Click(object sender, RoutedEventArgs e)
{
string message = string.Format(Properties.Resources.Msg_About_Body, this.Title);
MessageWindow.Show(message, Properties.Resources.Title_About, MessageBoxButton.OK, MessageBoxImage.Information);
}
/// <summary>
/// プロファイルメニューが開かれたときに、プロファイル一覧を動的に生成します。
/// </summary>
private void MenuProfile_SubmenuOpened(object sender, RoutedEventArgs e)
{
if (e.OriginalSource != sender) return;
// 静的アイテム([0]新規作成, [1]セパレータ)以外をクリア
while (MenuProfile.Items.Count > 2)
{
MenuProfile.Items.RemoveAt(2);
}
if (_profileNames != null)
{
foreach (var profile in _profileNames)
{
// 親アイテム(プロファイル名)
var parentItem = new MenuItem
{
Header = profile.Name
// IsChecked は設定しない(サブメニュー展開の阻害要因になるため)
};
// アクティブなら太字で強調
if (profile.IsActive)
{
parentItem.FontWeight = FontWeights.Bold;
}
// --- 子メニューの構築 ---
// 1. 切り替え
var switchItem = new MenuItem
{
Header = Properties.Resources.Menu_Profile_Switch,
Tag = profile.Name,
IsEnabled = !profile.IsActive
};
switchItem.Click += SwitchProfile_Click;
parentItem.Items.Add(switchItem);
parentItem.Items.Add(new Separator());
// 2. 名前変更
var renameItem = new MenuItem
{
Header = Properties.Resources.Menu_Profile_Rename,
Tag = profile.Name,
IsEnabled = !profile.IsActive
};
renameItem.Click += RenameProfile_Click;
parentItem.Items.Add(renameItem);
// 3. 複製
var dupItem = new MenuItem
{
Header = Properties.Resources.Menu_Profile_Duplicate,
Tag = profile.Name
};
dupItem.Click += DuplicateProfile_Click;
parentItem.Items.Add(dupItem);
// 4. 別窓で起動
var launchItem = new MenuItem
{
Header = Properties.Resources.Menu_Profile_LaunchNew,
Tag = profile.Name
};
launchItem.Click += LaunchNewWindow_Click;
parentItem.Items.Add(launchItem);
parentItem.Items.Add(new Separator());
// 5. 削除
var deleteItem = new MenuItem
{
Header = Properties.Resources.Menu_Profile_Delete,
Tag = profile.Name,
Foreground = System.Windows.Media.Brushes.Red,
IsEnabled = !profile.IsActive
};
deleteItem.Click += DeleteProfile_Click;
parentItem.Items.Add(deleteItem);
// 親アイテムをメニューに追加
MenuProfile.Items.Add(parentItem);
}
}
}
/// <summary>
/// WebViewがフォーカスを得たときに呼び出されます。
/// 現在アクティブなカラムを記録します。
/// </summary>
private void WebView_GotFocus(object sender, RoutedEventArgs e)
{
if (sender is Microsoft.Web.WebView2.Wpf.WebView2 webView && webView.DataContext is ColumnData col)
{
_activeColumnData = col;
// 全カラムの IsActive を更新
foreach (var c in Columns)
{
c.IsActive = (c == col);
}
}
}
/// <summary>
/// カラムフォーカスを隣へ移動させます。
/// </summary>
/// <param name="direction">移動方向 (-1: 左, 1: 右)</param>
private void MoveColumnFocus(int direction)
{
if (Columns.Count == 0) return;
int currentIndex = -1;
// 現在のアクティブカラムの位置を探す
if (_activeColumnData != null)
{
currentIndex = Columns.IndexOf(_activeColumnData);
}
// 見つからない、または未選択なら、方向に応じて端を選択
if (currentIndex == -1)
{
currentIndex = (direction > 0) ? 0 : Columns.Count - 1;
}
else
{
// インデックス移動
currentIndex += direction;
}
// 範囲制限
if (currentIndex < 0) currentIndex = 0;
if (currentIndex >= Columns.Count) currentIndex = Columns.Count - 1;
// ターゲットのカラムを取得してフォーカス
var targetColumn = Columns[currentIndex];
if (targetColumn.AssociatedWebView != null)
{
// 1. WebViewにフォーカスを当てる
targetColumn.AssociatedWebView.Focus();
// 2. そのカラムが見える位置までスクロールする
ScrollToColumn(targetColumn);
}
}
/// <summary>
/// 指定したカラムが見える位置までスクロールします。
/// </summary>
private void ScrollToColumn(ColumnData col)
{
var scrollViewer = ColumnItemsControl.Template.FindName("MainScrollViewer", ColumnItemsControl) as ScrollViewer;
if (scrollViewer == null) return;