OSDN Git Service

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