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