OSDN Git Service

初回起動時にHashStripSplitButtonのドロップダウンメニューを展開する処理をShownイベントに移動
[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             this.Visible = false;
310
311             this.TraceOutToolStripMenuItem.Checked = MyCommon.TraceFlag;
312
313             Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
314
315             Regex.CacheSize = 100;
316
317             // アイコン設定
318             this.Icon = this.iconAssets.IconMain; // メインフォーム(TweenMain)
319             this.NotifyIcon1.Icon = this.iconAssets.IconTray; // タスクトレイ
320             this.TabImage.Images.Add(this.iconAssets.IconTab); // タブ見出し
321
322             // <<<<<<<<<設定関連>>>>>>>>>
323             // 設定読み出し
324             this.LoadConfig();
325
326             // 現在の DPI と設定保存時の DPI との比を取得する
327             var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
328
329             this.initial = true;
330
331             // サムネイル関連の初期化
332             // プロキシ設定等の通信まわりの初期化が済んでから処理する
333             var imgazyobizinet = this.thumbGenerator.ImgAzyobuziNet;
334             imgazyobizinet.Enabled = this.settings.Common.EnableImgAzyobuziNet;
335             imgazyobizinet.DisabledInDM = this.settings.Common.ImgAzyobuziNetDisabledInDM;
336
337             Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.tw.Api.Connection;
338
339             // 画像投稿サービス
340             this.ImageSelector.Model.InitializeServices(this.tw, this.tw.Configuration);
341             this.ImageSelector.Model.SelectMediaService(this.settings.Common.UseImageServiceName, this.settings.Common.UseImageService);
342
343             this.tweetThumbnail1.Model.Initialize(this.thumbGenerator);
344
345             // ハッシュタグ/@id関連
346             this.AtIdSupl = new AtIdSupplement(this.settings.AtIdList.AtIdList, "@");
347             this.HashSupl = new AtIdSupplement(this.settings.Common.HashTags, "#");
348             this.HashMgr = new HashtagManage(this.HashSupl,
349                                     this.settings.Common.HashTags.ToArray(),
350                                     this.settings.Common.HashSelected,
351                                     this.settings.Common.HashIsPermanent,
352                                     this.settings.Common.HashIsHead,
353                                     this.settings.Common.HashIsNotAddToAtReply);
354             if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && this.HashMgr.IsPermanent) this.HashStripSplitButton.Text = this.HashMgr.UseHash;
355
356             // フォント&文字色&背景色保持
357             this.themeManager = new(this.settings.Local);
358             this.tweetDetailsView.Initialize(this, this.iconCache, this.themeManager);
359
360             // StringFormatオブジェクトへの事前設定
361             this.sfTab.Alignment = StringAlignment.Center;
362             this.sfTab.LineAlignment = StringAlignment.Center;
363
364             this.InitDetailHtmlFormat();
365             this.tweetDetailsView.ClearPostBrowser();
366
367             this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
368
369             this.history.Add(new StatusTextHistory(""));
370             this.hisIdx = 0;
371             this.inReplyTo = null;
372
373             // 各種ダイアログ設定
374             this.SearchDialog.Owner = this;
375             this.urlDialog.Owner = this;
376
377             // 新着バルーン通知のチェック状態設定
378             this.NewPostPopMenuItem.Checked = this.settings.Common.NewAllPop;
379             this.NotifyFileMenuItem.Checked = this.NewPostPopMenuItem.Checked;
380
381             // 新着取得時のリストスクロールをするか。trueならスクロールしない
382             this.ListLockMenuItem.Checked = this.settings.Common.ListLock;
383             this.LockListFileMenuItem.Checked = this.settings.Common.ListLock;
384             // サウンド再生(タブ別設定より優先)
385             this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
386             this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
387
388             // ウィンドウ設定
389             this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
390             this.mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
391             this.myLoc = this.settings.Local.FormLocation;
392             // タイトルバー領域
393             if (this.WindowState != FormWindowState.Minimized)
394             {
395                 var tbarRect = new Rectangle(this.myLoc, new Size(this.mySize.Width, SystemInformation.CaptionHeight));
396                 var outOfScreen = true;
397                 if (Screen.AllScreens.Length == 1) // ハングするとの報告
398                 {
399                     foreach (var scr in Screen.AllScreens)
400                     {
401                         if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
402                         {
403                             outOfScreen = false;
404                             break;
405                         }
406                     }
407
408                     if (outOfScreen)
409                         this.myLoc = new Point(0, 0);
410                 }
411                 this.DesktopLocation = this.myLoc;
412             }
413             this.TopMost = this.settings.Common.AlwaysTop;
414             this.mySpDis = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
415             this.mySpDis2 = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
416             this.mySpDis3 = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
417
418             this.PlaySoundMenuItem.Checked = this.settings.Common.PlaySound;
419             this.PlaySoundFileMenuItem.Checked = this.settings.Common.PlaySound;
420             // 入力欄
421             this.StatusText.Font = this.themeManager.FontInputFont;
422             this.StatusText.ForeColor = this.themeManager.ColorInputFont;
423
424             // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
425             this.StatusText.Multiline = false; // this.settings.Local.StatusMultiline の設定は後で反映される
426             this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
427
428             // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
429             this.SplitContainer1.IsPanelInverted = !this.settings.Common.StatusAreaAtBottom;
430
431             // 全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
432             if (this.settings.Common.UnreadManage == false)
433             {
434                 this.ReadedStripMenuItem.Enabled = false;
435                 this.UnreadStripMenuItem.Enabled = false;
436             }
437
438             // リンク先URL表示部の初期化(画面左下)
439             this.StatusLabelUrl.Text = "";
440             // 状態表示部の初期化(画面右下)
441             this.StatusLabel.Text = "";
442             this.StatusLabel.AutoToolTip = false;
443             this.StatusLabel.ToolTipText = "";
444             // 文字カウンタ初期化
445             this.lblLen.Text = this.GetRestStatusCount(this.FormatStatusTextExtended("")).ToString();
446
447             this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
448             this.CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
449             this.CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
450             this.CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
451
452             // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
453             // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
454             // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
455             this.SplitContainer2.Panel2.AccessibleName = "";
456
457             ////////////////////////////////////////////////////////////////////////////////
458             var sortOrder = (SortOrder)this.settings.Common.SortOrder;
459             var mode = this.settings.Common.SortColumn switch
460             {
461                 // 0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
462                 0 or 5 or 6 => ComparerMode.Id, // Idソートに読み替え
463                 1 => ComparerMode.Nickname, // ニックネーム
464                 2 => ComparerMode.Data, // 本文
465                 3 => ComparerMode.Id, // 時刻=発言Id
466                 4 => ComparerMode.Name, // 名前
467                 7 => ComparerMode.Source, // Source
468                 _ => ComparerMode.Id,
469             };
470             this.statuses.SetSortMode(mode, sortOrder);
471             ////////////////////////////////////////////////////////////////////////////////
472
473             this.ApplyListViewIconSize(this.settings.Common.IconSize);
474
475             // <<<<<<<<タブ関連>>>>>>>
476             foreach (var tab in this.statuses.Tabs)
477             {
478                 if (!this.AddNewTab(tab, startup: true))
479                     throw new TabException(Properties.Resources.TweenMain_LoadText1);
480             }
481
482             this.ListTabSelect(this.ListTab.SelectedTab);
483
484             // タブの位置を調整する
485             this.SetTabAlignment();
486
487             MyCommon.TwitterApiInfo.AccessLimitUpdated += this.TwitterApiStatus_AccessLimitUpdated;
488             Microsoft.Win32.SystemEvents.TimeChanged += this.SystemEvents_TimeChanged;
489
490             if (this.settings.Common.TabIconDisp)
491             {
492                 this.ListTab.DrawMode = TabDrawMode.Normal;
493             }
494             else
495             {
496                 this.ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
497                 this.ListTab.DrawItem += this.ListTab_DrawItem;
498                 this.ListTab.ImageList = null;
499             }
500
501             if (this.settings.Common.HotkeyEnabled)
502             {
503                 // グローバルホットキーの登録
504                 var modKey = HookGlobalHotkey.ModKeys.None;
505                 if ((this.settings.Common.HotkeyModifier & Keys.Alt) == Keys.Alt)
506                     modKey |= HookGlobalHotkey.ModKeys.Alt;
507                 if ((this.settings.Common.HotkeyModifier & Keys.Control) == Keys.Control)
508                     modKey |= HookGlobalHotkey.ModKeys.Ctrl;
509                 if ((this.settings.Common.HotkeyModifier & Keys.Shift) == Keys.Shift)
510                     modKey |= HookGlobalHotkey.ModKeys.Shift;
511                 if ((this.settings.Common.HotkeyModifier & Keys.LWin) == Keys.LWin)
512                     modKey |= HookGlobalHotkey.ModKeys.Win;
513
514                 this.hookGlobalHotkey.RegisterOriginalHotkey(this.settings.Common.HotkeyKey, this.settings.Common.HotkeyValue, modKey);
515             }
516
517             if (this.settings.Common.IsUseNotifyGrowl)
518                 this.gh.RegisterGrowl();
519
520             this.StatusLabel.Text = Properties.Resources.Form1_LoadText1;       // 画面右下の状態表示を変更
521
522             this.SetMainWindowTitle();
523             this.SetNotifyIconText();
524
525             if (!this.settings.Common.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
526             {
527                 this.Visible = true;
528             }
529
530             // タイマー設定
531
532             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Home] = () => this.InvokeAsync(() => this.RefreshTabAsync<HomeTabModel>());
533             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Mention] = () => this.InvokeAsync(() => this.RefreshTabAsync<MentionsTabModel>());
534             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Dm] = () => this.InvokeAsync(() => this.RefreshTabAsync<DirectMessagesTabModel>());
535             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.PublicSearch] = () => this.InvokeAsync(() => this.RefreshTabAsync<PublicSearchTabModel>());
536             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.User] = () => this.InvokeAsync(() => this.RefreshTabAsync<UserTimelineTabModel>());
537             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.List] = () => this.InvokeAsync(() => this.RefreshTabAsync<ListTimelineTabModel>());
538             this.timelineScheduler.UpdateFunc[TimelineSchedulerTaskType.Config] = () => this.InvokeAsync(() => Task.WhenAll(new[]
539             {
540                 this.DoGetFollowersMenu(),
541                 this.RefreshBlockIdsAsync(),
542                 this.RefreshMuteUserIdsAsync(),
543                 this.RefreshNoRetweetIdsAsync(),
544                 this.RefreshTwitterConfigurationAsync(),
545             }));
546             this.RefreshTimelineScheduler();
547
548             this.selectionDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.UpdateSelectedPost()), TimeSpan.FromMilliseconds(100), leading: true);
549             this.saveConfigDebouncer = DebounceTimer.Create(() => this.InvokeAsync(() => this.SaveConfigsAll(ifModified: true)), TimeSpan.FromSeconds(1));
550
551             // 更新中アイコンアニメーション間隔
552             this.TimerRefreshIcon.Interval = 200;
553             this.TimerRefreshIcon.Enabled = false;
554
555             this.ignoreConfigSave = false;
556             this.TweenMain_Resize(this, EventArgs.Empty);
557         }
558
559         private void TweenMain_Activated(object sender, EventArgs e)
560         {
561             // 画面がアクティブになったら、発言欄の背景色戻す
562             if (this.StatusText.Focused)
563             {
564                 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
565             }
566         }
567
568         private bool disposed = false;
569
570         /// <summary>
571         /// 使用中のリソースをすべてクリーンアップします。
572         /// </summary>
573         /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
574         protected override void Dispose(bool disposing)
575         {
576             base.Dispose(disposing);
577
578             if (this.disposed)
579                 return;
580
581             if (disposing)
582             {
583                 this.components?.Dispose();
584
585                 // 後始末
586                 this.SearchDialog.Dispose();
587                 this.urlDialog.Dispose();
588                 this.themeManager.Dispose();
589                 this.sfTab.Dispose();
590
591                 this.timelineScheduler.Dispose();
592                 this.workerCts.Cancel();
593                 this.thumbnailTokenSource?.Dispose();
594
595                 this.hookGlobalHotkey.Dispose();
596             }
597
598             // 終了時にRemoveHandlerしておかないとメモリリークする
599             // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
600             Microsoft.Win32.SystemEvents.PowerModeChanged -= this.SystemEvents_PowerModeChanged;
601             Microsoft.Win32.SystemEvents.TimeChanged -= this.SystemEvents_TimeChanged;
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.AppToken.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.GetTwitterAppToken(), account.Token, account.TokenSecret, account.Username, account.UserId);
2559                     else
2560                         this.tw.Initialize(TwitterAppToken.GetDefault(), "", "", "", 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.UserName = this.tw.Username;
5699                 this.settings.Common.UserId = this.tw.UserId;
5700                 this.settings.Common.Token = this.tw.AccessToken;
5701                 this.settings.Common.TokenSecret = this.tw.AccessTokenSecret;
5702                 this.settings.Common.SortOrder = (int)this.statuses.SortOrder;
5703                 this.settings.Common.SortColumn = this.statuses.SortMode switch
5704                 {
5705                     ComparerMode.Nickname => 1, // ニックネーム
5706                     ComparerMode.Data => 2, // 本文
5707                     ComparerMode.Id => 3, // 時刻=発言Id
5708                     ComparerMode.Name => 4, // 名前
5709                     ComparerMode.Source => 7, // Source
5710                     _ => throw new InvalidOperationException($"Invalid sort mode: {this.statuses.SortMode}"),
5711                 };
5712                 this.settings.Common.HashTags = this.HashMgr.HashHistories;
5713                 if (this.HashMgr.IsPermanent)
5714                 {
5715                     this.settings.Common.HashSelected = this.HashMgr.UseHash;
5716                 }
5717                 else
5718                 {
5719                     this.settings.Common.HashSelected = "";
5720                 }
5721                 this.settings.Common.HashIsHead = this.HashMgr.IsHead;
5722                 this.settings.Common.HashIsPermanent = this.HashMgr.IsPermanent;
5723                 this.settings.Common.HashIsNotAddToAtReply = this.HashMgr.IsNotAddToAtReply;
5724                 this.settings.Common.UseImageService = this.ImageSelector.Model.SelectedMediaServiceIndex;
5725                 this.settings.Common.UseImageServiceName = this.ImageSelector.Model.SelectedMediaServiceName;
5726
5727                 this.settings.SaveCommon();
5728             }
5729         }
5730
5731         private void SaveConfigsLocal()
5732         {
5733             if (this.ignoreConfigSave) return;
5734             lock (this.syncObject)
5735             {
5736                 this.ModifySettingLocal = false;
5737                 this.settings.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
5738                 this.settings.Local.FormSize = this.mySize;
5739                 this.settings.Local.FormLocation = this.myLoc;
5740                 this.settings.Local.SplitterDistance = this.mySpDis;
5741                 this.settings.Local.PreviewDistance = this.mySpDis3;
5742                 this.settings.Local.StatusMultiline = this.StatusText.Multiline;
5743                 this.settings.Local.StatusTextHeight = this.mySpDis2;
5744
5745                 if (this.ignoreConfigSave) return;
5746                 this.settings.SaveLocal();
5747             }
5748         }
5749
5750         private void SaveConfigsTabs()
5751         {
5752             var tabSettingList = new List<SettingTabs.SettingTabItem>();
5753
5754             var tabs = this.statuses.Tabs.Append(this.statuses.MuteTab);
5755
5756             foreach (var tab in tabs)
5757             {
5758                 if (!tab.IsPermanentTabType)
5759                     continue;
5760
5761                 var tabSetting = new SettingTabs.SettingTabItem
5762                 {
5763                     TabName = tab.TabName,
5764                     TabType = tab.TabType,
5765                     UnreadManage = tab.UnreadManage,
5766                     Protected = tab.Protected,
5767                     Notify = tab.Notify,
5768                     SoundFile = tab.SoundFile,
5769                 };
5770
5771                 switch (tab)
5772                 {
5773                     case FilterTabModel filterTab:
5774                         tabSetting.FilterArray = filterTab.FilterArray;
5775                         break;
5776                     case UserTimelineTabModel userTab:
5777                         tabSetting.User = userTab.ScreenName;
5778                         tabSetting.UserId = userTab.UserId;
5779                         break;
5780                     case PublicSearchTabModel searchTab:
5781                         tabSetting.SearchWords = searchTab.SearchWords;
5782                         tabSetting.SearchLang = searchTab.SearchLang;
5783                         break;
5784                     case ListTimelineTabModel listTab:
5785                         tabSetting.ListInfo = listTab.ListInfo;
5786                         break;
5787                 }
5788
5789                 tabSettingList.Add(tabSetting);
5790             }
5791
5792             this.settings.Tabs.Tabs = tabSettingList;
5793             this.settings.SaveTabs();
5794         }
5795
5796         private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
5797         {
5798             static void ShowFormatErrorDialog(IWin32Window owner)
5799             {
5800                 MessageBox.Show(
5801                     owner,
5802                     Properties.Resources.OpenURL_InvalidFormat,
5803                     Properties.Resources.OpenURL_Caption,
5804                     MessageBoxButtons.OK,
5805                     MessageBoxIcon.Error
5806                 );
5807             }
5808
5809             var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
5810             if (ret != DialogResult.OK)
5811                 return;
5812
5813             var match = Twitter.StatusUrlRegex.Match(inputText);
5814             if (!match.Success)
5815             {
5816                 ShowFormatErrorDialog(this);
5817                 return;
5818             }
5819
5820             try
5821             {
5822                 var statusId = new TwitterStatusId(match.Groups["StatusId"].Value);
5823                 await this.OpenRelatedTab(statusId);
5824             }
5825             catch (OverflowException)
5826             {
5827                 ShowFormatErrorDialog(this);
5828             }
5829             catch (TabException ex)
5830             {
5831                 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5832             }
5833         }
5834
5835         private void SaveLogMenuItem_Click(object sender, EventArgs e)
5836         {
5837             var tab = this.CurrentTab;
5838
5839             var rslt = MessageBox.Show(
5840                 string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
5841                 Properties.Resources.SaveLogMenuItem_ClickText2,
5842                 MessageBoxButtons.YesNoCancel,
5843                 MessageBoxIcon.Question);
5844             if (rslt == DialogResult.Cancel) return;
5845
5846             this.SaveFileDialog1.FileName = $"{ApplicationSettings.AssemblyName}Posts{DateTimeUtc.Now.ToLocalTime():yyMMdd-HHmmss}.tsv";
5847             this.SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
5848             this.SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
5849             this.SaveFileDialog1.FilterIndex = 0;
5850             this.SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
5851             this.SaveFileDialog1.RestoreDirectory = true;
5852
5853             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
5854             {
5855                 if (!this.SaveFileDialog1.ValidateNames) return;
5856                 using var sw = new StreamWriter(this.SaveFileDialog1.FileName, false, Encoding.UTF8);
5857                 if (rslt == DialogResult.Yes)
5858                 {
5859                     // All
5860                     for (var idx = 0; idx < tab.AllCount; idx++)
5861                     {
5862                         var post = tab[idx];
5863                         var protect = "";
5864                         if (post.IsProtect)
5865                             protect = "Protect";
5866                         sw.WriteLine(post.Nickname + "\t" +
5867                                  "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5868                                  post.CreatedAt.ToLocalTimeString() + "\t" +
5869                                  post.ScreenName + "\t" +
5870                                  post.StatusId.Id + "\t" +
5871                                  post.ImageUrl + "\t" +
5872                                  "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5873                                  protect);
5874                     }
5875                 }
5876                 else
5877                 {
5878                     foreach (var post in this.CurrentTab.SelectedPosts)
5879                     {
5880                         var protect = "";
5881                         if (post.IsProtect)
5882                             protect = "Protect";
5883                         sw.WriteLine(post.Nickname + "\t" +
5884                                  "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5885                                  post.CreatedAt.ToLocalTimeString() + "\t" +
5886                                  post.ScreenName + "\t" +
5887                                  post.StatusId.Id + "\t" +
5888                                  post.ImageUrl + "\t" +
5889                                  "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
5890                                  protect);
5891                     }
5892                 }
5893             }
5894             this.TopMost = this.settings.Common.AlwaysTop;
5895         }
5896
5897         public bool TabRename(string origTabName, [NotNullWhen(true)] out string? newTabName)
5898         {
5899             // タブ名変更
5900             newTabName = null;
5901             using (var inputName = new InputTabName())
5902             {
5903                 inputName.TabName = origTabName;
5904                 inputName.ShowDialog();
5905                 if (inputName.DialogResult == DialogResult.Cancel) return false;
5906                 newTabName = inputName.TabName;
5907             }
5908             this.TopMost = this.settings.Common.AlwaysTop;
5909             if (!MyCommon.IsNullOrEmpty(newTabName))
5910             {
5911                 // 新タブ名存在チェック
5912                 if (this.statuses.ContainsTab(newTabName))
5913                 {
5914                     var tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
5915                     MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
5916                     return false;
5917                 }
5918
5919                 var tabIndex = this.statuses.Tabs.IndexOf(origTabName);
5920                 var tabPage = this.ListTab.TabPages[tabIndex];
5921
5922                 // タブ名を変更
5923                 if (tabPage != null)
5924                     tabPage.Text = newTabName;
5925
5926                 this.statuses.RenameTab(origTabName, newTabName);
5927
5928                 var state = this.listViewState[origTabName];
5929                 this.listViewState.Remove(origTabName);
5930                 this.listViewState[newTabName] = state;
5931
5932                 this.SaveConfigsCommon();
5933                 this.SaveConfigsTabs();
5934                 this.rclickTabName = newTabName;
5935                 return true;
5936             }
5937             else
5938             {
5939                 return false;
5940             }
5941         }
5942
5943         private void ListTab_MouseClick(object sender, MouseEventArgs e)
5944         {
5945             if (e.Button == MouseButtons.Middle)
5946             {
5947                 foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
5948                 {
5949                     if (this.ListTab.GetTabRect(index).Contains(e.Location))
5950                     {
5951                         this.RemoveSpecifiedTab(tab.TabName, true);
5952                         this.SaveConfigsTabs();
5953                         break;
5954                     }
5955                 }
5956             }
5957         }
5958
5959         private void ListTab_DoubleClick(object sender, MouseEventArgs e)
5960             => this.TabRename(this.CurrentTabName, out _);
5961
5962         private void ListTab_MouseDown(object sender, MouseEventArgs e)
5963         {
5964             if (this.settings.Common.TabMouseLock) return;
5965             if (e.Button == MouseButtons.Left)
5966             {
5967                 foreach (var i in Enumerable.Range(0, this.statuses.Tabs.Count))
5968                 {
5969                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
5970                     {
5971                         this.tabDrag = true;
5972                         this.tabMouseDownPoint = e.Location;
5973                         break;
5974                     }
5975                 }
5976             }
5977             else
5978             {
5979                 this.tabDrag = false;
5980             }
5981         }
5982
5983         private void ListTab_DragEnter(object sender, DragEventArgs e)
5984         {
5985             if (e.Data.GetDataPresent(typeof(TabPage)))
5986                 e.Effect = DragDropEffects.Move;
5987             else
5988                 e.Effect = DragDropEffects.None;
5989         }
5990
5991         private void ListTab_DragDrop(object sender, DragEventArgs e)
5992         {
5993             if (!e.Data.GetDataPresent(typeof(TabPage))) return;
5994
5995             this.tabDrag = false;
5996             var tn = "";
5997             var bef = false;
5998             var cpos = new Point(e.X, e.Y);
5999             var spos = this.ListTab.PointToClient(cpos);
6000             foreach (var (tab, index) in this.statuses.Tabs.WithIndex())
6001             {
6002                 var rect = this.ListTab.GetTabRect(index);
6003                 if (rect.Contains(spos))
6004                 {
6005                     tn = tab.TabName;
6006                     if (spos.X <= (rect.Left + rect.Right) / 2)
6007                         bef = true;
6008                     else
6009                         bef = false;
6010
6011                     break;
6012                 }
6013             }
6014
6015             // タブのないところにドロップ->最後尾へ移動
6016             if (MyCommon.IsNullOrEmpty(tn))
6017             {
6018                 var lastTab = this.statuses.Tabs.Last();
6019                 tn = lastTab.TabName;
6020                 bef = false;
6021             }
6022
6023             var tp = (TabPage)e.Data.GetData(typeof(TabPage));
6024             if (tp.Text == tn) return;
6025
6026             this.ReOrderTab(tp.Text, tn, bef);
6027         }
6028
6029         public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
6030         {
6031             var baseIndex = this.GetTabPageIndex(baseTabText);
6032             if (baseIndex == -1)
6033                 return;
6034
6035             var targetIndex = this.GetTabPageIndex(targetTabText);
6036             if (targetIndex == -1)
6037                 return;
6038
6039             using (ControlTransaction.Layout(this.ListTab))
6040             {
6041                 // 選択中のタブを Remove メソッドで取り外すと選択状態が変化して Selecting イベントが発生するが、
6042                 // この時 TabInformations と TabControl の並び順が不一致なままで ListTabSelect メソッドが呼ばれてしまう。
6043                 // これを防ぐために、Remove メソッドを呼ぶ前に選択中のタブを切り替えておく必要がある
6044                 this.ListTab.SelectedIndex = targetIndex == 0 ? 1 : 0;
6045
6046                 var tab = this.statuses.Tabs[targetIndex];
6047                 var tabPage = this.ListTab.TabPages[targetIndex];
6048
6049                 this.ListTab.TabPages.Remove(tabPage);
6050
6051                 if (targetIndex < baseIndex)
6052                     baseIndex--;
6053
6054                 if (!isBeforeBaseTab)
6055                     baseIndex++;
6056
6057                 this.statuses.MoveTab(baseIndex, tab);
6058
6059                 this.ListTab.TabPages.Insert(baseIndex, tabPage);
6060             }
6061
6062             this.SaveConfigsTabs();
6063         }
6064
6065         private void MakeDirectMessageText()
6066         {
6067             var selectedPosts = this.CurrentTab.SelectedPosts;
6068             if (selectedPosts.Length > 1)
6069                 return;
6070
6071             var post = selectedPosts.Single();
6072             var text = $"D {post.ScreenName} {this.StatusText.Text}";
6073
6074             this.inReplyTo = null;
6075             this.StatusText.Text = text;
6076             this.StatusText.SelectionStart = text.Length;
6077             this.StatusText.Focus();
6078         }
6079
6080         private void MakeReplyText(bool atAll = false)
6081         {
6082             var selectedPosts = this.CurrentTab.SelectedPosts;
6083             if (selectedPosts.Any(x => x.IsDm))
6084             {
6085                 this.MakeDirectMessageText();
6086                 return;
6087             }
6088
6089             if (selectedPosts.Length == 1)
6090             {
6091                 var post = selectedPosts.Single();
6092                 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
6093                 var inReplyToScreenName = post.ScreenName;
6094                 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
6095             }
6096             else
6097             {
6098                 this.inReplyTo = null;
6099             }
6100
6101             var selfScreenName = this.tw.Username;
6102             var targetScreenNames = new List<string>();
6103             foreach (var post in selectedPosts)
6104             {
6105                 if (post.ScreenName != selfScreenName)
6106                     targetScreenNames.Add(post.ScreenName);
6107
6108                 if (atAll)
6109                 {
6110                     foreach (var (_, screenName) in post.ReplyToList)
6111                     {
6112                         if (screenName != selfScreenName)
6113                             targetScreenNames.Add(screenName);
6114                     }
6115                 }
6116             }
6117
6118             if (this.inReplyTo != null)
6119             {
6120                 var (_, screenName) = this.inReplyTo.Value;
6121                 if (screenName == selfScreenName)
6122                     targetScreenNames.Insert(0, screenName);
6123             }
6124
6125             var text = this.StatusText.Text;
6126             foreach (var screenName in targetScreenNames.AsEnumerable().Reverse())
6127             {
6128                 var atText = $"@{screenName} ";
6129                 if (!text.Contains(atText))
6130                     text = atText + text;
6131             }
6132
6133             this.StatusText.Text = text;
6134             this.StatusText.SelectionStart = text.Length;
6135             this.StatusText.Focus();
6136         }
6137
6138         private void ListTab_MouseUp(object sender, MouseEventArgs e)
6139             => this.tabDrag = false;
6140
6141         private int iconCnt = 0;
6142         private int blinkCnt = 0;
6143         private bool blink = false;
6144
6145         private void RefreshTasktrayIcon()
6146         {
6147             void EnableTasktrayAnimation()
6148                 => this.TimerRefreshIcon.Enabled = true;
6149
6150             void DisableTasktrayAnimation()
6151                 => this.TimerRefreshIcon.Enabled = false;
6152
6153             var busyTasks = this.workerSemaphore.CurrentCount != MaxWorderThreads;
6154             if (busyTasks)
6155             {
6156                 this.iconCnt += 1;
6157                 if (this.iconCnt >= this.iconAssets.IconTrayRefresh.Length)
6158                     this.iconCnt = 0;
6159
6160                 this.NotifyIcon1.Icon = this.iconAssets.IconTrayRefresh[this.iconCnt];
6161                 this.myStatusError = false;
6162                 EnableTasktrayAnimation();
6163                 return;
6164             }
6165
6166             var replyIconType = this.settings.Common.ReplyIconState;
6167             var reply = false;
6168             if (replyIconType != MyCommon.REPLY_ICONSTATE.None)
6169             {
6170                 var replyTab = this.statuses.GetTabByType<MentionsTabModel>();
6171                 if (replyTab != null && replyTab.UnreadCount > 0)
6172                     reply = true;
6173             }
6174
6175             if (replyIconType == MyCommon.REPLY_ICONSTATE.BlinkIcon && reply)
6176             {
6177                 this.blinkCnt += 1;
6178                 if (this.blinkCnt > 10)
6179                     this.blinkCnt = 0;
6180
6181                 if (this.blinkCnt == 0)
6182                     this.blink = !this.blink;
6183
6184                 this.NotifyIcon1.Icon = this.blink ? this.iconAssets.IconTrayReplyBlink : this.iconAssets.IconTrayReply;
6185                 EnableTasktrayAnimation();
6186                 return;
6187             }
6188
6189             DisableTasktrayAnimation();
6190
6191             this.iconCnt = 0;
6192             this.blinkCnt = 0;
6193             this.blink = false;
6194
6195             // 優先度:リプライ→エラー→オフライン→アイドル
6196             // エラーは更新アイコンでクリアされる
6197             if (replyIconType == MyCommon.REPLY_ICONSTATE.StaticIcon && reply)
6198                 this.NotifyIcon1.Icon = this.iconAssets.IconTrayReply;
6199             else if (this.myStatusError)
6200                 this.NotifyIcon1.Icon = this.iconAssets.IconTrayError;
6201             else if (this.myStatusOnline)
6202                 this.NotifyIcon1.Icon = this.iconAssets.IconTray;
6203             else
6204                 this.NotifyIcon1.Icon = this.iconAssets.IconTrayOffline;
6205         }
6206
6207         private void TimerRefreshIcon_Tick(object sender, EventArgs e)
6208             => this.RefreshTasktrayIcon(); // 200ms
6209
6210         private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
6211         {
6212             // 右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
6213             if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender != this.ContextMenuTabProperty)
6214                 this.rclickTabName = this.CurrentTabName;
6215
6216             if (this.statuses == null) return;
6217             if (this.statuses.Tabs == null) return;
6218
6219             if (!this.statuses.Tabs.TryGetValue(this.rclickTabName, out var tb))
6220                 return;
6221
6222             this.NotifyDispMenuItem.Checked = tb.Notify;
6223             this.NotifyTbMenuItem.Checked = tb.Notify;
6224
6225             this.soundfileListup = true;
6226             this.SoundFileComboBox.Items.Clear();
6227             this.SoundFileTbComboBox.Items.Clear();
6228             this.SoundFileComboBox.Items.Add("");
6229             this.SoundFileTbComboBox.Items.Add("");
6230             var oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
6231             if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
6232             {
6233                 oDir = oDir.GetDirectories("Sounds")[0];
6234             }
6235             foreach (var oFile in oDir.GetFiles("*.wav"))
6236             {
6237                 this.SoundFileComboBox.Items.Add(oFile.Name);
6238                 this.SoundFileTbComboBox.Items.Add(oFile.Name);
6239             }
6240             var idx = this.SoundFileComboBox.Items.IndexOf(tb.SoundFile);
6241             if (idx == -1) idx = 0;
6242             this.SoundFileComboBox.SelectedIndex = idx;
6243             this.SoundFileTbComboBox.SelectedIndex = idx;
6244             this.soundfileListup = false;
6245             this.UreadManageMenuItem.Checked = tb.UnreadManage;
6246             this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
6247
6248             this.TabMenuControl(this.rclickTabName);
6249         }
6250
6251         private void TabMenuControl(string tabName)
6252         {
6253             var tabInfo = this.statuses.GetTabByName(tabName)!;
6254
6255             this.FilterEditMenuItem.Enabled = true;
6256             this.EditRuleTbMenuItem.Enabled = true;
6257
6258             if (tabInfo.IsDefaultTabType)
6259             {
6260                 this.ProtectTabMenuItem.Enabled = false;
6261                 this.ProtectTbMenuItem.Enabled = false;
6262             }
6263             else
6264             {
6265                 this.ProtectTabMenuItem.Enabled = true;
6266                 this.ProtectTbMenuItem.Enabled = true;
6267             }
6268
6269             if (tabInfo.IsDefaultTabType || tabInfo.Protected)
6270             {
6271                 this.ProtectTabMenuItem.Checked = true;
6272                 this.ProtectTbMenuItem.Checked = true;
6273                 this.DeleteTabMenuItem.Enabled = false;
6274                 this.DeleteTbMenuItem.Enabled = false;
6275             }
6276             else
6277             {
6278                 this.ProtectTabMenuItem.Checked = false;
6279                 this.ProtectTbMenuItem.Checked = false;
6280                 this.DeleteTabMenuItem.Enabled = true;
6281                 this.DeleteTbMenuItem.Enabled = true;
6282             }
6283         }
6284
6285         private void ProtectTabMenuItem_Click(object sender, EventArgs e)
6286         {
6287             var checkState = ((ToolStripMenuItem)sender).Checked;
6288
6289             // チェック状態を同期
6290             this.ProtectTbMenuItem.Checked = checkState;
6291             this.ProtectTabMenuItem.Checked = checkState;
6292
6293             // ロック中はタブの削除を無効化
6294             this.DeleteTabMenuItem.Enabled = !checkState;
6295             this.DeleteTbMenuItem.Enabled = !checkState;
6296
6297             if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6298             this.statuses.Tabs[this.rclickTabName].Protected = checkState;
6299
6300             this.SaveConfigsTabs();
6301         }
6302
6303         private void UreadManageMenuItem_Click(object sender, EventArgs e)
6304         {
6305             this.UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6306             this.UnreadMngTbMenuItem.Checked = this.UreadManageMenuItem.Checked;
6307
6308             if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6309             this.ChangeTabUnreadManage(this.rclickTabName, this.UreadManageMenuItem.Checked);
6310
6311             this.SaveConfigsTabs();
6312         }
6313
6314         public void ChangeTabUnreadManage(string tabName, bool isManage)
6315         {
6316             var idx = this.GetTabPageIndex(tabName);
6317             if (idx == -1)
6318                 return;
6319
6320             var tab = this.statuses.Tabs[tabName];
6321             tab.UnreadManage = isManage;
6322
6323             if (this.settings.Common.TabIconDisp)
6324             {
6325                 var tabPage = this.ListTab.TabPages[idx];
6326                 if (tab.UnreadCount > 0)
6327                     tabPage.ImageIndex = 0;
6328                 else
6329                     tabPage.ImageIndex = -1;
6330             }
6331
6332             if (this.CurrentTabName == tabName)
6333             {
6334                 this.listCache?.PurgeCache();
6335                 this.CurrentListView.Refresh();
6336             }
6337
6338             this.SetMainWindowTitle();
6339             this.SetStatusLabelUrl();
6340             if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6341         }
6342
6343         private void NotifyDispMenuItem_Click(object sender, EventArgs e)
6344         {
6345             this.NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
6346             this.NotifyTbMenuItem.Checked = this.NotifyDispMenuItem.Checked;
6347
6348             if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6349
6350             this.statuses.Tabs[this.rclickTabName].Notify = this.NotifyDispMenuItem.Checked;
6351
6352             this.SaveConfigsTabs();
6353         }
6354
6355         private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
6356         {
6357             if (this.soundfileListup || MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6358
6359             this.statuses.Tabs[this.rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
6360
6361             this.SaveConfigsTabs();
6362         }
6363
6364         private void DeleteTabMenuItem_Click(object sender, EventArgs e)
6365         {
6366             if (MyCommon.IsNullOrEmpty(this.rclickTabName) || sender == this.DeleteTbMenuItem)
6367                 this.rclickTabName = this.CurrentTabName;
6368
6369             this.RemoveSpecifiedTab(this.rclickTabName, true);
6370             this.SaveConfigsTabs();
6371         }
6372
6373         private void FilterEditMenuItem_Click(object sender, EventArgs e)
6374         {
6375             if (MyCommon.IsNullOrEmpty(this.rclickTabName)) this.rclickTabName = this.statuses.HomeTab.TabName;
6376
6377             using (var fltDialog = new FilterDialog())
6378             {
6379                 fltDialog.Owner = this;
6380                 fltDialog.SetCurrent(this.rclickTabName);
6381                 fltDialog.ShowDialog(this);
6382             }
6383             this.TopMost = this.settings.Common.AlwaysTop;
6384
6385             this.ApplyPostFilters();
6386             this.SaveConfigsTabs();
6387         }
6388
6389         private async void AddTabMenuItem_Click(object sender, EventArgs e)
6390         {
6391             string? tabName = null;
6392             MyCommon.TabUsageType tabUsage;
6393             using (var inputName = new InputTabName())
6394             {
6395                 inputName.TabName = this.statuses.MakeTabName("MyTab");
6396                 inputName.IsShowUsage = true;
6397                 inputName.ShowDialog();
6398                 if (inputName.DialogResult == DialogResult.Cancel) return;
6399                 tabName = inputName.TabName;
6400                 tabUsage = inputName.Usage;
6401             }
6402             this.TopMost = this.settings.Common.AlwaysTop;
6403             if (!MyCommon.IsNullOrEmpty(tabName))
6404             {
6405                 // List対応
6406                 ListElement? list = null;
6407                 if (tabUsage == MyCommon.TabUsageType.Lists)
6408                 {
6409                     using var listAvail = new ListAvailable();
6410                     if (listAvail.ShowDialog(this) == DialogResult.Cancel)
6411                         return;
6412                     if (listAvail.SelectedList == null)
6413                         return;
6414                     list = listAvail.SelectedList;
6415                 }
6416
6417                 TabModel tab;
6418                 switch (tabUsage)
6419                 {
6420                     case MyCommon.TabUsageType.UserDefined:
6421                         tab = new FilterTabModel(tabName);
6422                         break;
6423                     case MyCommon.TabUsageType.PublicSearch:
6424                         tab = new PublicSearchTabModel(tabName);
6425                         break;
6426                     case MyCommon.TabUsageType.Lists:
6427                         tab = new ListTimelineTabModel(tabName, list!);
6428                         break;
6429                     default:
6430                         return;
6431                 }
6432
6433                 if (!this.statuses.AddTab(tab) || !this.AddNewTab(tab, startup: false))
6434                 {
6435                     var tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
6436                     MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6437                 }
6438                 else
6439                 {
6440                     // 成功
6441                     this.SaveConfigsTabs();
6442
6443                     var tabIndex = this.statuses.Tabs.Count - 1;
6444
6445                     if (tabUsage == MyCommon.TabUsageType.PublicSearch)
6446                     {
6447                         this.ListTab.SelectedIndex = tabIndex;
6448                         this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
6449                     }
6450                     if (tabUsage == MyCommon.TabUsageType.Lists)
6451                     {
6452                         this.ListTab.SelectedIndex = tabIndex;
6453                         await this.RefreshTabAsync(this.CurrentTab);
6454                     }
6455                 }
6456             }
6457         }
6458
6459         private void TabMenuItem_Click(object sender, EventArgs e)
6460         {
6461             // 選択発言を元にフィルタ追加
6462             foreach (var post in this.CurrentTab.SelectedPosts)
6463             {
6464                 // タブ選択(or追加)
6465                 if (!this.SelectTab(out var tab))
6466                     return;
6467
6468                 using (var fltDialog = new FilterDialog())
6469                 {
6470                     fltDialog.Owner = this;
6471                     fltDialog.SetCurrent(tab.TabName);
6472
6473                     if (post.RetweetedBy == null)
6474                     {
6475                         fltDialog.AddNewFilter(post.ScreenName, post.TextFromApi);
6476                     }
6477                     else
6478                     {
6479                         fltDialog.AddNewFilter(post.RetweetedBy, post.TextFromApi);
6480                     }
6481                     fltDialog.ShowDialog(this);
6482                 }
6483
6484                 this.TopMost = this.settings.Common.AlwaysTop;
6485             }
6486
6487             this.ApplyPostFilters();
6488             this.SaveConfigsTabs();
6489         }
6490
6491         protected override bool ProcessDialogKey(Keys keyData)
6492         {
6493             // TextBox1でEnterを押してもビープ音が鳴らないようにする
6494             if ((keyData & Keys.KeyCode) == Keys.Enter)
6495             {
6496                 if (this.StatusText.Focused)
6497                 {
6498                     var newLine = false;
6499                     var post = false;
6500
6501                     if (this.settings.Common.PostCtrlEnter) // Ctrl+Enter投稿時
6502                     {
6503                         if (this.StatusText.Multiline)
6504                         {
6505                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6506
6507                             if ((keyData & Keys.Control) == Keys.Control) post = true;
6508                         }
6509                         else
6510                         {
6511                             if ((keyData & Keys.Control) == Keys.Control) post = true;
6512                         }
6513                     }
6514                     else if (this.settings.Common.PostShiftEnter) // SHift+Enter投稿時
6515                     {
6516                         if (this.StatusText.Multiline)
6517                         {
6518                             if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) newLine = true;
6519
6520                             if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6521                         }
6522                         else
6523                         {
6524                             if ((keyData & Keys.Shift) == Keys.Shift) post = true;
6525                         }
6526                     }
6527                     else // Enter投稿時
6528                     {
6529                         if (this.StatusText.Multiline)
6530                         {
6531                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) newLine = true;
6532
6533                             if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
6534                                 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) post = true;
6535                         }
6536                         else
6537                         {
6538                             if (((keyData & Keys.Shift) == Keys.Shift) ||
6539                                 (((keyData & Keys.Control) != Keys.Control) &&
6540                                 ((keyData & Keys.Shift) != Keys.Shift))) post = true;
6541                         }
6542                     }
6543
6544                     if (newLine)
6545                     {
6546                         var pos1 = this.StatusText.SelectionStart;
6547                         if (this.StatusText.SelectionLength > 0)
6548                         {
6549                             this.StatusText.Text = this.StatusText.Text.Remove(pos1, this.StatusText.SelectionLength);  // 選択状態文字列削除
6550                         }
6551                         this.StatusText.Text = this.StatusText.Text.Insert(pos1, Environment.NewLine);  // 改行挿入
6552                         this.StatusText.SelectionStart = pos1 + Environment.NewLine.Length;    // カーソルを改行の次の文字へ移動
6553                         return true;
6554                     }
6555                     else if (post)
6556                     {
6557                         this.PostButton_Click(this.PostButton, EventArgs.Empty);
6558                         return true;
6559                     }
6560                 }
6561                 else
6562                 {
6563                     var tab = this.CurrentTab;
6564                     if (tab.TabType == MyCommon.TabUsageType.PublicSearch)
6565                     {
6566                         var tabPage = this.CurrentTabPage;
6567                         if (tabPage.Controls["panelSearch"].Controls["comboSearch"].Focused ||
6568                             tabPage.Controls["panelSearch"].Controls["comboLang"].Focused)
6569                         {
6570                             this.SearchButton_Click(tabPage.Controls["panelSearch"].Controls["comboSearch"], EventArgs.Empty);
6571                             return true;
6572                         }
6573                     }
6574                 }
6575             }
6576
6577             return base.ProcessDialogKey(keyData);
6578         }
6579
6580         private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
6581             => this.MakeReplyText(atAll: true);
6582
6583         private void IDRuleMenuItem_Click(object sender, EventArgs e)
6584         {
6585             var tab = this.CurrentTab;
6586             var selectedPosts = tab.SelectedPosts;
6587
6588             // 未選択なら処理終了
6589             if (selectedPosts.Length == 0)
6590                 return;
6591
6592             var screenNameArray = selectedPosts
6593                 .Select(x => x.RetweetedBy ?? x.ScreenName)
6594                 .ToArray();
6595
6596             this.AddFilterRuleByScreenName(screenNameArray);
6597
6598             if (screenNameArray.Length != 0)
6599             {
6600                 var atids = new List<string>();
6601                 foreach (var screenName in screenNameArray)
6602                 {
6603                     atids.Add("@" + screenName);
6604                 }
6605                 var cnt = this.AtIdSupl.ItemCount;
6606                 this.AtIdSupl.AddRangeItem(atids.ToArray());
6607                 if (this.AtIdSupl.ItemCount != cnt)
6608                     this.MarkSettingAtIdModified();
6609             }
6610         }
6611
6612         private void SourceRuleMenuItem_Click(object sender, EventArgs e)
6613         {
6614             var tab = this.CurrentTab;
6615             var selectedPosts = tab.SelectedPosts;
6616
6617             if (selectedPosts.Length == 0)
6618                 return;
6619
6620             var sourceArray = selectedPosts.Select(x => x.Source).ToArray();
6621
6622             this.AddFilterRuleBySource(sourceArray);
6623         }
6624
6625         public void AddFilterRuleByScreenName(params string[] screenNameArray)
6626         {
6627             // タブ選択(or追加)
6628             if (!this.SelectTab(out var tab)) return;
6629
6630             bool mv;
6631             bool mk;
6632             if (tab.TabType != MyCommon.TabUsageType.Mute)
6633             {
6634                 this.MoveOrCopy(out mv, out mk);
6635             }
6636             else
6637             {
6638                 // ミュートタブでは常に MoveMatches を true にする
6639                 mv = true;
6640                 mk = false;
6641             }
6642
6643             foreach (var screenName in screenNameArray)
6644             {
6645                 tab.AddFilter(new PostFilterRule
6646                 {
6647                     FilterName = screenName,
6648                     UseNameField = true,
6649                     MoveMatches = mv,
6650                     MarkMatches = mk,
6651                     UseRegex = false,
6652                     FilterByUrl = false,
6653                 });
6654             }
6655
6656             this.ApplyPostFilters();
6657             this.SaveConfigsTabs();
6658         }
6659
6660         public void AddFilterRuleBySource(params string[] sourceArray)
6661         {
6662             // タブ選択ダイアログを表示(or追加)
6663             if (!this.SelectTab(out var filterTab))
6664                 return;
6665
6666             bool mv;
6667             bool mk;
6668             if (filterTab.TabType != MyCommon.TabUsageType.Mute)
6669             {
6670                 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
6671                 this.MoveOrCopy(out mv, out mk);
6672             }
6673             else
6674             {
6675                 // ミュートタブでは常に MoveMatches を true にする
6676                 mv = true;
6677                 mk = false;
6678             }
6679
6680             // 振り分けルールに追加するSource
6681             foreach (var source in sourceArray)
6682             {
6683                 filterTab.AddFilter(new PostFilterRule
6684                 {
6685                     FilterSource = source,
6686                     MoveMatches = mv,
6687                     MarkMatches = mk,
6688                     UseRegex = false,
6689                     FilterByUrl = false,
6690                 });
6691             }
6692
6693             this.ApplyPostFilters();
6694             this.SaveConfigsTabs();
6695         }
6696
6697         private bool SelectTab([NotNullWhen(true)] out FilterTabModel? tab)
6698         {
6699             do
6700             {
6701                 tab = null;
6702
6703                 // 振り分け先タブ選択
6704                 using (var dialog = new TabsDialog(this.statuses))
6705                 {
6706                     if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
6707
6708                     tab = dialog.SelectedTab;
6709                 }
6710
6711                 this.CurrentTabPage.Focus();
6712                 // 新規タブを選択→タブ作成
6713                 if (tab == null)
6714                 {
6715                     string tabName;
6716                     using (var inputName = new InputTabName())
6717                     {
6718                         inputName.TabName = this.statuses.MakeTabName("MyTab");
6719                         inputName.ShowDialog();
6720                         if (inputName.DialogResult == DialogResult.Cancel) return false;
6721                         tabName = inputName.TabName;
6722                     }
6723                     this.TopMost = this.settings.Common.AlwaysTop;
6724                     if (!MyCommon.IsNullOrEmpty(tabName))
6725                     {
6726                         var newTab = new FilterTabModel(tabName);
6727                         if (!this.statuses.AddTab(newTab) || !this.AddNewTab(newTab, startup: false))
6728                         {
6729                             var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
6730                             MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
6731                             // もう一度タブ名入力
6732                         }
6733                         else
6734                         {
6735                             tab = newTab;
6736                             return true;
6737                         }
6738                     }
6739                 }
6740                 else
6741                 {
6742                     // 既存タブを選択
6743                     return true;
6744                 }
6745             }
6746             while (true);
6747         }
6748
6749         private void MoveOrCopy(out bool move, out bool mark)
6750         {
6751             {
6752                 // 移動するか?
6753                 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
6754                 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6755                     move = false;
6756                 else
6757                     move = true;
6758             }
6759             if (!move)
6760             {
6761                 // マークするか?
6762                 var tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
6763                 if (MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
6764                     mark = true;
6765                 else
6766                     mark = false;
6767             }
6768             else
6769             {
6770                 mark = false;
6771             }
6772         }
6773
6774         private void CopySTOTMenuItem_Click(object sender, EventArgs e)
6775             => this.CopyStot();
6776
6777         private void CopyURLMenuItem_Click(object sender, EventArgs e)
6778             => this.CopyIdUri();
6779
6780         private void SelectAllMenuItem_Click(object sender, EventArgs e)
6781         {
6782             if (this.StatusText.Focused)
6783             {
6784                 // 発言欄でのCtrl+A
6785                 this.StatusText.SelectAll();
6786             }
6787             else
6788             {
6789                 // ListView上でのCtrl+A
6790                 NativeMethods.SelectAllItems(this.CurrentListView);
6791             }
6792         }
6793
6794         private void MoveMiddle()
6795         {
6796             ListViewItem item;
6797             int idx1;
6798             int idx2;
6799
6800             var listView = this.CurrentListView;
6801             if (listView.SelectedIndices.Count == 0) return;
6802
6803             var idx = listView.SelectedIndices[0];
6804
6805             item = listView.GetItemAt(0, 25);
6806             if (item == null)
6807                 idx1 = 0;
6808             else
6809                 idx1 = item.Index;
6810
6811             item = listView.GetItemAt(0, listView.ClientSize.Height - 1);
6812             if (item == null)
6813                 idx2 = listView.VirtualListSize - 1;
6814             else
6815                 idx2 = item.Index;
6816
6817             idx -= Math.Abs(idx1 - idx2) / 2;
6818             if (idx < 0) idx = 0;
6819
6820             listView.EnsureVisible(listView.VirtualListSize - 1);
6821             listView.EnsureVisible(idx);
6822         }
6823
6824         private async void OpenURLMenuItem_Click(object sender, EventArgs e)
6825         {
6826             var linkElements = this.tweetDetailsView.GetLinkElements();
6827
6828             if (linkElements.Length == 0)
6829                 return;
6830
6831             var links = new List<OpenUrlItem>(linkElements.Length);
6832
6833             foreach (var linkElm in linkElements)
6834             {
6835                 var displayUrl = linkElm.GetAttribute("title");
6836                 var href = linkElm.GetAttribute("href");
6837                 var linkedText = linkElm.InnerText;
6838
6839                 if (MyCommon.IsNullOrEmpty(displayUrl))
6840                     displayUrl = href;
6841
6842                 links.Add(new OpenUrlItem(linkedText, displayUrl, href));
6843             }
6844
6845             string selectedUrl;
6846             bool isReverseSettings;
6847
6848             if (links.Count == 1)
6849             {
6850                 // ツイートに含まれる URL が 1 つのみの場合
6851                 //   => OpenURL ダイアログを表示せずにリンクを開く
6852                 selectedUrl = links[0].Href;
6853
6854                 // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
6855                 isReverseSettings = false;
6856             }
6857             else
6858             {
6859                 // ツイートに含まれる URL が複数ある場合
6860                 //   => OpenURL を表示しユーザーが選択したリンクを開く
6861                 this.urlDialog.ClearUrl();
6862
6863                 foreach (var link in links)
6864                     this.urlDialog.AddUrl(link);
6865
6866                 if (this.urlDialog.ShowDialog(this) != DialogResult.OK)
6867                     return;
6868
6869                 this.TopMost = this.settings.Common.AlwaysTop;
6870
6871                 selectedUrl = this.urlDialog.SelectedUrl;
6872
6873                 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
6874                 isReverseSettings = MyCommon.IsKeyDown(Keys.Control);
6875             }
6876
6877             await this.OpenUriAsync(new Uri(selectedUrl), isReverseSettings);
6878         }
6879
6880         private void ClearTabMenuItem_Click(object sender, EventArgs e)
6881         {
6882             if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
6883             this.ClearTab(this.rclickTabName, true);
6884         }
6885
6886         private void ClearTab(string tabName, bool showWarning)
6887         {
6888             if (showWarning)
6889             {
6890                 var tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
6891                 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
6892                 {
6893                     return;
6894                 }
6895             }
6896
6897             this.statuses.ClearTabIds(tabName);
6898             if (this.CurrentTabName == tabName)
6899             {
6900                 this.CurrentTab.ClearAnchor();
6901                 this.listCache?.PurgeCache();
6902                 this.listCache?.UpdateListSize();
6903             }
6904
6905             var tabIndex = this.statuses.Tabs.IndexOf(tabName);
6906             var tabPage = this.ListTab.TabPages[tabIndex];
6907             tabPage.ImageIndex = -1;
6908
6909             if (!this.settings.Common.TabIconDisp) this.ListTab.Refresh();
6910
6911             this.SetMainWindowTitle();
6912             this.SetStatusLabelUrl();
6913         }
6914
6915         private static long followers = 0;
6916
6917         private void SetMainWindowTitle()
6918         {
6919             // メインウインドウタイトルの書き換え
6920             var ttl = new StringBuilder(256);
6921             var ur = 0;
6922             var al = 0;
6923             if (this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
6924                 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6925                 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6926                 this.settings.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6927             {
6928                 foreach (var tab in this.statuses.Tabs)
6929                 {
6930                     ur += tab.UnreadCount;
6931                     al += tab.AllCount;
6932                 }
6933             }
6934
6935             if (this.settings.Common.DispUsername) ttl.Append(this.tw.Username).Append(" - ");
6936             ttl.Append(ApplicationSettings.ApplicationName);
6937             ttl.Append("  ");
6938             switch (this.settings.Common.DispLatestPost)
6939             {
6940                 case MyCommon.DispTitleEnum.Ver:
6941                     ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
6942                     break;
6943                 case MyCommon.DispTitleEnum.Post:
6944                     if (this.history != null && this.history.Count > 1)
6945                         ttl.Append(this.history[this.history.Count - 2].Status.Replace("\r\n", " "));
6946                     break;
6947                 case MyCommon.DispTitleEnum.UnreadRepCount:
6948                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6949                     break;
6950                 case MyCommon.DispTitleEnum.UnreadAllCount:
6951                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
6952                     break;
6953                 case MyCommon.DispTitleEnum.UnreadAllRepCount:
6954                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, this.statuses.MentionTab.UnreadCount + this.statuses.DirectMessageTab.UnreadCount);
6955                     break;
6956                 case MyCommon.DispTitleEnum.UnreadCountAllCount:
6957                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
6958                     break;
6959                 case MyCommon.DispTitleEnum.OwnStatus:
6960                     if (followers == 0 && this.tw.FollowersCount > 0) followers = this.tw.FollowersCount;
6961                     ttl.AppendFormat(Properties.Resources.OwnStatusTitle, this.tw.StatusesCount, this.tw.FriendsCount, this.tw.FollowersCount, this.tw.FollowersCount - followers);
6962                     break;
6963             }
6964
6965             try
6966             {
6967                 this.Text = ttl.ToString();
6968             }
6969             catch (AccessViolationException)
6970             {
6971                 // 原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
6972             }
6973         }
6974
6975         private string GetStatusLabelText()
6976         {
6977             // ステータス欄にカウント表示
6978             // タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
6979             if (this.statuses == null) return "";
6980             var tbRep = this.statuses.MentionTab;
6981             var tbDm = this.statuses.DirectMessageTab;
6982             if (tbRep == null || tbDm == null) return "";
6983             var urat = tbRep.UnreadCount + tbDm.UnreadCount;
6984             var ur = 0;
6985             var al = 0;
6986             var tur = 0;
6987             var tal = 0;
6988             var slbl = new StringBuilder(256);
6989             try
6990             {
6991                 foreach (var tab in this.statuses.Tabs)
6992                 {
6993                     ur += tab.UnreadCount;
6994                     al += tab.AllCount;
6995                     if (tab.TabName == this.CurrentTabName)
6996                     {
6997                         tur = tab.UnreadCount;
6998                         tal = tab.AllCount;
6999                     }
7000                 }
7001             }
7002             catch (Exception)
7003             {
7004                 return "";
7005             }
7006
7007             this.unreadCounter = ur;
7008             this.unreadAtCounter = urat;
7009
7010             var homeTab = this.statuses.HomeTab;
7011
7012             slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, this.postTimestamps.Count, this.favTimestamps.Count, homeTab.TweetsPerHour);
7013             if (this.settings.Common.TimelinePeriod == 0)
7014             {
7015                 slbl.Append(Properties.Resources.SetStatusLabelText2);
7016             }
7017             else
7018             {
7019                 slbl.Append(this.settings.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
7020             }
7021             return slbl.ToString();
7022         }
7023
7024         private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
7025         {
7026             try
7027             {
7028                 if (this.InvokeRequired && !this.IsDisposed)
7029                 {
7030                     await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
7031                 }
7032                 else
7033                 {
7034                     var endpointName = ((TwitterApiStatus.AccessLimitUpdatedEventArgs)e).EndpointName;
7035                     this.SetApiStatusLabel(endpointName);
7036                 }
7037             }
7038             catch (ObjectDisposedException)
7039             {
7040                 return;
7041             }
7042             catch (InvalidOperationException)
7043             {
7044                 return;
7045             }
7046         }
7047
7048         private void SetApiStatusLabel(string? endpointName = null)
7049         {
7050             var tabType = this.CurrentTab.TabType;
7051
7052             if (endpointName == null)
7053             {
7054                 var authByCookie = this.tw.Api.AppToken.AuthType == APIAuthType.TwitterComCookie;
7055
7056                 // 表示中のタブに応じて更新
7057                 endpointName = tabType switch
7058                 {
7059                     MyCommon.TabUsageType.Home => "/statuses/home_timeline",
7060                     MyCommon.TabUsageType.UserDefined => "/statuses/home_timeline",
7061                     MyCommon.TabUsageType.Mentions => "/statuses/mentions_timeline",
7062                     MyCommon.TabUsageType.Favorites => "/favorites/list",
7063                     MyCommon.TabUsageType.DirectMessage => "/direct_messages/events/list",
7064                     MyCommon.TabUsageType.UserTimeline =>
7065                         authByCookie ? UserTweetsAndRepliesRequest.EndpointName : "/statuses/user_timeline",
7066                     MyCommon.TabUsageType.Lists =>
7067                         authByCookie ? ListLatestTweetsTimelineRequest.EndpointName : "/lists/statuses",
7068                     MyCommon.TabUsageType.PublicSearch =>
7069                         authByCookie ? SearchTimelineRequest.EndpointName : "/search/tweets",
7070                     MyCommon.TabUsageType.Related => "/statuses/show/:id",
7071                     _ => null,
7072                 };
7073                 this.toolStripApiGauge.ApiEndpoint = endpointName;
7074             }
7075             else
7076             {
7077                 var currentEndpointName = this.toolStripApiGauge.ApiEndpoint;
7078                 this.toolStripApiGauge.ApiEndpoint = currentEndpointName;
7079             }
7080         }
7081
7082         private void SetStatusLabelUrl()
7083             => this.StatusLabelUrl.Text = this.GetStatusLabelText();
7084
7085         public void SetStatusLabel(string text)
7086             => this.StatusLabel.Text = text;
7087
7088         private void SetNotifyIconText()
7089         {
7090             var ur = new StringBuilder(64);
7091
7092             // タスクトレイアイコンのツールチップテキスト書き換え
7093             // Tween [未読/@]
7094             ur.Remove(0, ur.Length);
7095             if (this.settings.Common.DispUsername)
7096             {
7097                 ur.Append(this.tw.Username);
7098                 ur.Append(" - ");
7099             }
7100             ur.Append(ApplicationSettings.ApplicationName);
7101 #if DEBUG
7102             ur.Append("(Debug Build)");
7103 #endif
7104             if (this.unreadCounter != -1 && this.unreadAtCounter != -1)
7105             {
7106                 ur.Append(" [");
7107                 ur.Append(this.unreadCounter);
7108                 ur.Append("/@");
7109                 ur.Append(this.unreadAtCounter);
7110                 ur.Append("]");
7111             }
7112             this.NotifyIcon1.Text = ur.ToString();
7113         }
7114
7115         internal void CheckReplyTo(string statusText)
7116         {
7117             MatchCollection m;
7118             // ハッシュタグの保存
7119             m = Regex.Matches(statusText, Twitter.Hashtag, RegexOptions.IgnoreCase);
7120             var hstr = "";
7121             foreach (Match hm in m)
7122             {
7123                 if (!hstr.Contains("#" + hm.Result("$3") + " "))
7124                 {
7125                     hstr += "#" + hm.Result("$3") + " ";
7126                     this.HashSupl.AddItem("#" + hm.Result("$3"));
7127                 }
7128             }
7129             if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash) && !hstr.Contains(this.HashMgr.UseHash + " "))
7130             {
7131                 hstr += this.HashMgr.UseHash;
7132             }
7133             if (!MyCommon.IsNullOrEmpty(hstr)) this.HashMgr.AddHashToHistory(hstr.Trim(), false);
7134
7135             // 本当にリプライ先指定すべきかどうかの判定
7136             m = Regex.Matches(statusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
7137
7138             if (this.settings.Common.UseAtIdSupplement)
7139             {
7140                 var bCnt = this.AtIdSupl.ItemCount;
7141                 foreach (Match mid in m)
7142                 {
7143                     this.AtIdSupl.AddItem(mid.Result("${id}"));
7144                 }
7145                 if (bCnt != this.AtIdSupl.ItemCount)
7146                     this.MarkSettingAtIdModified();
7147             }
7148
7149             // リプライ先ステータスIDの指定がない場合は指定しない
7150             if (this.inReplyTo == null)
7151                 return;
7152
7153             // 通常Reply
7154             // 次の条件を満たす場合に in_reply_to_status_id 指定
7155             // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
7156             // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
7157             // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
7158
7159             if (m != null)
7160             {
7161                 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
7162                 if (statusText.StartsWith("@", StringComparison.Ordinal))
7163                 {
7164                     if (statusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
7165                 }
7166                 else
7167                 {
7168                     foreach (Match mid in m)
7169                     {
7170                         if (statusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
7171                     }
7172                 }
7173             }
7174
7175             this.inReplyTo = null;
7176         }
7177
7178         private void TweenMain_Resize(object sender, EventArgs e)
7179         {
7180             if (!this.initialLayout && this.settings.Common.MinimizeToTray && this.WindowState == FormWindowState.Minimized)
7181             {
7182                 this.Visible = false;
7183             }
7184             if (this.initialLayout && this.settings.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
7185             {
7186                 // 現在の DPI と設定保存時の DPI との比を取得する
7187                 var configScaleFactor = this.settings.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
7188
7189                 this.ClientSize = ScaleBy(configScaleFactor, this.settings.Local.FormSize);
7190
7191                 // Splitterの位置設定
7192                 var splitterDistance = ScaleBy(configScaleFactor.Height, this.settings.Local.SplitterDistance);
7193                 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
7194                     splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
7195                 {
7196                     this.SplitContainer1.SplitterDistance = splitterDistance;
7197                 }
7198
7199                 // 発言欄複数行
7200                 this.StatusText.Multiline = this.settings.Local.StatusMultiline;
7201                 if (this.StatusText.Multiline)
7202                 {
7203                     var statusTextHeight = ScaleBy(configScaleFactor.Height, this.settings.Local.StatusTextHeight);
7204                     var dis = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7205                     if (dis > this.SplitContainer2.Panel1MinSize && dis < this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth)
7206                     {
7207                         this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - statusTextHeight - this.SplitContainer2.SplitterWidth;
7208                     }
7209                     this.StatusText.Height = statusTextHeight;
7210                 }
7211                 else
7212                 {
7213                     if (this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth > 0)
7214                     {
7215                         this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7216                     }
7217                 }
7218
7219                 var previewDistance = ScaleBy(configScaleFactor.Width, this.settings.Local.PreviewDistance);
7220                 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
7221                 {
7222                     this.SplitContainer3.SplitterDistance = previewDistance;
7223                 }
7224
7225                 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
7226                 this.SplitContainer3.Panel2Collapsed = true;
7227
7228                 this.initialLayout = false;
7229             }
7230             if (this.WindowState != FormWindowState.Minimized)
7231             {
7232                 this.formWindowState = this.WindowState;
7233             }
7234         }
7235
7236         private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
7237         {
7238             this.PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7239             this.PlaySoundFileMenuItem.Checked = this.PlaySoundMenuItem.Checked;
7240             if (this.PlaySoundMenuItem.Checked)
7241             {
7242                 this.settings.Common.PlaySound = true;
7243             }
7244             else
7245             {
7246                 this.settings.Common.PlaySound = false;
7247             }
7248             this.MarkSettingCommonModified();
7249         }
7250
7251         private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
7252         {
7253             if (this.initialLayout)
7254                 return;
7255
7256             int splitterDistance;
7257             switch (this.WindowState)
7258             {
7259                 case FormWindowState.Normal:
7260                     splitterDistance = this.SplitContainer1.SplitterDistance;
7261                     break;
7262                 case FormWindowState.Maximized:
7263                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
7264                     var normalContainerHeight = this.mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
7265                     splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
7266                     splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
7267                     break;
7268                 default:
7269                     return;
7270             }
7271
7272             this.mySpDis = splitterDistance;
7273             this.MarkSettingLocalModified();
7274         }
7275
7276         private async Task DoRepliedStatusOpen()
7277         {
7278             var currentPost = this.CurrentPost;
7279             if (this.ExistCurrentPost && currentPost != null && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
7280             {
7281                 if (MyCommon.IsKeyDown(Keys.Shift))
7282                 {
7283                     await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7284                     return;
7285                 }
7286                 if (this.statuses.Posts.TryGetValue(currentPost.InReplyToStatusId, out var repPost))
7287                 {
7288                     MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname}   ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7289                 }
7290                 else
7291                 {
7292                     foreach (var tb in this.statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
7293                     {
7294                         if (tb == null || !tb.Contains(currentPost.InReplyToStatusId)) break;
7295                         repPost = tb.Posts[currentPost.InReplyToStatusId];
7296                         MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname}   ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
7297                         return;
7298                     }
7299                     await MyCommon.OpenInBrowserAsync(this, MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.ToTwitterStatusId()));
7300                 }
7301             }
7302         }
7303
7304         private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
7305             => await this.DoRepliedStatusOpen();
7306
7307         private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
7308         {
7309             if (this.initialLayout)
7310                 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
7311
7312             var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
7313             if (multiline != this.StatusText.Multiline)
7314             {
7315                 this.StatusText.Multiline = multiline;
7316                 this.settings.Local.StatusMultiline = multiline;
7317                 this.MarkSettingLocalModified();
7318             }
7319         }
7320
7321         private void StatusText_MultilineChanged(object sender, EventArgs e)
7322         {
7323             if (this.StatusText.Multiline)
7324                 this.StatusText.ScrollBars = ScrollBars.Vertical;
7325             else
7326                 this.StatusText.ScrollBars = ScrollBars.None;
7327
7328             if (!this.initialLayout)
7329                 this.MarkSettingLocalModified();
7330         }
7331
7332         private void MultiLineMenuItem_Click(object sender, EventArgs e)
7333         {
7334             // 発言欄複数行
7335             var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
7336             this.StatusText.Multiline = menuItemChecked;
7337             this.settings.Local.StatusMultiline = menuItemChecked;
7338             if (menuItemChecked)
7339             {
7340                 if (this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth < 0)
7341                     this.SplitContainer2.SplitterDistance = 0;
7342                 else
7343                     this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.mySpDis2 - this.SplitContainer2.SplitterWidth;
7344             }
7345             else
7346             {
7347                 this.SplitContainer2.SplitterDistance = this.SplitContainer2.Height - this.SplitContainer2.Panel2MinSize - this.SplitContainer2.SplitterWidth;
7348             }
7349             this.MarkSettingLocalModified();
7350         }
7351
7352         private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter converterType)
7353         {
7354             if (converterType == MyCommon.UrlConverter.Bitly || converterType == MyCommon.UrlConverter.Jmp)
7355             {
7356                 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
7357                 if (MyCommon.IsNullOrEmpty(this.settings.Common.BitlyAccessToken) &&
7358                     (MyCommon.IsNullOrEmpty(this.settings.Common.BilyUser) || MyCommon.IsNullOrEmpty(this.settings.Common.BitlyPwd)))
7359                 {
7360                     MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
7361                     return false;
7362                 }
7363             }
7364
7365             // Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
7366             // 参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
7367             // Appendix A.  Collected ABNF for URI
7368             // http://www.ietf.org/rfc/rfc3986.txt
7369
7370             const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
7371
7372             string result;
7373             if (this.StatusText.SelectionLength > 0)
7374             {
7375                 var tmp = this.StatusText.SelectedText;
7376                 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
7377                 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
7378                 {
7379                     // 文字列が選択されている場合はその文字列について処理
7380
7381                     // nico.ms使用、nicovideoにマッチしたら変換
7382                     if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7383                     {
7384                         result = Nicoms.Shorten(tmp);
7385                     }
7386                     else if (converterType != MyCommon.UrlConverter.Nicoms)
7387                     {
7388                         // 短縮URL変換
7389                         try
7390                         {
7391                             var srcUri = new Uri(tmp);
7392                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7393                             result = resultUri.AbsoluteUri;
7394                         }
7395                         catch (WebApiException e)
7396                         {
7397                             this.StatusLabel.Text = converterType + ":" + e.Message;
7398                             return false;
7399                         }
7400                         catch (UriFormatException e)
7401                         {
7402                             this.StatusLabel.Text = converterType + ":" + e.Message;
7403                             return false;
7404                         }
7405                     }
7406                     else
7407                     {
7408                         return true;
7409                     }
7410
7411                     if (!MyCommon.IsNullOrEmpty(result))
7412                     {
7413                         // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7414                         var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
7415                         if (origUrlIndex == -1)
7416                             return false;
7417
7418                         this.StatusText.Select(origUrlIndex, tmp.Length);
7419                         this.StatusText.SelectedText = result;
7420
7421                         // undoバッファにセット
7422                         var undo = new UrlUndo
7423                         {
7424                             Before = tmp,
7425                             After = result,
7426                         };
7427
7428                         if (this.urlUndoBuffer == null)
7429                         {
7430                             this.urlUndoBuffer = new List<UrlUndo>();
7431                             this.UrlUndoToolStripMenuItem.Enabled = true;
7432                         }
7433
7434                         this.urlUndoBuffer.Add(undo);
7435                     }
7436                 }
7437             }
7438             else
7439             {
7440                 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
7441                                    @"(?<url>(?<protocol>https?://)" +
7442                                    @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
7443                                    @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
7444                                    @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
7445                 // 正規表現にマッチしたURL文字列をtinyurl化
7446                 foreach (Match mt in Regex.Matches(this.StatusText.Text, url, RegexOptions.IgnoreCase))
7447                 {
7448                     if (this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1)
7449                         continue;
7450                     var tmp = mt.Result("${url}");
7451                     if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase))
7452                         tmp = "http://" + tmp;
7453
7454                     // 選んだURLを選択(?)
7455                     this.StatusText.Select(this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
7456
7457                     // nico.ms使用、nicovideoにマッチしたら変換
7458                     if (this.settings.Common.Nicoms && Regex.IsMatch(tmp, nico))
7459                     {
7460                         result = Nicoms.Shorten(tmp);
7461                     }
7462                     else if (converterType != MyCommon.UrlConverter.Nicoms)
7463                     {
7464                         // 短縮URL変換
7465                         try
7466                         {
7467                             var srcUri = new Uri(tmp);
7468                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(converterType, srcUri);
7469                             result = resultUri.AbsoluteUri;
7470                         }
7471                         catch (HttpRequestException e)
7472                         {
7473                             // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
7474                             // のように長いので「:」が含まれていればそれ以降のみを抽出する
7475                             var message = e.Message.Split(new[] { ':' }, count: 2).Last();
7476
7477                             this.StatusLabel.Text = converterType + ":" + message;
7478                             continue;
7479                         }
7480                         catch (WebApiException e)
7481                         {
7482                             this.StatusLabel.Text = converterType + ":" + e.Message;
7483                             continue;
7484                         }
7485                         catch (UriFormatException e)
7486                         {
7487                             this.StatusLabel.Text = converterType + ":" + e.Message;
7488                             continue;
7489                         }
7490                     }
7491                     else
7492                     {
7493                         continue;
7494                     }
7495
7496                     if (!MyCommon.IsNullOrEmpty(result))
7497                     {
7498                         // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
7499                         var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
7500                         if (origUrlIndex == -1)
7501                             return false;
7502
7503                         this.StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
7504                         this.StatusText.SelectedText = result;
7505                         // undoバッファにセット
7506                         var undo = new UrlUndo
7507                         {
7508                             Before = mt.Result("${url}"),
7509                             After = result,
7510                         };
7511
7512                         if (this.urlUndoBuffer == null)
7513                         {
7514                             this.urlUndoBuffer = new List<UrlUndo>();
7515                             this.UrlUndoToolStripMenuItem.Enabled = true;
7516                         }
7517
7518                         this.urlUndoBuffer.Add(undo);
7519                     }
7520                 }
7521             }
7522
7523             return true;
7524         }
7525
7526         private void DoUrlUndo()
7527         {
7528             if (this.urlUndoBuffer != null)
7529             {
7530                 var tmp = this.StatusText.Text;
7531                 foreach (var data in this.urlUndoBuffer)
7532                 {
7533                     tmp = tmp.Replace(data.After, data.Before);
7534                 }
7535                 this.StatusText.Text = tmp;
7536                 this.urlUndoBuffer = null;
7537                 this.UrlUndoToolStripMenuItem.Enabled = false;
7538                 this.StatusText.SelectionStart = 0;
7539                 this.StatusText.SelectionLength = 0;
7540             }
7541         }
7542
7543         private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
7544             => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
7545
7546         private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
7547             => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
7548
7549         private async void UxnuMenuItem_Click(object sender, EventArgs e)
7550             => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
7551
7552         private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
7553         {
7554             if (!await this.UrlConvertAsync(this.settings.Common.AutoShortUrlFirst))
7555             {
7556                 var rnd = new Random();
7557
7558                 MyCommon.UrlConverter svc;
7559                 // 前回使用した短縮URLサービス以外を選択する
7560                 do
7561                 {
7562                     svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
7563                 }
7564                 while (svc == this.settings.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
7565                 await this.UrlConvertAsync(svc);
7566             }
7567         }
7568
7569         private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
7570             => this.DoUrlUndo();
7571
7572         private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
7573         {
7574             this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7575             this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
7576             this.settings.Common.NewAllPop = this.NewPostPopMenuItem.Checked;
7577             this.MarkSettingCommonModified();
7578         }
7579
7580         private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
7581         {
7582             this.ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
7583             this.LockListFileMenuItem.Checked = this.ListLockMenuItem.Checked;
7584             this.settings.Common.ListLock = this.ListLockMenuItem.Checked;
7585             this.MarkSettingCommonModified();
7586         }
7587
7588         private void MenuStrip1_MenuActivate(object sender, EventArgs e)
7589         {
7590             // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
7591             this.MenuStrip1.Tag = new object();
7592             this.MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
7593         }
7594
7595         private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
7596         {
7597             var currentTabPage = this.CurrentTabPage;
7598             if (this.Tag != null) // 設定された戻り先へ遷移
7599             {
7600                 if (this.Tag == currentTabPage)
7601                     ((Control)currentTabPage.Tag).Select();
7602                 else
7603                     ((Control)this.Tag).Select();
7604             }
7605             else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
7606             {
7607                 this.Tag = currentTabPage.Tag;
7608                 ((Control)this.Tag).Select();
7609             }
7610             // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
7611             this.MenuStrip1.Tag = null;
7612         }
7613
7614         private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
7615         {
7616             if (this.Use2ColumnsMode)
7617             {
7618                 e.Cancel = true;
7619                 return;
7620             }
7621
7622             var lst = (DetailsListView)sender;
7623             var columnsCount = lst.Columns.Count;
7624
7625             var darr = new int[columnsCount];
7626             for (var i = 0; i < columnsCount; i++)
7627                 darr[lst.Columns[i].DisplayIndex] = i;
7628
7629             MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
7630
7631             for (var i = 0; i < columnsCount; i++)
7632                 this.settings.Local.ColumnsOrder[darr[i]] = i;
7633
7634             this.MarkSettingLocalModified();
7635             this.isColumnChanged = true;
7636         }
7637
7638         private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
7639         {
7640             var lst = (DetailsListView)sender;
7641             if (this.settings.Local == null) return;
7642
7643             var modified = false;
7644             if (this.Use2ColumnsMode)
7645             {
7646                 if (this.settings.Local.ColumnsWidth[0] != lst.Columns[0].Width)
7647                 {
7648                     this.settings.Local.ColumnsWidth[0] = lst.Columns[0].Width;
7649                     modified = true;
7650                 }
7651                 if (this.settings.Local.ColumnsWidth[2] != lst.Columns[1].Width)
7652                 {
7653                     this.settings.Local.ColumnsWidth[2] = lst.Columns[1].Width;
7654                     modified = true;
7655                 }
7656             }
7657             else
7658             {
7659                 var columnsCount = lst.Columns.Count;
7660                 for (var i = 0; i < columnsCount; i++)
7661                 {
7662                     if (this.settings.Local.ColumnsWidth[i] == lst.Columns[i].Width)
7663                         continue;
7664
7665                     this.settings.Local.ColumnsWidth[i] = lst.Columns[i].Width;
7666                     modified = true;
7667                 }
7668             }
7669             if (modified)
7670             {
7671                 this.MarkSettingLocalModified();
7672                 this.isColumnChanged = true;
7673             }
7674         }
7675
7676         private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
7677         {
7678             if (this.StatusText.Multiline) this.mySpDis2 = this.StatusText.Height;
7679             this.MarkSettingLocalModified();
7680         }
7681
7682         private void TweenMain_DragDrop(object sender, DragEventArgs e)
7683         {
7684             if (e.Data.GetDataPresent(DataFormats.FileDrop))
7685             {
7686                 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7687                 {
7688                     this.SelectMedia_DragDrop(e);
7689                 }
7690             }
7691             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7692             {
7693                 var (url, title) = GetUrlFromDataObject(e.Data);
7694
7695                 string appendText;
7696                 if (title == null)
7697                     appendText = url;
7698                 else
7699                     appendText = title + " " + url;
7700
7701                 if (this.StatusText.TextLength == 0)
7702                     this.StatusText.Text = appendText;
7703                 else
7704                     this.StatusText.Text += " " + appendText;
7705             }
7706             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7707             {
7708                 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
7709                 if (text != null)
7710                     this.StatusText.Text += text;
7711             }
7712             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7713             {
7714                 var data = (string)e.Data.GetData(DataFormats.StringFormat, true);
7715                 if (data != null) this.StatusText.Text += data;
7716             }
7717         }
7718
7719         /// <summary>
7720         /// IDataObject から URL とタイトルの対を取得します
7721         /// </summary>
7722         /// <remarks>
7723         /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
7724         /// </remarks>
7725         /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
7726         /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
7727         internal static (string Url, string? Title) GetUrlFromDataObject(IDataObject data)
7728         {
7729             if (data.GetDataPresent("text/x-moz-url"))
7730             {
7731                 // Firefox, Google Chrome で利用可能
7732                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
7733
7734                 using var stream = (MemoryStream)data.GetData("text/x-moz-url");
7735                 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
7736                 if (lines.Length < 2)
7737                     throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
7738
7739                 return (lines[0], lines[1]);
7740             }
7741             else if (data.GetDataPresent("IESiteModeToUrl"))
7742             {
7743                 // Internet Exproler 用
7744                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
7745
7746                 using var stream = (MemoryStream)data.GetData("IESiteModeToUrl");
7747                 var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
7748                 if (lines.Length < 2)
7749                     throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
7750
7751                 return (lines[0], lines[1]);
7752             }
7753             else if (data.GetDataPresent("UniformResourceLocatorW"))
7754             {
7755                 // それ以外のブラウザ向け
7756
7757                 using var stream = (MemoryStream)data.GetData("UniformResourceLocatorW");
7758                 var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
7759                 return (url, null);
7760             }
7761
7762             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
7763         }
7764
7765         private void TweenMain_DragEnter(object sender, DragEventArgs e)
7766         {
7767             if (e.Data.GetDataPresent(DataFormats.FileDrop))
7768             {
7769                 if (!e.Data.GetDataPresent(DataFormats.Html, false)) // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
7770                 {
7771                     this.SelectMedia_DragEnter(e);
7772                     return;
7773                 }
7774             }
7775             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
7776             {
7777                 e.Effect = DragDropEffects.Copy;
7778                 return;
7779             }
7780             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
7781             {
7782                 e.Effect = DragDropEffects.Copy;
7783                 return;
7784             }
7785             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
7786             {
7787                 e.Effect = DragDropEffects.Copy;
7788                 return;
7789             }
7790
7791             e.Effect = DragDropEffects.None;
7792         }
7793
7794         private void TweenMain_DragOver(object sender, DragEventArgs e)
7795         {
7796         }
7797
7798         public bool IsNetworkAvailable()
7799         {
7800             var nw = MyCommon.IsNetworkAvailable();
7801             this.myStatusOnline = nw;
7802             return nw;
7803         }
7804
7805         public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
7806         {
7807             var uriStr = uri.AbsoluteUri;
7808
7809             // OpenTween 内部で使用する URL
7810             if (uri.Authority == "opentween")
7811             {
7812                 await this.OpenInternalUriAsync(uri);
7813                 return;
7814             }
7815
7816             // ハッシュタグを含む Twitter 検索
7817             if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
7818             {
7819                 // ハッシュタグの場合は、タブで開く
7820                 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
7821                 var pos = unescapedQuery.IndexOf('#');
7822                 if (pos == -1) return;
7823
7824                 var hash = unescapedQuery.Substring(pos);
7825                 this.HashSupl.AddItem(hash);
7826                 this.HashMgr.AddHashToHistory(hash.Trim(), false);
7827                 this.AddNewTabForSearch(hash);
7828                 return;
7829             }
7830
7831             // ユーザープロフィールURL
7832             // フラグが立っている場合は設定と逆の動作をする
7833             if (this.settings.Common.OpenUserTimeline && !isReverseSettings ||
7834                 !this.settings.Common.OpenUserTimeline && isReverseSettings)
7835             {
7836                 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
7837                 if (userUriMatch.Success)
7838                 {
7839                     var screenName = userUriMatch.Groups["ScreenName"].Value;
7840                     if (this.IsTwitterId(screenName))
7841                     {
7842                         await this.AddNewTabForUserTimeline(screenName);
7843                         return;
7844                     }
7845                 }
7846             }
7847
7848             // どのパターンにも該当しないURL
7849             await MyCommon.OpenInBrowserAsync(this, uriStr);
7850         }
7851
7852         /// <summary>
7853         /// OpenTween 内部の機能を呼び出すための URL を開きます
7854         /// </summary>
7855         private async Task OpenInternalUriAsync(Uri uri)
7856         {
7857             // ツイートを開く (//opentween/status/:status_id)
7858             var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
7859             if (match.Success)
7860             {
7861                 var statusId = new TwitterStatusId(match.Groups[1].Value);
7862                 await this.OpenRelatedTab(statusId);
7863                 return;
7864             }
7865         }
7866
7867         private void ListTabSelect(TabPage tabPage)
7868         {
7869             this.SetListProperty();
7870
7871             var previousTabName = this.CurrentTabName;
7872             if (this.listViewState.TryGetValue(previousTabName, out var previousListViewState))
7873                 previousListViewState.Save(this.ListLockMenuItem.Checked);
7874
7875             this.listCache?.PurgeCache();
7876
7877             this.statuses.SelectTab(tabPage.Text);
7878
7879             this.InitializeTimelineListView();
7880
7881             var tab = this.CurrentTab;
7882             tab.ClearAnchor();
7883
7884             var listView = this.CurrentListView;
7885
7886             var currentListViewState = this.listViewState[tab.TabName];
7887             currentListViewState.Restore(forceScroll: true);
7888
7889             if (this.Use2ColumnsMode)
7890             {
7891                 listView.Columns[1].Text = this.columnText[2];
7892             }
7893             else
7894             {
7895                 for (var i = 0; i < listView.Columns.Count; i++)
7896                 {
7897                     listView.Columns[i].Text = this.columnText[i];
7898                 }
7899             }
7900         }
7901
7902         private void InitializeTimelineListView()
7903         {
7904             var listView = this.CurrentListView;
7905             var tab = this.CurrentTab;
7906
7907             var newCache = new TimelineListViewCache(listView, tab, this.settings.Common);
7908             (this.listCache, var oldCache) = (newCache, this.listCache);
7909             oldCache?.Dispose();
7910
7911             var newDrawer = new TimelineListViewDrawer(listView, tab, this.listCache, this.iconCache, this.themeManager);
7912             (this.listDrawer, var oldDrawer) = (newDrawer, this.listDrawer);
7913             oldDrawer?.Dispose();
7914
7915             newDrawer.IconSize = this.settings.Common.IconSize;
7916             newDrawer.UpdateItemHeight();
7917         }
7918
7919         private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
7920             => this.ListTabSelect(e.TabPage);
7921
7922         private void SelectListItem(DetailsListView lView, int index)
7923         {
7924             // 単一
7925             var bnd = new Rectangle();
7926             var flg = false;
7927             var item = lView.FocusedItem;
7928             if (item != null)
7929             {
7930                 bnd = item.Bounds;
7931                 flg = true;
7932             }
7933
7934             do
7935             {
7936                 lView.SelectedIndices.Clear();
7937             }
7938             while (lView.SelectedIndices.Count > 0);
7939             item = lView.Items[index];
7940             item.Selected = true;
7941             item.Focused = true;
7942
7943             if (flg) lView.Invalidate(bnd);
7944         }
7945
7946         private async void TweenMain_Shown(object sender, EventArgs e)
7947         {
7948             this.NotifyIcon1.Visible = true;
7949             this.StartTimers();
7950
7951             if (this.settings.IsFirstRun)
7952             {
7953                 // 初回起動時だけ右下のメニューを目立たせる
7954                 this.HashStripSplitButton.ShowDropDown();
7955             }
7956
7957             if (this.IsNetworkAvailable())
7958             {
7959                 var loadTasks = new TaskCollection();
7960
7961                 loadTasks.Add(new[]
7962                 {
7963                     this.RefreshMuteUserIdsAsync,
7964                     this.RefreshBlockIdsAsync,
7965                     this.RefreshNoRetweetIdsAsync,
7966                     this.RefreshTwitterConfigurationAsync,
7967                     this.RefreshTabAsync<HomeTabModel>,
7968                     this.RefreshTabAsync<MentionsTabModel>,
7969                     this.RefreshTabAsync<DirectMessagesTabModel>,
7970                     this.RefreshTabAsync<PublicSearchTabModel>,
7971                     this.RefreshTabAsync<UserTimelineTabModel>,
7972                     this.RefreshTabAsync<ListTimelineTabModel>,
7973                 });
7974
7975                 if (this.settings.Common.StartupFollowers)
7976                     loadTasks.Add(this.RefreshFollowerIdsAsync);
7977
7978                 if (this.settings.Common.GetFav)
7979                     loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>);
7980
7981                 var allTasks = loadTasks.RunAll();
7982
7983                 var i = 0;
7984                 while (true)
7985                 {
7986                     var timeout = Task.Delay(5000);
7987                     if (await Task.WhenAny(allTasks, timeout) != timeout)
7988                         break;
7989
7990                     i += 1;
7991                     if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
7992
7993                     if (MyCommon.EndingFlag)
7994                         return;
7995                 }
7996
7997                 if (MyCommon.EndingFlag) return;
7998
7999                 if (ApplicationSettings.VersionInfoUrl != null)
8000                 {
8001                     // バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
8002                     if (this.settings.Common.StartupVersion)
8003                         await this.CheckNewVersion(true);
8004                 }
8005                 else
8006                 {
8007                     // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
8008                     this.VerUpMenuItem.Enabled = false;
8009                     this.VerUpMenuItem.Available = false;
8010                     this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
8011                 }
8012
8013                 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
8014                 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
8015                 {
8016                     MessageBox.Show(Properties.Resources.ReAuthorizeText);
8017                     this.SettingStripMenuItem_Click(this.SettingStripMenuItem, EventArgs.Empty);
8018                 }
8019
8020                 // 取得失敗の場合は再試行する
8021                 var reloadTasks = new TaskCollection();
8022
8023                 if (!this.tw.GetFollowersSuccess && this.settings.Common.StartupFollowers)
8024                     reloadTasks.Add(() => this.RefreshFollowerIdsAsync());
8025
8026                 if (!this.tw.GetNoRetweetSuccess)
8027                     reloadTasks.Add(() => this.RefreshNoRetweetIdsAsync());
8028
8029                 if (this.tw.Configuration.PhotoSizeLimit == 0)
8030                     reloadTasks.Add(() => this.RefreshTwitterConfigurationAsync());
8031
8032                 await reloadTasks.RunAll();
8033             }
8034
8035             this.initial = false;
8036         }
8037
8038         private void StartTimers()
8039         {
8040             if (!this.StopRefreshAllMenuItem.Checked)
8041                 this.timelineScheduler.Enabled = true;
8042
8043             this.selectionDebouncer.Enabled = true;
8044             this.saveConfigDebouncer.Enabled = true;
8045             this.thumbGenerator.ImgAzyobuziNet.AutoUpdate = true;
8046         }
8047
8048         private async Task DoGetFollowersMenu()
8049         {
8050             await this.RefreshFollowerIdsAsync();
8051             this.DispSelectedPost(true);
8052         }
8053
8054         private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
8055             => await this.DoGetFollowersMenu();
8056
8057         private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
8058             => this.DoReTweetUnofficial();
8059
8060         private async Task DoReTweetOfficial(bool isConfirm)
8061         {
8062             // 公式RT
8063             if (this.ExistCurrentPost)
8064             {
8065                 var selectedPosts = this.CurrentTab.SelectedPosts;
8066
8067                 if (selectedPosts.Any(x => !x.CanRetweetBy(this.tw.UserId)))
8068                 {
8069                     if (selectedPosts.Any(x => x.IsProtect))
8070                         MessageBox.Show("Protected.");
8071
8072                     this.doFavRetweetFlags = false;
8073                     return;
8074                 }
8075
8076                 if (selectedPosts.Length > 15)
8077                 {
8078                     MessageBox.Show(Properties.Resources.RetweetLimitText);
8079                     this.doFavRetweetFlags = false;
8080                     return;
8081                 }
8082                 else if (selectedPosts.Length > 1)
8083                 {
8084                     var questionText = Properties.Resources.RetweetQuestion2;
8085                     if (this.doFavRetweetFlags) questionText = Properties.Resources.FavoriteRetweetQuestionText1;
8086                     switch (MessageBox.Show(questionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
8087                     {
8088                         case DialogResult.Cancel:
8089                         case DialogResult.No:
8090                             this.doFavRetweetFlags = false;
8091                             return;
8092                     }
8093                 }
8094                 else
8095                 {
8096                     if (!this.settings.Common.RetweetNoConfirm)
8097                     {
8098                         var questiontext = Properties.Resources.RetweetQuestion1;
8099                         if (this.doFavRetweetFlags) questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
8100                         if (isConfirm && MessageBox.Show(questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8101                         {
8102                             this.doFavRetweetFlags = false;
8103                             return;
8104                         }
8105                     }
8106                 }
8107
8108                 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
8109
8110                 await this.RetweetAsync(statusIds);
8111             }
8112         }
8113
8114         private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
8115             => await this.DoReTweetOfficial(true);
8116
8117         private async Task FavoritesRetweetOfficial()
8118         {
8119             if (!this.ExistCurrentPost) return;
8120             this.doFavRetweetFlags = true;
8121
8122             var tasks = new TaskCollection();
8123             tasks.Add(() => this.DoReTweetOfficial(true));
8124
8125             if (this.doFavRetweetFlags)
8126             {
8127                 this.doFavRetweetFlags = false;
8128                 tasks.Add(() => this.FavoriteChange(true, false));
8129             }
8130
8131             await tasks.RunAll();
8132         }
8133
8134         private async Task FavoritesRetweetUnofficial()
8135         {
8136             var post = this.CurrentPost;
8137             if (this.ExistCurrentPost && post != null && !post.IsDm)
8138             {
8139                 this.doFavRetweetFlags = true;
8140                 var favoriteTask = this.FavoriteChange(true);
8141                 if (!post.IsProtect && this.doFavRetweetFlags)
8142                 {
8143                     this.doFavRetweetFlags = false;
8144                     this.DoReTweetUnofficial();
8145                 }
8146
8147                 await favoriteTask;
8148             }
8149         }
8150
8151         /// <summary>
8152         /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
8153         /// </summary>
8154         /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
8155         /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
8156         /// <returns>復元されたツイート本文</returns>
8157         internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
8158         {
8159             // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
8160
8161             // 通常の URL
8162             statusHtml = Regex.Replace(statusHtml, """<a href="(?<href>.+?)" title="(?<title>.+?)">(?<text>.+?)</a>""", "${title}");
8163             // メンション
8164             statusHtml = Regex.Replace(statusHtml, """<a class="mention" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8165             // ハッシュタグ
8166             statusHtml = Regex.Replace(statusHtml, """<a class="hashtag" href="(?<href>.+?)">(?<text>.+?)</a>""", "${text}");
8167             // 絵文字
8168             statusHtml = Regex.Replace(statusHtml, """<img class="emoji" src=".+?" alt="(?<text>.+?)" />""", "${text}");
8169
8170             // <br> 除去
8171             if (multiline)
8172                 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
8173             else
8174                 statusHtml = statusHtml.Replace("<br>", " ");
8175
8176             // &nbsp; は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
8177             // 現状では半角スペースの代用として &nbsp; を使用しているため U+0020 に置換します
8178             statusHtml = statusHtml.Replace("&nbsp;", " ");
8179
8180             return WebUtility.HtmlDecode(statusHtml);
8181         }
8182
8183         private void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
8184         {
8185             this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
8186
8187             if (this.CurrentPost != null)
8188                 this.DispSelectedPost(true);
8189         }
8190
8191         private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
8192         {
8193             if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
8194                 this.DebugModeToolStripMenuItem.Visible = true;
8195             else
8196                 this.DebugModeToolStripMenuItem.Visible = false;
8197         }
8198
8199         private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
8200             => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
8201
8202         private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
8203             => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
8204
8205         private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
8206             => this.settings.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
8207
8208         private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
8209         {
8210             this.settings.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
8211             this.MarkSettingCommonModified();
8212         }
8213
8214         private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
8215         {
8216             this.settings.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
8217             this.MarkSettingCommonModified();
8218         }
8219
8220         private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
8221         {
8222             this.UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
8223             this.PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
8224             this.UrlAutoShortenMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8225             this.IdeographicSpaceToSpaceMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8226             this.MultiLineMenuItem.Checked = this.settings.Local.StatusMultiline;
8227             this.FocusLockMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8228         }
8229
8230         private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
8231         {
8232             this.UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
8233             this.PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
8234             this.UrlAutoShortenPullDownMenuItem.Checked = this.settings.Common.UrlConvertAuto;
8235             this.IdeographicSpaceToSpacePullDownMenuItem.Checked = this.settings.Common.WideSpaceConvert;
8236             this.MultiLinePullDownMenuItem.Checked = this.settings.Local.StatusMultiline;
8237             this.FocusLockPullDownMenuItem.Checked = this.settings.Common.FocusLockToStatusText;
8238         }
8239
8240         private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
8241         {
8242             if (this.TraceOutToolStripMenuItem.Checked)
8243                 MyCommon.TraceFlag = true;
8244             else
8245                 MyCommon.TraceFlag = false;
8246         }
8247
8248         private void TweenMain_Deactivate(object sender, EventArgs e)
8249             => this.StatusText_Leave(this.StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
8250
8251         private void TabRenameMenuItem_Click(object sender, EventArgs e)
8252         {
8253             if (MyCommon.IsNullOrEmpty(this.rclickTabName)) return;
8254
8255             _ = this.TabRename(this.rclickTabName, out _);
8256         }
8257
8258         private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
8259             => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
8260
8261         private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
8262             => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
8263
8264         private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
8265         {
8266             TwitterApiStatus? apiStatus;
8267
8268             using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
8269             {
8270                 var cancellationToken = dialog.EnableCancellation();
8271
8272                 try
8273                 {
8274                     var task = this.tw.GetInfoApi();
8275                     apiStatus = await dialog.WaitForAsync(this, task);
8276                 }
8277                 catch (WebApiException)
8278                 {
8279                     apiStatus = null;
8280                 }
8281
8282                 if (cancellationToken.IsCancellationRequested)
8283                     return;
8284
8285                 if (apiStatus == null)
8286                 {
8287                     MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
8288                     return;
8289                 }
8290             }
8291
8292             using var apiDlg = new ApiInfoDialog();
8293             apiDlg.ShowDialog(this);
8294         }
8295
8296         private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
8297         {
8298             var id = this.CurrentPost?.ScreenName ?? "";
8299
8300             await this.FollowCommand(id);
8301         }
8302
8303         internal async Task FollowCommand(string id)
8304         {
8305             using (var inputName = new InputTabName())
8306             {
8307                 inputName.FormTitle = "Follow";
8308                 inputName.FormDescription = Properties.Resources.FRMessage1;
8309                 inputName.TabName = id;
8310
8311                 if (inputName.ShowDialog(this) != DialogResult.OK)
8312                     return;
8313                 if (string.IsNullOrWhiteSpace(inputName.TabName))
8314                     return;
8315
8316                 id = inputName.TabName.Trim();
8317             }
8318
8319             using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
8320             {
8321                 try
8322                 {
8323                     var task = this.tw.Api.FriendshipsCreate(id).IgnoreResponse();
8324                     await dialog.WaitForAsync(this, task);
8325                 }
8326                 catch (WebApiException ex)
8327                 {
8328                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8329                     return;
8330                 }
8331             }
8332
8333             MessageBox.Show(Properties.Resources.FRMessage3);
8334         }
8335
8336         private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
8337         {
8338             var id = this.CurrentPost?.ScreenName ?? "";
8339
8340             await this.RemoveCommand(id, false);
8341         }
8342
8343         internal async Task RemoveCommand(string id, bool skipInput)
8344         {
8345             if (!skipInput)
8346             {
8347                 using var inputName = new InputTabName();
8348                 inputName.FormTitle = "Unfollow";
8349                 inputName.FormDescription = Properties.Resources.FRMessage1;
8350                 inputName.TabName = id;
8351
8352                 if (inputName.ShowDialog(this) != DialogResult.OK)
8353                     return;
8354                 if (string.IsNullOrWhiteSpace(inputName.TabName))
8355                     return;
8356
8357                 id = inputName.TabName.Trim();
8358             }
8359
8360             using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
8361             {
8362                 try
8363                 {
8364                     var task = this.tw.Api.FriendshipsDestroy(id).IgnoreResponse();
8365                     await dialog.WaitForAsync(this, task);
8366                 }
8367                 catch (WebApiException ex)
8368                 {
8369                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
8370                     return;
8371                 }
8372             }
8373
8374             MessageBox.Show(Properties.Resources.FRMessage3);
8375         }
8376
8377         private async void FriendshipMenuItem_Click(object sender, EventArgs e)
8378         {
8379             var id = this.CurrentPost?.ScreenName ?? "";
8380
8381             await this.ShowFriendship(id);
8382         }
8383
8384         internal async Task ShowFriendship(string id)
8385         {
8386             using (var inputName = new InputTabName())
8387             {
8388                 inputName.FormTitle = "Show Friendships";
8389                 inputName.FormDescription = Properties.Resources.FRMessage1;
8390                 inputName.TabName = id;
8391
8392                 if (inputName.ShowDialog(this) != DialogResult.OK)
8393                     return;
8394                 if (string.IsNullOrWhiteSpace(inputName.TabName))
8395                     return;
8396
8397                 id = inputName.TabName.Trim();
8398             }
8399
8400             bool isFollowing, isFollowed;
8401
8402             using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8403             {
8404                 var cancellationToken = dialog.EnableCancellation();
8405
8406                 try
8407                 {
8408                     var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8409                     var friendship = await dialog.WaitForAsync(this, task);
8410
8411                     isFollowing = friendship.Relationship.Source.Following;
8412                     isFollowed = friendship.Relationship.Source.FollowedBy;
8413                 }
8414                 catch (WebApiException ex)
8415                 {
8416                     if (!cancellationToken.IsCancellationRequested)
8417                         MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8418                     return;
8419                 }
8420
8421                 if (cancellationToken.IsCancellationRequested)
8422                     return;
8423             }
8424
8425             string result;
8426             if (isFollowing)
8427             {
8428                 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
8429             }
8430             else
8431             {
8432                 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
8433             }
8434             if (isFollowed)
8435             {
8436                 result += Properties.Resources.GetFriendshipInfo3;
8437             }
8438             else
8439             {
8440                 result += Properties.Resources.GetFriendshipInfo4;
8441             }
8442             result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
8443             MessageBox.Show(result);
8444         }
8445
8446         internal async Task ShowFriendship(string[] ids)
8447         {
8448             foreach (var id in ids)
8449             {
8450                 bool isFollowing, isFollowed;
8451
8452                 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
8453                 {
8454                     var cancellationToken = dialog.EnableCancellation();
8455
8456                     try
8457                     {
8458                         var task = this.tw.Api.FriendshipsShow(this.tw.Username, id);
8459                         var friendship = await dialog.WaitForAsync(this, task);
8460
8461                         isFollowing = friendship.Relationship.Source.Following;
8462                         isFollowed = friendship.Relationship.Source.FollowedBy;
8463                     }
8464                     catch (WebApiException ex)
8465                     {
8466                         if (!cancellationToken.IsCancellationRequested)
8467                             MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
8468                         return;
8469                     }
8470
8471                     if (cancellationToken.IsCancellationRequested)
8472                         return;
8473                 }
8474
8475                 var result = "";
8476                 var ff = "";
8477
8478                 ff = "  ";
8479                 if (isFollowing)
8480                 {
8481                     ff += Properties.Resources.GetFriendshipInfo1;
8482                 }
8483                 else
8484                 {
8485                     ff += Properties.Resources.GetFriendshipInfo2;
8486                 }
8487
8488                 ff += System.Environment.NewLine + "  ";
8489                 if (isFollowed)
8490                 {
8491                     ff += Properties.Resources.GetFriendshipInfo3;
8492                 }
8493                 else
8494                 {
8495                     ff += Properties.Resources.GetFriendshipInfo4;
8496                 }
8497                 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
8498                 if (isFollowing)
8499                 {
8500                     if (MessageBox.Show(
8501                         Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result,
8502                         Properties.Resources.GetFriendshipInfo8,
8503                         MessageBoxButtons.YesNo,
8504                         MessageBoxIcon.Question,
8505                         MessageBoxDefaultButton.Button2) == DialogResult.Yes)
8506                     {
8507                         await this.RemoveCommand(id, true);
8508                     }
8509                 }
8510                 else
8511                 {
8512                     MessageBox.Show(result);
8513                 }
8514             }
8515         }
8516
8517         private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
8518             => await this.DoShowUserStatus(this.tw.Username, false);
8519
8520         // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
8521         // URLから切り出した文字列を渡す
8522
8523         public bool IsTwitterId(string name)
8524         {
8525             if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
8526                 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
8527             else
8528                 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
8529         }
8530
8531         private void DoQuoteOfficial()
8532         {
8533             var post = this.CurrentPost;
8534             if (this.ExistCurrentPost && post != null)
8535             {
8536                 if (post.IsDm || !this.StatusText.Enabled)
8537                     return;
8538
8539                 if (post.IsProtect)
8540                 {
8541                     MessageBox.Show("Protected.");
8542                     return;
8543                 }
8544
8545                 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8546
8547                 this.inReplyTo = null;
8548
8549                 this.StatusText.Text += " " + MyCommon.GetStatusUrl(post);
8550
8551                 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8552                 this.StatusText.Focus();
8553             }
8554         }
8555
8556         private void DoReTweetUnofficial()
8557         {
8558             // RT @id:内容
8559             var post = this.CurrentPost;
8560             if (this.ExistCurrentPost && post != null)
8561             {
8562                 if (post.IsDm || !this.StatusText.Enabled)
8563                     return;
8564
8565                 if (post.IsProtect)
8566                 {
8567                     MessageBox.Show("Protected.");
8568                     return;
8569                 }
8570                 var rtdata = post.Text;
8571                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
8572
8573                 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
8574
8575                 // 投稿時に in_reply_to_status_id を付加する
8576                 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
8577                 var inReplyToScreenName = post.ScreenName;
8578                 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
8579
8580                 this.StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
8581
8582                 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
8583                 this.StatusText.Focus();
8584             }
8585         }
8586
8587         private void QuoteStripMenuItem_Click(object sender, EventArgs e)
8588             => this.DoQuoteOfficial();
8589
8590         private async void SearchButton_Click(object sender, EventArgs e)
8591         {
8592             // 公式検索
8593             var pnl = ((Control)sender).Parent;
8594             if (pnl == null) return;
8595             var tbName = pnl.Parent.Text;
8596             var tb = (PublicSearchTabModel)this.statuses.Tabs[tbName];
8597             var cmb = (ComboBox)pnl.Controls["comboSearch"];
8598             var cmbLang = (ComboBox)pnl.Controls["comboLang"];
8599             cmb.Text = cmb.Text.Trim();
8600             // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
8601             var quote = false;
8602             var buf = new StringBuilder();
8603             var c = cmb.Text.ToCharArray();
8604             for (var cnt = 0; cnt < cmb.Text.Length; cnt++)
8605             {
8606                 if (cnt > cmb.Text.Length - 4)
8607                 {
8608                     buf.Append(cmb.Text.Substring(cnt));
8609                     break;
8610                 }
8611                 if (c[cnt] == '"')
8612                 {
8613                     quote = !quote;
8614                 }
8615                 else
8616                 {
8617                     if (!quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
8618                     {
8619                         buf.Append(" OR ");
8620                         cnt += 3;
8621                         continue;
8622                     }
8623                 }
8624                 buf.Append(c[cnt]);
8625             }
8626             cmb.Text = buf.ToString();
8627
8628             var listView = (DetailsListView)pnl.Parent.Tag;
8629
8630             var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
8631
8632             tb.SearchWords = cmb.Text;
8633             tb.SearchLang = cmbLang.Text;
8634             if (MyCommon.IsNullOrEmpty(cmb.Text))
8635             {
8636                 listView.Focus();
8637                 this.SaveConfigsTabs();
8638                 return;
8639             }
8640             if (queryChanged)
8641             {
8642                 var idx = cmb.Items.IndexOf(tb.SearchWords);
8643                 if (idx > -1) cmb.Items.RemoveAt(idx);
8644                 cmb.Items.Insert(0, tb.SearchWords);
8645                 cmb.Text = tb.SearchWords;
8646                 cmb.SelectAll();
8647                 this.statuses.ClearTabIds(tbName);
8648                 this.listCache?.PurgeCache();
8649                 this.listCache?.UpdateListSize();
8650                 this.SaveConfigsTabs();   // 検索条件の保存
8651             }
8652
8653             listView.Focus();
8654             await this.RefreshTabAsync(tb);
8655         }
8656
8657         private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
8658             => await this.DoRefreshMore(); // もっと前を取得
8659
8660         /// <summary>
8661         /// 指定されたタブのListTabにおける位置を返します
8662         /// </summary>
8663         /// <remarks>
8664         /// 非表示のタブについて -1 が返ることを常に考慮して下さい
8665         /// </remarks>
8666         public int GetTabPageIndex(string tabName)
8667             => this.statuses.Tabs.IndexOf(tabName);
8668
8669         private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
8670         {
8671             try
8672             {
8673                 var restoredTab = this.statuses.UndoRemovedTab();
8674                 this.AddNewTab(restoredTab, startup: false);
8675
8676                 var tabIndex = this.statuses.Tabs.Count - 1;
8677                 this.ListTab.SelectedIndex = tabIndex;
8678
8679                 this.SaveConfigsTabs();
8680             }
8681             catch (TabException ex)
8682             {
8683                 MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8684             }
8685         }
8686
8687         private async Task DoMoveToRTHome()
8688         {
8689             var post = this.CurrentPost;
8690             if (post != null && post.RetweetedId != null)
8691                 await MyCommon.OpenInBrowserAsync(this, "https://twitter.com/" + post.RetweetedBy);
8692         }
8693
8694         private async void RetweetedByOpenInBrowserMenuItem_Click(object sender, EventArgs e)
8695             => await this.DoMoveToRTHome();
8696
8697         private void AuthorListManageMenuItem_Click(object sender, EventArgs e)
8698         {
8699             var screenName = this.CurrentPost?.ScreenName;
8700             if (screenName != null)
8701                 this.ListManageUserContext(screenName);
8702         }
8703
8704         private void RetweetedByListManageMenuItem_Click(object sender, EventArgs e)
8705         {
8706             var screenName = this.CurrentPost?.RetweetedBy;
8707             if (screenName != null)
8708                 this.ListManageUserContext(screenName);
8709         }
8710
8711         public void ListManageUserContext(string screenName)
8712         {
8713             using var listSelectForm = new MyLists(screenName, this.tw.Api);
8714             listSelectForm.ShowDialog(this);
8715         }
8716
8717         private void SearchControls_Enter(object sender, EventArgs e)
8718         {
8719             var pnl = (Control)sender;
8720             foreach (Control ctl in pnl.Controls)
8721             {
8722                 ctl.TabStop = true;
8723             }
8724         }
8725
8726         private void SearchControls_Leave(object sender, EventArgs e)
8727         {
8728             var pnl = (Control)sender;
8729             foreach (Control ctl in pnl.Controls)
8730             {
8731                 ctl.TabStop = false;
8732             }
8733         }
8734
8735         private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
8736         {
8737             var tab = this.CurrentTab;
8738             if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
8739             this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
8740         }
8741
8742         private void StatusLabel_DoubleClick(object sender, EventArgs e)
8743             => MessageBox.Show(this.StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
8744
8745         private void HashManageMenuItem_Click(object sender, EventArgs e)
8746         {
8747             DialogResult rslt;
8748             try
8749             {
8750                 rslt = this.HashMgr.ShowDialog();
8751             }
8752             catch (Exception)
8753             {
8754                 return;
8755             }
8756             this.TopMost = this.settings.Common.AlwaysTop;
8757             if (rslt == DialogResult.Cancel) return;
8758             if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8759             {
8760                 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8761                 this.HashTogglePullDownMenuItem.Checked = true;
8762                 this.HashToggleMenuItem.Checked = true;
8763             }
8764             else
8765             {
8766                 this.HashStripSplitButton.Text = "#[-]";
8767                 this.HashTogglePullDownMenuItem.Checked = false;
8768                 this.HashToggleMenuItem.Checked = false;
8769             }
8770
8771             this.MarkSettingCommonModified();
8772             this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8773         }
8774
8775         private void HashToggleMenuItem_Click(object sender, EventArgs e)
8776         {
8777             this.HashMgr.ToggleHash();
8778             if (!MyCommon.IsNullOrEmpty(this.HashMgr.UseHash))
8779             {
8780                 this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8781                 this.HashToggleMenuItem.Checked = true;
8782                 this.HashTogglePullDownMenuItem.Checked = true;
8783             }
8784             else
8785             {
8786                 this.HashStripSplitButton.Text = "#[-]";
8787                 this.HashToggleMenuItem.Checked = false;
8788                 this.HashTogglePullDownMenuItem.Checked = false;
8789             }
8790             this.MarkSettingCommonModified();
8791             this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
8792         }
8793
8794         private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
8795             => this.HashToggleMenuItem_Click(this.HashToggleMenuItem, EventArgs.Empty);
8796
8797         public void SetPermanentHashtag(string hashtag)
8798         {
8799             this.HashMgr.SetPermanentHash("#" + hashtag);
8800             this.HashStripSplitButton.Text = this.HashMgr.UseHash;
8801             this.HashTogglePullDownMenuItem.Checked = true;
8802             this.HashToggleMenuItem.Checked = true;
8803             // 使用ハッシュタグとして設定
8804             this.MarkSettingCommonModified();
8805         }
8806
8807         private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
8808         {
8809             var tab = this.CurrentTab;
8810             var post = this.CurrentPost;
8811             if (!this.ExistCurrentPost)
8812             {
8813                 this.ReplyOpMenuItem.Enabled = false;
8814                 this.ReplyAllOpMenuItem.Enabled = false;
8815                 this.DmOpMenuItem.Enabled = false;
8816                 this.CreateTabRuleOpMenuItem.Enabled = false;
8817                 this.CreateIdRuleOpMenuItem.Enabled = false;
8818                 this.CreateSourceRuleOpMenuItem.Enabled = false;
8819                 this.ReadOpMenuItem.Enabled = false;
8820                 this.UnreadOpMenuItem.Enabled = false;
8821                 this.AuthorMenuItem.Visible = false;
8822                 this.RetweetedByMenuItem.Visible = false;
8823             }
8824             else
8825             {
8826                 this.ReplyOpMenuItem.Enabled = true;
8827                 this.ReplyAllOpMenuItem.Enabled = true;
8828                 this.DmOpMenuItem.Enabled = true;
8829                 this.CreateTabRuleOpMenuItem.Enabled = true;
8830                 this.CreateIdRuleOpMenuItem.Enabled = true;
8831                 this.CreateSourceRuleOpMenuItem.Enabled = true;
8832                 this.ReadOpMenuItem.Enabled = true;
8833                 this.UnreadOpMenuItem.Enabled = true;
8834                 this.AuthorMenuItem.Visible = true;
8835                 this.AuthorMenuItem.Text = $"@{post!.ScreenName}";
8836                 this.RetweetedByMenuItem.Visible = post.RetweetedByUserId != null;
8837                 this.RetweetedByMenuItem.Text = $"@{post.RetweetedBy}";
8838             }
8839
8840             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post == null || post.IsDm)
8841             {
8842                 this.FavOpMenuItem.Enabled = false;
8843                 this.UnFavOpMenuItem.Enabled = false;
8844                 this.OpenStatusOpMenuItem.Enabled = false;
8845                 this.ShowRelatedStatusesMenuItem2.Enabled = false;
8846                 this.RtOpMenuItem.Enabled = false;
8847                 this.RtUnOpMenuItem.Enabled = false;
8848                 this.QtOpMenuItem.Enabled = false;
8849                 this.FavoriteRetweetMenuItem.Enabled = false;
8850                 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8851             }
8852             else
8853             {
8854                 this.FavOpMenuItem.Enabled = true;
8855                 this.UnFavOpMenuItem.Enabled = true;
8856                 this.OpenStatusOpMenuItem.Enabled = true;
8857                 this.ShowRelatedStatusesMenuItem2.Enabled = true;  // PublicSearchの時問題出るかも
8858
8859                 if (!post.CanRetweetBy(this.tw.UserId))
8860                 {
8861                     this.RtOpMenuItem.Enabled = false;
8862                     this.RtUnOpMenuItem.Enabled = false;
8863                     this.QtOpMenuItem.Enabled = false;
8864                     this.FavoriteRetweetMenuItem.Enabled = false;
8865                     this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
8866                 }
8867                 else
8868                 {
8869                     this.RtOpMenuItem.Enabled = true;
8870                     this.RtUnOpMenuItem.Enabled = true;
8871                     this.QtOpMenuItem.Enabled = true;
8872                     this.FavoriteRetweetMenuItem.Enabled = true;
8873                     this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
8874                 }
8875             }
8876
8877             if (tab.TabType != MyCommon.TabUsageType.Favorites)
8878             {
8879                 this.RefreshPrevOpMenuItem.Enabled = true;
8880             }
8881             else
8882             {
8883                 this.RefreshPrevOpMenuItem.Enabled = false;
8884             }
8885             if (!this.ExistCurrentPost || post == null || post.InReplyToStatusId == null)
8886             {
8887                 this.OpenRepSourceOpMenuItem.Enabled = false;
8888             }
8889             else
8890             {
8891                 this.OpenRepSourceOpMenuItem.Enabled = true;
8892             }
8893
8894             if (this.ExistCurrentPost && post != null)
8895             {
8896                 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
8897             }
8898         }
8899
8900         private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
8901             => this.ContextMenuTabProperty_Opening(sender, null!);
8902
8903         public Twitter TwitterInstance
8904             => this.tw;
8905
8906         private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
8907         {
8908             if (this.initialLayout)
8909                 return;
8910
8911             int splitterDistance;
8912             switch (this.WindowState)
8913             {
8914                 case FormWindowState.Normal:
8915                     splitterDistance = this.SplitContainer3.SplitterDistance;
8916                     break;
8917                 case FormWindowState.Maximized:
8918                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8919                     var normalContainerWidth = this.mySize.Width - SystemInformation.Border3DSize.Width * 2;
8920                     splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
8921                     splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
8922                     break;
8923                 default:
8924                     return;
8925             }
8926
8927             this.mySpDis3 = splitterDistance;
8928             this.MarkSettingLocalModified();
8929         }
8930
8931         private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
8932         {
8933             this.UndoRemoveTabMenuItem.Enabled = this.statuses.CanUndoRemovedTab;
8934
8935             if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
8936                 this.PublicSearchQueryMenuItem.Enabled = true;
8937             else
8938                 this.PublicSearchQueryMenuItem.Enabled = false;
8939
8940             var post = this.CurrentPost;
8941             if (!this.ExistCurrentPost || post == null)
8942             {
8943                 this.CopySTOTMenuItem.Enabled = false;
8944                 this.CopyURLMenuItem.Enabled = false;
8945                 this.CopyUserIdStripMenuItem.Enabled = false;
8946             }
8947             else
8948             {
8949                 this.CopySTOTMenuItem.Enabled = true;
8950                 this.CopyURLMenuItem.Enabled = true;
8951                 this.CopyUserIdStripMenuItem.Enabled = true;
8952
8953                 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
8954                 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
8955             }
8956         }
8957
8958         private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
8959             => this.SetNotifyIconText();
8960
8961         private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
8962             => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
8963
8964         private async Task DoShowUserStatus(string id, bool showInputDialog)
8965         {
8966             TwitterUser? user = null;
8967
8968             if (showInputDialog)
8969             {
8970                 using var inputName = new InputTabName();
8971                 inputName.FormTitle = "Show UserStatus";
8972                 inputName.FormDescription = Properties.Resources.FRMessage1;
8973                 inputName.TabName = id;
8974
8975                 if (inputName.ShowDialog(this) != DialogResult.OK)
8976                     return;
8977                 if (string.IsNullOrWhiteSpace(inputName.TabName))
8978                     return;
8979
8980                 id = inputName.TabName.Trim();
8981             }
8982
8983             using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
8984             {
8985                 var cancellationToken = dialog.EnableCancellation();
8986
8987                 try
8988                 {
8989                     var task = this.tw.GetUserInfo(id);
8990                     user = await dialog.WaitForAsync(this, task);
8991                 }
8992                 catch (WebApiException ex)
8993                 {
8994                     if (!cancellationToken.IsCancellationRequested)
8995                         MessageBox.Show($"Err:{ex.Message}(UsersShow)");
8996                     return;
8997                 }
8998
8999                 if (cancellationToken.IsCancellationRequested)
9000                     return;
9001             }
9002
9003             await this.DoShowUserStatus(user);
9004         }
9005
9006         private async Task DoShowUserStatus(TwitterUser user)
9007         {
9008             using var userDialog = new UserInfoDialog(this, this.tw.Api);
9009             var showUserTask = userDialog.ShowUserAsync(user);
9010             userDialog.ShowDialog(this);
9011
9012             this.Activate();
9013             this.BringToFront();
9014
9015             // ユーザー情報の表示が完了するまで userDialog を破棄しない
9016             await showUserTask;
9017         }
9018
9019         internal Task ShowUserStatus(string id, bool showInputDialog)
9020             => this.DoShowUserStatus(id, showInputDialog);
9021
9022         internal Task ShowUserStatus(string id)
9023             => this.DoShowUserStatus(id, true);
9024
9025         private async void AuthorShowProfileMenuItem_Click(object sender, EventArgs e)
9026         {
9027             var post = this.CurrentPost;
9028             if (post != null)
9029             {
9030                 await this.ShowUserStatus(post.ScreenName, false);
9031             }
9032         }
9033
9034         private async void RetweetedByShowProfileMenuItem_Click(object sender, EventArgs e)
9035         {
9036             var retweetedBy = this.CurrentPost?.RetweetedBy;
9037             if (retweetedBy != null)
9038             {
9039                 await this.ShowUserStatus(retweetedBy, false);
9040             }
9041         }
9042
9043         private async void RtCountMenuItem_Click(object sender, EventArgs e)
9044         {
9045             var post = this.CurrentPost;
9046             if (!this.ExistCurrentPost || post == null)
9047                 return;
9048
9049             var statusId = post.RetweetedId ?? post.StatusId;
9050             TwitterStatus status;
9051
9052             using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
9053             {
9054                 var cancellationToken = dialog.EnableCancellation();
9055
9056                 try
9057                 {
9058                     var task = this.tw.Api.StatusesShow(statusId.ToTwitterStatusId());
9059                     status = await dialog.WaitForAsync(this, task);
9060                 }
9061                 catch (WebApiException ex)
9062                 {
9063                     if (!cancellationToken.IsCancellationRequested)
9064                         MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
9065                     return;
9066                 }
9067
9068                 if (cancellationToken.IsCancellationRequested)
9069                     return;
9070             }
9071
9072             MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
9073         }
9074
9075         private void HookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
9076         {
9077             if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
9078             {
9079                 // アイコン化
9080                 this.Visible = false;
9081             }
9082             else if (Form.ActiveForm == null)
9083             {
9084                 this.Visible = true;
9085                 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9086                 this.Activate();
9087                 this.BringToFront();
9088                 this.StatusText.Focus();
9089             }
9090         }
9091
9092         private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
9093             => this.MultiLinePullDownMenuItem.PerformClick();
9094
9095 #region "画像投稿"
9096         private void ImageSelectMenuItem_Click(object sender, EventArgs e)
9097         {
9098             if (this.ImageSelector.Visible)
9099                 this.ImageSelector.EndSelection();
9100             else
9101                 this.ImageSelector.BeginSelection();
9102         }
9103
9104         private void SelectMedia_DragEnter(DragEventArgs e)
9105         {
9106             if (this.ImageSelector.Model.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
9107             {
9108                 e.Effect = DragDropEffects.Copy;
9109                 return;
9110             }
9111             e.Effect = DragDropEffects.None;
9112         }
9113
9114         private void SelectMedia_DragDrop(DragEventArgs e)
9115         {
9116             this.Activate();
9117             this.BringToFront();
9118
9119             var filePathArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
9120             this.ImageSelector.BeginSelection();
9121             this.ImageSelector.Model.AddMediaItemFromFilePath(filePathArray);
9122             this.StatusText.Focus();
9123         }
9124
9125         private void ImageSelector_BeginSelecting(object sender, EventArgs e)
9126         {
9127             this.TimelinePanel.Visible = false;
9128             this.TimelinePanel.Enabled = false;
9129         }
9130
9131         private void ImageSelector_EndSelecting(object sender, EventArgs e)
9132         {
9133             this.TimelinePanel.Visible = true;
9134             this.TimelinePanel.Enabled = true;
9135             this.CurrentListView.Focus();
9136         }
9137
9138         private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
9139             => this.AllowDrop = false;
9140
9141         private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
9142             => this.AllowDrop = true;
9143
9144         private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
9145         {
9146             if (this.ImageSelector.Visible)
9147             {
9148                 this.MarkSettingCommonModified();
9149                 this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9150             }
9151         }
9152
9153         private void ImageSelector_VisibleChanged(object sender, EventArgs e)
9154             => this.StatusText_TextChanged(this.StatusText, EventArgs.Empty);
9155
9156         /// <summary>
9157         /// StatusTextでCtrl+Vが押下された時の処理
9158         /// </summary>
9159         private void ProcClipboardFromStatusTextWhenCtrlPlusV()
9160         {
9161             try
9162             {
9163                 if (Clipboard.ContainsText())
9164                 {
9165                     // clipboardにテキストがある場合は貼り付け処理
9166                     this.StatusText.Paste(Clipboard.GetText());
9167                 }
9168                 else if (Clipboard.ContainsImage())
9169                 {
9170                     // clipboardから画像を取得
9171                     using var image = Clipboard.GetImage();
9172                     this.ImageSelector.BeginSelection();
9173                     this.ImageSelector.Model.AddMediaItemFromImage(image);
9174                 }
9175                 else if (Clipboard.ContainsFileDropList())
9176                 {
9177                     var files = Clipboard.GetFileDropList().Cast<string>().ToArray();
9178                     this.ImageSelector.BeginSelection();
9179                     this.ImageSelector.Model.AddMediaItemFromFilePath(files);
9180                 }
9181             }
9182             catch (ExternalException ex)
9183             {
9184                 MessageBox.Show(ex.Message);
9185             }
9186         }
9187 #endregion
9188
9189         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
9190         {
9191             using var form = new ListManage(this.tw);
9192             form.ShowDialog(this);
9193         }
9194
9195         private bool ModifySettingCommon { get; set; }
9196
9197         private bool ModifySettingLocal { get; set; }
9198
9199         private bool ModifySettingAtId { get; set; }
9200
9201         private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
9202         {
9203             var post = this.CurrentPost;
9204             if (this.ExistCurrentPost && post != null && !post.IsDm)
9205                 this.RtCountMenuItem.Enabled = true;
9206             else
9207                 this.RtCountMenuItem.Enabled = false;
9208         }
9209
9210         private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
9211             => this.CopyUserId();
9212
9213         private void CopyUserId()
9214         {
9215             var post = this.CurrentPost;
9216             if (post == null) return;
9217             var clstr = post.ScreenName;
9218             try
9219             {
9220                 Clipboard.SetDataObject(clstr, false, 5, 100);
9221             }
9222             catch (Exception ex)
9223             {
9224                 MessageBox.Show(ex.Message);
9225             }
9226         }
9227
9228         private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
9229         {
9230             var post = this.CurrentPost;
9231             if (this.ExistCurrentPost && post != null && !post.IsDm)
9232             {
9233                 try
9234                 {
9235                     await this.OpenRelatedTab(post);
9236                 }
9237                 catch (TabException ex)
9238                 {
9239                     MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
9240                 }
9241             }
9242         }
9243
9244         /// <summary>
9245         /// 指定されたツイートに対する関連発言タブを開きます
9246         /// </summary>
9247         /// <param name="statusId">表示するツイートのID</param>
9248         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9249         public async Task OpenRelatedTab(PostId statusId)
9250         {
9251             var post = this.statuses[statusId];
9252             if (post == null)
9253             {
9254                 try
9255                 {
9256                     post = await this.tw.GetStatusApi(false, statusId.ToTwitterStatusId());
9257                 }
9258                 catch (WebApiException ex)
9259                 {
9260                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
9261                     return;
9262                 }
9263             }
9264
9265             await this.OpenRelatedTab(post);
9266         }
9267
9268         /// <summary>
9269         /// 指定されたツイートに対する関連発言タブを開きます
9270         /// </summary>
9271         /// <param name="post">表示する対象となるツイート</param>
9272         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
9273         private async Task OpenRelatedTab(PostClass post)
9274         {
9275             var tabRelated = this.statuses.GetTabByType<RelatedPostsTabModel>();
9276             if (tabRelated != null)
9277             {
9278                 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
9279             }
9280
9281             var tabName = this.statuses.MakeTabName("Related Tweets");
9282
9283             tabRelated = new RelatedPostsTabModel(tabName, post)
9284             {
9285                 UnreadManage = false,
9286                 Notify = false,
9287             };
9288
9289             this.statuses.AddTab(tabRelated);
9290             this.AddNewTab(tabRelated, startup: false);
9291
9292             this.ListTab.SelectedIndex = this.statuses.Tabs.IndexOf(tabName);
9293
9294             await this.RefreshTabAsync(tabRelated);
9295
9296             var tabIndex = this.statuses.Tabs.IndexOf(tabRelated.TabName);
9297
9298             if (tabIndex != -1)
9299             {
9300                 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
9301
9302                 var tabPage = this.ListTab.TabPages[tabIndex];
9303                 var listView = (DetailsListView)tabPage.Tag;
9304                 var targetPost = tabRelated.TargetPost;
9305                 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
9306
9307                 if (index != -1 && index < listView.Items.Count)
9308                 {
9309                     listView.SelectedIndices.Add(index);
9310                     listView.Items[index].Focused = true;
9311                 }
9312             }
9313         }
9314
9315         private void CacheInfoMenuItem_Click(object sender, EventArgs e)
9316         {
9317             var buf = new StringBuilder();
9318             buf.AppendFormat("キャッシュエントリ保持数     : {0}" + Environment.NewLine, this.iconCache.CacheCount);
9319             buf.AppendFormat("キャッシュエントリ破棄数     : {0}" + Environment.NewLine, this.iconCache.CacheRemoveCount);
9320             MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
9321         }
9322
9323         private void TweenRestartMenuItem_Click(object sender, EventArgs e)
9324         {
9325             MyCommon.EndingFlag = true;
9326             try
9327             {
9328                 this.Close();
9329                 Application.Restart();
9330             }
9331             catch (Exception)
9332             {
9333                 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
9334             }
9335         }
9336
9337         private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
9338             => await MyCommon.OpenInBrowserAsync(this, MyCommon.TwitterUrl + this.tw.Username);
9339
9340         private bool ExistCurrentPost
9341         {
9342             get
9343             {
9344                 var post = this.CurrentPost;
9345                 return post != null && !post.IsDeleted;
9346             }
9347         }
9348
9349         private async void AuthorShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9350             => await this.ShowUserTimeline();
9351
9352         private async void RetweetedByShowUserTimelineMenuItem_Click(object sender, EventArgs e)
9353             => await this.ShowRetweeterTimeline();
9354
9355         private string GetUserIdFromCurPostOrInput(string caption)
9356         {
9357             var id = this.CurrentPost?.ScreenName ?? "";
9358
9359             using var inputName = new InputTabName();
9360             inputName.FormTitle = caption;
9361             inputName.FormDescription = Properties.Resources.FRMessage1;
9362             inputName.TabName = id;
9363
9364             if (inputName.ShowDialog() == DialogResult.OK &&
9365                 !MyCommon.IsNullOrEmpty(inputName.TabName.Trim()))
9366             {
9367                 id = inputName.TabName.Trim();
9368             }
9369             else
9370             {
9371                 id = "";
9372             }
9373             return id;
9374         }
9375
9376         private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
9377         {
9378             var id = this.GetUserIdFromCurPostOrInput("Show UserTimeline");
9379             if (!MyCommon.IsNullOrEmpty(id))
9380             {
9381                 await this.AddNewTabForUserTimeline(id);
9382             }
9383         }
9384
9385         private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
9386         {
9387             if (e.Mode == Microsoft.Win32.PowerModes.Resume)
9388                 this.timelineScheduler.SystemResumed();
9389         }
9390
9391         private void SystemEvents_TimeChanged(object sender, EventArgs e)
9392         {
9393             var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9394
9395             TimeZoneInfo.ClearCachedData();
9396
9397             var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
9398
9399             if (curTimeOffset != prevTimeOffset)
9400             {
9401                 // タイムゾーンの変更を反映
9402                 this.listCache?.PurgeCache();
9403                 this.CurrentListView.Refresh();
9404
9405                 this.DispSelectedPost(forceupdate: true);
9406             }
9407
9408             this.timelineScheduler.Reset();
9409         }
9410
9411         private void TimelineRefreshEnableChange(bool isEnable)
9412         {
9413             this.timelineScheduler.Enabled = isEnable;
9414         }
9415
9416         private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
9417             => this.TimelineRefreshEnableChange(!this.StopRefreshAllMenuItem.Checked);
9418
9419         private async Task OpenUserAppointUrl()
9420         {
9421             if (!MyCommon.IsNullOrEmpty(this.settings.Common.UserAppointUrl))
9422             {
9423                 if (this.settings.Common.UserAppointUrl.Contains("{ID}") || this.settings.Common.UserAppointUrl.Contains("{STATUS}"))
9424                 {
9425                     var post = this.CurrentPost;
9426                     if (post != null)
9427                     {
9428                         var xUrl = this.settings.Common.UserAppointUrl;
9429                         xUrl = xUrl.Replace("{ID}", post.ScreenName);
9430
9431                         var statusId = post.RetweetedId ?? post.StatusId;
9432                         xUrl = xUrl.Replace("{STATUS}", statusId.Id);
9433
9434                         await MyCommon.OpenInBrowserAsync(this, xUrl);
9435                     }
9436                 }
9437                 else
9438                 {
9439                     await MyCommon.OpenInBrowserAsync(this, this.settings.Common.UserAppointUrl);
9440                 }
9441             }
9442         }
9443
9444         private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
9445             => await this.OpenUserAppointUrl();
9446
9447         private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
9448         {
9449             if (Form.ActiveForm == null)
9450             {
9451                 await this.InvokeAsync(() =>
9452                 {
9453                     this.Visible = true;
9454                     if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
9455                     this.Activate();
9456                     this.BringToFront();
9457                     if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
9458                     {
9459                         if (!this.GoDirectMessage(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9460                     }
9461                     else
9462                     {
9463                         if (!this.GoStatus(new TwitterStatusId(e.StatusId))) this.StatusText.Focus();
9464                     }
9465                 });
9466             }
9467         }
9468
9469         private void ReplaceAppName()
9470         {
9471             this.MatomeMenuItem.Text = MyCommon.ReplaceAppName(this.MatomeMenuItem.Text);
9472             this.AboutMenuItem.Text = MyCommon.ReplaceAppName(this.AboutMenuItem.Text);
9473         }
9474
9475         private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
9476             => await MyCommon.OpenInBrowserAsync(this, Twitter.ServiceAvailabilityStatusUrl);
9477
9478         private void PostButton_KeyDown(object sender, KeyEventArgs e)
9479         {
9480             if (e.KeyCode == Keys.Space)
9481             {
9482                 this.JumpUnreadMenuItem_Click(this.JumpUnreadMenuItem, EventArgs.Empty);
9483
9484                 e.SuppressKeyPress = true;
9485             }
9486         }
9487
9488         private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
9489         {
9490             this.IconSizeNoneToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.IconNone;
9491             this.IconSize16ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon16;
9492             this.IconSize24ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon24;
9493             this.IconSize48ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48;
9494             this.IconSize48_2ToolStripMenuItem.Checked = this.settings.Common.IconSize == MyCommon.IconSizes.Icon48_2;
9495
9496             this.LockListSortOrderToolStripMenuItem.Checked = this.settings.Common.SortOrderLock;
9497         }
9498
9499         private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
9500             => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
9501
9502         private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
9503             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
9504
9505         private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
9506             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
9507
9508         private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
9509             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
9510
9511         private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
9512             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
9513
9514         private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
9515         {
9516             if (this.settings.Common.IconSize == iconSize) return;
9517
9518             var oldIconCol = this.Use2ColumnsMode;
9519
9520             this.settings.Common.IconSize = iconSize;
9521             this.ApplyListViewIconSize(iconSize);
9522
9523             if (this.Use2ColumnsMode != oldIconCol)
9524             {
9525                 foreach (TabPage tp in this.ListTab.TabPages)
9526                 {
9527                     this.ResetColumns((DetailsListView)tp.Tag);
9528                 }
9529             }
9530
9531             this.CurrentListView.Refresh();
9532             this.MarkSettingCommonModified();
9533         }
9534
9535         private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
9536         {
9537             var state = this.LockListSortOrderToolStripMenuItem.Checked;
9538             if (this.settings.Common.SortOrderLock == state) return;
9539
9540             this.settings.Common.SortOrderLock = state;
9541             this.MarkSettingCommonModified();
9542         }
9543
9544         private void TweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
9545         {
9546             if (!MyCommon.IsNullOrEmpty(e.StatusText))
9547             {
9548                 this.StatusLabelUrl.Text = e.StatusText;
9549             }
9550             else
9551             {
9552                 this.SetStatusLabelUrl();
9553             }
9554         }
9555     }
9556 }