OSDN Git Service

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