OSDN Git Service

AccountCollectionクラスを追加
[opentween/open-tween.git] / OpenTween / Tween.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 //           (c) 2008-2011 Moz (@syo68k)
4 //           (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 //           (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 //           (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 //           (c) 2011      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
9 //
10 // This file is part of OpenTween.
11 //
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
15 // any later version.
16 //
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
20 // for more details.
21 //
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
26
27 #nullable enable
28
29 // コンパイル後コマンド
30 // "c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
31 // "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
32
33 using System;
34 using System.Collections.Concurrent;
35 using System.Collections.Generic;
36 using System.ComponentModel;
37 using System.Diagnostics;
38 using System.Diagnostics.CodeAnalysis;
39 using System.Drawing;
40 using System.Globalization;
41 using System.IO;
42 using System.Linq;
43 using System.Media;
44 using System.Net;
45 using System.Net.Http;
46 using System.Reflection;
47 using System.Runtime.InteropServices;
48 using System.Text;
49 using System.Text.RegularExpressions;
50 using System.Threading;
51 using System.Threading.Tasks;
52 using System.Windows.Forms;
53 using OpenTween.Api;
54 using OpenTween.Api.DataModel;
55 using OpenTween.Api.GraphQL;
56 using OpenTween.Api.TwitterV2;
57 using OpenTween.Connection;
58 using OpenTween.MediaUploadServices;
59 using OpenTween.Models;
60 using OpenTween.OpenTweenCustomControl;
61 using OpenTween.Setting;
62 using OpenTween.SocialProtocol;
63 using OpenTween.Thumbnail;
64
65 namespace OpenTween
66 {
67     public partial class TweenMain : OTBaseForm
68     {
69         // 各種設定
70
71         /// <summary>画面サイズ</summary>
72         private Size mySize;
73
74         /// <summary>画面位置</summary>
75         private Point myLoc;
76
77         /// <summary>区切り位置</summary>
78         private int mySpDis;
79
80         /// <summary>発言欄区切り位置</summary>
81         private int mySpDis2;
82
83         /// <summary>プレビュー区切り位置</summary>
84         private int mySpDis3;
85
86         // 雑多なフラグ類
87         private bool initial; // true:起動時処理中
88         private bool initialLayout = true;
89         private bool ignoreConfigSave; // true:起動時処理中
90
91         /// <summary>タブドラッグ中フラグ(DoDragDropを実行するかの判定用)</summary>
92         private bool tabDrag;
93
94         private TabPage? beforeSelectedTab; // タブが削除されたときに前回選択されていたときのタブを選択する為に保持
95         private Point tabMouseDownPoint;
96
97         /// <summary>右クリックしたタブの名前(Tabコントロール機能不足対応)</summary>
98         private string? rclickTabName;
99
100         private readonly object syncObject = new(); // ロック用
101
102         private readonly DetailsHtmlBuilder detailsHtmlBuilder = new();
103
104         private bool myStatusError = false;
105         private bool myStatusOnline = false;
106         private bool soundfileListup = false;
107         private FormWindowState formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
108
109         // 設定ファイル
110         private readonly SettingManager settings;
111
112         // ユーザーアカウント
113         private readonly AccountCollection accounts;
114
115 #pragma warning disable SA1300
116         private Twitter tw => this.accounts.Primary; // AccountCollection への移行用
117 #pragma warning restore SA1300
118
119         // Growl呼び出し部
120         private readonly GrowlHelper gh = new(ApplicationSettings.ApplicationName);
121
122         // サブ画面インスタンス
123
124         /// <summary>検索画面インスタンス</summary>
125         internal SearchWordDialog SearchDialog = new();
126
127         private readonly OpenURL urlDialog = new();
128
129         /// <summary>@id補助</summary>
130         public AtIdSupplement AtIdSupl = null!;
131
132         /// <summary>Hashtag補助</summary>
133         public AtIdSupplement HashSupl = null!;
134
135         public HashtagManage HashMgr = null!;
136
137         // 表示フォント、色、アイコン
138         private ThemeManager themeManager;
139
140         /// <summary>アイコン画像リスト</summary>
141         private readonly ImageCache iconCache;
142
143         private readonly IconAssetsManager iconAssets;
144
145         private readonly ThumbnailGenerator thumbGenerator;
146
147         /// <summary>発言履歴</summary>
148         private readonly StatusTextHistory history = new();
149
150         // 発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
151
152         /// <summary>リプライ先のステータスID・スクリーン名</summary>
153         private (PostId StatusId, string ScreenName)? inReplyTo = null;
154
155         // 時速表示用
156         private readonly List<DateTimeUtc> postTimestamps = new();
157         private readonly List<DateTimeUtc> favTimestamps = new();
158
159         // 以下DrawItem関連
160         private readonly StringFormat sfTab = new();
161
162         //////////////////////////////////////////////////////////////////////////////////////////////////////////
163
164         /// <summary>発言保持クラス</summary>
165         private readonly TabInformations statuses;
166
167         private TimelineListViewCache? listCache;
168         private TimelineListViewDrawer? listDrawer;
169         private readonly Dictionary<string, TimelineListViewState> listViewState = new();
170
171         private bool isColumnChanged = false;
172
173         private const int MaxWorderThreads = 20;
174         private readonly SemaphoreSlim workerSemaphore = new(MaxWorderThreads);
175         private readonly CancellationTokenSource workerCts = new();
176         private readonly IProgress<string> workerProgress = null!;
177
178         private int unreadCounter = -1;
179         private int unreadAtCounter = -1;
180
181         private readonly string[] columnOrgText = new string[9];
182         private readonly string[] columnText = new string[9];
183
184         private bool doFavRetweetFlags = false;
185
186         //////////////////////////////////////////////////////////////////////////////////////////////////////////
187
188         private readonly TimelineScheduler timelineScheduler = new();
189         private readonly DebounceTimer selectionDebouncer;
190         private readonly DebounceTimer saveConfigDebouncer;
191
192         private readonly string recommendedStatusFooter;
193
194         internal bool SeparateUrlAndFullwidthCharacter { get; set; } = false;
195
196         private bool preventSmsCommand = true;
197
198         // URL短縮のUndo用
199         private readonly record struct UrlUndo(
200             string Before,
201             string After
202         );
203
204         private List<UrlUndo>? urlUndoBuffer = null;
205
206         private readonly record struct ReplyChain(
207             PostId OriginalId,
208             PostId InReplyToId,
209             TabModel OriginalTab
210         );
211
212         /// <summary>[, ]でのリプライ移動の履歴</summary>
213         private Stack<ReplyChain>? replyChains;
214
215         /// <summary>ポスト選択履歴</summary>
216         private readonly Stack<(TabModel, PostClass?)> selectPostChains = new();
217
218         public TabModel CurrentTab
219             => this.statuses.SelectedTab;
220
221         public string CurrentTabName
222             => this.statuses.SelectedTabName;
223
224         public TabPage CurrentTabPage
225             => this.ListTab.TabPages[this.statuses.Tabs.IndexOf(this.CurrentTabName)];
226
227         public DetailsListView CurrentListView
228             => (DetailsListView)this.CurrentTabPage.Tag;
229
230         public PostClass? CurrentPost
231             => this.CurrentTab.SelectedPost;
232
233         public bool Use2ColumnsMode
234             => this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
235
236         /// <summary>検索処理タイプ</summary>
237         internal enum SEARCHTYPE
238         {
239             DialogSearch,
240             NextSearch,
241             PrevSearch,
242         }
243
244         private readonly HookGlobalHotkey hookGlobalHotkey;
245
246         public TweenMain(
247             SettingManager settingManager,
248             TabInformations tabInfo,
249             AccountCollection accounts,
250             ImageCache imageCache,
251             IconAssetsManager iconAssets,
252             ThumbnailGenerator thumbGenerator
253         )
254         {
255             this.settings = settingManager;
256             this.statuses = tabInfo;
257             this.accounts = accounts;
258             this.iconCache = imageCache;
259             this.iconAssets = iconAssets;
260             this.thumbGenerator = thumbGenerator;
261
262             this.InitializeComponent();
263
264             if (!this.DesignMode)
265             {
266                 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
267                 this.StatusText.Dock = DockStyle.Fill;
268             }
269
270             this.hookGlobalHotkey = new HookGlobalHotkey(this);
271
272             this.hookGlobalHotkey.HotkeyPressed += this.HookGlobalHotkey_HotkeyPressed;
273             this.gh.NotifyClicked += this.GrowlHelper_Callback;
274
275             // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
276             this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
277
278             this.ImageSelector.Visible = false;
279             this.ImageSelector.Enabled = false;
280             this.ImageSelector.FilePickDialog = this.OpenFileDialog1;
281
282             this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
283
284             this.ReplaceAppName();
285             this.InitializeShortcuts();
286
287             this.ignoreConfigSave = true;
288
289             this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
290
291             Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
292
293             Regex.CacheSize = 100;
294
295             // アイコン設定
296             this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
297             this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
298             this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
299
300             // <<<<<<<<<設定関連>>>>>>>>>
301             // 設定読み出し
302             this.LoadConfig();
303
304             // 現在の DPI と設定保存時の DPI との比を取得する
305             var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
306
307             this.initial = true;
308
309             // サムネイル関連の初期化
310             // プロキシ設定等の通信まわりの初期化が済んでから処理する
311             var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
312             imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
313             imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
314
315             Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
316
317             // 画像投稿サービス
318             this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
319             this.ImageSelector.Model.SelectMediaService(this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
320
321             this.tweetThumbnail1.Model.Initialize(this.thumbGenerator);
322
323             // ハッシュタグ/@id関連
324             this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
325             this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
326             this.HashMgr = new HashtagManage(this.HashSupl,
327                                     this.settings.Common.HashTags.ToArray(),
328                                     this.settings.Common.HashSelected,
329                                     this.settings.Common.HashIsPermanent,
330                                     this.settings.Common.HashIsHead,
331                                     this.settings.Common.HashIsNotAddToAtReply);
332             if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
333
334             // フォント&文字色&背景色保持
335             this.themeManager = new(this.settings.Local);
336             this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager, this.detailsHtmlBuilder);
337
338             // StringFormatオブジェクトへの事前設定
339             this.sfTab.Alignment = StringAlignment.Center;
340             this.sfTab.LineAlignment = StringAlignment.Center;
341
342             this.detailsHtmlBuilder.Prepare(this.settings.Common, this.themeManager);
343             this.tweetDetailsView.ClearPostBrowser();
344
345             this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
346
347             this.inReplyTo = null;
348
349             // 各種ダイアログ設定
350             this.SearchDialog.Owner = this;
351             this.urlDialog.Owner = this;
352
353             // 新着バルーン通知のチェック状態設定
354             this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
355             this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
356
357             // 新着取得時のリストスクロールをするか。trueならスクロールしない
358             this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
359             this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
360             // サウンド再生(タブ別設定より優先)
361             this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
362             this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
363
364             // ウィンドウ設定
365             this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
366             this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
367             this.myLoc = this.settings.Local.FormLocation;
368             // タイトルバー領域
369             if (this.WindowState != FormWindowState.Minimized)
370             {
371                 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
372                 var outOfScreen = true;
373                 if (Screen.AllScreens.Length == 1) // ハングするとの報告
374                 {
375                     foreach (var scr in Screen.AllScreens)
376                     {
377                         if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
378                         {
379                             outOfScreen = false;
380                             break;
381                         }
382                     }
383
384                     if (outOfScreen)
385                         this.myLoc = new Point(0, 0);
386                 }
387                 this.DesktopLocation = this.myLoc;
388             }
389             this.TopMost = this.settings.Common.AlwaysTop;
390             this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
391             this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
392             this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
393
394             this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
395             this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
396             // 入力欄
397             this.StatusText.Font = this.themeManager.FontInputFont;
398             this.StatusText.ForeColor = this.themeManager.ColorInputFont;
399
400             // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
401             this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
402             this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
403
404             // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
405             this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
406
407             // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
408             if (this.settings.Common.UnreadManage == false)
409             {
410                 this.ReadedStripMenuItem.Enabled = false;
411                 this.UnreadStripMenuItem.Enabled = false;
412             }
413
414             // リンク先URL表示部の初期化(画面左下)
415             this.StatusLabelUrl.Text = "";
416             // 状態表示部の初期化(画面右下)
417             this.StatusLabel.Text = "";
418             this.StatusLabel.AutoToolTip = false;
419             this.StatusLabel.ToolTipText = "";
420             // 文字カウンタ初期化
421             this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
422
423             this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
424             this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
425             this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
426             this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
427
428             // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
429             // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
430             // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
431             this.SplitContainer2.Panel2.AccessibleName = "";
432
433             ////////////////////////////////////////////////////////////////////////////////
434             var sortOrder = (SortOrder)this.settings.Common.SortOrder;
435             var mode = this.settings.Common.SortColumn switch
436             {
437                 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
438                 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
439                 1 => ComparerMode.Nickname, // ニックネーム
440                 2 => ComparerMode.Data, // 本文
441                 3 => ComparerMode.Id, // 時刻=発言Id
442                 4 => ComparerMode.Name, // 名前
443                 7 => ComparerMode.Source, // Source
444                 _ => ComparerMode.Id,
445             };
446             this.statuses.SetSortMode(mode, sortOrder);
447             ////////////////////////////////////////////////////////////////////////////////
448
449             this.ApplyListViewIconSize(this.settings.Common.IconSize);
450
451             // <<<<<<<<タブ関連>>>>>>>
452             foreach (var tab in this.statuses.Tabs)
453             {
454                 if (!this.AddNewTab(tab, startup: true))
455                     throw new TabException(Properties.Resources.TweenMain_LoadText1);
456             }
457
458             this.ListTabSelect(this.ListTab.SelectedTab);
459
460             // タブの位置を調整する
461             this.SetTabAlignment();
462
463             MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
464             Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
465
466             if (this.settings.Common.TabIconDisp)
467             {
468                 this.ListTab.DrawMode = TabDrawMode.Normal;
469             }
470             else
471             {
472                 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
473                 this.ListTab.DrawItem += this.ListTab_DrawItem;
474                 this.ListTab.ImageList = null;
475             }
476
477             if (this.settings.Common.HotkeyEnabled)
478             {
479                 // グローバルホットキーの登録
480                 var modKey = HookGlobalHotkey.ModKeys.None;
481                 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
482                     modKey |= HookGlobalHotkey.ModKeys.Alt;
483                 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
484                     modKey |= HookGlobalHotkey.ModKeys.Ctrl;
485                 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
486                     modKey |= HookGlobalHotkey.ModKeys.Shift;
487                 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
488                     modKey |= HookGlobalHotkey.ModKeys.Win;
489
490                 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
491             }
492
493             if (this.settings.Common.IsUseNotifyGrowl)
494                 this.gh.RegisterGrowl();
495
496             this.StatusLabel.Text = Properties.Resources.Form1_LoadText1;       // 画面右下の状態表示を変更
497
498             this.SetMainWindowTitle();
499             this.SetNotifyIconText();
500
501             if (this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
502             {
503                 this.Visible = false;
504             }
505
506             // タイマー設定
507
508             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
509             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
510             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
511             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
512             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
513             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
514             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
515             {
516                 this.DoGetFollowersMenu(),
517                 this.RefreshBlockIdsAsync(),
518                 this.RefreshMuteUserIdsAsync(),
519                 this.RefreshNoRetweetIdsAsync(),
520                 this.RefreshTwitterConfigurationAsync(),
521             }));
522             this.RefreshTimelineScheduler();
523
524             this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
525             this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
526
527             // 更新中アイコンアニメーション間隔
528             this.TimerRefreshIcon.Interval = 200;
529             this.TimerRefreshIcon.Enabled = false;
530
531             this.ignoreConfigSave = false;
532             this.ApplyLayoutFromSettings();
533         }
534
535         private void TweenMain_Activated(object sender, EventArgs e)
536         {
537             // 画面がアクティブになったら、発言欄の背景色戻す
538             if (this.StatusText.Focused)
539             {
540                 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
541             }
542         }
543
544         private bool disposed = false;
545
546         /// <summary>
547         /// 使用中のリソースをすべてクリーンアップします。
548         /// </summary>
549         /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
550         protected override void Dispose(bool disposing)
551         {
552             base.Dispose(disposing);
553
554             if (this.disposed)
555                 return;
556
557             if (disposing)
558             {
559                 this.components?.Dispose();
560
561                 // 後始末
562                 this.SearchDialog.Dispose();
563                 this.urlDialog.Dispose();
564                 this.themeManager.Dispose();
565                 this.sfTab.Dispose();
566
567                 this.timelineScheduler.Dispose();
568                 this.workerCts.Cancel();
569                 this.thumbnailTokenSource?.Dispose();
570
571                 this.hookGlobalHotkey.Dispose();
572             }
573
574             // 終了時にRemoveHandlerしておかないとメモリリークする
575             // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
576             Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
577             Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
578             MyCommon.TwitterApiInfo.AccessLimitUpdated -= this.TwitterApiStatus_AccessLimitUpdated;
579
580             this.disposed = true;
581         }
582
583         private void InitColumns(ListView list, bool startup)
584         {
585             this.InitColumnText();
586
587             ColumnHeader[]? columns = null;
588             try
589             {
590                 if (this.Use2ColumnsMode)
591                 {
592                     columns = new[]
593                     {
594                         new ColumnHeader(), // アイコン
595                         new ColumnHeader(), // 本文
596                     };
597
598                     columns[0].Text = this.columnText[0];
599                     columns[1].Text = this.columnText[2];
600
601                     if (startup)
602                     {
603                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
604
605                         columns[0].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[0]);
606                         columns[1].Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[2]);
607                         columns[0].DisplayIndex = 0;
608                         columns[1].DisplayIndex = 1;
609                     }
610                     else
611                     {
612                         var idx = 0;
613                         foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
614                         {
615                             columns[idx].Width = curListColumn.Width;
616                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
617                             idx++;
618                         }
619                     }
620                 }
621                 else
622                 {
623                     columns = new[]
624                     {
625                         new ColumnHeader(), // アイコン
626                         new ColumnHeader(), // ニックネーム
627                         new ColumnHeader(), // 本文
628                         new ColumnHeader(), // 日付
629                         new ColumnHeader(), // ユーザID
630                         new ColumnHeader(), // 未読
631                         new ColumnHeader(), // マーク&プロテクト
632                         new ColumnHeader(), // ソース
633                     };
634
635                     foreach (var i in Enumerable.Range(0, columns.Length))
636                         columns[i].Text = this.columnText[i];
637
638                     if (startup)
639                     {
640                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this.settings.Local.ScaleDimension.Width;
641
642                         foreach (var (column, index) in columns.WithIndex())
643                         {
644                             column.Width = ScaleBy(widthScaleFactor, this.settings.Local.ColumnsWidth[index]);
645                             column.DisplayIndex = this.settings.Local.ColumnsOrder[index];
646                         }
647                     }
648                     else
649                     {
650                         var idx = 0;
651                         foreach (var curListColumn in this.CurrentListView.Columns.Cast<ColumnHeader>())
652                         {
653                             columns[idx].Width = curListColumn.Width;
654                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
655                             idx++;
656                         }
657                     }
658                 }
659
660                 list.Columns.AddRange(columns);
661
662                 columns = null;
663             }
664             finally
665             {
666                 if (columns != null)
667                 {
668                     foreach (var column in columns)
669                         column?.Dispose();
670                 }
671             }
672         }
673
674         private void InitColumnText()
675         {
676             this.columnText[0] = "";
677             this.columnText[1] = Properties.Resources.AddNewTabText2;
678             this.columnText[2] = Properties.Resources.AddNewTabText3;
679             this.columnText[3] = Properties.Resources.AddNewTabText4_2;
680             this.columnText[4] = Properties.Resources.AddNewTabText5;
681             this.columnText[5] = "";
682             this.columnText[6] = "";
683             this.columnText[7] = "Source";
684
685             this.columnOrgText[0] = "";
686             this.columnOrgText[1] = Properties.Resources.AddNewTabText2;
687             this.columnOrgText[2] = Properties.Resources.AddNewTabText3;
688             this.columnOrgText[3] = Properties.Resources.AddNewTabText4_2;
689             this.columnOrgText[4] = Properties.Resources.AddNewTabText5;
690             this.columnOrgText[5] = "";
691             this.columnOrgText[6] = "";
692             this.columnOrgText[7] = "Source";
693
694             var c = this.statuses.SortMode switch
695             {
696                 ComparerMode.Nickname => 1, // ニックネーム
697                 ComparerMode.Data => 2, // 本文
698                 ComparerMode.Id => 3, // 時刻=発言Id
699                 ComparerMode.Name => 4, // 名前
700                 ComparerMode.Source => 7, // Source
701                 _ => 0,
702             };
703
704             if (this.Use2ColumnsMode)
705             {
706                 if (this.statuses.SortOrder == SortOrder.Descending)
707                 {
708                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
709                     this.columnText[2] = this.columnOrgText[2] + "▾";
710                 }
711                 else
712                 {
713                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
714                     this.columnText[2] = this.columnOrgText[2] + "▴";
715                 }
716             }
717             else
718             {
719                 if (this.statuses.SortOrder == SortOrder.Descending)
720                 {
721                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
722                     this.columnText[c] = this.columnOrgText[c] + "▾";
723                 }
724                 else
725                 {
726                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
727                     this.columnText[c] = this.columnOrgText[c] + "▴";
728                 }
729             }
730         }
731
732         private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
733         {
734             string txt;
735             try
736             {
737                 txt = this.statuses.Tabs[e.Index].TabName;
738             }
739             catch (Exception)
740             {
741                 return;
742             }
743
744             e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
745             if (e.State == DrawItemState.Selected)
746             {
747                 e.DrawFocusRectangle();
748             }
749             Brush fore;
750             try
751             {
752                 if (this.statuses.Tabs[txt].UnreadCount > 0)
753                     fore = Brushes.Red;
754                 else
755                     fore = System.Drawing.SystemBrushes.ControlText;
756             }
757             catch (Exception)
758             {
759                 fore = System.Drawing.SystemBrushes.ControlText;
760             }
761             e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, this.sfTab);
762         }
763
764         private void LoadConfig()
765         {
766             this.statuses.LoadTabsFromSettings(this.settings.Tabs);
767             this.statuses.AddDefaultTabs();
768         }
769
770         private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e)
771         {
772             this.RefreshTimelineScheduler();
773         }
774
775         private void RefreshTimelineScheduler()
776         {
777             static TimeSpan IntervalSecondsOrDisabled(int seconds)
778                 => seconds == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(seconds);
779
780             this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Home] = IntervalSecondsOrDisabled(this.settings.Common.TimelinePeriod);
781             this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Mention] = IntervalSecondsOrDisabled(this.settings.Common.ReplyPeriod);
782             this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Dm] = IntervalSecondsOrDisabled(this.settings.Common.DMPeriod);
783             this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.PublicSearch] = IntervalSecondsOrDisabled(this.settings.Common.PubSearchPeriod);
784             this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.User] = IntervalSecondsOrDisabled(this.settings.Common.UserTimelinePeriod);
785             this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.List] = IntervalSecondsOrDisabled(this.settings.Common.ListsPeriod);
786             this.timelineScheduler.UpdateInterval[TimelineSchedulerTaskType.Config] = TimeSpan.FromHours(6);
787             this.timelineScheduler.UpdateAfterSystemResume = TimeSpan.FromSeconds(30);
788
789             this.timelineScheduler.RefreshSchedule();
790         }
791
792         private void MarkSettingCommonModified()
793         {
794             if (this.saveConfigDebouncer == null)
795                 return;
796
797             this.ModifySettingCommon = true;
798             _ = this.saveConfigDebouncer.Call();
799         }
800
801         private void MarkSettingLocalModified()
802         {
803             if (this.saveConfigDebouncer == null)
804                 return;
805
806             this.ModifySettingLocal = true;
807             _ = this.saveConfigDebouncer.Call();
808         }
809
810         internal void MarkSettingAtIdModified()
811         {
812             if (this.saveConfigDebouncer == null)
813                 return;
814
815             this.ModifySettingAtId = true;
816             _ = this.saveConfigDebouncer.Call();
817         }
818
819         internal void RefreshTimeline()
820         {
821             var curListView = this.CurrentListView;
822
823             // 現在表示中のタブのスクロール位置を退避
824             var currentListViewState = this.listViewState[this.CurrentTabName];
825             currentListViewState.Save(this.ListLockMenuItem.Checked);
826
827             // 更新確定
828             int addCount;
829             addCount = this.statuses.SubmitUpdate(
830                 out var soundFile,
831                 out var notifyPosts,
832                 out var newMentionOrDm,
833                 out var isDelete);
834
835             if (MyCommon.EndingFlag) return;
836
837             // リストに反映&選択状態復元
838             if (this.listCache != null && (this.listCache.IsListSizeMismatched || isDelete))
839             {
840                 using (ControlTransaction.Update(curListView))
841                 {
842                     this.listCache.PurgeCache();
843                     this.listCache.UpdateListSize();
844
845                     // 選択位置などを復元
846                     currentListViewState.RestoreSelection();
847                 }
848             }
849
850             if (addCount > 0)
851             {
852                 if (this.settings.Common.TabIconDisp)
853                 {
854                     foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
855                     {
856                         var tabPage = this.ListTab.TabPages[index];
857                         if (tab.UnreadCount > 0 && tabPage.ImageIndex != 0)
858                             tabPage.ImageIndex = 0; // 未読アイコン
859                     }
860                 }
861                 else
862                 {
863                     this.ListTab.Refresh();
864                 }
865             }
866
867             // スクロール位置を復元
868             currentListViewState.RestoreScroll();
869
870             // 新着通知
871             this.NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
872
873             this.SetMainWindowTitle();
874             if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) this.SetStatusLabelUrl();
875
876             this.HashSupl.AddRangeItem(this.tw.GetHashList());
877         }
878
879         private bool BalloonRequired()
880         {
881             if (this.initial)
882                 return false;
883
884             if (NativeMethods.IsScreenSaverRunning())
885                 return false;
886
887             // 「新着通知」が無効
888             if (!this.NewPostPopMenuItem.Checked)
889                 return false;
890
891             // 「画面最小化・アイコン時のみバルーンを表示する」が有効
892             if (this.settings.Common.LimitBalloon)
893             {
894                 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
895                     return false;
896             }
897
898             return true;
899         }
900
901         private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
902         {
903             if (this.settings.Common.ReadOwnPost)
904             {
905                 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == this.tw.UserId))
906                     return;
907             }
908
909             // 新着通知
910             if (this.BalloonRequired())
911             {
912                 if (notifyPosts != null && notifyPosts.Length > 0)
913                 {
914                     // Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
915                     if (this.settings.Common.IsUseNotifyGrowl)
916                     {
917                         var sb = new StringBuilder();
918                         var reply = false;
919                         var dm = false;
920
921                         foreach (var post in notifyPosts)
922                         {
923                             if (!(notifyPosts.Length > 3))
924                             {
925                                 sb.Clear();
926                                 reply = false;
927                                 dm = false;
928                             }
929                             if (post.IsReply && !post.IsExcludeReply) reply = true;
930                             if (post.IsDm) dm = true;
931                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
932                             switch (this.settings.Common.NameBalloon)
933                             {
934                                 case MyCommon.NameBalloonEnum.UserID:
935                                     sb.Append(post.ScreenName).Append(" : ");
936                                     break;
937                                 case MyCommon.NameBalloonEnum.NickName:
938                                     sb.Append(post.Nickname).Append(" : ");
939                                     break;
940                             }
941                             sb.Append(post.TextFromApi);
942                             if (notifyPosts.Length > 3)
943                             {
944                                 if (notifyPosts.Last() != post) continue;
945                             }
946
947                             var title = new StringBuilder();
948                             GrowlHelper.NotifyType nt;
949                             if (this.settings.Common.DispUsername)
950                             {
951                                 title.Append(this.tw.Username);
952                                 title.Append(" - ");
953                             }
954
955                             if (dm)
956                             {
957                                 title.Append(ApplicationSettings.ApplicationName);
958                                 title.Append(" [DM] ");
959                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
960                                 nt = GrowlHelper.NotifyType.DirectMessage;
961                             }
962                             else if (reply)
963                             {
964                                 title.Append(ApplicationSettings.ApplicationName);
965                                 title.Append(" [Reply!] ");
966                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
967                                 nt = GrowlHelper.NotifyType.Reply;
968                             }
969                             else
970                             {
971                                 title.Append(ApplicationSettings.ApplicationName);
972                                 title.Append(" ");
973                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
974                                 nt = GrowlHelper.NotifyType.Notify;
975                             }
976                             var bText = sb.ToString();
977                             if (MyCommon.IsNullOrEmpty(bText)) return;
978
979                             var image = this.iconCache.TryGetFromCache(post.ImageUrl);
980                             this.gh.Notify(nt, post.StatusId.Id, title.ToString(), bText, image?.Image, post.ImageUrl);
981                         }
982                     }
983                     else
984                     {
985                         var sb = new StringBuilder();
986                         var reply = false;
987                         var dm = false;
988                         foreach (var post in notifyPosts)
989                         {
990                             if (post.IsReply && !post.IsExcludeReply) reply = true;
991                             if (post.IsDm) dm = true;
992                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
993                             switch (this.settings.Common.NameBalloon)
994                             {
995                                 case MyCommon.NameBalloonEnum.UserID:
996                                     sb.Append(post.ScreenName).Append(" : ");
997                                     break;
998                                 case MyCommon.NameBalloonEnum.NickName:
999                                     sb.Append(post.Nickname).Append(" : ");
1000                                     break;
1001                             }
1002                             sb.Append(post.TextFromApi);
1003                         }
1004
1005                         var title = new StringBuilder();
1006                         ToolTipIcon ntIcon;
1007                         if (this.settings.Common.DispUsername)
1008                         {
1009                             title.Append(this.tw.Username);
1010                             title.Append(" - ");
1011                         }
1012
1013                         if (dm)
1014                         {
1015                             ntIcon = ToolTipIcon.Warning;
1016                             title.Append(ApplicationSettings.ApplicationName);
1017                             title.Append(" [DM] ");
1018                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1019                         }
1020                         else if (reply)
1021                         {
1022                             ntIcon = ToolTipIcon.Warning;
1023                             title.Append(ApplicationSettings.ApplicationName);
1024                             title.Append(" [Reply!] ");
1025                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1026                         }
1027                         else
1028                         {
1029                             ntIcon = ToolTipIcon.Info;
1030                             title.Append(ApplicationSettings.ApplicationName);
1031                             title.Append(" ");
1032                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1033                         }
1034                         var bText = sb.ToString();
1035                         if (MyCommon.IsNullOrEmpty(bText)) return;
1036
1037                         this.NotifyIcon1.BalloonTipTitle = title.ToString();
1038                         this.NotifyIcon1.BalloonTipText = bText;
1039                         this.NotifyIcon1.BalloonTipIcon = ntIcon;
1040                         this.NotifyIcon1.ShowBalloonTip(500);
1041                     }
1042                 }
1043             }
1044
1045             // サウンド再生
1046             if (!this.initial && this.settings.Common.PlaySound && !MyCommon.IsNullOrEmpty(soundFile))
1047             {
1048                 try
1049                 {
1050                     var dir = Application.StartupPath;
1051                     if (Directory.Exists(Path.Combine(dir, "Sounds")))
1052                     {
1053                         dir = Path.Combine(dir, "Sounds");
1054                     }
1055                     using var player = new SoundPlayer(Path.Combine(dir, soundFile));
1056                     player.Play();
1057                 }
1058                 catch (Exception)
1059                 {
1060                 }
1061             }
1062
1063             // mentions新着時に画面ブリンク
1064             if (!this.initial && this.settings.Common.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1065             {
1066                 NativeMethods.FlashMyWindow(this.Handle, 3);
1067             }
1068         }
1069
1070         private async void MyList_SelectedIndexChanged(object sender, EventArgs e)
1071         {
1072             var listView = this.CurrentListView;
1073             if (listView != sender)
1074                 return;
1075
1076             var indices = listView.SelectedIndices.Cast<int>().ToArray();
1077             this.CurrentTab.SelectPosts(indices);
1078
1079             if (indices.Length != 1)
1080                 return;
1081
1082             var index = indices[0];
1083             if (index > listView.VirtualListSize - 1) return;
1084
1085             this.PushSelectPostChain();
1086
1087             var post = this.CurrentPost!;
1088             this.statuses.SetReadAllTab(post.StatusId, read: true);
1089
1090             this.listCache?.RefreshStyle();
1091             await this.selectionDebouncer.Call();
1092         }
1093
1094         private void StatusTextHistoryBack()
1095         {
1096             this.history.SetCurrentItem(this.StatusText.Text, this.inReplyTo);
1097             var historyItem = this.history.Back();
1098             this.inReplyTo = historyItem.InReplyTo;
1099             this.StatusText.Text = historyItem.Status;
1100             this.StatusText.SelectionStart = this.StatusText.Text.Length;
1101         }
1102
1103         private void StatusTextHistoryForward()
1104         {
1105             this.history.SetCurrentItem(this.StatusText.Text, this.inReplyTo);
1106             var historyItem = this.history.Forward();
1107             this.inReplyTo = historyItem.InReplyTo;
1108             this.StatusText.Text = historyItem.Status;
1109             this.StatusText.SelectionStart = this.StatusText.Text.Length;
1110         }
1111
1112         private async void PostButton_Click(object sender, EventArgs e)
1113         {
1114             if (this.StatusText.Text.Trim().Length == 0)
1115             {
1116                 if (!this.ImageSelector.Enabled)
1117                 {
1118                     await this.DoRefresh();
1119                     return;
1120                 }
1121             }
1122
1123             var currentPost = this.CurrentPost;
1124             if (this.ExistCurrentPost && currentPost != null && this.StatusText.Text.Trim() == string.Format("RT @{0}: {1}", currentPost.ScreenName, currentPost.TextFromApi))
1125             {
1126                 var rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
1127                                                                "Retweet",
1128                                                                MessageBoxButtons.YesNoCancel,
1129                                                                MessageBoxIcon.Question);
1130                 switch (rtResult)
1131                 {
1132                     case DialogResult.Yes:
1133                         this.StatusText.Text = "";
1134                         await this.DoReTweetOfficial(false);
1135                         return;
1136                     case DialogResult.Cancel:
1137                         return;
1138                 }
1139             }
1140
1141             if (TextContainsOnlyMentions(this.StatusText.Text))
1142             {
1143                 var message = string.Format(Properties.Resources.PostConfirmText, this.StatusText.Text);
1144                 var ret = MessageBox.Show(message, ApplicationSettings.ApplicationName, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
1145
1146                 if (ret != DialogResult.OK)
1147                     return;
1148             }
1149
1150             if (this.settings.Common.Nicoms)
1151             {
1152                 this.StatusText.SelectionStart = this.StatusText.Text.Length;
1153                 await this.UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
1154             }
1155
1156             this.StatusText.SelectionStart = this.StatusText.Text.Length;
1157             this.CheckReplyTo(this.StatusText.Text);
1158
1159             var status = new PostStatusParams();
1160
1161             var statusTextCompat = this.FormatStatusText(this.StatusText.Text);
1162             if (this.GetRestStatusCount(statusTextCompat) >= 0 && this.tw.Api.AuthType == APIAuthType.OAuth1)
1163             {
1164                 // auto_populate_reply_metadata や attachment_url を使用しなくても 140 字以内に
1165                 // 収まる場合はこれらのオプションを使用せずに投稿する
1166                 status.Text = statusTextCompat;
1167                 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1168             }
1169             else
1170             {
1171                 status.Text = this.FormatStatusTextExtended(this.StatusText.Text, out var autoPopulatedUserIds, out var attachmentUrl);
1172                 status.InReplyToStatusId = this.inReplyTo?.StatusId;
1173
1174                 status.AttachmentUrl = attachmentUrl;
1175
1176                 // リプライ先がセットされていても autoPopulatedUserIds が空の場合は auto_populate_reply_metadata を有効にしない
1177                 //  (非公式 RT の場合など)
1178                 var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
1179                 if (replyToPost != null && autoPopulatedUserIds.Length != 0)
1180                 {
1181                     status.AutoPopulateReplyMetadata = true;
1182
1183                     // ReplyToList のうち autoPopulatedUserIds に含まれていないユーザー ID を抽出
1184                     status.ExcludeReplyUserIds = replyToPost.ReplyToList.Select(x => x.UserId).Except(autoPopulatedUserIds)
1185                         .ToArray();
1186                 }
1187             }
1188
1189             if (this.GetRestStatusCount(status.Text) < 0)
1190             {
1191                 // 文字数制限を超えているが強制的に投稿するか
1192                 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
1193                 if (ret != DialogResult.OK)
1194                     return;
1195             }
1196
1197             IMediaUploadService? uploadService = null;
1198             IMediaItem[]? uploadItems = null;
1199             if (this.ImageSelector.Visible)
1200             {
1201                 // 画像投稿
1202                 if (!this.ImageSelector.TryGetSelectedMedia(out var serviceName, out uploadItems))
1203                     return;
1204
1205                 this.ImageSelector.EndSelection();
1206                 uploadService = this.ImageSelector.Model.GetService(serviceName);
1207             }
1208
1209             this.history.AddLast(this.StatusText.Text, this.inReplyTo);
1210
1211             this.inReplyTo = null;
1212             this.StatusText.Text = "";
1213             if (!this.settings.Common.FocusLockToStatusText)
1214                 this.CurrentListView.Focus();
1215             this.urlUndoBuffer = null;
1216             this.UrlUndoToolStripMenuItem.Enabled = false;  // Undoをできないように設定
1217
1218             // Google検索(試験実装)
1219             if (this.StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && this.StatusText.Text.Trim().Length > 7)
1220             {
1221                 var tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(this.StatusText.Text.Substring(7)));
1222                 await MyCommon.OpenInBrowserAsync(this, tmp);
1223             }
1224
1225             await this.PostMessageAsync(status, uploadService, uploadItems);
1226         }
1227
1228         private void EndToolStripMenuItem_Click(object sender, EventArgs e)
1229         {
1230             MyCommon.EndingFlag = true;
1231             this.Close();
1232         }
1233
1234         private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
1235         {
1236             if (!this.settings.Common.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon.EndingFlag == false)
1237             {
1238                 // _endingFlag=false:フォームの×ボタン
1239                 e.Cancel = true;
1240                 this.Visible = false;
1241             }
1242             else
1243             {
1244                 this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
1245                 this.ignoreConfigSave = true;
1246                 MyCommon.EndingFlag = true;
1247                 this.timelineScheduler.Enabled = false;
1248                 this.TimerRefreshIcon.Enabled = false;
1249             }
1250         }
1251
1252         private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
1253         {
1254             this.Visible = true;
1255             if (this.WindowState == FormWindowState.Minimized)
1256             {
1257                 this.WindowState = FormWindowState.Normal;
1258             }
1259             this.Activate();
1260             this.BringToFront();
1261         }
1262
1263         private static int errorCount = 0;
1264
1265         private static bool CheckAccountValid()
1266         {
1267             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1268             {
1269                 errorCount += 1;
1270                 if (errorCount > 5)
1271                 {
1272                     errorCount = 0;
1273                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1274                     return true;
1275                 }
1276                 return false;
1277             }
1278             errorCount = 0;
1279             return true;
1280         }
1281
1282         /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1283         private Task RefreshTabAsync<T>()
1284             where T : TabModel
1285             => this.RefreshTabAsync<T>(backward: false);
1286
1287         /// <summary>指定された型 <typeparamref name="T"/> に合致する全てのタブを更新します</summary>
1288         private Task RefreshTabAsync<T>(bool backward)
1289             where T : TabModel
1290         {
1291             var loadTasks =
1292                 from tab in this.statuses.GetTabsByType<T>()
1293                 select this.RefreshTabAsync(tab, backward);
1294
1295             return Task.WhenAll(loadTasks);
1296         }
1297
1298         /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1299         private Task RefreshTabAsync(TabModel tab)
1300             => this.RefreshTabAsync(tab, backward: false);
1301
1302         /// <summary>指定されたタブ <paramref name="tab"/> を更新します</summary>
1303         private async Task RefreshTabAsync(TabModel tab, bool backward)
1304         {
1305             await this.workerSemaphore.WaitAsync();
1306
1307             try
1308             {
1309                 this.RefreshTasktrayIcon();
1310                 await Task.Run(() => tab.RefreshAsync(this.tw, backward, this.initial, this.workerProgress));
1311             }
1312             catch (WebApiException ex)
1313             {
1314                 this.myStatusError = true;
1315                 var tabType = tab switch
1316                 {
1317                     HomeTabModel => "GetTimeline",
1318                     MentionsTabModel => "GetTimeline",
1319                     DirectMessagesTabModel => "GetDirectMessage",
1320                     FavoritesTabModel => "GetFavorites",
1321                     PublicSearchTabModel => "GetSearch",
1322                     UserTimelineTabModel => "GetUserTimeline",
1323                     ListTimelineTabModel => "GetListStatus",
1324                     RelatedPostsTabModel => "GetRelatedTweets",
1325                     _ => tab.GetType().Name.Replace("Model", ""),
1326                 };
1327                 this.StatusLabel.Text = $"Err:{ex.Message}({tabType})";
1328             }
1329             finally
1330             {
1331                 this.RefreshTimeline();
1332                 this.workerSemaphore.Release();
1333             }
1334         }
1335
1336         private async Task FavAddAsync(PostId statusId, TabModel tab)
1337         {
1338             await this.workerSemaphore.WaitAsync();
1339
1340             try
1341             {
1342                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1343
1344                 this.RefreshTasktrayIcon();
1345                 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
1346             }
1347             catch (WebApiException ex)
1348             {
1349                 this.myStatusError = true;
1350                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
1351             }
1352             finally
1353             {
1354                 this.workerSemaphore.Release();
1355             }
1356         }
1357
1358         private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, PostId statusId, TabModel tab)
1359         {
1360             if (ct.IsCancellationRequested)
1361                 return;
1362
1363             if (!CheckAccountValid())
1364                 throw new WebApiException("Auth error. Check your account");
1365
1366             if (!tab.Posts.TryGetValue(statusId, out var post))
1367                 return;
1368
1369             if (post.IsFav)
1370                 return;
1371
1372             await Task.Run(async () =>
1373             {
1374                 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
1375
1376                 try
1377                 {
1378                     var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1379                     try
1380                     {
1381                         await this.tw.Api.FavoritesCreate(twitterStatusId)
1382                             .IgnoreResponse()
1383                             .ConfigureAwait(false);
1384                     }
1385                     catch (TwitterApiException ex)
1386                         when (ex.Errors.All(x => x.Code == TwitterErrorCode.AlreadyFavorited))
1387                     {
1388                         // エラーコード 139 のみの場合は成功と見なす
1389                     }
1390
1391                     if (this.settings.Common.RestrictFavCheck)
1392                     {
1393                         var status = await this.tw.Api.StatusesShow(twitterStatusId)
1394                             .ConfigureAwait(false);
1395
1396                         if (status.Favorited != true)
1397                             throw new WebApiException("NG(Restricted?)");
1398                     }
1399
1400                     this.favTimestamps.Add(DateTimeUtc.Now);
1401
1402                     // TLでも取得済みならfav反映
1403                     if (this.statuses.Posts.TryGetValue(statusId, out var postTl))
1404                     {
1405                         postTl.IsFav = true;
1406
1407                         var favTab = this.statuses.FavoriteTab;
1408                         favTab.AddPostQueue(postTl);
1409                     }
1410
1411                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
1412                     foreach (var tb in this.statuses.GetTabsInnerStorageType())
1413                     {
1414                         if (tb.Contains(statusId))
1415                             tb.Posts[statusId].IsFav = true;
1416                     }
1417
1418                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
1419                 }
1420                 catch (WebApiException)
1421                 {
1422                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
1423                     throw;
1424                 }
1425
1426                 // 時速表示用
1427                 var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1428                 foreach (var i in MyCommon.CountDown(this.favTimestamps.Count - 1, 0))
1429                 {
1430                     if (this.favTimestamps[i] < oneHour)
1431                         this.favTimestamps.RemoveAt(i);
1432                 }
1433
1434                 this.statuses.DistributePosts();
1435             });
1436
1437             if (ct.IsCancellationRequested)
1438                 return;
1439
1440             this.RefreshTimeline();
1441
1442             if (this.CurrentTabName == tab.TabName)
1443             {
1444                 using (ControlTransaction.Update(this.CurrentListView))
1445                 {
1446                     var idx = tab.IndexOf(statusId);
1447                     if (idx != -1)
1448                         this.listCache?.RefreshStyle(idx);
1449                 }
1450
1451                 var currentPost = this.CurrentPost;
1452                 if (currentPost != null && statusId == currentPost.StatusId)
1453                     this.DispSelectedPost(true); // 選択アイテム再表示
1454             }
1455         }
1456
1457         private async Task FavRemoveAsync(IReadOnlyList<PostId> statusIds, TabModel tab)
1458         {
1459             await this.workerSemaphore.WaitAsync();
1460
1461             try
1462             {
1463                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1464
1465                 this.RefreshTasktrayIcon();
1466                 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
1467             }
1468             catch (WebApiException ex)
1469             {
1470                 this.myStatusError = true;
1471                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
1472             }
1473             finally
1474             {
1475                 this.workerSemaphore.Release();
1476             }
1477         }
1478
1479         private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds, TabModel tab)
1480         {
1481             if (ct.IsCancellationRequested)
1482                 return;
1483
1484             if (!CheckAccountValid())
1485                 throw new WebApiException("Auth error. Check your account");
1486
1487             var successIds = new List<PostId>();
1488
1489             await Task.Run(async () =>
1490             {
1491                 // スレッド処理はしない
1492                 var allCount = 0;
1493                 var failedCount = 0;
1494                 foreach (var statusId in statusIds)
1495                 {
1496                     allCount++;
1497
1498                     var post = tab.Posts[statusId];
1499
1500                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
1501
1502                     if (!post.IsFav)
1503                         continue;
1504
1505                     var twitterStatusId = (post.RetweetedId ?? post.StatusId).ToTwitterStatusId();
1506
1507                     try
1508                     {
1509                         await this.tw.Api.FavoritesDestroy(twitterStatusId)
1510                             .IgnoreResponse()
1511                             .ConfigureAwait(false);
1512                     }
1513                     catch (WebApiException)
1514                     {
1515                         failedCount++;
1516                         continue;
1517                     }
1518
1519                     successIds.Add(statusId);
1520                     post.IsFav = false; // リスト再描画必要
1521
1522                     if (this.statuses.Posts.TryGetValue(statusId, out var tabinfoPost))
1523                         tabinfoPost.IsFav = false;
1524
1525                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
1526                     foreach (var tb in this.statuses.GetTabsInnerStorageType())
1527                     {
1528                         if (tb.Contains(statusId))
1529                             tb.Posts[statusId].IsFav = false;
1530                     }
1531                 }
1532             });
1533
1534             if (ct.IsCancellationRequested)
1535                 return;
1536
1537             var favTab = this.statuses.FavoriteTab;
1538             foreach (var statusId in successIds)
1539             {
1540                 // ツイートが削除された訳ではないので IsDeleted はセットしない
1541                 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
1542             }
1543
1544             this.RefreshTimeline();
1545
1546             if (this.CurrentTabName == tab.TabName)
1547             {
1548                 if (tab.TabType == MyCommon.TabUsageType.Favorites)
1549                 {
1550                     // 色変えは不要
1551                 }
1552                 else
1553                 {
1554                     using (ControlTransaction.Update(this.CurrentListView))
1555                     {
1556                         foreach (var statusId in successIds)
1557                         {
1558                             var idx = tab.IndexOf(statusId);
1559                             if (idx != -1)
1560                                 this.listCache?.RefreshStyle(idx);
1561                         }
1562                     }
1563
1564                     var currentPost = this.CurrentPost;
1565                     if (currentPost != null && successIds.Contains(currentPost.StatusId))
1566                         this.DispSelectedPost(true); // 選択アイテム再表示
1567                 }
1568             }
1569         }
1570
1571         private async Task PostMessageAsync(PostStatusParams postParams, IMediaUploadService? uploadService, IMediaItem[]? uploadItems)
1572         {
1573             await this.workerSemaphore.WaitAsync();
1574
1575             try
1576             {
1577                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1578
1579                 this.RefreshTasktrayIcon();
1580                 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, postParams, uploadService, uploadItems);
1581             }
1582             catch (WebApiException ex)
1583             {
1584                 this.myStatusError = true;
1585                 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
1586             }
1587             finally
1588             {
1589                 this.workerSemaphore.Release();
1590             }
1591         }
1592
1593         private async Task PostMessageAsyncInternal(
1594             IProgress<string> p,
1595             CancellationToken ct,
1596             PostStatusParams postParams,
1597             IMediaUploadService? uploadService,
1598             IMediaItem[]? uploadItems)
1599         {
1600             if (ct.IsCancellationRequested)
1601                 return;
1602
1603             if (!CheckAccountValid())
1604                 throw new WebApiException("Auth error. Check your account");
1605
1606             p.Report("Posting...");
1607
1608             PostClass? post = null;
1609             var errMsg = "";
1610
1611             try
1612             {
1613                 await Task.Run(async () =>
1614                 {
1615                     var postParamsWithMedia = postParams;
1616
1617                     if (uploadService != null && uploadItems != null && uploadItems.Length > 0)
1618                     {
1619                         postParamsWithMedia = await uploadService.UploadAsync(uploadItems, postParamsWithMedia)
1620                             .ConfigureAwait(false);
1621                     }
1622
1623                     post = await this.tw.PostStatus(postParamsWithMedia)
1624                         .ConfigureAwait(false);
1625                 });
1626
1627                 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1628             }
1629             catch (WebApiException ex)
1630             {
1631                 // 処理は中断せずエラーの表示のみ行う
1632                 errMsg = $"Err:{ex.Message}(PostMessage)";
1633                 p.Report(errMsg);
1634                 this.myStatusError = true;
1635             }
1636             catch (UnauthorizedAccessException ex)
1637             {
1638                 // アップロード対象のファイルが開けなかった場合など
1639                 errMsg = $"Err:{ex.Message}(PostMessage)";
1640                 p.Report(errMsg);
1641                 this.myStatusError = true;
1642             }
1643             finally
1644             {
1645                 // 使い終わった MediaItem は破棄する
1646                 if (uploadItems != null)
1647                 {
1648                     foreach (var disposableItem in uploadItems.OfType<IDisposable>())
1649                     {
1650                         disposableItem.Dispose();
1651                     }
1652                 }
1653             }
1654
1655             if (ct.IsCancellationRequested)
1656                 return;
1657
1658             if (!MyCommon.IsNullOrEmpty(errMsg) &&
1659                 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
1660                 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
1661             {
1662                 var message = string.Format(Properties.Resources.StatusUpdateFailed, errMsg, postParams.Text);
1663
1664                 var ret = MessageBox.Show(
1665                     message,
1666                     "Failed to update status",
1667                     MessageBoxButtons.RetryCancel,
1668                     MessageBoxIcon.Question);
1669
1670                 if (ret == DialogResult.Retry)
1671                 {
1672                     await this.PostMessageAsync(postParams, uploadService, uploadItems);
1673                 }
1674                 else
1675                 {
1676                     this.StatusTextHistoryBack();
1677                     this.StatusText.Focus();
1678
1679                     // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
1680                     if (this.settings.Common.FocusLockToStatusText)
1681                         this.StatusText_Enter(this.StatusText, EventArgs.Empty);
1682                 }
1683                 return;
1684             }
1685
1686             this.postTimestamps.Add(DateTimeUtc.Now);
1687
1688             var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1689             foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1690             {
1691                 if (this.postTimestamps[i] < oneHour)
1692                     this.postTimestamps.RemoveAt(i);
1693             }
1694
1695             if (!this.HashMgr.IsPermanent && !MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
1696             {
1697                 this.HashMgr.ClearHashtag();
1698                 this.HashStripSplitButton.Text = "#[-]";
1699                 this.HashTogglePullDownMenuItem.Checked = false;
1700                 this.HashToggleMenuItem.Checked = false;
1701             }
1702
1703             this.SetMainWindowTitle();
1704
1705             // TLに反映
1706             if (post != null)
1707             {
1708                 this.statuses.AddPost(post);
1709                 this.statuses.DistributePosts();
1710                 this.RefreshTimeline();
1711             }
1712
1713             if (this.settings.Common.PostAndGet)
1714                 await this.RefreshTabAsync<HomeTabModel>();
1715         }
1716
1717         private async Task RetweetAsync(IReadOnlyList<PostId> statusIds)
1718         {
1719             await this.workerSemaphore.WaitAsync();
1720
1721             try
1722             {
1723                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
1724
1725                 this.RefreshTasktrayIcon();
1726                 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
1727             }
1728             catch (WebApiException ex)
1729             {
1730                 this.myStatusError = true;
1731                 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
1732             }
1733             finally
1734             {
1735                 this.workerSemaphore.Release();
1736             }
1737         }
1738
1739         private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<PostId> statusIds)
1740         {
1741             if (ct.IsCancellationRequested)
1742                 return;
1743
1744             if (!CheckAccountValid())
1745                 throw new WebApiException("Auth error. Check your account");
1746
1747             bool read;
1748             if (!this.settings.Common.UnreadManage)
1749                 read = true;
1750             else
1751                 read = this.initial && this.settings.Common.Read;
1752
1753             p.Report("Posting...");
1754
1755             var posts = new List<PostClass>();
1756
1757             await Task.Run(async () =>
1758             {
1759                 foreach (var statusId in statusIds)
1760                 {
1761                     var post = await this.tw.PostRetweet(statusId, read).ConfigureAwait(false);
1762                     if (post != null) posts.Add(post);
1763                 }
1764             });
1765
1766             if (ct.IsCancellationRequested)
1767                 return;
1768
1769             p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
1770
1771             this.postTimestamps.Add(DateTimeUtc.Now);
1772
1773             var oneHour = DateTimeUtc.Now - TimeSpan.FromHours(1);
1774             foreach (var i in MyCommon.CountDown(this.postTimestamps.Count - 1, 0))
1775             {
1776                 if (this.postTimestamps[i] < oneHour)
1777                     this.postTimestamps.RemoveAt(i);
1778             }
1779
1780             // 自分のRTはTLの更新では取得できない場合があるので、
1781             // 投稿時取得の有無に関わらず追加しておく
1782             posts.ForEach(post => this.statuses.AddPost(post));
1783
1784             if (this.settings.Common.PostAndGet)
1785             {
1786                 await this.RefreshTabAsync<HomeTabModel>();
1787             }
1788             else
1789             {
1790                 this.statuses.DistributePosts();
1791                 this.RefreshTimeline();
1792             }
1793         }
1794
1795         private async Task RefreshFollowerIdsAsync()
1796         {
1797             await this.workerSemaphore.WaitAsync();
1798
1799             try
1800             {
1801                 this.RefreshTasktrayIcon();
1802                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
1803
1804                 await this.tw.RefreshFollowerIds();
1805
1806                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
1807
1808                 this.RefreshTimeline();
1809                 this.listCache?.PurgeCache();
1810                 this.CurrentListView.Refresh();
1811             }
1812             catch (WebApiException ex)
1813             {
1814                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
1815             }
1816             finally
1817             {
1818                 this.workerSemaphore.Release();
1819             }
1820         }
1821
1822         private async Task RefreshNoRetweetIdsAsync()
1823         {
1824             await this.workerSemaphore.WaitAsync();
1825
1826             try
1827             {
1828                 this.RefreshTasktrayIcon();
1829                 await this.tw.RefreshNoRetweetIds();
1830
1831                 this.StatusLabel.Text = "NoRetweetIds refreshed";
1832             }
1833             catch (WebApiException ex)
1834             {
1835                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
1836             }
1837             finally
1838             {
1839                 this.workerSemaphore.Release();
1840             }
1841         }
1842
1843         private async Task RefreshBlockIdsAsync()
1844         {
1845             await this.workerSemaphore.WaitAsync();
1846
1847             try
1848             {
1849                 this.RefreshTasktrayIcon();
1850                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
1851
1852                 await this.tw.RefreshBlockIds();
1853
1854                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
1855             }
1856             catch (WebApiException ex)
1857             {
1858                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
1859             }
1860             finally
1861             {
1862                 this.workerSemaphore.Release();
1863             }
1864         }
1865
1866         private async Task RefreshTwitterConfigurationAsync()
1867         {
1868             await this.workerSemaphore.WaitAsync();
1869
1870             try
1871             {
1872                 this.RefreshTasktrayIcon();
1873                 await this.tw.RefreshConfiguration();
1874
1875                 if (this.tw.Configuration.PhotoSizeLimit != 0)
1876                 {
1877                     foreach (var (_, service) in this.ImageSelector.Model.MediaServices)
1878                     {
1879                         service.UpdateTwitterConfiguration(this.tw.Configuration);
1880                     }
1881                 }
1882
1883                 this.listCache?.PurgeCache();
1884                 this.CurrentListView.Refresh();
1885             }
1886             catch (WebApiException ex)
1887             {
1888                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
1889             }
1890             finally
1891             {
1892                 this.workerSemaphore.Release();
1893             }
1894         }
1895
1896         private async Task RefreshMuteUserIdsAsync()
1897         {
1898             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
1899
1900             try
1901             {
1902                 await this.tw.RefreshMuteUserIdsAsync();
1903             }
1904             catch (WebApiException ex)
1905             {
1906                 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
1907                 return;
1908             }
1909
1910             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
1911         }
1912
1913         private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
1914         {
1915             if (e.Button == MouseButtons.Left)
1916             {
1917                 this.Visible = true;
1918                 if (this.WindowState == FormWindowState.Minimized)
1919                 {
1920                     this.WindowState = this.formWindowState;
1921                 }
1922                 this.Activate();
1923                 this.BringToFront();
1924             }
1925         }
1926
1927         private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
1928             => await this.ListItemDoubleClickAction();
1929
1930         private async Task ListItemDoubleClickAction()
1931         {
1932             switch (this.settings.Common.ListDoubleClickAction)
1933             {
1934                 case MyCommon.ListItemDoubleClickActionType.Reply:
1935                     this.MakeReplyText();
1936                     break;
1937                 case MyCommon.ListItemDoubleClickActionType.ReplyAll:
1938                     this.MakeReplyText(atAll: true);
1939                     break;
1940                 case MyCommon.ListItemDoubleClickActionType.Favorite:
1941                     await this.FavoriteChange(true);
1942                     break;
1943                 case MyCommon.ListItemDoubleClickActionType.ShowProfile:
1944                     var post = this.CurrentPost;
1945                     if (post != null)
1946                         await this.ShowUserStatus(post.ScreenName, false);
1947                     break;
1948                 case MyCommon.ListItemDoubleClickActionType.ShowTimeline:
1949                     await this.ShowUserTimeline();
1950                     break;
1951                 case MyCommon.ListItemDoubleClickActionType.ShowRelated:
1952                     this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
1953                     break;
1954                 case MyCommon.ListItemDoubleClickActionType.OpenHomeInBrowser:
1955                     this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty);
1956                     break;
1957                 case MyCommon.ListItemDoubleClickActionType.OpenStatusInBrowser:
1958                     this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty);
1959                     break;
1960                 case MyCommon.ListItemDoubleClickActionType.None:
1961                 default:
1962                     // 動作なし
1963                     break;
1964             }
1965         }
1966
1967         private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
1968             => await this.FavoriteChange(true);
1969
1970         private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
1971             => await this.FavoriteChange(false);
1972
1973         private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
1974             => await this.FavoritesRetweetOfficial();
1975
1976         private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
1977             => await this.FavoritesRetweetUnofficial();
1978
1979         private async Task FavoriteChange(bool favAdd, bool multiFavoriteChangeDialogEnable = true)
1980         {
1981             var tab = this.CurrentTab;
1982             var posts = tab.SelectedPosts;
1983
1984             // trueでFavAdd,falseでFavRemove
1985             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || posts.Length == 0
1986                 || !this.ExistCurrentPost) return;
1987
1988             if (posts.Length > 1)
1989             {
1990                 if (favAdd)
1991                 {
1992                     // 複数ツイートの一括ふぁぼは禁止
1993                     // https://support.twitter.com/articles/76915#favoriting
1994                     MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
1995                     this.doFavRetweetFlags = false;
1996                     return;
1997                 }
1998                 else
1999                 {
2000                     if (multiFavoriteChangeDialogEnable)
2001                     {
2002                         var confirm = MessageBox.Show(
2003                             Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
2004                             Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
2005                             MessageBoxButtons.OKCancel,
2006                             MessageBoxIcon.Question);
2007
2008                         if (confirm == DialogResult.Cancel)
2009                             return;
2010                     }
2011                 }
2012             }
2013
2014             if (favAdd)
2015             {
2016                 var selectedPost = posts.Single();
2017                 if (selectedPost.IsFav)
2018                 {
2019                     this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
2020                     return;
2021                 }
2022
2023                 await this.FavAddAsync(selectedPost.StatusId, tab);
2024             }
2025             else
2026             {
2027                 var selectedPosts = posts.Where(x => x.IsFav);
2028                 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
2029                 if (statusIds.Length == 0)
2030                 {
2031                     this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
2032                     return;
2033                 }
2034
2035                 await this.FavRemoveAsync(statusIds, tab);
2036             }
2037         }
2038
2039         private async void AuthorOpenInBrowserMenuItem_Click(object sender, EventArgs e)
2040         {
2041             var post = this.CurrentPost;
2042             if (post != null)
2043                 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + post.ScreenName);
2044             else
2045                 await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl);
2046         }
2047
2048         private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
2049         {
2050             if ((!this.initialLayout) && this.Visible)
2051             {
2052                 if (this.WindowState == FormWindowState.Normal)
2053                 {
2054                     this.mySize = this.ClientSize;
2055                     this.mySpDis = this.SplitContainer1.SplitterDistance;
2056                     this.mySpDis3 = this.SplitContainer3.SplitterDistance;
2057                     if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
2058                     this.MarkSettingLocalModified();
2059                 }
2060             }
2061         }
2062
2063         private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
2064         {
2065             var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
2066             if (comparerMode == null)
2067                 return;
2068
2069             this.SetSortColumn(comparerMode.Value);
2070         }
2071
2072         /// <summary>
2073         /// 列インデックスからソートを行う ComparerMode を求める
2074         /// </summary>
2075         /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
2076         /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
2077         private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
2078         {
2079             if (this.Use2ColumnsMode)
2080                 return ComparerMode.Id;
2081
2082             return columnIndex switch
2083             {
2084                 1 => ComparerMode.Nickname, // ニックネーム
2085                 2 => ComparerMode.Data, // 本文
2086                 3 => ComparerMode.Id, // 時刻=発言Id
2087                 4 => ComparerMode.Name, // 名前
2088                 7 => ComparerMode.Source, // Source
2089                 _ => (ComparerMode?)null, // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
2090             };
2091         }
2092
2093         /// <summary>
2094         /// 発言一覧の指定した位置の列でソートする
2095         /// </summary>
2096         /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
2097         private void SetSortColumnByDisplayIndex(int columnIndex)
2098         {
2099             // 表示上の列の位置から ColumnHeader を求める
2100             var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2101                 .FirstOrDefault(x => x.DisplayIndex == columnIndex);
2102
2103             if (col == null)
2104                 return;
2105
2106             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2107             if (comparerMode == null)
2108                 return;
2109
2110             this.SetSortColumn(comparerMode.Value);
2111         }
2112
2113         /// <summary>
2114         /// 発言一覧の最後列の項目でソートする
2115         /// </summary>
2116         private void SetSortLastColumn()
2117         {
2118             // 表示上の最後列にある ColumnHeader を求める
2119             var col = this.CurrentListView.Columns.Cast<ColumnHeader>()
2120                 .OrderByDescending(x => x.DisplayIndex)
2121                 .First();
2122
2123             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
2124             if (comparerMode == null)
2125                 return;
2126
2127             this.SetSortColumn(comparerMode.Value);
2128         }
2129
2130         /// <summary>
2131         /// 発言一覧を指定された ComparerMode に基づいてソートする
2132         /// </summary>
2133         private void SetSortColumn(ComparerMode sortColumn)
2134         {
2135             if (this.settings.Common.SortOrderLock)
2136                 return;
2137
2138             this.statuses.ToggleSortOrder(sortColumn);
2139             this.InitColumnText();
2140
2141             var list = this.CurrentListView;
2142             if (this.Use2ColumnsMode)
2143             {
2144                 list.Columns[0].Text = this.columnText[0];
2145                 list.Columns[1].Text = this.columnText[2];
2146             }
2147             else
2148             {
2149                 for (var i = 0; i <= 7; i++)
2150                 {
2151                     list.Columns[i].Text = this.columnText[i];
2152                 }
2153             }
2154
2155             this.listCache?.PurgeCache();
2156
2157             var tab = this.CurrentTab;
2158             var post = this.CurrentPost;
2159             if (tab.AllCount > 0 && post != null)
2160             {
2161                 var idx = tab.IndexOf(post.StatusId);
2162                 if (idx > -1)
2163                 {
2164                     this.SelectListItem(list, idx);
2165                     list.EnsureVisible(idx);
2166                 }
2167             }
2168             list.Refresh();
2169
2170             this.MarkSettingCommonModified();
2171         }
2172
2173         private void TweenMain_LocationChanged(object sender, EventArgs e)
2174         {
2175             if (this.WindowState == FormWindowState.Normal && !this.initialLayout)
2176             {
2177                 this.myLoc = this.DesktopLocation;
2178                 this.MarkSettingLocalModified();
2179             }
2180         }
2181
2182         private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
2183         {
2184             var post = this.CurrentPost;
2185             if (!this.ExistCurrentPost)
2186             {
2187                 this.ReplyStripMenuItem.Enabled = false;
2188                 this.ReplyAllStripMenuItem.Enabled = false;
2189                 this.DMStripMenuItem.Enabled = false;
2190                 this.TabMenuItem.Enabled = false;
2191                 this.IDRuleMenuItem.Enabled = false;
2192                 this.SourceRuleMenuItem.Enabled = false;
2193                 this.ReadedStripMenuItem.Enabled = false;
2194                 this.UnreadStripMenuItem.Enabled = false;
2195                 this.AuthorContextMenuItem.Visible = false;
2196                 this.RetweetedByContextMenuItem.Visible = false;
2197             }
2198             else
2199             {
2200                 this.ReplyStripMenuItem.Enabled = true;
2201                 this.ReplyAllStripMenuItem.Enabled = true;
2202                 this.DMStripMenuItem.Enabled = true;
2203                 this.TabMenuItem.Enabled = true;
2204                 this.IDRuleMenuItem.Enabled = true;
2205                 this.SourceRuleMenuItem.Enabled = true;
2206                 this.ReadedStripMenuItem.Enabled = true;
2207                 this.UnreadStripMenuItem.Enabled = true;
2208                 this.AuthorContextMenuItem.Visible = true;
2209                 this.AuthorContextMenuItem.Text = $"@{post!.ScreenName}";
2210                 this.RetweetedByContextMenuItem.Visible = post.RetweetedByUserId != null;
2211                 this.RetweetedByContextMenuItem.Text = $"@{post.RetweetedBy}";
2212             }
2213             var tab = this.CurrentTab;
2214             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
2215             {
2216                 this.FavAddToolStripMenuItem.Enabled = false;
2217                 this.FavRemoveToolStripMenuItem.Enabled = false;
2218                 this.StatusOpenMenuItem.Enabled = false;
2219                 this.ShowRelatedStatusesMenuItem.Enabled = false;
2220
2221                 this.ReTweetStripMenuItem.Enabled = false;
2222                 this.ReTweetUnofficialStripMenuItem.Enabled = false;
2223                 this.QuoteStripMenuItem.Enabled = false;
2224                 this.FavoriteRetweetContextMenu.Enabled = false;
2225                 this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2226             }
2227             else
2228             {
2229                 this.FavAddToolStripMenuItem.Enabled = true;
2230                 this.FavRemoveToolStripMenuItem.Enabled = true;
2231                 this.StatusOpenMenuItem.Enabled = true;
2232                 this.ShowRelatedStatusesMenuItem.Enabled = true;  // PublicSearchの時問題出るかも
2233
2234                 if (!post.CanRetweetBy(this.tw.UserId))
2235                 {
2236                     this.ReTweetStripMenuItem.Enabled = false;
2237                     this.ReTweetUnofficialStripMenuItem.Enabled = false;
2238                     this.QuoteStripMenuItem.Enabled = false;
2239                     this.FavoriteRetweetContextMenu.Enabled = false;
2240                     this.FavoriteRetweetUnofficialContextMenu.Enabled = false;
2241                 }
2242                 else
2243                 {
2244                     this.ReTweetStripMenuItem.Enabled = true;
2245                     this.ReTweetUnofficialStripMenuItem.Enabled = true;
2246                     this.QuoteStripMenuItem.Enabled = true;
2247                     this.FavoriteRetweetContextMenu.Enabled = true;
2248                     this.FavoriteRetweetUnofficialContextMenu.Enabled = true;
2249                 }
2250             }
2251
2252             if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
2253             {
2254                 this.RepliedStatusOpenMenuItem.Enabled = false;
2255             }
2256             else
2257             {
2258                 this.RepliedStatusOpenMenuItem.Enabled = true;
2259             }
2260
2261             if (this.ExistCurrentPost && post != null)
2262             {
2263                 this.DeleteStripMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
2264                 if (post.RetweetedByUserId == this.tw.UserId)
2265                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
2266                 else
2267                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
2268             }
2269         }
2270
2271         private void ReplyStripMenuItem_Click(object sender, EventArgs e)
2272             => this.MakeReplyText();
2273
2274         private void DMStripMenuItem_Click(object sender, EventArgs e)
2275             => this.MakeDirectMessageText();
2276
2277         private async Task DoStatusDelete()
2278         {
2279             var posts = this.CurrentTab.SelectedPosts;
2280             if (posts.Length == 0)
2281                 return;
2282
2283             // 選択されたツイートの中に削除可能なものが一つでもあるか
2284             if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
2285                 return;
2286
2287             var ret = MessageBox.Show(
2288                 this,
2289                 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
2290                 Properties.Resources.DeleteStripMenuItem_ClickText2,
2291                 MessageBoxButtons.OKCancel,
2292                 MessageBoxIcon.Question);
2293
2294             if (ret != DialogResult.OK)
2295                 return;
2296
2297             var currentListView = this.CurrentListView;
2298             var focusedIndex = currentListView.FocusedItem?.Index ?? currentListView.TopItem?.Index ?? 0;
2299
2300             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
2301             {
2302                 Exception? lastException = null;
2303                 foreach (var post in posts)
2304                 {
2305                     if (!post.CanDeleteBy(this.tw.UserId))
2306                         continue;
2307
2308                     try
2309                     {
2310                         if (post.StatusId is TwitterDirectMessageId dmId)
2311                         {
2312                             await this.tw.Api.DirectMessagesEventsDestroy(dmId);
2313                         }
2314                         else
2315                         {
2316                             if (post.RetweetedByUserId == this.tw.UserId)
2317                             {
2318                                 // 自分が RT したツイート (自分が RT した自分のツイートも含む)
2319                                 //   => RT を取り消し
2320                                 await this.tw.DeleteRetweet(post);
2321                             }
2322                             else
2323                             {
2324                                 if (post.UserId == this.tw.UserId)
2325                                 {
2326                                     if (post.RetweetedId != null)
2327                                     {
2328                                         // 他人に RT された自分のツイート
2329                                         //   => RT 元の自分のツイートを削除
2330                                         await this.tw.DeleteTweet(post.RetweetedId.ToTwitterStatusId());
2331                                     }
2332                                     else
2333                                     {
2334                                         // 自分のツイート
2335                                         //   => ツイートを削除
2336                                         await this.tw.DeleteTweet(post.StatusId.ToTwitterStatusId());
2337                                     }
2338                                 }
2339                             }
2340                         }
2341                     }
2342                     catch (WebApiException ex)
2343                     {
2344                         lastException = ex;
2345                         continue;
2346                     }
2347
2348                     this.statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
2349                 }
2350
2351                 if (lastException == null)
2352                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
2353                 else
2354                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
2355
2356                 using (ControlTransaction.Update(currentListView))
2357                 {
2358                     this.listCache?.PurgeCache();
2359                     this.listCache?.UpdateListSize();
2360
2361                     currentListView.SelectedIndices.Clear();
2362
2363                     var currentTab = this.CurrentTab;
2364                     if (currentTab.AllCount != 0)
2365                     {
2366                         int selectedIndex;
2367                         if (currentTab.AllCount - 1 > focusedIndex && focusedIndex > -1)
2368                             selectedIndex = focusedIndex;
2369                         else
2370                             selectedIndex = currentTab.AllCount - 1;
2371
2372                         currentListView.SelectedIndices.Add(selectedIndex);
2373                         currentListView.EnsureVisible(selectedIndex);
2374                         currentListView.FocusedItem = currentListView.Items[selectedIndex];
2375                     }
2376                 }
2377
2378                 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2379                 {
2380                     var tabPage = this.ListTab.TabPages[index];
2381                     if (this.settings.Common.TabIconDisp && tab.UnreadCount == 0)
2382                     {
2383                         if (tabPage.ImageIndex == 0)
2384                             tabPage.ImageIndex = -1; // タブアイコン
2385                     }
2386                 }
2387
2388                 if (!this.settings.Common.TabIconDisp)
2389                     this.ListTab.Refresh();
2390             }
2391         }
2392
2393         private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
2394             => await this.DoStatusDelete();
2395
2396         private void ReadedStripMenuItem_Click(object sender, EventArgs e)
2397         {
2398             using (ControlTransaction.Update(this.CurrentListView))
2399             {
2400                 var tab = this.CurrentTab;
2401                 foreach (var statusId in tab.SelectedStatusIds)
2402                 {
2403                     this.statuses.SetReadAllTab(statusId, read: true);
2404                     var idx = tab.IndexOf(statusId);
2405                     this.listCache?.RefreshStyle(idx);
2406                 }
2407             }
2408             if (this.settings.Common.TabIconDisp)
2409             {
2410                 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2411                 {
2412                     if (tab.UnreadCount == 0)
2413                     {
2414                         var tabPage = this.ListTab.TabPages[index];
2415                         if (tabPage.ImageIndex == 0)
2416                             tabPage.ImageIndex = -1; // タブアイコン
2417                     }
2418                 }
2419             }
2420             if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2421         }
2422
2423         private void UnreadStripMenuItem_Click(object sender, EventArgs e)
2424         {
2425             using (ControlTransaction.Update(this.CurrentListView))
2426             {
2427                 var tab = this.CurrentTab;
2428                 foreach (var statusId in tab.SelectedStatusIds)
2429                 {
2430                     this.statuses.SetReadAllTab(statusId, read: false);
2431                     var idx = tab.IndexOf(statusId);
2432                     this.listCache?.RefreshStyle(idx);
2433                 }
2434             }
2435             if (this.settings.Common.TabIconDisp)
2436             {
2437                 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2438                 {
2439                     if (tab.UnreadCount > 0)
2440                     {
2441                         var tabPage = this.ListTab.TabPages[index];
2442                         if (tabPage.ImageIndex == -1)
2443                             tabPage.ImageIndex = 0; // タブアイコン
2444                     }
2445                 }
2446             }
2447             if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
2448         }
2449
2450         private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
2451             => await this.DoRefresh();
2452
2453         private async Task DoRefresh()
2454             => await this.RefreshTabAsync(this.CurrentTab);
2455
2456         private async Task DoRefreshMore()
2457             => await this.RefreshTabAsync(this.CurrentTab, backward: true);
2458
2459         private DialogResult ShowSettingDialog()
2460         {
2461             using var settingDialog = new AppendSettingDialog();
2462             settingDialog.Icon = this.iconAssets.IconMain;
2463             settingDialog.IntervalChanged += this.TimerInterval_Changed;
2464
2465             settingDialog.LoadConfig(this.settings.Common, this.settings.Local);
2466
2467             DialogResult result;
2468             try
2469             {
2470                 result = settingDialog.ShowDialog(this);
2471             }
2472             catch (Exception)
2473             {
2474                 return DialogResult.Abort;
2475             }
2476
2477             if (result == DialogResult.OK)
2478             {
2479                 lock (this.syncObject)
2480                 {
2481                     settingDialog.SaveConfig(this.settings.Common, this.settings.Local);
2482                 }
2483             }
2484
2485             return result;
2486         }
2487
2488         private async void SettingStripMenuItem_Click(object sender, EventArgs e)
2489         {
2490             // 設定画面表示前のユーザー情報
2491             var previousUserId = this.settings.Common.UserId;
2492             var oldIconCol = this.Use2ColumnsMode;
2493
2494             if (this.ShowSettingDialog() == DialogResult.OK)
2495             {
2496                 lock (this.syncObject)
2497                 {
2498                     this.settings.ApplySettings();
2499
2500                     this.accounts.LoadFromSettings(this.settings.Common);
2501                     this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
2502
2503                     try
2504                     {
2505                         if (this.settings.Common.TabIconDisp)
2506                         {
2507                             this.ListTab.DrawItem -= this.ListTab_DrawItem;
2508                             this.ListTab.DrawMode = TabDrawMode.Normal;
2509                             this.ListTab.ImageList = this.TabImage;
2510                         }
2511                         else
2512                         {
2513                             this.ListTab.DrawItem -= this.ListTab_DrawItem;
2514                             this.ListTab.DrawItem += this.ListTab_DrawItem;
2515                             this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
2516                             this.ListTab.ImageList = null;
2517                         }
2518                     }
2519                     catch (Exception ex)
2520                     {
2521                         ex.Data["Instance"] = "ListTab(TabIconDisp)";
2522                         ex.Data["IsTerminatePermission"] = false;
2523                         throw;
2524                     }
2525
2526                     try
2527                     {
2528                         if (!this.settings.Common.UnreadManage)
2529                         {
2530                             this.ReadedStripMenuItem.Enabled = false;
2531                             this.UnreadStripMenuItem.Enabled = false;
2532                             if (this.settings.Common.TabIconDisp)
2533                             {
2534                                 foreach (TabPage myTab in this.ListTab.TabPages)
2535                                 {
2536                                     myTab.ImageIndex = -1;
2537                                 }
2538                             }
2539                         }
2540                         else
2541                         {
2542                             this.ReadedStripMenuItem.Enabled = true;
2543                             this.UnreadStripMenuItem.Enabled = true;
2544                         }
2545                     }
2546                     catch (Exception ex)
2547                     {
2548                         ex.Data["Instance"] = "ListTab(UnreadManage)";
2549                         ex.Data["IsTerminatePermission"] = false;
2550                         throw;
2551                     }
2552
2553                     // タブの表示位置の決定
2554                     this.SetTabAlignment();
2555
2556                     this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
2557
2558                     var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
2559                     imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
2560                     imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
2561
2562                     this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
2563                     this.NotifyFileMenuItem.Checked = this.settings.Common.NewAllPop;
2564                     this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
2565                     this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
2566
2567                     var newTheme = new ThemeManager(this.settings.Local);
2568                     (var oldTheme, this.themeManager) = (this.themeManager, newTheme);
2569                     this.tweetDetailsView.Theme = this.themeManager;
2570                     if (this.listDrawer != null)
2571                         this.listDrawer.Theme = this.themeManager;
2572                     oldTheme.Dispose();
2573
2574                     try
2575                     {
2576                         if (this.StatusText.Focused)
2577                             this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
2578
2579                         this.StatusText.Font = this.themeManager.FontInputFont;
2580                         this.StatusText.ForeColor = this.themeManager.ColorInputFont;
2581                     }
2582                     catch (Exception ex)
2583                     {
2584                         MessageBox.Show(ex.Message);
2585                     }
2586
2587                     try
2588                     {
2589                         this.detailsHtmlBuilder.Prepare(this.settings.Common, this.themeManager);
2590                     }
2591                     catch (Exception ex)
2592                     {
2593                         ex.Data["Instance"] = "Font";
2594                         ex.Data["IsTerminatePermission"] = false;
2595                         throw;
2596                     }
2597
2598                     try
2599                     {
2600                         if (this.settings.Common.TabIconDisp)
2601                         {
2602                             foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
2603                             {
2604                                 var tabPage = this.ListTab.TabPages[index];
2605                                 if (tab.UnreadCount == 0)
2606                                     tabPage.ImageIndex = -1;
2607                                 else
2608                                     tabPage.ImageIndex = 0;
2609                             }
2610                         }
2611                     }
2612                     catch (Exception ex)
2613                     {
2614                         ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
2615                         ex.Data["IsTerminatePermission"] = false;
2616                         throw;
2617                     }
2618
2619                     try
2620                     {
2621                         this.ApplyListViewIconSize(this.settings.Common.IconSize);
2622
2623                         foreach (TabPage tp in this.ListTab.TabPages)
2624                         {
2625                             var lst = (DetailsListView)tp.Tag;
2626
2627                             using (ControlTransaction.Update(lst))
2628                             {
2629                                 lst.GridLines = this.settings.Common.ShowGrid;
2630
2631                                 if (this.Use2ColumnsMode != oldIconCol)
2632                                     this.ResetColumns(lst);
2633                             }
2634                         }
2635                     }
2636                     catch (Exception ex)
2637                     {
2638                         ex.Data["Instance"] = "ListView(IconSize)";
2639                         ex.Data["IsTerminatePermission"] = false;
2640                         throw;
2641                     }
2642
2643                     this.SetMainWindowTitle();
2644                     this.SetNotifyIconText();
2645
2646                     this.listCache?.PurgeCache();
2647                     this.CurrentListView.Refresh();
2648                     this.ListTab.Refresh();
2649
2650                     this.hookGlobalHotkey.UnregisterAllOriginalHotkey();
2651                     if (this.settings.Common.HotkeyEnabled)
2652                     {
2653                         // グローバルホットキーの登録。設定で変更可能にするかも
2654                         var modKey = HookGlobalHotkey.ModKeys.None;
2655                         if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
2656                             modKey |= HookGlobalHotkey.ModKeys.Alt;
2657                         if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
2658                             modKey |= HookGlobalHotkey.ModKeys.Ctrl;
2659                         if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
2660                             modKey |= HookGlobalHotkey.ModKeys.Shift;
2661                         if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
2662                             modKey |= HookGlobalHotkey.ModKeys.Win;
2663
2664                         this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
2665                     }
2666
2667                     if (this.settings.Common.IsUseNotifyGrowl) this.gh.RegisterGrowl();
2668                     try
2669                     {
2670                         this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
2671                     }
2672                     catch (Exception)
2673                     {
2674                     }
2675                 }
2676             }
2677
2678             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2679
2680             this.TopMost = this.settings.Common.AlwaysTop;
2681             this.SaveConfigsAll(false);
2682
2683             if (this.tw.UserId != previousUserId)
2684                 await this.DoGetFollowersMenu();
2685         }
2686
2687         /// <summary>
2688         /// タブの表示位置を設定する
2689         /// </summary>
2690         private void SetTabAlignment()
2691         {
2692             var newAlignment = this.settings.Common.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
2693             if (this.ListTab.Alignment == newAlignment) return;
2694
2695             // リスト上の選択位置などを退避
2696             var currentListViewState = this.listViewState[this.CurrentTabName];
2697             currentListViewState.Save(this.ListLockMenuItem.Checked);
2698
2699             this.ListTab.Alignment = newAlignment;
2700
2701             currentListViewState.Restore(forceScroll: true);
2702         }
2703
2704         private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
2705         {
2706             // アイコンサイズの再設定
2707             if (this.listDrawer != null)
2708             {
2709                 this.listDrawer.IconSize = iconSz;
2710                 this.listDrawer.UpdateItemHeight();
2711             }
2712
2713             this.listCache?.PurgeCache();
2714         }
2715
2716         private void ResetColumns(DetailsListView list)
2717         {
2718             using (ControlTransaction.Update(list))
2719             using (ControlTransaction.Layout(list, false))
2720             {
2721                 // カラムヘッダの再設定
2722                 list.ColumnClick -= this.MyList_ColumnClick;
2723                 list.DrawColumnHeader -= this.MyList_DrawColumnHeader;
2724                 list.ColumnReordered -= this.MyList_ColumnReordered;
2725                 list.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
2726
2727                 var cols = list.Columns.Cast<ColumnHeader>().ToList();
2728                 list.Columns.Clear();
2729                 cols.ForEach(col => col.Dispose());
2730                 cols.Clear();
2731
2732                 this.InitColumns(list, true);
2733
2734                 list.ColumnClick += this.MyList_ColumnClick;
2735                 list.DrawColumnHeader += this.MyList_DrawColumnHeader;
2736                 list.ColumnReordered += this.MyList_ColumnReordered;
2737                 list.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
2738             }
2739         }
2740
2741         public void AddNewTabForSearch(string searchWord)
2742         {
2743             // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2744             foreach (var tb in this.statuses.GetTabsByType<PublicSearchTabModel>())
2745             {
2746                 if (tb.SearchWords == searchWord && MyCommon.IsNullOrEmpty(tb.SearchLang))
2747                 {
2748                     var tabIndex = this.statuses.Tabs.IndexOf(tb);
2749                     this.ListTab.SelectedIndex = tabIndex;
2750                     return;
2751                 }
2752             }
2753             // ユニークなタブ名生成
2754             var tabName = searchWord;
2755             for (var i = 0; i <= 100; i++)
2756             {
2757                 if (this.statuses.ContainsTab(tabName))
2758                     tabName += "_";
2759                 else
2760                     break;
2761             }
2762             // タブ追加
2763             var tab = new PublicSearchTabModel(tabName);
2764             this.statuses.AddTab(tab);
2765             this.AddNewTab(tab, startup: false);
2766             // 追加したタブをアクティブに
2767             this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2768             // 検索条件の設定
2769             var tabPage = this.CurrentTabPage;
2770             var cmb = (ComboBox)tabPage.Controls["panelSearch"].Controls["comboSearch"];
2771             cmb.Items.Add(searchWord);
2772             cmb.Text = searchWord;
2773             this.SaveConfigsTabs();
2774             // 検索実行
2775             this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
2776         }
2777
2778         private async Task ShowUserTimeline()
2779         {
2780             var post = this.CurrentPost;
2781             if (post == null || !this.ExistCurrentPost) return;
2782             await this.AddNewTabForUserTimeline(post.ScreenName);
2783         }
2784
2785         private async Task ShowRetweeterTimeline()
2786         {
2787             var retweetedBy = this.CurrentPost?.RetweetedBy;
2788             if (retweetedBy == null || !this.ExistCurrentPost) return;
2789             await this.AddNewTabForUserTimeline(retweetedBy);
2790         }
2791
2792         private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
2793         {
2794             if (e.KeyCode == Keys.Escape)
2795             {
2796                 this.RemoveSpecifiedTab(this.CurrentTabName, false);
2797                 this.SaveConfigsTabs();
2798                 e.SuppressKeyPress = true;
2799             }
2800         }
2801
2802         public async Task AddNewTabForUserTimeline(string user)
2803         {
2804             // 同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
2805             foreach (var tb in this.statuses.GetTabsByType<UserTimelineTabModel>())
2806             {
2807                 if (tb.ScreenName == user)
2808                 {
2809                     var tabIndex = this.statuses.Tabs.IndexOf(tb);
2810                     this.ListTab.SelectedIndex = tabIndex;
2811                     return;
2812                 }
2813             }
2814             // ユニークなタブ名生成
2815             var tabName = "user:" + user;
2816             while (this.statuses.ContainsTab(tabName))
2817             {
2818                 tabName += "_";
2819             }
2820             // タブ追加
2821             var tab = new UserTimelineTabModel(tabName, user);
2822             this.statuses.AddTab(tab);
2823             this.AddNewTab(tab, startup: false);
2824             // 追加したタブをアクティブに
2825             this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1;
2826             this.SaveConfigsTabs();
2827             // 検索実行
2828             await this.RefreshTabAsync(tab);
2829         }
2830
2831         public bool AddNewTab(TabModel tab, bool startup)
2832         {
2833             // 重複チェック
2834             if (this.ListTab.TabPages.Cast<TabPage>().Any(x => x.Text == tab.TabName))
2835                 return false;
2836
2837             // 新規タブ名チェック
2838             if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
2839
2840             var tabPage = new TabPage();
2841             var listCustom = new DetailsListView();
2842
2843             var cnt = this.statuses.Tabs.Count;
2844
2845             // ToDo:Create and set controls follow tabtypes
2846
2847             using (ControlTransaction.Update(listCustom))
2848             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
2849             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
2850             using (ControlTransaction.Layout(this.SplitContainer1, false))
2851             using (ControlTransaction.Layout(this.ListTab, false))
2852             using (ControlTransaction.Layout(this))
2853             using (ControlTransaction.Layout(tabPage, false))
2854             {
2855                 tabPage.Controls.Add(listCustom);
2856
2857                 // UserTimeline関連
2858                 var userTab = tab as UserTimelineTabModel;
2859                 var listTab = tab as ListTimelineTabModel;
2860                 var searchTab = tab as PublicSearchTabModel;
2861
2862                 if (userTab != null || listTab != null)
2863                 {
2864                     var label = new Label
2865                     {
2866                         Dock = DockStyle.Top,
2867                         Name = "labelUser",
2868                         TabIndex = 0,
2869                     };
2870
2871                     if (listTab != null)
2872                     {
2873                         label.Text = listTab.ListInfo.ToString();
2874                     }
2875                     else if (userTab != null)
2876                     {
2877                         label.Text = userTab.ScreenName + "'s Timeline";
2878                     }
2879                     label.TextAlign = ContentAlignment.MiddleLeft;
2880                     using (var tmpComboBox = new ComboBox())
2881                     {
2882                         label.Height = tmpComboBox.Height;
2883                     }
2884                     tabPage.Controls.Add(label);
2885                 }
2886                 // 検索関連の準備
2887                 else if (searchTab != null)
2888                 {
2889                     var pnl = new Panel();
2890
2891                     var lbl = new Label();
2892                     var cmb = new ComboBox();
2893                     var btn = new Button();
2894                     var cmbLang = new ComboBox();
2895
2896                     using (ControlTransaction.Layout(pnl, false))
2897                     {
2898                         pnl.Controls.Add(cmb);
2899                         pnl.Controls.Add(cmbLang);
2900                         pnl.Controls.Add(btn);
2901                         pnl.Controls.Add(lbl);
2902                         pnl.Name = "panelSearch";
2903                         pnl.TabIndex = 0;
2904                         pnl.Dock = DockStyle.Top;
2905                         pnl.Height = cmb.Height;
2906                         pnl.Enter += this.SearchControls_Enter;
2907                         pnl.Leave += this.SearchControls_Leave;
2908
2909                         cmb.Text = "";
2910                         cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2911                         cmb.Dock = DockStyle.Fill;
2912                         cmb.Name = "comboSearch";
2913                         cmb.DropDownStyle = ComboBoxStyle.DropDown;
2914                         cmb.ImeMode = ImeMode.NoControl;
2915                         cmb.TabStop = false;
2916                         cmb.TabIndex = 1;
2917                         cmb.AutoCompleteMode = AutoCompleteMode.None;
2918                         cmb.KeyDown += this.SearchComboBox_KeyDown;
2919
2920                         cmbLang.Text = "";
2921                         cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
2922                         cmbLang.Dock = DockStyle.Right;
2923                         cmbLang.Width = 50;
2924                         cmbLang.Name = "comboLang";
2925                         cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
2926                         cmbLang.TabStop = false;
2927                         cmbLang.TabIndex = 2;
2928                         cmbLang.Items.Add("");
2929                         cmbLang.Items.Add("ja");
2930                         cmbLang.Items.Add("en");
2931                         cmbLang.Items.Add("ar");
2932                         cmbLang.Items.Add("da");
2933                         cmbLang.Items.Add("nl");
2934                         cmbLang.Items.Add("fa");
2935                         cmbLang.Items.Add("fi");
2936                         cmbLang.Items.Add("fr");
2937                         cmbLang.Items.Add("de");
2938                         cmbLang.Items.Add("hu");
2939                         cmbLang.Items.Add("is");
2940                         cmbLang.Items.Add("it");
2941                         cmbLang.Items.Add("no");
2942                         cmbLang.Items.Add("pl");
2943                         cmbLang.Items.Add("pt");
2944                         cmbLang.Items.Add("ru");
2945                         cmbLang.Items.Add("es");
2946                         cmbLang.Items.Add("sv");
2947                         cmbLang.Items.Add("th");
2948
2949                         lbl.Text = "Search(C-S-f)";
2950                         lbl.Name = "label1";
2951                         lbl.Dock = DockStyle.Left;
2952                         lbl.Width = 90;
2953                         lbl.Height = cmb.Height;
2954                         lbl.TextAlign = ContentAlignment.MiddleLeft;
2955                         lbl.TabIndex = 0;
2956
2957                         btn.Text = "Search";
2958                         btn.Name = "buttonSearch";
2959                         btn.UseVisualStyleBackColor = true;
2960                         btn.Dock = DockStyle.Right;
2961                         btn.TabStop = false;
2962                         btn.TabIndex = 3;
2963                         btn.Click += this.SearchButton_Click;
2964
2965                         if (!MyCommon.IsNullOrEmpty(searchTab.SearchWords))
2966                         {
2967                             cmb.Items.Add(searchTab.SearchWords);
2968                             cmb.Text = searchTab.SearchWords;
2969                         }
2970
2971                         cmbLang.Text = searchTab.SearchLang;
2972
2973                         tabPage.Controls.Add(pnl);
2974                     }
2975                 }
2976
2977                 tabPage.Tag = listCustom;
2978                 this.ListTab.Controls.Add(tabPage);
2979
2980                 tabPage.Location = new Point(4, 4);
2981                 tabPage.Name = "CTab" + cnt;
2982                 tabPage.Size = new Size(380, 260);
2983                 tabPage.TabIndex = 2 + cnt;
2984                 tabPage.Text = tab.TabName;
2985                 tabPage.UseVisualStyleBackColor = true;
2986                 tabPage.AccessibleRole = AccessibleRole.PageTab;
2987
2988                 listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
2989                 listCustom.TabIndex = 1;
2990                 listCustom.AllowColumnReorder = true;
2991                 listCustom.ContextMenuStrip = this.ContextMenuOperate;
2992                 listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
2993                 listCustom.Dock = DockStyle.Fill;
2994                 listCustom.FullRowSelect = true;
2995                 listCustom.HideSelection = false;
2996                 listCustom.Location = new Point(0, 0);
2997                 listCustom.Margin = new Padding(0);
2998                 listCustom.Name = "CList" + Environment.TickCount;
2999                 listCustom.ShowItemToolTips = true;
3000                 listCustom.Size = new Size(380, 260);
3001                 listCustom.UseCompatibleStateImageBehavior = false;
3002                 listCustom.View = View.Details;
3003                 listCustom.OwnerDraw = true;
3004                 listCustom.VirtualMode = true;
3005
3006                 listCustom.GridLines = this.settings.Common.ShowGrid;
3007                 listCustom.AllowDrop = true;
3008
3009                 this.InitColumns(listCustom, startup);
3010
3011                 listCustom.SelectedIndexChanged += this.MyList_SelectedIndexChanged;
3012                 listCustom.MouseDoubleClick += this.MyList_MouseDoubleClick;
3013                 listCustom.ColumnClick += this.MyList_ColumnClick;
3014                 listCustom.DrawColumnHeader += this.MyList_DrawColumnHeader;
3015                 listCustom.DragDrop += this.TweenMain_DragDrop;
3016                 listCustom.DragEnter += this.TweenMain_DragEnter;
3017                 listCustom.DragOver += this.TweenMain_DragOver;
3018                 listCustom.MouseClick += this.MyList_MouseClick;
3019                 listCustom.ColumnReordered += this.MyList_ColumnReordered;
3020                 listCustom.ColumnWidthChanged += this.MyList_ColumnWidthChanged;
3021                 listCustom.HScrolled += this.MyList_HScrolled;
3022             }
3023
3024             var state = new TimelineListViewState(listCustom, tab);
3025             this.listViewState[tab.TabName] = state;
3026
3027             return true;
3028         }
3029
3030         public bool RemoveSpecifiedTab(string tabName, bool confirm)
3031         {
3032             var tabInfo = this.statuses.GetTabByName(tabName);
3033             if (tabInfo == null || tabInfo.IsDefaultTabType || tabInfo.Protected)
3034                 return false;
3035
3036             if (confirm)
3037             {
3038                 var tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
3039                 var result = MessageBox.Show(
3040                     tmp,
3041                     tabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
3042                     MessageBoxButtons.OKCancel,
3043                     MessageBoxIcon.Question,
3044                     MessageBoxDefaultButton.Button2);
3045                 if (result == DialogResult.Cancel)
3046                 {
3047                     return false;
3048                 }
3049             }
3050
3051             var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3052             if (tabIndex == -1)
3053                 return false;
3054
3055             var tabPage = this.ListTab.TabPages[tabIndex];
3056
3057             this.SetListProperty();   // 他のタブに列幅等を反映
3058
3059             this.listViewState.Remove(tabName);
3060
3061             // オブジェクトインスタンスの削除
3062             var listCustom = (DetailsListView)tabPage.Tag;
3063             tabPage.Tag = null;
3064
3065             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
3066             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
3067             using (ControlTransaction.Layout(this.SplitContainer1, false))
3068             using (ControlTransaction.Layout(this.ListTab, false))
3069             using (ControlTransaction.Layout(this))
3070             using (ControlTransaction.Layout(tabPage, false))
3071             {
3072                 if (this.CurrentTabName == tabName)
3073                 {
3074                     this.ListTab.SelectTab((this.beforeSelectedTab != null && this.ListTab.TabPages.Contains(this.beforeSelectedTab)) ? this.beforeSelectedTab : this.ListTab.TabPages[0]);
3075                     this.beforeSelectedTab = null;
3076                 }
3077                 this.ListTab.Controls.Remove(tabPage);
3078
3079                 // 後付けのコントロールを破棄
3080                 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
3081                 {
3082                     using var label = tabPage.Controls["labelUser"];
3083                     tabPage.Controls.Remove(label);
3084                 }
3085                 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
3086                 {
3087                     using var pnl = tabPage.Controls["panelSearch"];
3088
3089                     pnl.Enter -= this.SearchControls_Enter;
3090                     pnl.Leave -= this.SearchControls_Leave;
3091                     tabPage.Controls.Remove(pnl);
3092
3093                     foreach (Control ctrl in pnl.Controls)
3094                     {
3095                         if (ctrl.Name == "buttonSearch")
3096                         {
3097                             ctrl.Click -= this.SearchButton_Click;
3098                         }
3099                         else if (ctrl.Name == "comboSearch")
3100                         {
3101                             ctrl.KeyDown -= this.SearchComboBox_KeyDown;
3102                         }
3103                         pnl.Controls.Remove(ctrl);
3104                         ctrl.Dispose();
3105                     }
3106                 }
3107
3108                 tabPage.Controls.Remove(listCustom);
3109
3110                 listCustom.SelectedIndexChanged -= this.MyList_SelectedIndexChanged;
3111                 listCustom.MouseDoubleClick -= this.MyList_MouseDoubleClick;
3112                 listCustom.ColumnClick -= this.MyList_ColumnClick;
3113                 listCustom.DrawColumnHeader -= this.MyList_DrawColumnHeader;
3114                 listCustom.DragDrop -= this.TweenMain_DragDrop;
3115                 listCustom.DragEnter -= this.TweenMain_DragEnter;
3116                 listCustom.DragOver -= this.TweenMain_DragOver;
3117                 listCustom.MouseClick -= this.MyList_MouseClick;
3118                 listCustom.ColumnReordered -= this.MyList_ColumnReordered;
3119                 listCustom.ColumnWidthChanged -= this.MyList_ColumnWidthChanged;
3120                 listCustom.HScrolled -= this.MyList_HScrolled;
3121
3122                 var cols = listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
3123                 listCustom.Columns.Clear();
3124                 cols.ForEach(col => col.Dispose());
3125                 cols.Clear();
3126
3127                 listCustom.ContextMenuStrip = null;
3128                 listCustom.ColumnHeaderContextMenuStrip = null;
3129                 listCustom.Font = null;
3130
3131                 listCustom.SmallImageList = null;
3132                 listCustom.ListViewItemSorter = null;
3133
3134                 // キャッシュのクリア
3135                 this.listCache?.PurgeCache();
3136             }
3137
3138             tabPage.Dispose();
3139             listCustom.Dispose();
3140             this.statuses.RemoveTab(tabName);
3141
3142             return true;
3143         }
3144
3145         private void ListTab_Deselected(object sender, TabControlEventArgs e)
3146         {
3147             this.listCache?.PurgeCache();
3148             this.beforeSelectedTab = e.TabPage;
3149         }
3150
3151         private void ListTab_MouseMove(object sender, MouseEventArgs e)
3152         {
3153             // タブのD&D
3154
3155             if (!this.settings.Common.TabMouseLock && e.Button == MouseButtons.Left && this.tabDrag)
3156             {
3157                 var tn = "";
3158                 var dragEnableRectangle = new Rectangle(this.tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2), this.tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
3159                 if (!dragEnableRectangle.Contains(e.Location))
3160                 {
3161                     // タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
3162                     tn = this.CurrentTabName;
3163                 }
3164
3165                 if (MyCommon.IsNullOrEmpty(tn)) return;
3166
3167                 var tabIndex = this.statuses.Tabs.IndexOf(tn);
3168                 if (tabIndex != -1)
3169                 {
3170                     var tabPage = this.ListTab.TabPages[tabIndex];
3171                     this.ListTab.DoDragDrop(tabPage, DragDropEffects.All);
3172                 }
3173             }
3174             else
3175             {
3176                 this.tabDrag = false;
3177             }
3178
3179             var cpos = new Point(e.X, e.Y);
3180             foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3181             {
3182                 var rect = this.ListTab.GetTabRect(index);
3183                 if (rect.Contains(cpos))
3184                 {
3185                     this.rclickTabName = tab.TabName;
3186                     break;
3187                 }
3188             }
3189         }
3190
3191         private void ListTab_SelectedIndexChanged(object sender, EventArgs e)
3192         {
3193             this.SetMainWindowTitle();
3194             this.SetStatusLabelUrl();
3195             this.SetApiStatusLabel();
3196             if (this.ListTab.Focused || ((Control)this.CurrentTabPage.Tag).Focused)
3197                 this.Tag = this.ListTab.Tag;
3198             this.TabMenuControl(this.CurrentTabName);
3199             this.PushSelectPostChain();
3200             this.DispSelectedPost();
3201         }
3202
3203         private void SetListProperty()
3204         {
3205             if (!this.isColumnChanged) return;
3206
3207             var currentListView = this.CurrentListView;
3208
3209             var dispOrder = new int[currentListView.Columns.Count];
3210             for (var i = 0; i < currentListView.Columns.Count; i++)
3211             {
3212                 for (var j = 0; j < currentListView.Columns.Count; j++)
3213                 {
3214                     if (currentListView.Columns[j].DisplayIndex == i)
3215                     {
3216                         dispOrder[i] = j;
3217                         break;
3218                     }
3219                 }
3220             }
3221
3222             // 列幅、列並びを他のタブに設定
3223             foreach (TabPage tb in this.ListTab.TabPages)
3224             {
3225                 if (tb.Text == this.CurrentTabName)
3226                     continue;
3227
3228                 if (tb.Tag != null && tb.Controls.Count > 0)
3229                 {
3230                     var lst = (DetailsListView)tb.Tag;
3231                     for (var i = 0; i < lst.Columns.Count; i++)
3232                     {
3233                         lst.Columns[dispOrder[i]].DisplayIndex = i;
3234                         lst.Columns[i].Width = currentListView.Columns[i].Width;
3235                     }
3236                 }
3237             }
3238
3239             this.isColumnChanged = false;
3240         }
3241
3242         private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
3243         {
3244             if (e.KeyChar == '@')
3245             {
3246                 if (!this.settings.Common.UseAtIdSupplement) return;
3247                 // @マーク
3248                 var cnt = this.AtIdSupl.ItemCount;
3249                 this.ShowSuplDialog(this.StatusText, this.AtIdSupl);
3250                 if (cnt != this.AtIdSupl.ItemCount)
3251                     this.MarkSettingAtIdModified();
3252                 e.Handled = true;
3253             }
3254             else if (e.KeyChar == '#')
3255             {
3256                 if (!this.settings.Common.UseHashSupplement) return;
3257                 this.ShowSuplDialog(this.StatusText, this.HashSupl);
3258                 e.Handled = true;
3259             }
3260         }
3261
3262         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
3263             => this.ShowSuplDialog(owner, dialog, 0, "");
3264
3265         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
3266             => this.ShowSuplDialog(owner, dialog, offset, "");
3267
3268         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
3269         {
3270             dialog.StartsWith = startswith;
3271             if (dialog.Visible)
3272             {
3273                 dialog.Focus();
3274             }
3275             else
3276             {
3277                 dialog.ShowDialog();
3278             }
3279             this.TopMost = this.settings.Common.AlwaysTop;
3280             var selStart = owner.SelectionStart;
3281             var fHalf = "";
3282             var eHalf = "";
3283             if (dialog.DialogResult == DialogResult.OK)
3284             {
3285                 if (!MyCommon.IsNullOrEmpty(dialog.InputText))
3286                 {
3287                     if (selStart > 0)
3288                     {
3289                         fHalf = owner.Text.Substring(0, selStart - offset);
3290                     }
3291                     if (selStart < owner.Text.Length)
3292                     {
3293                         eHalf = owner.Text.Substring(selStart);
3294                     }
3295                     owner.Text = fHalf + dialog.InputText + eHalf;
3296                     owner.SelectionStart = selStart + dialog.InputText.Length;
3297                 }
3298             }
3299             else
3300             {
3301                 if (selStart > 0)
3302                 {
3303                     fHalf = owner.Text.Substring(0, selStart);
3304                 }
3305                 if (selStart < owner.Text.Length)
3306                 {
3307                     eHalf = owner.Text.Substring(selStart);
3308                 }
3309                 owner.Text = fHalf + eHalf;
3310                 if (selStart > 0)
3311                 {
3312                     owner.SelectionStart = selStart;
3313                 }
3314             }
3315             owner.Focus();
3316         }
3317
3318         private void StatusText_KeyUp(object sender, KeyEventArgs e)
3319         {
3320             // スペースキーで未読ジャンプ
3321             if (!e.Alt && !e.Control && !e.Shift)
3322             {
3323                 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
3324                 {
3325                     var isSpace = false;
3326                     foreach (var c in this.StatusText.Text)
3327                     {
3328                         if (c == ' ' || c == ' ')
3329                         {
3330                             isSpace = true;
3331                         }
3332                         else
3333                         {
3334                             isSpace = false;
3335                             break;
3336                         }
3337                     }
3338                     if (isSpace)
3339                     {
3340                         e.Handled = true;
3341                         this.StatusText.Text = "";
3342                         this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
3343                     }
3344                 }
3345             }
3346             this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
3347         }
3348
3349         private void StatusText_TextChanged(object sender, EventArgs e)
3350         {
3351             // 文字数カウント
3352             var pLen = this.GetRestStatusCount(this.FormatStatusTextExtended(this.StatusText.Text));
3353             this.lblLen.Text = pLen.ToString();
3354             if (pLen < 0)
3355             {
3356                 this.StatusText.ForeColor = Color.Red;
3357             }
3358             else
3359             {
3360                 this.StatusText.ForeColor = this.themeManager.ColorInputFont;
3361             }
3362
3363             this.StatusText.AccessibleDescription = string.Format(Properties.Resources.StatusText_AccessibleDescription, pLen);
3364
3365             if (MyCommon.IsNullOrEmpty(this.StatusText.Text))
3366             {
3367                 this.inReplyTo = null;
3368             }
3369         }
3370
3371         /// <summary>
3372         /// メンション以外の文字列が含まれていないテキストであるか判定します
3373         /// </summary>
3374         internal static bool TextContainsOnlyMentions(string text)
3375         {
3376             var mentions = TweetExtractor.ExtractMentionEntities(text).OrderBy(x => x.Indices[0]);
3377             var startIndex = 0;
3378
3379             foreach (var mention in mentions)
3380             {
3381                 var textPart = text.Substring(startIndex, mention.Indices[0] - startIndex);
3382
3383                 if (!string.IsNullOrWhiteSpace(textPart))
3384                     return false;
3385
3386                 startIndex = mention.Indices[1];
3387             }
3388
3389             var textPartLast = text.Substring(startIndex);
3390
3391             if (!string.IsNullOrWhiteSpace(textPartLast))
3392                 return false;
3393
3394             return true;
3395         }
3396
3397         /// <summary>
3398         /// 投稿時に auto_populate_reply_metadata オプションによって自動で追加されるメンションを除去します
3399         /// </summary>
3400         private string RemoveAutoPopuratedMentions(string statusText, out long[] autoPopulatedUserIds)
3401         {
3402             var autoPopulatedUserIdList = new List<long>();
3403
3404             var replyToPost = this.inReplyTo != null ? this.statuses[this.inReplyTo.Value.StatusId] : null;
3405             if (replyToPost != null)
3406             {
3407                 if (statusText.StartsWith($"@{replyToPost.ScreenName} ", StringComparison.Ordinal))
3408                 {
3409                     statusText = statusText.Substring(replyToPost.ScreenName.Length + 2);
3410                     autoPopulatedUserIdList.Add(replyToPost.UserId);
3411
3412                     foreach (var (userId, screenName) in replyToPost.ReplyToList)
3413                     {
3414                         if (statusText.StartsWith($"@{screenName} ", StringComparison.Ordinal))
3415                         {
3416                             statusText = statusText.Substring(screenName.Length + 2);
3417                             autoPopulatedUserIdList.Add(userId);
3418                         }
3419                     }
3420                 }
3421             }
3422
3423             autoPopulatedUserIds = autoPopulatedUserIdList.ToArray();
3424
3425             return statusText;
3426         }
3427
3428         /// <summary>
3429         /// attachment_url に指定可能な URL が含まれていれば除去
3430         /// </summary>
3431         private string RemoveAttachmentUrl(string statusText, out string? attachmentUrl)
3432         {
3433             attachmentUrl = null;
3434
3435             // attachment_url は media_id と同時に使用できない
3436             if (this.ImageSelector.Visible && this.ImageSelector.Model.SelectedMediaService is TwitterPhoto)
3437                 return statusText;
3438
3439             var match = Twitter.AttachmentUrlRegex.Match(statusText);
3440             if (!match.Success)
3441                 return statusText;
3442
3443             attachmentUrl = match.Value;
3444
3445             // マッチした URL を空白に置換
3446             statusText = statusText.Substring(0, match.Index);
3447
3448             // テキストと URL の間にスペースが含まれていれば除去
3449             return statusText.TrimEnd(' ');
3450         }
3451
3452         private string FormatStatusTextExtended(string statusText)
3453             => this.FormatStatusTextExtended(statusText, out _, out _);
3454
3455         /// <summary>
3456         /// <see cref="FormatStatusText"/> に加えて、拡張モードで140字にカウントされない文字列の除去を行います
3457         /// </summary>
3458         private string FormatStatusTextExtended(string statusText, out long[] autoPopulatedUserIds, out string? attachmentUrl)
3459         {
3460             statusText = this.RemoveAutoPopuratedMentions(statusText, out autoPopulatedUserIds);
3461
3462             statusText = this.RemoveAttachmentUrl(statusText, out attachmentUrl);
3463
3464             return this.FormatStatusText(statusText);
3465         }
3466
3467         internal string FormatStatusText(string statusText)
3468             => this.FormatStatusText(statusText, Control.ModifierKeys);
3469
3470         /// <summary>
3471         /// ツイート投稿前のフッター付与などの前処理を行います
3472         /// </summary>
3473         internal string FormatStatusText(string statusText, Keys modifierKeys)
3474         {
3475             statusText = statusText.Replace("\r\n", "\n");
3476
3477             if (this.SeparateUrlAndFullwidthCharacter)
3478             {
3479                 // URLと全角文字の切り離し
3480                 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
3481             }
3482
3483             if (this.settings.Common.WideSpaceConvert)
3484             {
3485                 // 文中の全角スペースを半角スペース1個にする
3486                 statusText = statusText.Replace(" ", " ");
3487             }
3488
3489             // DM の場合はこれ以降の処理を行わない
3490             if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
3491                 return statusText;
3492
3493             bool disableFooter;
3494             if (this.settings.Common.PostShiftEnter)
3495             {
3496                 disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Control);
3497             }
3498             else
3499             {
3500                 if (this.settings.Local.StatusMultiline && !this.settings.Common.PostCtrlEnter)
3501                     disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Control);
3502                 else
3503                     disableFooter = MyCommon.IsKeyDown(modifierKeys, Keys.Shift);
3504             }
3505
3506             if (statusText.Contains("RT @"))
3507                 disableFooter = true;
3508
3509             // 自分宛のリプライの場合は先頭の「@screen_name 」の部分を除去する (in_reply_to_status_id は維持される)
3510             if (this.inReplyTo != null && this.inReplyTo.Value.ScreenName == this.tw.Username)
3511             {
3512                 var mentionSelf = $"@{this.tw.Username} ";
3513                 if (statusText.StartsWith(mentionSelf, StringComparison.OrdinalIgnoreCase))
3514                 {
3515                     if (statusText.Length > mentionSelf.Length || this.GetSelectedImageService() != null)
3516                         statusText = statusText.Substring(mentionSelf.Length);
3517                 }
3518             }
3519
3520             var header = "";
3521             var footer = "";
3522
3523             var hashtag = this.HashMgr.UseHash;
3524             if (!MyCommon.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
3525             {
3526                 if (this.HashMgr.IsHead)
3527                     header = this.HashMgr.UseHash + " ";
3528                 else
3529                     footer = " " + this.HashMgr.UseHash;
3530             }
3531
3532             if (!disableFooter)
3533             {
3534                 if (this.settings.Local.UseRecommendStatus)
3535                 {
3536                     // 推奨ステータスを使用する
3537                     footer += this.recommendedStatusFooter;
3538                 }
3539                 else if (!MyCommon.IsNullOrEmpty(this.settings.Local.StatusText))
3540                 {
3541                     // テキストボックスに入力されている文字列を使用する
3542                     footer += " " + this.settings.Local.StatusText.Trim();
3543                 }
3544             }
3545
3546             statusText = header + statusText + footer;
3547
3548             if (this.preventSmsCommand)
3549             {
3550                 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
3551                 // 参照: https://support.twitter.com/articles/14020
3552
3553                 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
3554                     && !Twitter.DMSendTextRegex.IsMatch(statusText))
3555                 {
3556                     // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
3557                     statusText = '\u200b' + statusText;
3558                 }
3559             }
3560
3561             return statusText;
3562         }
3563
3564         /// <summary>
3565         /// 投稿欄に表示する入力可能な文字数を計算します
3566         /// </summary>
3567         private int GetRestStatusCount(string statusText)
3568         {
3569             var remainCount = this.tw.GetTextLengthRemain(statusText);
3570
3571             var uploadService = this.GetSelectedImageService();
3572             if (uploadService != null)
3573             {
3574                 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
3575                 remainCount -= uploadService.GetReservedTextLength(1);
3576             }
3577
3578             return remainCount;
3579         }
3580
3581         private IMediaUploadService? GetSelectedImageService()
3582             => this.ImageSelector.Visible ? this.ImageSelector.Model.SelectedMediaService : null;
3583
3584         /// <summary>
3585         /// 全てのタブの振り分けルールを反映し直します
3586         /// </summary>
3587         private void ApplyPostFilters()
3588         {
3589             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3590             {
3591                 this.statuses.FilterAll();
3592
3593                 var listView = this.CurrentListView;
3594                 using (ControlTransaction.Update(listView))
3595                 {
3596                     this.listCache?.PurgeCache();
3597                     this.listCache?.UpdateListSize();
3598                 }
3599
3600                 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
3601                 {
3602                     var tabPage = this.ListTab.TabPages[index];
3603
3604                     if (this.settings.Common.TabIconDisp)
3605                     {
3606                         if (tab.UnreadCount > 0)
3607                             tabPage.ImageIndex = 0;
3608                         else
3609                             tabPage.ImageIndex = -1;
3610                     }
3611                 }
3612
3613                 if (!this.settings.Common.TabIconDisp)
3614                     this.ListTab.Refresh();
3615
3616                 this.SetMainWindowTitle();
3617                 this.SetStatusLabelUrl();
3618             }
3619         }
3620
3621         private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
3622             => e.DrawDefault = true;
3623
3624         private void MyList_HScrolled(object sender, EventArgs e)
3625             => ((DetailsListView)sender).Refresh();
3626
3627         protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
3628         {
3629             base.ScaleControl(factor, specified);
3630
3631             ScaleChildControl(this.TabImage, factor);
3632
3633             var tabpages = this.ListTab.TabPages.Cast<TabPage>();
3634             var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
3635
3636             foreach (var listview in listviews)
3637             {
3638                 ScaleChildControl(listview, factor);
3639             }
3640         }
3641
3642         internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
3643         {
3644             var tab = this.CurrentTab;
3645
3646             if (tab.AllCount == 0)
3647             {
3648                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3649                 return;
3650             }
3651
3652             var selectedIndex = tab.SelectedIndex;
3653
3654             int startIndex;
3655             switch (searchType)
3656             {
3657                 case SEARCHTYPE.NextSearch: // 次を検索
3658                     if (selectedIndex != -1)
3659                         startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
3660                     else
3661                         startIndex = 0;
3662                     break;
3663                 case SEARCHTYPE.PrevSearch: // 前を検索
3664                     if (selectedIndex != -1)
3665                         startIndex = Math.Max(selectedIndex - 1, 0);
3666                     else
3667                         startIndex = tab.AllCount - 1;
3668                     break;
3669                 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
3670                 default:
3671                     if (selectedIndex != -1)
3672                         startIndex = selectedIndex;
3673                     else
3674                         startIndex = 0;
3675                     break;
3676             }
3677
3678             Func<string, bool> stringComparer;
3679             try
3680             {
3681                 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
3682             }
3683             catch (ArgumentException)
3684             {
3685                 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3686                 return;
3687             }
3688
3689             var reverse = searchType == SEARCHTYPE.PrevSearch;
3690             var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
3691                 .DefaultIfEmpty(-1).First();
3692
3693             if (foundIndex == -1)
3694             {
3695                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3696                 return;
3697             }
3698
3699             var listView = this.CurrentListView;
3700             this.SelectListItem(listView, foundIndex);
3701             listView.EnsureVisible(foundIndex);
3702         }
3703
3704         private void MenuItemSubSearch_Click(object sender, EventArgs e)
3705             => this.ShowSearchDialog(); // 検索メニュー
3706
3707         private void MenuItemSearchNext_Click(object sender, EventArgs e)
3708         {
3709             var previousSearch = this.SearchDialog.ResultOptions;
3710             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3711             {
3712                 this.SearchDialog.Reset();
3713                 this.ShowSearchDialog();
3714                 return;
3715             }
3716
3717             // 次を検索
3718             this.DoTabSearch(
3719                 previousSearch.Query,
3720                 previousSearch.CaseSensitive,
3721                 previousSearch.UseRegex,
3722                 SEARCHTYPE.NextSearch);
3723         }
3724
3725         private void MenuItemSearchPrev_Click(object sender, EventArgs e)
3726         {
3727             var previousSearch = this.SearchDialog.ResultOptions;
3728             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
3729             {
3730                 this.SearchDialog.Reset();
3731                 this.ShowSearchDialog();
3732                 return;
3733             }
3734
3735             // 前を検索
3736             this.DoTabSearch(
3737                 previousSearch.Query,
3738                 previousSearch.CaseSensitive,
3739                 previousSearch.UseRegex,
3740                 SEARCHTYPE.PrevSearch);
3741         }
3742
3743         /// <summary>
3744         /// 検索ダイアログを表示し、検索を実行します
3745         /// </summary>
3746         private void ShowSearchDialog()
3747         {
3748             if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
3749             {
3750                 this.TopMost = this.settings.Common.AlwaysTop;
3751                 return;
3752             }
3753             this.TopMost = this.settings.Common.AlwaysTop;
3754
3755             var searchOptions = this.SearchDialog.ResultOptions!;
3756             if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
3757             {
3758                 if (searchOptions.NewTab)
3759                 {
3760                     var tabName = Properties.Resources.SearchResults_TabName;
3761
3762                     try
3763                     {
3764                         tabName = this.statuses.MakeTabName(tabName);
3765                     }
3766                     catch (TabException ex)
3767                     {
3768                         MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
3769                     }
3770
3771                     var resultTab = new LocalSearchTabModel(tabName);
3772                     this.AddNewTab(resultTab, startup: false);
3773                     this.statuses.AddTab(resultTab);
3774
3775                     var targetTab = this.CurrentTab;
3776
3777                     Func<string, bool> stringComparer;
3778                     try
3779                     {
3780                         stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
3781                     }
3782                     catch (ArgumentException)
3783                     {
3784                         MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
3785                         return;
3786                     }
3787
3788                     var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
3789                     if (foundIndices.Length == 0)
3790                     {
3791                         MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
3792                         return;
3793                     }
3794
3795                     var foundPosts = foundIndices.Select(x => targetTab[x]);
3796                     foreach (var post in foundPosts)
3797                     {
3798                         resultTab.AddPostQueue(post);
3799                     }
3800
3801                     this.statuses.DistributePosts();
3802                     this.RefreshTimeline();
3803
3804                     var tabIndex = this.statuses.Tabs.IndexOf(tabName);
3805                     this.ListTab.SelectedIndex = tabIndex;
3806                 }
3807                 else
3808                 {
3809                     this.DoTabSearch(
3810                         searchOptions.Query,
3811                         searchOptions.CaseSensitive,
3812                         searchOptions.UseRegex,
3813                         SEARCHTYPE.DialogSearch);
3814                 }
3815             }
3816             else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
3817             {
3818                 this.AddNewTabForSearch(searchOptions.Query);
3819             }
3820         }
3821
3822         /// <summary>発言検索に使用するメソッドを生成します</summary>
3823         /// <exception cref="ArgumentException">
3824         /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
3825         /// </exception>
3826         private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
3827         {
3828             if (useRegex)
3829             {
3830                 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
3831                 var regex = new Regex(query, regexOption);
3832
3833                 return x => regex.IsMatch(x);
3834             }
3835             else
3836             {
3837                 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
3838
3839                 return x => x.IndexOf(query, comparisonType) != -1;
3840             }
3841         }
3842
3843         private void AboutMenuItem_Click(object sender, EventArgs e)
3844         {
3845             using (var about = new TweenAboutBox())
3846             {
3847                 about.ShowDialog(this);
3848             }
3849             this.TopMost = this.settings.Common.AlwaysTop;
3850         }
3851
3852         private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
3853         {
3854             var bgnIdx = this.statuses.SelectedTabIndex;
3855
3856             if (this.ImageSelector.Enabled)
3857                 return;
3858
3859             TabModel? foundTab = null;
3860             var foundIndex = 0;
3861
3862             // 現在タブから最終タブまで探索
3863             foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Skip(bgnIdx))
3864             {
3865                 var unreadIndex = tab.NextUnreadIndex;
3866                 if (unreadIndex != -1)
3867                 {
3868                     this.ListTab.SelectedIndex = index;
3869                     foundTab = tab;
3870                     foundIndex = unreadIndex;
3871                     break;
3872                 }
3873             }
3874
3875             // 未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
3876             if (foundTab == null && bgnIdx > 0)
3877             {
3878                 foreach (var (tab, index) in this.statuses.Tabs.WithIndex().Take(bgnIdx))
3879                 {
3880                     var unreadIndex = tab.NextUnreadIndex;
3881                     if (unreadIndex != -1)
3882                     {
3883                         this.ListTab.SelectedIndex = index;
3884                         foundTab = tab;
3885                         foundIndex = unreadIndex;
3886                         break;
3887                     }
3888                 }
3889             }
3890
3891             DetailsListView lst;
3892
3893             if (foundTab == null)
3894             {
3895                 // 全部調べたが未読見つからず→先頭タブの最新発言へ
3896                 this.ListTab.SelectedIndex = 0;
3897                 var tabPage = this.ListTab.TabPages[0];
3898                 var tab = this.statuses.Tabs[0];
3899
3900                 if (tab.AllCount == 0)
3901                     return;
3902
3903                 if (this.statuses.SortOrder == SortOrder.Ascending)
3904                     foundIndex = tab.AllCount - 1;
3905                 else
3906                     foundIndex = 0;
3907
3908                 lst = (DetailsListView)tabPage.Tag;
3909             }
3910             else
3911             {
3912                 var foundTabIndex = this.statuses.Tabs.IndexOf(foundTab);
3913                 lst = (DetailsListView)this.ListTab.TabPages[foundTabIndex].Tag;
3914             }
3915
3916             this.SelectListItem(lst, foundIndex);
3917
3918             if (this.statuses.SortMode == ComparerMode.Id)
3919             {
3920                 var rowHeight = lst.SmallImageList.ImageSize.Height;
3921                 if (this.statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - rowHeight - 10 ||
3922                     this.statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < rowHeight + 10)
3923                 {
3924                     this.MoveTop();
3925                 }
3926                 else
3927                 {
3928                     lst.EnsureVisible(foundIndex);
3929                 }
3930             }
3931             else
3932             {
3933                 lst.EnsureVisible(foundIndex);
3934             }
3935
3936             lst.Focus();
3937         }
3938
3939         private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
3940         {
3941             var tab = this.CurrentTab;
3942             var post = this.CurrentPost;
3943             if (post != null && tab.TabType != MyCommon.TabUsageType.DirectMessage)
3944                 await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(post));
3945         }
3946
3947         private async void VerUpMenuItem_Click(object sender, EventArgs e)
3948             => await this.CheckNewVersion(false);
3949
3950         private void RunTweenUp()
3951         {
3952             var pinfo = new ProcessStartInfo
3953             {
3954                 UseShellExecute = true,
3955                 WorkingDirectory = this.settings.SettingsPath,
3956                 FileName = Path.Combine(this.settings.SettingsPath, "TweenUp3.exe"),
3957                 Arguments = "\"" + Application.StartupPath + "\"",
3958             };
3959
3960             try
3961             {
3962                 Process.Start(pinfo);
3963             }
3964             catch (Exception)
3965             {
3966                 MessageBox.Show("Failed to execute TweenUp3.exe.");
3967             }
3968         }
3969
3970         public readonly record struct VersionInfo(
3971             Version Version,
3972             Uri DownloadUri,
3973             string ReleaseNote
3974         );
3975
3976         /// <summary>
3977         /// OpenTween の最新バージョンの情報を取得します
3978         /// </summary>
3979         public async Task<VersionInfo> GetVersionInfoAsync()
3980         {
3981             var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
3982                 DateTimeUtc.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
3983
3984             var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
3985                 .ConfigureAwait(false);
3986
3987             // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
3988             var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
3989
3990             var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
3991             var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
3992
3993             msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
3994
3995             return new VersionInfo
3996             {
3997                 Version = Version.Parse(msgHeader[0]),
3998                 DownloadUri = new Uri(msgHeader[1]),
3999                 ReleaseNote = msgBody,
4000             };
4001         }
4002
4003         private async Task CheckNewVersion(bool startup = false)
4004         {
4005             if (ApplicationSettings.VersionInfoUrl == null)
4006                 return; // 更新チェック無効化
4007
4008             try
4009             {
4010                 var versionInfo = await this.GetVersionInfoAsync();
4011
4012                 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
4013                 {
4014                     // 更新不要
4015                     if (!startup)
4016                     {
4017                         var msgtext = string.Format(
4018                             Properties.Resources.CheckNewVersionText7,
4019                             MyCommon.GetReadableVersion(),
4020                             MyCommon.GetReadableVersion(versionInfo.Version));
4021                         msgtext = MyCommon.ReplaceAppName(msgtext);
4022
4023                         MessageBox.Show(
4024                             msgtext,
4025                             MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4026                             MessageBoxButtons.OK,
4027                             MessageBoxIcon.Information);
4028                     }
4029                     return;
4030                 }
4031
4032                 if (startup && versionInfo.Version <= this.settings.Common.SkipUpdateVersion)
4033                     return;
4034
4035                 using var dialog = new UpdateDialog();
4036
4037                 dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
4038                     MyCommon.GetReadableVersion(versionInfo.Version));
4039                 dialog.DetailsText = versionInfo.ReleaseNote;
4040
4041                 if (dialog.ShowDialog(this) == DialogResult.Yes)
4042                 {
4043                     await MyCommon.OpenInBrowserAsync(this, versionInfo.DownloadUri);
4044                 }
4045                 else if (dialog.SkipButtonPressed)
4046                 {
4047                     this.settings.Common.SkipUpdateVersion = versionInfo.Version;
4048                     this.MarkSettingCommonModified();
4049                 }
4050             }
4051             catch (Exception)
4052             {
4053                 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
4054                 if (!startup)
4055                 {
4056                     MessageBox.Show(
4057                         Properties.Resources.CheckNewVersionText10,
4058                         MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
4059                         MessageBoxButtons.OK,
4060                         MessageBoxIcon.Exclamation,
4061                         MessageBoxDefaultButton.Button2);
4062                 }
4063             }
4064         }
4065
4066         private void UpdateSelectedPost()
4067         {
4068             // 件数関連の場合、タイトル即時書き換え
4069             if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
4070                this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
4071                this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
4072                this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
4073             {
4074                 this.SetMainWindowTitle();
4075             }
4076             if (!this.StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
4077                 this.SetStatusLabelUrl();
4078
4079             if (this.settings.Common.TabIconDisp)
4080             {
4081                 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
4082                 {
4083                     if (tab.UnreadCount == 0)
4084                     {
4085                         var tabPage = this.ListTab.TabPages[index];
4086                         if (tabPage.ImageIndex == 0)
4087                             tabPage.ImageIndex = -1;
4088                     }
4089                 }
4090             }
4091             else
4092             {
4093                 this.ListTab.Refresh();
4094             }
4095
4096             this.DispSelectedPost();
4097         }
4098
4099         private void DispSelectedPost()
4100             => this.DispSelectedPost(false);
4101
4102         private PostClass displayPost = new();
4103
4104         /// <summary>
4105         /// サムネイル表示に使用する CancellationToken の生成元
4106         /// </summary>
4107         private CancellationTokenSource? thumbnailTokenSource = null;
4108
4109         private void DispSelectedPost(bool forceupdate)
4110         {
4111             var currentPost = this.CurrentPost;
4112             if (currentPost == null)
4113                 return;
4114
4115             var oldDisplayPost = this.displayPost;
4116             this.displayPost = currentPost;
4117
4118             if (!forceupdate && currentPost.Equals(oldDisplayPost))
4119                 return;
4120
4121             var loadTasks = new TaskCollection();
4122             loadTasks.Add(() => this.tweetDetailsView.ShowPostDetails(currentPost));
4123
4124             if (this.settings.Common.PreviewEnable)
4125             {
4126                 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
4127                 oldTokenSource?.Cancel();
4128
4129                 var token = this.thumbnailTokenSource!.Token;
4130                 loadTasks.Add(() => this.PrepareThumbnailControl(currentPost, token));
4131             }
4132             else
4133             {
4134                 this.SplitContainer3.Panel2Collapsed = true;
4135             }
4136
4137             // サムネイルの読み込みを待たずに次に選択されたツイートを表示するため await しない
4138             _ = loadTasks
4139                 .IgnoreException(x => x is OperationCanceledException)
4140                 .RunAll();
4141         }
4142
4143         private async Task PrepareThumbnailControl(PostClass post, CancellationToken token)
4144         {
4145             var prepareTask = this.tweetThumbnail1.Model.PrepareThumbnails(post, token);
4146
4147             var timeout = Task.Delay(100);
4148             if ((await Task.WhenAny(prepareTask, timeout)) == timeout)
4149             {
4150                 token.ThrowIfCancellationRequested();
4151
4152                 // サムネイル情報の読み込みに時間が掛かっている場合は一旦サムネイル領域を非表示にする
4153                 this.SplitContainer3.Panel2Collapsed = true;
4154             }
4155
4156             await prepareTask;
4157             token.ThrowIfCancellationRequested();
4158
4159             this.SplitContainer3.Panel2Collapsed = !this.tweetThumbnail1.Model.ThumbnailAvailable;
4160         }
4161
4162         private async void MatomeMenuItem_Click(object sender, EventArgs e)
4163             => await this.OpenApplicationWebsite();
4164
4165         private async Task OpenApplicationWebsite()
4166             => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.WebsiteUrl);
4167
4168         private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
4169             => await MyCommon.OpenInBrowserAsync(this, ApplicationSettings.ShortcutKeyUrl);
4170
4171         private async void ListTab_KeyDown(object sender, KeyEventArgs e)
4172         {
4173             var tab = this.CurrentTab;
4174             if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
4175             {
4176                 var pnl = this.CurrentTabPage.Controls["panelSearch"];
4177                 if (pnl.Controls["comboSearch"].Focused ||
4178                     pnl.Controls["comboLang"].Focused ||
4179                     pnl.Controls["buttonSearch"].Focused) return;
4180             }
4181
4182             if (e.Control || e.Shift || e.Alt)
4183                 tab.ClearAnchor();
4184
4185             if (this.CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
4186             {
4187                 e.Handled = true;
4188                 e.SuppressKeyPress = true;
4189             }
4190
4191             if (asyncTask != null)
4192                 await asyncTask;
4193         }
4194
4195         private ShortcutCommand[] shortcutCommands = Array.Empty<ShortcutCommand>();
4196
4197         private void InitializeShortcuts()
4198         {
4199             this.shortcutCommands = new[]
4200             {
4201                 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
4202                 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
4203                     .FocusedOn(FocusedControl.ListTab)
4204                     .Do(() => SendKeys.Send("{DOWN}")),
4205
4206                 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
4207                     .FocusedOn(FocusedControl.ListTab)
4208                     .Do(() => SendKeys.Send("{UP}")),
4209
4210                 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
4211                     .FocusedOn(FocusedControl.ListTab)
4212                     .Do(() => SendKeys.Send("{PGDN}")),
4213
4214                 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
4215                     .FocusedOn(FocusedControl.ListTab)
4216                     .Do(() => SendKeys.Send("{PGUP}")),
4217
4218                 ShortcutCommand.Create(Keys.F1)
4219                     .Do(() => this.OpenApplicationWebsite()),
4220
4221                 ShortcutCommand.Create(Keys.F3)
4222                     .Do(() => this.MenuItemSearchNext_Click(this.MenuItemSearchNext, EventArgs.Empty)),
4223
4224                 ShortcutCommand.Create(Keys.F5)
4225                     .Do(() => this.DoRefresh()),
4226
4227                 ShortcutCommand.Create(Keys.F6)
4228                     .Do(() => this.RefreshTabAsync<MentionsTabModel>()),
4229
4230                 ShortcutCommand.Create(Keys.F7)
4231                     .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>()),
4232
4233                 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
4234                     .NotFocusedOn(FocusedControl.StatusText)
4235                     .Do(() =>
4236                     {
4237                         this.CurrentTab.ClearAnchor();
4238                         this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
4239                     }),
4240
4241                 ShortcutCommand.Create(Keys.G)
4242                     .NotFocusedOn(FocusedControl.StatusText)
4243                     .Do(() =>
4244                     {
4245                         this.CurrentTab.ClearAnchor();
4246                         this.ShowRelatedStatusesMenuItem_Click(this.ShowRelatedStatusesMenuItem, EventArgs.Empty);
4247                     }),
4248
4249                 ShortcutCommand.Create(Keys.Right, Keys.N)
4250                     .FocusedOn(FocusedControl.ListTab)
4251                     .Do(() => this.GoRelPost(forward: true)),
4252
4253                 ShortcutCommand.Create(Keys.Left, Keys.P)
4254                     .FocusedOn(FocusedControl.ListTab)
4255                     .Do(() => this.GoRelPost(forward: false)),
4256
4257                 ShortcutCommand.Create(Keys.OemPeriod)
4258                     .FocusedOn(FocusedControl.ListTab)
4259                     .Do(() => this.GoAnchor()),
4260
4261                 ShortcutCommand.Create(Keys.I)
4262                     .FocusedOn(FocusedControl.ListTab)
4263                     .OnlyWhen(() => this.StatusText.Enabled)
4264                     .Do(() => this.StatusText.Focus()),
4265
4266                 ShortcutCommand.Create(Keys.Enter)
4267                     .FocusedOn(FocusedControl.ListTab)
4268                     .Do(() => this.ListItemDoubleClickAction()),
4269
4270                 ShortcutCommand.Create(Keys.R)
4271                     .FocusedOn(FocusedControl.ListTab)
4272                     .Do(() => this.DoRefresh()),
4273
4274                 ShortcutCommand.Create(Keys.L)
4275                     .FocusedOn(FocusedControl.ListTab)
4276                     .Do(() =>
4277                     {
4278                         this.CurrentTab.ClearAnchor();
4279                         this.GoPost(forward: true);
4280                     }),
4281
4282                 ShortcutCommand.Create(Keys.H)
4283                     .FocusedOn(FocusedControl.ListTab)
4284                     .Do(() =>
4285                     {
4286                         this.CurrentTab.ClearAnchor();
4287                         this.GoPost(forward: false);
4288                     }),
4289
4290                 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
4291                     .FocusedOn(FocusedControl.ListTab)
4292                     .Do(() =>
4293                     {
4294                         this.CurrentTab.ClearAnchor();
4295                         this.MoveTop();
4296                     }),
4297
4298                 ShortcutCommand.Create(Keys.S)
4299                     .FocusedOn(FocusedControl.ListTab)
4300                     .Do(() =>
4301                     {
4302                         this.CurrentTab.ClearAnchor();
4303                         this.GoNextTab(forward: true);
4304                     }),
4305
4306                 ShortcutCommand.Create(Keys.A)
4307                     .FocusedOn(FocusedControl.ListTab)
4308                     .Do(() =>
4309                     {
4310                         this.CurrentTab.ClearAnchor();
4311                         this.GoNextTab(forward: false);
4312                     }),
4313
4314                 // ] in_reply_to参照元へ戻る
4315                 ShortcutCommand.Create(Keys.Oem4)
4316                     .FocusedOn(FocusedControl.ListTab)
4317                     .Do(() =>
4318                     {
4319                         this.CurrentTab.ClearAnchor();
4320                         return this.GoInReplyToPostTree();
4321                     }),
4322
4323                 // [ in_reply_toへジャンプ
4324                 ShortcutCommand.Create(Keys.Oem6)
4325                     .FocusedOn(FocusedControl.ListTab)
4326                     .Do(() =>
4327                     {
4328                         this.CurrentTab.ClearAnchor();
4329                         this.GoBackInReplyToPostTree();
4330                     }),
4331
4332                 ShortcutCommand.Create(Keys.Escape)
4333                     .FocusedOn(FocusedControl.ListTab)
4334                     .Do(() =>
4335                     {
4336                         this.CurrentTab.ClearAnchor();
4337                         var tab = this.CurrentTab;
4338                         var tabtype = tab.TabType;
4339                         if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
4340                         {
4341                             this.RemoveSpecifiedTab(tab.TabName, false);
4342                             this.SaveConfigsTabs();
4343                         }
4344                     }),
4345
4346                 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
4347                 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
4348                     .FocusedOn(FocusedControl.ListTab)
4349                     .Do(() => this.CurrentTab.ClearAnchor(), preventDefault: false),
4350
4351                 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
4352                 ShortcutCommand.Create(Keys.Up, Keys.Down)
4353                     .FocusedOn(FocusedControl.PostBrowser)
4354                     .Do(() => { }),
4355
4356                 ShortcutCommand.Create(Keys.Control | Keys.R)
4357                     .Do(() => this.MakeReplyText()),
4358
4359                 ShortcutCommand.Create(Keys.Control | Keys.D)
4360                     .Do(() => this.DoStatusDelete()),
4361
4362                 ShortcutCommand.Create(Keys.Control | Keys.M)
4363                     .Do(() => this.MakeDirectMessageText()),
4364
4365                 ShortcutCommand.Create(Keys.Control | Keys.S)
4366                     .Do(() => this.FavoriteChange(favAdd: true)),
4367
4368                 ShortcutCommand.Create(Keys.Control | Keys.I)
4369                     .Do(() => this.DoRepliedStatusOpen()),
4370
4371                 ShortcutCommand.Create(Keys.Control | Keys.Q)
4372                     .Do(() => this.DoQuoteOfficial()),
4373
4374                 ShortcutCommand.Create(Keys.Control | Keys.B)
4375                     .Do(() => this.ReadedStripMenuItem_Click(this.ReadedStripMenuItem, EventArgs.Empty)),
4376
4377                 ShortcutCommand.Create(Keys.Control | Keys.T)
4378                     .Do(() => this.HashManageMenuItem_Click(this.HashManageMenuItem, EventArgs.Empty)),
4379
4380                 ShortcutCommand.Create(Keys.Control | Keys.L)
4381                     .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(this.UrlConvertAutoToolStripMenuItem, EventArgs.Empty)),
4382
4383                 ShortcutCommand.Create(Keys.Control | Keys.Y)
4384                     .NotFocusedOn(FocusedControl.PostBrowser)
4385                     .Do(() => this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty)),
4386
4387                 ShortcutCommand.Create(Keys.Control | Keys.F)
4388                     .Do(() => this.MenuItemSubSearch_Click(this.MenuItemSubSearch, EventArgs.Empty)),
4389
4390                 ShortcutCommand.Create(Keys.Control | Keys.U)
4391                     .Do(() => this.ShowUserTimeline()),
4392
4393                 ShortcutCommand.Create(Keys.Control | Keys.H)
4394                     .Do(() => this.AuthorOpenInBrowserMenuItem_Click(this.AuthorOpenInBrowserContextMenuItem, EventArgs.Empty)),
4395
4396                 ShortcutCommand.Create(Keys.Control | Keys.O)
4397                     .Do(() => this.StatusOpenMenuItem_Click(this.StatusOpenMenuItem, EventArgs.Empty)),
4398
4399                 ShortcutCommand.Create(Keys.Control | Keys.E)
4400                     .Do(() => this.OpenURLMenuItem_Click(this.OpenURLMenuItem, EventArgs.Empty)),
4401
4402                 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
4403                     .FocusedOn(FocusedControl.ListTab)
4404                     .Do(() => this.selectionDebouncer.Call(), preventDefault: false),
4405
4406                 ShortcutCommand.Create(Keys.Control | Keys.N)
4407                     .FocusedOn(FocusedControl.ListTab)
4408                     .Do(() => this.GoNextTab(forward: true)),
4409
4410                 ShortcutCommand.Create(Keys.Control | Keys.P)
4411                     .FocusedOn(FocusedControl.ListTab)
4412                     .Do(() => this.GoNextTab(forward: false)),
4413
4414                 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
4415                     .FocusedOn(FocusedControl.ListTab)
4416                     .Do(() => this.CopyStot()),
4417
4418                 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
4419                 ShortcutCommand.Create(Keys.Control | Keys.D1)
4420                     .FocusedOn(FocusedControl.ListTab)
4421                     .OnlyWhen(() => this.statuses.Tabs.Count >= 1)
4422                     .Do(() => this.ListTab.SelectedIndex = 0),
4423
4424                 ShortcutCommand.Create(Keys.Control | Keys.D2)
4425                     .FocusedOn(FocusedControl.ListTab)
4426                     .OnlyWhen(() => this.statuses.Tabs.Count >= 2)
4427                     .Do(() => this.ListTab.SelectedIndex = 1),
4428
4429                 ShortcutCommand.Create(Keys.Control | Keys.D3)
4430                     .FocusedOn(FocusedControl.ListTab)
4431                     .OnlyWhen(() => this.statuses.Tabs.Count >= 3)
4432                     .Do(() => this.ListTab.SelectedIndex = 2),
4433
4434                 ShortcutCommand.Create(Keys.Control | Keys.D4)
4435                     .FocusedOn(FocusedControl.ListTab)
4436                     .OnlyWhen(() => this.statuses.Tabs.Count >= 4)
4437                     .Do(() => this.ListTab.SelectedIndex = 3),
4438
4439                 ShortcutCommand.Create(Keys.Control | Keys.D5)
4440                     .FocusedOn(FocusedControl.ListTab)
4441                     .OnlyWhen(() => this.statuses.Tabs.Count >= 5)
4442                     .Do(() => this.ListTab.SelectedIndex = 4),
4443
4444                 ShortcutCommand.Create(Keys.Control | Keys.D6)
4445                     .FocusedOn(FocusedControl.ListTab)
4446                     .OnlyWhen(() => this.statuses.Tabs.Count >= 6)
4447                     .Do(() => this.ListTab.SelectedIndex = 5),
4448
4449                 ShortcutCommand.Create(Keys.Control | Keys.D7)
4450                     .FocusedOn(FocusedControl.ListTab)
4451                     .OnlyWhen(() => this.statuses.Tabs.Count >= 7)
4452                     .Do(() => this.ListTab.SelectedIndex = 6),
4453
4454                 ShortcutCommand.Create(Keys.Control | Keys.D8)
4455                     .FocusedOn(FocusedControl.ListTab)
4456                     .OnlyWhen(() => this.statuses.Tabs.Count >= 8)
4457                     .Do(() => this.ListTab.SelectedIndex = 7),
4458
4459                 ShortcutCommand.Create(Keys.Control | Keys.D9)
4460                     .FocusedOn(FocusedControl.ListTab)
4461                     .Do(() => this.ListTab.SelectedIndex = this.statuses.Tabs.Count - 1),
4462
4463                 ShortcutCommand.Create(Keys.Control | Keys.A)
4464                     .FocusedOn(FocusedControl.StatusText)
4465                     .Do(() => this.StatusText.SelectAll()),
4466
4467                 ShortcutCommand.Create(Keys.Control | Keys.V)
4468                     .FocusedOn(FocusedControl.StatusText)
4469                     .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
4470
4471                 ShortcutCommand.Create(Keys.Control | Keys.Up)
4472                     .FocusedOn(FocusedControl.StatusText)
4473                     .Do(() => this.StatusTextHistoryBack()),
4474
4475                 ShortcutCommand.Create(Keys.Control | Keys.Down)
4476                     .FocusedOn(FocusedControl.StatusText)
4477                     .Do(() => this.StatusTextHistoryForward()),
4478
4479                 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
4480                     .FocusedOn(FocusedControl.StatusText)
4481                     .Do(() =>
4482                     {
4483                         if (this.ListTab.SelectedIndex == 0)
4484                         {
4485                             this.ListTab.SelectedIndex = this.ListTab.TabCount - 1;
4486                         }
4487                         else
4488                         {
4489                             this.ListTab.SelectedIndex -= 1;
4490                         }
4491                         this.StatusText.Focus();
4492                     }),
4493
4494                 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
4495                     .FocusedOn(FocusedControl.StatusText)
4496                     .Do(() =>
4497                     {
4498                         if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4499                         {
4500                             this.ListTab.SelectedIndex = 0;
4501                         }
4502                         else
4503                         {
4504                             this.ListTab.SelectedIndex += 1;
4505                         }
4506                         this.StatusText.Focus();
4507                     }),
4508
4509                 ShortcutCommand.Create(Keys.Control | Keys.Y)
4510                     .FocusedOn(FocusedControl.PostBrowser)
4511                     .Do(() =>
4512                     {
4513                         var multiline = !this.settings.Local.StatusMultiline;
4514                         this.settings.Local.StatusMultiline = multiline;
4515                         this.MultiLineMenuItem.Checked = multiline;
4516                         this.MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
4517                     }),
4518
4519                 ShortcutCommand.Create(Keys.Shift | Keys.F3)
4520                     .Do(() => this.MenuItemSearchPrev_Click(this.MenuItemSearchPrev, EventArgs.Empty)),
4521
4522                 ShortcutCommand.Create(Keys.Shift | Keys.F5)
4523                     .Do(() => this.DoRefreshMore()),
4524
4525                 ShortcutCommand.Create(Keys.Shift | Keys.F6)
4526                     .Do(() => this.RefreshTabAsync<MentionsTabModel>(backward: true)),
4527
4528                 ShortcutCommand.Create(Keys.Shift | Keys.F7)
4529                     .Do(() => this.RefreshTabAsync<DirectMessagesTabModel>(backward: true)),
4530
4531                 ShortcutCommand.Create(Keys.Shift | Keys.R)
4532                     .NotFocusedOn(FocusedControl.StatusText)
4533                     .Do(() => this.DoRefreshMore()),
4534
4535                 ShortcutCommand.Create(Keys.Shift | Keys.H)
4536                     .FocusedOn(FocusedControl.ListTab)
4537                     .Do(() => this.GoTopEnd(goTop: true)),
4538
4539                 ShortcutCommand.Create(Keys.Shift | Keys.L)
4540                     .FocusedOn(FocusedControl.ListTab)
4541                     .Do(() => this.GoTopEnd(goTop: false)),
4542
4543                 ShortcutCommand.Create(Keys.Shift | Keys.M)
4544                     .FocusedOn(FocusedControl.ListTab)
4545                     .Do(() => this.GoMiddle()),
4546
4547                 ShortcutCommand.Create(Keys.Shift | Keys.G)
4548                     .FocusedOn(FocusedControl.ListTab)
4549                     .Do(() => this.GoLast()),
4550
4551                 ShortcutCommand.Create(Keys.Shift | Keys.Z)
4552                     .FocusedOn(FocusedControl.ListTab)
4553                     .Do(() => this.MoveMiddle()),
4554
4555                 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
4556                     .FocusedOn(FocusedControl.ListTab)
4557                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
4558
4559                 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
4560                     .FocusedOn(FocusedControl.ListTab)
4561                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
4562
4563                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4564                 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
4565                     .FocusedOn(FocusedControl.ListTab)
4566                     .Do(() => this.GoFav(forward: true)),
4567
4568                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
4569                 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
4570                     .FocusedOn(FocusedControl.ListTab)
4571                     .Do(() => this.GoFav(forward: false)),
4572
4573                 ShortcutCommand.Create(Keys.Shift | Keys.Space)
4574                     .FocusedOn(FocusedControl.ListTab)
4575                     .Do(() => this.GoBackSelectPostChain()),
4576
4577                 ShortcutCommand.Create(Keys.Alt | Keys.R)
4578                     .Do(() => this.DoReTweetOfficial(isConfirm: true)),
4579
4580                 ShortcutCommand.Create(Keys.Alt | Keys.P)
4581                     .OnlyWhen(() => this.CurrentPost != null)
4582                     .Do(() => this.DoShowUserStatus(this.CurrentPost!.ScreenName, showInputDialog: false)),
4583
4584                 ShortcutCommand.Create(Keys.Alt | Keys.Up)
4585                     .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
4586
4587                 ShortcutCommand.Create(Keys.Alt | Keys.Down)
4588                     .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
4589
4590                 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
4591                     .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
4592
4593                 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
4594                     .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
4595
4596                 // 別タブの同じ書き込みへ(ALT+←/→)
4597                 ShortcutCommand.Create(Keys.Alt | Keys.Right)
4598                     .FocusedOn(FocusedControl.ListTab)
4599                     .Do(() => this.GoSamePostToAnotherTab(left: false)),
4600
4601                 ShortcutCommand.Create(Keys.Alt | Keys.Left)
4602                     .FocusedOn(FocusedControl.ListTab)
4603                     .Do(() => this.GoSamePostToAnotherTab(left: true)),
4604
4605                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
4606                     .Do(() => this.MakeReplyText(atAll: true)),
4607
4608                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
4609                     .Do(() => this.CopyIdUri()),
4610
4611                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
4612                     .OnlyWhen(() => this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
4613                     .Do(() => this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus()),
4614
4615                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.L)
4616                     .Do(() => this.DoQuoteOfficial()),
4617
4618                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
4619                     .Do(() => this.FavoriteChange(favAdd: false)),
4620
4621                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
4622                     .Do(() => this.UnreadStripMenuItem_Click(this.UnreadStripMenuItem, EventArgs.Empty)),
4623
4624                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
4625                     .Do(() => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty)),
4626
4627                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
4628                     .Do(() => this.ImageSelectMenuItem_Click(this.ImageSelectMenuItem, EventArgs.Empty)),
4629
4630                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
4631                     .Do(() => this.DoMoveToRTHome()),
4632
4633                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
4634                     .FocusedOn(FocusedControl.StatusText)
4635                     .Do(() =>
4636                     {
4637                         var tab = this.CurrentTab;
4638                         var selectedIndex = tab.SelectedIndex;
4639                         if (selectedIndex != -1 && selectedIndex > 0)
4640                         {
4641                             var listView = this.CurrentListView;
4642                             var idx = selectedIndex - 1;
4643                             this.SelectListItem(listView, idx);
4644                             listView.EnsureVisible(idx);
4645                         }
4646                     }),
4647
4648                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
4649                     .FocusedOn(FocusedControl.StatusText)
4650                     .Do(() =>
4651                     {
4652                         var tab = this.CurrentTab;
4653                         var selectedIndex = tab.SelectedIndex;
4654                         if (selectedIndex != -1 && selectedIndex < tab.AllCount - 1)
4655                         {
4656                             var listView = this.CurrentListView;
4657                             var idx = selectedIndex + 1;
4658                             this.SelectListItem(listView, idx);
4659                             listView.EnsureVisible(idx);
4660                         }
4661                     }),
4662
4663                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
4664                     .FocusedOn(FocusedControl.StatusText)
4665                     .Do(() =>
4666                     {
4667                         if (this.StatusText.SelectionStart > 0)
4668                         {
4669                             var endidx = this.StatusText.SelectionStart - 1;
4670                             var startstr = "";
4671                             for (var i = this.StatusText.SelectionStart - 1; i >= 0; i--)
4672                             {
4673                                 var c = this.StatusText.Text[i];
4674                                 if (char.IsLetterOrDigit(c) || c == '_')
4675                                 {
4676                                     continue;
4677                                 }
4678                                 if (c == '@')
4679                                 {
4680                                     startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4681                                     var cnt = this.AtIdSupl.ItemCount;
4682                                     this.ShowSuplDialog(this.StatusText, this.AtIdSupl, startstr.Length + 1, startstr);
4683                                     if (this.AtIdSupl.ItemCount != cnt)
4684                                         this.MarkSettingAtIdModified();
4685                                 }
4686                                 else if (c == '#')
4687                                 {
4688                                     startstr = this.StatusText.Text.Substring(i + 1, endidx - i);
4689                                     this.ShowSuplDialog(this.StatusText, this.HashSupl, startstr.Length + 1, startstr);
4690                                 }
4691                                 else
4692                                 {
4693                                     break;
4694                                 }
4695                             }
4696                         }
4697                     }),
4698
4699                 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
4700                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
4701                     .FocusedOn(FocusedControl.ListTab)
4702                     .Do(() => this.SetSortColumnByDisplayIndex(0)),
4703
4704                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
4705                     .FocusedOn(FocusedControl.ListTab)
4706                     .Do(() => this.SetSortColumnByDisplayIndex(1)),
4707
4708                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
4709                     .FocusedOn(FocusedControl.ListTab)
4710                     .Do(() => this.SetSortColumnByDisplayIndex(2)),
4711
4712                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
4713                     .FocusedOn(FocusedControl.ListTab)
4714                     .Do(() => this.SetSortColumnByDisplayIndex(3)),
4715
4716                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
4717                     .FocusedOn(FocusedControl.ListTab)
4718                     .Do(() => this.SetSortColumnByDisplayIndex(4)),
4719
4720                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
4721                     .FocusedOn(FocusedControl.ListTab)
4722                     .Do(() => this.SetSortColumnByDisplayIndex(5)),
4723
4724                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
4725                     .FocusedOn(FocusedControl.ListTab)
4726                     .Do(() => this.SetSortColumnByDisplayIndex(6)),
4727
4728                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
4729                     .FocusedOn(FocusedControl.ListTab)
4730                     .Do(() => this.SetSortColumnByDisplayIndex(7)),
4731
4732                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
4733                     .FocusedOn(FocusedControl.ListTab)
4734                     .Do(() => this.SetSortLastColumn()),
4735
4736                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
4737                     .FocusedOn(FocusedControl.ListTab)
4738                     .Do(() => this.FavoritesRetweetOfficial()),
4739
4740                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
4741                     .FocusedOn(FocusedControl.ListTab)
4742                     .Do(() => this.FavoritesRetweetUnofficial()),
4743
4744                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
4745                     .FocusedOn(FocusedControl.ListTab)
4746                     .Do(() => this.OpenUserAppointUrl()),
4747
4748                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4749                     .FocusedOn(FocusedControl.PostBrowser)
4750                     .Do(() => this.DoReTweetUnofficial()),
4751
4752                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
4753                     .OnlyWhen(() => this.ExistCurrentPost)
4754                     .Do(() => this.tweetDetailsView.DoTranslation()),
4755
4756                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
4757                     .Do(() => this.DoReTweetUnofficial()),
4758
4759                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
4760                     .Do(() => this.CopyUserId()),
4761
4762                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
4763                     .Do(() => this.tweetThumbnail1.Model.ScrollUp()),
4764
4765                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
4766                     .Do(() => this.tweetThumbnail1.Model.ScrollDown()),
4767
4768                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
4769                     .FocusedOn(FocusedControl.ListTab)
4770                     .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
4771                     .Do(() => this.tweetThumbnail1.OpenImageInBrowser()),
4772             };
4773         }
4774
4775         internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task? asyncTask)
4776         {
4777             // Task を返す非同期処理があれば asyncTask に代入する
4778             asyncTask = null;
4779
4780             // ShortcutCommand に対応しているコマンドはここで処理される
4781             foreach (var command in this.shortcutCommands)
4782             {
4783                 if (command.IsMatch(keyData, focusedOn))
4784                 {
4785                     asyncTask = command.RunCommand();
4786                     return command.PreventDefault;
4787                 }
4788             }
4789
4790             return false;
4791         }
4792
4793         private void GoNextTab(bool forward)
4794         {
4795             var idx = this.statuses.SelectedTabIndex;
4796             var tabCount = this.statuses.Tabs.Count;
4797             if (forward)
4798             {
4799                 idx += 1;
4800                 if (idx > tabCount - 1) idx = 0;
4801             }
4802             else
4803             {
4804                 idx -= 1;
4805                 if (idx < 0) idx = tabCount - 1;
4806             }
4807             this.ListTab.SelectedIndex = idx;
4808         }
4809
4810         private void CopyStot()
4811         {
4812             var sb = new StringBuilder();
4813             var tab = this.CurrentTab;
4814             var isProtected = false;
4815             var isDm = tab.TabType == MyCommon.TabUsageType.DirectMessage;
4816             foreach (var post in tab.SelectedPosts)
4817             {
4818                 if (post.IsDeleted) continue;
4819                 if (!isDm)
4820                 {
4821                     if (post.RetweetedId != null)
4822                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
4823                     else
4824                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4825                 }
4826                 else
4827                 {
4828                     sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
4829                 }
4830             }
4831             if (isProtected)
4832             {
4833                 MessageBox.Show(Properties.Resources.CopyStotText1);
4834             }
4835             if (sb.Length > 0)
4836             {
4837                 var clstr = sb.ToString();
4838                 try
4839                 {
4840                     Clipboard.SetDataObject(clstr, false, 5, 100);
4841                 }
4842                 catch (Exception ex)
4843                 {
4844                     MessageBox.Show(ex.Message);
4845                 }
4846             }
4847         }
4848
4849         private void CopyIdUri()
4850         {
4851             var tab = this.CurrentTab;
4852             if (tab == null || tab is DirectMessagesTabModel)
4853                 return;
4854
4855             var copyUrls = new List<string>();
4856             foreach (var post in tab.SelectedPosts)
4857                 copyUrls.Add(MyCommon.GetStatusUrl(post));
4858
4859             if (copyUrls.Count == 0)
4860                 return;
4861
4862             try
4863             {
4864                 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
4865             }
4866             catch (ExternalException ex)
4867             {
4868                 MessageBox.Show(ex.Message);
4869             }
4870         }
4871
4872         private void GoFav(bool forward)
4873         {
4874             var tab = this.CurrentTab;
4875             if (tab.AllCount == 0)
4876                 return;
4877
4878             var selectedIndex = tab.SelectedIndex;
4879
4880             int fIdx;
4881             int toIdx;
4882             int stp;
4883
4884             if (forward)
4885             {
4886                 if (selectedIndex == -1)
4887                 {
4888                     fIdx = 0;
4889                 }
4890                 else
4891                 {
4892                     fIdx = selectedIndex + 1;
4893                     if (fIdx > tab.AllCount - 1)
4894                         return;
4895                 }
4896                 toIdx = tab.AllCount;
4897                 stp = 1;
4898             }
4899             else
4900             {
4901                 if (selectedIndex == -1)
4902                 {
4903                     fIdx = tab.AllCount - 1;
4904                 }
4905                 else
4906                 {
4907                     fIdx = selectedIndex - 1;
4908                     if (fIdx < 0)
4909                         return;
4910                 }
4911                 toIdx = -1;
4912                 stp = -1;
4913             }
4914
4915             for (var idx = fIdx; idx != toIdx; idx += stp)
4916             {
4917                 if (tab[idx].IsFav)
4918                 {
4919                     var listView = this.CurrentListView;
4920                     this.SelectListItem(listView, idx);
4921                     listView.EnsureVisible(idx);
4922                     break;
4923                 }
4924             }
4925         }
4926
4927         private void GoSamePostToAnotherTab(bool left)
4928         {
4929             var tab = this.CurrentTab;
4930
4931             // Directタブは対象外(見つかるはずがない)
4932             if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
4933                 return;
4934
4935             var selectedStatusId = tab.SelectedStatusId;
4936             if (selectedStatusId == null)
4937                 return;
4938
4939             int fIdx, toIdx, stp;
4940
4941             if (left)
4942             {
4943                 // 左のタブへ
4944                 if (this.ListTab.SelectedIndex == 0)
4945                 {
4946                     return;
4947                 }
4948                 else
4949                 {
4950                     fIdx = this.ListTab.SelectedIndex - 1;
4951                 }
4952                 toIdx = -1;
4953                 stp = -1;
4954             }
4955             else
4956             {
4957                 // 右のタブへ
4958                 if (this.ListTab.SelectedIndex == this.ListTab.TabCount - 1)
4959                 {
4960                     return;
4961                 }
4962                 else
4963                 {
4964                     fIdx = this.ListTab.SelectedIndex + 1;
4965                 }
4966                 toIdx = this.ListTab.TabCount;
4967                 stp = 1;
4968             }
4969
4970             for (var tabidx = fIdx; tabidx != toIdx; tabidx += stp)
4971             {
4972                 var targetTab = this.statuses.Tabs[tabidx];
4973
4974                 // Directタブは対象外
4975                 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
4976                     continue;
4977
4978                 var foundIndex = targetTab.IndexOf(selectedStatusId);
4979                 if (foundIndex != -1)
4980                 {
4981                     this.ListTab.SelectedIndex = tabidx;
4982                     var listView = this.CurrentListView;
4983                     this.SelectListItem(listView, foundIndex);
4984                     listView.EnsureVisible(foundIndex);
4985                     return;
4986                 }
4987             }
4988         }
4989
4990         private void GoPost(bool forward)
4991         {
4992             var tab = this.CurrentTab;
4993             var currentPost = this.CurrentPost;
4994
4995             if (currentPost == null)
4996                 return;
4997
4998             var selectedIndex = tab.SelectedIndex;
4999
5000             int fIdx, toIdx, stp;
5001
5002             if (forward)
5003             {
5004                 fIdx = selectedIndex + 1;
5005                 if (fIdx > tab.AllCount - 1) return;
5006                 toIdx = tab.AllCount;
5007                 stp = 1;
5008             }
5009             else
5010             {
5011                 fIdx = selectedIndex - 1;
5012                 if (fIdx < 0) return;
5013                 toIdx = -1;
5014                 stp = -1;
5015             }
5016
5017             string name;
5018             if (currentPost.RetweetedBy == null)
5019             {
5020                 name = currentPost.ScreenName;
5021             }
5022             else
5023             {
5024                 name = currentPost.RetweetedBy;
5025             }
5026             for (var idx = fIdx; idx != toIdx; idx += stp)
5027             {
5028                 var post = tab[idx];
5029                 if (post.RetweetedId == null)
5030                 {
5031                     if (post.ScreenName == name)
5032                     {
5033                         var listView = this.CurrentListView;
5034                         this.SelectListItem(listView, idx);
5035                         listView.EnsureVisible(idx);
5036                         break;
5037                     }
5038                 }
5039                 else
5040                 {
5041                     if (post.RetweetedBy == name)
5042                     {
5043                         var listView = this.CurrentListView;
5044                         this.SelectListItem(listView, idx);
5045                         listView.EnsureVisible(idx);
5046                         break;
5047                     }
5048                 }
5049             }
5050         }
5051
5052         private void GoRelPost(bool forward)
5053         {
5054             var tab = this.CurrentTab;
5055             var selectedIndex = tab.SelectedIndex;
5056
5057             if (selectedIndex == -1)
5058                 return;
5059
5060             int fIdx, toIdx, stp;
5061
5062             if (forward)
5063             {
5064                 fIdx = selectedIndex + 1;
5065                 if (fIdx > tab.AllCount - 1) return;
5066                 toIdx = tab.AllCount;
5067                 stp = 1;
5068             }
5069             else
5070             {
5071                 fIdx = selectedIndex - 1;
5072                 if (fIdx < 0) return;
5073                 toIdx = -1;
5074                 stp = -1;
5075             }
5076
5077             var anchorPost = tab.AnchorPost;
5078             if (anchorPost == null)
5079             {
5080                 var currentPost = this.CurrentPost;
5081                 if (currentPost == null)
5082                     return;
5083
5084                 anchorPost = currentPost;
5085                 tab.AnchorPost = currentPost;
5086             }
5087
5088             for (var idx = fIdx; idx != toIdx; idx += stp)
5089             {
5090                 var post = tab[idx];
5091                 if (post.ScreenName == anchorPost.ScreenName ||
5092                     post.RetweetedBy == anchorPost.ScreenName ||
5093                     post.ScreenName == anchorPost.RetweetedBy ||
5094                     (!MyCommon.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == anchorPost.RetweetedBy) ||
5095                     anchorPost.ReplyToList.Any(x => x.UserId == post.UserId) ||
5096                     anchorPost.ReplyToList.Any(x => x.UserId == post.RetweetedByUserId) ||
5097                     post.ReplyToList.Any(x => x.UserId == anchorPost.UserId) ||
5098                     post.ReplyToList.Any(x => x.UserId == anchorPost.RetweetedByUserId))
5099                 {
5100                     var listView = this.CurrentListView;
5101                     this.SelectListItem(listView, idx);
5102                     listView.EnsureVisible(idx);
5103                     break;
5104                 }
5105             }
5106         }
5107
5108         private void GoAnchor()
5109         {
5110             var anchorStatusId = this.CurrentTab.AnchorStatusId;
5111             if (anchorStatusId == null)
5112                 return;
5113
5114             var idx = this.CurrentTab.IndexOf(anchorStatusId);
5115             if (idx == -1)
5116                 return;
5117
5118             var listView = this.CurrentListView;
5119             this.SelectListItem(listView, idx);
5120             listView.EnsureVisible(idx);
5121         }
5122
5123         private void GoTopEnd(bool goTop)
5124         {
5125             var listView = this.CurrentListView;
5126             if (listView.VirtualListSize == 0)
5127                 return;
5128
5129             ListViewItem item;
5130             int idx;
5131
5132             if (goTop)
5133             {
5134                 item = listView.GetItemAt(0, 25);
5135                 if (item == null)
5136                     idx = 0;
5137                 else
5138                     idx = item.Index;
5139             }
5140             else
5141             {
5142                 item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5143                 if (item == null)
5144                     idx = listView.VirtualListSize - 1;
5145                 else
5146                     idx = item.Index;
5147             }
5148             this.SelectListItem(listView, idx);
5149         }
5150
5151         private void GoMiddle()
5152         {
5153             var listView = this.CurrentListView;
5154             if (listView.VirtualListSize == 0)
5155                 return;
5156
5157             ListViewItem item;
5158             int idx1;
5159             int idx2;
5160             int idx3;
5161
5162             item = listView.GetItemAt(0, 0);
5163             if (item == null)
5164             {
5165                 idx1 = 0;
5166             }
5167             else
5168             {
5169                 idx1 = item.Index;
5170             }
5171
5172             item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
5173             if (item == null)
5174             {
5175                 idx2 = listView.VirtualListSize - 1;
5176             }
5177             else
5178             {
5179                 idx2 = item.Index;
5180             }
5181             idx3 = (idx1 + idx2) / 2;
5182
5183             this.SelectListItem(listView, idx3);
5184         }
5185
5186         private void GoLast()
5187         {
5188             var listView = this.CurrentListView;
5189             if (listView.VirtualListSize == 0) return;
5190
5191             if (this.statuses.SortOrder == SortOrder.Ascending)
5192             {
5193                 this.SelectListItem(listView, listView.VirtualListSize - 1);
5194                 listView.EnsureVisible(listView.VirtualListSize - 1);
5195             }
5196             else
5197             {
5198                 this.SelectListItem(listView, 0);
5199                 listView.EnsureVisible(0);
5200             }
5201         }
5202
5203         private void MoveTop()
5204         {
5205             var listView = this.CurrentListView;
5206             if (listView.SelectedIndices.Count == 0) return;
5207             var idx = listView.SelectedIndices[0];
5208             if (this.statuses.SortOrder == SortOrder.Ascending)
5209             {
5210                 listView.EnsureVisible(listView.VirtualListSize - 1);
5211             }
5212             else
5213             {
5214                 listView.EnsureVisible(0);
5215             }
5216             listView.EnsureVisible(idx);
5217         }
5218
5219         private async Task GoInReplyToPostTree()
5220         {
5221             var curTabClass = this.CurrentTab;
5222             var currentPost = this.CurrentPost;
5223
5224             if (currentPost == null)
5225                 return;
5226
5227             if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && currentPost.InReplyToStatusId == null && currentPost.TextFromApi.Contains("@"))
5228             {
5229                 try
5230                 {
5231                     var post = await this.tw.GetStatusApi(false, currentPost.StatusId.ToTwitterStatusId());
5232
5233                     currentPost = currentPost with
5234                     {
5235                         InReplyToStatusId = post.InReplyToStatusId,
5236                         InReplyToUser = post.InReplyToUser,
5237                         IsReply = post.IsReply,
5238                     };
5239                     curTabClass.ReplacePost(currentPost);
5240                     this.listCache?.PurgeCache();
5241
5242                     var index = curTabClass.SelectedIndex;
5243                     this.CurrentListView.RedrawItems(index, index, false);
5244                 }
5245                 catch (WebApiException ex)
5246                 {
5247                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5248                 }
5249             }
5250
5251             if (!(this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)) return;
5252
5253             if (this.replyChains == null || (this.replyChains.Count > 0 && this.replyChains.Peek().InReplyToId != currentPost.StatusId))
5254             {
5255                 this.replyChains = new Stack<ReplyChain>();
5256             }
5257             this.replyChains.Push(new ReplyChain(currentPost.StatusId, currentPost.InReplyToStatusId, curTabClass));
5258
5259             int inReplyToIndex;
5260             string inReplyToTabName;
5261             var inReplyToId = currentPost.InReplyToStatusId;
5262             var inReplyToUser = currentPost.InReplyToUser;
5263
5264             var inReplyToPosts = from tab in this.statuses.Tabs
5265                                  orderby tab != curTabClass
5266                                  from post in tab.Posts.Values
5267                                  where post.StatusId == inReplyToId
5268                                  let index = tab.IndexOf(post.StatusId)
5269                                  where index != -1
5270                                  select new { Tab = tab, Index = index };
5271
5272             var inReplyPost = inReplyToPosts.FirstOrDefault();
5273             if (inReplyPost == null)
5274             {
5275                 try
5276                 {
5277                     await Task.Run(async () =>
5278                     {
5279                         var post = await this.tw.GetStatusApi(false, currentPost.InReplyToStatusId.ToTwitterStatusId())
5280                             .ConfigureAwait(false);
5281                         post.IsRead = true;
5282
5283                         this.statuses.AddPost(post);
5284                         this.statuses.DistributePosts();
5285                     });
5286                 }
5287                 catch (WebApiException ex)
5288                 {
5289                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
5290                     await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5291                     return;
5292                 }
5293
5294                 this.RefreshTimeline();
5295
5296                 inReplyPost = inReplyToPosts.FirstOrDefault();
5297                 if (inReplyPost == null)
5298                 {
5299                     await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(inReplyToUser, inReplyToId.ToTwitterStatusId()));
5300                     return;
5301                 }
5302             }
5303             inReplyToTabName = inReplyPost.Tab.TabName;
5304             inReplyToIndex = inReplyPost.Index;
5305
5306             var tabIndex = this.statuses.Tabs.IndexOf(inReplyToTabName);
5307             var tabPage = this.ListTab.TabPages[tabIndex];
5308             var listView = (DetailsListView)tabPage.Tag;
5309
5310             if (this.CurrentTabName != inReplyToTabName)
5311             {
5312                 this.ListTab.SelectedIndex = tabIndex;
5313             }
5314
5315             this.SelectListItem(listView, inReplyToIndex);
5316             listView.EnsureVisible(inReplyToIndex);
5317         }
5318
5319         private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
5320         {
5321             var curTabClass = this.CurrentTab;
5322             var currentPost = this.CurrentPost;
5323
5324             if (currentPost == null)
5325                 return;
5326
5327             if (parallel)
5328             {
5329                 if (currentPost.InReplyToStatusId != null)
5330                 {
5331                     var posts = from t in this.statuses.Tabs
5332                                 from p in t.Posts
5333                                 where p.Value.StatusId != currentPost.StatusId && p.Value.InReplyToStatusId == currentPost.InReplyToStatusId
5334                                 let indexOf = t.IndexOf(p.Value.StatusId)
5335                                 where indexOf > -1
5336                                 orderby isForward ? indexOf : indexOf * -1
5337                                 orderby t != curTabClass
5338                                 select new { Tab = t, Post = p.Value, Index = indexOf };
5339                     try
5340                     {
5341                         var postList = posts.ToList();
5342                         for (var i = postList.Count - 1; i >= 0; i--)
5343                         {
5344                             var index = i;
5345                             if (postList.FindIndex(pst => pst.Post.StatusId == postList[index].Post.StatusId) != index)
5346                             {
5347                                 postList.RemoveAt(index);
5348                             }
5349                         }
5350                         var currentIndex = this.CurrentTab.SelectedIndex;
5351                         var post = postList.FirstOrDefault(pst => pst.Tab == curTabClass && isForward ? pst.Index > currentIndex : pst.Index < currentIndex);
5352                         if (post == null) post = postList.FirstOrDefault(pst => pst.Tab != curTabClass);
5353                         if (post == null) post = postList.First();
5354                         var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5355                         this.ListTab.SelectedIndex = tabIndex;
5356                         var listView = this.CurrentListView;
5357                         this.SelectListItem(listView, post.Index);
5358                         listView.EnsureVisible(post.Index);
5359                     }
5360                     catch (InvalidOperationException)
5361                     {
5362                         return;
5363                     }
5364                 }
5365             }
5366             else
5367             {
5368                 if (this.replyChains == null || this.replyChains.Count < 1)
5369                 {
5370                     var posts = from t in this.statuses.Tabs
5371                                 from p in t.Posts
5372                                 where p.Value.InReplyToStatusId == currentPost.StatusId
5373                                 let indexOf = t.IndexOf(p.Value.StatusId)
5374                                 where indexOf > -1
5375                                 orderby indexOf
5376                                 orderby t != curTabClass
5377                                 select new { Tab = t, Index = indexOf };
5378                     try
5379                     {
5380                         var post = posts.First();
5381                         var tabIndex = this.statuses.Tabs.IndexOf(post.Tab);
5382                         this.ListTab.SelectedIndex = tabIndex;
5383                         var listView = this.CurrentListView;
5384                         this.SelectListItem(listView, post.Index);
5385                         listView.EnsureVisible(post.Index);
5386                     }
5387                     catch (InvalidOperationException)
5388                     {
5389                         return;
5390                     }
5391                 }
5392                 else
5393                 {
5394                     var chainHead = this.replyChains.Pop();
5395                     if (chainHead.InReplyToId == currentPost.StatusId)
5396                     {
5397                         var tab = chainHead.OriginalTab;
5398                         if (!this.statuses.Tabs.Contains(tab))
5399                         {
5400                             this.replyChains = null;
5401                         }
5402                         else
5403                         {
5404                             var idx = tab.IndexOf(chainHead.OriginalId);
5405                             if (idx == -1)
5406                             {
5407                                 this.replyChains = null;
5408                             }
5409                             else
5410                             {
5411                                 var tabIndex = this.statuses.Tabs.IndexOf(tab);
5412                                 try
5413                                 {
5414                                     this.ListTab.SelectedIndex = tabIndex;
5415                                 }
5416                                 catch (Exception)
5417                                 {
5418                                     this.replyChains = null;
5419                                 }
5420                                 var listView = this.CurrentListView;
5421                                 this.SelectListItem(listView, idx);
5422                                 listView.EnsureVisible(idx);
5423                             }
5424                         }
5425                     }
5426                     else
5427                     {
5428                         this.replyChains = null;
5429                         this.GoBackInReplyToPostTree(parallel);
5430                     }
5431                 }
5432             }
5433         }
5434
5435         private void GoBackSelectPostChain()
5436         {
5437             if (this.selectPostChains.Count > 1)
5438             {
5439                 var idx = -1;
5440                 TabModel? foundTab = null;
5441
5442                 do
5443                 {
5444                     try
5445                     {
5446                         this.selectPostChains.Pop();
5447                         var (tab, post) = this.selectPostChains.Peek();
5448
5449                         if (!this.statuses.Tabs.Contains(tab))
5450                             continue; // 該当タブが存在しないので無視
5451
5452                         if (post != null)
5453                         {
5454                             idx = tab.IndexOf(post.StatusId);
5455                             if (idx == -1) continue;  // 該当ポストが存在しないので無視
5456                         }
5457
5458                         foundTab = tab;
5459
5460                         this.selectPostChains.Pop();
5461                     }
5462                     catch (InvalidOperationException)
5463                     {
5464                     }
5465
5466                     break;
5467                 }
5468                 while (this.selectPostChains.Count > 1);
5469
5470                 if (foundTab == null)
5471                 {
5472                     // 状態がおかしいので処理を中断
5473                     // 履歴が残り1つであればクリアしておく
5474                     if (this.selectPostChains.Count == 1)
5475                         this.selectPostChains.Clear();
5476                     return;
5477                 }
5478
5479                 var tabIndex = this.statuses.Tabs.IndexOf(foundTab);
5480                 var tabPage = this.ListTab.TabPages[tabIndex];
5481                 var lst = (DetailsListView)tabPage.Tag;
5482                 this.ListTab.SelectedIndex = tabIndex;
5483
5484                 if (idx > -1)
5485                 {
5486                     this.SelectListItem(lst, idx);
5487                     lst.EnsureVisible(idx);
5488                 }
5489                 lst.Focus();
5490             }
5491         }
5492
5493         private void PushSelectPostChain()
5494         {
5495             var currentTab = this.CurrentTab;
5496             var currentPost = this.CurrentPost;
5497
5498             var count = this.selectPostChains.Count;
5499             if (count > 0)
5500             {
5501                 var (tab, post) = this.selectPostChains.Peek();
5502                 if (tab == currentTab)
5503                 {
5504                     if (post == currentPost) return;  // 最新の履歴と同一
5505                     if (post == null) this.selectPostChains.Pop();  // 置き換えるため削除
5506                 }
5507             }
5508             if (count >= 2500) this.TrimPostChain();
5509             this.selectPostChains.Push((currentTab, currentPost));
5510         }
5511
5512         private void TrimPostChain()
5513         {
5514             if (this.selectPostChains.Count <= 2000) return;
5515             var p = new Stack<(TabModel, PostClass?)>(2000);
5516             for (var i = 0; i < 2000; i++)
5517             {
5518                 p.Push(this.selectPostChains.Pop());
5519             }
5520             this.selectPostChains.Clear();
5521             for (var i = 0; i < 2000; i++)
5522             {
5523                 this.selectPostChains.Push(p.Pop());
5524             }
5525         }
5526
5527         private bool GoStatus(PostId statusId)
5528         {
5529             var tab = this.statuses.Tabs
5530                 .Where(x => x.TabType != MyCommon.TabUsageType.DirectMessage)
5531                 .Where(x => x.Contains(statusId))
5532                 .FirstOrDefault();
5533
5534             if (tab == null)
5535                 return false;
5536
5537             var index = tab.IndexOf(statusId);
5538
5539             var tabIndex = this.statuses.Tabs.IndexOf(tab);
5540             this.ListTab.SelectedIndex = tabIndex;
5541
5542             var listView = this.CurrentListView;
5543             this.SelectListItem(listView, index);
5544             listView.EnsureVisible(index);
5545
5546             return true;
5547         }
5548
5549         private bool GoDirectMessage(PostId statusId)
5550         {
5551             var tab = this.statuses.DirectMessageTab;
5552             var index = tab.IndexOf(statusId);
5553
5554             if (index == -1)
5555                 return false;
5556
5557             var tabIndex = this.statuses.Tabs.IndexOf(tab);
5558             this.ListTab.SelectedIndex = tabIndex;
5559
5560             var listView = this.CurrentListView;
5561             this.SelectListItem(listView, index);
5562             listView.EnsureVisible(index);
5563
5564             return true;
5565         }
5566
5567         private void MyList_MouseClick(object sender, MouseEventArgs e)
5568             => this.CurrentTab.ClearAnchor();
5569
5570         private void StatusText_Enter(object sender, EventArgs e)
5571         {
5572             // フォーカスの戻り先を StatusText に設定
5573             this.Tag = this.StatusText;
5574             this.StatusText.BackColor = this.themeManager.ColorInputBackcolor;
5575         }
5576
5577         public Color InputBackColor
5578             => this.themeManager.ColorInputBackcolor;
5579
5580         private void StatusText_Leave(object sender, EventArgs e)
5581         {
5582             // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
5583             if (this.ListTab.SelectedTab != null && this.MenuStrip1.Tag == null) this.Tag = this.ListTab.SelectedTab.Tag;
5584             this.StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
5585         }
5586
5587         private async void StatusText_KeyDown(object sender, KeyEventArgs e)
5588         {
5589             if (this.CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
5590             {
5591                 e.Handled = true;
5592                 e.SuppressKeyPress = true;
5593             }
5594
5595             this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
5596
5597             if (asyncTask != null)
5598                 await asyncTask;
5599         }
5600
5601         private void SaveConfigsAll(bool ifModified)
5602         {
5603             if (!ifModified)
5604             {
5605                 this.SaveConfigsCommon();
5606                 this.SaveConfigsLocal();
5607                 this.SaveConfigsTabs();
5608                 this.SaveConfigsAtId();
5609             }
5610             else
5611             {
5612                 if (this.ModifySettingCommon) this.SaveConfigsCommon();
5613                 if (this.ModifySettingLocal) this.SaveConfigsLocal();
5614                 if (this.ModifySettingAtId) this.SaveConfigsAtId();
5615             }
5616         }
5617
5618         private void SaveConfigsAtId()
5619         {
5620             if (this.ignoreConfigSave || !this.settings.Common.UseAtIdSupplement && this.AtIdSupl == null) return;
5621
5622             this.ModifySettingAtId = false;
5623             this.settings.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
5624             this.settings.SaveAtIdList();
5625         }
5626
5627         private void SaveConfigsCommon()
5628         {
5629             if (this.ignoreConfigSave) return;
5630
5631             this.ModifySettingCommon = false;
5632             lock (this.syncObject)
5633             {
5634                 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5635                 this.settings.Common.SortColumn = this.statuses.SortMode switch
5636                 {
5637                     ComparerMode.Nickname => 1, // ニックネーム
5638                     ComparerMode.Data => 2, // 本文
5639                     ComparerMode.Id => 3, // 時刻=発言Id
5640                     ComparerMode.Name => 4, // 名前
5641                     ComparerMode.Source => 7, // Source
5642                     _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5643                 };
5644                 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5645                 if (this.HashMgr.IsPermanent)
5646                 {
5647                     this.settings.Common.HashSelected = this.HashMgr.UseHash;
5648                 }
5649                 else
5650                 {
5651                     this.settings.Common.HashSelected = "";
5652                 }
5653                 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5654                 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5655                 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5656                 this.settings.Common.UseImageService = this.ImageSelector.Model.SelectedMediaServiceIndex;
5657                 this.settings.Common.UseImageServiceName = this.ImageSelector.Model.SelectedMediaServiceName;
5658
5659                 this.settings.SaveCommon();
5660             }
5661         }
5662
5663         private void SaveConfigsLocal()
5664         {
5665             if (this.ignoreConfigSave) return;
5666             lock (this.syncObject)
5667             {
5668                 this.ModifySettingLocal = false;
5669                 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5670                 this.settings.Local.FormSize = this.mySize;
5671                 this.settings.Local.FormLocation = this.myLoc;
5672                 this.settings.Local.SplitterDistance = this.mySpDis;
5673                 this.settings.Local.PreviewDistance = this.mySpDis3;
5674                 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5675                 this.settings.Local.StatusTextHeight = this.mySpDis2;
5676
5677                 if (this.ignoreConfigSave) return;
5678                 this.settings.SaveLocal();
5679             }
5680         }
5681
5682         private void SaveConfigsTabs()
5683         {
5684             var tabSettingList = new List<SettingTabs.SettingTabItem>();
5685
5686             var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5687
5688             foreach (var tab in tabs)
5689             {
5690                 if (!tab.IsPermanentTabType)
5691                     continue;
5692
5693                 var tabSetting = new SettingTabs.SettingTabItem
5694                 {
5695                     TabName = tab.TabName,
5696                     TabType = tab.TabType,
5697                     UnreadManage = tab.UnreadManage,
5698                     Protected = tab.Protected,
5699                     Notify = tab.Notify,
5700                     SoundFile = tab.SoundFile,
5701                 };
5702
5703                 switch (tab)
5704                 {
5705                     case FilterTabModel filterTab:
5706                         tabSetting.FilterArray = filterTab.FilterArray;
5707                         break;
5708                     case UserTimelineTabModel userTab:
5709                         tabSetting.User = userTab.ScreenName;
5710                         tabSetting.UserId = userTab.UserId;
5711                         break;
5712                     case PublicSearchTabModel searchTab:
5713                         tabSetting.SearchWords = searchTab.SearchWords;
5714                         tabSetting.SearchLang = searchTab.SearchLang;
5715                         break;
5716                     case ListTimelineTabModel listTab:
5717                         tabSetting.ListInfo = listTab.ListInfo;
5718                         break;
5719                 }
5720
5721                 tabSettingList.Add(tabSetting);
5722             }
5723
5724             this.settings.Tabs.Tabs = tabSettingList;
5725             this.settings.SaveTabs();
5726         }
5727
5728         private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5729         {
5730             static void ShowFormatErrorDialog(IWin32Window owner)
5731             {
5732                 MessageBox.Show(
5733                     owner,
5734                     Properties.Resources.OpenURL_InvalidFormat,
5735                     Properties.Resources.OpenURL_Caption,
5736                     MessageBoxButtons.OK,
5737                     MessageBoxIcon.Error
5738                 );
5739             }
5740
5741             var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5742             if (ret != DialogResult.OK)
5743                 return;
5744
5745             var match = Twitter.StatusUrlRegex.Match(inputText);
5746             if (!match.Success)
5747             {
5748                 ShowFormatErrorDialog(this);
5749                 return;
5750             }
5751
5752             try
5753             {
5754                 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
5755                 await this.OpenRelatedTab(statusId);
5756             }
5757             catch (OverflowException)
5758             {
5759                 ShowFormatErrorDialog(this);
5760             }
5761             catch (TabException ex)
5762             {
5763                 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5764             }
5765         }
5766
5767         private void SaveLogMenuItem_Click(object sender, EventArgs e)
5768         {
5769             var tab = this.CurrentTab;
5770
5771             var rslt = MessageBox.Show(
5772                 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5773                 Properties.Resources.SaveLogMenuItem_ClickText2,
5774                 MessageBoxButtons.YesNoCancel,
5775                 MessageBoxIcon.Question);
5776             if (rslt == DialogResult.Cancel) return;
5777
5778             this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5779             this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5780             this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5781             this.SaveFileDialog1.FilterIndex = 0;
5782             this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5783             this.SaveFileDialog1.RestoreDirectory = true;
5784
5785             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5786             {
5787                 if (!this.SaveFileDialog1.ValidateNames) return;
5788                 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5789                 if (rslt == DialogResult.Yes)
5790                 {
5791                     // All
5792                     for (var idx = 0; idx < tab.AllCount; idx++)
5793                     {
5794                         var post = tab[idx];
5795                         var protect = "";
5796                         if (post.IsProtect)
5797                             protect = "Protect";
5798                         sw.WriteLine(post.Nickname + "\t" +
5799                                  "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5800                                  post.CreatedAt.ToLocalTimeString() + "\t" +
5801                                  post.ScreenName + "\t" +
5802                                  post.StatusId.Id + "\t" +
5803                                  post.ImageUrl + "\t" +
5804                                  "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5805                                  protect);
5806                     }
5807                 }
5808                 else
5809                 {
5810                     foreach (var post in this.CurrentTab.SelectedPosts)
5811                     {
5812                         var protect = "";
5813                         if (post.IsProtect)
5814                             protect = "Protect";
5815                         sw.WriteLine(post.Nickname + "\t" +
5816                                  "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5817                                  post.CreatedAt.ToLocalTimeString() + "\t" +
5818                                  post.ScreenName + "\t" +
5819                                  post.StatusId.Id + "\t" +
5820                                  post.ImageUrl + "\t" +
5821                                  "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5822                                  protect);
5823                     }
5824                 }
5825             }
5826             this.TopMost = this.settings.Common.AlwaysTop;
5827         }
5828
5829         public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5830         {
5831             // タブ名変更
5832             newTabName = null;
5833             using (var inputName = new InputTabName())
5834             {
5835                 inputName.TabName = origTabName;
5836                 inputName.ShowDialog();
5837                 if (inputName.DialogResult == DialogResult.Cancel) return false;
5838                 newTabName = inputName.TabName;
5839             }
5840             this.TopMost = this.settings.Common.AlwaysTop;
5841             if (!MyCommon.IsNullOrEmpty(newTabName))
5842             {
5843                 // 新タブ名存在チェック
5844                 if (this.statuses.ContainsTab(newTabName))
5845                 {
5846                     var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5847                     MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5848                     return false;
5849                 }
5850
5851                 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5852                 var tabPage = this.ListTab.TabPages[tabIndex];
5853
5854                 // タブ名を変更
5855                 if (tabPage != null)
5856                     tabPage.Text = newTabName;
5857
5858                 this.statuses.RenameTab(origTabName, newTabName);
5859
5860                 var state = this.listViewState[origTabName];
5861                 this.listViewState.Remove(origTabName);
5862                 this.listViewState[newTabName] = state;
5863
5864                 this.SaveConfigsCommon();
5865                 this.SaveConfigsTabs();
5866                 this.rclickTabName = newTabName;
5867                 return true;
5868             }
5869             else
5870             {
5871                 return false;
5872             }
5873         }
5874
5875         private void ListTab_MouseClick(object sender, MouseEventArgs e)
5876         {
5877             if (e.Button == MouseButtons.Middle)
5878             {
5879                 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5880                 {
5881                     if (this.ListTab.GetTabRect(index).Contains(e.Location))
5882                     {
5883                         this.RemoveSpecifiedTab(tab.TabName, true);
5884                         this.SaveConfigsTabs();
5885                         break;
5886                     }
5887                 }
5888             }
5889         }
5890
5891         private void ListTab_DoubleClick(object sender, MouseEventArgs e)
5892             => this.TabRename(this.CurrentTabName, out _);
5893
5894         private void ListTab_MouseDown(object sender, MouseEventArgs e)
5895         {
5896             if (this.settings.Common.TabMouseLock) return;
5897             if (e.Button == MouseButtons.Left)
5898             {
5899                 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
5900                 {
5901                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
5902                     {
5903                         this.tabDrag = true;
5904                         this.tabMouseDownPoint = e.Location;
5905                         break;
5906                     }
5907                 }
5908             }
5909             else
5910             {
5911                 this.tabDrag = false;
5912             }
5913         }
5914
5915         private void ListTab_DragEnter(object sender, DragEventArgs e)
5916         {
5917             if (e.Data.GetDataPresent(typeof(TabPage)))
5918                 e.Effect = DragDropEffects.Move;
5919             else
5920                 e.Effect = DragDropEffects.None;
5921         }
5922
5923         private void ListTab_DragDrop(object sender, DragEventArgs e)
5924         {
5925             if (!e.Data.GetDataPresent(typeof(TabPage))) return;
5926
5927             this.tabDrag = false;
5928             var tn = "";
5929             var bef = false;
5930             var cpos = new Point(e.X, e.Y);
5931             var spos = this.ListTab.PointToClient(cpos);
5932             foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5933             {
5934                 var rect = this.ListTab.GetTabRect(index);
5935                 if (rect.Contains(spos))
5936                 {
5937                     tn = tab.TabName;
5938                     if (spos.X <= (rect.Left + rect.Right) / 2)
5939                         bef = true;
5940                     else
5941                         bef = false;
5942
5943                     break;
5944                 }
5945             }
5946
5947             // タブのないところにドロップ->最後尾へ移動
5948             if (MyCommon.IsNullOrEmpty(tn))
5949             {
5950                 var lastTab = this.statuses.Tabs.Last();
5951                 tn = lastTab.TabName;
5952                 bef = false;
5953             }
5954
5955             var tp = (TabPage)e.Data.GetData(typeof(TabPage));
5956             if (tp.Text == tn) return;
5957
5958             this.ReOrderTab(tp.Text, tn, bef);
5959         }
5960
5961         public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
5962         {
5963             var baseIndex = this.GetTabPageIndex(baseTabText);
5964             if (baseIndex == -1)
5965                 return;
5966
5967             var targetIndex = this.GetTabPageIndex(targetTabText);
5968             if (targetIndex == -1)
5969                 return;
5970
5971             using (ControlTransaction.Layout(this.ListTab))
5972             {
5973                 // 選択中のタブを Remove メソッドで取り外すと選択状態が変化して Selecting イベントが発生するが、
5974                 // この時 TabInformations と TabControl の並び順が不一致なままで ListTabSelect メソッドが呼ばれてしまう。
5975                 // これを防ぐために、Remove メソッドを呼ぶ前に選択中のタブを切り替えておく必要がある
5976                 this.ListTab.SelectedIndex = targetIndex == 0 ? 1 : 0;
5977
5978                 var tab = this.statuses.Tabs[targetIndex];
5979                 var tabPage = this.ListTab.TabPages[targetIndex];
5980
5981                 this.ListTab.TabPages.Remove(tabPage);
5982
5983                 if (targetIndex < baseIndex)
5984                     baseIndex--;
5985
5986                 if (!isBeforeBaseTab)
5987                     baseIndex++;
5988
5989                 this.statuses.MoveTab(baseIndex, tab);
5990
5991                 this.ListTab.TabPages.Insert(baseIndex, tabPage);
5992             }
5993
5994             this.SaveConfigsTabs();
5995         }
5996
5997         private void MakeDirectMessageText()
5998         {
5999             var selectedPosts = this.CurrentTab.SelectedPosts;
6000             if (selectedPosts.Length > 1)
6001                 return;
6002
6003             var post = selectedPosts.Single();
6004             var text = $"D {post.ScreenName} {this.StatusText.Text}";
6005
6006             this.inReplyTo = null;
6007             this.StatusText.Text = text;
6008             this.StatusText.SelectionStart = text.Length;
6009             this.StatusText.Focus();
6010         }
6011
6012         private void MakeReplyText(bool atAll = false)
6013         {
6014             var selectedPosts = this.CurrentTab.SelectedPosts;
6015             if (selectedPosts.Any(x => x.IsDm))
6016             {
6017                 this.MakeDirectMessageText();
6018                 return;
6019             }
6020
6021             if (selectedPosts.Length == 1)
6022             {
6023                 var post = selectedPosts.Single();
6024                 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6025                 var inReplyToScreenName = post.ScreenName;
6026                 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6027             }
6028             else
6029             {
6030                 this.inReplyTo = null;
6031             }
6032
6033             var selfScreenName = this.tw.Username;
6034             var targetScreenNames = new List<string>();
6035             foreach (var post in selectedPosts)
6036             {
6037                 if (post.ScreenName != selfScreenName)
6038                     targetScreenNames.Add(post.ScreenName);
6039
6040                 if (atAll)
6041                 {
6042                     foreach (var (_, screenName) in post.ReplyToList)
6043                     {
6044                         if (screenName != selfScreenName)
6045                             targetScreenNames.Add(screenName);
6046                     }
6047                 }
6048             }
6049
6050             if (this.inReplyTo != null)
6051             {
6052                 var (_, screenName) = this.inReplyTo.Value;
6053                 if (screenName == selfScreenName)
6054                     targetScreenNames.Insert(0, screenName);
6055             }
6056
6057             var text = this.StatusText.Text;
6058             foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6059             {
6060                 var atText = $"@{screenName} ";
6061                 if (!text.Contains(atText))
6062                     text = atText + text;
6063             }
6064
6065             this.StatusText.Text = text;
6066             this.StatusText.SelectionStart = text.Length;
6067             this.StatusText.Focus();
6068         }
6069
6070         private void ListTab_MouseUp(object sender, MouseEventArgs e)
6071             => this.tabDrag = false;
6072
6073         private int iconCnt = 0;
6074         private int blinkCnt = 0;
6075         private bool blink = false;
6076
6077         private void RefreshTasktrayIcon()
6078         {
6079             void EnableTasktrayAnimation()
6080                 => this.TimerRefreshIcon.Enabled = true;
6081
6082             void DisableTasktrayAnimation()
6083                 => this.TimerRefreshIcon.Enabled = false;
6084
6085             var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6086             if (busyTasks)
6087             {
6088                 this.iconCnt += 1;
6089                 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6090                     this.iconCnt = 0;
6091
6092                 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6093                 this.myStatusError = false;
6094                 EnableTasktrayAnimation();
6095                 return;
6096             }
6097
6098             var replyIconType = this.settings.Common.ReplyIconState;
6099             var reply = false;
6100             if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6101             {
6102                 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6103                 if (replyTab != null && replyTab.UnreadCount > 0)
6104                     reply = true;
6105             }
6106
6107             if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6108             {
6109                 this.blinkCnt += 1;
6110                 if (this.blinkCnt > 10)
6111                     this.blinkCnt = 0;
6112
6113                 if (this.blinkCnt == 0)
6114                     this.blink = !this.blink;
6115
6116                 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6117                 EnableTasktrayAnimation();
6118                 return;
6119             }
6120
6121             DisableTasktrayAnimation();
6122
6123             this.iconCnt = 0;
6124             this.blinkCnt = 0;
6125             this.blink = false;
6126
6127             // 優先度:リプライ→エラー→オフライン→アイドル
6128             // エラーは更新アイコンでクリアされる
6129             if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6130                 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6131             else if (this.myStatusError)
6132                 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6133             else if (this.myStatusOnline)
6134                 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6135             else
6136                 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6137         }
6138
6139         private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6140             => this.RefreshTasktrayIcon(); // 200ms
6141
6142         private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6143         {
6144             // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6145             if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6146                 this.rclickTabName = this.CurrentTabName;
6147
6148             if (this.statuses == null) return;
6149             if (this.statuses.Tabs == null) return;
6150
6151             if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6152                 return;
6153
6154             this.NotifyDispMenuItem.Checked = tb.Notify;
6155             this.NotifyTbMenuItem.Checked = tb.Notify;
6156
6157             this.soundfileListup = true;
6158             this.SoundFileComboBox.Items.Clear();
6159             this.SoundFileTbComboBox.Items.Clear();
6160             this.SoundFileComboBox.Items.Add("");
6161             this.SoundFileTbComboBox.Items.Add("");
6162             var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6163             if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6164             {
6165                 oDir = oDir.GetDirectories("Sounds")[0];
6166             }
6167             foreach (var oFile in oDir.GetFiles("*.wav"))
6168             {
6169                 this.SoundFileComboBox.Items.Add(oFile.Name);
6170                 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6171             }
6172             var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6173             if (idx == -1) idx = 0;
6174             this.SoundFileComboBox.SelectedIndex = idx;
6175             this.SoundFileTbComboBox.SelectedIndex = idx;
6176             this.soundfileListup = false;
6177             this.UreadManageMenuItem.Checked = tb.UnreadManage;
6178             this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6179
6180             this.TabMenuControl(this.rclickTabName);
6181         }
6182
6183         private void TabMenuControl(string tabName)
6184         {
6185             var tabInfo = this.statuses.GetTabByName(tabName)!;
6186
6187             this.FilterEditMenuItem.Enabled = true;
6188             this.EditRuleTbMenuItem.Enabled = true;
6189
6190             if (tabInfo.IsDefaultTabType)
6191             {
6192                 this.ProtectTabMenuItem.Enabled = false;
6193                 this.ProtectTbMenuItem.Enabled = false;
6194             }
6195             else
6196             {
6197                 this.ProtectTabMenuItem.Enabled = true;
6198                 this.ProtectTbMenuItem.Enabled = true;
6199             }
6200
6201             if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6202             {
6203                 this.ProtectTabMenuItem.Checked = true;
6204                 this.ProtectTbMenuItem.Checked = true;
6205                 this.DeleteTabMenuItem.Enabled = false;
6206                 this.DeleteTbMenuItem.Enabled = false;
6207             }
6208             else
6209             {
6210                 this.ProtectTabMenuItem.Checked = false;
6211                 this.ProtectTbMenuItem.Checked = false;
6212                 this.DeleteTabMenuItem.Enabled = true;
6213                 this.DeleteTbMenuItem.Enabled = true;
6214             }
6215         }
6216
6217         private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6218         {
6219             var checkState = ((ToolStripMenuItem)sender).Checked;
6220
6221             // チェック状態を同期
6222             this.ProtectTbMenuItem.Checked = checkState;
6223             this.ProtectTabMenuItem.Checked = checkState;
6224
6225             // ロック中はタブの削除を無効化
6226             this.DeleteTabMenuItem.Enabled = !checkState;
6227             this.DeleteTbMenuItem.Enabled = !checkState;
6228
6229             if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6230             this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6231
6232             this.SaveConfigsTabs();
6233         }
6234
6235         private void UreadManageMenuItem_Click(object sender, EventArgs e)
6236         {
6237             this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6238             this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6239
6240             if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6241             this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6242
6243             this.SaveConfigsTabs();
6244         }
6245
6246         public void ChangeTabUnreadManage(string tabName, bool isManage)
6247         {
6248             var idx = this.GetTabPageIndex(tabName);
6249             if (idx == -1)
6250                 return;
6251
6252             var tab = this.statuses.Tabs[tabName];
6253             tab.UnreadManage = isManage;
6254
6255             if (this.settings.Common.TabIconDisp)
6256             {
6257                 var tabPage = this.ListTab.TabPages[idx];
6258                 if (tab.UnreadCount > 0)
6259                     tabPage.ImageIndex = 0;
6260                 else
6261                     tabPage.ImageIndex = -1;
6262             }
6263
6264             if (this.CurrentTabName == tabName)
6265             {
6266                 this.listCache?.PurgeCache();
6267                 this.CurrentListView.Refresh();
6268             }
6269
6270             this.SetMainWindowTitle();
6271             this.SetStatusLabelUrl();
6272             if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6273         }
6274
6275         private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6276         {
6277             this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6278             this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6279
6280             if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6281
6282             this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6283
6284             this.SaveConfigsTabs();
6285         }
6286
6287         private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6288         {
6289             if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6290
6291             this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6292
6293             this.SaveConfigsTabs();
6294         }
6295
6296         private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6297         {
6298             if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6299                 this.rclickTabName = this.CurrentTabName;
6300
6301             this.RemoveSpecifiedTab(this.rclickTabName, true);
6302             this.SaveConfigsTabs();
6303         }
6304
6305         private void FilterEditMenuItem_Click(object sender, EventArgs e)
6306         {
6307             if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6308
6309             using (var fltDialog = new FilterDialog())
6310             {
6311                 fltDialog.Owner = this;
6312                 fltDialog.SetCurrent(this.rclickTabName);
6313                 fltDialog.ShowDialog(this);
6314             }
6315             this.TopMost = this.settings.Common.AlwaysTop;
6316
6317             this.ApplyPostFilters();
6318             this.SaveConfigsTabs();
6319         }
6320
6321         private async void AddTabMenuItem_Click(object sender, EventArgs e)
6322         {
6323             string? tabName = null;
6324             MyCommon.TabUsageType tabUsage;
6325             using (var inputName = new InputTabName())
6326             {
6327                 inputName.TabName = this.statuses.MakeTabName("MyTab");
6328                 inputName.IsShowUsage = true;
6329                 inputName.ShowDialog();
6330                 if (inputName.DialogResult == DialogResult.Cancel) return;
6331                 tabName = inputName.TabName;
6332                 tabUsage = inputName.Usage;
6333             }
6334             this.TopMost = this.settings.Common.AlwaysTop;
6335             if (!MyCommon.IsNullOrEmpty(tabName))
6336             {
6337                 // List対応
6338                 ListElement? list = null;
6339                 if (tabUsage == MyCommon.TabUsageType.Lists)
6340                 {
6341                     using var listAvail = new ListAvailable();
6342                     if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6343                         return;
6344                     if (listAvail.SelectedList == null)
6345                         return;
6346                     list = listAvail.SelectedList;
6347                 }
6348
6349                 TabModel tab;
6350                 switch (tabUsage)
6351                 {
6352                     case MyCommon.TabUsageType.UserDefined:
6353                         tab = new FilterTabModel(tabName);
6354                         break;
6355                     case MyCommon.TabUsageType.PublicSearch:
6356                         tab = new PublicSearchTabModel(tabName);
6357                         break;
6358                     case MyCommon.TabUsageType.Lists:
6359                         tab = new ListTimelineTabModel(tabName, list!);
6360                         break;
6361                     default:
6362                         return;
6363                 }
6364
6365                 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6366                 {
6367                     var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6368                     MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6369                 }
6370                 else
6371                 {
6372                     // 成功
6373                     this.SaveConfigsTabs();
6374
6375                     var tabIndex = this.statuses.Tabs.Count - 1;
6376
6377                     if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6378                     {
6379                         this.ListTab.SelectedIndex = tabIndex;
6380                         this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6381                     }
6382                     if (tabUsage == MyCommon.TabUsageType.Lists)
6383                     {
6384                         this.ListTab.SelectedIndex = tabIndex;
6385                         await this.RefreshTabAsync(this.CurrentTab);
6386                     }
6387                 }
6388             }
6389         }
6390
6391         private void TabMenuItem_Click(object sender, EventArgs e)
6392         {
6393             // 選択発言を元にフィルタ追加
6394             foreach (var post in this.CurrentTab.SelectedPosts)
6395             {
6396                 // タブ選択(or追加)
6397                 if (!this.SelectTab(out var tab))
6398                     return;
6399
6400                 using (var fltDialog = new FilterDialog())
6401                 {
6402                     fltDialog.Owner = this;
6403                     fltDialog.SetCurrent(tab.TabName);
6404
6405                     if (post.RetweetedBy == null)
6406                     {
6407                         fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6408                     }
6409                     else
6410                     {
6411                         fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6412                     }
6413                     fltDialog.ShowDialog(this);
6414                 }
6415
6416                 this.TopMost = this.settings.Common.AlwaysTop;
6417             }
6418
6419             this.ApplyPostFilters();
6420             this.SaveConfigsTabs();
6421         }
6422
6423         protected override bool ProcessDialogKey(Keys keyData)
6424         {
6425             // TextBox1でEnterを押してもビープ音が鳴らないようにする
6426             if ((keyData & Keys.KeyCode) == Keys.Enter)
6427             {
6428                 if (this.StatusText.Focused)
6429                 {
6430                     var newLine = false;
6431                     var post = false;
6432
6433                     if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6434                     {
6435                         if (this.StatusText.Multiline)
6436                         {
6437                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6438
6439                             if ((keyData & Keys.Control) == Keys.Control) post = true;
6440                         }
6441                         else
6442                         {
6443                             if ((keyData & Keys.Control) == Keys.Control) post = true;
6444                         }
6445                     }
6446                     else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6447                     {
6448                         if (this.StatusText.Multiline)
6449                         {
6450                             if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6451
6452                             if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6453                         }
6454                         else
6455                         {
6456                             if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6457                         }
6458                     }
6459                     else // Enter投稿時
6460                     {
6461                         if (this.StatusText.Multiline)
6462                         {
6463                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6464
6465                             if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6466                                 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6467                         }
6468                         else
6469                         {
6470                             if (((keyData & Keys.Shift) == Keys.Shift) ||
6471                                 (((keyData & Keys.Control) != Keys.Control) &&
6472                                 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6473                         }
6474                     }
6475
6476                     if (newLine)
6477                     {
6478                         var pos1 = this.StatusText.SelectionStart;
6479                         if (this.StatusText.SelectionLength > 0)
6480                         {
6481                             this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength);  // 選択状態文字列削除
6482                         }
6483                         this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine);  // 改行挿入
6484                         this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length;    // カーソルを改行の次の文字へ移動
6485                         return true;
6486                     }
6487                     else if (post)
6488                     {
6489                         this.PostButton_Click(this.PostButton, EventArgs.Empty);
6490                         return true;
6491                     }
6492                 }
6493                 else
6494                 {
6495                     var tab = this.CurrentTab;
6496                     if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6497                     {
6498                         var tabPage = this.CurrentTabPage;
6499                         if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6500                             tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6501                         {
6502                             this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6503                             return true;
6504                         }
6505                     }
6506                 }
6507             }
6508
6509             return base.ProcessDialogKey(keyData);
6510         }
6511
6512         private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6513             => this.MakeReplyText(atAll: true);
6514
6515         private void IDRuleMenuItem_Click(object sender, EventArgs e)
6516         {
6517             var tab = this.CurrentTab;
6518             var selectedPosts = tab.SelectedPosts;
6519
6520             // 未選択なら処理終了
6521             if (selectedPosts.Length == 0)
6522                 return;
6523
6524             var screenNameArray = selectedPosts
6525                 .Select(x => x.RetweetedBy ?? x.ScreenName)
6526                 .ToArray();
6527
6528             this.AddFilterRuleByScreenName(screenNameArray);
6529
6530             if (screenNameArray.Length != 0)
6531             {
6532                 var atids = new List<string>();
6533                 foreach (var screenName in screenNameArray)
6534                 {
6535                     atids.Add("@" + screenName);
6536                 }
6537                 var cnt = this.AtIdSupl.ItemCount;
6538                 this.AtIdSupl.AddRangeItem(atids.ToArray());
6539                 if (this.AtIdSupl.ItemCount != cnt)
6540                     this.MarkSettingAtIdModified();
6541             }
6542         }
6543
6544         private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6545         {
6546             var tab = this.CurrentTab;
6547             var selectedPosts = tab.SelectedPosts;
6548
6549             if (selectedPosts.Length == 0)
6550                 return;
6551
6552             var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6553
6554             this.AddFilterRuleBySource(sourceArray);
6555         }
6556
6557         public void AddFilterRuleByScreenName(params string[] screenNameArray)
6558         {
6559             // タブ選択(or追加)
6560             if (!this.SelectTab(out var tab)) return;
6561
6562             bool mv;
6563             bool mk;
6564             if (tab.TabType != MyCommon.TabUsageType.Mute)
6565             {
6566                 this.MoveOrCopy(out mv, out mk);
6567             }
6568             else
6569             {
6570                 // ミュートタブでは常に MoveMatches を true にする
6571                 mv = true;
6572                 mk = false;
6573             }
6574
6575             foreach (var screenName in screenNameArray)
6576             {
6577                 tab.AddFilter(new PostFilterRule
6578                 {
6579                     FilterName = screenName,
6580                     UseNameField = true,
6581                     MoveMatches = mv,
6582                     MarkMatches = mk,
6583                     UseRegex = false,
6584                     FilterByUrl = false,
6585                 });
6586             }
6587
6588             this.ApplyPostFilters();
6589             this.SaveConfigsTabs();
6590         }
6591
6592         public void AddFilterRuleBySource(params string[] sourceArray)
6593         {
6594             // タブ選択ダイアログを表示(or追加)
6595             if (!this.SelectTab(out var filterTab))
6596                 return;
6597
6598             bool mv;
6599             bool mk;
6600             if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6601             {
6602                 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6603                 this.MoveOrCopy(out mv, out mk);
6604             }
6605             else
6606             {
6607                 // ミュートタブでは常に MoveMatches を true にする
6608                 mv = true;
6609                 mk = false;
6610             }
6611
6612             // 振り分けルールに追加するSource
6613             foreach (var source in sourceArray)
6614             {
6615                 filterTab.AddFilter(new PostFilterRule
6616                 {
6617                     FilterSource = source,
6618                     MoveMatches = mv,
6619                     MarkMatches = mk,
6620                     UseRegex = false,
6621                     FilterByUrl = false,
6622                 });
6623             }
6624
6625             this.ApplyPostFilters();
6626             this.SaveConfigsTabs();
6627         }
6628
6629         private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6630         {
6631             do
6632             {
6633                 tab = null;
6634
6635                 // 振り分け先タブ選択
6636                 using (var dialog = new TabsDialog(this.statuses))
6637                 {
6638                     if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6639
6640                     tab = dialog.SelectedTab;
6641                 }
6642
6643                 this.CurrentTabPage.Focus();
6644                 // 新規タブを選択→タブ作成
6645                 if (tab == null)
6646                 {
6647                     string tabName;
6648                     using (var inputName = new InputTabName())
6649                     {
6650                         inputName.TabName = this.statuses.MakeTabName("MyTab");
6651                         inputName.ShowDialog();
6652                         if (inputName.DialogResult == DialogResult.Cancel) return false;
6653                         tabName = inputName.TabName;
6654                     }
6655                     this.TopMost = this.settings.Common.AlwaysTop;
6656                     if (!MyCommon.IsNullOrEmpty(tabName))
6657                     {
6658                         var newTab = new FilterTabModel(tabName);
6659                         if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6660                         {
6661                             var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6662                             MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6663                             // もう一度タブ名入力
6664                         }
6665                         else
6666                         {
6667                             tab = newTab;
6668                             return true;
6669                         }
6670                     }
6671                 }
6672                 else
6673                 {
6674                     // 既存タブを選択
6675                     return true;
6676                 }
6677             }
6678             while (true);
6679         }
6680
6681         private void MoveOrCopy(out bool move, out bool mark)
6682         {
6683             {
6684                 // 移動するか?
6685                 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6686                 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6687                     move = false;
6688                 else
6689                     move = true;
6690             }
6691             if (!move)
6692             {
6693                 // マークするか?
6694                 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6695                 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6696                     mark = true;
6697                 else
6698                     mark = false;
6699             }
6700             else
6701             {
6702                 mark = false;
6703             }
6704         }
6705
6706         private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6707             => this.CopyStot();
6708
6709         private void CopyURLMenuItem_Click(object sender, EventArgs e)
6710             => this.CopyIdUri();
6711
6712         private void SelectAllMenuItem_Click(object sender, EventArgs e)
6713         {
6714             if (this.StatusText.Focused)
6715             {
6716                 // 発言欄でのCtrl+A
6717                 this.StatusText.SelectAll();
6718             }
6719             else
6720             {
6721                 // ListView上でのCtrl+A
6722                 NativeMethods.SelectAllItems(this.CurrentListView);
6723             }
6724         }
6725
6726         private void MoveMiddle()
6727         {
6728             ListViewItem item;
6729             int idx1;
6730             int idx2;
6731
6732             var listView = this.CurrentListView;
6733             if (listView.SelectedIndices.Count == 0) return;
6734
6735             var idx = listView.SelectedIndices[0];
6736
6737             item = listView.GetItemAt(0, 25);
6738             if (item == null)
6739                 idx1 = 0;
6740             else
6741                 idx1 = item.Index;
6742
6743             item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6744             if (item == null)
6745                 idx2 = listView.VirtualListSize - 1;
6746             else
6747                 idx2 = item.Index;
6748
6749             idx -= Math.Abs(idx1 - idx2) / 2;
6750             if (idx < 0) idx = 0;
6751
6752             listView.EnsureVisible(listView.VirtualListSize - 1);
6753             listView.EnsureVisible(idx);
6754         }
6755
6756         private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6757         {
6758             var linkElements = this.tweetDetailsView.GetLinkElements();
6759
6760             if (linkElements.Length == 0)
6761                 return;
6762
6763             var links = new List<OpenUrlItem>(linkElements.Length);
6764
6765             foreach (var linkElm in linkElements)
6766             {
6767                 var displayUrl = linkElm.GetAttribute("title");
6768                 var href = linkElm.GetAttribute("href");
6769                 var linkedText = linkElm.InnerText;
6770
6771                 if (MyCommon.IsNullOrEmpty(displayUrl))
6772                     displayUrl = href;
6773
6774                 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6775             }
6776
6777             string selectedUrl;
6778             bool isReverseSettings;
6779
6780             if (links.Count == 1)
6781             {
6782                 // ツイートに含まれる URL が 1 つのみの場合
6783                 //   => OpenURL ダイアログを表示せずにリンクを開く
6784                 selectedUrl = links[0].Href;
6785
6786                 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6787                 isReverseSettings = false;
6788             }
6789             else
6790             {
6791                 // ツイートに含まれる URL が複数ある場合
6792                 //   => OpenURL を表示しユーザーが選択したリンクを開く
6793                 this.urlDialog.ClearUrl();
6794
6795                 foreach (var link in links)
6796                     this.urlDialog.AddUrl(link);
6797
6798                 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6799                     return;
6800
6801                 this.TopMost = this.settings.Common.AlwaysTop;
6802
6803                 selectedUrl = this.urlDialog.SelectedUrl;
6804
6805                 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6806                 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6807             }
6808
6809             await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6810         }
6811
6812         private void ClearTabMenuItem_Click(object sender, EventArgs e)
6813         {
6814             if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6815             this.ClearTab(this.rclickTabName, true);
6816         }
6817
6818         private void ClearTab(string tabName, bool showWarning)
6819         {
6820             if (showWarning)
6821             {
6822                 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6823                 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6824                 {
6825                     return;
6826                 }
6827             }
6828
6829             this.statuses.ClearTabIds(tabName);
6830             if (this.CurrentTabName == tabName)
6831             {
6832                 this.CurrentTab.ClearAnchor();
6833                 this.listCache?.PurgeCache();
6834                 this.listCache?.UpdateListSize();
6835             }
6836
6837             var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6838             var tabPage = this.ListTab.TabPages[tabIndex];
6839             tabPage.ImageIndex = -1;
6840
6841             if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6842
6843             this.SetMainWindowTitle();
6844             this.SetStatusLabelUrl();
6845         }
6846
6847         private static long followers = 0;
6848
6849         private void SetMainWindowTitle()
6850         {
6851             // メインウインドウタイトルの書き換え
6852             var ttl = new StringBuilder(256);
6853             var ur = 0;
6854             var al = 0;
6855             if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6856                 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6857                 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6858                 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6859             {
6860                 foreach (var tab in this.statuses.Tabs)
6861                 {
6862                     ur += tab.UnreadCount;
6863                     al += tab.AllCount;
6864                 }
6865             }
6866
6867             if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6868             ttl.Append(ApplicationSettings.ApplicationName);
6869             ttl.Append("  ");
6870             switch (this.settings.Common.DispLatestPost)
6871             {
6872                 case MyCommon.DispTitleEnum.Ver:
6873                     ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6874                     break;
6875                 case MyCommon.DispTitleEnum.Post:
6876                     if (this.history.Peek() is { } lastItem)
6877                         ttl.Append(lastItem.Status.Replace("\r\n", " "));
6878                     break;
6879                 case MyCommon.DispTitleEnum.UnreadRepCount:
6880                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6881                     break;
6882                 case MyCommon.DispTitleEnum.UnreadAllCount:
6883                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6884                     break;
6885                 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6886                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6887                     break;
6888                 case MyCommon.DispTitleEnum.UnreadCountAllCount:
6889                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
6890                     break;
6891                 case MyCommon.DispTitleEnum.OwnStatus:
6892                     if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
6893                     ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
6894                     break;
6895             }
6896
6897             try
6898             {
6899                 this.Text = ttl.ToString();
6900             }
6901             catch (AccessViolationException)
6902             {
6903                 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
6904             }
6905         }
6906
6907         private string GetStatusLabelText()
6908         {
6909             // ステータス欄にカウント表示
6910             // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
6911             if (this.statuses == null) return "";
6912             var tbRep = this.statuses.MentionTab;
6913             var tbDm = this.statuses.DirectMessageTab;
6914             if (tbRep == null || tbDm == null) return "";
6915             var urat = tbRep.UnreadCount + tbDm.UnreadCount;
6916             var ur = 0;
6917             var al = 0;
6918             var tur = 0;
6919             var tal = 0;
6920             var slbl = new StringBuilder(256);
6921             try
6922             {
6923                 foreach (var tab in this.statuses.Tabs)
6924                 {
6925                     ur += tab.UnreadCount;
6926                     al += tab.AllCount;
6927                     if (tab.TabName == this.CurrentTabName)
6928                     {
6929                         tur = tab.UnreadCount;
6930                         tal = tab.AllCount;
6931                     }
6932                 }
6933             }
6934             catch (Exception)
6935             {
6936                 return "";
6937             }
6938
6939             this.unreadCounter = ur;
6940             this.unreadAtCounter = urat;
6941
6942             var homeTab = this.statuses.HomeTab;
6943
6944             slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
6945             if (this.settings.Common.TimelinePeriod == 0)
6946             {
6947                 slbl.Append(Properties.Resources.SetStatusLabelText2);
6948             }
6949             else
6950             {
6951                 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
6952             }
6953             return slbl.ToString();
6954         }
6955
6956         private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
6957         {
6958             try
6959             {
6960                 if (this.InvokeRequired && !this.IsDisposed)
6961                 {
6962                     await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
6963                 }
6964                 else
6965                 {
6966                     var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
6967                     this.SetApiStatusLabel(endpointName);
6968                 }
6969             }
6970             catch (ObjectDisposedException)
6971             {
6972                 return;
6973             }
6974             catch (InvalidOperationException)
6975             {
6976                 return;
6977             }
6978         }
6979
6980         private void SetApiStatusLabel(string? endpointName = null)
6981         {
6982             var tabType = this.CurrentTab.TabType;
6983
6984             if (endpointName == null)
6985             {
6986                 var authByCookie = this.tw.Api.AuthType == APIAuthType.TwitterComCookie;
6987
6988                 // 表示中のタブに応じて更新
6989                 endpointName = tabType switch
6990                 {
6991                     MyCommon.TabUsageType.Home => "/statuses/home_timeline",
6992                     MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
6993                     MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
6994                     MyCommon.TabUsageType.Favorites => "/favorites/list",
6995                     MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
6996                     MyCommon.TabUsageType.UserTimeline =>
6997                         authByCookie ? UserTweetsAndRepliesRequest.EndpointName : "/statuses/user_timeline",
6998                     MyCommon.TabUsageType.Lists =>
6999                         authByCookie ? ListLatestTweetsTimelineRequest.EndpointName : "/lists/statuses",
7000                     MyCommon.TabUsageType.PublicSearch =>
7001                         authByCookie ? SearchTimelineRequest.EndpointName : "/search/tweets",
7002                     MyCommon.TabUsageType.Related => "/statuses/show/:id",
7003                     _ => null,
7004                 };
7005                 this.toolStripApiGauge.ApiEndpoint = endpointName;
7006             }
7007             else
7008             {
7009                 var currentEndpointName = this.toolStripApiGauge.ApiEndpoint;
7010                 this.toolStripApiGauge.ApiEndpoint = currentEndpointName;
7011             }
7012         }
7013
7014         private void SetStatusLabelUrl()
7015             => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7016
7017         public void SetStatusLabel(string text)
7018             => this.StatusLabel.Text = text;
7019
7020         private void SetNotifyIconText()
7021         {
7022             var ur = new StringBuilder(64);
7023
7024             // タスクトレイアイコンのツールチップテキスト書き換え
7025             // Tween [未読/@]
7026             ur.Remove(0, ur.Length);
7027             if (this.settings.Common.DispUsername)
7028             {
7029                 ur.Append(this.tw.Username);
7030                 ur.Append(" - ");
7031             }
7032             ur.Append(ApplicationSettings.ApplicationName);
7033 #if DEBUG
7034             ur.Append("(Debug Build)");
7035 #endif
7036             if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7037             {
7038                 ur.Append(" [");
7039                 ur.Append(this.unreadCounter);
7040                 ur.Append("/@");
7041                 ur.Append(this.unreadAtCounter);
7042                 ur.Append("]");
7043             }
7044             this.NotifyIcon1.Text = ur.ToString();
7045         }
7046
7047         internal void CheckReplyTo(string statusText)
7048         {
7049             MatchCollection m;
7050             // ハッシュタグの保存
7051             m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7052             var hstr = "";
7053             foreach (Match hm in m)
7054             {
7055                 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7056                 {
7057                     hstr += "#" + hm.Result("$3") + " ";
7058                     this.HashSupl.AddItem("#" + hm.Result("$3"));
7059                 }
7060             }
7061             if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7062             {
7063                 hstr += this.HashMgr.UseHash;
7064             }
7065             if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7066
7067             // 本当にリプライ先指定すべきかどうかの判定
7068             m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7069
7070             if (this.settings.Common.UseAtIdSupplement)
7071             {
7072                 var bCnt = this.AtIdSupl.ItemCount;
7073                 foreach (Match mid in m)
7074                 {
7075                     this.AtIdSupl.AddItem(mid.Result("${id}"));
7076                 }
7077                 if (bCnt != this.AtIdSupl.ItemCount)
7078                     this.MarkSettingAtIdModified();
7079             }
7080
7081             // リプライ先ステータスIDの指定がない場合は指定しない
7082             if (this.inReplyTo == null)
7083                 return;
7084
7085             // 通常Reply
7086             // 次の条件を満たす場合に in_reply_to_status_id 指定
7087             // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7088             // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7089             // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7090
7091             if (m != null)
7092             {
7093                 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7094                 if (statusText.StartsWith("@", StringComparison.Ordinal))
7095                 {
7096                     if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7097                 }
7098                 else
7099                 {
7100                     foreach (Match mid in m)
7101                     {
7102                         if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7103                     }
7104                 }
7105             }
7106
7107             this.inReplyTo = null;
7108         }
7109
7110         private void TweenMain_Resize(object sender, EventArgs e)
7111         {
7112             if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7113             {
7114                 this.Visible = false;
7115             }
7116             if (this.WindowState != FormWindowState.Minimized)
7117             {
7118                 this.formWindowState = this.WindowState;
7119             }
7120         }
7121
7122         private void ApplyLayoutFromSettings()
7123         {
7124             // 現在の DPI と設定保存時の DPI との比を取得する
7125             var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7126
7127             this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7128
7129             // Splitterの位置設定
7130             var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7131             if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7132                 splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7133             {
7134                 this.SplitContainer1.SplitterDistance = splitterDistance;
7135             }
7136
7137             // 発言欄複数行
7138             this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7139             if (this.StatusText.Multiline)
7140             {
7141                 var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7142                 var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7143                 if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7144                 {
7145                     this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7146                 }
7147                 this.StatusText.Height = statusTextHeight;
7148             }
7149             else
7150             {
7151                 if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7152                 {
7153                     this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7154                 }
7155             }
7156
7157             var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7158             if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7159             {
7160                 this.SplitContainer3.SplitterDistance = previewDistance;
7161             }
7162
7163             // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7164             this.SplitContainer3.Panel2Collapsed = true;
7165             this.initialLayout = false;
7166         }
7167
7168         private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7169         {
7170             this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7171             this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7172             if (this.PlaySoundMenuItem.Checked)
7173             {
7174                 this.settings.Common.PlaySound = true;
7175             }
7176             else
7177             {
7178                 this.settings.Common.PlaySound = false;
7179             }
7180             this.MarkSettingCommonModified();
7181         }
7182
7183         private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7184         {
7185             if (this.initialLayout)
7186                 return;
7187
7188             int splitterDistance;
7189             switch (this.WindowState)
7190             {
7191                 case FormWindowState.Normal:
7192                     splitterDistance = this.SplitContainer1.SplitterDistance;
7193                     break;
7194                 case FormWindowState.Maximized:
7195                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7196                     var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7197                     splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7198                     splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7199                     break;
7200                 default:
7201                     return;
7202             }
7203
7204             this.mySpDis = splitterDistance;
7205             this.MarkSettingLocalModified();
7206         }
7207
7208         private async Task DoRepliedStatusOpen()
7209         {
7210             var currentPost = this.CurrentPost;
7211             if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7212             {
7213                 if (MyCommon.IsKeyDown(Keys.Shift))
7214                 {
7215                     await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7216                     return;
7217                 }
7218                 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId, out var repPost))
7219                 {
7220                     MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname}   ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7221                 }
7222                 else
7223                 {
7224                     foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7225                     {
7226                         if (tb == null || !tb.Contains(currentPost.InReplyToStatusId)) break;
7227                         repPost = tb.Posts[currentPost.InReplyToStatusId];
7228                         MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname}   ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7229                         return;
7230                     }
7231                     await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7232                 }
7233             }
7234         }
7235
7236         private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7237             => await this.DoRepliedStatusOpen();
7238
7239         private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7240         {
7241             if (this.initialLayout)
7242                 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7243
7244             var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7245             if (multiline != this.StatusText.Multiline)
7246             {
7247                 this.StatusText.Multiline = multiline;
7248                 this.settings.Local.StatusMultiline = multiline;
7249                 this.MarkSettingLocalModified();
7250             }
7251         }
7252
7253         private void StatusText_MultilineChanged(object sender, EventArgs e)
7254         {
7255             if (this.StatusText.Multiline)
7256                 this.StatusText.ScrollBars = ScrollBars.Vertical;
7257             else
7258                 this.StatusText.ScrollBars = ScrollBars.None;
7259
7260             if (!this.initialLayout)
7261                 this.MarkSettingLocalModified();
7262         }
7263
7264         private void MultiLineMenuItem_Click(object sender, EventArgs e)
7265         {
7266             // 発言欄複数行
7267             var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7268             this.StatusText.Multiline = menuItemChecked;
7269             this.settings.Local.StatusMultiline = menuItemChecked;
7270             if (menuItemChecked)
7271             {
7272                 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7273                     this.SplitContainer2.SplitterDistance = 0;
7274                 else
7275                     this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7276             }
7277             else
7278             {
7279                 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7280             }
7281             this.MarkSettingLocalModified();
7282         }
7283
7284         private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7285         {
7286             if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7287             {
7288                 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7289                 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7290                     (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7291                 {
7292                     MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7293                     return false;
7294                 }
7295             }
7296
7297             // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7298             // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7299             // Appendix A.  Collected ABNF for URI
7300             // http://www.ietf.org/rfc/rfc3986.txt
7301
7302             const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7303
7304             string result;
7305             if (this.StatusText.SelectionLength > 0)
7306             {
7307                 var tmp = this.StatusText.SelectedText;
7308                 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7309                 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7310                 {
7311                     // 文字列が選択されている場合はその文字列について処理
7312
7313                     // nico.ms使用、nicovideoにマッチしたら変換
7314                     if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7315                     {
7316                         result = Nicoms.Shorten(tmp);
7317                     }
7318                     else if (converterType != MyCommon.UrlConverter.Nicoms)
7319                     {
7320                         // 短縮URL変換
7321                         try
7322                         {
7323                             var srcUri = new Uri(tmp);
7324                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7325                             result = resultUri.AbsoluteUri;
7326                         }
7327                         catch (WebApiException e)
7328                         {
7329                             this.StatusLabel.Text = converterType + ":" + e.Message;
7330                             return false;
7331                         }
7332                         catch (UriFormatException e)
7333                         {
7334                             this.StatusLabel.Text = converterType + ":" + e.Message;
7335                             return false;
7336                         }
7337                     }
7338                     else
7339                     {
7340                         return true;
7341                     }
7342
7343                     if (!MyCommon.IsNullOrEmpty(result))
7344                     {
7345                         // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7346                         var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7347                         if (origUrlIndex == -1)
7348                             return false;
7349
7350                         this.StatusText.Select(origUrlIndex, tmp.Length);
7351                         this.StatusText.SelectedText = result;
7352
7353                         // undoバッファにセット
7354                         var undo = new UrlUndo
7355                         {
7356                             Before = tmp,
7357                             After = result,
7358                         };
7359
7360                         if (this.urlUndoBuffer == null)
7361                         {
7362                             this.urlUndoBuffer = new List<UrlUndo>();
7363                             this.UrlUndoToolStripMenuItem.Enabled = true;
7364                         }
7365
7366                         this.urlUndoBuffer.Add(undo);
7367                     }
7368                 }
7369             }
7370             else
7371             {
7372                 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7373                                    @"(?<url>(?<protocol>https?://)" +
7374                                    @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7375                                    @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7376                                    @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7377                 // 正規表現にマッチしたURL文字列をtinyurl化
7378                 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7379                 {
7380                     if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7381                         continue;
7382                     var tmp = mt.Result("${url}");
7383                     if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7384                         tmp = "http://" + tmp;
7385
7386                     // 選んだURLを選択(?)
7387                     this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7388
7389                     // nico.ms使用、nicovideoにマッチしたら変換
7390                     if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7391                     {
7392                         result = Nicoms.Shorten(tmp);
7393                     }
7394                     else if (converterType != MyCommon.UrlConverter.Nicoms)
7395                     {
7396                         // 短縮URL変換
7397                         try
7398                         {
7399                             var srcUri = new Uri(tmp);
7400                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7401                             result = resultUri.AbsoluteUri;
7402                         }
7403                         catch (HttpRequestException e)
7404                         {
7405                             // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7406                             // のように長いので「:」が含まれていればそれ以降のみを抽出する
7407                             var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7408
7409                             this.StatusLabel.Text = converterType + ":" + message;
7410                             continue;
7411                         }
7412                         catch (WebApiException e)
7413                         {
7414                             this.StatusLabel.Text = converterType + ":" + e.Message;
7415                             continue;
7416                         }
7417                         catch (UriFormatException e)
7418                         {
7419                             this.StatusLabel.Text = converterType + ":" + e.Message;
7420                             continue;
7421                         }
7422                     }
7423                     else
7424                     {
7425                         continue;
7426                     }
7427
7428                     if (!MyCommon.IsNullOrEmpty(result))
7429                     {
7430                         // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7431                         var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7432                         if (origUrlIndex == -1)
7433                             return false;
7434
7435                         this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7436                         this.StatusText.SelectedText = result;
7437                         // undoバッファにセット
7438                         var undo = new UrlUndo
7439                         {
7440                             Before = mt.Result("${url}"),
7441                             After = result,
7442                         };
7443
7444                         if (this.urlUndoBuffer == null)
7445                         {
7446                             this.urlUndoBuffer = new List<UrlUndo>();
7447                             this.UrlUndoToolStripMenuItem.Enabled = true;
7448                         }
7449
7450                         this.urlUndoBuffer.Add(undo);
7451                     }
7452                 }
7453             }
7454
7455             return true;
7456         }
7457
7458         private void DoUrlUndo()
7459         {
7460             if (this.urlUndoBuffer != null)
7461             {
7462                 var tmp = this.StatusText.Text;
7463                 foreach (var data in this.urlUndoBuffer)
7464                 {
7465                     tmp = tmp.Replace(data.After, data.Before);
7466                 }
7467                 this.StatusText.Text = tmp;
7468                 this.urlUndoBuffer = null;
7469                 this.UrlUndoToolStripMenuItem.Enabled = false;
7470                 this.StatusText.SelectionStart = 0;
7471                 this.StatusText.SelectionLength = 0;
7472             }
7473         }
7474
7475         private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7476             => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7477
7478         private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7479             => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7480
7481         private async void UxnuMenuItem_Click(object sender, EventArgs e)
7482             => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7483
7484         private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7485         {
7486             if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7487             {
7488                 var rnd = new Random();
7489
7490                 MyCommon.UrlConverter svc;
7491                 // 前回使用した短縮URLサービス以外を選択する
7492                 do
7493                 {
7494                     svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7495                 }
7496                 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7497                 await this.UrlConvertAsync(svc);
7498             }
7499         }
7500
7501         private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7502             => this.DoUrlUndo();
7503
7504         private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7505         {
7506             this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7507             this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7508             this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7509             this.MarkSettingCommonModified();
7510         }
7511
7512         private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7513         {
7514             this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7515             this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7516             this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7517             this.MarkSettingCommonModified();
7518         }
7519
7520         private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7521         {
7522             // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7523             this.MenuStrip1.Tag = new object();
7524             this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7525         }
7526
7527         private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7528         {
7529             var currentTabPage = this.CurrentTabPage;
7530             if (this.Tag != null) // 設定された戻り先へ遷移
7531             {
7532                 if (this.Tag == currentTabPage)
7533                     ((Control)currentTabPage.Tag).Select();
7534                 else
7535                     ((Control)this.Tag).Select();
7536             }
7537             else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7538             {
7539                 this.Tag = currentTabPage.Tag;
7540                 ((Control)this.Tag).Select();
7541             }
7542             // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7543             this.MenuStrip1.Tag = null;
7544         }
7545
7546         private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7547         {
7548             if (this.Use2ColumnsMode)
7549             {
7550                 e.Cancel = true;
7551                 return;
7552             }
7553
7554             var lst = (DetailsListView)sender;
7555             var columnsCount = lst.Columns.Count;
7556
7557             var darr = new int[columnsCount];
7558             for (var i = 0; i < columnsCount; i++)
7559                 darr[lst.Columns[i].DisplayIndex] = i;
7560
7561             MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7562
7563             for (var i = 0; i < columnsCount; i++)
7564                 this.settings.Local.ColumnsOrder[darr[i]] = i;
7565
7566             this.MarkSettingLocalModified();
7567             this.isColumnChanged = true;
7568         }
7569
7570         private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7571         {
7572             var lst = (DetailsListView)sender;
7573             if (this.settings.Local == null) return;
7574
7575             var modified = false;
7576             if (this.Use2ColumnsMode)
7577             {
7578                 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7579                 {
7580                     this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7581                     modified = true;
7582                 }
7583                 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7584                 {
7585                     this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7586                     modified = true;
7587                 }
7588             }
7589             else
7590             {
7591                 var columnsCount = lst.Columns.Count;
7592                 for (var i = 0; i < columnsCount; i++)
7593                 {
7594                     if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7595                         continue;
7596
7597                     this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7598                     modified = true;
7599                 }
7600             }
7601             if (modified)
7602             {
7603                 this.MarkSettingLocalModified();
7604                 this.isColumnChanged = true;
7605             }
7606         }
7607
7608         private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7609         {
7610             if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7611             this.MarkSettingLocalModified();
7612         }
7613
7614         private void TweenMain_DragDrop(object sender, DragEventArgs e)
7615         {
7616             if (e.Data.GetDataPresent(DataFormats.FileDrop))
7617             {
7618                 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7619                 {
7620                     this.SelectMedia_DragDrop(e);
7621                 }
7622             }
7623             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7624             {
7625                 var (url, title) = GetUrlFromDataObject(e.Data);
7626
7627                 string appendText;
7628                 if (title == null)
7629                     appendText = url;
7630                 else
7631                     appendText = title + " " + url;
7632
7633                 if (this.StatusText.TextLength == 0)
7634                     this.StatusText.Text = appendText;
7635                 else
7636                     this.StatusText.Text += " " + appendText;
7637             }
7638             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7639             {
7640                 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7641                 if (text != null)
7642                     this.StatusText.Text += text;
7643             }
7644             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7645             {
7646                 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7647                 if (data != null) this.StatusText.Text += data;
7648             }
7649         }
7650
7651         /// <summary>
7652         /// IDataObject から URL とタイトルの対を取得します
7653         /// </summary>
7654         /// <remarks>
7655         /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7656         /// </remarks>
7657         /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7658         /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7659         internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7660         {
7661             if (data.GetDataPresent("text/x-moz-url"))
7662             {
7663                 // Firefox, Google Chrome で利用可能
7664                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7665
7666                 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7667                 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7668                 if (lines.Length < 2)
7669                     throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7670
7671                 return (lines[0], lines[1]);
7672             }
7673             else if (data.GetDataPresent("IESiteModeToUrl"))
7674             {
7675                 // Internet Exproler 用
7676                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7677
7678                 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7679                 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7680                 if (lines.Length < 2)
7681                     throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7682
7683                 return (lines[0], lines[1]);
7684             }
7685             else if (data.GetDataPresent("UniformResourceLocatorW"))
7686             {
7687                 // それ以外のブラウザ向け
7688
7689                 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7690                 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7691                 return (url, null);
7692             }
7693
7694             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7695         }
7696
7697         private void TweenMain_DragEnter(object sender, DragEventArgs e)
7698         {
7699             if (e.Data.GetDataPresent(DataFormats.FileDrop))
7700             {
7701                 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7702                 {
7703                     this.SelectMedia_DragEnter(e);
7704                     return;
7705                 }
7706             }
7707             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7708             {
7709                 e.Effect = DragDropEffects.Copy;
7710                 return;
7711             }
7712             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7713             {
7714                 e.Effect = DragDropEffects.Copy;
7715                 return;
7716             }
7717             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7718             {
7719                 e.Effect = DragDropEffects.Copy;
7720                 return;
7721             }
7722
7723             e.Effect = DragDropEffects.None;
7724         }
7725
7726         private void TweenMain_DragOver(object sender, DragEventArgs e)
7727         {
7728         }
7729
7730         public bool IsNetworkAvailable()
7731         {
7732             var nw = MyCommon.IsNetworkAvailable();
7733             this.myStatusOnline = nw;
7734             return nw;
7735         }
7736
7737         public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7738         {
7739             var uriStr = uri.AbsoluteUri;
7740
7741             // OpenTween 内部で使用する URL
7742             if (uri.Authority == "opentween")
7743             {
7744                 await this.OpenInternalUriAsync(uri);
7745                 return;
7746             }
7747
7748             // ハッシュタグを含む Twitter 検索
7749             if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7750             {
7751                 // ハッシュタグの場合は、タブで開く
7752                 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7753                 var pos = unescapedQuery.IndexOf('#');
7754                 if (pos == -1) return;
7755
7756                 var hash = unescapedQuery.Substring(pos);
7757                 this.HashSupl.AddItem(hash);
7758                 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7759                 this.AddNewTabForSearch(hash);
7760                 return;
7761             }
7762
7763             // ユーザープロフィールURL
7764             // フラグが立っている場合は設定と逆の動作をする
7765             if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7766                 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7767             {
7768                 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7769                 if (userUriMatch.Success)
7770                 {
7771                     var screenName = userUriMatch.Groups["ScreenName"].Value;
7772                     if (this.IsTwitterId(screenName))
7773                     {
7774                         await this.AddNewTabForUserTimeline(screenName);
7775                         return;
7776                     }
7777                 }
7778             }
7779
7780             // どのパターンにも該当しないURL
7781             await MyCommon.OpenInBrowserAsync(this, uriStr);
7782         }
7783
7784         /// <summary>
7785         /// OpenTween 内部の機能を呼び出すための URL を開きます
7786         /// </summary>
7787         private async Task OpenInternalUriAsync(Uri uri)
7788         {
7789             // ツイートを開く (//opentween/status/:status_id)
7790             var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7791             if (match.Success)
7792             {
7793                 var statusId = new TwitterStatusId(match.Groups[1].Value);
7794                 await this.OpenRelatedTab(statusId);
7795                 return;
7796             }
7797         }
7798
7799         private void ListTabSelect(TabPage tabPage)
7800         {
7801             this.SetListProperty();
7802
7803             var previousTabName = this.CurrentTabName;
7804             if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7805                 previousListViewState.Save(this.ListLockMenuItem.Checked);
7806
7807             this.listCache?.PurgeCache();
7808
7809             this.statuses.SelectTab(tabPage.Text);
7810
7811             this.InitializeTimelineListView();
7812
7813             var tab = this.CurrentTab;
7814             tab.ClearAnchor();
7815
7816             var listView = this.CurrentListView;
7817
7818             var currentListViewState = this.listViewState[tab.TabName];
7819             currentListViewState.Restore(forceScroll: true);
7820
7821             if (this.Use2ColumnsMode)
7822             {
7823                 listView.Columns[1].Text = this.columnText[2];
7824             }
7825             else
7826             {
7827                 for (var i = 0; i < listView.Columns.Count; i++)
7828                 {
7829                     listView.Columns[i].Text = this.columnText[i];
7830                 }
7831             }
7832         }
7833
7834         private void InitializeTimelineListView()
7835         {
7836             var listView = this.CurrentListView;
7837             var tab = this.CurrentTab;
7838
7839             var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7840             (this.listCache, var oldCache) = (newCache, this.listCache);
7841             oldCache?.Dispose();
7842
7843             var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager);
7844             (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7845             oldDrawer?.Dispose();
7846
7847             newDrawer.IconSize = this.settings.Common.IconSize;
7848             newDrawer.UpdateItemHeight();
7849         }
7850
7851         private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7852             => this.ListTabSelect(e.TabPage);
7853
7854         private void SelectListItem(DetailsListView lView, int index)
7855         {
7856             // 単一
7857             var bnd = new Rectangle();
7858             var flg = false;
7859             var item = lView.FocusedItem;
7860             if (item != null)
7861             {
7862                 bnd = item.Bounds;
7863                 flg = true;
7864             }
7865
7866             do
7867             {
7868                 lView.SelectedIndices.Clear();
7869             }
7870             while (lView.SelectedIndices.Count > 0);
7871             item = lView.Items[index];
7872             item.Selected = true;
7873             item.Focused = true;
7874
7875             if (flg) lView.Invalidate(bnd);
7876         }
7877
7878         private async void TweenMain_Shown(object sender, EventArgs e)
7879         {
7880             this.NotifyIcon1.Visible = true;
7881             this.StartTimers();
7882
7883             if (this.settings.IsFirstRun)
7884             {
7885                 // 初回起動時だけ右下のメニューを目立たせる
7886                 this.HashStripSplitButton.ShowDropDown();
7887             }
7888
7889             if (this.IsNetworkAvailable())
7890             {
7891                 var loadTasks = new TaskCollection();
7892
7893                 loadTasks.Add(new[]
7894                 {
7895                     this.RefreshMuteUserIdsAsync,
7896                     this.RefreshBlockIdsAsync,
7897                     this.RefreshNoRetweetIdsAsync,
7898                     this.RefreshTwitterConfigurationAsync,
7899                     this.RefreshTabAsync<HomeTabModel>,
7900                     this.RefreshTabAsync<MentionsTabModel>,
7901                     this.RefreshTabAsync<DirectMessagesTabModel>,
7902                     this.RefreshTabAsync<PublicSearchTabModel>,
7903                     this.RefreshTabAsync<UserTimelineTabModel>,
7904                     this.RefreshTabAsync<ListTimelineTabModel>,
7905                 });
7906
7907                 if (this.settings.Common.StartupFollowers)
7908                     loadTasks.Add(this.RefreshFollowerIdsAsync);
7909
7910                 if (this.settings.Common.GetFav)
7911                     loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>);
7912
7913                 var allTasks = loadTasks.RunAll();
7914
7915                 var i = 0;
7916                 while (true)
7917                 {
7918                     var timeout = Task.Delay(5000);
7919                     if (await Task.WhenAny(allTasks, timeout) != timeout)
7920                         break;
7921
7922                     i += 1;
7923                     if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
7924
7925                     if (MyCommon.EndingFlag)
7926                         return;
7927                 }
7928
7929                 if (MyCommon.EndingFlag) return;
7930
7931                 if (ApplicationSettings.VersionInfoUrl != null)
7932                 {
7933                     // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
7934                     if (this.settings.Common.StartupVersion)
7935                         await this.CheckNewVersion(true);
7936                 }
7937                 else
7938                 {
7939                     // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
7940                     this.VerUpMenuItem.Enabled = false;
7941                     this.VerUpMenuItem.Available = false;
7942                     this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
7943                 }
7944
7945                 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
7946                 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
7947                 {
7948                     MessageBox.Show(Properties.Resources.ReAuthorizeText);
7949                     this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
7950                 }
7951
7952                 // 取得失敗の場合は再試行する
7953                 var reloadTasks = new TaskCollection();
7954
7955                 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
7956                     reloadTasks.Add(() => this.RefreshFollowerIdsAsync());
7957
7958                 if (!this.tw.GetNoRetweetSuccess)
7959                     reloadTasks.Add(() => this.RefreshNoRetweetIdsAsync());
7960
7961                 if (this.tw.Configuration.PhotoSizeLimit == 0)
7962                     reloadTasks.Add(() => this.RefreshTwitterConfigurationAsync());
7963
7964                 await reloadTasks.RunAll();
7965             }
7966
7967             this.initial = false;
7968         }
7969
7970         private void StartTimers()
7971         {
7972             if (!this.StopRefreshAllMenuItem.Checked)
7973                 this.timelineScheduler.Enabled = true;
7974
7975             this.selectionDebouncer.Enabled = true;
7976             this.saveConfigDebouncer.Enabled = true;
7977             this.thumbGenerator.ImgAzyobuziNet.AutoUpdate = true;
7978         }
7979
7980         private async Task DoGetFollowersMenu()
7981         {
7982             await this.RefreshFollowerIdsAsync();
7983             this.DispSelectedPost(true);
7984         }
7985
7986         private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
7987             => await this.DoGetFollowersMenu();
7988
7989         private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
7990             => this.DoReTweetUnofficial();
7991
7992         private async Task DoReTweetOfficial(bool isConfirm)
7993         {
7994             // 公式RT
7995             if (this.ExistCurrentPost)
7996             {
7997                 var selectedPosts = this.CurrentTab.SelectedPosts;
7998
7999                 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8000                 {
8001                     if (selectedPosts.Any(x => x.IsProtect))
8002                         MessageBox.Show("Protected.");
8003
8004                     this.doFavRetweetFlags = false;
8005                     return;
8006                 }
8007
8008                 if (selectedPosts.Length > 15)
8009                 {
8010                     MessageBox.Show(Properties.Resources.RetweetLimitText);
8011                     this.doFavRetweetFlags = false;
8012                     return;
8013                 }
8014                 else if (selectedPosts.Length > 1)
8015                 {
8016                     var questionText = Properties.Resources.RetweetQuestion2;
8017                     if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8018                     switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8019                     {
8020                         case DialogResult.Cancel:
8021                         case DialogResult.No:
8022                             this.doFavRetweetFlags = false;
8023                             return;
8024                     }
8025                 }
8026                 else
8027                 {
8028                     if (!this.settings.Common.RetweetNoConfirm)
8029                     {
8030                         var questiontext = Properties.Resources.RetweetQuestion1;
8031                         if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8032                         if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8033                         {
8034                             this.doFavRetweetFlags = false;
8035                             return;
8036                         }
8037                     }
8038                 }
8039
8040                 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8041
8042                 await this.RetweetAsync(statusIds);
8043             }
8044         }
8045
8046         private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8047             => await this.DoReTweetOfficial(true);
8048
8049         private async Task FavoritesRetweetOfficial()
8050         {
8051             if (!this.ExistCurrentPost) return;
8052             this.doFavRetweetFlags = true;
8053
8054             var tasks = new TaskCollection();
8055             tasks.Add(() => this.DoReTweetOfficial(true));
8056
8057             if (this.doFavRetweetFlags)
8058             {
8059                 this.doFavRetweetFlags = false;
8060                 tasks.Add(() => this.FavoriteChange(true, false));
8061             }
8062
8063             await tasks.RunAll();
8064         }
8065
8066         private async Task FavoritesRetweetUnofficial()
8067         {
8068             var post = this.CurrentPost;
8069             if (this.ExistCurrentPost && post != null && !post.IsDm)
8070             {
8071                 this.doFavRetweetFlags = true;
8072                 var favoriteTask = this.FavoriteChange(true);
8073                 if (!post.IsProtect && this.doFavRetweetFlags)
8074                 {
8075                     this.doFavRetweetFlags = false;
8076                     this.DoReTweetUnofficial();
8077                 }
8078
8079                 await favoriteTask;
8080             }
8081         }
8082
8083         /// <summary>
8084         /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8085         /// </summary>
8086         /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8087         /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8088         /// <returns>復元されたツイート本文</returns>
8089         internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8090         {
8091             // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8092
8093             // 通常の URL
8094             statusHtml = Regex.Replace(statusHtml, """<a href="(?<href>.+?)" title="(?<title>.+?)">(?<text>.+?)</a>""", "${title}");
8095             // メンション
8096             statusHtml = Regex.Replace(statusHtml, """<a class="mention" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8097             // ハッシュタグ
8098             statusHtml = Regex.Replace(statusHtml, """<a class="hashtag" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8099             // 絵文字
8100             statusHtml = Regex.Replace(statusHtml, """<img class="emoji" src=".+?" alt="(?<text>.+?)" />""", "${text}");
8101
8102             // <br> 除去
8103             if (multiline)
8104                 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8105             else
8106                 statusHtml = statusHtml.Replace("<br>", " ");
8107
8108             // &nbsp; は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8109             // 現状では半角スペースの代用として &nbsp; を使用しているため U+0020 に置換します
8110             statusHtml = statusHtml.Replace("&nbsp;", " ");
8111
8112             return WebUtility.HtmlDecode(statusHtml);
8113         }
8114
8115         private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8116         {
8117             this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8118
8119             if (this.CurrentPost != null)
8120                 this.DispSelectedPost(true);
8121         }
8122
8123         private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8124         {
8125             if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock | Keys.Control | Keys.Shift))
8126                 this.DebugModeToolStripMenuItem.Visible = true;
8127             else
8128                 this.DebugModeToolStripMenuItem.Visible = false;
8129         }
8130
8131         private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8132             => this.SeparateUrlAndFullwidthCharacter = ((ToolStripMenuItem)sender).Checked;
8133
8134         private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8135             => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8136
8137         private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8138             => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8139
8140         private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8141         {
8142             this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8143             this.MarkSettingCommonModified();
8144         }
8145
8146         private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8147         {
8148             this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8149             this.MarkSettingCommonModified();
8150         }
8151
8152         private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8153         {
8154             this.UrlMultibyteSplitMenuItem.Checked = this.SeparateUrlAndFullwidthCharacter;
8155             this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8156             this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8157             this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8158             this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8159             this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8160         }
8161
8162         private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8163         {
8164             this.UrlMultibyteSplitPullDownMenuItem.Checked = this.SeparateUrlAndFullwidthCharacter;
8165             this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8166             this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8167             this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8168             this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8169             this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8170         }
8171
8172         private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8173         {
8174             if (this.TraceOutToolStripMenuItem.Checked)
8175                 MyCommon.TraceFlag = true;
8176             else
8177                 MyCommon.TraceFlag = false;
8178         }
8179
8180         private void TweenMain_Deactivate(object sender, EventArgs e)
8181             => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8182
8183         private void TabRenameMenuItem_Click(object sender, EventArgs e)
8184         {
8185             if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8186
8187             _ = this.TabRename(this.rclickTabName, out _);
8188         }
8189
8190         private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8191             => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8192
8193         private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8194             => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8195
8196         private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8197         {
8198             TwitterApiStatus? apiStatus;
8199
8200             using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8201             {
8202                 var cancellationToken = dialog.EnableCancellation();
8203
8204                 try
8205                 {
8206                     var task = this.tw.GetInfoApi();
8207                     apiStatus = await dialog.WaitForAsync(this, task);
8208                 }
8209                 catch (WebApiException)
8210                 {
8211                     apiStatus = null;
8212                 }
8213
8214                 if (cancellationToken.IsCancellationRequested)
8215                     return;
8216
8217                 if (apiStatus == null)
8218                 {
8219                     MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8220                     return;
8221                 }
8222             }
8223
8224             using var apiDlg = new ApiInfoDialog();
8225             apiDlg.ShowDialog(this);
8226         }
8227
8228         private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8229         {
8230             var id = this.CurrentPost?.ScreenName ?? "";
8231
8232             await this.FollowCommand(id);
8233         }
8234
8235         internal async Task FollowCommand(string id)
8236         {
8237             using (var inputName = new InputTabName())
8238             {
8239                 inputName.FormTitle = "Follow";
8240                 inputName.FormDescription = Properties.Resources.FRMessage1;
8241                 inputName.TabName = id;
8242
8243                 if (inputName.ShowDialog(this) != DialogResult.OK)
8244                     return;
8245                 if (string.IsNullOrWhiteSpace(inputName.TabName))
8246                     return;
8247
8248                 id = inputName.TabName.Trim();
8249             }
8250
8251             using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8252             {
8253                 try
8254                 {
8255                     var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8256                     await dialog.WaitForAsync(this, task);
8257                 }
8258                 catch (WebApiException ex)
8259                 {
8260                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8261                     return;
8262                 }
8263             }
8264
8265             MessageBox.Show(Properties.Resources.FRMessage3);
8266         }
8267
8268         private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8269         {
8270             var id = this.CurrentPost?.ScreenName ?? "";
8271
8272             await this.RemoveCommand(id, false);
8273         }
8274
8275         internal async Task RemoveCommand(string id, bool skipInput)
8276         {
8277             if (!skipInput)
8278             {
8279                 using var inputName = new InputTabName();
8280                 inputName.FormTitle = "Unfollow";
8281                 inputName.FormDescription = Properties.Resources.FRMessage1;
8282                 inputName.TabName = id;
8283
8284                 if (inputName.ShowDialog(this) != DialogResult.OK)
8285                     return;
8286                 if (string.IsNullOrWhiteSpace(inputName.TabName))
8287                     return;
8288
8289                 id = inputName.TabName.Trim();
8290             }
8291
8292             using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8293             {
8294                 try
8295                 {
8296                     var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8297                     await dialog.WaitForAsync(this, task);
8298                 }
8299                 catch (WebApiException ex)
8300                 {
8301                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8302                     return;
8303                 }
8304             }
8305
8306             MessageBox.Show(Properties.Resources.FRMessage3);
8307         }
8308
8309         private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8310         {
8311             var id = this.CurrentPost?.ScreenName ?? "";
8312
8313             await this.ShowFriendship(id);
8314         }
8315
8316         internal async Task ShowFriendship(string id)
8317         {
8318             using (var inputName = new InputTabName())
8319             {
8320                 inputName.FormTitle = "Show Friendships";
8321                 inputName.FormDescription = Properties.Resources.FRMessage1;
8322                 inputName.TabName = id;
8323
8324                 if (inputName.ShowDialog(this) != DialogResult.OK)
8325                     return;
8326                 if (string.IsNullOrWhiteSpace(inputName.TabName))
8327                     return;
8328
8329                 id = inputName.TabName.Trim();
8330             }
8331
8332             bool isFollowing, isFollowed;
8333
8334             using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8335             {
8336                 var cancellationToken = dialog.EnableCancellation();
8337
8338                 try
8339                 {
8340                     var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8341                     var friendship = await dialog.WaitForAsync(this, task);
8342
8343                     isFollowing = friendship.Relationship.Source.Following;
8344                     isFollowed = friendship.Relationship.Source.FollowedBy;
8345                 }
8346                 catch (WebApiException ex)
8347                 {
8348                     if (!cancellationToken.IsCancellationRequested)
8349                         MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8350                     return;
8351                 }
8352
8353                 if (cancellationToken.IsCancellationRequested)
8354                     return;
8355             }
8356
8357             string result;
8358             if (isFollowing)
8359             {
8360                 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8361             }
8362             else
8363             {
8364                 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8365             }
8366             if (isFollowed)
8367             {
8368                 result += Properties.Resources.GetFriendshipInfo3;
8369             }
8370             else
8371             {
8372                 result += Properties.Resources.GetFriendshipInfo4;
8373             }
8374             result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8375             MessageBox.Show(result);
8376         }
8377
8378         internal async Task ShowFriendship(string[] ids)
8379         {
8380             foreach (var id in ids)
8381             {
8382                 bool isFollowing, isFollowed;
8383
8384                 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8385                 {
8386                     var cancellationToken = dialog.EnableCancellation();
8387
8388                     try
8389                     {
8390                         var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8391                         var friendship = await dialog.WaitForAsync(this, task);
8392
8393                         isFollowing = friendship.Relationship.Source.Following;
8394                         isFollowed = friendship.Relationship.Source.FollowedBy;
8395                     }
8396                     catch (WebApiException ex)
8397                     {
8398                         if (!cancellationToken.IsCancellationRequested)
8399                             MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8400                         return;
8401                     }
8402
8403                     if (cancellationToken.IsCancellationRequested)
8404                         return;
8405                 }
8406
8407                 var result = "";
8408                 var ff = "";
8409
8410                 ff = "  ";
8411                 if (isFollowing)
8412                 {
8413                     ff += Properties.Resources.GetFriendshipInfo1;
8414                 }
8415                 else
8416                 {
8417                     ff += Properties.Resources.GetFriendshipInfo2;
8418                 }
8419
8420                 ff += System.Environment.NewLine + "  ";
8421                 if (isFollowed)
8422                 {
8423                     ff += Properties.Resources.GetFriendshipInfo3;
8424                 }
8425                 else
8426                 {
8427                     ff += Properties.Resources.GetFriendshipInfo4;
8428                 }
8429                 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8430                 if (isFollowing)
8431                 {
8432                     if (MessageBox.Show(
8433                         Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8434                         Properties.Resources.GetFriendshipInfo8,
8435                         MessageBoxButtons.YesNo,
8436                         MessageBoxIcon.Question,
8437                         MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8438                     {
8439                         await this.RemoveCommand(id, true);
8440                     }
8441                 }
8442                 else
8443                 {
8444                     MessageBox.Show(result);
8445                 }
8446             }
8447         }
8448
8449         private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8450             => await this.DoShowUserStatus(this.tw.Username, false);
8451
8452         // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8453         // URLから切り出した文字列を渡す
8454
8455         public bool IsTwitterId(string name)
8456         {
8457             if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8458                 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8459             else
8460                 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8461         }
8462
8463         private void DoQuoteOfficial()
8464         {
8465             var post = this.CurrentPost;
8466             if (this.ExistCurrentPost && post != null)
8467             {
8468                 if (post.IsDm || !this.StatusText.Enabled)
8469                     return;
8470
8471                 if (post.IsProtect)
8472                 {
8473                     MessageBox.Show("Protected.");
8474                     return;
8475                 }
8476
8477                 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8478
8479                 this.inReplyTo = null;
8480
8481                 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8482
8483                 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8484                 this.StatusText.Focus();
8485             }
8486         }
8487
8488         private void DoReTweetUnofficial()
8489         {
8490             // RT @id:内容
8491             var post = this.CurrentPost;
8492             if (this.ExistCurrentPost && post != null)
8493             {
8494                 if (post.IsDm || !this.StatusText.Enabled)
8495                     return;
8496
8497                 if (post.IsProtect)
8498                 {
8499                     MessageBox.Show("Protected.");
8500                     return;
8501                 }
8502                 var rtdata = post.Text;
8503                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8504
8505                 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8506
8507                 // 投稿時に in_reply_to_status_id を付加する
8508                 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8509                 var inReplyToScreenName = post.ScreenName;
8510                 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8511
8512                 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8513
8514                 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8515                 this.StatusText.Focus();
8516             }
8517         }
8518
8519         private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8520             => this.DoQuoteOfficial();
8521
8522         private async void SearchButton_Click(object sender, EventArgs e)
8523         {
8524             // 公式検索
8525             var pnl = ((Control)sender).Parent;
8526             if (pnl == null) return;
8527             var tbName = pnl.Parent.Text;
8528             var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8529             var cmb = (ComboBox)pnl.Controls["comboSearch"];
8530             var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8531             cmb.Text = cmb.Text.Trim();
8532             // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8533             var quote = false;
8534             var buf = new StringBuilder();
8535             var c = cmb.Text.ToCharArray();
8536             for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8537             {
8538                 if (cnt > cmb.Text.Length - 4)
8539                 {
8540                     buf.Append(cmb.Text.Substring(cnt));
8541                     break;
8542                 }
8543                 if (c[cnt] == '"')
8544                 {
8545                     quote = !quote;
8546                 }
8547                 else
8548                 {
8549                     if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8550                     {
8551                         buf.Append(" OR ");
8552                         cnt += 3;
8553                         continue;
8554                     }
8555                 }
8556                 buf.Append(c[cnt]);
8557             }
8558             cmb.Text = buf.ToString();
8559
8560             var listView = (DetailsListView)pnl.Parent.Tag;
8561
8562             var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8563
8564             tb.SearchWords = cmb.Text;
8565             tb.SearchLang = cmbLang.Text;
8566             if (MyCommon.IsNullOrEmpty(cmb.Text))
8567             {
8568                 listView.Focus();
8569                 this.SaveConfigsTabs();
8570                 return;
8571             }
8572             if (queryChanged)
8573             {
8574                 var idx = cmb.Items.IndexOf(tb.SearchWords);
8575                 if (idx > -1) cmb.Items.RemoveAt(idx);
8576                 cmb.Items.Insert(0, tb.SearchWords);
8577                 cmb.Text = tb.SearchWords;
8578                 cmb.SelectAll();
8579                 this.statuses.ClearTabIds(tbName);
8580                 this.listCache?.PurgeCache();
8581                 this.listCache?.UpdateListSize();
8582                 this.SaveConfigsTabs();   // 検索条件の保存
8583             }
8584
8585             listView.Focus();
8586             await this.RefreshTabAsync(tb);
8587         }
8588
8589         private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8590             => await this.DoRefreshMore(); // もっと前を取得
8591
8592         /// <summary>
8593         /// 指定されたタブのListTabにおける位置を返します
8594         /// </summary>
8595         /// <remarks>
8596         /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8597         /// </remarks>
8598         public int GetTabPageIndex(string tabName)
8599             => this.statuses.Tabs.IndexOf(tabName);
8600
8601         private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8602         {
8603             try
8604             {
8605                 var restoredTab = this.statuses.UndoRemovedTab();
8606                 this.AddNewTab(restoredTab, startup: false);
8607
8608                 var tabIndex = this.statuses.Tabs.Count - 1;
8609                 this.ListTab.SelectedIndex = tabIndex;
8610
8611                 this.SaveConfigsTabs();
8612             }
8613             catch (TabException ex)
8614             {
8615                 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8616             }
8617         }
8618
8619         private async Task DoMoveToRTHome()
8620         {
8621             var post = this.CurrentPost;
8622             if (post != null && post.RetweetedId != null)
8623                 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8624         }
8625
8626         private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8627             => await this.DoMoveToRTHome();
8628
8629         private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8630         {
8631             var screenName = this.CurrentPost?.ScreenName;
8632             if (screenName != null)
8633                 this.ListManageUserContext(screenName);
8634         }
8635
8636         private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8637         {
8638             var screenName = this.CurrentPost?.RetweetedBy;
8639             if (screenName != null)
8640                 this.ListManageUserContext(screenName);
8641         }
8642
8643         public void ListManageUserContext(string screenName)
8644         {
8645             using var listSelectForm = new MyLists(screenName, this.tw.Api);
8646             listSelectForm.ShowDialog(this);
8647         }
8648
8649         private void SearchControls_Enter(object sender, EventArgs e)
8650         {
8651             var pnl = (Control)sender;
8652             foreach (Control ctl in pnl.Controls)
8653             {
8654                 ctl.TabStop = true;
8655             }
8656         }
8657
8658         private void SearchControls_Leave(object sender, EventArgs e)
8659         {
8660             var pnl = (Control)sender;
8661             foreach (Control ctl in pnl.Controls)
8662             {
8663                 ctl.TabStop = false;
8664             }
8665         }
8666
8667         private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8668         {
8669             var tab = this.CurrentTab;
8670             if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8671             this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8672         }
8673
8674         private void StatusLabel_DoubleClick(object sender, EventArgs e)
8675             => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8676
8677         private void HashManageMenuItem_Click(object sender, EventArgs e)
8678         {
8679             DialogResult rslt;
8680             try
8681             {
8682                 rslt = this.HashMgr.ShowDialog();
8683             }
8684             catch (Exception)
8685             {
8686                 return;
8687             }
8688             this.TopMost = this.settings.Common.AlwaysTop;
8689             if (rslt == DialogResult.Cancel) return;
8690             if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8691             {
8692                 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8693                 this.HashTogglePullDownMenuItem.Checked = true;
8694                 this.HashToggleMenuItem.Checked = true;
8695             }
8696             else
8697             {
8698                 this.HashStripSplitButton.Text = "#[-]";
8699                 this.HashTogglePullDownMenuItem.Checked = false;
8700                 this.HashToggleMenuItem.Checked = false;
8701             }
8702
8703             this.MarkSettingCommonModified();
8704             this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8705         }
8706
8707         private void HashToggleMenuItem_Click(object sender, EventArgs e)
8708         {
8709             this.HashMgr.ToggleHash();
8710             if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8711             {
8712                 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8713                 this.HashToggleMenuItem.Checked = true;
8714                 this.HashTogglePullDownMenuItem.Checked = true;
8715             }
8716             else
8717             {
8718                 this.HashStripSplitButton.Text = "#[-]";
8719                 this.HashToggleMenuItem.Checked = false;
8720                 this.HashTogglePullDownMenuItem.Checked = false;
8721             }
8722             this.MarkSettingCommonModified();
8723             this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8724         }
8725
8726         private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8727             => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8728
8729         public void SetPermanentHashtag(string hashtag)
8730         {
8731             this.HashMgr.SetPermanentHash("#" + hashtag);
8732             this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8733             this.HashTogglePullDownMenuItem.Checked = true;
8734             this.HashToggleMenuItem.Checked = true;
8735             // 使用ハッシュタグとして設定
8736             this.MarkSettingCommonModified();
8737         }
8738
8739         private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8740         {
8741             var tab = this.CurrentTab;
8742             var post = this.CurrentPost;
8743             if (!this.ExistCurrentPost)
8744             {
8745                 this.ReplyOpMenuItem.Enabled = false;
8746                 this.ReplyAllOpMenuItem.Enabled = false;
8747                 this.DmOpMenuItem.Enabled = false;
8748                 this.CreateTabRuleOpMenuItem.Enabled = false;
8749                 this.CreateIdRuleOpMenuItem.Enabled = false;
8750                 this.CreateSourceRuleOpMenuItem.Enabled = false;
8751                 this.ReadOpMenuItem.Enabled = false;
8752                 this.UnreadOpMenuItem.Enabled = false;
8753                 this.AuthorMenuItem.Visible = false;
8754                 this.RetweetedByMenuItem.Visible = false;
8755             }
8756             else
8757             {
8758                 this.ReplyOpMenuItem.Enabled = true;
8759                 this.ReplyAllOpMenuItem.Enabled = true;
8760                 this.DmOpMenuItem.Enabled = true;
8761                 this.CreateTabRuleOpMenuItem.Enabled = true;
8762                 this.CreateIdRuleOpMenuItem.Enabled = true;
8763                 this.CreateSourceRuleOpMenuItem.Enabled = true;
8764                 this.ReadOpMenuItem.Enabled = true;
8765                 this.UnreadOpMenuItem.Enabled = true;
8766                 this.AuthorMenuItem.Visible = true;
8767                 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8768                 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8769                 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8770             }
8771
8772             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8773             {
8774                 this.FavOpMenuItem.Enabled = false;
8775                 this.UnFavOpMenuItem.Enabled = false;
8776                 this.OpenStatusOpMenuItem.Enabled = false;
8777                 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8778                 this.RtOpMenuItem.Enabled = false;
8779                 this.RtUnOpMenuItem.Enabled = false;
8780                 this.QtOpMenuItem.Enabled = false;
8781                 this.FavoriteRetweetMenuItem.Enabled = false;
8782                 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8783             }
8784             else
8785             {
8786                 this.FavOpMenuItem.Enabled = true;
8787                 this.UnFavOpMenuItem.Enabled = true;
8788                 this.OpenStatusOpMenuItem.Enabled = true;
8789                 this.ShowRelatedStatusesMenuItem2.Enabled = true;  // PublicSearchの時問題出るかも
8790
8791                 if (!post.CanRetweetBy(this.tw.UserId))
8792                 {
8793                     this.RtOpMenuItem.Enabled = false;
8794                     this.RtUnOpMenuItem.Enabled = false;
8795                     this.QtOpMenuItem.Enabled = false;
8796                     this.FavoriteRetweetMenuItem.Enabled = false;
8797                     this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8798                 }
8799                 else
8800                 {
8801                     this.RtOpMenuItem.Enabled = true;
8802                     this.RtUnOpMenuItem.Enabled = true;
8803                     this.QtOpMenuItem.Enabled = true;
8804                     this.FavoriteRetweetMenuItem.Enabled = true;
8805                     this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8806                 }
8807             }
8808
8809             if (tab.TabType != MyCommon.TabUsageType.Favorites)
8810             {
8811                 this.RefreshPrevOpMenuItem.Enabled = true;
8812             }
8813             else
8814             {
8815                 this.RefreshPrevOpMenuItem.Enabled = false;
8816             }
8817             if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8818             {
8819                 this.OpenRepSourceOpMenuItem.Enabled = false;
8820             }
8821             else
8822             {
8823                 this.OpenRepSourceOpMenuItem.Enabled = true;
8824             }
8825
8826             if (this.ExistCurrentPost && post != null)
8827             {
8828                 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8829             }
8830         }
8831
8832         private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8833             => this.ContextMenuTabProperty_Opening(sender, null!);
8834
8835         public Twitter TwitterInstance
8836             => this.tw;
8837
8838         private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8839         {
8840             if (this.initialLayout)
8841                 return;
8842
8843             int splitterDistance;
8844             switch (this.WindowState)
8845             {
8846                 case FormWindowState.Normal:
8847                     splitterDistance = this.SplitContainer3.SplitterDistance;
8848                     break;
8849                 case FormWindowState.Maximized:
8850                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8851                     var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8852                     splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8853                     splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8854                     break;
8855                 default:
8856                     return;
8857             }
8858
8859             this.mySpDis3 = splitterDistance;
8860             this.MarkSettingLocalModified();
8861         }
8862
8863         private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
8864         {
8865             this.UndoRemoveTabMenuItem.Enabled = this.statuses.CanUndoRemovedTab;
8866
8867             if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
8868                 this.PublicSearchQueryMenuItem.Enabled = true;
8869             else
8870                 this.PublicSearchQueryMenuItem.Enabled = false;
8871
8872             var post = this.CurrentPost;
8873             if (!this.ExistCurrentPost || post == null)
8874             {
8875                 this.CopySTOTMenuItem.Enabled = false;
8876                 this.CopyURLMenuItem.Enabled = false;
8877                 this.CopyUserIdStripMenuItem.Enabled = false;
8878             }
8879             else
8880             {
8881                 this.CopySTOTMenuItem.Enabled = true;
8882                 this.CopyURLMenuItem.Enabled = true;
8883                 this.CopyUserIdStripMenuItem.Enabled = true;
8884
8885                 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
8886                 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
8887             }
8888         }
8889
8890         private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
8891             => this.SetNotifyIconText();
8892
8893         private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
8894             => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
8895
8896         private async Task DoShowUserStatus(string id, bool showInputDialog)
8897         {
8898             TwitterUser? user = null;
8899
8900             if (showInputDialog)
8901             {
8902                 using var inputName = new InputTabName();
8903                 inputName.FormTitle = "Show UserStatus";
8904                 inputName.FormDescription = Properties.Resources.FRMessage1;
8905                 inputName.TabName = id;
8906
8907                 if (inputName.ShowDialog(this) != DialogResult.OK)
8908                     return;
8909                 if (string.IsNullOrWhiteSpace(inputName.TabName))
8910                     return;
8911
8912                 id = inputName.TabName.Trim();
8913             }
8914
8915             using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
8916             {
8917                 var cancellationToken = dialog.EnableCancellation();
8918
8919                 try
8920                 {
8921                     var task = this.tw.GetUserInfo(id);
8922                     user = await dialog.WaitForAsync(this, task);
8923                 }
8924                 catch (WebApiException ex)
8925                 {
8926                     if (!cancellationToken.IsCancellationRequested)
8927                         MessageBox.Show($"Err:{ex.Message}(UsersShow)");
8928                     return;
8929                 }
8930
8931                 if (cancellationToken.IsCancellationRequested)
8932                     return;
8933             }
8934
8935             await this.DoShowUserStatus(user);
8936         }
8937
8938         private async Task DoShowUserStatus(TwitterUser user)
8939         {
8940             using var userDialog = new UserInfoDialog(this, this.tw.Api, this.detailsHtmlBuilder);
8941             var showUserTask = userDialog.ShowUserAsync(user);
8942             userDialog.ShowDialog(this);
8943
8944             this.Activate();
8945             this.BringToFront();
8946
8947             // ユーザー情報の表示が完了するまで userDialog を破棄しない
8948             await showUserTask;
8949         }
8950
8951         internal Task ShowUserStatus(string id, bool showInputDialog)
8952             => this.DoShowUserStatus(id, showInputDialog);
8953
8954         internal Task ShowUserStatus(string id)
8955             => this.DoShowUserStatus(id, true);
8956
8957         private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
8958         {
8959             var post = this.CurrentPost;
8960             if (post != null)
8961             {
8962                 await this.ShowUserStatus(post.ScreenName, false);
8963             }
8964         }
8965
8966         private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
8967         {
8968             var retweetedBy = this.CurrentPost?.RetweetedBy;
8969             if (retweetedBy != null)
8970             {
8971                 await this.ShowUserStatus(retweetedBy, false);
8972             }
8973         }
8974
8975         private async void RtCountMenuItem_Click(object sender, EventArgs e)
8976         {
8977             var post = this.CurrentPost;
8978             if (!this.ExistCurrentPost || post == null)
8979                 return;
8980
8981             var statusId = post.RetweetedId ?? post.StatusId;
8982             TwitterStatus status;
8983
8984             using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
8985             {
8986                 var cancellationToken = dialog.EnableCancellation();
8987
8988                 try
8989                 {
8990                     var task = this.tw.Api.StatusesShow(statusId.ToTwitterStatusId());
8991                     status = await dialog.WaitForAsync(this, task);
8992                 }
8993                 catch (WebApiException ex)
8994                 {
8995                     if (!cancellationToken.IsCancellationRequested)
8996                         MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
8997                     return;
8998                 }
8999
9000                 if (cancellationToken.IsCancellationRequested)
9001                     return;
9002             }
9003
9004             MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9005         }
9006
9007         private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9008         {
9009             if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9010             {
9011                 // アイコン化
9012                 this.Visible = false;
9013             }
9014             else if (Form.ActiveForm == null)
9015             {
9016                 this.Visible = true;
9017                 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9018                 this.Activate();
9019                 this.BringToFront();
9020                 this.StatusText.Focus();
9021             }
9022         }
9023
9024         private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9025             => this.MultiLinePullDownMenuItem.PerformClick();
9026
9027 #region "画像投稿"
9028         private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9029         {
9030             if (this.ImageSelector.Visible)
9031                 this.ImageSelector.EndSelection();
9032             else
9033                 this.ImageSelector.BeginSelection();
9034         }
9035
9036         private void SelectMedia_DragEnter(DragEventArgs e)
9037         {
9038             if (this.ImageSelector.Model.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9039             {
9040                 e.Effect = DragDropEffects.Copy;
9041                 return;
9042             }
9043             e.Effect = DragDropEffects.None;
9044         }
9045
9046         private void SelectMedia_DragDrop(DragEventArgs e)
9047         {
9048             this.Activate();
9049             this.BringToFront();
9050
9051             var filePathArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
9052             this.ImageSelector.BeginSelection();
9053             this.ImageSelector.Model.AddMediaItemFromFilePath(filePathArray);
9054             this.StatusText.Focus();
9055         }
9056
9057         private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9058         {
9059             this.TimelinePanel.Visible = false;
9060             this.TimelinePanel.Enabled = false;
9061         }
9062
9063         private void ImageSelector_EndSelecting(object sender, EventArgs e)
9064         {
9065             this.TimelinePanel.Visible = true;
9066             this.TimelinePanel.Enabled = true;
9067             this.CurrentListView.Focus();
9068         }
9069
9070         private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9071             => this.AllowDrop = false;
9072
9073         private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9074             => this.AllowDrop = true;
9075
9076         private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9077         {
9078             if (this.ImageSelector.Visible)
9079             {
9080                 this.MarkSettingCommonModified();
9081                 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9082             }
9083         }
9084
9085         private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9086             => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9087
9088         /// <summary>
9089         /// StatusTextでCtrl+Vが押下された時の処理
9090         /// </summary>
9091         private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9092         {
9093             try
9094             {
9095                 if (Clipboard.ContainsText())
9096                 {
9097                     // clipboardにテキストがある場合は貼り付け処理
9098                     this.StatusText.Paste(Clipboard.GetText());
9099                 }
9100                 else if (Clipboard.ContainsImage())
9101                 {
9102                     // clipboardから画像を取得
9103                     using var image = Clipboard.GetImage();
9104                     this.ImageSelector.BeginSelection();
9105                     this.ImageSelector.Model.AddMediaItemFromImage(image);
9106                 }
9107                 else if (Clipboard.ContainsFileDropList())
9108                 {
9109                     var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9110                     this.ImageSelector.BeginSelection();
9111                     this.ImageSelector.Model.AddMediaItemFromFilePath(files);
9112                 }
9113             }
9114             catch (ExternalException ex)
9115             {
9116                 MessageBox.Show(ex.Message);
9117             }
9118         }
9119 #endregion
9120
9121         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9122         {
9123             using var form = new ListManage(this.tw);
9124             form.ShowDialog(this);
9125         }
9126
9127         private bool ModifySettingCommon { get; set; }
9128
9129         private bool ModifySettingLocal { get; set; }
9130
9131         private bool ModifySettingAtId { get; set; }
9132
9133         private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9134         {
9135             var post = this.CurrentPost;
9136             if (this.ExistCurrentPost && post != null && !post.IsDm)
9137                 this.RtCountMenuItem.Enabled = true;
9138             else
9139                 this.RtCountMenuItem.Enabled = false;
9140         }
9141
9142         private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9143             => this.CopyUserId();
9144
9145         private void CopyUserId()
9146         {
9147             var post = this.CurrentPost;
9148             if (post == null) return;
9149             var clstr = post.ScreenName;
9150             try
9151             {
9152                 Clipboard.SetDataObject(clstr, false, 5, 100);
9153             }
9154             catch (Exception ex)
9155             {
9156                 MessageBox.Show(ex.Message);
9157             }
9158         }
9159
9160         private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9161         {
9162             var post = this.CurrentPost;
9163             if (this.ExistCurrentPost && post != null && !post.IsDm)
9164             {
9165                 try
9166                 {
9167                     await this.OpenRelatedTab(post);
9168                 }
9169                 catch (TabException ex)
9170                 {
9171                     MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9172                 }
9173             }
9174         }
9175
9176         /// <summary>
9177         /// 指定されたツイートに対する関連発言タブを開きます
9178         /// </summary>
9179         /// <param name="statusId">表示するツイートのID</param>
9180         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9181         public async Task OpenRelatedTab(PostId statusId)
9182         {
9183             var post = this.statuses[statusId];
9184             if (post == null)
9185             {
9186                 try
9187                 {
9188                     post = await this.tw.GetStatusApi(false, statusId.ToTwitterStatusId());
9189                 }
9190                 catch (WebApiException ex)
9191                 {
9192                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9193                     return;
9194                 }
9195             }
9196
9197             await this.OpenRelatedTab(post);
9198         }
9199
9200         /// <summary>
9201         /// 指定されたツイートに対する関連発言タブを開きます
9202         /// </summary>
9203         /// <param name="post">表示する対象となるツイート</param>
9204         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9205         private async Task OpenRelatedTab(PostClass post)
9206         {
9207             var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9208             if (tabRelated != null)
9209             {
9210                 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9211             }
9212
9213             var tabName = this.statuses.MakeTabName("Related Tweets");
9214
9215             tabRelated = new RelatedPostsTabModel(tabName, post)
9216             {
9217                 UnreadManage = false,
9218                 Notify = false,
9219             };
9220
9221             this.statuses.AddTab(tabRelated);
9222             this.AddNewTab(tabRelated, startup: false);
9223
9224             this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9225
9226             await this.RefreshTabAsync(tabRelated);
9227
9228             var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9229
9230             if (tabIndex != -1)
9231             {
9232                 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9233
9234                 var tabPage = this.ListTab.TabPages[tabIndex];
9235                 var listView = (DetailsListView)tabPage.Tag;
9236                 var targetPost = tabRelated.TargetPost;
9237                 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9238
9239                 if (index != -1 && index < listView.Items.Count)
9240                 {
9241                     listView.SelectedIndices.Add(index);
9242                     listView.Items[index].Focused = true;
9243                 }
9244             }
9245         }
9246
9247         private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9248         {
9249             var buf = new StringBuilder();
9250             buf.AppendFormat("キャッシュエントリ保持数     : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9251             buf.AppendFormat("キャッシュエントリ破棄数     : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9252             MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9253         }
9254
9255         private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9256         {
9257             MyCommon.EndingFlag = true;
9258             try
9259             {
9260                 this.Close();
9261                 Application.Restart();
9262             }
9263             catch (Exception)
9264             {
9265                 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9266             }
9267         }
9268
9269         private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9270             => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9271
9272         private bool ExistCurrentPost
9273         {
9274             get
9275             {
9276                 var post = this.CurrentPost;
9277                 return post != null && !post.IsDeleted;
9278             }
9279         }
9280
9281         private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9282             => await this.ShowUserTimeline();
9283
9284         private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9285             => await this.ShowRetweeterTimeline();
9286
9287         private string GetUserIdFromCurPostOrInput(string caption)
9288         {
9289             var id = this.CurrentPost?.ScreenName ?? "";
9290
9291             using var inputName = new InputTabName();
9292             inputName.FormTitle = caption;
9293             inputName.FormDescription = Properties.Resources.FRMessage1;
9294             inputName.TabName = id;
9295
9296             if (inputName.ShowDialog() == DialogResult.OK &&
9297                 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9298             {
9299                 id = inputName.TabName.Trim();
9300             }
9301             else
9302             {
9303                 id = "";
9304             }
9305             return id;
9306         }
9307
9308         private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9309         {
9310             var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9311             if (!MyCommon.IsNullOrEmpty(id))
9312             {
9313                 await this.AddNewTabForUserTimeline(id);
9314             }
9315         }
9316
9317         private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9318         {
9319             if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9320                 this.timelineScheduler.SystemResumed();
9321         }
9322
9323         private void SystemEvents_TimeChanged(object sender, EventArgs e)
9324         {
9325             var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9326
9327             TimeZoneInfo.ClearCachedData();
9328
9329             var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9330
9331             if (curTimeOffset != prevTimeOffset)
9332             {
9333                 // タイムゾーンの変更を反映
9334                 this.listCache?.PurgeCache();
9335                 this.CurrentListView.Refresh();
9336
9337                 this.DispSelectedPost(forceupdate: true);
9338             }
9339
9340             this.timelineScheduler.Reset();
9341         }
9342
9343         private void TimelineRefreshEnableChange(bool isEnable)
9344         {
9345             this.timelineScheduler.Enabled = isEnable;
9346         }
9347
9348         private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9349             => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9350
9351         private async Task OpenUserAppointUrl()
9352         {
9353             if (!MyCommon.IsNullOrEmpty(this.settings.Common.UserAppointUrl))
9354             {
9355                 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9356                 {
9357                     var post = this.CurrentPost;
9358                     if (post != null)
9359                     {
9360                         var xUrl = this.settings.Common.UserAppointUrl;
9361                         xUrl = xUrl.Replace("{ID}", post.ScreenName);
9362
9363                         var statusId = post.RetweetedId ?? post.StatusId;
9364                         xUrl = xUrl.Replace("{STATUS}", statusId.Id);
9365
9366                         await MyCommon.OpenInBrowserAsync(this, xUrl);
9367                     }
9368                 }
9369                 else
9370                 {
9371                     await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9372                 }
9373             }
9374         }
9375
9376         private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9377             => await this.OpenUserAppointUrl();
9378
9379         private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9380         {
9381             if (Form.ActiveForm == null)
9382             {
9383                 await this.InvokeAsync(() =>
9384                 {
9385                     this.Visible = true;
9386                     if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9387                     this.Activate();
9388                     this.BringToFront();
9389                     if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9390                     {
9391                         if (!this.GoDirectMessage(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9392                     }
9393                     else
9394                     {
9395                         if (!this.GoStatus(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9396                     }
9397                 });
9398             }
9399         }
9400
9401         private void ReplaceAppName()
9402         {
9403             this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9404             this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9405         }
9406
9407         private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9408             => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9409
9410         private void PostButton_KeyDown(object sender, KeyEventArgs e)
9411         {
9412             if (e.KeyCode == Keys.Space)
9413             {
9414                 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9415
9416                 e.SuppressKeyPress = true;
9417             }
9418         }
9419
9420         private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9421         {
9422             this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9423             this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9424             this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9425             this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9426             this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9427
9428             this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9429         }
9430
9431         private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9432             => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9433
9434         private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9435             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9436
9437         private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9438             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9439
9440         private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9441             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9442
9443         private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9444             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9445
9446         private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9447         {
9448             if (this.settings.Common.IconSize == iconSize) return;
9449
9450             var oldIconCol = this.Use2ColumnsMode;
9451
9452             this.settings.Common.IconSize = iconSize;
9453             this.ApplyListViewIconSize(iconSize);
9454
9455             if (this.Use2ColumnsMode != oldIconCol)
9456             {
9457                 foreach (TabPage tp in this.ListTab.TabPages)
9458                 {
9459                     this.ResetColumns((DetailsListView)tp.Tag);
9460                 }
9461             }
9462
9463             this.CurrentListView.Refresh();
9464             this.MarkSettingCommonModified();
9465         }
9466
9467         private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9468         {
9469             var state = this.LockListSortOrderToolStripMenuItem.Checked;
9470             if (this.settings.Common.SortOrderLock == state) return;
9471
9472             this.settings.Common.SortOrderLock = state;
9473             this.MarkSettingCommonModified();
9474         }
9475
9476         private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9477         {
9478             if (!MyCommon.IsNullOrEmpty(e.StatusText))
9479             {
9480                 this.StatusLabelUrl.Text = e.StatusText;
9481             }
9482             else
9483             {
9484                 this.SetStatusLabelUrl();
9485             }
9486         }
9487     }
9488 }