OSDN Git Service

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