OSDN Git Service

2d232d644bddfd1cf0a85d720bb00871b3f7c7ba
[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 struct ReplyChain
289         {
290             public long OriginalId;
291             public long InReplyToId;
292             public 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             {
8461                 UrlDialog.ClearUrl();
8462
8463                 string openUrlStr = "";
8464
8465                 if (linkElements.Length == 1)
8466                 {
8467                     // ツイートに含まれる URL が 1 つのみの場合
8468                     //   => OpenURL ダイアログを表示せずにリンクを開く
8469
8470                     string urlStr = "";
8471                     try
8472                     {
8473                         urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8474                     }
8475                     catch (ArgumentException)
8476                     {
8477                         //変なHTML?
8478                         return;
8479                     }
8480                     catch (Exception)
8481                     {
8482                         return;
8483                     }
8484                     if (string.IsNullOrEmpty(urlStr)) return;
8485                     openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8486
8487                     // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8488                     await this.OpenUriAsync(new Uri(openUrlStr));
8489                 }
8490                 else
8491                 {
8492                     // ツイートに含まれる URL が複数ある場合
8493                     //   => OpenURL を表示しユーザーが選択したリンクを開く
8494
8495                     foreach (var linkElm in linkElements)
8496                     {
8497                         string urlStr = "";
8498                         string linkText = "";
8499                         string href = "";
8500                         try
8501                         {
8502                             urlStr = linkElm.GetAttribute("title");
8503                             href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8504                             if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8505                             linkText = linkElm.InnerText;
8506                         }
8507                         catch (ArgumentException)
8508                         {
8509                             //変なHTML?
8510                             return;
8511                         }
8512                         catch (Exception)
8513                         {
8514                             return;
8515                         }
8516                         if (string.IsNullOrEmpty(urlStr)) continue;
8517                         UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8518                     }
8519                     try
8520                     {
8521                         if (UrlDialog.ShowDialog() == DialogResult.OK)
8522                         {
8523                             openUrlStr = UrlDialog.SelectedUrl;
8524
8525                             // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8526                             await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8527                         }
8528                     }
8529                     catch (Exception)
8530                     {
8531                         return;
8532                     }
8533                     this.TopMost = SettingManager.Common.AlwaysTop;
8534                 }
8535             }
8536         }
8537
8538         private void ClearTabMenuItem_Click(object sender, EventArgs e)
8539         {
8540             if (string.IsNullOrEmpty(_rclickTabName)) return;
8541             ClearTab(_rclickTabName, true);
8542         }
8543
8544         private void ClearTab(string tabName, bool showWarning)
8545         {
8546             if (showWarning)
8547             {
8548                 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8549                 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8550                 {
8551                     return;
8552                 }
8553             }
8554
8555             _statuses.ClearTabIds(tabName);
8556             if (this.CurrentTabName == tabName)
8557             {
8558                 _anchorPost = null;
8559                 _anchorFlag = false;
8560                 this.PurgeListViewItemCache();
8561             }
8562
8563             var tabIndex = this._statuses.Tabs.IndexOf(tabName);
8564             var tabPage = this.ListTab.TabPages[tabIndex];
8565             tabPage.ImageIndex = -1;
8566
8567             var listView = (DetailsListView)tabPage.Tag;
8568             listView.VirtualListSize = 0;
8569
8570             if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8571
8572             SetMainWindowTitle();
8573             SetStatusLabelUrl();
8574         }
8575
8576         private static long followers = 0;
8577
8578         private void SetMainWindowTitle()
8579         {
8580             //メインウインドウタイトルの書き換え
8581             StringBuilder ttl = new StringBuilder(256);
8582             int ur = 0;
8583             int al = 0;
8584             if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8585                 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8586                 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8587                 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8588             {
8589                 foreach (var tab in _statuses.Tabs)
8590                 {
8591                     ur += tab.UnreadCount;
8592                     al += tab.AllCount;
8593                 }
8594             }
8595
8596             if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8597             ttl.Append(ApplicationSettings.ApplicationName);
8598             ttl.Append("  ");
8599             switch (SettingManager.Common.DispLatestPost)
8600             {
8601                 case MyCommon.DispTitleEnum.Ver:
8602                     ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8603                     break;
8604                 case MyCommon.DispTitleEnum.Post:
8605                     if (_history != null && _history.Count > 1)
8606                         ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8607                     break;
8608                 case MyCommon.DispTitleEnum.UnreadRepCount:
8609                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8610                     break;
8611                 case MyCommon.DispTitleEnum.UnreadAllCount:
8612                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8613                     break;
8614                 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8615                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8616                     break;
8617                 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8618                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8619                     break;
8620                 case MyCommon.DispTitleEnum.OwnStatus:
8621                     if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8622                     ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8623                     break;
8624             }
8625
8626             try
8627             {
8628                 this.Text = ttl.ToString();
8629             }
8630             catch (AccessViolationException)
8631             {
8632                 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8633             }
8634         }
8635
8636         private string GetStatusLabelText()
8637         {
8638             //ステータス欄にカウント表示
8639             //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8640             if (_statuses == null) return "";
8641             TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8642             TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8643             if (tbRep == null || tbDm == null) return "";
8644             int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8645             int ur = 0;
8646             int al = 0;
8647             int tur = 0;
8648             int tal = 0;
8649             StringBuilder slbl = new StringBuilder(256);
8650             try
8651             {
8652                 foreach (var tab in _statuses.Tabs)
8653                 {
8654                     ur += tab.UnreadCount;
8655                     al += tab.AllCount;
8656                     if (tab.TabName == this.CurrentTabName)
8657                     {
8658                         tur = tab.UnreadCount;
8659                         tal = tab.AllCount;
8660                     }
8661                 }
8662             }
8663             catch (Exception)
8664             {
8665                 return "";
8666             }
8667
8668             UnreadCounter = ur;
8669             UnreadAtCounter = urat;
8670
8671             var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8672
8673             slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8674             if (SettingManager.Common.TimelinePeriod == 0)
8675             {
8676                 slbl.Append(Properties.Resources.SetStatusLabelText2);
8677             }
8678             else
8679             {
8680                 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8681             }
8682             return slbl.ToString();
8683         }
8684
8685         private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8686         {
8687             try
8688             {
8689                 if (this.InvokeRequired && !this.IsDisposed)
8690                 {
8691                     await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8692                 }
8693                 else
8694                 {
8695                     var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8696                     SetApiStatusLabel(endpointName);
8697                 }
8698             }
8699             catch (ObjectDisposedException)
8700             {
8701                 return;
8702             }
8703             catch (InvalidOperationException)
8704             {
8705                 return;
8706             }
8707         }
8708
8709         private void SetApiStatusLabel(string endpointName = null)
8710         {
8711             var tabType = this.CurrentTab.TabType;
8712
8713             if (endpointName == null)
8714             {
8715                 // 表示中のタブに応じて更新
8716                 switch (tabType)
8717                 {
8718                     case MyCommon.TabUsageType.Home:
8719                     case MyCommon.TabUsageType.UserDefined:
8720                         endpointName = "/statuses/home_timeline";
8721                         break;
8722
8723                     case MyCommon.TabUsageType.Mentions:
8724                         endpointName = "/statuses/mentions_timeline";
8725                         break;
8726
8727                     case MyCommon.TabUsageType.Favorites:
8728                         endpointName = "/favorites/list";
8729                         break;
8730
8731                     case MyCommon.TabUsageType.DirectMessage:
8732                         endpointName = "/direct_messages/events/list";
8733                         break;
8734
8735                     case MyCommon.TabUsageType.UserTimeline:
8736                         endpointName = "/statuses/user_timeline";
8737                         break;
8738
8739                     case MyCommon.TabUsageType.Lists:
8740                         endpointName = "/lists/statuses";
8741                         break;
8742
8743                     case MyCommon.TabUsageType.PublicSearch:
8744                         endpointName = "/search/tweets";
8745                         break;
8746
8747                     case MyCommon.TabUsageType.Related:
8748                         endpointName = "/statuses/show/:id";
8749                         break;
8750
8751                     default:
8752                         break;
8753                 }
8754
8755                 this.toolStripApiGauge.ApiEndpoint = endpointName;
8756             }
8757             else
8758             {
8759                 // 表示中のタブに関連する endpoint であれば更新
8760                 var update = false;
8761
8762                 switch (endpointName)
8763                 {
8764                     case "/statuses/home_timeline":
8765                         update = tabType == MyCommon.TabUsageType.Home ||
8766                                  tabType == MyCommon.TabUsageType.UserDefined;
8767                         break;
8768
8769                     case "/statuses/mentions_timeline":
8770                         update = tabType == MyCommon.TabUsageType.Mentions;
8771                         break;
8772
8773                     case "/favorites/list":
8774                         update = tabType == MyCommon.TabUsageType.Favorites;
8775                         break;
8776
8777                     case "/direct_messages/events/list":
8778                         update = tabType == MyCommon.TabUsageType.DirectMessage;
8779                         break;
8780
8781                     case "/statuses/user_timeline":
8782                         update = tabType == MyCommon.TabUsageType.UserTimeline;
8783                         break;
8784
8785                     case "/lists/statuses":
8786                         update = tabType == MyCommon.TabUsageType.Lists;
8787                         break;
8788
8789                     case "/search/tweets":
8790                         update = tabType == MyCommon.TabUsageType.PublicSearch;
8791                         break;
8792
8793                     case "/statuses/show/:id":
8794                         update = tabType == MyCommon.TabUsageType.Related;
8795                         break;
8796
8797                     default:
8798                         break;
8799                 }
8800
8801                 if (update)
8802                 {
8803                     this.toolStripApiGauge.ApiEndpoint = endpointName;
8804                 }
8805             }
8806         }
8807
8808         private void SetStatusLabelUrl()
8809             => this.StatusLabelUrl.Text = this.GetStatusLabelText();
8810
8811         public void SetStatusLabel(string text)
8812             => this.StatusLabel.Text = text;
8813
8814         private void SetNotifyIconText()
8815         {
8816             var ur = new StringBuilder(64);
8817
8818             // タスクトレイアイコンのツールチップテキスト書き換え
8819             // Tween [未読/@]
8820             ur.Remove(0, ur.Length);
8821             if (SettingManager.Common.DispUsername)
8822             {
8823                 ur.Append(tw.Username);
8824                 ur.Append(" - ");
8825             }
8826             ur.Append(ApplicationSettings.ApplicationName);
8827 #if DEBUG
8828             ur.Append("(Debug Build)");
8829 #endif
8830             if (UnreadCounter != -1 && UnreadAtCounter != -1)
8831             {
8832                 ur.Append(" [");
8833                 ur.Append(UnreadCounter);
8834                 ur.Append("/@");
8835                 ur.Append(UnreadAtCounter);
8836                 ur.Append("]");
8837             }
8838             NotifyIcon1.Text = ur.ToString();
8839         }
8840
8841         internal void CheckReplyTo(string StatusText)
8842         {
8843             MatchCollection m;
8844             //ハッシュタグの保存
8845             m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8846             string hstr = "";
8847             foreach (Match hm in m)
8848             {
8849                 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8850                 {
8851                     hstr += "#" + hm.Result("$3") + " ";
8852                     HashSupl.AddItem("#" + hm.Result("$3"));
8853                 }
8854             }
8855             if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
8856             {
8857                 hstr += HashMgr.UseHash;
8858             }
8859             if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
8860
8861             // 本当にリプライ先指定すべきかどうかの判定
8862             m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
8863
8864             if (SettingManager.Common.UseAtIdSupplement)
8865             {
8866                 int bCnt = AtIdSupl.ItemCount;
8867                 foreach (Match mid in m)
8868                 {
8869                     AtIdSupl.AddItem(mid.Result("${id}"));
8870                 }
8871                 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
8872             }
8873
8874             // リプライ先ステータスIDの指定がない場合は指定しない
8875             if (this.inReplyTo == null)
8876                 return;
8877
8878             // 通常Reply
8879             // 次の条件を満たす場合に in_reply_to_status_id 指定
8880             // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
8881             // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
8882             // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
8883
8884             if (m != null)
8885             {
8886                 var inReplyToScreenName = this.inReplyTo.Value.ScreenName;
8887                 if (StatusText.StartsWith("@", StringComparison.Ordinal))
8888                 {
8889                     if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
8890                 }
8891                 else
8892                 {
8893                     foreach (Match mid in m)
8894                     {
8895                         if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
8896                     }
8897                 }
8898             }
8899
8900             this.inReplyTo = null;
8901         }
8902
8903         private void TweenMain_Resize(object sender, EventArgs e)
8904         {
8905             if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
8906             {
8907                 this.Visible = false;
8908             }
8909             if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
8910             {
8911                 // 現在の DPI と設定保存時の DPI との比を取得する
8912                 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
8913
8914                 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
8915
8916                 // Splitterの位置設定
8917                 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
8918                 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
8919                     splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
8920                 {
8921                     this.SplitContainer1.SplitterDistance = splitterDistance;
8922                 }
8923
8924                 //発言欄複数行
8925                 StatusText.Multiline = SettingManager.Local.StatusMultiline;
8926                 if (StatusText.Multiline)
8927                 {
8928                     var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
8929                     int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8930                     if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
8931                     {
8932                         SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
8933                     }
8934                     StatusText.Height = statusTextHeight;
8935                 }
8936                 else
8937                 {
8938                     if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
8939                     {
8940                         SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
8941                     }
8942                 }
8943
8944                 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
8945                 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
8946                 {
8947                     this.SplitContainer3.SplitterDistance = previewDistance;
8948                 }
8949
8950                 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
8951                 this.SplitContainer3.Panel2Collapsed = true;
8952
8953                 _initialLayout = false;
8954             }
8955             if (this.WindowState != FormWindowState.Minimized)
8956             {
8957                 _formWindowState = this.WindowState;
8958             }
8959         }
8960
8961         private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
8962         {
8963             PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8964             this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
8965             if (PlaySoundMenuItem.Checked)
8966             {
8967                 SettingManager.Common.PlaySound = true;
8968             }
8969             else
8970             {
8971                 SettingManager.Common.PlaySound = false;
8972             }
8973             ModifySettingCommon = true;
8974         }
8975
8976         private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
8977         {
8978             if (this._initialLayout)
8979                 return;
8980
8981             int splitterDistance;
8982             switch (this.WindowState)
8983             {
8984                 case FormWindowState.Normal:
8985                     splitterDistance = this.SplitContainer1.SplitterDistance;
8986                     break;
8987                 case FormWindowState.Maximized:
8988                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
8989                     var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
8990                     splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
8991                     splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
8992                     break;
8993                 default:
8994                     return;
8995             }
8996
8997             this._mySpDis = splitterDistance;
8998             this.ModifySettingLocal = true;
8999         }
9000
9001         private async Task doRepliedStatusOpen()
9002         {
9003             var currentPost = this.CurrentPost;
9004             if (this.ExistCurrentPost && currentPost.InReplyToUser != null && currentPost.InReplyToStatusId != null)
9005             {
9006                 if (MyCommon.IsKeyDown(Keys.Shift))
9007                 {
9008                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
9009                     return;
9010                 }
9011                 if (_statuses.ContainsKey(currentPost.InReplyToStatusId.Value))
9012                 {
9013                     PostClass repPost = _statuses[currentPost.InReplyToStatusId.Value];
9014                     MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname}   ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
9015                 }
9016                 else
9017                 {
9018                     foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9019                     {
9020                         if (tb == null || !tb.Contains(currentPost.InReplyToStatusId.Value)) break;
9021                         PostClass repPost = _statuses[currentPost.InReplyToStatusId.Value];
9022                         MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname}   ({repPost.CreatedAt.ToLocalTimeString()})" + Environment.NewLine + repPost.TextFromApi);
9023                         return;
9024                     }
9025                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(currentPost.InReplyToUser, currentPost.InReplyToStatusId.Value));
9026                 }
9027             }
9028         }
9029
9030         private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9031             => await this.doRepliedStatusOpen();
9032
9033         private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9034         {
9035             if (this._initialLayout)
9036                 return; // SettingLocal の反映が完了するまで multiline の判定を行わない
9037
9038             var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9039             if (multiline != this.StatusText.Multiline)
9040             {
9041                 this.StatusText.Multiline = multiline;
9042                 SettingManager.Local.StatusMultiline = multiline;
9043                 ModifySettingLocal = true;
9044             }
9045         }
9046
9047         private void StatusText_MultilineChanged(object sender, EventArgs e)
9048         {
9049             if (this.StatusText.Multiline)
9050                 this.StatusText.ScrollBars = ScrollBars.Vertical;
9051             else
9052                 this.StatusText.ScrollBars = ScrollBars.None;
9053
9054             ModifySettingLocal = true;
9055         }
9056
9057         private void MultiLineMenuItem_Click(object sender, EventArgs e)
9058         {
9059             //発言欄複数行
9060             var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
9061             StatusText.Multiline = menuItemChecked;
9062             SettingManager.Local.StatusMultiline = menuItemChecked;
9063             if (menuItemChecked)
9064             {
9065                 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9066                     SplitContainer2.SplitterDistance = 0;
9067                 else
9068                     SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9069             }
9070             else
9071             {
9072                 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9073             }
9074             ModifySettingLocal = true;
9075         }
9076
9077         private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9078         {
9079             if (Converter_Type == MyCommon.UrlConverter.Bitly || Converter_Type == MyCommon.UrlConverter.Jmp)
9080             {
9081                 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
9082                 if (string.IsNullOrEmpty(SettingManager.Common.BitlyAccessToken) &&
9083                     (string.IsNullOrEmpty(SettingManager.Common.BilyUser) || string.IsNullOrEmpty(SettingManager.Common.BitlyPwd)))
9084                 {
9085                     MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
9086                     return false;
9087                 }
9088             }
9089
9090             //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9091             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9092
9093             //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9094             //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9095             //Appendix A.  Collected ABNF for URI
9096             //http://www.ietf.org/rfc/rfc3986.txt
9097
9098             string result = "";
9099
9100             const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9101
9102             if (StatusText.SelectionLength > 0)
9103             {
9104                 string tmp = StatusText.SelectedText;
9105                 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9106                 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9107                 {
9108                     // 文字列が選択されている場合はその文字列について処理
9109
9110                     //nico.ms使用、nicovideoにマッチしたら変換
9111                     if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9112                     {
9113                         result = nicoms.Shorten(tmp);
9114                     }
9115                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9116                     {
9117                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9118                         try
9119                         {
9120                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9121                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9122                             result = resultUri.AbsoluteUri;
9123                         }
9124                         catch (WebApiException e)
9125                         {
9126                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9127                             return false;
9128                         }
9129                         catch (UriFormatException e)
9130                         {
9131                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9132                             return false;
9133                         }
9134                     }
9135                     else
9136                     {
9137                         return true;
9138                     }
9139
9140                     if (!string.IsNullOrEmpty(result))
9141                     {
9142                         urlUndo undotmp = new urlUndo();
9143
9144                         // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9145                         var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9146                         if (origUrlIndex == -1)
9147                             return false;
9148
9149                         StatusText.Select(origUrlIndex, tmp.Length);
9150                         StatusText.SelectedText = result;
9151
9152                         //undoバッファにセット
9153                         undotmp.Before = tmp;
9154                         undotmp.After = result;
9155
9156                         if (urlUndoBuffer == null)
9157                         {
9158                             urlUndoBuffer = new List<urlUndo>();
9159                             UrlUndoToolStripMenuItem.Enabled = true;
9160                         }
9161
9162                         urlUndoBuffer.Add(undotmp);
9163                     }
9164                 }
9165             }
9166             else
9167             {
9168                 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9169                                    @"(?<url>(?<protocol>https?://)" +
9170                                    @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9171                                    @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9172                                    @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9173                 // 正規表現にマッチしたURL文字列をtinyurl化
9174                 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9175                 {
9176                     if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9177                     string tmp = mt.Result("${url}");
9178                     if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9179                     urlUndo undotmp = new urlUndo();
9180
9181                     //選んだURLを選択(?)
9182                     StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9183
9184                     //nico.ms使用、nicovideoにマッチしたら変換
9185                     if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9186                     {
9187                         result = nicoms.Shorten(tmp);
9188                     }
9189                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9190                     {
9191                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9192                         try
9193                         {
9194                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9195                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9196                             result = resultUri.AbsoluteUri;
9197                         }
9198                         catch (HttpRequestException e)
9199                         {
9200                             // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9201                             // のように長いので「:」が含まれていればそれ以降のみを抽出する
9202                             var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9203
9204                             this.StatusLabel.Text = Converter_Type + ":" + message;
9205                             continue;
9206                         }
9207                         catch (WebApiException e)
9208                         {
9209                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9210                             continue;
9211                         }
9212                         catch (UriFormatException e)
9213                         {
9214                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9215                             continue;
9216                         }
9217                     }
9218                     else
9219                     {
9220                         continue;
9221                     }
9222
9223                     if (!string.IsNullOrEmpty(result))
9224                     {
9225                         // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9226                         var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9227                         if (origUrlIndex == -1)
9228                             return false;
9229
9230                         StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9231                         StatusText.SelectedText = result;
9232                         //undoバッファにセット
9233                         undotmp.Before = mt.Result("${url}");
9234                         undotmp.After = result;
9235
9236                         if (urlUndoBuffer == null)
9237                         {
9238                             urlUndoBuffer = new List<urlUndo>();
9239                             UrlUndoToolStripMenuItem.Enabled = true;
9240                         }
9241
9242                         urlUndoBuffer.Add(undotmp);
9243                     }
9244                 }
9245             }
9246
9247             return true;
9248         }
9249
9250         private void doUrlUndo()
9251         {
9252             if (urlUndoBuffer != null)
9253             {
9254                 string tmp = StatusText.Text;
9255                 foreach (urlUndo data in urlUndoBuffer)
9256                 {
9257                     tmp = tmp.Replace(data.After, data.Before);
9258                 }
9259                 StatusText.Text = tmp;
9260                 urlUndoBuffer = null;
9261                 UrlUndoToolStripMenuItem.Enabled = false;
9262                 StatusText.SelectionStart = 0;
9263                 StatusText.SelectionLength = 0;
9264             }
9265         }
9266
9267         private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9268             => await this.UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9269
9270         private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9271             => await this.UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9272
9273         private async void UxnuMenuItem_Click(object sender, EventArgs e)
9274             => await this.UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9275
9276         private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9277         {
9278             if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9279             {
9280                 MyCommon.UrlConverter svc = SettingManager.Common.AutoShortUrlFirst;
9281                 Random rnd = new Random();
9282                 // 前回使用した短縮URLサービス以外を選択する
9283                 do
9284                 {
9285                     svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9286                 }
9287                 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9288                 await UrlConvertAsync(svc);
9289             }
9290         }
9291
9292         private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9293             => this.doUrlUndo();
9294
9295         private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9296         {
9297             this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9298             this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9299             SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9300             ModifySettingCommon = true;
9301         }
9302
9303         private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9304         {
9305             ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9306             this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9307             SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9308             ModifySettingCommon = true;
9309         }
9310
9311         private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9312         {
9313             // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9314             MenuStrip1.Tag = new Object();
9315             MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9316         }
9317
9318         private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9319         {
9320             var currentTabPage = this.CurrentTabPage;
9321             if (this.Tag != null) // 設定された戻り先へ遷移
9322             {
9323                 if (this.Tag == currentTabPage)
9324                     ((Control)currentTabPage.Tag).Select();
9325                 else
9326                     ((Control)this.Tag).Select();
9327             }
9328             else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9329             {
9330                 this.Tag = currentTabPage.Tag;
9331                 ((Control)this.Tag).Select();
9332             }
9333             // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9334             MenuStrip1.Tag = null;
9335         }
9336
9337         private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9338         {
9339             DetailsListView lst = (DetailsListView)sender;
9340             if (SettingManager.Local == null) return;
9341
9342             if (_iconCol)
9343             {
9344                 SettingManager.Local.Width1 = lst.Columns[0].Width;
9345                 SettingManager.Local.Width3 = lst.Columns[1].Width;
9346             }
9347             else
9348             {
9349                 int[] darr = new int[lst.Columns.Count];
9350                 for (int i = 0; i < lst.Columns.Count; i++)
9351                 {
9352                     darr[lst.Columns[i].DisplayIndex] = i;
9353                 }
9354                 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9355
9356                 for (int i = 0; i < lst.Columns.Count; i++)
9357                 {
9358                     switch (darr[i])
9359                     {
9360                         case 0:
9361                             SettingManager.Local.DisplayIndex1 = i;
9362                             break;
9363                         case 1:
9364                             SettingManager.Local.DisplayIndex2 = i;
9365                             break;
9366                         case 2:
9367                             SettingManager.Local.DisplayIndex3 = i;
9368                             break;
9369                         case 3:
9370                             SettingManager.Local.DisplayIndex4 = i;
9371                             break;
9372                         case 4:
9373                             SettingManager.Local.DisplayIndex5 = i;
9374                             break;
9375                         case 5:
9376                             SettingManager.Local.DisplayIndex6 = i;
9377                             break;
9378                         case 6:
9379                             SettingManager.Local.DisplayIndex7 = i;
9380                             break;
9381                         case 7:
9382                             SettingManager.Local.DisplayIndex8 = i;
9383                             break;
9384                     }
9385                 }
9386                 SettingManager.Local.Width1 = lst.Columns[0].Width;
9387                 SettingManager.Local.Width2 = lst.Columns[1].Width;
9388                 SettingManager.Local.Width3 = lst.Columns[2].Width;
9389                 SettingManager.Local.Width4 = lst.Columns[3].Width;
9390                 SettingManager.Local.Width5 = lst.Columns[4].Width;
9391                 SettingManager.Local.Width6 = lst.Columns[5].Width;
9392                 SettingManager.Local.Width7 = lst.Columns[6].Width;
9393                 SettingManager.Local.Width8 = lst.Columns[7].Width;
9394             }
9395             ModifySettingLocal = true;
9396             _isColumnChanged = true;
9397         }
9398
9399         private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9400         {
9401             DetailsListView lst = (DetailsListView)sender;
9402             if (SettingManager.Local == null) return;
9403             if (_iconCol)
9404             {
9405                 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9406                 {
9407                     SettingManager.Local.Width1 = lst.Columns[0].Width;
9408                     ModifySettingLocal = true;
9409                     _isColumnChanged = true;
9410                 }
9411                 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9412                 {
9413                     SettingManager.Local.Width3 = lst.Columns[1].Width;
9414                     ModifySettingLocal = true;
9415                     _isColumnChanged = true;
9416                 }
9417             }
9418             else
9419             {
9420                 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9421                 {
9422                     SettingManager.Local.Width1 = lst.Columns[0].Width;
9423                     ModifySettingLocal = true;
9424                     _isColumnChanged = true;
9425                 }
9426                 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9427                 {
9428                     SettingManager.Local.Width2 = lst.Columns[1].Width;
9429                     ModifySettingLocal = true;
9430                     _isColumnChanged = true;
9431                 }
9432                 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9433                 {
9434                     SettingManager.Local.Width3 = lst.Columns[2].Width;
9435                     ModifySettingLocal = true;
9436                     _isColumnChanged = true;
9437                 }
9438                 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9439                 {
9440                     SettingManager.Local.Width4 = lst.Columns[3].Width;
9441                     ModifySettingLocal = true;
9442                     _isColumnChanged = true;
9443                 }
9444                 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9445                 {
9446                     SettingManager.Local.Width5 = lst.Columns[4].Width;
9447                     ModifySettingLocal = true;
9448                     _isColumnChanged = true;
9449                 }
9450                 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9451                 {
9452                     SettingManager.Local.Width6 = lst.Columns[5].Width;
9453                     ModifySettingLocal = true;
9454                     _isColumnChanged = true;
9455                 }
9456                 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9457                 {
9458                     SettingManager.Local.Width7 = lst.Columns[6].Width;
9459                     ModifySettingLocal = true;
9460                     _isColumnChanged = true;
9461                 }
9462                 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9463                 {
9464                     SettingManager.Local.Width8 = lst.Columns[7].Width;
9465                     ModifySettingLocal = true;
9466                     _isColumnChanged = true;
9467                 }
9468             }
9469             // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9470             //if (changed)
9471             //{
9472             //    SaveConfigsLocal();
9473             //}
9474         }
9475
9476         private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9477         {
9478             if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9479             ModifySettingLocal = true;
9480         }
9481
9482         private void TweenMain_DragDrop(object sender, DragEventArgs e)
9483         {
9484             if (e.Data.GetDataPresent(DataFormats.FileDrop))
9485             {
9486                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9487                 {
9488                     SelectMedia_DragDrop(e);
9489                 }
9490             }
9491             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9492             {
9493                 var (url, title) = GetUrlFromDataObject(e.Data);
9494
9495                 string appendText;
9496                 if (title == null)
9497                     appendText = url;
9498                 else
9499                     appendText = title + " " + url;
9500
9501                 if (this.StatusText.TextLength == 0)
9502                     this.StatusText.Text = appendText;
9503                 else
9504                     this.StatusText.Text += " " + appendText;
9505             }
9506             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9507             {
9508                 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9509                 if (text != null)
9510                     this.StatusText.Text += text;
9511             }
9512             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9513             {
9514                 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9515                 if (data != null) StatusText.Text += data;
9516             }
9517         }
9518
9519         /// <summary>
9520         /// IDataObject から URL とタイトルの対を取得します
9521         /// </summary>
9522         /// <remarks>
9523         /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9524         /// </remarks>
9525         /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9526         /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9527         internal static (string Url, string Title) GetUrlFromDataObject(IDataObject data)
9528         {
9529             if (data.GetDataPresent("text/x-moz-url"))
9530             {
9531                 // Firefox, Google Chrome で利用可能
9532                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9533
9534                 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9535                 {
9536                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9537                     if (lines.Length < 2)
9538                         throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9539
9540                     return (lines[0], lines[1]);
9541                 }
9542             }
9543             else if (data.GetDataPresent("IESiteModeToUrl"))
9544             {
9545                 // Internet Exproler 用
9546                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9547
9548                 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9549                 {
9550                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9551                     if (lines.Length < 2)
9552                         throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9553
9554                     return (lines[0], lines[1]);
9555                 }
9556             }
9557             else if (data.GetDataPresent("UniformResourceLocatorW"))
9558             {
9559                 // それ以外のブラウザ向け
9560
9561                 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9562                 {
9563                     var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9564                     return (url, null);
9565                 }
9566             }
9567
9568             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9569         }
9570
9571         private void TweenMain_DragEnter(object sender, DragEventArgs e)
9572         {
9573             if (e.Data.GetDataPresent(DataFormats.FileDrop))
9574             {
9575                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9576                 {
9577                     SelectMedia_DragEnter(e);
9578                     return;
9579                 }
9580             }
9581             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9582             {
9583                 e.Effect = DragDropEffects.Copy;
9584                 return;
9585             }
9586             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9587             {
9588                 e.Effect = DragDropEffects.Copy;
9589                 return;
9590             }
9591             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9592             {
9593                 e.Effect = DragDropEffects.Copy;
9594                 return;
9595             }
9596
9597             e.Effect = DragDropEffects.None;
9598         }
9599
9600         private void TweenMain_DragOver(object sender, DragEventArgs e)
9601         {
9602         }
9603
9604         public bool IsNetworkAvailable()
9605         {
9606             bool nw = true;
9607             nw = MyCommon.IsNetworkAvailable();
9608             _myStatusOnline = nw;
9609             return nw;
9610         }
9611
9612         public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9613         {
9614             var uriStr = uri.AbsoluteUri;
9615
9616             // OpenTween 内部で使用する URL
9617             if (uri.Authority == "opentween")
9618             {
9619                 await this.OpenInternalUriAsync(uri);
9620                 return;
9621             }
9622
9623             // ハッシュタグを含む Twitter 検索
9624             if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9625             {
9626                 // ハッシュタグの場合は、タブで開く
9627                 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9628                 var pos = unescapedQuery.IndexOf('#');
9629                 if (pos == -1) return;
9630
9631                 var hash = unescapedQuery.Substring(pos);
9632                 this.HashSupl.AddItem(hash);
9633                 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9634                 this.AddNewTabForSearch(hash);
9635                 return;
9636             }
9637
9638             // ユーザープロフィールURL
9639             // フラグが立っている場合は設定と逆の動作をする
9640             if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9641                 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9642             {
9643                 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9644                 if (userUriMatch.Success)
9645                 {
9646                     var screenName = userUriMatch.Groups["ScreenName"].Value;
9647                     if (this.IsTwitterId(screenName))
9648                     {
9649                         await this.AddNewTabForUserTimeline(screenName);
9650                         return;
9651                     }
9652                 }
9653             }
9654
9655             // どのパターンにも該当しないURL
9656             await this.OpenUriInBrowserAsync(uriStr);
9657         }
9658
9659         /// <summary>
9660         /// OpenTween 内部の機能を呼び出すための URL を開きます
9661         /// </summary>
9662         private async Task OpenInternalUriAsync(Uri uri)
9663         {
9664             // ツイートを開く (//opentween/status/:status_id)
9665             var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9666             if (match.Success)
9667             {
9668                 var statusId = long.Parse(match.Groups[1].Value);
9669                 await this.OpenRelatedTab(statusId);
9670                 return;
9671             }
9672         }
9673
9674         public Task OpenUriInBrowserAsync(string UriString)
9675         {
9676             return Task.Run(() =>
9677             {
9678                 string myPath = UriString;
9679
9680                 try
9681                 {
9682                     var configBrowserPath = SettingManager.Local.BrowserPath;
9683                     if (!string.IsNullOrEmpty(configBrowserPath))
9684                     {
9685                         if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9686                         {
9687                             int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9688                             string browserPath = configBrowserPath.Substring(1, sep - 1);
9689                             string arg = "";
9690                             if (sep < configBrowserPath.Length - 1)
9691                             {
9692                                 arg = configBrowserPath.Substring(sep + 1);
9693                             }
9694                             myPath = arg + " " + myPath;
9695                             System.Diagnostics.Process.Start(browserPath, myPath);
9696                         }
9697                         else
9698                         {
9699                             System.Diagnostics.Process.Start(configBrowserPath, myPath);
9700                         }
9701                     }
9702                     else
9703                     {
9704                         System.Diagnostics.Process.Start(myPath);
9705                     }
9706                 }
9707                 catch (Exception)
9708                 {
9709                     //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9710                 }
9711             });
9712         }
9713
9714         private void ListTabSelect(TabPage _tab)
9715         {
9716             SetListProperty();
9717
9718             this.PurgeListViewItemCache();
9719
9720             this._statuses.SelectTab(_tab.Text);
9721
9722             var listView = this.CurrentListView;
9723
9724             _anchorPost = null;
9725             _anchorFlag = false;
9726
9727             if (_iconCol)
9728             {
9729                 listView.Columns[1].Text = ColumnText[2];
9730             }
9731             else
9732             {
9733                 for (int i = 0; i < listView.Columns.Count; i++)
9734                 {
9735                     listView.Columns[i].Text = ColumnText[i];
9736                 }
9737             }
9738         }
9739
9740         private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9741             => this.ListTabSelect(e.TabPage);
9742
9743         private void SelectListItem(DetailsListView LView, int Index)
9744         {
9745             //単一
9746             Rectangle bnd = new Rectangle();
9747             bool flg = false;
9748             var item = LView.FocusedItem;
9749             if (item != null)
9750             {
9751                 bnd = item.Bounds;
9752                 flg = true;
9753             }
9754
9755             do
9756             {
9757                 LView.SelectedIndices.Clear();
9758             }
9759             while (LView.SelectedIndices.Count > 0);
9760             item = LView.Items[Index];
9761             item.Selected = true;
9762             item.Focused = true;
9763
9764             if (flg) LView.Invalidate(bnd);
9765         }
9766
9767         private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9768         {
9769             //複数
9770             Rectangle bnd = new Rectangle();
9771             bool flg = false;
9772             var item = LView.FocusedItem;
9773             if (item != null)
9774             {
9775                 bnd = item.Bounds;
9776                 flg = true;
9777             }
9778
9779             if (Index != null)
9780             {
9781                 do
9782                 {
9783                     LView.SelectedIndices.Clear();
9784                 }
9785                 while (LView.SelectedIndices.Count > 0);
9786                 LView.SelectItems(Index);
9787             }
9788             if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9789             {
9790                 LView.SelectionMark = selectionMarkIndex;
9791             }
9792             if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9793             {
9794                 LView.Items[focusedIndex].Focused = true;
9795             }
9796             else if (Index != null && Index.Length != 0)
9797             {
9798                 LView.Items[Index.Last()].Focused = true;
9799             }
9800
9801             if (flg) LView.Invalidate(bnd);
9802         }
9803
9804         private void StartUserStream()
9805         {
9806             tw.NewPostFromStream += tw_NewPostFromStream;
9807             tw.UserStreamStarted += tw_UserStreamStarted;
9808             tw.UserStreamStopped += tw_UserStreamStopped;
9809             tw.PostDeleted += tw_PostDeleted;
9810             tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9811
9812             this.RefreshUserStreamsMenu();
9813
9814             if (SettingManager.Common.UserstreamStartup)
9815                 tw.StartUserStream();
9816         }
9817
9818         private async void TweenMain_Shown(object sender, EventArgs e)
9819         {
9820             NotifyIcon1.Visible = true;
9821
9822             if (this.IsNetworkAvailable())
9823             {
9824                 StartUserStream();
9825
9826                 var loadTasks = new List<Task>
9827                 {
9828                     this.RefreshMuteUserIdsAsync(),
9829                     this.RefreshBlockIdsAsync(),
9830                     this.RefreshNoRetweetIdsAsync(),
9831                     this.RefreshTwitterConfigurationAsync(),
9832                     this.RefreshTabAsync<HomeTabModel>(),
9833                     this.RefreshTabAsync<MentionsTabModel>(),
9834                     this.RefreshTabAsync<DirectMessagesTabModel>(),
9835                     this.RefreshTabAsync<PublicSearchTabModel>(),
9836                     this.RefreshTabAsync<UserTimelineTabModel>(),
9837                     this.RefreshTabAsync<ListTimelineTabModel>(),
9838                 };
9839
9840                 if (SettingManager.Common.StartupFollowers)
9841                     loadTasks.Add(this.RefreshFollowerIdsAsync());
9842
9843                 if (SettingManager.Common.GetFav)
9844                     loadTasks.Add(this.RefreshTabAsync<FavoritesTabModel>());
9845
9846                 var allTasks = Task.WhenAll(loadTasks);
9847
9848                 var i = 0;
9849                 while (true)
9850                 {
9851                     var timeout = Task.Delay(5000);
9852                     if (await Task.WhenAny(allTasks, timeout) != timeout)
9853                         break;
9854
9855                     i += 1;
9856                     if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
9857
9858                     if (MyCommon._endingFlag)
9859                         return;
9860                 }
9861
9862                 if (MyCommon._endingFlag) return;
9863
9864                 if (ApplicationSettings.VersionInfoUrl != null)
9865                 {
9866                     //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
9867                     if (SettingManager.Common.StartupVersion)
9868                         await this.CheckNewVersion(true);
9869                 }
9870                 else
9871                 {
9872                     // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
9873                     this.VerUpMenuItem.Enabled = false;
9874                     this.VerUpMenuItem.Available = false;
9875                     this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
9876                 }
9877
9878                 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
9879                 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
9880                 {
9881                     MessageBox.Show(Properties.Resources.ReAuthorizeText);
9882                     SettingStripMenuItem_Click(null, null);
9883                 }
9884
9885                 // 取得失敗の場合は再試行する
9886                 var reloadTasks = new List<Task>();
9887
9888                 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
9889                     reloadTasks.Add(this.RefreshFollowerIdsAsync());
9890
9891                 if (!tw.GetNoRetweetSuccess)
9892                     reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
9893
9894                 if (this.tw.Configuration.PhotoSizeLimit == 0)
9895                     reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
9896
9897                 await Task.WhenAll(reloadTasks);
9898             }
9899
9900             _initial = false;
9901
9902             TimerTimeline.Enabled = true;
9903         }
9904
9905         private async Task doGetFollowersMenu()
9906         {
9907             await this.RefreshFollowerIdsAsync();
9908             await this.DispSelectedPost(true);
9909         }
9910
9911         private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
9912             => await this.doGetFollowersMenu();
9913
9914         private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
9915             => this.doReTweetUnofficial();
9916
9917         private async Task doReTweetOfficial(bool isConfirm)
9918         {
9919             //公式RT
9920             if (this.ExistCurrentPost)
9921             {
9922                 var selectedPosts = this.CurrentTab.SelectedPosts;
9923
9924                 if (selectedPosts.Any(x => !x.CanRetweetBy(this.twitterApi.CurrentUserId)))
9925                 {
9926                     if (selectedPosts.Any(x => x.IsProtect))
9927                         MessageBox.Show("Protected.");
9928
9929                     _DoFavRetweetFlags = false;
9930                     return;
9931                 }
9932
9933                 if (selectedPosts.Length > 15)
9934                 {
9935                     MessageBox.Show(Properties.Resources.RetweetLimitText);
9936                     _DoFavRetweetFlags = false;
9937                     return;
9938                 }
9939                 else if (selectedPosts.Length > 1)
9940                 {
9941                     string QuestionText = Properties.Resources.RetweetQuestion2;
9942                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
9943                     switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
9944                     {
9945                         case DialogResult.Cancel:
9946                         case DialogResult.No:
9947                             _DoFavRetweetFlags = false;
9948                             return;
9949                     }
9950                 }
9951                 else
9952                 {
9953                     if (!SettingManager.Common.RetweetNoConfirm)
9954                     {
9955                         string Questiontext = Properties.Resources.RetweetQuestion1;
9956                         if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
9957                         if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9958                         {
9959                             _DoFavRetweetFlags = false;
9960                             return;
9961                         }
9962                     }
9963                 }
9964
9965                 var statusIds = selectedPosts.Select(x => x.StatusId).ToList();
9966
9967                 await this.RetweetAsync(statusIds);
9968             }
9969         }
9970
9971         private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
9972             => await this.doReTweetOfficial(true);
9973
9974         private async Task FavoritesRetweetOfficial()
9975         {
9976             if (!this.ExistCurrentPost) return;
9977             _DoFavRetweetFlags = true;
9978             var retweetTask = this.doReTweetOfficial(true);
9979             if (_DoFavRetweetFlags)
9980             {
9981                 _DoFavRetweetFlags = false;
9982                 var favoriteTask = this.FavoriteChange(true, false);
9983
9984                 await Task.WhenAll(retweetTask, favoriteTask);
9985             }
9986             else
9987             {
9988                 await retweetTask;
9989             }
9990         }
9991
9992         private async Task FavoritesRetweetUnofficial()
9993         {
9994             var post = this.CurrentPost;
9995             if (this.ExistCurrentPost && !post.IsDm)
9996             {
9997                 _DoFavRetweetFlags = true;
9998                 var favoriteTask = this.FavoriteChange(true);
9999                 if (!post.IsProtect && _DoFavRetweetFlags)
10000                 {
10001                     _DoFavRetweetFlags = false;
10002                     doReTweetUnofficial();
10003                 }
10004
10005                 await favoriteTask;
10006             }
10007         }
10008
10009         /// <summary>
10010         /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10011         /// </summary>
10012         /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10013         /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10014         /// <returns>復元されたツイート本文</returns>
10015         internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10016         {
10017             // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10018
10019             // 通常の URL
10020             statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10021             // メンション
10022             statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10023             // ハッシュタグ
10024             statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10025             // 絵文字
10026             statusHtml = Regex.Replace(statusHtml, "<img class=\"emoji\" src=\".+?\" alt=\"(?<text>.+?)\" />", "${text}");
10027
10028             // <br> 除去
10029             if (multiline)
10030                 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10031             else
10032                 statusHtml = statusHtml.Replace("<br>", " ");
10033
10034             // &nbsp; は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10035             // 現状では半角スペースの代用として &nbsp; を使用しているため U+0020 に置換します
10036             statusHtml = statusHtml.Replace("&nbsp;", " ");
10037
10038             return WebUtility.HtmlDecode(statusHtml);
10039         }
10040
10041         private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10042         {
10043             this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10044
10045             if (this.CurrentPost != null)
10046                 await this.DispSelectedPost(true);
10047         }
10048
10049         private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10050         {
10051             if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10052                 DebugModeToolStripMenuItem.Visible = true;
10053             else
10054                 DebugModeToolStripMenuItem.Visible = false;
10055         }
10056
10057         private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
10058             => this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
10059
10060         private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
10061             => this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
10062
10063         private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
10064             => SettingManager.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
10065
10066         private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
10067         {
10068             SettingManager.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
10069             ModifySettingCommon = true;
10070         }
10071
10072         private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10073         {
10074             SettingManager.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
10075             ModifySettingCommon = true;
10076         }
10077
10078         private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
10079         {
10080             UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
10081             PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
10082             UrlAutoShortenMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10083             IdeographicSpaceToSpaceMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10084             MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
10085             FocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10086         }
10087
10088         private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10089         {
10090             UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
10091             PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
10092             UrlAutoShortenPullDownMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10093             IdeographicSpaceToSpacePullDownMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10094             MultiLinePullDownMenuItem.Checked = SettingManager.Local.StatusMultiline;
10095             FocusLockPullDownMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10096         }
10097
10098         private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10099         {
10100             if (TraceOutToolStripMenuItem.Checked)
10101                 MyCommon.TraceFlag = true;
10102             else
10103                 MyCommon.TraceFlag = false;
10104         }
10105
10106         private void TweenMain_Deactivate(object sender, EventArgs e)
10107             => this.StatusText_Leave(StatusText, EventArgs.Empty); // 画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10108
10109         private void TabRenameMenuItem_Click(object sender, EventArgs e)
10110         {
10111             if (string.IsNullOrEmpty(_rclickTabName)) return;
10112
10113             TabRename(_rclickTabName, out var _);
10114         }
10115
10116         private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10117             => await this.UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10118
10119         private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10120             => await this.UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10121
10122         private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10123         {
10124             TwitterApiStatus apiStatus;
10125
10126             using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10127             {
10128                 var cancellationToken = dialog.EnableCancellation();
10129
10130                 try
10131                 {
10132                     var task = this.tw.GetInfoApi();
10133                     apiStatus = await dialog.WaitForAsync(this, task);
10134                 }
10135                 catch (WebApiException)
10136                 {
10137                     apiStatus = null;
10138                 }
10139
10140                 if (cancellationToken.IsCancellationRequested)
10141                     return;
10142
10143                 if (apiStatus == null)
10144                 {
10145                     MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10146                     return;
10147                 }
10148             }
10149
10150             using (var apiDlg = new ApiInfoDialog())
10151             {
10152                 apiDlg.ShowDialog(this);
10153             }
10154         }
10155
10156         private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10157         {
10158             var id = this.CurrentPost?.ScreenName ?? "";
10159
10160             await this.FollowCommand(id);
10161         }
10162
10163         internal async Task FollowCommand(string id)
10164         {
10165             using (var inputName = new InputTabName())
10166             {
10167                 inputName.FormTitle = "Follow";
10168                 inputName.FormDescription = Properties.Resources.FRMessage1;
10169                 inputName.TabName = id;
10170
10171                 if (inputName.ShowDialog(this) != DialogResult.OK)
10172                     return;
10173                 if (string.IsNullOrWhiteSpace(inputName.TabName))
10174                     return;
10175
10176                 id = inputName.TabName.Trim();
10177             }
10178
10179             using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10180             {
10181                 try
10182                 {
10183                     var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
10184                     await dialog.WaitForAsync(this, task);
10185                 }
10186                 catch (WebApiException ex)
10187                 {
10188                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10189                     return;
10190                 }
10191             }
10192
10193             MessageBox.Show(Properties.Resources.FRMessage3);
10194         }
10195
10196         private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10197         {
10198             var id = this.CurrentPost?.ScreenName ?? "";
10199
10200             await this.RemoveCommand(id, false);
10201         }
10202
10203         internal async Task RemoveCommand(string id, bool skipInput)
10204         {
10205             if (!skipInput)
10206             {
10207                 using (var inputName = new InputTabName())
10208                 {
10209                     inputName.FormTitle = "Unfollow";
10210                     inputName.FormDescription = Properties.Resources.FRMessage1;
10211                     inputName.TabName = id;
10212
10213                     if (inputName.ShowDialog(this) != DialogResult.OK)
10214                         return;
10215                     if (string.IsNullOrWhiteSpace(inputName.TabName))
10216                         return;
10217
10218                     id = inputName.TabName.Trim();
10219                 }
10220             }
10221
10222             using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10223             {
10224                 try
10225                 {
10226                     var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
10227                     await dialog.WaitForAsync(this, task);
10228                 }
10229                 catch (WebApiException ex)
10230                 {
10231                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10232                     return;
10233                 }
10234             }
10235
10236             MessageBox.Show(Properties.Resources.FRMessage3);
10237         }
10238
10239         private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10240         {
10241             var id = this.CurrentPost?.ScreenName ?? "";
10242
10243             await this.ShowFriendship(id);
10244         }
10245
10246         internal async Task ShowFriendship(string id)
10247         {
10248             using (var inputName = new InputTabName())
10249             {
10250                 inputName.FormTitle = "Show Friendships";
10251                 inputName.FormDescription = Properties.Resources.FRMessage1;
10252                 inputName.TabName = id;
10253
10254                 if (inputName.ShowDialog(this) != DialogResult.OK)
10255                     return;
10256                 if (string.IsNullOrWhiteSpace(inputName.TabName))
10257                     return;
10258
10259                 id = inputName.TabName.Trim();
10260             }
10261
10262             bool isFollowing, isFollowed;
10263
10264             using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10265             {
10266                 var cancellationToken = dialog.EnableCancellation();
10267
10268                 try
10269                 {
10270                     var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10271                     var friendship = await dialog.WaitForAsync(this, task);
10272
10273                     isFollowing = friendship.Relationship.Source.Following;
10274                     isFollowed = friendship.Relationship.Source.FollowedBy;
10275                 }
10276                 catch (WebApiException ex)
10277                 {
10278                     if (!cancellationToken.IsCancellationRequested)
10279                         MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10280                     return;
10281                 }
10282
10283                 if (cancellationToken.IsCancellationRequested)
10284                     return;
10285             }
10286
10287             string result = "";
10288             if (isFollowing)
10289             {
10290                 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10291             }
10292             else
10293             {
10294                 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10295             }
10296             if (isFollowed)
10297             {
10298                 result += Properties.Resources.GetFriendshipInfo3;
10299             }
10300             else
10301             {
10302                 result += Properties.Resources.GetFriendshipInfo4;
10303             }
10304             result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10305             MessageBox.Show(result);
10306         }
10307
10308         internal async Task ShowFriendship(string[] ids)
10309         {
10310             foreach (string id in ids)
10311             {
10312                 bool isFollowing, isFollowed;
10313
10314                 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10315                 {
10316                     var cancellationToken = dialog.EnableCancellation();
10317
10318                     try
10319                     {
10320                         var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10321                         var friendship = await dialog.WaitForAsync(this, task);
10322
10323                         isFollowing = friendship.Relationship.Source.Following;
10324                         isFollowed = friendship.Relationship.Source.FollowedBy;
10325                     }
10326                     catch (WebApiException ex)
10327                     {
10328                         if (!cancellationToken.IsCancellationRequested)
10329                             MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10330                         return;
10331                     }
10332
10333                     if (cancellationToken.IsCancellationRequested)
10334                         return;
10335                 }
10336
10337                 string result = "";
10338                 string ff = "";
10339
10340                 ff = "  ";
10341                 if (isFollowing)
10342                 {
10343                     ff += Properties.Resources.GetFriendshipInfo1;
10344                 }
10345                 else
10346                 {
10347                     ff += Properties.Resources.GetFriendshipInfo2;
10348                 }
10349
10350                 ff += System.Environment.NewLine + "  ";
10351                 if (isFollowed)
10352                 {
10353                     ff += Properties.Resources.GetFriendshipInfo3;
10354                 }
10355                 else
10356                 {
10357                     ff += Properties.Resources.GetFriendshipInfo4;
10358                 }
10359                 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10360                 if (isFollowing)
10361                 {
10362                     if (MessageBox.Show(
10363                         Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10364                         MessageBoxButtons.YesNo,
10365                         MessageBoxIcon.Question,
10366                         MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10367                     {
10368                         await this.RemoveCommand(id, true);
10369                     }
10370                 }
10371                 else
10372                 {
10373                     MessageBox.Show(result);
10374                 }
10375             }
10376         }
10377
10378         private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10379             => await this.doShowUserStatus(tw.Username, false);
10380
10381         // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10382         // URLから切り出した文字列を渡す
10383
10384         public bool IsTwitterId(string name)
10385         {
10386             if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10387                 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10388             else
10389                 return !this.tw.Configuration.NonUsernamePaths.Contains(name, StringComparer.InvariantCultureIgnoreCase);
10390         }
10391
10392         private void doQuoteOfficial()
10393         {
10394             if (this.ExistCurrentPost)
10395             {
10396                 var post = this.CurrentPost;
10397                 if (post.IsDm || !StatusText.Enabled)
10398                     return;
10399
10400                 if (post.IsProtect)
10401                 {
10402                     MessageBox.Show("Protected.");
10403                     return;
10404                 }
10405
10406                 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10407
10408                 this.inReplyTo = null;
10409
10410                 StatusText.Text += " " + MyCommon.GetStatusUrl(post);
10411
10412                 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10413                 StatusText.Focus();
10414             }
10415         }
10416
10417         private void doReTweetUnofficial()
10418         {
10419             //RT @id:内容
10420             if (this.ExistCurrentPost)
10421             {
10422                 var post = this.CurrentPost;
10423                 if (post.IsDm || !StatusText.Enabled)
10424                     return;
10425
10426                 if (post.IsProtect)
10427                 {
10428                     MessageBox.Show("Protected.");
10429                     return;
10430                 }
10431                 string rtdata = post.Text;
10432                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10433
10434                 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10435
10436                 // 投稿時に in_reply_to_status_id を付加する
10437                 var inReplyToStatusId = post.RetweetedId ?? post.StatusId;
10438                 var inReplyToScreenName = post.ScreenName;
10439                 this.inReplyTo = (inReplyToStatusId, inReplyToScreenName);
10440
10441                 StatusText.Text += " RT @" + post.ScreenName + ": " + rtdata;
10442
10443                 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10444                 StatusText.Focus();
10445             }
10446         }
10447
10448         private void QuoteStripMenuItem_Click(object sender, EventArgs e)
10449             => this.doQuoteOfficial();
10450
10451         private async void SearchButton_Click(object sender, EventArgs e)
10452         {
10453             //公式検索
10454             Control pnl = ((Control)sender).Parent;
10455             if (pnl == null) return;
10456             string tbName = pnl.Parent.Text;
10457             var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10458             ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10459             ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10460             cmb.Text = cmb.Text.Trim();
10461             // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10462             bool Quote = false;
10463             StringBuilder buf = new StringBuilder();
10464             char[] c = cmb.Text.ToCharArray();
10465             for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10466             {
10467                 if (cnt > cmb.Text.Length - 4)
10468                 {
10469                     buf.Append(cmb.Text.Substring(cnt));
10470                     break;
10471                 }
10472                 if (c[cnt] == '"')
10473                 {
10474                     Quote = !Quote;
10475                 }
10476                 else
10477                 {
10478                     if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10479                     {
10480                         buf.Append(" OR ");
10481                         cnt += 3;
10482                         continue;
10483                     }
10484                 }
10485                 buf.Append(c[cnt]);
10486             }
10487             cmb.Text = buf.ToString();
10488
10489             var listView = (DetailsListView)pnl.Parent.Tag;
10490
10491             var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10492
10493             tb.SearchWords = cmb.Text;
10494             tb.SearchLang = cmbLang.Text;
10495             if (string.IsNullOrEmpty(cmb.Text))
10496             {
10497                 listView.Focus();
10498                 SaveConfigsTabs();
10499                 return;
10500             }
10501             if (queryChanged)
10502             {
10503                 int idx = cmb.Items.IndexOf(tb.SearchWords);
10504                 if (idx > -1) cmb.Items.RemoveAt(idx);
10505                 cmb.Items.Insert(0, tb.SearchWords);
10506                 cmb.Text = tb.SearchWords;
10507                 cmb.SelectAll();
10508                 this.PurgeListViewItemCache();
10509                 listView.VirtualListSize = 0;
10510                 _statuses.ClearTabIds(tbName);
10511                 SaveConfigsTabs();   //検索条件の保存
10512             }
10513
10514             listView.Focus();
10515             await this.RefreshTabAsync(tb);
10516         }
10517
10518         private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10519             => await this.DoRefreshMore(); // もっと前を取得
10520
10521         /// <summary>
10522         /// 指定されたタブのListTabにおける位置を返します
10523         /// </summary>
10524         /// <remarks>
10525         /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10526         /// </remarks>
10527         public int GetTabPageIndex(string tabName)
10528             => this._statuses.Tabs.IndexOf(tabName);
10529
10530         private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10531         {
10532             if (_statuses.RemovedTab.Count == 0)
10533             {
10534                 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10535                 return;
10536             }
10537             else
10538             {
10539                 DetailsListView listView = null;
10540
10541                 TabModel tb = _statuses.RemovedTab.Pop();
10542                 if (tb.TabType == MyCommon.TabUsageType.Related)
10543                 {
10544                     var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10545                     if (relatedTab != null)
10546                     {
10547                         // 関連発言なら既存のタブを置き換える
10548                         tb.TabName = relatedTab.TabName;
10549                         this.ClearTab(tb.TabName, false);
10550
10551                         this._statuses.ReplaceTab(tb);
10552
10553                         var tabIndex = this._statuses.Tabs.IndexOf(tb);
10554                         var tabPage = this.ListTab.TabPages[tabIndex];
10555                         listView = (DetailsListView)tabPage.Tag;
10556                         this.ListTab.SelectedIndex = tabIndex;
10557                     }
10558                     else
10559                     {
10560                         const string TabName = "Related Tweets";
10561                         string renamed = TabName;
10562                         for (int i = 2; i <= 100; i++)
10563                         {
10564                             if (!_statuses.ContainsTab(renamed)) break;
10565                             renamed = TabName + i;
10566                         }
10567                         tb.TabName = renamed;
10568
10569                         _statuses.AddTab(tb);
10570                         AddNewTab(tb, startup: false);
10571
10572                         var tabIndex = this._statuses.Tabs.Count - 1;
10573                         var tabPage = this.ListTab.TabPages[tabIndex];
10574
10575                         listView = (DetailsListView)tabPage.Tag;
10576                         this.ListTab.SelectedIndex = tabIndex;
10577                     }
10578                 }
10579                 else
10580                 {
10581                     string renamed = tb.TabName;
10582                     for (int i = 1; i < int.MaxValue; i++)
10583                     {
10584                         if (!_statuses.ContainsTab(renamed)) break;
10585                         renamed = tb.TabName + "(" + i + ")";
10586                     }
10587                     tb.TabName = renamed;
10588
10589                     _statuses.AddTab(tb);
10590                     AddNewTab(tb, startup: false);
10591
10592                     var tabIndex = this._statuses.Tabs.Count - 1;
10593                     var tabPage = this.ListTab.TabPages[tabIndex];
10594
10595                     listView = (DetailsListView)tabPage.Tag;
10596                     this.ListTab.SelectedIndex = tabIndex;
10597                 }
10598                 SaveConfigsTabs();
10599
10600                 if (listView != null)
10601                 {
10602                     using (ControlTransaction.Update(listView))
10603                     {
10604                         listView.VirtualListSize = tb.AllCount;
10605                     }
10606                 }
10607             }
10608         }
10609
10610         private async Task doMoveToRTHome()
10611         {
10612             var post = this.CurrentPost;
10613             if (post != null && post.RetweetedId != null)
10614                 await this.OpenUriInBrowserAsync("https://twitter.com/" + post.RetweetedBy);
10615         }
10616
10617         private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10618             => await this.doMoveToRTHome();
10619
10620         private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10621         {
10622             var screenName = this.CurrentPost?.ScreenName;
10623             if (screenName != null)
10624                 this.ListManageUserContext(screenName);
10625         }
10626
10627         public void ListManageUserContext(string screenName)
10628         {
10629             using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10630             {
10631                 listSelectForm.ShowDialog(this);
10632             }
10633         }
10634
10635         private void SearchControls_Enter(object sender, EventArgs e)
10636         {
10637             Control pnl = (Control)sender;
10638             foreach (Control ctl in pnl.Controls)
10639             {
10640                 ctl.TabStop = true;
10641             }
10642         }
10643
10644         private void SearchControls_Leave(object sender, EventArgs e)
10645         {
10646             Control pnl = (Control)sender;
10647             foreach (Control ctl in pnl.Controls)
10648             {
10649                 ctl.TabStop = false;
10650             }
10651         }
10652
10653         private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10654         {
10655             var tab = this.CurrentTab;
10656             if (tab.TabType != MyCommon.TabUsageType.PublicSearch) return;
10657             this.CurrentTabPage.Controls["panelSearch"].Controls["comboSearch"].Focus();
10658         }
10659
10660         private void StatusLabel_DoubleClick(object sender, EventArgs e)
10661             => MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10662
10663         private void HashManageMenuItem_Click(object sender, EventArgs e)
10664         {
10665             DialogResult rslt = DialogResult.Cancel;
10666             try
10667             {
10668                 rslt = HashMgr.ShowDialog();
10669             }
10670             catch (Exception)
10671             {
10672                 return;
10673             }
10674             this.TopMost = SettingManager.Common.AlwaysTop;
10675             if (rslt == DialogResult.Cancel) return;
10676             if (!string.IsNullOrEmpty(HashMgr.UseHash))
10677             {
10678                 HashStripSplitButton.Text = HashMgr.UseHash;
10679                 HashTogglePullDownMenuItem.Checked = true;
10680                 HashToggleMenuItem.Checked = true;
10681             }
10682             else
10683             {
10684                 HashStripSplitButton.Text = "#[-]";
10685                 HashTogglePullDownMenuItem.Checked = false;
10686                 HashToggleMenuItem.Checked = false;
10687             }
10688             //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10689             //{
10690             //    int sidx = StatusText.SelectionStart;
10691             //    string hash = HashMgr.UseHash + " ";
10692             //    if (sidx > 0)
10693             //    {
10694             //        if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10695             //            hash = " " + hash;
10696             //    }
10697             //    StatusText.Text = StatusText.Text.Insert(sidx, hash);
10698             //    sidx += hash.Length;
10699             //    StatusText.SelectionStart = sidx;
10700             //    StatusText.Focus();
10701             //}
10702             ModifySettingCommon = true;
10703             this.StatusText_TextChanged(null, null);
10704         }
10705
10706         private void HashToggleMenuItem_Click(object sender, EventArgs e)
10707         {
10708             HashMgr.ToggleHash();
10709             if (!string.IsNullOrEmpty(HashMgr.UseHash))
10710             {
10711                 HashStripSplitButton.Text = HashMgr.UseHash;
10712                 HashToggleMenuItem.Checked = true;
10713                 HashTogglePullDownMenuItem.Checked = true;
10714             }
10715             else
10716             {
10717                 HashStripSplitButton.Text = "#[-]";
10718                 HashToggleMenuItem.Checked = false;
10719                 HashTogglePullDownMenuItem.Checked = false;
10720             }
10721             ModifySettingCommon = true;
10722             this.StatusText_TextChanged(null, null);
10723         }
10724
10725         private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10726             => this.HashToggleMenuItem_Click(null, null);
10727
10728         public void SetPermanentHashtag(string hashtag)
10729         {
10730             HashMgr.SetPermanentHash("#" + hashtag);
10731             HashStripSplitButton.Text = HashMgr.UseHash;
10732             HashTogglePullDownMenuItem.Checked = true;
10733             HashToggleMenuItem.Checked = true;
10734             //使用ハッシュタグとして設定
10735             ModifySettingCommon = true;
10736         }
10737
10738         private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10739         {
10740             if (!this.ExistCurrentPost)
10741             {
10742                 this.ReplyOpMenuItem.Enabled = false;
10743                 this.ReplyAllOpMenuItem.Enabled = false;
10744                 this.DmOpMenuItem.Enabled = false;
10745                 this.ShowProfMenuItem.Enabled = false;
10746                 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10747                 this.ListManageMenuItem.Enabled = false;
10748                 this.OpenFavOpMenuItem.Enabled = false;
10749                 this.CreateTabRuleOpMenuItem.Enabled = false;
10750                 this.CreateIdRuleOpMenuItem.Enabled = false;
10751                 this.CreateSourceRuleOpMenuItem.Enabled = false;
10752                 this.ReadOpMenuItem.Enabled = false;
10753                 this.UnreadOpMenuItem.Enabled = false;
10754             }
10755             else
10756             {
10757                 this.ReplyOpMenuItem.Enabled = true;
10758                 this.ReplyAllOpMenuItem.Enabled = true;
10759                 this.DmOpMenuItem.Enabled = true;
10760                 this.ShowProfMenuItem.Enabled = true;
10761                 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10762                 this.ListManageMenuItem.Enabled = true;
10763                 this.OpenFavOpMenuItem.Enabled = true;
10764                 this.CreateTabRuleOpMenuItem.Enabled = true;
10765                 this.CreateIdRuleOpMenuItem.Enabled = true;
10766                 this.CreateSourceRuleOpMenuItem.Enabled = true;
10767                 this.ReadOpMenuItem.Enabled = true;
10768                 this.UnreadOpMenuItem.Enabled = true;
10769             }
10770
10771             var tab = this.CurrentTab;
10772             var post = this.CurrentPost;
10773             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || post.IsDm)
10774             {
10775                 this.FavOpMenuItem.Enabled = false;
10776                 this.UnFavOpMenuItem.Enabled = false;
10777                 this.OpenStatusOpMenuItem.Enabled = false;
10778                 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10779                 this.RtOpMenuItem.Enabled = false;
10780                 this.RtUnOpMenuItem.Enabled = false;
10781                 this.QtOpMenuItem.Enabled = false;
10782                 this.FavoriteRetweetMenuItem.Enabled = false;
10783                 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10784             }
10785             else
10786             {
10787                 this.FavOpMenuItem.Enabled = true;
10788                 this.UnFavOpMenuItem.Enabled = true;
10789                 this.OpenStatusOpMenuItem.Enabled = true;
10790                 this.ShowRelatedStatusesMenuItem2.Enabled = true;  //PublicSearchの時問題出るかも
10791
10792                 if (!post.CanRetweetBy(this.twitterApi.CurrentUserId))
10793                 {
10794                     this.RtOpMenuItem.Enabled = false;
10795                     this.RtUnOpMenuItem.Enabled = false;
10796                     this.QtOpMenuItem.Enabled = false;
10797                     this.FavoriteRetweetMenuItem.Enabled = false;
10798                     this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
10799                 }
10800                 else
10801                 {
10802                     this.RtOpMenuItem.Enabled = true;
10803                     this.RtUnOpMenuItem.Enabled = true;
10804                     this.QtOpMenuItem.Enabled = true;
10805                     this.FavoriteRetweetMenuItem.Enabled = true;
10806                     this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
10807                 }
10808             }
10809
10810             if (tab.TabType != MyCommon.TabUsageType.Favorites)
10811             {
10812                 this.RefreshPrevOpMenuItem.Enabled = true;
10813             }
10814             else
10815             {
10816                 this.RefreshPrevOpMenuItem.Enabled = false;
10817             }
10818             if (!this.ExistCurrentPost || post.InReplyToStatusId == null)
10819             {
10820                 OpenRepSourceOpMenuItem.Enabled = false;
10821             }
10822             else
10823             {
10824                 OpenRepSourceOpMenuItem.Enabled = true;
10825             }
10826             if (!this.ExistCurrentPost || string.IsNullOrEmpty(post.RetweetedBy))
10827             {
10828                 OpenRterHomeMenuItem.Enabled = false;
10829             }
10830             else
10831             {
10832                 OpenRterHomeMenuItem.Enabled = true;
10833             }
10834
10835             if (this.ExistCurrentPost)
10836             {
10837                 this.DelOpMenuItem.Enabled = post.CanDeleteBy(this.tw.UserId);
10838             }
10839         }
10840
10841         private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
10842             => this.ContextMenuTabProperty_Opening(sender, null);
10843
10844         public Twitter TwitterInstance
10845             => this.tw;
10846
10847         private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
10848         {
10849             if (this._initialLayout)
10850                 return;
10851
10852             int splitterDistance;
10853             switch (this.WindowState)
10854             {
10855                 case FormWindowState.Normal:
10856                     splitterDistance = this.SplitContainer3.SplitterDistance;
10857                     break;
10858                 case FormWindowState.Maximized:
10859                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
10860                     var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
10861                     splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
10862                     splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
10863                     break;
10864                 default:
10865                     return;
10866             }
10867
10868             this._mySpDis3 = splitterDistance;
10869             this.ModifySettingLocal = true;
10870         }
10871
10872         private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
10873         {
10874             if (_statuses.RemovedTab.Count == 0)
10875             {
10876                 UndoRemoveTabMenuItem.Enabled = false;
10877             }
10878             else
10879             {
10880                 UndoRemoveTabMenuItem.Enabled = true;
10881             }
10882
10883             if (this.CurrentTab.TabType == MyCommon.TabUsageType.PublicSearch)
10884                 PublicSearchQueryMenuItem.Enabled = true;
10885             else
10886                 PublicSearchQueryMenuItem.Enabled = false;
10887
10888             if (!this.ExistCurrentPost)
10889             {
10890                 this.CopySTOTMenuItem.Enabled = false;
10891                 this.CopyURLMenuItem.Enabled = false;
10892                 this.CopyUserIdStripMenuItem.Enabled = false;
10893             }
10894             else
10895             {
10896                 this.CopySTOTMenuItem.Enabled = true;
10897                 this.CopyURLMenuItem.Enabled = true;
10898                 this.CopyUserIdStripMenuItem.Enabled = true;
10899
10900                 var post = this.CurrentPost;
10901                 if (post.IsDm) this.CopyURLMenuItem.Enabled = false;
10902                 if (post.IsProtect) this.CopySTOTMenuItem.Enabled = false;
10903             }
10904         }
10905
10906         private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
10907             => this.SetNotifyIconText();
10908
10909         private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
10910             => await this.ShowUserStatus(this.CurrentPost?.ScreenName ?? "");
10911
10912         private async Task doShowUserStatus(string id, bool ShowInputDialog)
10913         {
10914             TwitterUser user = null;
10915
10916             if (ShowInputDialog)
10917             {
10918                 using (var inputName = new InputTabName())
10919                 {
10920                     inputName.FormTitle = "Show UserStatus";
10921                     inputName.FormDescription = Properties.Resources.FRMessage1;
10922                     inputName.TabName = id;
10923
10924                     if (inputName.ShowDialog(this) != DialogResult.OK)
10925                         return;
10926                     if (string.IsNullOrWhiteSpace(inputName.TabName))
10927                         return;
10928
10929                     id = inputName.TabName.Trim();
10930                 }
10931             }
10932
10933             using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
10934             {
10935                 var cancellationToken = dialog.EnableCancellation();
10936
10937                 try
10938                 {
10939                     var task = this.twitterApi.UsersShow(id);
10940                     user = await dialog.WaitForAsync(this, task);
10941                 }
10942                 catch (WebApiException ex)
10943                 {
10944                     if (!cancellationToken.IsCancellationRequested)
10945                         MessageBox.Show($"Err:{ex.Message}(UsersShow)");
10946                     return;
10947                 }
10948
10949                 if (cancellationToken.IsCancellationRequested)
10950                     return;
10951             }
10952
10953             await this.doShowUserStatus(user);
10954         }
10955
10956         private async Task doShowUserStatus(TwitterUser user)
10957         {
10958             using (var userDialog = new UserInfoDialog(this, this.twitterApi))
10959             {
10960                 var showUserTask = userDialog.ShowUserAsync(user);
10961                 userDialog.ShowDialog(this);
10962
10963                 this.Activate();
10964                 this.BringToFront();
10965
10966                 // ユーザー情報の表示が完了するまで userDialog を破棄しない
10967                 await showUserTask;
10968             }
10969         }
10970
10971         internal Task ShowUserStatus(string id, bool ShowInputDialog)
10972             => this.doShowUserStatus(id, ShowInputDialog);
10973
10974         internal Task ShowUserStatus(string id)
10975             => this.doShowUserStatus(id, true);
10976
10977         private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
10978         {
10979             var post = this.CurrentPost;
10980             if (post != null)
10981             {
10982                 await this.ShowUserStatus(post.ScreenName, false);
10983             }
10984         }
10985
10986         private async void RtCountMenuItem_Click(object sender, EventArgs e)
10987         {
10988             if (!this.ExistCurrentPost)
10989                 return;
10990
10991             var post = this.CurrentPost;
10992             var statusId = post.RetweetedId ?? post.StatusId;
10993             TwitterStatus status;
10994
10995             using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
10996             {
10997                 var cancellationToken = dialog.EnableCancellation();
10998
10999                 try
11000                 {
11001                     var task = this.twitterApi.StatusesShow(statusId);
11002                     status = await dialog.WaitForAsync(this, task);
11003                 }
11004                 catch (WebApiException ex)
11005                 {
11006                     if (!cancellationToken.IsCancellationRequested)
11007                         MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11008                     return;
11009                 }
11010
11011                 if (cancellationToken.IsCancellationRequested)
11012                     return;
11013             }
11014
11015             MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11016         }
11017
11018         private HookGlobalHotkey _hookGlobalHotkey;
11019         public TweenMain()
11020         {
11021             _hookGlobalHotkey = new HookGlobalHotkey(this);
11022
11023             // この呼び出しは、Windows フォーム デザイナで必要です。
11024             InitializeComponent();
11025
11026             // InitializeComponent() 呼び出しの後で初期化を追加します。
11027
11028             if (!this.DesignMode)
11029             {
11030                 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11031                 this.StatusText.Dock = DockStyle.Fill;
11032             }
11033
11034             this.tweetDetailsView.Owner = this;
11035
11036             this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11037             this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11038             this.gh.NotifyClicked += GrowlHelper_Callback;
11039
11040             // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11041             this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11042
11043             this.ImageSelector.Visible = false;
11044             this.ImageSelector.Enabled = false;
11045             this.ImageSelector.FilePickDialog = OpenFileDialog1;
11046
11047             this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11048
11049             this.ReplaceAppName();
11050             this.InitializeShortcuts();
11051         }
11052
11053         private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11054         {
11055             if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11056             {
11057                 //アイコン化
11058                 this.Visible = false;
11059             }
11060             else if (Form.ActiveForm == null)
11061             {
11062                 this.Visible = true;
11063                 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11064                 this.Activate();
11065                 this.BringToFront();
11066                 this.StatusText.Focus();
11067             }
11068         }
11069
11070         private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11071             => this.MultiLinePullDownMenuItem.PerformClick();
11072
11073 #region "画像投稿"
11074         private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11075         {
11076             if (ImageSelector.Visible)
11077                 ImageSelector.EndSelection();
11078             else
11079                 ImageSelector.BeginSelection();
11080         }
11081
11082         private void SelectMedia_DragEnter(DragEventArgs e)
11083         {
11084             if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11085             {
11086                 e.Effect = DragDropEffects.Copy;
11087                 return;
11088             }
11089             e.Effect = DragDropEffects.None;
11090         }
11091
11092         private void SelectMedia_DragDrop(DragEventArgs e)
11093         {
11094             this.Activate();
11095             this.BringToFront();
11096             ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11097             StatusText.Focus();
11098         }
11099
11100         private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11101         {
11102             TimelinePanel.Visible = false;
11103             TimelinePanel.Enabled = false;
11104         }
11105
11106         private void ImageSelector_EndSelecting(object sender, EventArgs e)
11107         {
11108             TimelinePanel.Visible = true;
11109             TimelinePanel.Enabled = true;
11110             this.CurrentListView.Focus();
11111         }
11112
11113         private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11114             => this.AllowDrop = false;
11115
11116         private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11117             => this.AllowDrop = true;
11118
11119         private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11120         {
11121             if (ImageSelector.Visible)
11122             {
11123                 ModifySettingCommon = true;
11124                 SaveConfigsAll(true);
11125
11126                 this.StatusText_TextChanged(null, null);
11127             }
11128         }
11129
11130         private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11131             => this.StatusText_TextChanged(null, null);
11132
11133         /// <summary>
11134         /// StatusTextでCtrl+Vが押下された時の処理
11135         /// </summary>
11136         private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11137         {
11138             try
11139             {
11140                 if (Clipboard.ContainsText())
11141                 {
11142                     // clipboardにテキストがある場合は貼り付け処理
11143                     this.StatusText.Paste(Clipboard.GetText());
11144                 }
11145                 else if (Clipboard.ContainsImage())
11146                 {
11147                     // 画像があるので投稿処理を行う
11148                     if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11149                                        Properties.Resources.PostPictureWarn4,
11150                                        MessageBoxButtons.OKCancel,
11151                                        MessageBoxIcon.Question,
11152                                        MessageBoxDefaultButton.Button2)
11153                                    == DialogResult.OK)
11154                     {
11155                         // clipboardから画像を取得
11156                         using (var image = Clipboard.GetImage())
11157                         {
11158                             this.ImageSelector.BeginSelection(image);
11159                         }
11160                     }
11161                 }
11162             }
11163             catch (ExternalException ex)
11164             {
11165                 MessageBox.Show(ex.Message);
11166             }
11167         }
11168 #endregion
11169
11170         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11171         {
11172             using (ListManage form = new ListManage(tw))
11173             {
11174                 form.ShowDialog(this);
11175             }
11176         }
11177
11178         public bool ModifySettingCommon { get; set; }
11179         public bool ModifySettingLocal { get; set; }
11180         public bool ModifySettingAtId { get; set; }
11181
11182         private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11183         {
11184             var post = this.CurrentPost;
11185             if (this.ExistCurrentPost && !post.IsDm)
11186                 RtCountMenuItem.Enabled = true;
11187             else
11188                 RtCountMenuItem.Enabled = false;
11189
11190             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11191             //    TinyUrlConvertToolStripMenuItem.Enabled = false;
11192             //else
11193             //    TinyUrlConvertToolStripMenuItem.Enabled = true;
11194         }
11195
11196         private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11197             => this.CopyUserId();
11198
11199         private void CopyUserId()
11200         {
11201             var post = this.CurrentPost;
11202             if (post == null) return;
11203             var clstr = post.ScreenName;
11204             try
11205             {
11206                 Clipboard.SetDataObject(clstr, false, 5, 100);
11207             }
11208             catch (Exception ex)
11209             {
11210                 MessageBox.Show(ex.Message);
11211             }
11212         }
11213
11214         private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11215         {
11216             var post = this.CurrentPost;
11217             if (this.ExistCurrentPost && !post.IsDm)
11218             {
11219                 try
11220                 {
11221                     await this.OpenRelatedTab(post);
11222                 }
11223                 catch (TabException ex)
11224                 {
11225                     MessageBox.Show(this, ex.Message, ApplicationSettings.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11226                 }
11227             }
11228         }
11229
11230         /// <summary>
11231         /// 指定されたツイートに対する関連発言タブを開きます
11232         /// </summary>
11233         /// <param name="statusId">表示するツイートのID</param>
11234         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11235         public async Task OpenRelatedTab(long statusId)
11236         {
11237             var post = this._statuses[statusId];
11238             if (post == null)
11239             {
11240                 try
11241                 {
11242                     post = await this.tw.GetStatusApi(false, statusId);
11243                 }
11244                 catch (WebApiException ex)
11245                 {
11246                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11247                     return;
11248                 }
11249             }
11250
11251             await this.OpenRelatedTab(post);
11252         }
11253
11254         /// <summary>
11255         /// 指定されたツイートに対する関連発言タブを開きます
11256         /// </summary>
11257         /// <param name="post">表示する対象となるツイート</param>
11258         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11259         private async Task OpenRelatedTab(PostClass post)
11260         {
11261             var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11262             if (tabRelated != null)
11263             {
11264                 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11265             }
11266
11267             var tabName = this._statuses.MakeTabName("Related Tweets");
11268
11269             tabRelated = new RelatedPostsTabModel(tabName, post)
11270             {
11271                 UnreadManage = false,
11272                 Notify = false,
11273             };
11274
11275             this._statuses.AddTab(tabRelated);
11276             this.AddNewTab(tabRelated, startup: false);
11277
11278             this.ListTab.SelectedIndex = this._statuses.Tabs.IndexOf(tabName);
11279
11280             await this.RefreshTabAsync(tabRelated);
11281
11282             var tabIndex = this._statuses.Tabs.IndexOf(tabRelated.TabName);
11283
11284             if (tabIndex != -1)
11285             {
11286                 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11287
11288                 var tabPage = this.ListTab.TabPages[tabIndex];
11289                 var listView = (DetailsListView)tabPage.Tag;
11290                 var targetPost = tabRelated.TargetPost;
11291                 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11292
11293                 if (index != -1 && index < listView.Items.Count)
11294                 {
11295                     listView.SelectedIndices.Add(index);
11296                     listView.Items[index].Focused = true;
11297                 }
11298             }
11299         }
11300
11301         private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11302         {
11303             StringBuilder buf = new StringBuilder();
11304             //buf.AppendFormat("キャッシュメモリ容量         : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11305             //buf.AppendFormat("物理メモリ使用割合           : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11306             buf.AppendFormat("キャッシュエントリ保持数     : {0}" + Environment.NewLine, IconCache.CacheCount);
11307             buf.AppendFormat("キャッシュエントリ破棄数     : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11308             MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11309         }
11310
11311         private void tw_UserIdChanged()
11312             => this.ModifySettingCommon = true;
11313
11314 #region "Userstream"
11315         private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11316         {
11317             try
11318             {
11319                 if (InvokeRequired && !IsDisposed)
11320                 {
11321                     await this.InvokeAsync(async () =>
11322                     {
11323                         this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11324                         if (this.CurrentTab.Contains(e.StatusId))
11325                         {
11326                             this.PurgeListViewItemCache();
11327                             this.CurrentListView.Update();
11328                             var post = this.CurrentPost;
11329                             if (post != null && post.StatusId == e.StatusId)
11330                                 await this.DispSelectedPost(true);
11331                         }
11332                     });
11333                     return;
11334                 }
11335             }
11336             catch (ObjectDisposedException)
11337             {
11338                 return;
11339             }
11340             catch (InvalidOperationException)
11341             {
11342                 return;
11343             }
11344         }
11345
11346         private void tw_NewPostFromStream(object sender, EventArgs e)
11347         {
11348             if (SettingManager.Common.ReadOldPosts)
11349             {
11350                 _statuses.SetReadHomeTab(); //新着時未読クリア
11351             }
11352
11353             this._statuses.DistributePosts();
11354
11355             this.RefreshThrottlingTimer.Invoke();
11356         }
11357
11358         private async void tw_UserStreamStarted(object sender, EventArgs e)
11359         {
11360             try
11361             {
11362                 if (InvokeRequired && !IsDisposed)
11363                 {
11364                     await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11365                     return;
11366                 }
11367             }
11368             catch (ObjectDisposedException)
11369             {
11370                 return;
11371             }
11372             catch (InvalidOperationException)
11373             {
11374                 return;
11375             }
11376
11377             this.RefreshUserStreamsMenu();
11378             this.MenuItemUserStream.Enabled = true;
11379
11380             StatusLabel.Text = "UserStream Started.";
11381         }
11382
11383         private async void tw_UserStreamStopped(object sender, EventArgs e)
11384         {
11385             try
11386             {
11387                 if (InvokeRequired && !IsDisposed)
11388                 {
11389                     await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11390                     return;
11391                 }
11392             }
11393             catch (ObjectDisposedException)
11394             {
11395                 return;
11396             }
11397             catch (InvalidOperationException)
11398             {
11399                 return;
11400             }
11401
11402             this.RefreshUserStreamsMenu();
11403             this.MenuItemUserStream.Enabled = true;
11404
11405             StatusLabel.Text = "UserStream Stopped.";
11406         }
11407
11408         private void RefreshUserStreamsMenu()
11409         {
11410             if (this.tw.UserStreamActive)
11411             {
11412                 this.MenuItemUserStream.Text = "&UserStream ▶";
11413                 this.StopToolStripMenuItem.Text = "&Stop";
11414             }
11415             else
11416             {
11417                 this.MenuItemUserStream.Text = "&UserStream ■";
11418                 this.StopToolStripMenuItem.Text = "&Start";
11419             }
11420         }
11421
11422         private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11423         {
11424             try
11425             {
11426                 if (InvokeRequired && !IsDisposed)
11427                 {
11428                     await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11429                     return;
11430                 }
11431             }
11432             catch (ObjectDisposedException)
11433             {
11434                 return;
11435             }
11436             catch (InvalidOperationException)
11437             {
11438                 return;
11439             }
11440             var ev = e.EventData;
11441             StatusLabel.Text = "Event: " + ev.Event;
11442             //if (ev.Event == "favorite")
11443             //{
11444             //    NotifyFavorite(ev);
11445             //}
11446             NotifyEvent(ev);
11447             if (ev.Event == "favorite" || ev.Event == "unfavorite")
11448             {
11449                 if (this.CurrentTab.Contains(ev.Id))
11450                 {
11451                     this.PurgeListViewItemCache();
11452                     this.CurrentListView.Update();
11453                 }
11454                 if (ev.Event == "unfavorite" && ev.Username.Equals(tw.Username, StringComparison.InvariantCultureIgnoreCase))
11455                 {
11456                     var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11457                     favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11458                 }
11459             }
11460         }
11461
11462         private void NotifyEvent(Twitter.FormattedEvent ev)
11463         {
11464             //新着通知 
11465             if (BalloonRequired(ev))
11466             {
11467                 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11468                 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11469                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11470                 StringBuilder title = new StringBuilder();
11471                 if (SettingManager.Common.DispUsername)
11472                 {
11473                     title.Append(tw.Username);
11474                     title.Append(" - ");
11475                 }
11476                 else
11477                 {
11478                     //title.Clear();
11479                 }
11480                 title.Append(ApplicationSettings.ApplicationName);
11481                 title.Append(" [");
11482                 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11483                 title.Append("] by ");
11484                 if (!string.IsNullOrEmpty(ev.Username))
11485                 {
11486                     title.Append(ev.Username);
11487                 }
11488                 else
11489                 {
11490                     //title.Append("");
11491                 }
11492                 string text;
11493                 if (!string.IsNullOrEmpty(ev.Target))
11494                 {
11495                     //NotifyIcon1.BalloonTipText = ev.Target;
11496                     text = ev.Target;
11497                 }
11498                 else
11499                 {
11500                     //NotifyIcon1.BalloonTipText = " ";
11501                     text = " ";
11502                 }
11503                 //NotifyIcon1.ShowBalloonTip(500);
11504                 if (SettingManager.Common.IsUseNotifyGrowl)
11505                 {
11506                     gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11507                               ev.Id.ToString(), title.ToString(), text);
11508                 }
11509                 else
11510                 {
11511                     NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11512                     NotifyIcon1.BalloonTipTitle = title.ToString();
11513                     NotifyIcon1.BalloonTipText = text;
11514                     NotifyIcon1.ShowBalloonTip(500);
11515                 }
11516             }
11517
11518             //サウンド再生
11519             string snd = SettingManager.Common.EventSoundFile;
11520             if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11521             {
11522                 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11523                 {
11524                     try
11525                     {
11526                         string dir = Application.StartupPath;
11527                         if (Directory.Exists(Path.Combine(dir, "Sounds")))
11528                         {
11529                             dir = Path.Combine(dir, "Sounds");
11530                         }
11531                         using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11532                         {
11533                             player.Play();
11534                         }
11535                     }
11536                     catch (Exception)
11537                     {
11538                     }
11539                 }
11540             }
11541         }
11542
11543         private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11544         {
11545             MenuItemUserStream.Enabled = false;
11546             if (StopRefreshAllMenuItem.Checked)
11547             {
11548                 StopRefreshAllMenuItem.Checked = false;
11549                 return;
11550             }
11551             if (this.tw.UserStreamActive)
11552             {
11553                 tw.StopUserStream();
11554             }
11555             else
11556             {
11557                 tw.StartUserStream();
11558             }
11559         }
11560
11561         private static string inputTrack = "";
11562
11563         private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11564         {
11565             if (TrackToolStripMenuItem.Checked)
11566             {
11567                 using (InputTabName inputForm = new InputTabName())
11568                 {
11569                     inputForm.TabName = inputTrack;
11570                     inputForm.FormTitle = "Input track word";
11571                     inputForm.FormDescription = "Track word";
11572                     if (inputForm.ShowDialog() != DialogResult.OK)
11573                     {
11574                         TrackToolStripMenuItem.Checked = false;
11575                         return;
11576                     }
11577                     inputTrack = inputForm.TabName.Trim();
11578                 }
11579                 if (!inputTrack.Equals(tw.TrackWord))
11580                 {
11581                     tw.TrackWord = inputTrack;
11582                     this.ModifySettingCommon = true;
11583                     TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11584                     tw.ReconnectUserStream();
11585                 }
11586             }
11587             else
11588             {
11589                 tw.TrackWord = "";
11590                 tw.ReconnectUserStream();
11591             }
11592             this.ModifySettingCommon = true;
11593         }
11594
11595         private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11596         {
11597             tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11598             this.ModifySettingCommon = true;
11599             tw.ReconnectUserStream();
11600         }
11601
11602         private void EventViewerMenuItem_Click(object sender, EventArgs e)
11603         {
11604             if (evtDialog == null || evtDialog.IsDisposed)
11605             {
11606                 this.evtDialog = new EventViewerDialog
11607                 {
11608                     Owner = this,
11609                 };
11610
11611                 //親の中央に表示
11612                 this.evtDialog.Location = new Point
11613                 {
11614                     X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2),
11615                     Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2),
11616                 };
11617             }
11618             evtDialog.EventSource = tw.StoredEvent;
11619             if (!evtDialog.Visible)
11620             {
11621                 evtDialog.Show(this);
11622             }
11623             else
11624             {
11625                 evtDialog.Activate();
11626             }
11627             this.TopMost = SettingManager.Common.AlwaysTop;
11628         }
11629 #endregion
11630
11631         private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11632         {
11633             MyCommon._endingFlag = true;
11634             try
11635             {
11636                 this.Close();
11637                 Application.Restart();
11638             }
11639             catch (Exception)
11640             {
11641                 MessageBox.Show("Failed to restart. Please run " + ApplicationSettings.ApplicationName + " manually.");
11642             }
11643         }
11644
11645         private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11646             => await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11647
11648         private bool ExistCurrentPost
11649         {
11650             get
11651             {
11652                 var post = this.CurrentPost;
11653                 return post != null && !post.IsDeleted;
11654             }
11655         }
11656
11657         private async void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11658             => await this.ShowUserTimeline();
11659
11660         private string GetUserIdFromCurPostOrInput(string caption)
11661         {
11662             var id = this.CurrentPost?.ScreenName ?? "";
11663
11664             using (InputTabName inputName = new InputTabName())
11665             {
11666                 inputName.FormTitle = caption;
11667                 inputName.FormDescription = Properties.Resources.FRMessage1;
11668                 inputName.TabName = id;
11669                 if (inputName.ShowDialog() == DialogResult.OK &&
11670                     !string.IsNullOrEmpty(inputName.TabName.Trim()))
11671                 {
11672                     id = inputName.TabName.Trim();
11673                 }
11674                 else
11675                 {
11676                     id = "";
11677                 }
11678             }
11679             return id;
11680         }
11681
11682         private async void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11683         {
11684             string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11685             if (!string.IsNullOrEmpty(id))
11686             {
11687                 await this.AddNewTabForUserTimeline(id);
11688             }
11689         }
11690
11691         private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11692         {
11693             if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
11694         }
11695
11696         private async void SystemEvents_TimeChanged(object sender, EventArgs e)
11697         {
11698             var prevTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11699
11700             TimeZoneInfo.ClearCachedData();
11701
11702             var curTimeOffset = TimeZoneInfo.Local.BaseUtcOffset;
11703
11704             if (curTimeOffset != prevTimeOffset)
11705             {
11706                 // タイムゾーンの変更を反映
11707                 this.PurgeListViewItemCache();
11708                 this.CurrentListView.Refresh();
11709
11710                 await this.DispSelectedPost(forceupdate: true);
11711             }
11712         }
11713
11714         private void TimelineRefreshEnableChange(bool isEnable)
11715         {
11716             if (isEnable)
11717             {
11718                 tw.StartUserStream();
11719             }
11720             else
11721             {
11722                 tw.StopUserStream();
11723             }
11724             TimerTimeline.Enabled = isEnable;
11725         }
11726
11727         private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11728             => this.TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
11729
11730         private async Task OpenUserAppointUrl()
11731         {
11732             if (SettingManager.Common.UserAppointUrl != null)
11733             {
11734                 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
11735                 {
11736                     var post = this.CurrentPost;
11737                     if (post != null)
11738                     {
11739                         string xUrl = SettingManager.Common.UserAppointUrl;
11740                         xUrl = xUrl.Replace("{ID}", post.ScreenName);
11741
11742                         var statusId = post.RetweetedId ?? post.StatusId;
11743                         xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
11744
11745                         await this.OpenUriInBrowserAsync(xUrl);
11746                     }
11747                 }
11748                 else
11749                 {
11750                     await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
11751                 }
11752             }
11753         }
11754
11755         private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
11756             => await this.OpenUserAppointUrl();
11757
11758         private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
11759         {
11760             if (Form.ActiveForm == null)
11761             {
11762                 await this.InvokeAsync(() =>
11763                 {
11764                     this.Visible = true;
11765                     if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11766                     this.Activate();
11767                     this.BringToFront();
11768                     if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
11769                     {
11770                         if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
11771                     }
11772                     else
11773                     {
11774                         if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
11775                     }
11776                 });
11777             }
11778         }
11779
11780         private void ReplaceAppName()
11781         {
11782             MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
11783             AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
11784         }
11785
11786         private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
11787             => this.SplitContainer3.Panel2Collapsed = false;
11788
11789         private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
11790             => await this.OpenThumbnailPicture(e.Thumbnail);
11791
11792         private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
11793             => await this.OpenUriInBrowserAsync(e.ImageUrl);
11794
11795         private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
11796         {
11797             var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
11798
11799             await this.OpenUriInBrowserAsync(url);
11800         }
11801
11802         private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
11803             => await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
11804
11805         private void PostButton_KeyDown(object sender, KeyEventArgs e)
11806         {
11807             if (e.KeyCode == Keys.Space)
11808             {
11809                 this.JumpUnreadMenuItem_Click(null, null);
11810
11811                 e.SuppressKeyPress = true;
11812             }
11813         }
11814
11815         private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
11816         {
11817             this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
11818             this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
11819             this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
11820             this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
11821             this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
11822
11823             this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
11824         }
11825
11826         private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
11827             => this.ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
11828
11829         private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
11830             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
11831
11832         private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
11833             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
11834
11835         private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
11836             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
11837
11838         private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
11839             => this.ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
11840
11841         private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
11842         {
11843             if (SettingManager.Common.IconSize == iconSize) return;
11844
11845             var oldIconCol = _iconCol;
11846
11847             SettingManager.Common.IconSize = iconSize;
11848             ApplyListViewIconSize(iconSize);
11849
11850             if (_iconCol != oldIconCol)
11851             {
11852                 foreach (TabPage tp in ListTab.TabPages)
11853                 {
11854                     ResetColumns((DetailsListView)tp.Tag);
11855                 }
11856             }
11857
11858             this.CurrentListView.Refresh();
11859
11860             ModifySettingCommon = true;
11861         }
11862
11863         private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
11864         {
11865             var state = this.LockListSortOrderToolStripMenuItem.Checked;
11866             if (SettingManager.Common.SortOrderLock == state) return;
11867
11868             SettingManager.Common.SortOrderLock = state;
11869
11870             ModifySettingCommon = true;
11871         }
11872
11873         private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
11874         {
11875             if (!string.IsNullOrEmpty(e.StatusText))
11876             {
11877                 this.StatusLabelUrl.Text = e.StatusText;
11878             }
11879             else
11880             {
11881                 this.SetStatusLabelUrl();
11882             }
11883         }
11884     }
11885 }