OSDN Git Service

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