OSDN Git Service

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