OSDN Git Service

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