OSDN Git Service

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