OSDN Git Service

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