OSDN Git Service

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