OSDN Git Service

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