OSDN Git Service

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