OSDN Git Service

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