OSDN Git Service

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