OSDN Git Service

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