OSDN Git Service

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