OSDN Git Service

ウィンドウ上部の「その他機能」メニューに「投稿設定」を追加
[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             var header = "";
4761             var footer = "";
4762
4763             var hashtag = this.HashMgr.UseHash;
4764             if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
4765             {
4766                 if (HashMgr.IsHead)
4767                     header = HashMgr.UseHash + " ";
4768                 else
4769                     footer = " " + HashMgr.UseHash;
4770             }
4771
4772             if (!disableFooter)
4773             {
4774                 if (SettingManager.Local.UseRecommendStatus)
4775                 {
4776                     // 推奨ステータスを使用する
4777                     footer += this.recommendedStatusFooter;
4778                 }
4779                 else if (!string.IsNullOrEmpty(SettingManager.Local.StatusText))
4780                 {
4781                     // テキストボックスに入力されている文字列を使用する
4782                     footer += " " + SettingManager.Local.StatusText.Trim();
4783                 }
4784             }
4785
4786             statusText = header + statusText + footer;
4787
4788             if (this.preventSmsCommand)
4789             {
4790                 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
4791                 // 参照: https://support.twitter.com/articles/14020
4792
4793                 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
4794                     && !Twitter.DMSendTextRegex.IsMatch(statusText))
4795                 {
4796                     // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
4797                     statusText = '\u200b' + statusText;
4798                 }
4799             }
4800
4801             return statusText;
4802         }
4803
4804         /// <summary>
4805         /// 投稿欄に表示する入力可能な文字数を計算します
4806         /// </summary>
4807         private int GetRestStatusCount(string statusText)
4808         {
4809             //文字数カウント
4810             var remainCount = this.tw.GetTextLengthRemain(statusText);
4811
4812             var uploadService = this.ImageSelector.SelectedService;
4813             if (this.ImageSelector.Visible && uploadService != null)
4814             {
4815                 // TODO: ImageSelector で選択中の画像の枚数が mediaCount 引数に渡るようにする
4816                 remainCount -= uploadService.GetReservedTextLength(1);
4817             }
4818
4819             return remainCount;
4820         }
4821
4822         private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
4823         {
4824             if (sender != this._curList)
4825                 return;
4826
4827             var listCache = this._listItemCache;
4828             if (listCache?.TargetList == sender && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
4829             {
4830                 // If the newly requested cache is a subset of the old cache,
4831                 // no need to rebuild everything, so do nothing.
4832                 return;
4833             }
4834
4835             // Now we need to rebuild the cache.
4836             this.CreateCache(e.StartIndex, e.EndIndex);
4837         }
4838
4839         private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
4840         {
4841             var listCache = this._listItemCache;
4842             if (listCache?.TargetList == sender)
4843             {
4844                 if (listCache.TryGetValue(e.ItemIndex, out var item, out var cacheItemPost))
4845                 {
4846                     e.Item = item;
4847                     return;
4848                 }
4849             }
4850
4851             // A cache miss, so create a new ListViewItem and pass it back.
4852             TabPage tb = (TabPage)((DetailsListView)sender).Parent;
4853             try
4854             {
4855                 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
4856             }
4857             catch (Exception)
4858             {
4859                 // 不正な要求に対する間に合わせの応答
4860                 string[] sitem = {"", "", "", "", "", "", "", ""};
4861                 e.Item = new ImageListViewItem(sitem);
4862             }
4863         }
4864
4865         private void CreateCache(int startIndex, int endIndex)
4866         {
4867             var tabInfo = this._statuses.Tabs[this._curTab.Text];
4868
4869             if (tabInfo.AllCount == 0)
4870                 return;
4871
4872             // インデックスを 0...(tabInfo.AllCount - 1) の範囲内にする
4873             int FilterRange(int index)
4874                 => Math.Max(Math.Min(index, tabInfo.AllCount - 1), 0);
4875
4876             // キャッシュ要求(要求範囲±30を作成)
4877             startIndex = FilterRange(startIndex - 30);
4878             endIndex = FilterRange(endIndex + 30);
4879
4880             var cacheLength = endIndex - startIndex + 1;
4881
4882             var posts = tabInfo[startIndex, endIndex]; //配列で取得
4883             var listItems = Enumerable.Range(0, cacheLength)
4884                 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
4885                 .ToArray();
4886
4887             var listCache = new ListViewItemCache
4888             {
4889                 TargetList = this._curList,
4890                 StartIndex = startIndex,
4891                 EndIndex = endIndex,
4892                 Post = posts,
4893                 ListItem = listItems,
4894             };
4895
4896             Interlocked.Exchange(ref this._listItemCache, listCache);
4897         }
4898
4899         /// <summary>
4900         /// DetailsListView のための ListViewItem のキャッシュを消去する
4901         /// </summary>
4902         private void PurgeListViewItemCache()
4903         {
4904             Interlocked.Exchange(ref this._listItemCache, null);
4905         }
4906
4907         private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
4908         {
4909             StringBuilder mk = new StringBuilder();
4910             //if (Post.IsDeleted) mk.Append("×");
4911             //if (Post.IsMark) mk.Append("♪");
4912             //if (Post.IsProtect) mk.Append("Ю");
4913             //if (Post.InReplyToStatusId != null) mk.Append("⇒");
4914             if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount);
4915             ImageListViewItem itm;
4916             if (Post.RetweetedId == null)
4917             {
4918                 string[] sitem= {"",
4919                                  Post.Nickname,
4920                                  Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4921                                  Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4922                                  Post.ScreenName,
4923                                  "",
4924                                  mk.ToString(),
4925                                  Post.Source};
4926                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4927             }
4928             else
4929             {
4930                 string[] sitem = {"",
4931                                   Post.Nickname,
4932                                   Post.IsDeleted ? "(DELETED)" : Post.AccessibleText.Replace('\n', ' '),
4933                                   Post.CreatedAt.ToString(SettingManager.Common.DateTimeFormat),
4934                                   Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
4935                                   "",
4936                                   mk.ToString(),
4937                                   Post.Source};
4938                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
4939             }
4940             itm.StateIndex = Post.StateIndex;
4941             itm.Tag = Post;
4942
4943             bool read = Post.IsRead;
4944             //未読管理していなかったら既読として扱う
4945             if (!_statuses.Tabs[Tab.Text].UnreadManage || !SettingManager.Common.UnreadManage) read = true;
4946             ChangeItemStyleRead(read, itm, Post, null);
4947             if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
4948             return itm;
4949         }
4950
4951         /// <summary>
4952         /// 全てのタブの振り分けルールを反映し直します
4953         /// </summary>
4954         private void ApplyPostFilters()
4955         {
4956             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
4957             {
4958                 this.PurgeListViewItemCache();
4959                 this._curPost = null;
4960                 this._curItemIndex = -1;
4961                 this._statuses.FilterAll();
4962
4963                 foreach (TabPage tabPage in this.ListTab.TabPages)
4964                 {
4965                     var tab = this._statuses.Tabs[tabPage.Text];
4966
4967                     var listview = (DetailsListView)tabPage.Tag;
4968                     using (ControlTransaction.Update(listview))
4969                     {
4970                         listview.VirtualListSize = tab.AllCount;
4971                     }
4972
4973                     if (SettingManager.Common.TabIconDisp)
4974                     {
4975                         if (tab.UnreadCount > 0)
4976                             tabPage.ImageIndex = 0;
4977                         else
4978                             tabPage.ImageIndex = -1;
4979                     }
4980                 }
4981
4982                 if (!SettingManager.Common.TabIconDisp)
4983                     this.ListTab.Refresh();
4984
4985                 SetMainWindowTitle();
4986                 SetStatusLabelUrl();
4987             }
4988         }
4989
4990         private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
4991         {
4992             e.DrawDefault = true;
4993         }
4994
4995         private void MyList_HScrolled(object sender, EventArgs e)
4996         {
4997             DetailsListView listView = (DetailsListView)sender;
4998             listView.Refresh();
4999         }
5000
5001         private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5002         {
5003             if (e.State == 0) return;
5004             e.DrawDefault = false;
5005
5006             SolidBrush brs2 = null;
5007             if (!e.Item.Selected)     //e.ItemStateでうまく判定できない???
5008             {
5009                 if (e.Item.BackColor == _clSelf)
5010                     brs2 = _brsBackColorMine;
5011                 else if (e.Item.BackColor == _clAtSelf)
5012                     brs2 = _brsBackColorAt;
5013                 else if (e.Item.BackColor == _clTarget)
5014                     brs2 = _brsBackColorYou;
5015                 else if (e.Item.BackColor == _clAtTarget)
5016                     brs2 = _brsBackColorAtYou;
5017                 else if (e.Item.BackColor == _clAtFromTarget)
5018                     brs2 = _brsBackColorAtFromTarget;
5019                 else if (e.Item.BackColor == _clAtTo)
5020                     brs2 = _brsBackColorAtTo;
5021                 else
5022                     brs2 = _brsBackColorNone;
5023             }
5024             else
5025             {
5026                 //選択中の行
5027                 if (((Control)sender).Focused)
5028                     brs2 = _brsHighLight;
5029                 else
5030                     brs2 = _brsDeactiveSelection;
5031             }
5032             e.Graphics.FillRectangle(brs2, e.Bounds);
5033             e.DrawFocusRectangle();
5034             this.DrawListViewItemIcon(e);
5035         }
5036
5037         private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5038         {
5039             if (e.ItemState == 0) return;
5040
5041             if (e.ColumnIndex > 0)
5042             {
5043                 //アイコン以外の列
5044                 var post = (PostClass)e.Item.Tag;
5045
5046                 RectangleF rct = e.Bounds;
5047                 rct.Width = e.Header.Width;
5048                 int fontHeight = e.Item.Font.Height;
5049                 if (_iconCol)
5050                 {
5051                     rct.Y += fontHeight;
5052                     rct.Height -= fontHeight;
5053                 }
5054
5055                 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out var heightDiff));
5056
5057                 //if (heightDiff > fontHeight * 0.7)
5058                 //{
5059                 //    rct.Height += fontHeight;
5060                 //    drawLineCount += 1;
5061                 //}
5062
5063                 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5064                 if (!_iconCol && drawLineCount <= 1)
5065                 {
5066                     //rct.Inflate(0, heightDiff / -2);
5067                     //rct.Height += fontHeight / 2;
5068                 }
5069                 else if (heightDiff < fontHeight * 0.7)
5070                 {
5071                     //最終行が70%以上欠けていたら、最終行は表示しない
5072                     //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5073                     rct.Height = (fontHeight * drawLineCount) - 1;
5074                 }
5075                 else
5076                 {
5077                     drawLineCount += 1;
5078                 }
5079
5080                 //if (!_iconCol && drawLineCount > 1)
5081                 //{
5082                 //    rct.Y += fontHeight * 0.2;
5083                 //    if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5084                 //}
5085
5086                 if (rct.Width > 0)
5087                 {
5088                     Color color = (!e.Item.Selected) ? e.Item.ForeColor :   //選択されていない行
5089                         (((Control)sender).Focused) ? _clHighLight :        //選択中の行
5090                         _clUnread;
5091
5092                     if (_iconCol)
5093                     {
5094                         Rectangle rctB = e.Bounds;
5095                         rctB.Width = e.Header.Width;
5096                         rctB.Height = fontHeight;
5097
5098                         using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5099                         {
5100                             TextRenderer.DrawText(e.Graphics,
5101                                                     post.IsDeleted ? "(DELETED)" : post.TextSingleLine,
5102                                                     e.Item.Font,
5103                                                     Rectangle.Round(rct),
5104                                                     color,
5105                                                     TextFormatFlags.WordBreak |
5106                                                     TextFormatFlags.EndEllipsis |
5107                                                     TextFormatFlags.GlyphOverhangPadding |
5108                                                     TextFormatFlags.NoPrefix);
5109                             TextRenderer.DrawText(e.Graphics,
5110                                                     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 + "]",
5111                                                     fnt,
5112                                                     rctB,
5113                                                     color,
5114                                                     TextFormatFlags.SingleLine |
5115                                                     TextFormatFlags.EndEllipsis |
5116                                                     TextFormatFlags.GlyphOverhangPadding |
5117                                                     TextFormatFlags.NoPrefix);
5118                         }
5119                     }
5120                     else
5121                     {
5122                         string text;
5123                         if (e.ColumnIndex != 2)
5124                             text = e.SubItem.Text;
5125                         else
5126                             text = post.IsDeleted ? "(DELETED)" : post.TextSingleLine;
5127
5128                         if (drawLineCount == 1)
5129                         {
5130                             TextRenderer.DrawText(e.Graphics,
5131                                                     text,
5132                                                     e.Item.Font,
5133                                                     Rectangle.Round(rct),
5134                                                     color,
5135                                                     TextFormatFlags.SingleLine |
5136                                                     TextFormatFlags.EndEllipsis |
5137                                                     TextFormatFlags.GlyphOverhangPadding |
5138                                                     TextFormatFlags.NoPrefix |
5139                                                     TextFormatFlags.VerticalCenter);
5140                         }
5141                         else
5142                         {
5143                             TextRenderer.DrawText(e.Graphics,
5144                                                     text,
5145                                                     e.Item.Font,
5146                                                     Rectangle.Round(rct),
5147                                                     color,
5148                                                     TextFormatFlags.WordBreak |
5149                                                     TextFormatFlags.EndEllipsis |
5150                                                     TextFormatFlags.GlyphOverhangPadding |
5151                                                     TextFormatFlags.NoPrefix);
5152                         }
5153                     }
5154                     //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5155                 }
5156             }
5157         }
5158
5159         private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5160         {
5161             if (_iconSz == 0) return;
5162
5163             ImageListViewItem item = (ImageListViewItem)e.Item;
5164
5165             //e.Bounds.Leftが常に0を指すから自前で計算
5166             Rectangle itemRect = item.Bounds;
5167             var col0 = e.Item.ListView.Columns[0];
5168             itemRect.Width = col0.Width;
5169
5170             if (col0.DisplayIndex > 0)
5171             {
5172                 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5173                 {
5174                     if (clm.DisplayIndex < col0.DisplayIndex)
5175                         itemRect.X += clm.Width;
5176                 }
5177             }
5178
5179             // ディスプレイの DPI 設定を考慮したアイコンサイズ
5180             var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5181             var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5182
5183             Rectangle iconRect;
5184             var img = item.Image;
5185             if (img != null)
5186             {
5187                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5188                 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5189
5190                 if (iconRect.Width > 0)
5191                 {
5192                     e.Graphics.FillRectangle(Brushes.White, iconRect);
5193                     e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5194                     try
5195                     {
5196                         e.Graphics.DrawImage(img.Image, iconRect);
5197                     }
5198                     catch (ArgumentException)
5199                     {
5200                         item.RefreshImageAsync();
5201                     }
5202                 }
5203             }
5204             else
5205             {
5206                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5207                 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5208
5209                 item.GetImageAsync();
5210             }
5211
5212             if (item.StateIndex > -1)
5213             {
5214                 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5215                 if (stateRect.Width > 0)
5216                 {
5217                     //e.Graphics.FillRectangle(Brushes.White, stateRect);
5218                     //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5219                     e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5220                 }
5221             }
5222         }
5223
5224         protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5225         {
5226             base.ScaleControl(factor, specified);
5227
5228             ScaleChildControl(this.TabImage, factor);
5229
5230             var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5231             var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5232
5233             foreach (var listview in listviews)
5234             {
5235                 ScaleChildControl(listview, factor);
5236             }
5237         }
5238
5239         //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5240         //{
5241         //    ImageListViewItem item = (ImageListViewItem)e.Item;
5242         //    if (item.StateImageIndex > -1)
5243         //    {
5244         //        ////e.Bounds.Leftが常に0を指すから自前で計算
5245         //        //Rectangle itemRect = item.Bounds;
5246         //        //itemRect.Width = e.Item.ListView.Columns[4].Width;
5247
5248         //        //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5249         //        //{
5250         //        //    if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5251         //        //    {
5252         //        //        itemRect.X += clm.Width;
5253         //        //    }
5254         //        //}
5255
5256         //        //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5257         //        //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5258
5259         //        if (rct.Width > 0)
5260         //        {
5261         //            RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5262         //            //e.Graphics.FillRectangle(Brushes.White, rct);
5263         //            //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5264         //            e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5265         //        }
5266         //    }
5267         //}
5268
5269         internal void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5270         {
5271             var tab = this._statuses.Tabs[this._curTab.Text];
5272
5273             if (tab.AllCount == 0)
5274             {
5275                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5276                 return;
5277             }
5278
5279             var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5280
5281             int startIndex;
5282             switch (searchType)
5283             {
5284                 case SEARCHTYPE.NextSearch: // 次を検索
5285                     if (selectedIndex != -1)
5286                         startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5287                     else
5288                         startIndex = 0;
5289                     break;
5290                 case SEARCHTYPE.PrevSearch: // 前を検索
5291                     if (selectedIndex != -1)
5292                         startIndex = Math.Max(selectedIndex - 1, 0);
5293                     else
5294                         startIndex = tab.AllCount - 1;
5295                     break;
5296                 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5297                 default:
5298                     if (selectedIndex != -1)
5299                         startIndex = selectedIndex;
5300                     else
5301                         startIndex = 0;
5302                     break;
5303             }
5304
5305             Func<string, bool> stringComparer;
5306             try
5307             {
5308                 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5309             }
5310             catch (ArgumentException)
5311             {
5312                 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5313                 return;
5314             }
5315
5316             var reverse = searchType == SEARCHTYPE.PrevSearch;
5317             var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5318                 .DefaultIfEmpty(-1).First();
5319
5320             if (foundIndex == -1)
5321             {
5322                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5323                 return;
5324             }
5325
5326             this.SelectListItem(this._curList, foundIndex);
5327             this._curList.EnsureVisible(foundIndex);
5328         }
5329
5330         private void MenuItemSubSearch_Click(object sender, EventArgs e)
5331         {
5332             // 検索メニュー
5333             this.ShowSearchDialog();
5334         }
5335
5336         private void MenuItemSearchNext_Click(object sender, EventArgs e)
5337         {
5338             var previousSearch = this.SearchDialog.ResultOptions;
5339             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5340             {
5341                 this.SearchDialog.Reset();
5342                 this.ShowSearchDialog();
5343                 return;
5344             }
5345
5346             // 次を検索
5347             this.DoTabSearch(
5348                 previousSearch.Query,
5349                 previousSearch.CaseSensitive,
5350                 previousSearch.UseRegex,
5351                 SEARCHTYPE.NextSearch);
5352         }
5353
5354         private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5355         {
5356             var previousSearch = this.SearchDialog.ResultOptions;
5357             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5358             {
5359                 this.SearchDialog.Reset();
5360                 this.ShowSearchDialog();
5361                 return;
5362             }
5363
5364             // 前を検索
5365             this.DoTabSearch(
5366                 previousSearch.Query,
5367                 previousSearch.CaseSensitive,
5368                 previousSearch.UseRegex,
5369                 SEARCHTYPE.PrevSearch);
5370         }
5371
5372         /// <summary>
5373         /// 検索ダイアログを表示し、検索を実行します
5374         /// </summary>
5375         private void ShowSearchDialog()
5376         {
5377             if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5378             {
5379                 this.TopMost = SettingManager.Common.AlwaysTop;
5380                 return;
5381             }
5382             this.TopMost = SettingManager.Common.AlwaysTop;
5383
5384             var searchOptions = this.SearchDialog.ResultOptions;
5385             if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5386             {
5387                 if (searchOptions.NewTab)
5388                 {
5389                     var tabName = Properties.Resources.SearchResults_TabName;
5390
5391                     try
5392                     {
5393                         tabName = this._statuses.MakeTabName(tabName);
5394                     }
5395                     catch (TabException ex)
5396                     {
5397                         MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5398                     }
5399
5400                     var resultTab = new LocalSearchTabModel(tabName);
5401                     this.AddNewTab(resultTab, startup: false);
5402                     this._statuses.AddTab(resultTab);
5403
5404                     var targetTab = this._statuses.Tabs[this._curTab.Text];
5405
5406                     Func<string, bool> stringComparer;
5407                     try
5408                     {
5409                         stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5410                     }
5411                     catch (ArgumentException)
5412                     {
5413                         MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5414                         return;
5415                     }
5416
5417                     var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5418                     if (foundIndices.Length == 0)
5419                     {
5420                         MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5421                         return;
5422                     }
5423
5424                     var foundPosts = foundIndices.Select(x => targetTab[x]);
5425                     foreach (var post in foundPosts)
5426                     {
5427                         resultTab.AddPostQueue(post);
5428                     }
5429
5430                     this._statuses.DistributePosts();
5431                     this.RefreshTimeline();
5432
5433                     var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5434                         .First(x => x.Text == tabName);
5435
5436                     this.ListTab.SelectedTab = tabPage;
5437                 }
5438                 else
5439                 {
5440                     this.DoTabSearch(
5441                         searchOptions.Query,
5442                         searchOptions.CaseSensitive,
5443                         searchOptions.UseRegex,
5444                         SEARCHTYPE.DialogSearch);
5445                 }
5446             }
5447             else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5448             {
5449                 this.AddNewTabForSearch(searchOptions.Query);
5450             }
5451         }
5452
5453         /// <summary>発言検索に使用するメソッドを生成します</summary>
5454         /// <exception cref="ArgumentException">
5455         /// <paramref name="useRegex"/> が true かつ、<paramref name="query"/> が不正な正規表現な場合
5456         /// </exception>
5457         private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5458         {
5459             if (useRegex)
5460             {
5461                 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5462                 var regex = new Regex(query, regexOption);
5463
5464                 return x => regex.IsMatch(x);
5465             }
5466             else
5467             {
5468                 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5469
5470                 return x => x.IndexOf(query, comparisonType) != -1;
5471             }
5472         }
5473
5474         private void AboutMenuItem_Click(object sender, EventArgs e)
5475         {
5476             using (TweenAboutBox about = new TweenAboutBox())
5477             {
5478                 about.ShowDialog(this);
5479             }
5480             this.TopMost = SettingManager.Common.AlwaysTop;
5481         }
5482
5483         private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5484         {
5485             int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5486
5487             if (ImageSelector.Enabled)
5488                 return;
5489
5490             TabModel foundTab = null;
5491             int foundIndex = 0;
5492
5493             DetailsListView lst = null;
5494
5495             //現在タブから最終タブまで探索
5496             for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5497             {
5498                 var tabPage = this.ListTab.TabPages[i];
5499                 var tab = this._statuses.Tabs[tabPage.Text];
5500                 var unreadIndex = tab.NextUnreadIndex;
5501
5502                 if (unreadIndex != -1)
5503                 {
5504                     ListTab.SelectedIndex = i;
5505                     foundTab = tab;
5506                     foundIndex = unreadIndex;
5507                     lst = (DetailsListView)tabPage.Tag;
5508                     break;
5509                 }
5510             }
5511
5512             //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5513             if (foundTab == null && bgnIdx > 0)
5514             {
5515                 for (int i = 0; i < bgnIdx; i++)
5516                 {
5517                     var tabPage = this.ListTab.TabPages[i];
5518                     var tab = this._statuses.Tabs[tabPage.Text];
5519                     var unreadIndex = tab.NextUnreadIndex;
5520
5521                     if (unreadIndex != -1)
5522                     {
5523                         ListTab.SelectedIndex = i;
5524                         foundTab = tab;
5525                         foundIndex = unreadIndex;
5526                         lst = (DetailsListView)tabPage.Tag;
5527                         break;
5528                     }
5529                 }
5530             }
5531
5532             if (foundTab == null)
5533             {
5534                 //全部調べたが未読見つからず→先頭タブの最新発言へ
5535                 ListTab.SelectedIndex = 0;
5536                 var tabPage = this.ListTab.TabPages[0];
5537                 var tab = this._statuses.Tabs[tabPage.Text];
5538
5539                 if (tab.AllCount == 0)
5540                     return;
5541
5542                 if (_statuses.SortOrder == SortOrder.Ascending)
5543                     foundIndex = tab.AllCount - 1;
5544                 else
5545                     foundIndex = 0;
5546
5547                 lst = (DetailsListView)tabPage.Tag;
5548             }
5549
5550             SelectListItem(lst, foundIndex);
5551
5552             if (_statuses.SortMode == ComparerMode.Id)
5553             {
5554                 if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[foundIndex].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5555                     _statuses.SortOrder == SortOrder.Descending && lst.Items[foundIndex].Position.Y < _iconSz + 10)
5556                 {
5557                     MoveTop();
5558                 }
5559                 else
5560                 {
5561                     lst.EnsureVisible(foundIndex);
5562                 }
5563             }
5564             else
5565             {
5566                 lst.EnsureVisible(foundIndex);
5567             }
5568
5569             lst.Focus();
5570         }
5571
5572         private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5573         {
5574             if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5575             {
5576                 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5577                 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5578             }
5579         }
5580
5581         private async void FavorareMenuItem_Click(object sender, EventArgs e)
5582         {
5583             if (_curList.SelectedIndices.Count > 0)
5584             {
5585                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5586                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5587             }
5588         }
5589
5590         private async void VerUpMenuItem_Click(object sender, EventArgs e)
5591         {
5592             await this.CheckNewVersion(false);
5593         }
5594
5595         private void RunTweenUp()
5596         {
5597             ProcessStartInfo pinfo = new ProcessStartInfo();
5598             pinfo.UseShellExecute = true;
5599             pinfo.WorkingDirectory = MyCommon.settingPath;
5600             pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5601             pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5602             try
5603             {
5604                 Process.Start(pinfo);
5605             }
5606             catch (Exception)
5607             {
5608                 MessageBox.Show("Failed to execute TweenUp3.exe.");
5609             }
5610         }
5611
5612         public class VersionInfo
5613         {
5614             public Version Version { get; set; }
5615             public Uri DownloadUri { get; set; }
5616             public string ReleaseNote { get; set; }
5617         }
5618
5619         /// <summary>
5620         /// OpenTween の最新バージョンの情報を取得します
5621         /// </summary>
5622         public async Task<VersionInfo> GetVersionInfoAsync()
5623         {
5624             var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
5625                 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
5626
5627             var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
5628                 .ConfigureAwait(false);
5629
5630             // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
5631             var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
5632
5633             var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
5634             var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
5635
5636             msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
5637
5638             return new VersionInfo
5639             {
5640                 Version = Version.Parse(msgHeader[0]),
5641                 DownloadUri = new Uri(msgHeader[1]),
5642                 ReleaseNote = msgBody,
5643             };
5644         }
5645
5646         private async Task CheckNewVersion(bool startup = false)
5647         {
5648             if (ApplicationSettings.VersionInfoUrl == null)
5649                 return; // 更新チェック無効化
5650
5651             try
5652             {
5653                 var versionInfo = await this.GetVersionInfoAsync();
5654
5655                 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
5656                 {
5657                     // 更新不要
5658                     if (!startup)
5659                     {
5660                         var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
5661                             MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
5662                         msgtext = MyCommon.ReplaceAppName(msgtext);
5663
5664                         MessageBox.Show(msgtext,
5665                             MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5666                             MessageBoxButtons.OK, MessageBoxIcon.Information);
5667                     }
5668                     return;
5669                 }
5670
5671                 using (var dialog = new UpdateDialog())
5672                 {
5673                     dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
5674                         MyCommon.GetReadableVersion(versionInfo.Version));
5675                     dialog.DetailsText = versionInfo.ReleaseNote;
5676
5677                     if (dialog.ShowDialog(this) == DialogResult.Yes)
5678                     {
5679                         await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
5680                     }
5681                 }
5682             }
5683             catch (Exception)
5684             {
5685                 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
5686                 if (!startup)
5687                 {
5688                     MessageBox.Show(Properties.Resources.CheckNewVersionText10,
5689                         MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
5690                         MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
5691                 }
5692             }
5693         }
5694
5695         private async Task Colorize()
5696         {
5697             _colorize = false;
5698             await this.DispSelectedPost();
5699             //件数関連の場合、タイトル即時書き換え
5700             if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
5701                SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
5702                SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
5703                SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
5704             {
5705                 SetMainWindowTitle();
5706             }
5707             if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase))
5708                 SetStatusLabelUrl();
5709             foreach (TabPage tb in ListTab.TabPages)
5710             {
5711                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
5712                 {
5713                     if (SettingManager.Common.TabIconDisp)
5714                     {
5715                         if (tb.ImageIndex == 0) tb.ImageIndex = -1;
5716                     }
5717                 }
5718             }
5719             if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
5720         }
5721
5722         public string createDetailHtml(string orgdata)
5723         {
5724             if (SettingManager.Local.UseTwemoji)
5725                 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
5726
5727             return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
5728         }
5729
5730         private Task DispSelectedPost()
5731         {
5732             return this.DispSelectedPost(false);
5733         }
5734
5735         private PostClass displayPost = new PostClass();
5736
5737         /// <summary>
5738         /// サムネイル表示に使用する CancellationToken の生成元
5739         /// </summary>
5740         private CancellationTokenSource thumbnailTokenSource = null;
5741
5742         private async Task DispSelectedPost(bool forceupdate)
5743         {
5744             if (_curList.SelectedIndices.Count == 0 || _curPost == null)
5745                 return;
5746
5747             var oldDisplayPost = this.displayPost;
5748             this.displayPost = this._curPost;
5749
5750             if (!forceupdate && this._curPost.Equals(oldDisplayPost))
5751                 return;
5752
5753             var loadTasks = new List<Task>
5754             {
5755                 this.tweetDetailsView.ShowPostDetails(this._curPost),
5756             };
5757
5758             this.SplitContainer3.Panel2Collapsed = true;
5759
5760             if (SettingManager.Common.PreviewEnable)
5761             {
5762                 var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
5763                 oldTokenSource?.Cancel();
5764
5765                 var token = this.thumbnailTokenSource.Token;
5766                 loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
5767             }
5768
5769             try
5770             {
5771                 await Task.WhenAll(loadTasks);
5772             }
5773             catch (OperationCanceledException) { }
5774         }
5775
5776         private async void MatomeMenuItem_Click(object sender, EventArgs e)
5777         {
5778             await this.OpenApplicationWebsite();
5779         }
5780
5781         private async Task OpenApplicationWebsite()
5782         {
5783             await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
5784         }
5785
5786         private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
5787         {
5788             await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
5789         }
5790
5791         private async void ListTab_KeyDown(object sender, KeyEventArgs e)
5792         {
5793             if (ListTab.SelectedTab != null)
5794             {
5795                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
5796                 {
5797                     Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
5798                     if (pnl.Controls["comboSearch"].Focused ||
5799                         pnl.Controls["comboLang"].Focused ||
5800                         pnl.Controls["buttonSearch"].Focused) return;
5801                 }
5802
5803                 if (e.Control || e.Shift || e.Alt)
5804                     this._anchorFlag = false;
5805
5806                 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out var asyncTask))
5807                 {
5808                     e.Handled = true;
5809                     e.SuppressKeyPress = true;
5810                 }
5811
5812                 if (asyncTask != null)
5813                     await asyncTask;
5814             }
5815         }
5816
5817         private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
5818
5819         private void InitializeShortcuts()
5820         {
5821             this.shortcutCommands = new[]
5822             {
5823                 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
5824                 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
5825                     .FocusedOn(FocusedControl.ListTab)
5826                     .Do(() => SendKeys.Send("{DOWN}")),
5827
5828                 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
5829                     .FocusedOn(FocusedControl.ListTab)
5830                     .Do(() => SendKeys.Send("{UP}")),
5831
5832                 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
5833                     .FocusedOn(FocusedControl.ListTab)
5834                     .Do(() => SendKeys.Send("{PGDN}")),
5835
5836                 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
5837                     .FocusedOn(FocusedControl.ListTab)
5838                     .Do(() => SendKeys.Send("{PGUP}")),
5839
5840                 ShortcutCommand.Create(Keys.F1)
5841                     .Do(() => this.OpenApplicationWebsite()),
5842
5843                 ShortcutCommand.Create(Keys.F3)
5844                     .Do(() => this.MenuItemSearchNext_Click(null, null)),
5845
5846                 ShortcutCommand.Create(Keys.F5)
5847                     .Do(() => this.DoRefresh()),
5848
5849                 ShortcutCommand.Create(Keys.F6)
5850                     .Do(() => this.GetReplyAsync()),
5851
5852                 ShortcutCommand.Create(Keys.F7)
5853                     .Do(() => this.GetDirectMessagesAsync()),
5854
5855                 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
5856                     .NotFocusedOn(FocusedControl.StatusText)
5857                     .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
5858
5859                 ShortcutCommand.Create(Keys.G)
5860                     .NotFocusedOn(FocusedControl.StatusText)
5861                     .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
5862
5863                 ShortcutCommand.Create(Keys.Right, Keys.N)
5864                     .FocusedOn(FocusedControl.ListTab)
5865                     .Do(() => this.GoRelPost(forward: true)),
5866
5867                 ShortcutCommand.Create(Keys.Left, Keys.P)
5868                     .FocusedOn(FocusedControl.ListTab)
5869                     .Do(() => this.GoRelPost(forward: false)),
5870
5871                 ShortcutCommand.Create(Keys.OemPeriod)
5872                     .FocusedOn(FocusedControl.ListTab)
5873                     .Do(() => this.GoAnchor()),
5874
5875                 ShortcutCommand.Create(Keys.I)
5876                     .FocusedOn(FocusedControl.ListTab)
5877                     .OnlyWhen(() => this.StatusText.Enabled)
5878                     .Do(() => this.StatusText.Focus()),
5879
5880                 ShortcutCommand.Create(Keys.Enter)
5881                     .FocusedOn(FocusedControl.ListTab)
5882                     .Do(() => this.MakeReplyOrDirectStatus()),
5883
5884                 ShortcutCommand.Create(Keys.R)
5885                     .FocusedOn(FocusedControl.ListTab)
5886                     .Do(() => this.DoRefresh()),
5887
5888                 ShortcutCommand.Create(Keys.L)
5889                     .FocusedOn(FocusedControl.ListTab)
5890                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
5891
5892                 ShortcutCommand.Create(Keys.H)
5893                     .FocusedOn(FocusedControl.ListTab)
5894                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
5895
5896                 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
5897                     .FocusedOn(FocusedControl.ListTab)
5898                     .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
5899
5900                 ShortcutCommand.Create(Keys.S)
5901                     .FocusedOn(FocusedControl.ListTab)
5902                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
5903
5904                 ShortcutCommand.Create(Keys.A)
5905                     .FocusedOn(FocusedControl.ListTab)
5906                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
5907
5908                 // ] in_reply_to参照元へ戻る
5909                 ShortcutCommand.Create(Keys.Oem4)
5910                     .FocusedOn(FocusedControl.ListTab)
5911                     .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
5912
5913                 // [ in_reply_toへジャンプ
5914                 ShortcutCommand.Create(Keys.Oem6)
5915                     .FocusedOn(FocusedControl.ListTab)
5916                     .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
5917
5918                 ShortcutCommand.Create(Keys.Escape)
5919                     .FocusedOn(FocusedControl.ListTab)
5920                     .Do(() => {
5921                         this._anchorFlag = false;
5922                         if (ListTab.SelectedTab != null)
5923                         {
5924                             var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
5925                             if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
5926                             {
5927                                 var relTp = ListTab.SelectedTab;
5928                                 RemoveSpecifiedTab(relTp.Text, false);
5929                                 SaveConfigsTabs();
5930                             }
5931                         }
5932                     }),
5933
5934                 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
5935                 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
5936                     .FocusedOn(FocusedControl.ListTab)
5937                     .Do(() => this._anchorFlag = false, preventDefault: false),
5938
5939                 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
5940                 ShortcutCommand.Create(Keys.Up, Keys.Down)
5941                     .FocusedOn(FocusedControl.PostBrowser)
5942                     .Do(() => { }),
5943
5944                 ShortcutCommand.Create(Keys.Control | Keys.R)
5945                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
5946
5947                 ShortcutCommand.Create(Keys.Control | Keys.D)
5948                     .Do(() => this.doStatusDelete()),
5949
5950                 ShortcutCommand.Create(Keys.Control | Keys.M)
5951                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
5952
5953                 ShortcutCommand.Create(Keys.Control | Keys.S)
5954                     .Do(() => this.FavoriteChange(FavAdd: true)),
5955
5956                 ShortcutCommand.Create(Keys.Control | Keys.I)
5957                     .Do(() => this.doRepliedStatusOpen()),
5958
5959                 ShortcutCommand.Create(Keys.Control | Keys.Q)
5960                     .Do(() => this.doQuoteOfficial()),
5961
5962                 ShortcutCommand.Create(Keys.Control | Keys.B)
5963                     .Do(() => this.ReadedStripMenuItem_Click(null, null)),
5964
5965                 ShortcutCommand.Create(Keys.Control | Keys.T)
5966                     .Do(() => this.HashManageMenuItem_Click(null, null)),
5967
5968                 ShortcutCommand.Create(Keys.Control | Keys.L)
5969                     .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
5970
5971                 ShortcutCommand.Create(Keys.Control | Keys.Y)
5972                     .NotFocusedOn(FocusedControl.PostBrowser)
5973                     .Do(() => this.MultiLineMenuItem_Click(null, null)),
5974
5975                 ShortcutCommand.Create(Keys.Control | Keys.F)
5976                     .Do(() => this.MenuItemSubSearch_Click(null, null)),
5977
5978                 ShortcutCommand.Create(Keys.Control | Keys.U)
5979                     .Do(() => this.ShowUserTimeline()),
5980
5981                 ShortcutCommand.Create(Keys.Control | Keys.H)
5982                     .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
5983
5984                 ShortcutCommand.Create(Keys.Control | Keys.G)
5985                     .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
5986
5987                 ShortcutCommand.Create(Keys.Control | Keys.O)
5988                     .Do(() => this.StatusOpenMenuItem_Click(null, null)),
5989
5990                 ShortcutCommand.Create(Keys.Control | Keys.E)
5991                     .Do(() => this.OpenURLMenuItem_Click(null, null)),
5992
5993                 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
5994                     .FocusedOn(FocusedControl.ListTab)
5995                     .Do(() => this._colorize = true, preventDefault: false),
5996
5997                 ShortcutCommand.Create(Keys.Control | Keys.N)
5998                     .FocusedOn(FocusedControl.ListTab)
5999                     .Do(() => this.GoNextTab(forward: true)),
6000
6001                 ShortcutCommand.Create(Keys.Control | Keys.P)
6002                     .FocusedOn(FocusedControl.ListTab)
6003                     .Do(() => this.GoNextTab(forward: false)),
6004
6005                 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6006                     .FocusedOn(FocusedControl.ListTab)
6007                     .Do(() => this.CopyStot()),
6008
6009                 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6010                 ShortcutCommand.Create(Keys.Control | Keys.D1)
6011                     .FocusedOn(FocusedControl.ListTab)
6012                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6013                     .Do(() => this.ListTab.SelectedIndex = 0),
6014
6015                 ShortcutCommand.Create(Keys.Control | Keys.D2)
6016                     .FocusedOn(FocusedControl.ListTab)
6017                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6018                     .Do(() => this.ListTab.SelectedIndex = 1),
6019
6020                 ShortcutCommand.Create(Keys.Control | Keys.D3)
6021                     .FocusedOn(FocusedControl.ListTab)
6022                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6023                     .Do(() => this.ListTab.SelectedIndex = 2),
6024
6025                 ShortcutCommand.Create(Keys.Control | Keys.D4)
6026                     .FocusedOn(FocusedControl.ListTab)
6027                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6028                     .Do(() => this.ListTab.SelectedIndex = 3),
6029
6030                 ShortcutCommand.Create(Keys.Control | Keys.D5)
6031                     .FocusedOn(FocusedControl.ListTab)
6032                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6033                     .Do(() => this.ListTab.SelectedIndex = 4),
6034
6035                 ShortcutCommand.Create(Keys.Control | Keys.D6)
6036                     .FocusedOn(FocusedControl.ListTab)
6037                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6038                     .Do(() => this.ListTab.SelectedIndex = 5),
6039
6040                 ShortcutCommand.Create(Keys.Control | Keys.D7)
6041                     .FocusedOn(FocusedControl.ListTab)
6042                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6043                     .Do(() => this.ListTab.SelectedIndex = 6),
6044
6045                 ShortcutCommand.Create(Keys.Control | Keys.D8)
6046                     .FocusedOn(FocusedControl.ListTab)
6047                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6048                     .Do(() => this.ListTab.SelectedIndex = 7),
6049
6050                 ShortcutCommand.Create(Keys.Control | Keys.D9)
6051                     .FocusedOn(FocusedControl.ListTab)
6052                     .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6053
6054                 ShortcutCommand.Create(Keys.Control | Keys.A)
6055                     .FocusedOn(FocusedControl.StatusText)
6056                     .Do(() => this.StatusText.SelectAll()),
6057
6058                 ShortcutCommand.Create(Keys.Control | Keys.V)
6059                     .FocusedOn(FocusedControl.StatusText)
6060                     .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6061
6062                 ShortcutCommand.Create(Keys.Control | Keys.Up)
6063                     .FocusedOn(FocusedControl.StatusText)
6064                     .Do(() => {
6065                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6066                         {
6067                             var inReplyToStatusId = this.inReplyTo?.Item1;
6068                             var inReplyToScreenName = this.inReplyTo?.Item2;
6069                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6070                         }
6071                         _hisIdx -= 1;
6072                         if (_hisIdx < 0) _hisIdx = 0;
6073
6074                         var historyItem = this._history[this._hisIdx];
6075                         StatusText.Text = historyItem.status;
6076                         StatusText.SelectionStart = StatusText.Text.Length;
6077                         if (historyItem.inReplyToId != null)
6078                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6079                         else
6080                             this.inReplyTo = null;
6081                     }),
6082
6083                 ShortcutCommand.Create(Keys.Control | Keys.Down)
6084                     .FocusedOn(FocusedControl.StatusText)
6085                     .Do(() => {
6086                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6087                         {
6088                             var inReplyToStatusId = this.inReplyTo?.Item1;
6089                             var inReplyToScreenName = this.inReplyTo?.Item2;
6090                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6091                         }
6092                         _hisIdx += 1;
6093                         if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6094
6095                         var historyItem = this._history[this._hisIdx];
6096                         StatusText.Text = historyItem.status;
6097                         StatusText.SelectionStart = StatusText.Text.Length;
6098                         if (historyItem.inReplyToId != null)
6099                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6100                         else
6101                             this.inReplyTo = null;
6102                     }),
6103
6104                 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6105                     .FocusedOn(FocusedControl.StatusText)
6106                     .Do(() => {
6107                         if (ListTab.SelectedIndex == 0)
6108                         {
6109                             ListTab.SelectedIndex = ListTab.TabCount - 1;
6110                         }
6111                         else
6112                         {
6113                             ListTab.SelectedIndex -= 1;
6114                         }
6115                         StatusText.Focus();
6116                     }),
6117
6118                 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6119                     .FocusedOn(FocusedControl.StatusText)
6120                     .Do(() => {
6121                         if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6122                         {
6123                             ListTab.SelectedIndex = 0;
6124                         }
6125                         else
6126                         {
6127                             ListTab.SelectedIndex += 1;
6128                         }
6129                         StatusText.Focus();
6130                     }),
6131
6132                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6133                     .FocusedOn(FocusedControl.PostBrowser)
6134                     .Do(() => {
6135                         var multiline = !SettingManager.Local.StatusMultiline;
6136                         SettingManager.Local.StatusMultiline = multiline;
6137                         MultiLineMenuItem.Checked = multiline;
6138                         MultiLineMenuItem_Click(this.MultiLineMenuItem, EventArgs.Empty);
6139                     }),
6140
6141                 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6142                     .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6143
6144                 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6145                     .Do(() => this.DoRefreshMore()),
6146
6147                 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6148                     .Do(() => this.GetReplyAsync(loadMore: true)),
6149
6150                 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6151                     .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6152
6153                 ShortcutCommand.Create(Keys.Shift | Keys.R)
6154                     .NotFocusedOn(FocusedControl.StatusText)
6155                     .Do(() => this.DoRefreshMore()),
6156
6157                 ShortcutCommand.Create(Keys.Shift | Keys.H)
6158                     .FocusedOn(FocusedControl.ListTab)
6159                     .Do(() => this.GoTopEnd(GoTop: true)),
6160
6161                 ShortcutCommand.Create(Keys.Shift | Keys.L)
6162                     .FocusedOn(FocusedControl.ListTab)
6163                     .Do(() => this.GoTopEnd(GoTop: false)),
6164
6165                 ShortcutCommand.Create(Keys.Shift | Keys.M)
6166                     .FocusedOn(FocusedControl.ListTab)
6167                     .Do(() => this.GoMiddle()),
6168
6169                 ShortcutCommand.Create(Keys.Shift | Keys.G)
6170                     .FocusedOn(FocusedControl.ListTab)
6171                     .Do(() => this.GoLast()),
6172
6173                 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6174                     .FocusedOn(FocusedControl.ListTab)
6175                     .Do(() => this.MoveMiddle()),
6176
6177                 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6178                     .FocusedOn(FocusedControl.ListTab)
6179                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6180
6181                 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6182                     .FocusedOn(FocusedControl.ListTab)
6183                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6184
6185                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6186                 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6187                     .FocusedOn(FocusedControl.ListTab)
6188                     .Do(() => this.GoFav(forward: true)),
6189
6190                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6191                 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6192                     .FocusedOn(FocusedControl.ListTab)
6193                     .Do(() => this.GoFav(forward: false)),
6194
6195                 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6196                     .FocusedOn(FocusedControl.ListTab)
6197                     .Do(() => this.GoBackSelectPostChain()),
6198
6199                 ShortcutCommand.Create(Keys.Alt | Keys.R)
6200                     .Do(() => this.doReTweetOfficial(isConfirm: true)),
6201
6202                 ShortcutCommand.Create(Keys.Alt | Keys.P)
6203                     .OnlyWhen(() => this._curPost != null)
6204                     .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6205
6206                 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6207                     .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: false)),
6208
6209                 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6210                     .Do(() => this.tweetDetailsView.ScrollDownPostBrowser(forward: true)),
6211
6212                 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6213                     .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: false)),
6214
6215                 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6216                     .Do(() => this.tweetDetailsView.PageDownPostBrowser(forward: true)),
6217
6218                 // 別タブの同じ書き込みへ(ALT+←/→)
6219                 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6220                     .FocusedOn(FocusedControl.ListTab)
6221                     .Do(() => this.GoSamePostToAnotherTab(left: false)),
6222
6223                 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6224                     .FocusedOn(FocusedControl.ListTab)
6225                     .Do(() => this.GoSamePostToAnotherTab(left: true)),
6226
6227                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6228                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6229
6230                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6231                     .Do(() => this.CopyIdUri()),
6232
6233                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6234                     .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6235                         this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6236                     .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6237
6238                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6239                     .Do(() => this.FavoriteChange(FavAdd: false)),
6240
6241                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6242                     .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6243
6244                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6245                     .Do(() => this.HashToggleMenuItem_Click(null, null)),
6246
6247                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6248                     .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6249
6250                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6251                     .Do(() => this.doMoveToRTHome()),
6252
6253                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6254                     .Do(() => this.FavorareMenuItem_Click(null, null)),
6255
6256                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6257                     .FocusedOn(FocusedControl.StatusText)
6258                     .Do(() => {
6259                         if (_curList != null && _curList.VirtualListSize != 0 &&
6260                                     _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6261                         {
6262                             var idx = _curList.SelectedIndices[0] - 1;
6263                             SelectListItem(_curList, idx);
6264                             _curList.EnsureVisible(idx);
6265                         }
6266                     }),
6267
6268                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6269                     .FocusedOn(FocusedControl.StatusText)
6270                     .Do(() => {
6271                         if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6272                                     && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6273                         {
6274                             var idx = _curList.SelectedIndices[0] + 1;
6275                             SelectListItem(_curList, idx);
6276                             _curList.EnsureVisible(idx);
6277                         }
6278                     }),
6279
6280                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6281                     .FocusedOn(FocusedControl.StatusText)
6282                     .Do(() => {
6283                         if (StatusText.SelectionStart > 0)
6284                         {
6285                             int endidx = StatusText.SelectionStart - 1;
6286                             string startstr = "";
6287                             for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6288                             {
6289                                 char c = StatusText.Text[i];
6290                                 if (Char.IsLetterOrDigit(c) || c == '_')
6291                                 {
6292                                     continue;
6293                                 }
6294                                 if (c == '@')
6295                                 {
6296                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6297                                     int cnt = AtIdSupl.ItemCount;
6298                                     ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6299                                     if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6300                                 }
6301                                 else if (c == '#')
6302                                 {
6303                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6304                                     ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6305                                 }
6306                                 else
6307                                 {
6308                                     break;
6309                                 }
6310                             }
6311                         }
6312                     }),
6313
6314                 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6315                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6316                     .FocusedOn(FocusedControl.ListTab)
6317                     .Do(() => this.SetSortColumnByDisplayIndex(0)),
6318
6319                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6320                     .FocusedOn(FocusedControl.ListTab)
6321                     .Do(() => this.SetSortColumnByDisplayIndex(1)),
6322
6323                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6324                     .FocusedOn(FocusedControl.ListTab)
6325                     .Do(() => this.SetSortColumnByDisplayIndex(2)),
6326
6327                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6328                     .FocusedOn(FocusedControl.ListTab)
6329                     .Do(() => this.SetSortColumnByDisplayIndex(3)),
6330
6331                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6332                     .FocusedOn(FocusedControl.ListTab)
6333                     .Do(() => this.SetSortColumnByDisplayIndex(4)),
6334
6335                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6336                     .FocusedOn(FocusedControl.ListTab)
6337                     .Do(() => this.SetSortColumnByDisplayIndex(5)),
6338
6339                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6340                     .FocusedOn(FocusedControl.ListTab)
6341                     .Do(() => this.SetSortColumnByDisplayIndex(6)),
6342
6343                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6344                     .FocusedOn(FocusedControl.ListTab)
6345                     .Do(() => this.SetSortColumnByDisplayIndex(7)),
6346
6347                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6348                     .FocusedOn(FocusedControl.ListTab)
6349                     .Do(() => this.SetSortLastColumn()),
6350
6351                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6352                     .Do(() => this.FavoritesRetweetOfficial()),
6353
6354                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6355                     .Do(() => this.FavoritesRetweetUnofficial()),
6356
6357                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6358                     .Do(() => this.OpenUserAppointUrl()),
6359
6360                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6361                     .FocusedOn(FocusedControl.PostBrowser)
6362                     .Do(() => this.doReTweetUnofficial()),
6363
6364                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6365                     .OnlyWhen(() => this.ExistCurrentPost)
6366                     .Do(() => this.tweetDetailsView.DoTranslation()),
6367
6368                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6369                     .Do(() => this.doReTweetUnofficial()),
6370
6371                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6372                     .Do(() => this.CopyUserId()),
6373
6374                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6375                     .Do(() => this.tweetThumbnail1.ScrollUp()),
6376
6377                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6378                     .Do(() => this.tweetThumbnail1.ScrollDown()),
6379
6380                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
6381                     .FocusedOn(FocusedControl.ListTab)
6382                     .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
6383                     .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
6384             };
6385         }
6386
6387         internal bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
6388         {
6389             // Task を返す非同期処理があれば asyncTask に代入する
6390             asyncTask = null;
6391
6392             // ShortcutCommand に対応しているコマンドはここで処理される
6393             foreach (var command in this.shortcutCommands)
6394             {
6395                 if (command.IsMatch(keyData, focusedOn))
6396                 {
6397                     asyncTask = command.RunCommand();
6398                     return command.PreventDefault;
6399                 }
6400             }
6401
6402             return false;
6403         }
6404
6405         private void GoNextTab(bool forward)
6406         {
6407             int idx = ListTab.SelectedIndex;
6408             if (forward)
6409             {
6410                 idx += 1;
6411                 if (idx > ListTab.TabPages.Count - 1) idx = 0;
6412             }
6413             else
6414             {
6415                 idx -= 1;
6416                 if (idx < 0) idx = ListTab.TabPages.Count - 1;
6417             }
6418             ListTab.SelectedIndex = idx;
6419         }
6420
6421         private void CopyStot()
6422         {
6423             string clstr = "";
6424             StringBuilder sb = new StringBuilder();
6425             bool IsProtected = false;
6426             bool isDm = false;
6427             if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
6428             foreach (int idx in _curList.SelectedIndices)
6429             {
6430                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
6431                 if (post.IsDeleted) continue;
6432                 if (!isDm)
6433                 {
6434                     if (post.RetweetedId != null)
6435                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
6436                     else
6437                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6438                 }
6439                 else
6440                 {
6441                     sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
6442                 }
6443             }
6444             if (IsProtected)
6445             {
6446                 MessageBox.Show(Properties.Resources.CopyStotText1);
6447             }
6448             if (sb.Length > 0)
6449             {
6450                 clstr = sb.ToString();
6451                 try
6452                 {
6453                     Clipboard.SetDataObject(clstr, false, 5, 100);
6454                 }
6455                 catch (Exception ex)
6456                 {
6457                     MessageBox.Show(ex.Message);
6458                 }
6459             }
6460         }
6461
6462         private void CopyIdUri()
6463         {
6464             if (this._curTab == null)
6465                 return;
6466
6467             var tab = this._statuses.GetTabByName(this._curTab.Text);
6468             if (tab == null || tab is DirectMessagesTabModel)
6469                 return;
6470
6471             var copyUrls = new List<string>();
6472             foreach (int idx in _curList.SelectedIndices)
6473             {
6474                 var post = tab[idx];
6475                 copyUrls.Add(MyCommon.GetStatusUrl(post));
6476             }
6477
6478             if (copyUrls.Count == 0)
6479                 return;
6480
6481             try
6482             {
6483                 Clipboard.SetDataObject(string.Join(Environment.NewLine, copyUrls), false, 5, 100);
6484             }
6485             catch (ExternalException ex)
6486             {
6487                 MessageBox.Show(ex.Message);
6488             }
6489         }
6490
6491         private void GoFav(bool forward)
6492         {
6493             if (_curList.VirtualListSize == 0) return;
6494             int fIdx = 0;
6495             int toIdx = 0;
6496             int stp = 1;
6497
6498             if (forward)
6499             {
6500                 if (_curList.SelectedIndices.Count == 0)
6501                 {
6502                     fIdx = 0;
6503                 }
6504                 else
6505                 {
6506                     fIdx = _curList.SelectedIndices[0] + 1;
6507                     if (fIdx > _curList.VirtualListSize - 1) return;
6508                 }
6509                 toIdx = _curList.VirtualListSize;
6510                 stp = 1;
6511             }
6512             else
6513             {
6514                 if (_curList.SelectedIndices.Count == 0)
6515                 {
6516                     fIdx = _curList.VirtualListSize - 1;
6517                 }
6518                 else
6519                 {
6520                     fIdx = _curList.SelectedIndices[0] - 1;
6521                     if (fIdx < 0) return;
6522                 }
6523                 toIdx = -1;
6524                 stp = -1;
6525             }
6526
6527             for (int idx = fIdx; idx != toIdx; idx += stp)
6528             {
6529                 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
6530                 {
6531                     SelectListItem(_curList, idx);
6532                     _curList.EnsureVisible(idx);
6533                     break;
6534                 }
6535             }
6536         }
6537
6538         private void GoSamePostToAnotherTab(bool left)
6539         {
6540             if (this._curList.SelectedIndices.Count == 0)
6541                 return;
6542
6543             var tab = this._statuses.Tabs[this._curTab.Text];
6544
6545             // Directタブは対象外(見つかるはずがない)
6546             if (tab.TabType == MyCommon.TabUsageType.DirectMessage)
6547                 return;
6548
6549             var selectedIndex = this._curList.SelectedIndices[0];
6550             var selectedStatusId = tab.GetStatusIdAt(selectedIndex);
6551
6552             int fIdx, toIdx, stp;
6553
6554             if (left)
6555             {
6556                 // 左のタブへ
6557                 if (ListTab.SelectedIndex == 0)
6558                 {
6559                     return;
6560                 }
6561                 else
6562                 {
6563                     fIdx = ListTab.SelectedIndex - 1;
6564                 }
6565                 toIdx = -1;
6566                 stp = -1;
6567             }
6568             else
6569             {
6570                 // 右のタブへ
6571                 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6572                 {
6573                     return;
6574                 }
6575                 else
6576                 {
6577                     fIdx = ListTab.SelectedIndex + 1;
6578                 }
6579                 toIdx = ListTab.TabCount;
6580                 stp = 1;
6581             }
6582
6583             for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
6584             {
6585                 var targetTab = this._statuses.Tabs[this.ListTab.TabPages[tabidx].Text];
6586
6587                 // Directタブは対象外
6588                 if (targetTab.TabType == MyCommon.TabUsageType.DirectMessage)
6589                     continue;
6590
6591                 var foundIndex = targetTab.IndexOf(selectedStatusId);
6592                 if (foundIndex != -1)
6593                 {
6594                     ListTab.SelectedIndex = tabidx;
6595                     SelectListItem(_curList, foundIndex);
6596                     _curList.EnsureVisible(foundIndex);
6597                     return;
6598                 }
6599             }
6600         }
6601
6602         private void GoPost(bool forward)
6603         {
6604             if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6605                 return;
6606
6607             var tab = this._statuses.Tabs[this._curTab.Text];
6608             var selectedIndex = this._curList.SelectedIndices[0];
6609
6610             int fIdx, toIdx, stp;
6611
6612             if (forward)
6613             {
6614                 fIdx = selectedIndex + 1;
6615                 if (fIdx > tab.AllCount - 1) return;
6616                 toIdx = tab.AllCount;
6617                 stp = 1;
6618             }
6619             else
6620             {
6621                 fIdx = selectedIndex - 1;
6622                 if (fIdx < 0) return;
6623                 toIdx = -1;
6624                 stp = -1;
6625             }
6626
6627             string name = "";
6628             if (_curPost.RetweetedId == null)
6629             {
6630                 name = _curPost.ScreenName;
6631             }
6632             else
6633             {
6634                 name = _curPost.RetweetedBy;
6635             }
6636             for (int idx = fIdx; idx != toIdx; idx += stp)
6637             {
6638                 var post = tab[idx];
6639                 if (post.RetweetedId == null)
6640                 {
6641                     if (post.ScreenName == name)
6642                     {
6643                         SelectListItem(_curList, idx);
6644                         _curList.EnsureVisible(idx);
6645                         break;
6646                     }
6647                 }
6648                 else
6649                 {
6650                     if (post.RetweetedBy == name)
6651                     {
6652                         SelectListItem(_curList, idx);
6653                         _curList.EnsureVisible(idx);
6654                         break;
6655                     }
6656                 }
6657             }
6658         }
6659
6660         private void GoRelPost(bool forward)
6661         {
6662             if (this._curList.SelectedIndices.Count == 0)
6663                 return;
6664
6665             var tab = this._statuses.Tabs[this._curTab.Text];
6666             var selectedIndex = this._curList.SelectedIndices[0];
6667
6668             int fIdx, toIdx, stp;
6669
6670             if (forward)
6671             {
6672                 fIdx = selectedIndex + 1;
6673                 if (fIdx > tab.AllCount - 1) return;
6674                 toIdx = tab.AllCount;
6675                 stp = 1;
6676             }
6677             else
6678             {
6679                 fIdx = selectedIndex - 1;
6680                 if (fIdx < 0) return;
6681                 toIdx = -1;
6682                 stp = -1;
6683             }
6684
6685             if (!_anchorFlag)
6686             {
6687                 if (_curPost == null) return;
6688                 _anchorPost = _curPost;
6689                 _anchorFlag = true;
6690             }
6691             else
6692             {
6693                 if (_anchorPost == null) return;
6694             }
6695
6696             for (int idx = fIdx; idx != toIdx; idx += stp)
6697             {
6698                 var post = tab[idx];
6699                 if (post.ScreenName == _anchorPost.ScreenName ||
6700                     post.RetweetedBy == _anchorPost.ScreenName ||
6701                     post.ScreenName == _anchorPost.RetweetedBy ||
6702                     (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
6703                     _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
6704                     _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
6705                     post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
6706                     post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
6707                 {
6708                     SelectListItem(_curList, idx);
6709                     _curList.EnsureVisible(idx);
6710                     break;
6711                 }
6712             }
6713         }
6714
6715         private void GoAnchor()
6716         {
6717             if (_anchorPost == null) return;
6718             int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
6719             if (idx == -1) return;
6720
6721             SelectListItem(_curList, idx);
6722             _curList.EnsureVisible(idx);
6723         }
6724
6725         private void GoTopEnd(bool GoTop)
6726         {
6727             if (_curList.VirtualListSize == 0)
6728                 return;
6729
6730             ListViewItem _item;
6731             int idx;
6732
6733             if (GoTop)
6734             {
6735                 _item = _curList.GetItemAt(0, 25);
6736                 if (_item == null)
6737                     idx = 0;
6738                 else
6739                     idx = _item.Index;
6740             }
6741             else
6742             {
6743                 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6744                 if (_item == null)
6745                     idx = _curList.VirtualListSize - 1;
6746                 else
6747                     idx = _item.Index;
6748             }
6749             SelectListItem(_curList, idx);
6750         }
6751
6752         private void GoMiddle()
6753         {
6754             if (_curList.VirtualListSize == 0)
6755                 return;
6756
6757             ListViewItem _item;
6758             int idx1;
6759             int idx2;
6760             int idx3;
6761
6762             _item = _curList.GetItemAt(0, 0);
6763             if (_item == null)
6764             {
6765                 idx1 = 0;
6766             }
6767             else
6768             {
6769                 idx1 = _item.Index;
6770             }
6771
6772             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
6773             if (_item == null)
6774             {
6775                 idx2 = _curList.VirtualListSize - 1;
6776             }
6777             else
6778             {
6779                 idx2 = _item.Index;
6780             }
6781             idx3 = (idx1 + idx2) / 2;
6782
6783             SelectListItem(_curList, idx3);
6784         }
6785
6786         private void GoLast()
6787         {
6788             if (_curList.VirtualListSize == 0) return;
6789
6790             if (_statuses.SortOrder == SortOrder.Ascending)
6791             {
6792                 SelectListItem(_curList, _curList.VirtualListSize - 1);
6793                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6794             }
6795             else
6796             {
6797                 SelectListItem(_curList, 0);
6798                 _curList.EnsureVisible(0);
6799             }
6800         }
6801
6802         private void MoveTop()
6803         {
6804             if (_curList.SelectedIndices.Count == 0) return;
6805             int idx = _curList.SelectedIndices[0];
6806             if (_statuses.SortOrder == SortOrder.Ascending)
6807             {
6808                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
6809             }
6810             else
6811             {
6812                 _curList.EnsureVisible(0);
6813             }
6814             _curList.EnsureVisible(idx);
6815         }
6816
6817         private async Task GoInReplyToPostTree()
6818         {
6819             if (_curPost == null) return;
6820
6821             TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6822
6823             if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
6824             {
6825                 try
6826                 {
6827                     var post = await tw.GetStatusApi(false, _curPost.StatusId);
6828
6829                     _curPost.InReplyToStatusId = post.InReplyToStatusId;
6830                     _curPost.InReplyToUser = post.InReplyToUser;
6831                     _curPost.IsReply = post.IsReply;
6832                     this.PurgeListViewItemCache();
6833                     _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
6834                 }
6835                 catch (WebApiException ex)
6836                 {
6837                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6838                 }
6839             }
6840
6841             if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
6842
6843             if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
6844             {
6845                 replyChains = new Stack<ReplyChain>();
6846             }
6847             replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
6848
6849             int inReplyToIndex;
6850             string inReplyToTabName;
6851             long inReplyToId = _curPost.InReplyToStatusId.Value;
6852             string inReplyToUser = _curPost.InReplyToUser;
6853             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6854
6855             var inReplyToPosts = from tab in _statuses.Tabs.Values
6856                                  orderby tab != curTabClass
6857                                  from post in tab.Posts.Values
6858                                  where post.StatusId == inReplyToId
6859                                  let index = tab.IndexOf(post.StatusId)
6860                                  where index != -1
6861                                  select new {Tab = tab, Index = index};
6862
6863             var inReplyPost = inReplyToPosts.FirstOrDefault();
6864             if (inReplyPost == null)
6865             {
6866                 try
6867                 {
6868                     await Task.Run(async () =>
6869                     {
6870                         var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
6871                             .ConfigureAwait(false);
6872                         post.IsRead = true;
6873
6874                         _statuses.AddPost(post);
6875                         _statuses.DistributePosts();
6876                     });
6877                 }
6878                 catch (WebApiException ex)
6879                 {
6880                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
6881                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6882                     return;
6883                 }
6884
6885                 this.RefreshTimeline();
6886
6887                 inReplyPost = inReplyToPosts.FirstOrDefault();
6888                 if (inReplyPost == null)
6889                 {
6890                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(inReplyToUser, inReplyToId));
6891                     return;
6892                 }
6893             }
6894             inReplyToTabName = inReplyPost.Tab.TabName;
6895             inReplyToIndex = inReplyPost.Index;
6896
6897             TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
6898             DetailsListView listView = (DetailsListView)tabPage.Tag;
6899
6900             if (_curTab != tabPage)
6901             {
6902                 this.ListTab.SelectTab(tabPage);
6903             }
6904
6905             this.SelectListItem(listView, inReplyToIndex);
6906             listView.EnsureVisible(inReplyToIndex);
6907         }
6908
6909         private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
6910         {
6911             if (_curPost == null) return;
6912
6913             TabModel curTabClass = _statuses.Tabs[_curTab.Text];
6914             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
6915
6916             if (parallel)
6917             {
6918                 if (_curPost.InReplyToStatusId != null)
6919                 {
6920                     var posts = from t in _statuses.Tabs
6921                                 from p in t.Value.Posts
6922                                 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
6923                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6924                                 where indexOf > -1
6925                                 orderby isForward ? indexOf : indexOf * -1
6926                                 orderby t.Value != curTabClass
6927                                 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
6928                     try
6929                     {
6930                         var postList = posts.ToList();
6931                         for (int i = postList.Count - 1; i >= 0; i--)
6932                         {
6933                             int index = i;
6934                             if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
6935                             {
6936                                 postList.RemoveAt(index);
6937                             }
6938                         }
6939                         var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
6940                         if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
6941                         if (post == null) post = postList.First();
6942                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6943                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6944                         SelectListItem(listView, post.Index);
6945                         listView.EnsureVisible(post.Index);
6946                     }
6947                     catch (InvalidOperationException)
6948                     {
6949                         return;
6950                     }
6951                 }
6952             }
6953             else
6954             {
6955                 if (replyChains == null || replyChains.Count < 1)
6956                 {
6957                     var posts = from t in _statuses.Tabs
6958                                 from p in t.Value.Posts
6959                                 where p.Value.InReplyToStatusId == _curPost.StatusId
6960                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
6961                                 where indexOf > -1
6962                                 orderby indexOf
6963                                 orderby t.Value != curTabClass
6964                                 select new {Tab = t.Value, Index = indexOf};
6965                     try
6966                     {
6967                         var post = posts.First();
6968                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
6969                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
6970                         SelectListItem(listView, post.Index);
6971                         listView.EnsureVisible(post.Index);
6972                     }
6973                     catch (InvalidOperationException)
6974                     {
6975                         return;
6976                     }
6977                 }
6978                 else
6979                 {
6980                     ReplyChain chainHead = replyChains.Pop();
6981                     if (chainHead.InReplyToId == _curPost.StatusId)
6982                     {
6983                         int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
6984                         if (idx == -1)
6985                         {
6986                             replyChains = null;
6987                         }
6988                         else
6989                         {
6990                             try
6991                             {
6992                                 ListTab.SelectTab(chainHead.OriginalTab);
6993                             }
6994                             catch (Exception)
6995                             {
6996                                 replyChains = null;
6997                             }
6998                             SelectListItem(_curList, idx);
6999                             _curList.EnsureVisible(idx);
7000                         }
7001                     }
7002                     else
7003                     {
7004                         replyChains = null;
7005                         this.GoBackInReplyToPostTree(parallel);
7006                     }
7007                 }
7008             }
7009         }
7010
7011         private void GoBackSelectPostChain()
7012         {
7013             if (this.selectPostChains.Count > 1)
7014             {
7015                 var idx = -1;
7016                 TabPage tp = null;
7017
7018                 do
7019                 {
7020                     try
7021                     {
7022                         this.selectPostChains.Pop();
7023                         var (tabPage, post) = this.selectPostChains.Peek();
7024
7025                         if (!this.ListTab.TabPages.Contains(tabPage)) continue;  //該当タブが存在しないので無視
7026
7027                         if (post != null)
7028                         {
7029                             idx = this._statuses.Tabs[tabPage.Text].IndexOf(post.StatusId);
7030                             if (idx == -1) continue;  //該当ポストが存在しないので無視
7031                         }
7032
7033                         tp = tabPage;
7034
7035                         this.selectPostChains.Pop();
7036                     }
7037                     catch (InvalidOperationException)
7038                     {
7039                     }
7040
7041                     break;
7042                 }
7043                 while (this.selectPostChains.Count > 1);
7044
7045                 if (tp == null)
7046                 {
7047                     //状態がおかしいので処理を中断
7048                     //履歴が残り1つであればクリアしておく
7049                     if (this.selectPostChains.Count == 1)
7050                         this.selectPostChains.Clear();
7051                     return;
7052                 }
7053
7054                 DetailsListView lst = (DetailsListView)tp.Tag;
7055                 this.ListTab.SelectedTab = tp;
7056                 if (idx > -1)
7057                 {
7058                     SelectListItem(lst, idx);
7059                     lst.EnsureVisible(idx);
7060                 }
7061                 lst.Focus();
7062             }
7063         }
7064
7065         private void PushSelectPostChain()
7066         {
7067             int count = this.selectPostChains.Count;
7068             if (count > 0)
7069             {
7070                 var (tabPage, post) = this.selectPostChains.Peek();
7071                 if (tabPage == this._curTab)
7072                 {
7073                     if (post == this._curPost) return;  //最新の履歴と同一
7074                     if (post == null) this.selectPostChains.Pop();  //置き換えるため削除
7075                 }
7076             }
7077             if (count >= 2500) TrimPostChain();
7078             this.selectPostChains.Push((this._curTab, this._curPost));
7079         }
7080
7081         private void TrimPostChain()
7082         {
7083             if (this.selectPostChains.Count <= 2000) return;
7084             var p = new Stack<ValueTuple<TabPage, PostClass>>(2000);
7085             for (int i = 0; i < 2000; i++)
7086             {
7087                 p.Push(this.selectPostChains.Pop());
7088             }
7089             this.selectPostChains.Clear();
7090             for (int i = 0; i < 2000; i++)
7091             {
7092                 this.selectPostChains.Push(p.Pop());
7093             }
7094         }
7095
7096         private bool GoStatus(long statusId)
7097         {
7098             if (statusId == 0) return false;
7099             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7100             {
7101                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7102                 {
7103                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7104                     ListTab.SelectedIndex = tabidx;
7105                     SelectListItem(_curList, idx);
7106                     _curList.EnsureVisible(idx);
7107                     return true;
7108                 }
7109             }
7110             return false;
7111         }
7112
7113         private bool GoDirectMessage(long statusId)
7114         {
7115             if (statusId == 0) return false;
7116             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7117             {
7118                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7119                 {
7120                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7121                     ListTab.SelectedIndex = tabidx;
7122                     SelectListItem(_curList, idx);
7123                     _curList.EnsureVisible(idx);
7124                     return true;
7125                 }
7126             }
7127             return false;
7128         }
7129
7130         private void MyList_MouseClick(object sender, MouseEventArgs e)
7131         {
7132             _anchorFlag = false;
7133         }
7134
7135         private void StatusText_Enter(object sender, EventArgs e)
7136         {
7137             // フォーカスの戻り先を StatusText に設定
7138             this.Tag = StatusText;
7139             StatusText.BackColor = _clInputBackcolor;
7140         }
7141
7142         public Color InputBackColor
7143         {
7144             get => _clInputBackcolor;
7145             set => _clInputBackcolor = value;
7146         }
7147
7148         private void StatusText_Leave(object sender, EventArgs e)
7149         {
7150             // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7151             if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7152             StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7153         }
7154
7155         private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7156         {
7157             if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out var asyncTask))
7158             {
7159                 e.Handled = true;
7160                 e.SuppressKeyPress = true;
7161             }
7162
7163             this.StatusText_TextChanged(null, null);
7164
7165             if (asyncTask != null)
7166                 await asyncTask;
7167         }
7168
7169         private void SaveConfigsAll(bool ifModified)
7170         {
7171             if (!ifModified)
7172             {
7173                 SaveConfigsCommon();
7174                 SaveConfigsLocal();
7175                 SaveConfigsTabs();
7176                 SaveConfigsAtId();
7177             }
7178             else
7179             {
7180                 if (ModifySettingCommon) SaveConfigsCommon();
7181                 if (ModifySettingLocal) SaveConfigsLocal();
7182                 if (ModifySettingAtId) SaveConfigsAtId();
7183             }
7184         }
7185
7186         private void SaveConfigsAtId()
7187         {
7188             if (_ignoreConfigSave || !SettingManager.Common.UseAtIdSupplement && AtIdSupl == null) return;
7189
7190             ModifySettingAtId = false;
7191             SettingManager.AtIdList.AtIdList = this.AtIdSupl.GetItemList();
7192             SettingManager.SaveAtIdList();
7193         }
7194
7195         private void SaveConfigsCommon()
7196         {
7197             if (_ignoreConfigSave) return;
7198
7199             ModifySettingCommon = false;
7200             lock (_syncObject)
7201             {
7202                 SettingManager.Common.UserName = tw.Username;
7203                 SettingManager.Common.UserId = tw.UserId;
7204                 SettingManager.Common.Token = tw.AccessToken;
7205                 SettingManager.Common.TokenSecret = tw.AccessTokenSecret;
7206                 SettingManager.Common.SortOrder = (int)_statuses.SortOrder;
7207                 switch (_statuses.SortMode)
7208                 {
7209                     case ComparerMode.Nickname:  //ニックネーム
7210                         SettingManager.Common.SortColumn = 1;
7211                         break;
7212                     case ComparerMode.Data:  //本文
7213                         SettingManager.Common.SortColumn = 2;
7214                         break;
7215                     case ComparerMode.Id:  //時刻=発言Id
7216                         SettingManager.Common.SortColumn = 3;
7217                         break;
7218                     case ComparerMode.Name:  //名前
7219                         SettingManager.Common.SortColumn = 4;
7220                         break;
7221                     case ComparerMode.Source:  //Source
7222                         SettingManager.Common.SortColumn = 7;
7223                         break;
7224                 }
7225
7226                 SettingManager.Common.HashTags = HashMgr.HashHistories;
7227                 if (HashMgr.IsPermanent)
7228                 {
7229                     SettingManager.Common.HashSelected = HashMgr.UseHash;
7230                 }
7231                 else
7232                 {
7233                     SettingManager.Common.HashSelected = "";
7234                 }
7235                 SettingManager.Common.HashIsHead = HashMgr.IsHead;
7236                 SettingManager.Common.HashIsPermanent = HashMgr.IsPermanent;
7237                 SettingManager.Common.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7238                 SettingManager.Common.TrackWord = tw.TrackWord;
7239                 SettingManager.Common.AllAtReply = tw.AllAtReply;
7240                 SettingManager.Common.UseImageService = ImageSelector.ServiceIndex;
7241                 SettingManager.Common.UseImageServiceName = ImageSelector.ServiceName;
7242
7243                 SettingManager.SaveCommon();
7244             }
7245         }
7246
7247         private void SaveConfigsLocal()
7248         {
7249             if (_ignoreConfigSave) return;
7250             lock (_syncObject)
7251             {
7252                 ModifySettingLocal = false;
7253                 SettingManager.Local.ScaleDimension = this.CurrentAutoScaleDimensions;
7254                 SettingManager.Local.FormSize = _mySize;
7255                 SettingManager.Local.FormLocation = _myLoc;
7256                 SettingManager.Local.SplitterDistance = _mySpDis;
7257                 SettingManager.Local.PreviewDistance = _mySpDis3;
7258                 SettingManager.Local.StatusMultiline = StatusText.Multiline;
7259                 SettingManager.Local.StatusTextHeight = _mySpDis2;
7260
7261                 SettingManager.Local.FontUnread = _fntUnread;
7262                 SettingManager.Local.ColorUnread = _clUnread;
7263                 SettingManager.Local.FontRead = _fntReaded;
7264                 SettingManager.Local.ColorRead = _clReaded;
7265                 SettingManager.Local.FontDetail = _fntDetail;
7266                 SettingManager.Local.ColorDetail = _clDetail;
7267                 SettingManager.Local.ColorDetailBackcolor = _clDetailBackcolor;
7268                 SettingManager.Local.ColorDetailLink = _clDetailLink;
7269                 SettingManager.Local.ColorFav = _clFav;
7270                 SettingManager.Local.ColorOWL = _clOWL;
7271                 SettingManager.Local.ColorRetweet = _clRetweet;
7272                 SettingManager.Local.ColorSelf = _clSelf;
7273                 SettingManager.Local.ColorAtSelf = _clAtSelf;
7274                 SettingManager.Local.ColorTarget = _clTarget;
7275                 SettingManager.Local.ColorAtTarget = _clAtTarget;
7276                 SettingManager.Local.ColorAtFromTarget = _clAtFromTarget;
7277                 SettingManager.Local.ColorAtTo = _clAtTo;
7278                 SettingManager.Local.ColorListBackcolor = _clListBackcolor;
7279                 SettingManager.Local.ColorInputBackcolor = _clInputBackcolor;
7280                 SettingManager.Local.ColorInputFont = _clInputFont;
7281                 SettingManager.Local.FontInputFont = _fntInputFont;
7282
7283                 if (_ignoreConfigSave) return;
7284                 SettingManager.SaveLocal();
7285             }
7286         }
7287
7288         private void SaveConfigsTabs()
7289         {
7290             var tabSettingList = new List<SettingTabs.SettingTabItem>();
7291
7292             var tabs = this.ListTab.TabPages.Cast<TabPage>()
7293                 .Select(x => this._statuses.Tabs[x.Text])
7294                 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7295
7296             foreach (var tab in tabs)
7297             {
7298                 if (!tab.IsPermanentTabType)
7299                     continue;
7300
7301                 var tabSetting = new SettingTabs.SettingTabItem
7302                 {
7303                     TabName = tab.TabName,
7304                     TabType = tab.TabType,
7305                     UnreadManage = tab.UnreadManage,
7306                     Protected = tab.Protected,
7307                     Notify = tab.Notify,
7308                     SoundFile = tab.SoundFile,
7309                 };
7310
7311                 switch (tab)
7312                 {
7313                     case FilterTabModel filterTab:
7314                         tabSetting.FilterArray = filterTab.FilterArray;
7315                         break;
7316                     case UserTimelineTabModel userTab:
7317                         tabSetting.User = userTab.ScreenName;
7318                         break;
7319                     case PublicSearchTabModel searchTab:
7320                         tabSetting.SearchWords = searchTab.SearchWords;
7321                         tabSetting.SearchLang = searchTab.SearchLang;
7322                         break;
7323                     case ListTimelineTabModel listTab:
7324                         tabSetting.ListInfo = listTab.ListInfo;
7325                         break;
7326                 }
7327
7328                 tabSettingList.Add(tabSetting);
7329             }
7330
7331             SettingManager.Tabs.Tabs = tabSettingList;
7332             SettingManager.SaveTabs();
7333         }
7334
7335         private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7336         {
7337             var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out var inputText);
7338             if (ret != DialogResult.OK)
7339                 return;
7340
7341             var match = Twitter.StatusUrlRegex.Match(inputText);
7342             if (!match.Success)
7343             {
7344                 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
7345                     Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
7346                 return;
7347             }
7348
7349             try
7350             {
7351                 var statusId = long.Parse(match.Groups["StatusId"].Value);
7352                 await this.OpenRelatedTab(statusId);
7353             }
7354             catch (TabException ex)
7355             {
7356                 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
7357             }
7358         }
7359
7360         private void SaveLogMenuItem_Click(object sender, EventArgs e)
7361         {
7362             DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
7363                     Properties.Resources.SaveLogMenuItem_ClickText2,
7364                     MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
7365             if (rslt == DialogResult.Cancel) return;
7366
7367             SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
7368             SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
7369             SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
7370             SaveFileDialog1.FilterIndex = 0;
7371             SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
7372             SaveFileDialog1.RestoreDirectory = true;
7373
7374             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
7375             {
7376                 if (!SaveFileDialog1.ValidateNames) return;
7377                 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
7378                 {
7379                     if (rslt == DialogResult.Yes)
7380                     {
7381                         //All
7382                         for (int idx = 0; idx < _curList.VirtualListSize; idx++)
7383                         {
7384                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
7385                             string protect = "";
7386                             if (post.IsProtect) protect = "Protect";
7387                             sw.WriteLine(post.Nickname + "\t" +
7388                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7389                                      post.CreatedAt + "\t" +
7390                                      post.ScreenName + "\t" +
7391                                      post.StatusId + "\t" +
7392                                      post.ImageUrl + "\t" +
7393                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7394                                      protect);
7395                         }
7396                     }
7397                     else
7398                     {
7399                         foreach (int idx in _curList.SelectedIndices)
7400                         {
7401                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
7402                             string protect = "";
7403                             if (post.IsProtect) protect = "Protect";
7404                             sw.WriteLine(post.Nickname + "\t" +
7405                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7406                                      post.CreatedAt + "\t" +
7407                                      post.ScreenName + "\t" +
7408                                      post.StatusId + "\t" +
7409                                      post.ImageUrl + "\t" +
7410                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
7411                                      protect);
7412                         }
7413                     }
7414                 }
7415             }
7416             this.TopMost = SettingManager.Common.AlwaysTop;
7417         }
7418
7419         public bool TabRename(string origTabName, out string newTabName)
7420         {
7421             //タブ名変更
7422             newTabName = null;
7423             using (InputTabName inputName = new InputTabName())
7424             {
7425                 inputName.TabName = origTabName;
7426                 inputName.ShowDialog();
7427                 if (inputName.DialogResult == DialogResult.Cancel) return false;
7428                 newTabName = inputName.TabName;
7429             }
7430             this.TopMost = SettingManager.Common.AlwaysTop;
7431             if (!string.IsNullOrEmpty(newTabName))
7432             {
7433                 //新タブ名存在チェック
7434                 for (int i = 0; i < ListTab.TabCount; i++)
7435                 {
7436                     if (ListTab.TabPages[i].Text == newTabName)
7437                     {
7438                         string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabName);
7439                         MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
7440                         return false;
7441                     }
7442                 }
7443
7444                 var tabPage = this.ListTab.TabPages.Cast<TabPage>()
7445                     .FirstOrDefault(x => x.Text == origTabName);
7446
7447                 // タブ名を変更
7448                 if (tabPage != null)
7449                     tabPage.Text = newTabName;
7450
7451                 _statuses.RenameTab(origTabName, newTabName);
7452
7453                 SaveConfigsCommon();
7454                 SaveConfigsTabs();
7455                 _rclickTabName = newTabName;
7456                 return true;
7457             }
7458             else
7459             {
7460                 return false;
7461             }
7462         }
7463
7464         private void ListTab_MouseClick(object sender, MouseEventArgs e)
7465         {
7466             if (e.Button == MouseButtons.Middle)
7467             {
7468                 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
7469                 {
7470                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
7471                     {
7472                         this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
7473                         this.SaveConfigsTabs();
7474                         break;
7475                     }
7476                 }
7477             }
7478         }
7479
7480         private void ListTab_DoubleClick(object sender, MouseEventArgs e)
7481         {
7482             TabRename(this.ListTab.SelectedTab.Text, out var _);
7483         }
7484
7485         private void ListTab_MouseDown(object sender, MouseEventArgs e)
7486         {
7487             if (SettingManager.Common.TabMouseLock) return;
7488             if (e.Button == MouseButtons.Left)
7489             {
7490                 for (int i = 0; i < ListTab.TabPages.Count; i++)
7491                 {
7492                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
7493                     {
7494                         _tabDrag = true;
7495                         _tabMouseDownPoint = e.Location;
7496                         break;
7497                     }
7498                 }
7499             }
7500             else
7501             {
7502                 _tabDrag = false;
7503             }
7504         }
7505
7506         private void ListTab_DragEnter(object sender, DragEventArgs e)
7507         {
7508             if (e.Data.GetDataPresent(typeof(TabPage)))
7509                 e.Effect = DragDropEffects.Move;
7510             else
7511                 e.Effect = DragDropEffects.None;
7512         }
7513
7514         private void ListTab_DragDrop(object sender, DragEventArgs e)
7515         {
7516             if (!e.Data.GetDataPresent(typeof(TabPage))) return;
7517
7518             _tabDrag = false;
7519             string tn = "";
7520             bool bef = false;
7521             Point cpos = new Point(e.X, e.Y);
7522             Point spos = ListTab.PointToClient(cpos);
7523             int i;
7524             for (i = 0; i < ListTab.TabPages.Count; i++)
7525             {
7526                 Rectangle rect = ListTab.GetTabRect(i);
7527                 if (rect.Left <= spos.X && spos.X <= rect.Right &&
7528                     rect.Top <= spos.Y && spos.Y <= rect.Bottom)
7529                 {
7530                     tn = ListTab.TabPages[i].Text;
7531                     if (spos.X <= (rect.Left + rect.Right) / 2)
7532                         bef = true;
7533                     else
7534                         bef = false;
7535
7536                     break;
7537                 }
7538             }
7539
7540             //タブのないところにドロップ->最後尾へ移動
7541             if (string.IsNullOrEmpty(tn))
7542             {
7543                 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
7544                 bef = false;
7545                 i = ListTab.TabPages.Count - 1;
7546             }
7547
7548             TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
7549             if (tp.Text == tn) return;
7550
7551             ReOrderTab(tp.Text, tn, bef);
7552         }
7553
7554         public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
7555         {
7556             var baseIndex = this.GetTabPageIndex(baseTabText);
7557             if (baseIndex == -1)
7558                 return;
7559
7560             var targetIndex = this.GetTabPageIndex(targetTabText);
7561             if (targetIndex == -1)
7562                 return;
7563
7564             using (ControlTransaction.Layout(this.ListTab))
7565             {
7566                 var mTp = this.ListTab.TabPages[targetIndex];
7567                 this.ListTab.TabPages.Remove(mTp);
7568
7569                 if (targetIndex < baseIndex)
7570                     baseIndex--;
7571
7572                 if (isBeforeBaseTab)
7573                     ListTab.TabPages.Insert(baseIndex, mTp);
7574                 else
7575                     ListTab.TabPages.Insert(baseIndex + 1, mTp);
7576             }
7577
7578             SaveConfigsTabs();
7579         }
7580
7581         private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
7582         {
7583             //isAuto:true=先頭に挿入、false=カーソル位置に挿入
7584             //isReply:true=@,false=DM
7585             if (!StatusText.Enabled) return;
7586             if (_curList == null) return;
7587             if (_curTab == null) return;
7588             if (!this.ExistCurrentPost) return;
7589
7590             // 複数あてリプライはReplyではなく通常ポスト
7591             //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
7592             //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
7593             //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
7594
7595             if (_curList.SelectedIndices.Count > 0)
7596             {
7597                 // アイテムが1件以上選択されている
7598                 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
7599                 {
7600                     // 単独ユーザー宛リプライまたはDM
7601                     if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
7602                     {
7603                         // ダイレクトメッセージ
7604                         StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
7605                         StatusText.SelectionStart = StatusText.Text.Length;
7606                         StatusText.Focus();
7607                         this.inReplyTo = null;
7608                         return;
7609                     }
7610                     if (string.IsNullOrEmpty(StatusText.Text))
7611                     {
7612                         //空の場合
7613
7614                         // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
7615                         StatusText.Text = "@" + _curPost.ScreenName + " ";
7616
7617                         var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7618                         var inReplyToScreenName = this._curPost.ScreenName;
7619                         this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7620                     }
7621                     else
7622                     {
7623                         //何か入力済の場合
7624
7625                         if (isAuto)
7626                         {
7627                             //1件選んでEnter or DoubleClick
7628                             if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
7629                             {
7630                                 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
7631                                 {
7632                                     //返信先書き換え
7633                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7634                                     var inReplyToScreenName = this._curPost.ScreenName;
7635                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7636                                 }
7637                                 return;
7638                             }
7639                             if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
7640                             {
7641                                 //文頭@以外
7642                                 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7643                                 {
7644                                     // 複数リプライ
7645                                     StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
7646                                     this.inReplyTo = null;
7647                                 }
7648                                 else
7649                                 {
7650                                     // 単独リプライ
7651                                     StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7652                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7653                                     var inReplyToScreenName = this._curPost.ScreenName;
7654                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7655                                 }
7656                             }
7657                             else
7658                             {
7659                                 //文頭@
7660                                 // 複数リプライ
7661                                 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
7662                                 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
7663                                 this.inReplyTo = null;
7664                             }
7665                         }
7666                         else
7667                         {
7668                             //1件選んでCtrl-Rの場合(返信先操作せず)
7669                             int sidx = StatusText.SelectionStart;
7670                             string id = "@" + _curPost.ScreenName + " ";
7671                             if (sidx > 0)
7672                             {
7673                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7674                                 {
7675                                     id = " " + id;
7676                                 }
7677                             }
7678                             StatusText.Text = StatusText.Text.Insert(sidx, id);
7679                             sidx += id.Length;
7680                             //if (StatusText.Text.StartsWith("@"))
7681                             //{
7682                             //    //複数リプライ
7683                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7684                             //    sidx += 5 + _curPost.ScreenName.Length;
7685                             //}
7686                             //else
7687                             //{
7688                             //    // 複数リプライ
7689                             //    StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
7690                             //    sidx += 3 + _curPost.ScreenName.Length;
7691                             //}
7692                             StatusText.SelectionStart = sidx;
7693                             StatusText.Focus();
7694                             //_reply_to_id = 0;
7695                             //_reply_to_name = null;
7696                             return;
7697                         }
7698                     }
7699                 }
7700                 else
7701                 {
7702                     // 複数リプライ
7703                     if (!isAuto && !isReply) return;
7704
7705                     //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
7706
7707                     if (isAuto)
7708                     {
7709                         //Enter or DoubleClick
7710
7711                         string sTxt = StatusText.Text;
7712                         if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
7713                         {
7714                             sTxt = ". " + sTxt;
7715                             this.inReplyTo = null;
7716                         }
7717                         for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7718                         {
7719                             PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7720                             if (!sTxt.Contains("@" + post.ScreenName + " "))
7721                             {
7722                                 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
7723                                 //sTxt = "@" + post.ScreenName + " " + sTxt;
7724                             }
7725                         }
7726                         StatusText.Text = sTxt;
7727                     }
7728                     else
7729                     {
7730                         //C-S-r or C-r
7731                         if (_curList.SelectedIndices.Count > 1)
7732                         {
7733                             //複数ポスト選択
7734
7735                             string ids = "";
7736                             int sidx = StatusText.SelectionStart;
7737                             for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
7738                             {
7739                                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
7740                                 if (!ids.Contains("@" + post.ScreenName + " ") &&
7741                                     !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7742                                 {
7743                                     ids += "@" + post.ScreenName + " ";
7744                                 }
7745                                 if (isAll)
7746                                 {
7747                                     foreach (string nm in post.ReplyToList)
7748                                     {
7749                                         if (!ids.Contains("@" + nm + " ") &&
7750                                             !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7751                                         {
7752                                             Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7753                                             if (m.Success)
7754                                                 ids += "@" + m.Result("${id}") + " ";
7755                                             else
7756                                                 ids += "@" + nm + " ";
7757                                         }
7758                                     }
7759                                 }
7760                             }
7761                             if (ids.Length == 0) return;
7762                             if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
7763                             {
7764                                 StatusText.Text = ". " + StatusText.Text;
7765                                 sidx += 2;
7766                                 this.inReplyTo = null;
7767                             }
7768                             if (sidx > 0)
7769                             {
7770                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7771                                 {
7772                                     ids = " " + ids;
7773                                 }
7774                             }
7775                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
7776                             sidx += ids.Length;
7777                             //if (StatusText.Text.StartsWith("@"))
7778                             //{
7779                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
7780                             //    sidx += 2 + ids.Length;
7781                             //}
7782                             //else
7783                             //{
7784                             //    StatusText.Text = StatusText.Text.Insert(sidx, ids);
7785                             //    sidx += 1 + ids.Length;
7786                             //}
7787                             StatusText.SelectionStart = sidx;
7788                             StatusText.Focus();
7789                             return;
7790                         }
7791                         else
7792                         {
7793                             //1件のみ選択のC-S-r(返信元付加する可能性あり)
7794
7795                             string ids = "";
7796                             int sidx = StatusText.SelectionStart;
7797                             PostClass post = _curPost;
7798                             if (!ids.Contains("@" + post.ScreenName + " ") &&
7799                                 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7800                             {
7801                                 ids += "@" + post.ScreenName + " ";
7802                             }
7803                             foreach (string nm in post.ReplyToList)
7804                             {
7805                                 if (!ids.Contains("@" + nm + " ") &&
7806                                     !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7807                                 {
7808                                     Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
7809                                     if (m.Success)
7810                                         ids += "@" + m.Result("${id}") + " ";
7811                                     else
7812                                         ids += "@" + nm + " ";
7813                                 }
7814                             }
7815                             if (!string.IsNullOrEmpty(post.RetweetedBy))
7816                             {
7817                                 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
7818                                    !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
7819                                 {
7820                                     ids += "@" + post.RetweetedBy + " ";
7821                                 }
7822                             }
7823                             if (ids.Length == 0) return;
7824                             if (string.IsNullOrEmpty(StatusText.Text))
7825                             {
7826                                 //未入力の場合のみ返信先付加
7827                                 StatusText.Text = ids;
7828                                 StatusText.SelectionStart = ids.Length;
7829                                 StatusText.Focus();
7830
7831                                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
7832                                 var inReplyToScreenName = this._curPost.ScreenName;
7833                                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
7834                                 return;
7835                             }
7836
7837                             if (sidx > 0)
7838                             {
7839                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
7840                                 {
7841                                     ids = " " + ids;
7842                                 }
7843                             }
7844                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
7845                             sidx += ids.Length;
7846                             StatusText.SelectionStart = sidx;
7847                             StatusText.Focus();
7848                             return;
7849                         }
7850                     }
7851                 }
7852                 StatusText.SelectionStart = StatusText.Text.Length;
7853                 StatusText.Focus();
7854             }
7855         }
7856
7857         private void ListTab_MouseUp(object sender, MouseEventArgs e)
7858         {
7859             _tabDrag = false;
7860         }
7861
7862         private static int iconCnt = 0;
7863         private static int blinkCnt = 0;
7864         private static bool blink = false;
7865         private static bool idle = false;
7866
7867         private async Task RefreshTasktrayIcon()
7868         {
7869             if (_colorize)
7870                 await this.Colorize();
7871
7872             if (!TimerRefreshIcon.Enabled) return;
7873             //Static usCheckCnt As int = 0
7874
7875             //Static iconDlListTopItem As ListViewItem = null
7876
7877             //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
7878             //    ((ImageDictionary)this.TIconDic).PauseGetImage = false;
7879             //else
7880             //    ((ImageDictionary)this.TIconDic).PauseGetImage = true;
7881             //
7882             //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
7883
7884             iconCnt += 1;
7885             blinkCnt += 1;
7886             //usCheckCnt += 1;
7887
7888             //if (usCheckCnt > 300)    //1min
7889             //{
7890             //    usCheckCnt = 0;
7891             //    if (!this.IsReceivedUserStream)
7892             //    {
7893             //        TraceOut("ReconnectUserStream");
7894             //        tw.ReconnectUserStream();
7895             //    }
7896             //}
7897
7898             var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
7899
7900             if (iconCnt >= this.NIconRefresh.Length)
7901             {
7902                 iconCnt = 0;
7903             }
7904             if (blinkCnt > 10)
7905             {
7906                 blinkCnt = 0;
7907                 //未保存の変更を保存
7908                 SaveConfigsAll(true);
7909             }
7910
7911             if (busy)
7912             {
7913                 NotifyIcon1.Icon = NIconRefresh[iconCnt];
7914                 idle = false;
7915                 _myStatusError = false;
7916                 return;
7917             }
7918
7919             TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
7920             if (SettingManager.Common.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
7921             {
7922                 if (blinkCnt > 0) return;
7923                 blink = !blink;
7924                 if (blink || SettingManager.Common.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
7925                 {
7926                     NotifyIcon1.Icon = ReplyIcon;
7927                 }
7928                 else
7929                 {
7930                     NotifyIcon1.Icon = ReplyIconBlink;
7931                 }
7932                 idle = false;
7933                 return;
7934             }
7935
7936             if (idle) return;
7937             idle = true;
7938             //優先度:エラー→オフライン→アイドル
7939             //エラーは更新アイコンでクリアされる
7940             if (_myStatusError)
7941             {
7942                 NotifyIcon1.Icon = NIconAtRed;
7943                 return;
7944             }
7945             if (_myStatusOnline)
7946             {
7947                 NotifyIcon1.Icon = NIconAt;
7948             }
7949             else
7950             {
7951                 NotifyIcon1.Icon = NIconAtSmoke;
7952             }
7953         }
7954
7955         private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
7956         {
7957             //200ms
7958             await this.RefreshTasktrayIcon();
7959         }
7960
7961         private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
7962         {
7963             //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
7964             if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
7965             {
7966                 if (ListTab != null && ListTab.SelectedTab != null)
7967                     _rclickTabName = ListTab.SelectedTab.Text;
7968                 else
7969                     return;
7970             }
7971
7972             if (_statuses == null) return;
7973             if (_statuses.Tabs == null) return;
7974
7975             if (!this._statuses.Tabs.TryGetValue(this._rclickTabName, out var tb))
7976                 return;
7977
7978             NotifyDispMenuItem.Checked = tb.Notify;
7979             this.NotifyTbMenuItem.Checked = tb.Notify;
7980
7981             soundfileListup = true;
7982             SoundFileComboBox.Items.Clear();
7983             this.SoundFileTbComboBox.Items.Clear();
7984             SoundFileComboBox.Items.Add("");
7985             this.SoundFileTbComboBox.Items.Add("");
7986             DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
7987             if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
7988             {
7989                 oDir = oDir.GetDirectories("Sounds")[0];
7990             }
7991             foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
7992             {
7993                 SoundFileComboBox.Items.Add(oFile.Name);
7994                 this.SoundFileTbComboBox.Items.Add(oFile.Name);
7995             }
7996             int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
7997             if (idx == -1) idx = 0;
7998             SoundFileComboBox.SelectedIndex = idx;
7999             this.SoundFileTbComboBox.SelectedIndex = idx;
8000             soundfileListup = false;
8001             UreadManageMenuItem.Checked = tb.UnreadManage;
8002             this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8003
8004             TabMenuControl(_rclickTabName);
8005         }
8006
8007         private void TabMenuControl(string tabName)
8008         {
8009             var tabInfo = _statuses.GetTabByName(tabName);
8010
8011             this.FilterEditMenuItem.Enabled = true;
8012             this.EditRuleTbMenuItem.Enabled = true;
8013
8014             if (tabInfo.IsDefaultTabType)
8015             {
8016                 this.ProtectTabMenuItem.Enabled = false;
8017                 this.ProtectTbMenuItem.Enabled = false;
8018             }
8019             else
8020             {
8021                 this.ProtectTabMenuItem.Enabled = true;
8022                 this.ProtectTbMenuItem.Enabled = true;
8023             }
8024
8025             if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8026             {
8027                 this.ProtectTabMenuItem.Checked = true;
8028                 this.ProtectTbMenuItem.Checked = true;
8029                 this.DeleteTabMenuItem.Enabled = false;
8030                 this.DeleteTbMenuItem.Enabled = false;
8031             }
8032             else
8033             {
8034                 this.ProtectTabMenuItem.Checked = false;
8035                 this.ProtectTbMenuItem.Checked = false;
8036                 this.DeleteTabMenuItem.Enabled = true;
8037                 this.DeleteTbMenuItem.Enabled = true;
8038             }
8039         }
8040
8041         private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8042         {
8043             var checkState = ((ToolStripMenuItem)sender).Checked;
8044
8045             // チェック状態を同期
8046             this.ProtectTbMenuItem.Checked = checkState;
8047             this.ProtectTabMenuItem.Checked = checkState;
8048
8049             // ロック中はタブの削除を無効化
8050             this.DeleteTabMenuItem.Enabled = !checkState;
8051             this.DeleteTbMenuItem.Enabled = !checkState;
8052
8053             if (string.IsNullOrEmpty(_rclickTabName)) return;
8054             _statuses.Tabs[_rclickTabName].Protected = checkState;
8055
8056             SaveConfigsTabs();
8057         }
8058
8059         private void UreadManageMenuItem_Click(object sender, EventArgs e)
8060         {
8061             UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8062             this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8063
8064             if (string.IsNullOrEmpty(_rclickTabName)) return;
8065             ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8066
8067             SaveConfigsTabs();
8068         }
8069
8070         public void ChangeTabUnreadManage(string tabName, bool isManage)
8071         {
8072             var idx = this.GetTabPageIndex(tabName);
8073             if (idx == -1)
8074                 return;
8075
8076             _statuses.Tabs[tabName].UnreadManage = isManage;
8077             if (SettingManager.Common.TabIconDisp)
8078             {
8079                 if (_statuses.Tabs[tabName].UnreadCount > 0)
8080                     ListTab.TabPages[idx].ImageIndex = 0;
8081                 else
8082                     ListTab.TabPages[idx].ImageIndex = -1;
8083             }
8084
8085             if (_curTab.Text == tabName)
8086             {
8087                 this.PurgeListViewItemCache();
8088                 _curList.Refresh();
8089             }
8090
8091             SetMainWindowTitle();
8092             SetStatusLabelUrl();
8093             if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8094         }
8095
8096         private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8097         {
8098             NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8099             this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8100
8101             if (string.IsNullOrEmpty(_rclickTabName)) return;
8102
8103             _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8104
8105             SaveConfigsTabs();
8106         }
8107
8108         private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8109         {
8110             if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8111
8112             _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8113
8114             SaveConfigsTabs();
8115         }
8116
8117         private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8118         {
8119             if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8120
8121             RemoveSpecifiedTab(_rclickTabName, true);
8122             SaveConfigsTabs();
8123         }
8124
8125         private void FilterEditMenuItem_Click(object sender, EventArgs e)
8126         {
8127             if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8128
8129             using (var fltDialog = new FilterDialog())
8130             {
8131                 fltDialog.Owner = this;
8132                 fltDialog.SetCurrent(_rclickTabName);
8133                 fltDialog.ShowDialog(this);
8134             }
8135             this.TopMost = SettingManager.Common.AlwaysTop;
8136
8137             this.ApplyPostFilters();
8138             SaveConfigsTabs();
8139         }
8140
8141         private void AddTabMenuItem_Click(object sender, EventArgs e)
8142         {
8143             string tabName = null;
8144             MyCommon.TabUsageType tabUsage;
8145             using (InputTabName inputName = new InputTabName())
8146             {
8147                 inputName.TabName = _statuses.MakeTabName("MyTab");
8148                 inputName.IsShowUsage = true;
8149                 inputName.ShowDialog();
8150                 if (inputName.DialogResult == DialogResult.Cancel) return;
8151                 tabName = inputName.TabName;
8152                 tabUsage = inputName.Usage;
8153             }
8154             this.TopMost = SettingManager.Common.AlwaysTop;
8155             if (!string.IsNullOrEmpty(tabName))
8156             {
8157                 //List対応
8158                 ListElement list = null;
8159                 if (tabUsage == MyCommon.TabUsageType.Lists)
8160                 {
8161                     using (ListAvailable listAvail = new ListAvailable())
8162                     {
8163                         if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8164                         if (listAvail.SelectedList == null) return;
8165                         list = listAvail.SelectedList;
8166                     }
8167                 }
8168
8169                 TabModel tab;
8170                 switch (tabUsage)
8171                 {
8172                     case MyCommon.TabUsageType.UserDefined:
8173                         tab = new FilterTabModel(tabName);
8174                         break;
8175                     case MyCommon.TabUsageType.PublicSearch:
8176                         tab = new PublicSearchTabModel(tabName);
8177                         break;
8178                     case MyCommon.TabUsageType.Lists:
8179                         tab = new ListTimelineTabModel(tabName, list);
8180                         break;
8181                     default:
8182                         return;
8183                 }
8184
8185                 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8186                 {
8187                     string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8188                     MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8189                 }
8190                 else
8191                 {
8192                     //成功
8193                     SaveConfigsTabs();
8194                     if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8195                     {
8196                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8197                         ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8198                     }
8199                     if (tabUsage == MyCommon.TabUsageType.Lists)
8200                     {
8201                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8202                         var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8203                         this.GetListTimelineAsync(listTab);
8204                     }
8205                 }
8206             }
8207         }
8208
8209         private void TabMenuItem_Click(object sender, EventArgs e)
8210         {
8211             using (var fltDialog = new FilterDialog())
8212             {
8213                 fltDialog.Owner = this;
8214
8215                 //選択発言を元にフィルタ追加
8216                 foreach (int idx in _curList.SelectedIndices)
8217                 {
8218                     //タブ選択(or追加)
8219                     if (!SelectTab(out var tabName)) return;
8220
8221                     fltDialog.SetCurrent(tabName);
8222                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8223                     {
8224                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8225                     }
8226                     else
8227                     {
8228                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8229                     }
8230                     fltDialog.ShowDialog(this);
8231                     this.TopMost = SettingManager.Common.AlwaysTop;
8232                 }
8233             }
8234
8235             this.ApplyPostFilters();
8236             SaveConfigsTabs();
8237             if (this.ListTab.SelectedTab != null &&
8238                 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8239             {
8240                 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8241             }
8242         }
8243
8244         protected override bool ProcessDialogKey(Keys keyData)
8245         {
8246             //TextBox1でEnterを押してもビープ音が鳴らないようにする
8247             if ((keyData & Keys.KeyCode) == Keys.Enter)
8248             {
8249                 if (StatusText.Focused)
8250                 {
8251                     bool _NewLine = false;
8252                     bool _Post = false;
8253
8254                     if (SettingManager.Common.PostCtrlEnter) //Ctrl+Enter投稿時
8255                     {
8256                         if (StatusText.Multiline)
8257                         {
8258                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8259
8260                             if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8261                         }
8262                         else
8263                         {
8264                             if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8265                         }
8266
8267                     }
8268                     else if (SettingManager.Common.PostShiftEnter) //SHift+Enter投稿時
8269                     {
8270                         if (StatusText.Multiline)
8271                         {
8272                             if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8273
8274                             if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8275                         }
8276                         else
8277                         {
8278                             if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8279                         }
8280
8281                     }
8282                     else //Enter投稿時
8283                     {
8284                         if (StatusText.Multiline)
8285                         {
8286                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8287
8288                             if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8289                                 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8290                         }
8291                         else
8292                         {
8293                             if (((keyData & Keys.Shift) == Keys.Shift) ||
8294                                 (((keyData & Keys.Control) != Keys.Control) &&
8295                                 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8296                         }
8297                     }
8298
8299                     if (_NewLine)
8300                     {
8301                         int pos1 = StatusText.SelectionStart;
8302                         if (StatusText.SelectionLength > 0)
8303                         {
8304                             StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength);  //選択状態文字列削除
8305                         }
8306                         StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine);  //改行挿入
8307                         StatusText.SelectionStart = pos1 + Environment.NewLine.Length;    //カーソルを改行の次の文字へ移動
8308                         return true;
8309                     }
8310                     else if (_Post)
8311                     {
8312                         PostButton_Click(null, null);
8313                         return true;
8314                     }
8315                 }
8316                 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8317                          (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8318                          ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8319                 {
8320                     this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8321                     return true;
8322                 }
8323             }
8324
8325             return base.ProcessDialogKey(keyData);
8326         }
8327
8328         private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
8329         {
8330             MakeReplyOrDirectStatus(false, true, true);
8331         }
8332
8333         private void IDRuleMenuItem_Click(object sender, EventArgs e)
8334         {
8335             //未選択なら処理終了
8336             if (_curList.SelectedIndices.Count == 0) return;
8337
8338             var tab = this._statuses.Tabs[this._curTab.Text];
8339             var screenNameArray = this._curList.SelectedIndices.Cast<int>()
8340                 .Select(x => tab[x])
8341                 .Select(x => x.RetweetedId != null ? x.RetweetedBy : x.ScreenName)
8342                 .ToArray();
8343
8344             this.AddFilterRuleByScreenName(screenNameArray);
8345
8346             if (screenNameArray.Length != 0)
8347             {
8348                 List<string> atids = new List<string>();
8349                 foreach (var screenName in screenNameArray)
8350                 {
8351                     atids.Add("@" + screenName);
8352                 }
8353                 int cnt = AtIdSupl.ItemCount;
8354                 AtIdSupl.AddRangeItem(atids.ToArray());
8355                 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
8356             }
8357         }
8358
8359         private void SourceRuleMenuItem_Click(object sender, EventArgs e)
8360         {
8361             if (this._curList.SelectedIndices.Count == 0)
8362                 return;
8363
8364             var tab = this._statuses.Tabs[this._curTab.Text];
8365             var sourceArray = this._curList.SelectedIndices.Cast<int>()
8366                 .Select(x => tab[x].Source).ToArray();
8367
8368             this.AddFilterRuleBySource(sourceArray);
8369         }
8370
8371         public void AddFilterRuleByScreenName(params string[] screenNameArray)
8372         {
8373             //タブ選択(or追加)
8374             if (!SelectTab(out var tabName)) return;
8375
8376             var tab = (FilterTabModel)this._statuses.Tabs[tabName];
8377
8378             bool mv;
8379             bool mk;
8380             if (tab.TabType != MyCommon.TabUsageType.Mute)
8381             {
8382                 this.MoveOrCopy(out mv, out mk);
8383             }
8384             else
8385             {
8386                 // ミュートタブでは常に MoveMatches を true にする
8387                 mv = true;
8388                 mk = false;
8389             }
8390
8391             foreach (var screenName in screenNameArray)
8392             {
8393                 tab.AddFilter(new PostFilterRule
8394                 {
8395                     FilterName = screenName,
8396                     UseNameField = true,
8397                     MoveMatches = mv,
8398                     MarkMatches = mk,
8399                     UseRegex = false,
8400                     FilterByUrl = false,
8401                 });
8402             }
8403
8404             this.ApplyPostFilters();
8405             SaveConfigsTabs();
8406         }
8407
8408         public void AddFilterRuleBySource(params string[] sourceArray)
8409         {
8410             // タブ選択ダイアログを表示(or追加)
8411             if (!this.SelectTab(out var tabName))
8412                 return;
8413
8414             var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
8415
8416             bool mv;
8417             bool mk;
8418             if (filterTab.TabType != MyCommon.TabUsageType.Mute)
8419             {
8420                 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
8421                 this.MoveOrCopy(out mv, out mk);
8422             }
8423             else
8424             {
8425                 // ミュートタブでは常に MoveMatches を true にする
8426                 mv = true;
8427                 mk = false;
8428             }
8429
8430             // 振り分けルールに追加するSource
8431             foreach (var source in sourceArray)
8432             {
8433                 filterTab.AddFilter(new PostFilterRule
8434                 {
8435                     FilterSource = source,
8436                     MoveMatches = mv,
8437                     MarkMatches = mk,
8438                     UseRegex = false,
8439                     FilterByUrl = false,
8440                 });
8441             }
8442
8443             this.ApplyPostFilters();
8444             this.SaveConfigsTabs();
8445         }
8446
8447         private bool SelectTab(out string tabName)
8448         {
8449             do
8450             {
8451                 tabName = null;
8452
8453                 //振り分け先タブ選択
8454                 using (var dialog = new TabsDialog(_statuses))
8455                 {
8456                     if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
8457
8458                     var selectedTab = dialog.SelectedTab;
8459                     tabName = selectedTab == null ? null : selectedTab.TabName;
8460                 }
8461
8462                 ListTab.SelectedTab.Focus();
8463                 //新規タブを選択→タブ作成
8464                 if (tabName == null)
8465                 {
8466                     using (InputTabName inputName = new InputTabName())
8467                     {
8468                         inputName.TabName = _statuses.MakeTabName("MyTab");
8469                         inputName.ShowDialog();
8470                         if (inputName.DialogResult == DialogResult.Cancel) return false;
8471                         tabName = inputName.TabName;
8472                     }
8473                     this.TopMost = SettingManager.Common.AlwaysTop;
8474                     if (!string.IsNullOrEmpty(tabName))
8475                     {
8476                         var tab = new FilterTabModel(tabName);
8477                         if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8478                         {
8479                             string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
8480                             MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8481                             //もう一度タブ名入力
8482                         }
8483                         else
8484                         {
8485                             return true;
8486                         }
8487                     }
8488                 }
8489                 else
8490                 {
8491                     //既存タブを選択
8492                     return true;
8493                 }
8494             }
8495             while (true);
8496         }
8497
8498         private void MoveOrCopy(out bool move, out bool mark)
8499         {
8500             {
8501                 //移動するか?
8502                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
8503                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8504                     move = false;
8505                 else
8506                     move = true;
8507             }
8508             if (!move)
8509             {
8510                 //マークするか?
8511                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
8512                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
8513                     mark = true;
8514                 else
8515                     mark = false;
8516             }
8517             else
8518             {
8519                 mark = false;
8520             }
8521         }
8522         private void CopySTOTMenuItem_Click(object sender, EventArgs e)
8523         {
8524             this.CopyStot();
8525         }
8526
8527         private void CopyURLMenuItem_Click(object sender, EventArgs e)
8528         {
8529             this.CopyIdUri();
8530         }
8531
8532         private void SelectAllMenuItem_Click(object sender, EventArgs e)
8533         {
8534             if (StatusText.Focused)
8535             {
8536                 // 発言欄でのCtrl+A
8537                 StatusText.SelectAll();
8538             }
8539             else
8540             {
8541                 // ListView上でのCtrl+A
8542                 NativeMethods.SelectAllItems(this._curList);
8543             }
8544         }
8545
8546         private void MoveMiddle()
8547         {
8548             ListViewItem _item;
8549             int idx1;
8550             int idx2;
8551
8552             if (_curList.SelectedIndices.Count == 0) return;
8553
8554             int idx = _curList.SelectedIndices[0];
8555
8556             _item = _curList.GetItemAt(0, 25);
8557             if (_item == null)
8558                 idx1 = 0;
8559             else
8560                 idx1 = _item.Index;
8561
8562             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
8563             if (_item == null)
8564                 idx2 = _curList.VirtualListSize - 1;
8565             else
8566                 idx2 = _item.Index;
8567
8568             idx -= Math.Abs(idx1 - idx2) / 2;
8569             if (idx < 0) idx = 0;
8570
8571             _curList.EnsureVisible(_curList.VirtualListSize - 1);
8572             _curList.EnsureVisible(idx);
8573         }
8574
8575         private async void OpenURLMenuItem_Click(object sender, EventArgs e)
8576         {
8577             var linkElements = this.tweetDetailsView.GetLinkElements();
8578
8579             if (linkElements.Length > 0)
8580             {
8581                 UrlDialog.ClearUrl();
8582
8583                 string openUrlStr = "";
8584
8585                 if (linkElements.Length == 1)
8586                 {
8587                     // ツイートに含まれる URL が 1 つのみの場合
8588                     //   => OpenURL ダイアログを表示せずにリンクを開く
8589
8590                     string urlStr = "";
8591                     try
8592                     {
8593                         urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
8594                     }
8595                     catch (ArgumentException)
8596                     {
8597                         //変なHTML?
8598                         return;
8599                     }
8600                     catch (Exception)
8601                     {
8602                         return;
8603                     }
8604                     if (string.IsNullOrEmpty(urlStr)) return;
8605                     openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
8606
8607                     // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
8608                     await this.OpenUriAsync(new Uri(openUrlStr));
8609                 }
8610                 else
8611                 {
8612                     // ツイートに含まれる URL が複数ある場合
8613                     //   => OpenURL を表示しユーザーが選択したリンクを開く
8614
8615                     foreach (var linkElm in linkElements)
8616                     {
8617                         string urlStr = "";
8618                         string linkText = "";
8619                         string href = "";
8620                         try
8621                         {
8622                             urlStr = linkElm.GetAttribute("title");
8623                             href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
8624                             if (string.IsNullOrEmpty(urlStr)) urlStr = href;
8625                             linkText = linkElm.InnerText;
8626                         }
8627                         catch (ArgumentException)
8628                         {
8629                             //変なHTML?
8630                             return;
8631                         }
8632                         catch (Exception)
8633                         {
8634                             return;
8635                         }
8636                         if (string.IsNullOrEmpty(urlStr)) continue;
8637                         UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
8638                     }
8639                     try
8640                     {
8641                         if (UrlDialog.ShowDialog() == DialogResult.OK)
8642                         {
8643                             openUrlStr = UrlDialog.SelectedUrl;
8644
8645                             // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
8646                             await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
8647                         }
8648                     }
8649                     catch (Exception)
8650                     {
8651                         return;
8652                     }
8653                     this.TopMost = SettingManager.Common.AlwaysTop;
8654                 }
8655             }
8656         }
8657
8658         private void ClearTabMenuItem_Click(object sender, EventArgs e)
8659         {
8660             if (string.IsNullOrEmpty(_rclickTabName)) return;
8661             ClearTab(_rclickTabName, true);
8662         }
8663
8664         private void ClearTab(string tabName, bool showWarning)
8665         {
8666             if (showWarning)
8667             {
8668                 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
8669                 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
8670                 {
8671                     return;
8672                 }
8673             }
8674
8675             _statuses.ClearTabIds(tabName);
8676             if (ListTab.SelectedTab.Text == tabName)
8677             {
8678                 _anchorPost = null;
8679                 _anchorFlag = false;
8680                 this.PurgeListViewItemCache();
8681                 _curItemIndex = -1;
8682                 _curPost = null;
8683             }
8684             foreach (TabPage tb in ListTab.TabPages)
8685             {
8686                 if (tb.Text == tabName)
8687                 {
8688                     ((DetailsListView)tb.Tag).VirtualListSize = 0;
8689                     tb.ImageIndex = -1;
8690                     break;
8691                 }
8692             }
8693             if (!SettingManager.Common.TabIconDisp) ListTab.Refresh();
8694
8695             SetMainWindowTitle();
8696             SetStatusLabelUrl();
8697         }
8698
8699         private static long followers = 0;
8700
8701         private void SetMainWindowTitle()
8702         {
8703             //メインウインドウタイトルの書き換え
8704             StringBuilder ttl = new StringBuilder(256);
8705             int ur = 0;
8706             int al = 0;
8707             if (SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.None &&
8708                 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Post &&
8709                 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
8710                 SettingManager.Common.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
8711             {
8712                 foreach (var tab in _statuses.Tabs.Values)
8713                 {
8714                     ur += tab.UnreadCount;
8715                     al += tab.AllCount;
8716                 }
8717             }
8718
8719             if (SettingManager.Common.DispUsername) ttl.Append(tw.Username).Append(" - ");
8720             ttl.Append(Application.ProductName);
8721             ttl.Append("  ");
8722             switch (SettingManager.Common.DispLatestPost)
8723             {
8724                 case MyCommon.DispTitleEnum.Ver:
8725                     ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
8726                     break;
8727                 case MyCommon.DispTitleEnum.Post:
8728                     if (_history != null && _history.Count > 1)
8729                         ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
8730                     break;
8731                 case MyCommon.DispTitleEnum.UnreadRepCount:
8732                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8733                     break;
8734                 case MyCommon.DispTitleEnum.UnreadAllCount:
8735                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
8736                     break;
8737                 case MyCommon.DispTitleEnum.UnreadAllRepCount:
8738                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
8739                     break;
8740                 case MyCommon.DispTitleEnum.UnreadCountAllCount:
8741                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
8742                     break;
8743                 case MyCommon.DispTitleEnum.OwnStatus:
8744                     if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
8745                     ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
8746                     break;
8747             }
8748
8749             try
8750             {
8751                 this.Text = ttl.ToString();
8752             }
8753             catch (AccessViolationException)
8754             {
8755                 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
8756             }
8757         }
8758
8759         private string GetStatusLabelText()
8760         {
8761             //ステータス欄にカウント表示
8762             //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
8763             if (_statuses == null) return "";
8764             TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8765             TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
8766             if (tbRep == null || tbDm == null) return "";
8767             int urat = tbRep.UnreadCount + tbDm.UnreadCount;
8768             int ur = 0;
8769             int al = 0;
8770             int tur = 0;
8771             int tal = 0;
8772             StringBuilder slbl = new StringBuilder(256);
8773             try
8774             {
8775                 foreach (var tab in _statuses.Tabs.Values)
8776                 {
8777                     ur += tab.UnreadCount;
8778                     al += tab.AllCount;
8779                     if (_curTab != null && tab.TabName.Equals(_curTab.Text))
8780                     {
8781                         tur = tab.UnreadCount;
8782                         tal = tab.AllCount;
8783                     }
8784                 }
8785             }
8786             catch (Exception)
8787             {
8788                 return "";
8789             }
8790
8791             UnreadCounter = ur;
8792             UnreadAtCounter = urat;
8793
8794             var homeTab = this._statuses.GetTabByType<HomeTabModel>();
8795
8796             slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, homeTab.TweetsPerHour);
8797             if (SettingManager.Common.TimelinePeriod == 0)
8798             {
8799                 slbl.Append(Properties.Resources.SetStatusLabelText2);
8800             }
8801             else
8802             {
8803                 slbl.Append(SettingManager.Common.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
8804             }
8805             return slbl.ToString();
8806         }
8807
8808         private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
8809         {
8810             try
8811             {
8812                 if (this.InvokeRequired && !this.IsDisposed)
8813                 {
8814                     await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
8815                 }
8816                 else
8817                 {
8818                     var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
8819                     SetApiStatusLabel(endpointName);
8820                 }
8821             }
8822             catch (ObjectDisposedException)
8823             {
8824                 return;
8825             }
8826             catch (InvalidOperationException)
8827             {
8828                 return;
8829             }
8830         }
8831
8832         private void SetApiStatusLabel(string endpointName = null)
8833         {
8834             if (_curTab == null)
8835             {
8836                 this.toolStripApiGauge.ApiEndpoint = null;
8837             }
8838             else
8839             {
8840                 var tabType = _statuses.Tabs[_curTab.Text].TabType;
8841
8842                 if (endpointName == null)
8843                 {
8844                     // 表示中のタブに応じて更新
8845                     switch (tabType)
8846                     {
8847                         case MyCommon.TabUsageType.Home:
8848                         case MyCommon.TabUsageType.UserDefined:
8849                             endpointName = "/statuses/home_timeline";
8850                             break;
8851
8852                         case MyCommon.TabUsageType.Mentions:
8853                             endpointName = "/statuses/mentions_timeline";
8854                             break;
8855
8856                         case MyCommon.TabUsageType.Favorites:
8857                             endpointName = "/favorites/list";
8858                             break;
8859
8860                         case MyCommon.TabUsageType.DirectMessage:
8861                             endpointName = "/direct_messages";
8862                             break;
8863
8864                         case MyCommon.TabUsageType.UserTimeline:
8865                             endpointName = "/statuses/user_timeline";
8866                             break;
8867
8868                         case MyCommon.TabUsageType.Lists:
8869                             endpointName = "/lists/statuses";
8870                             break;
8871
8872                         case MyCommon.TabUsageType.PublicSearch:
8873                             endpointName = "/search/tweets";
8874                             break;
8875
8876                         case MyCommon.TabUsageType.Related:
8877                             endpointName = "/statuses/show/:id";
8878                             break;
8879
8880                         default:
8881                             break;
8882                     }
8883
8884                     this.toolStripApiGauge.ApiEndpoint = endpointName;
8885                 }
8886                 else
8887                 {
8888                     // 表示中のタブに関連する endpoint であれば更新
8889                     var update = false;
8890
8891                     switch (endpointName)
8892                     {
8893                         case "/statuses/home_timeline":
8894                             update = tabType == MyCommon.TabUsageType.Home ||
8895                                      tabType == MyCommon.TabUsageType.UserDefined;
8896                             break;
8897
8898                         case "/statuses/mentions_timeline":
8899                             update = tabType == MyCommon.TabUsageType.Mentions;
8900                             break;
8901
8902                         case "/favorites/list":
8903                             update = tabType == MyCommon.TabUsageType.Favorites;
8904                             break;
8905
8906                         case "/direct_messages:":
8907                             update = tabType == MyCommon.TabUsageType.DirectMessage;
8908                             break;
8909
8910                         case "/statuses/user_timeline":
8911                             update = tabType == MyCommon.TabUsageType.UserTimeline;
8912                             break;
8913
8914                         case "/lists/statuses":
8915                             update = tabType == MyCommon.TabUsageType.Lists;
8916                             break;
8917
8918                         case "/search/tweets":
8919                             update = tabType == MyCommon.TabUsageType.PublicSearch;
8920                             break;
8921
8922                         case "/statuses/show/:id":
8923                             update = tabType == MyCommon.TabUsageType.Related;
8924                             break;
8925
8926                         default:
8927                             break;
8928                     }
8929
8930                     if (update)
8931                     {
8932                         this.toolStripApiGauge.ApiEndpoint = endpointName;
8933                     }
8934                 }
8935             }
8936         }
8937
8938         private void SetStatusLabelUrl()
8939         {
8940             StatusLabelUrl.Text = GetStatusLabelText();
8941         }
8942
8943         public void SetStatusLabel(string text)
8944         {
8945             StatusLabel.Text = text;
8946         }
8947
8948         private void SetNotifyIconText()
8949         {
8950             var ur = new StringBuilder(64);
8951
8952             // タスクトレイアイコンのツールチップテキスト書き換え
8953             // Tween [未読/@]
8954             ur.Remove(0, ur.Length);
8955             if (SettingManager.Common.DispUsername)
8956             {
8957                 ur.Append(tw.Username);
8958                 ur.Append(" - ");
8959             }
8960             ur.Append(Application.ProductName);
8961 #if DEBUG
8962             ur.Append("(Debug Build)");
8963 #endif
8964             if (UnreadCounter != -1 && UnreadAtCounter != -1)
8965             {
8966                 ur.Append(" [");
8967                 ur.Append(UnreadCounter);
8968                 ur.Append("/@");
8969                 ur.Append(UnreadAtCounter);
8970                 ur.Append("]");
8971             }
8972             NotifyIcon1.Text = ur.ToString();
8973         }
8974
8975         internal void CheckReplyTo(string StatusText)
8976         {
8977             MatchCollection m;
8978             //ハッシュタグの保存
8979             m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
8980             string hstr = "";
8981             foreach (Match hm in m)
8982             {
8983                 if (!hstr.Contains("#" + hm.Result("$3") + " "))
8984                 {
8985                     hstr += "#" + hm.Result("$3") + " ";
8986                     HashSupl.AddItem("#" + hm.Result("$3"));
8987                 }
8988             }
8989             if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
8990             {
8991                 hstr += HashMgr.UseHash;
8992             }
8993             if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
8994
8995             // 本当にリプライ先指定すべきかどうかの判定
8996             m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
8997
8998             if (SettingManager.Common.UseAtIdSupplement)
8999             {
9000                 int bCnt = AtIdSupl.ItemCount;
9001                 foreach (Match mid in m)
9002                 {
9003                     AtIdSupl.AddItem(mid.Result("${id}"));
9004                 }
9005                 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9006             }
9007
9008             // リプライ先ステータスIDの指定がない場合は指定しない
9009             if (this.inReplyTo == null)
9010                 return;
9011
9012             // 通常Reply
9013             // 次の条件を満たす場合に in_reply_to_status_id 指定
9014             // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9015             // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9016             // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9017
9018             if (m != null)
9019             {
9020                 var inReplyToScreenName = this.inReplyTo.Item2;
9021                 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9022                 {
9023                     if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9024                 }
9025                 else
9026                 {
9027                     foreach (Match mid in m)
9028                     {
9029                         if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9030                     }
9031                 }
9032             }
9033
9034             this.inReplyTo = null;
9035         }
9036
9037         private void TweenMain_Resize(object sender, EventArgs e)
9038         {
9039             if (!_initialLayout && SettingManager.Common.MinimizeToTray && WindowState == FormWindowState.Minimized)
9040             {
9041                 this.Visible = false;
9042             }
9043             if (_initialLayout && SettingManager.Local != null && this.WindowState == FormWindowState.Normal && this.Visible)
9044             {
9045                 // 現在の DPI と設定保存時の DPI との比を取得する
9046                 var configScaleFactor = SettingManager.Local.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9047
9048                 this.ClientSize = ScaleBy(configScaleFactor, SettingManager.Local.FormSize);
9049
9050                 // Splitterの位置設定
9051                 var splitterDistance = ScaleBy(configScaleFactor.Height, SettingManager.Local.SplitterDistance);
9052                 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9053                     splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9054                 {
9055                     this.SplitContainer1.SplitterDistance = splitterDistance;
9056                 }
9057
9058                 //発言欄複数行
9059                 StatusText.Multiline = SettingManager.Local.StatusMultiline;
9060                 if (StatusText.Multiline)
9061                 {
9062                     var statusTextHeight = ScaleBy(configScaleFactor.Height, SettingManager.Local.StatusTextHeight);
9063                     int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9064                     if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9065                     {
9066                         SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9067                     }
9068                     StatusText.Height = statusTextHeight;
9069                 }
9070                 else
9071                 {
9072                     if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9073                     {
9074                         SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9075                     }
9076                 }
9077
9078                 var previewDistance = ScaleBy(configScaleFactor.Width, SettingManager.Local.PreviewDistance);
9079                 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9080                 {
9081                     this.SplitContainer3.SplitterDistance = previewDistance;
9082                 }
9083
9084                 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9085                 this.SplitContainer3.Panel2Collapsed = true;
9086
9087                 _initialLayout = false;
9088             }
9089             if (this.WindowState != FormWindowState.Minimized)
9090             {
9091                 _formWindowState = this.WindowState;
9092             }
9093         }
9094
9095         private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9096         {
9097             PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9098             this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9099             if (PlaySoundMenuItem.Checked)
9100             {
9101                 SettingManager.Common.PlaySound = true;
9102             }
9103             else
9104             {
9105                 SettingManager.Common.PlaySound = false;
9106             }
9107             ModifySettingCommon = true;
9108         }
9109
9110         private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9111         {
9112             if (this._initialLayout)
9113                 return;
9114
9115             int splitterDistance;
9116             switch (this.WindowState)
9117             {
9118                 case FormWindowState.Normal:
9119                     splitterDistance = this.SplitContainer1.SplitterDistance;
9120                     break;
9121                 case FormWindowState.Maximized:
9122                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9123                     var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9124                     splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9125                     splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9126                     break;
9127                 default:
9128                     return;
9129             }
9130
9131             this._mySpDis = splitterDistance;
9132             this.ModifySettingLocal = true;
9133         }
9134
9135         private async Task doRepliedStatusOpen()
9136         {
9137             if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9138             {
9139                 if (MyCommon.IsKeyDown(Keys.Shift))
9140                 {
9141                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9142                     return;
9143                 }
9144                 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9145                 {
9146                     PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9147                     MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname}   ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9148                 }
9149                 else
9150                 {
9151                     foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9152                     {
9153                         if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9154                         PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9155                         MessageBox.Show($"{repPost.ScreenName} / {repPost.Nickname}   ({repPost.CreatedAt})" + Environment.NewLine + repPost.TextFromApi);
9156                         return;
9157                     }
9158                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9159                 }
9160             }
9161         }
9162
9163         private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9164         {
9165             await this.doRepliedStatusOpen();
9166         }
9167
9168         private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
9169         {
9170             var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
9171             if (multiline != this.StatusText.Multiline)
9172             {
9173                 this.StatusText.Multiline = multiline;
9174                 SettingManager.Local.StatusMultiline = multiline;
9175                 ModifySettingLocal = true;
9176             }
9177         }
9178
9179         private void StatusText_MultilineChanged(object sender, EventArgs e)
9180         {
9181             if (this.StatusText.Multiline)
9182                 this.StatusText.ScrollBars = ScrollBars.Vertical;
9183             else
9184                 this.StatusText.ScrollBars = ScrollBars.None;
9185
9186             ModifySettingLocal = true;
9187         }
9188
9189         private void MultiLineMenuItem_Click(object sender, EventArgs e)
9190         {
9191             //発言欄複数行
9192             var menuItemChecked = ((ToolStripMenuItem)sender).Checked;
9193             StatusText.Multiline = menuItemChecked;
9194             SettingManager.Local.StatusMultiline = menuItemChecked;
9195             if (menuItemChecked)
9196             {
9197                 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
9198                     SplitContainer2.SplitterDistance = 0;
9199                 else
9200                     SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
9201             }
9202             else
9203             {
9204                 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9205             }
9206             ModifySettingLocal = true;
9207         }
9208
9209         private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
9210         {
9211             if (Converter_Type == MyCommon.UrlConverter.Bitly || Converter_Type == MyCommon.UrlConverter.Jmp)
9212             {
9213                 // OAuth2 アクセストークンまたは API キー (旧方式) のいずれも設定されていなければ短縮しない
9214                 if (string.IsNullOrEmpty(SettingManager.Common.BitlyAccessToken) &&
9215                     (string.IsNullOrEmpty(SettingManager.Common.BilyUser) || string.IsNullOrEmpty(SettingManager.Common.BitlyPwd)))
9216                 {
9217                     MessageBox.Show(this, Properties.Resources.UrlConvert_BitlyAuthRequired, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
9218                     return false;
9219                 }
9220             }
9221
9222             //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
9223             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
9224
9225             //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
9226             //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
9227             //Appendix A.  Collected ABNF for URI
9228             //http://www.ietf.org/rfc/rfc3986.txt
9229
9230             string result = "";
9231
9232             const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
9233
9234             if (StatusText.SelectionLength > 0)
9235             {
9236                 string tmp = StatusText.SelectedText;
9237                 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
9238                 if (tmp.StartsWith("http", StringComparison.OrdinalIgnoreCase))
9239                 {
9240                     // 文字列が選択されている場合はその文字列について処理
9241
9242                     //nico.ms使用、nicovideoにマッチしたら変換
9243                     if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9244                     {
9245                         result = nicoms.Shorten(tmp);
9246                     }
9247                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9248                     {
9249                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9250                         try
9251                         {
9252                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9253                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9254                             result = resultUri.AbsoluteUri;
9255                         }
9256                         catch (WebApiException e)
9257                         {
9258                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9259                             return false;
9260                         }
9261                         catch (UriFormatException e)
9262                         {
9263                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9264                             return false;
9265                         }
9266                     }
9267                     else
9268                     {
9269                         return true;
9270                     }
9271
9272                     if (!string.IsNullOrEmpty(result))
9273                     {
9274                         urlUndo undotmp = new urlUndo();
9275
9276                         // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9277                         var origUrlIndex = this.StatusText.Text.IndexOf(tmp, StringComparison.Ordinal);
9278                         if (origUrlIndex == -1)
9279                             return false;
9280
9281                         StatusText.Select(origUrlIndex, tmp.Length);
9282                         StatusText.SelectedText = result;
9283
9284                         //undoバッファにセット
9285                         undotmp.Before = tmp;
9286                         undotmp.After = result;
9287
9288                         if (urlUndoBuffer == null)
9289                         {
9290                             urlUndoBuffer = new List<urlUndo>();
9291                             UrlUndoToolStripMenuItem.Enabled = true;
9292                         }
9293
9294                         urlUndoBuffer.Add(undotmp);
9295                     }
9296                 }
9297             }
9298             else
9299             {
9300                 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
9301                                    @"(?<url>(?<protocol>https?://)" +
9302                                    @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
9303                                    @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
9304                                    @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
9305                 // 正規表現にマッチしたURL文字列をtinyurl化
9306                 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
9307                 {
9308                     if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
9309                     string tmp = mt.Result("${url}");
9310                     if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
9311                     urlUndo undotmp = new urlUndo();
9312
9313                     //選んだURLを選択(?)
9314                     StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
9315
9316                     //nico.ms使用、nicovideoにマッチしたら変換
9317                     if (SettingManager.Common.Nicoms && Regex.IsMatch(tmp, nico))
9318                     {
9319                         result = nicoms.Shorten(tmp);
9320                     }
9321                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
9322                     {
9323                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
9324                         try
9325                         {
9326                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
9327                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
9328                             result = resultUri.AbsoluteUri;
9329                         }
9330                         catch (HttpRequestException e)
9331                         {
9332                             // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
9333                             // のように長いので「:」が含まれていればそれ以降のみを抽出する
9334                             var message = e.Message.Split(new[] { ':' }, count: 2).Last();
9335
9336                             this.StatusLabel.Text = Converter_Type + ":" + message;
9337                             continue;
9338                         }
9339                         catch (WebApiException e)
9340                         {
9341                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9342                             continue;
9343                         }
9344                         catch (UriFormatException e)
9345                         {
9346                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
9347                             continue;
9348                         }
9349                     }
9350                     else
9351                     {
9352                         continue;
9353                     }
9354
9355                     if (!string.IsNullOrEmpty(result))
9356                     {
9357                         // 短縮 URL が生成されるまでの間に投稿欄から元の URL が削除されていたら中断する
9358                         var origUrlIndex = this.StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal);
9359                         if (origUrlIndex == -1)
9360                             return false;
9361
9362                         StatusText.Select(origUrlIndex, mt.Result("${url}").Length);
9363                         StatusText.SelectedText = result;
9364                         //undoバッファにセット
9365                         undotmp.Before = mt.Result("${url}");
9366                         undotmp.After = result;
9367
9368                         if (urlUndoBuffer == null)
9369                         {
9370                             urlUndoBuffer = new List<urlUndo>();
9371                             UrlUndoToolStripMenuItem.Enabled = true;
9372                         }
9373
9374                         urlUndoBuffer.Add(undotmp);
9375                     }
9376                 }
9377             }
9378
9379             return true;
9380         }
9381
9382         private void doUrlUndo()
9383         {
9384             if (urlUndoBuffer != null)
9385             {
9386                 string tmp = StatusText.Text;
9387                 foreach (urlUndo data in urlUndoBuffer)
9388                 {
9389                     tmp = tmp.Replace(data.After, data.Before);
9390                 }
9391                 StatusText.Text = tmp;
9392                 urlUndoBuffer = null;
9393                 UrlUndoToolStripMenuItem.Enabled = false;
9394                 StatusText.SelectionStart = 0;
9395                 StatusText.SelectionLength = 0;
9396             }
9397         }
9398
9399         private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
9400         {
9401             await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
9402         }
9403
9404         private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
9405         {
9406             await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
9407         }
9408
9409         private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
9410         {
9411             await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
9412         }
9413
9414         private async void UxnuMenuItem_Click(object sender, EventArgs e)
9415         {
9416             await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
9417         }
9418
9419         private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
9420         {
9421             if (!await UrlConvertAsync(SettingManager.Common.AutoShortUrlFirst))
9422             {
9423                 MyCommon.UrlConverter svc = SettingManager.Common.AutoShortUrlFirst;
9424                 Random rnd = new Random();
9425                 // 前回使用した短縮URLサービス以外を選択する
9426                 do
9427                 {
9428                     svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
9429                 }
9430                 while (svc == SettingManager.Common.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
9431                 await UrlConvertAsync(svc);
9432             }
9433         }
9434
9435         private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
9436         {
9437             doUrlUndo();
9438         }
9439
9440         private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
9441         {
9442             this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9443             this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
9444             SettingManager.Common.NewAllPop = NewPostPopMenuItem.Checked;
9445             ModifySettingCommon = true;
9446         }
9447
9448         private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
9449         {
9450             ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9451             this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
9452             SettingManager.Common.ListLock = ListLockMenuItem.Checked;
9453             ModifySettingCommon = true;
9454         }
9455
9456         private void MenuStrip1_MenuActivate(object sender, EventArgs e)
9457         {
9458             // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
9459             MenuStrip1.Tag = new Object();
9460             MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
9461         }
9462
9463         private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
9464         {
9465             if (this.Tag != null) // 設定された戻り先へ遷移
9466             {
9467                 if (this.Tag == this.ListTab.SelectedTab)
9468                     ((Control)this.ListTab.SelectedTab.Tag).Select();
9469                 else
9470                     ((Control)this.Tag).Select();
9471             }
9472             else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
9473             {
9474                 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
9475                 {
9476                     this.Tag = ListTab.SelectedTab.Tag;
9477                     ((Control)this.Tag).Select();
9478                 }
9479             }
9480             // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
9481             MenuStrip1.Tag = null;
9482         }
9483
9484         private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
9485         {
9486             DetailsListView lst = (DetailsListView)sender;
9487             if (SettingManager.Local == null) return;
9488
9489             if (_iconCol)
9490             {
9491                 SettingManager.Local.Width1 = lst.Columns[0].Width;
9492                 SettingManager.Local.Width3 = lst.Columns[1].Width;
9493             }
9494             else
9495             {
9496                 int[] darr = new int[lst.Columns.Count];
9497                 for (int i = 0; i < lst.Columns.Count; i++)
9498                 {
9499                     darr[lst.Columns[i].DisplayIndex] = i;
9500                 }
9501                 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
9502
9503                 for (int i = 0; i < lst.Columns.Count; i++)
9504                 {
9505                     switch (darr[i])
9506                     {
9507                         case 0:
9508                             SettingManager.Local.DisplayIndex1 = i;
9509                             break;
9510                         case 1:
9511                             SettingManager.Local.DisplayIndex2 = i;
9512                             break;
9513                         case 2:
9514                             SettingManager.Local.DisplayIndex3 = i;
9515                             break;
9516                         case 3:
9517                             SettingManager.Local.DisplayIndex4 = i;
9518                             break;
9519                         case 4:
9520                             SettingManager.Local.DisplayIndex5 = i;
9521                             break;
9522                         case 5:
9523                             SettingManager.Local.DisplayIndex6 = i;
9524                             break;
9525                         case 6:
9526                             SettingManager.Local.DisplayIndex7 = i;
9527                             break;
9528                         case 7:
9529                             SettingManager.Local.DisplayIndex8 = i;
9530                             break;
9531                     }
9532                 }
9533                 SettingManager.Local.Width1 = lst.Columns[0].Width;
9534                 SettingManager.Local.Width2 = lst.Columns[1].Width;
9535                 SettingManager.Local.Width3 = lst.Columns[2].Width;
9536                 SettingManager.Local.Width4 = lst.Columns[3].Width;
9537                 SettingManager.Local.Width5 = lst.Columns[4].Width;
9538                 SettingManager.Local.Width6 = lst.Columns[5].Width;
9539                 SettingManager.Local.Width7 = lst.Columns[6].Width;
9540                 SettingManager.Local.Width8 = lst.Columns[7].Width;
9541             }
9542             ModifySettingLocal = true;
9543             _isColumnChanged = true;
9544         }
9545
9546         private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
9547         {
9548             DetailsListView lst = (DetailsListView)sender;
9549             if (SettingManager.Local == null) return;
9550             if (_iconCol)
9551             {
9552                 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9553                 {
9554                     SettingManager.Local.Width1 = lst.Columns[0].Width;
9555                     ModifySettingLocal = true;
9556                     _isColumnChanged = true;
9557                 }
9558                 if (SettingManager.Local.Width3 != lst.Columns[1].Width)
9559                 {
9560                     SettingManager.Local.Width3 = lst.Columns[1].Width;
9561                     ModifySettingLocal = true;
9562                     _isColumnChanged = true;
9563                 }
9564             }
9565             else
9566             {
9567                 if (SettingManager.Local.Width1 != lst.Columns[0].Width)
9568                 {
9569                     SettingManager.Local.Width1 = lst.Columns[0].Width;
9570                     ModifySettingLocal = true;
9571                     _isColumnChanged = true;
9572                 }
9573                 if (SettingManager.Local.Width2 != lst.Columns[1].Width)
9574                 {
9575                     SettingManager.Local.Width2 = lst.Columns[1].Width;
9576                     ModifySettingLocal = true;
9577                     _isColumnChanged = true;
9578                 }
9579                 if (SettingManager.Local.Width3 != lst.Columns[2].Width)
9580                 {
9581                     SettingManager.Local.Width3 = lst.Columns[2].Width;
9582                     ModifySettingLocal = true;
9583                     _isColumnChanged = true;
9584                 }
9585                 if (SettingManager.Local.Width4 != lst.Columns[3].Width)
9586                 {
9587                     SettingManager.Local.Width4 = lst.Columns[3].Width;
9588                     ModifySettingLocal = true;
9589                     _isColumnChanged = true;
9590                 }
9591                 if (SettingManager.Local.Width5 != lst.Columns[4].Width)
9592                 {
9593                     SettingManager.Local.Width5 = lst.Columns[4].Width;
9594                     ModifySettingLocal = true;
9595                     _isColumnChanged = true;
9596                 }
9597                 if (SettingManager.Local.Width6 != lst.Columns[5].Width)
9598                 {
9599                     SettingManager.Local.Width6 = lst.Columns[5].Width;
9600                     ModifySettingLocal = true;
9601                     _isColumnChanged = true;
9602                 }
9603                 if (SettingManager.Local.Width7 != lst.Columns[6].Width)
9604                 {
9605                     SettingManager.Local.Width7 = lst.Columns[6].Width;
9606                     ModifySettingLocal = true;
9607                     _isColumnChanged = true;
9608                 }
9609                 if (SettingManager.Local.Width8 != lst.Columns[7].Width)
9610                 {
9611                     SettingManager.Local.Width8 = lst.Columns[7].Width;
9612                     ModifySettingLocal = true;
9613                     _isColumnChanged = true;
9614                 }
9615             }
9616             // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
9617             //if (changed)
9618             //{
9619             //    SaveConfigsLocal();
9620             //}
9621         }
9622
9623         private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
9624         {
9625             if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
9626             ModifySettingLocal = true;
9627         }
9628
9629         private void TweenMain_DragDrop(object sender, DragEventArgs e)
9630         {
9631             if (e.Data.GetDataPresent(DataFormats.FileDrop))
9632             {
9633                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9634                 {
9635                     SelectMedia_DragDrop(e);
9636                 }
9637             }
9638             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9639             {
9640                 var (url, title) = GetUrlFromDataObject(e.Data);
9641
9642                 string appendText;
9643                 if (title == null)
9644                     appendText = url;
9645                 else
9646                     appendText = title + " " + url;
9647
9648                 if (this.StatusText.TextLength == 0)
9649                     this.StatusText.Text = appendText;
9650                 else
9651                     this.StatusText.Text += " " + appendText;
9652             }
9653             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9654             {
9655                 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
9656                 if (text != null)
9657                     this.StatusText.Text += text;
9658             }
9659             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9660             {
9661                 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
9662                 if (data != null) StatusText.Text += data;
9663             }
9664         }
9665
9666         /// <summary>
9667         /// IDataObject から URL とタイトルの対を取得します
9668         /// </summary>
9669         /// <remarks>
9670         /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
9671         /// </remarks>
9672         /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
9673         /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
9674         internal static (string Url, string Title) GetUrlFromDataObject(IDataObject data)
9675         {
9676             if (data.GetDataPresent("text/x-moz-url"))
9677             {
9678                 // Firefox, Google Chrome で利用可能
9679                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
9680
9681                 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
9682                 {
9683                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
9684                     if (lines.Length < 2)
9685                         throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
9686
9687                     return (lines[0], lines[1]);
9688                 }
9689             }
9690             else if (data.GetDataPresent("IESiteModeToUrl"))
9691             {
9692                 // Internet Exproler 用
9693                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
9694
9695                 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
9696                 {
9697                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
9698                     if (lines.Length < 2)
9699                         throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
9700
9701                     return (lines[0], lines[1]);
9702                 }
9703             }
9704             else if (data.GetDataPresent("UniformResourceLocatorW"))
9705             {
9706                 // それ以外のブラウザ向け
9707
9708                 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
9709                 {
9710                     var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
9711                     return (url, null);
9712                 }
9713             }
9714
9715             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
9716         }
9717
9718         private void TweenMain_DragEnter(object sender, DragEventArgs e)
9719         {
9720             if (e.Data.GetDataPresent(DataFormats.FileDrop))
9721             {
9722                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
9723                 {
9724                     SelectMedia_DragEnter(e);
9725                     return;
9726                 }
9727             }
9728             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
9729             {
9730                 e.Effect = DragDropEffects.Copy;
9731                 return;
9732             }
9733             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
9734             {
9735                 e.Effect = DragDropEffects.Copy;
9736                 return;
9737             }
9738             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
9739             {
9740                 e.Effect = DragDropEffects.Copy;
9741                 return;
9742             }
9743
9744             e.Effect = DragDropEffects.None;
9745         }
9746
9747         private void TweenMain_DragOver(object sender, DragEventArgs e)
9748         {
9749         }
9750
9751         public bool IsNetworkAvailable()
9752         {
9753             bool nw = true;
9754             nw = MyCommon.IsNetworkAvailable();
9755             _myStatusOnline = nw;
9756             return nw;
9757         }
9758
9759         public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
9760         {
9761             var uriStr = uri.AbsoluteUri;
9762
9763             // OpenTween 内部で使用する URL
9764             if (uri.Authority == "opentween")
9765             {
9766                 await this.OpenInternalUriAsync(uri);
9767                 return;
9768             }
9769
9770             // ハッシュタグを含む Twitter 検索
9771             if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
9772             {
9773                 // ハッシュタグの場合は、タブで開く
9774                 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
9775                 var pos = unescapedQuery.IndexOf('#');
9776                 if (pos == -1) return;
9777
9778                 var hash = unescapedQuery.Substring(pos);
9779                 this.HashSupl.AddItem(hash);
9780                 this.HashMgr.AddHashToHistory(hash.Trim(), false);
9781                 this.AddNewTabForSearch(hash);
9782                 return;
9783             }
9784
9785             // ユーザープロフィールURL
9786             // フラグが立っている場合は設定と逆の動作をする
9787             if( SettingManager.Common.OpenUserTimeline && !isReverseSettings ||
9788                 !SettingManager.Common.OpenUserTimeline && isReverseSettings )
9789             {
9790                 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
9791                 if (userUriMatch.Success)
9792                 {
9793                     var screenName = userUriMatch.Groups["ScreenName"].Value;
9794                     if (this.IsTwitterId(screenName))
9795                     {
9796                         this.AddNewTabForUserTimeline(screenName);
9797                         return;
9798                     }
9799                 }
9800             }
9801
9802             // どのパターンにも該当しないURL
9803             await this.OpenUriInBrowserAsync(uriStr);
9804         }
9805
9806         /// <summary>
9807         /// OpenTween 内部の機能を呼び出すための URL を開きます
9808         /// </summary>
9809         private async Task OpenInternalUriAsync(Uri uri)
9810         {
9811             // ツイートを開く (//opentween/status/:status_id)
9812             var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
9813             if (match.Success)
9814             {
9815                 var statusId = long.Parse(match.Groups[1].Value);
9816                 await this.OpenRelatedTab(statusId);
9817                 return;
9818             }
9819         }
9820
9821         public Task OpenUriInBrowserAsync(string UriString)
9822         {
9823             return Task.Run(() =>
9824             {
9825                 string myPath = UriString;
9826
9827                 try
9828                 {
9829                     var configBrowserPath = SettingManager.Local.BrowserPath;
9830                     if (!string.IsNullOrEmpty(configBrowserPath))
9831                     {
9832                         if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
9833                         {
9834                             int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
9835                             string browserPath = configBrowserPath.Substring(1, sep - 1);
9836                             string arg = "";
9837                             if (sep < configBrowserPath.Length - 1)
9838                             {
9839                                 arg = configBrowserPath.Substring(sep + 1);
9840                             }
9841                             myPath = arg + " " + myPath;
9842                             System.Diagnostics.Process.Start(browserPath, myPath);
9843                         }
9844                         else
9845                         {
9846                             System.Diagnostics.Process.Start(configBrowserPath, myPath);
9847                         }
9848                     }
9849                     else
9850                     {
9851                         System.Diagnostics.Process.Start(myPath);
9852                     }
9853                 }
9854                 catch (Exception)
9855                 {
9856                     //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
9857                 }
9858             });
9859         }
9860
9861         private void ListTabSelect(TabPage _tab)
9862         {
9863             SetListProperty();
9864
9865             this.PurgeListViewItemCache();
9866
9867             _curTab = _tab;
9868             _curList = (DetailsListView)_tab.Tag;
9869
9870             if (_curList.SelectedIndices.Count > 0)
9871             {
9872                 _curItemIndex = _curList.SelectedIndices[0];
9873                 _curPost = GetCurTabPost(_curItemIndex);
9874             }
9875             else
9876             {
9877                 _curItemIndex = -1;
9878                 _curPost = null;
9879             }
9880
9881             _anchorPost = null;
9882             _anchorFlag = false;
9883
9884             if (_iconCol)
9885             {
9886                 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
9887             }
9888             else
9889             {
9890                 for (int i = 0; i < _curList.Columns.Count; i++)
9891                 {
9892                     ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
9893                 }
9894             }
9895         }
9896
9897         private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
9898         {
9899             ListTabSelect(e.TabPage);
9900         }
9901
9902         private void SelectListItem(DetailsListView LView, int Index)
9903         {
9904             //単一
9905             Rectangle bnd = new Rectangle();
9906             bool flg = false;
9907             var item = LView.FocusedItem;
9908             if (item != null)
9909             {
9910                 bnd = item.Bounds;
9911                 flg = true;
9912             }
9913
9914             do
9915             {
9916                 LView.SelectedIndices.Clear();
9917             }
9918             while (LView.SelectedIndices.Count > 0);
9919             item = LView.Items[Index];
9920             item.Selected = true;
9921             item.Focused = true;
9922
9923             if (flg) LView.Invalidate(bnd);
9924         }
9925
9926         private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
9927         {
9928             //複数
9929             Rectangle bnd = new Rectangle();
9930             bool flg = false;
9931             var item = LView.FocusedItem;
9932             if (item != null)
9933             {
9934                 bnd = item.Bounds;
9935                 flg = true;
9936             }
9937
9938             if (Index != null)
9939             {
9940                 do
9941                 {
9942                     LView.SelectedIndices.Clear();
9943                 }
9944                 while (LView.SelectedIndices.Count > 0);
9945                 LView.SelectItems(Index);
9946             }
9947             if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
9948             {
9949                 LView.SelectionMark = selectionMarkIndex;
9950             }
9951             if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
9952             {
9953                 LView.Items[focusedIndex].Focused = true;
9954             }
9955             else if (Index != null && Index.Length != 0)
9956             {
9957                 LView.Items[Index.Last()].Focused = true;
9958             }
9959
9960             if (flg) LView.Invalidate(bnd);
9961         }
9962
9963         private void StartUserStream()
9964         {
9965             tw.NewPostFromStream += tw_NewPostFromStream;
9966             tw.UserStreamStarted += tw_UserStreamStarted;
9967             tw.UserStreamStopped += tw_UserStreamStopped;
9968             tw.PostDeleted += tw_PostDeleted;
9969             tw.UserStreamEventReceived += tw_UserStreamEventArrived;
9970
9971             this.RefreshUserStreamsMenu();
9972
9973             if (SettingManager.Common.UserstreamStartup)
9974                 tw.StartUserStream();
9975         }
9976
9977         private async void TweenMain_Shown(object sender, EventArgs e)
9978         {
9979             NotifyIcon1.Visible = true;
9980
9981             if (this.IsNetworkAvailable())
9982             {
9983                 StartUserStream();
9984
9985                 var loadTasks = new List<Task>
9986                 {
9987                     this.RefreshMuteUserIdsAsync(),
9988                     this.RefreshBlockIdsAsync(),
9989                     this.RefreshNoRetweetIdsAsync(),
9990                     this.RefreshTwitterConfigurationAsync(),
9991                     this.GetHomeTimelineAsync(),
9992                     this.GetReplyAsync(),
9993                     this.GetDirectMessagesAsync(),
9994                     this.GetPublicSearchAllAsync(),
9995                     this.GetUserTimelineAllAsync(),
9996                     this.GetListTimelineAllAsync(),
9997                 };
9998
9999                 if (SettingManager.Common.StartupFollowers)
10000                     loadTasks.Add(this.RefreshFollowerIdsAsync());
10001
10002                 if (SettingManager.Common.GetFav)
10003                     loadTasks.Add(this.GetFavoritesAsync());
10004
10005                 var allTasks = Task.WhenAll(loadTasks);
10006
10007                 var i = 0;
10008                 while (true)
10009                 {
10010                     var timeout = Task.Delay(5000);
10011                     if (await Task.WhenAny(allTasks, timeout) != timeout)
10012                         break;
10013
10014                     i += 1;
10015                     if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
10016
10017                     if (MyCommon._endingFlag)
10018                         return;
10019                 }
10020
10021                 if (MyCommon._endingFlag) return;
10022
10023                 if (ApplicationSettings.VersionInfoUrl != null)
10024                 {
10025                     //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
10026                     if (SettingManager.Common.StartupVersion)
10027                         await this.CheckNewVersion(true);
10028                 }
10029                 else
10030                 {
10031                     // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
10032                     this.VerUpMenuItem.Enabled = false;
10033                     this.VerUpMenuItem.Available = false;
10034                     this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
10035                 }
10036
10037                 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
10038                 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
10039                 {
10040                     MessageBox.Show(Properties.Resources.ReAuthorizeText);
10041                     SettingStripMenuItem_Click(null, null);
10042                 }
10043
10044                 // 取得失敗の場合は再試行する
10045                 var reloadTasks = new List<Task>();
10046
10047                 if (!tw.GetFollowersSuccess && SettingManager.Common.StartupFollowers)
10048                     reloadTasks.Add(this.RefreshFollowerIdsAsync());
10049
10050                 if (!tw.GetNoRetweetSuccess)
10051                     reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
10052
10053                 if (this.tw.Configuration.PhotoSizeLimit == 0)
10054                     reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
10055
10056                 await Task.WhenAll(reloadTasks);
10057             }
10058
10059             _initial = false;
10060
10061             TimerTimeline.Enabled = true;
10062         }
10063
10064         private async Task doGetFollowersMenu()
10065         {
10066             await this.RefreshFollowerIdsAsync();
10067             await this.DispSelectedPost(true);
10068         }
10069
10070         private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
10071         {
10072             await this.doGetFollowersMenu();
10073         }
10074
10075         private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
10076         {
10077             doReTweetUnofficial();
10078         }
10079
10080         private async Task doReTweetOfficial(bool isConfirm)
10081         {
10082             //公式RT
10083             if (this.ExistCurrentPost)
10084             {
10085                 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
10086                 {
10087                     if (this._curPost.IsProtect)
10088                         MessageBox.Show("Protected.");
10089
10090                     _DoFavRetweetFlags = false;
10091                     return;
10092                 }
10093                 if (_curList.SelectedIndices.Count > 15)
10094                 {
10095                     MessageBox.Show(Properties.Resources.RetweetLimitText);
10096                     _DoFavRetweetFlags = false;
10097                     return;
10098                 }
10099                 else if (_curList.SelectedIndices.Count > 1)
10100                 {
10101                     string QuestionText = Properties.Resources.RetweetQuestion2;
10102                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
10103                     switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
10104                     {
10105                         case DialogResult.Cancel:
10106                         case DialogResult.No:
10107                             _DoFavRetweetFlags = false;
10108                             return;
10109                     }
10110                 }
10111                 else
10112                 {
10113                     if (!SettingManager.Common.RetweetNoConfirm)
10114                     {
10115                         string Questiontext = Properties.Resources.RetweetQuestion1;
10116                         if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
10117                         if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
10118                         {
10119                             _DoFavRetweetFlags = false;
10120                             return;
10121                         }
10122                     }
10123                 }
10124
10125                 var statusIds = new List<long>();
10126                 foreach (int idx in _curList.SelectedIndices)
10127                 {
10128                     PostClass post = GetCurTabPost(idx);
10129                     if (post.CanRetweetBy(this.twitterApi.CurrentUserId))
10130                         statusIds.Add(post.StatusId);
10131                 }
10132
10133                 await this.RetweetAsync(statusIds);
10134             }
10135         }
10136
10137         private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
10138         {
10139             await this.doReTweetOfficial(true);
10140         }
10141
10142         private async Task FavoritesRetweetOfficial()
10143         {
10144             if (!this.ExistCurrentPost) return;
10145             _DoFavRetweetFlags = true;
10146             var retweetTask = this.doReTweetOfficial(true);
10147             if (_DoFavRetweetFlags)
10148             {
10149                 _DoFavRetweetFlags = false;
10150                 var favoriteTask = this.FavoriteChange(true, false);
10151
10152                 await Task.WhenAll(retweetTask, favoriteTask);
10153             }
10154             else
10155             {
10156                 await retweetTask;
10157             }
10158         }
10159
10160         private async Task FavoritesRetweetUnofficial()
10161         {
10162             if (this.ExistCurrentPost && !_curPost.IsDm)
10163             {
10164                 _DoFavRetweetFlags = true;
10165                 var favoriteTask = this.FavoriteChange(true);
10166                 if (!_curPost.IsProtect && _DoFavRetweetFlags)
10167                 {
10168                     _DoFavRetweetFlags = false;
10169                     doReTweetUnofficial();
10170                 }
10171
10172                 await favoriteTask;
10173             }
10174         }
10175
10176         /// <summary>
10177         /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
10178         /// </summary>
10179         /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
10180         /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
10181         /// <returns>復元されたツイート本文</returns>
10182         internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
10183         {
10184             // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
10185
10186             // 通常の URL
10187             statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
10188             // メンション
10189             statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10190             // ハッシュタグ
10191             statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
10192
10193             // <br> 除去
10194             if (multiline)
10195                 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
10196             else
10197                 statusHtml = statusHtml.Replace("<br>", " ");
10198
10199             // &nbsp; は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
10200             // 現状では半角スペースの代用として &nbsp; を使用しているため U+0020 に置換します
10201             statusHtml = statusHtml.Replace("&nbsp;", " ");
10202
10203             return WebUtility.HtmlDecode(statusHtml);
10204         }
10205
10206         private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
10207         {
10208             this.tweetDetailsView.DumpPostClass = this.DumpPostClassToolStripMenuItem.Checked;
10209
10210             if (_curPost != null)
10211                 await this.DispSelectedPost(true);
10212         }
10213
10214         private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
10215         {
10216             if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
10217                 DebugModeToolStripMenuItem.Visible = true;
10218             else
10219                 DebugModeToolStripMenuItem.Visible = false;
10220         }
10221
10222         private void UrlMultibyteSplitMenuItem_CheckedChanged(object sender, EventArgs e)
10223         {
10224             this.urlMultibyteSplit = ((ToolStripMenuItem)sender).Checked;
10225         }
10226
10227         private void PreventSmsCommandMenuItem_CheckedChanged(object sender, EventArgs e)
10228         {
10229             this.preventSmsCommand = ((ToolStripMenuItem)sender).Checked;
10230         }
10231
10232         private void UrlAutoShortenMenuItem_CheckedChanged(object sender, EventArgs e)
10233         {
10234             SettingManager.Common.UrlConvertAuto = ((ToolStripMenuItem)sender).Checked;
10235         }
10236
10237         private void IdeographicSpaceToSpaceMenuItem_Click(object sender, EventArgs e)
10238         {
10239             SettingManager.Common.WideSpaceConvert = ((ToolStripMenuItem)sender).Checked;
10240             ModifySettingCommon = true;
10241         }
10242
10243         private void FocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
10244         {
10245             SettingManager.Common.FocusLockToStatusText = ((ToolStripMenuItem)sender).Checked;
10246             ModifySettingCommon = true;
10247         }
10248
10249         private void PostModeMenuItem_DropDownOpening(object sender, EventArgs e)
10250         {
10251             UrlMultibyteSplitMenuItem.Checked = this.urlMultibyteSplit;
10252             PreventSmsCommandMenuItem.Checked = this.preventSmsCommand;
10253             UrlAutoShortenMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10254             IdeographicSpaceToSpaceMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10255             MultiLineMenuItem.Checked = SettingManager.Local.StatusMultiline;
10256             FocusLockMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10257         }
10258
10259         private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
10260         {
10261             UrlMultibyteSplitPullDownMenuItem.Checked = this.urlMultibyteSplit;
10262             PreventSmsCommandPullDownMenuItem.Checked = this.preventSmsCommand;
10263             UrlAutoShortenPullDownMenuItem.Checked = SettingManager.Common.UrlConvertAuto;
10264             IdeographicSpaceToSpacePullDownMenuItem.Checked = SettingManager.Common.WideSpaceConvert;
10265             MultiLinePullDownMenuItem.Checked = SettingManager.Local.StatusMultiline;
10266             FocusLockPullDownMenuItem.Checked = SettingManager.Common.FocusLockToStatusText;
10267         }
10268
10269         private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
10270         {
10271             if (TraceOutToolStripMenuItem.Checked)
10272                 MyCommon.TraceFlag = true;
10273             else
10274                 MyCommon.TraceFlag = false;
10275         }
10276
10277         private void TweenMain_Deactivate(object sender, EventArgs e)
10278         {
10279             //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
10280             this.StatusText_Leave(StatusText, System.EventArgs.Empty);
10281         }
10282
10283         private void TabRenameMenuItem_Click(object sender, EventArgs e)
10284         {
10285             if (string.IsNullOrEmpty(_rclickTabName)) return;
10286
10287             TabRename(_rclickTabName, out var _);
10288         }
10289
10290         private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
10291         {
10292             await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
10293         }
10294
10295         private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
10296         {
10297             await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
10298         }
10299
10300         private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
10301         {
10302             TwitterApiStatus apiStatus;
10303
10304             using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
10305             {
10306                 var cancellationToken = dialog.EnableCancellation();
10307
10308                 try
10309                 {
10310                     var task = this.tw.GetInfoApi();
10311                     apiStatus = await dialog.WaitForAsync(this, task);
10312                 }
10313                 catch (WebApiException)
10314                 {
10315                     apiStatus = null;
10316                 }
10317
10318                 if (cancellationToken.IsCancellationRequested)
10319                     return;
10320
10321                 if (apiStatus == null)
10322                 {
10323                     MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
10324                     return;
10325                 }
10326             }
10327
10328             using (var apiDlg = new ApiInfoDialog())
10329             {
10330                 apiDlg.ShowDialog(this);
10331             }
10332         }
10333
10334         private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
10335         {
10336             var id = _curPost?.ScreenName ?? "";
10337
10338             await this.FollowCommand(id);
10339         }
10340
10341         internal async Task FollowCommand(string id)
10342         {
10343             using (var inputName = new InputTabName())
10344             {
10345                 inputName.FormTitle = "Follow";
10346                 inputName.FormDescription = Properties.Resources.FRMessage1;
10347                 inputName.TabName = id;
10348
10349                 if (inputName.ShowDialog(this) != DialogResult.OK)
10350                     return;
10351                 if (string.IsNullOrWhiteSpace(inputName.TabName))
10352                     return;
10353
10354                 id = inputName.TabName.Trim();
10355             }
10356
10357             using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
10358             {
10359                 try
10360                 {
10361                     var task = this.twitterApi.FriendshipsCreate(id).IgnoreResponse();
10362                     await dialog.WaitForAsync(this, task);
10363                 }
10364                 catch (WebApiException ex)
10365                 {
10366                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10367                     return;
10368                 }
10369             }
10370
10371             MessageBox.Show(Properties.Resources.FRMessage3);
10372         }
10373
10374         private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
10375         {
10376             var id = _curPost?.ScreenName ?? "";
10377
10378             await this.RemoveCommand(id, false);
10379         }
10380
10381         internal async Task RemoveCommand(string id, bool skipInput)
10382         {
10383             if (!skipInput)
10384             {
10385                 using (var inputName = new InputTabName())
10386                 {
10387                     inputName.FormTitle = "Unfollow";
10388                     inputName.FormDescription = Properties.Resources.FRMessage1;
10389                     inputName.TabName = id;
10390
10391                     if (inputName.ShowDialog(this) != DialogResult.OK)
10392                         return;
10393                     if (string.IsNullOrWhiteSpace(inputName.TabName))
10394                         return;
10395
10396                     id = inputName.TabName.Trim();
10397                 }
10398             }
10399
10400             using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
10401             {
10402                 try
10403                 {
10404                     var task = this.twitterApi.FriendshipsDestroy(id).IgnoreResponse();
10405                     await dialog.WaitForAsync(this, task);
10406                 }
10407                 catch (WebApiException ex)
10408                 {
10409                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
10410                     return;
10411                 }
10412             }
10413
10414             MessageBox.Show(Properties.Resources.FRMessage3);
10415         }
10416
10417         private async void FriendshipMenuItem_Click(object sender, EventArgs e)
10418         {
10419             var id = _curPost?.ScreenName ?? "";
10420
10421             await this.ShowFriendship(id);
10422         }
10423
10424         internal async Task ShowFriendship(string id)
10425         {
10426             using (var inputName = new InputTabName())
10427             {
10428                 inputName.FormTitle = "Show Friendships";
10429                 inputName.FormDescription = Properties.Resources.FRMessage1;
10430                 inputName.TabName = id;
10431
10432                 if (inputName.ShowDialog(this) != DialogResult.OK)
10433                     return;
10434                 if (string.IsNullOrWhiteSpace(inputName.TabName))
10435                     return;
10436
10437                 id = inputName.TabName.Trim();
10438             }
10439
10440             bool isFollowing, isFollowed;
10441
10442             using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10443             {
10444                 var cancellationToken = dialog.EnableCancellation();
10445
10446                 try
10447                 {
10448                     var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10449                     var friendship = await dialog.WaitForAsync(this, task);
10450
10451                     isFollowing = friendship.Relationship.Source.Following;
10452                     isFollowed = friendship.Relationship.Source.FollowedBy;
10453                 }
10454                 catch (WebApiException ex)
10455                 {
10456                     if (!cancellationToken.IsCancellationRequested)
10457                         MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10458                     return;
10459                 }
10460
10461                 if (cancellationToken.IsCancellationRequested)
10462                     return;
10463             }
10464
10465             string result = "";
10466             if (isFollowing)
10467             {
10468                 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
10469             }
10470             else
10471             {
10472                 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
10473             }
10474             if (isFollowed)
10475             {
10476                 result += Properties.Resources.GetFriendshipInfo3;
10477             }
10478             else
10479             {
10480                 result += Properties.Resources.GetFriendshipInfo4;
10481             }
10482             result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
10483             MessageBox.Show(result);
10484         }
10485
10486         internal async Task ShowFriendship(string[] ids)
10487         {
10488             foreach (string id in ids)
10489             {
10490                 bool isFollowing, isFollowed;
10491
10492                 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
10493                 {
10494                     var cancellationToken = dialog.EnableCancellation();
10495
10496                     try
10497                     {
10498                         var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
10499                         var friendship = await dialog.WaitForAsync(this, task);
10500
10501                         isFollowing = friendship.Relationship.Source.Following;
10502                         isFollowed = friendship.Relationship.Source.FollowedBy;
10503                     }
10504                     catch (WebApiException ex)
10505                     {
10506                         if (!cancellationToken.IsCancellationRequested)
10507                             MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
10508                         return;
10509                     }
10510
10511                     if (cancellationToken.IsCancellationRequested)
10512                         return;
10513                 }
10514
10515                 string result = "";
10516                 string ff = "";
10517
10518                 ff = "  ";
10519                 if (isFollowing)
10520                 {
10521                     ff += Properties.Resources.GetFriendshipInfo1;
10522                 }
10523                 else
10524                 {
10525                     ff += Properties.Resources.GetFriendshipInfo2;
10526                 }
10527
10528                 ff += System.Environment.NewLine + "  ";
10529                 if (isFollowed)
10530                 {
10531                     ff += Properties.Resources.GetFriendshipInfo3;
10532                 }
10533                 else
10534                 {
10535                     ff += Properties.Resources.GetFriendshipInfo4;
10536                 }
10537                 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
10538                 if (isFollowing)
10539                 {
10540                     if (MessageBox.Show(
10541                         Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
10542                         MessageBoxButtons.YesNo,
10543                         MessageBoxIcon.Question,
10544                         MessageBoxDefaultButton.Button2) == DialogResult.Yes)
10545                     {
10546                         await this.RemoveCommand(id, true);
10547                     }
10548                 }
10549                 else
10550                 {
10551                     MessageBox.Show(result);
10552                 }
10553             }
10554         }
10555
10556         private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
10557         {
10558             await this.doShowUserStatus(tw.Username, false);
10559             //if (!string.IsNullOrEmpty(tw.UserInfoXml))
10560             //{
10561             //    doShowUserStatus(tw.Username, false);
10562             //}
10563             //else
10564             //{
10565             //    MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
10566             //    return;
10567             //}
10568         }
10569
10570         // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
10571         // URLから切り出した文字列を渡す
10572
10573         public bool IsTwitterId(string name)
10574         {
10575             if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
10576                 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
10577             else
10578                 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
10579         }
10580
10581         private void doQuoteOfficial()
10582         {
10583             if (this.ExistCurrentPost)
10584             {
10585                 if (_curPost.IsDm ||
10586                     !StatusText.Enabled) return;
10587
10588                 if (_curPost.IsProtect)
10589                 {
10590                     MessageBox.Show("Protected.");
10591                     return;
10592                 }
10593
10594                 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10595
10596                 StatusText.Text += " " + MyCommon.GetStatusUrl(_curPost);
10597
10598                 this.inReplyTo = null;
10599
10600                 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10601                 StatusText.Focus();
10602             }
10603         }
10604
10605         private void doReTweetUnofficial()
10606         {
10607             //RT @id:内容
10608             if (this.ExistCurrentPost)
10609             {
10610                 if (_curPost.IsDm || !StatusText.Enabled)
10611                     return;
10612
10613                 if (_curPost.IsProtect)
10614                 {
10615                     MessageBox.Show("Protected.");
10616                     return;
10617                 }
10618                 string rtdata = _curPost.Text;
10619                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
10620
10621                 var selection = (this.StatusText.SelectionStart, this.StatusText.SelectionLength);
10622
10623                 StatusText.Text += " RT @" + _curPost.ScreenName + ": " + rtdata;
10624
10625                 // 投稿時に in_reply_to_status_id を付加する
10626                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
10627                 var inReplyToScreenName = this._curPost.ScreenName;
10628                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
10629
10630                 (this.StatusText.SelectionStart, this.StatusText.SelectionLength) = selection;
10631                 StatusText.Focus();
10632             }
10633         }
10634
10635         private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
10636         {
10637             doQuoteOfficial();
10638         }
10639
10640         private void SearchButton_Click(object sender, EventArgs e)
10641         {
10642             //公式検索
10643             Control pnl = ((Control)sender).Parent;
10644             if (pnl == null) return;
10645             string tbName = pnl.Parent.Text;
10646             var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
10647             ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
10648             ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
10649             cmb.Text = cmb.Text.Trim();
10650             // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
10651             bool Quote = false;
10652             StringBuilder buf = new StringBuilder();
10653             char[] c = cmb.Text.ToCharArray();
10654             for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
10655             {
10656                 if (cnt > cmb.Text.Length - 4)
10657                 {
10658                     buf.Append(cmb.Text.Substring(cnt));
10659                     break;
10660                 }
10661                 if (c[cnt] == '"')
10662                 {
10663                     Quote = !Quote;
10664                 }
10665                 else
10666                 {
10667                     if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
10668                     {
10669                         buf.Append(" OR ");
10670                         cnt += 3;
10671                         continue;
10672                     }
10673                 }
10674                 buf.Append(c[cnt]);
10675             }
10676             cmb.Text = buf.ToString();
10677
10678             var listView = (DetailsListView)pnl.Parent.Tag;
10679
10680             var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
10681
10682             tb.SearchWords = cmb.Text;
10683             tb.SearchLang = cmbLang.Text;
10684             if (string.IsNullOrEmpty(cmb.Text))
10685             {
10686                 listView.Focus();
10687                 SaveConfigsTabs();
10688                 return;
10689             }
10690             if (queryChanged)
10691             {
10692                 int idx = cmb.Items.IndexOf(tb.SearchWords);
10693                 if (idx > -1) cmb.Items.RemoveAt(idx);
10694                 cmb.Items.Insert(0, tb.SearchWords);
10695                 cmb.Text = tb.SearchWords;
10696                 cmb.SelectAll();
10697                 this.PurgeListViewItemCache();
10698                 listView.VirtualListSize = 0;
10699                 _statuses.ClearTabIds(tbName);
10700                 SaveConfigsTabs();   //検索条件の保存
10701             }
10702
10703             this.GetPublicSearchAsync(tb);
10704             listView.Focus();
10705         }
10706
10707         private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
10708         {
10709             //もっと前を取得
10710             await this.DoRefreshMore();
10711         }
10712
10713         /// <summary>
10714         /// 指定されたタブのListTabにおける位置を返します
10715         /// </summary>
10716         /// <remarks>
10717         /// 非表示のタブについて -1 が返ることを常に考慮して下さい
10718         /// </remarks>
10719         public int GetTabPageIndex(string tabName)
10720         {
10721             var index = 0;
10722             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
10723             {
10724                 if (tabPage.Text == tabName)
10725                     return index;
10726
10727                 index++;
10728             }
10729
10730             return -1;
10731         }
10732
10733         private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
10734         {
10735             if (_statuses.RemovedTab.Count == 0)
10736             {
10737                 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
10738                 return;
10739             }
10740             else
10741             {
10742                 DetailsListView listView = null;
10743
10744                 TabModel tb = _statuses.RemovedTab.Pop();
10745                 if (tb.TabType == MyCommon.TabUsageType.Related)
10746                 {
10747                     var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
10748                     if (relatedTab != null)
10749                     {
10750                         // 関連発言なら既存のタブを置き換える
10751                         tb.TabName = relatedTab.TabName;
10752                         this.ClearTab(tb.TabName, false);
10753                         _statuses.Tabs[tb.TabName] = tb;
10754
10755                         for (int i = 0; i < ListTab.TabPages.Count; i++)
10756                         {
10757                             var tabPage = ListTab.TabPages[i];
10758                             if (tb.TabName == tabPage.Text)
10759                             {
10760                                 listView = (DetailsListView)tabPage.Tag;
10761                                 ListTab.SelectedIndex = i;
10762                                 break;
10763                             }
10764                         }
10765                     }
10766                     else
10767                     {
10768                         const string TabName = "Related Tweets";
10769                         string renamed = TabName;
10770                         for (int i = 2; i <= 100; i++)
10771                         {
10772                             if (!_statuses.ContainsTab(renamed)) break;
10773                             renamed = TabName + i;
10774                         }
10775                         tb.TabName = renamed;
10776
10777                         _statuses.AddTab(tb);
10778                         AddNewTab(tb, startup: false);
10779
10780                         var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10781                         listView = (DetailsListView)tabPage.Tag;
10782                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10783                     }
10784                 }
10785                 else
10786                 {
10787                     string renamed = tb.TabName;
10788                     for (int i = 1; i < int.MaxValue; i++)
10789                     {
10790                         if (!_statuses.ContainsTab(renamed)) break;
10791                         renamed = tb.TabName + "(" + i + ")";
10792                     }
10793                     tb.TabName = renamed;
10794
10795                     _statuses.AddTab(tb);
10796                     AddNewTab(tb, startup: false);
10797
10798                     var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
10799                     listView = (DetailsListView)tabPage.Tag;
10800                     ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
10801                 }
10802                 SaveConfigsTabs();
10803
10804                 if (listView != null)
10805                 {
10806                     using (ControlTransaction.Update(listView))
10807                     {
10808                         listView.VirtualListSize = tb.AllCount;
10809                     }
10810                 }
10811             }
10812         }
10813
10814         private async Task doMoveToRTHome()
10815         {
10816             if (_curList.SelectedIndices.Count > 0)
10817             {
10818                 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
10819                 if (post.RetweetedId != null)
10820                 {
10821                     await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
10822                 }
10823             }
10824         }
10825
10826         private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
10827         {
10828             await this.doMoveToRTHome();
10829         }
10830
10831         private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
10832         {
10833             var screenName = this._curPost?.ScreenName;
10834             if (screenName != null)
10835                 this.ListManageUserContext(screenName);
10836         }
10837
10838         public void ListManageUserContext(string screenName)
10839         {
10840             using (var listSelectForm = new MyLists(screenName, this.twitterApi))
10841             {
10842                 listSelectForm.ShowDialog(this);
10843             }
10844         }
10845
10846         private void SearchControls_Enter(object sender, EventArgs e)
10847         {
10848             Control pnl = (Control)sender;
10849             foreach (Control ctl in pnl.Controls)
10850             {
10851                 ctl.TabStop = true;
10852             }
10853         }
10854
10855         private void SearchControls_Leave(object sender, EventArgs e)
10856         {
10857             Control pnl = (Control)sender;
10858             foreach (Control ctl in pnl.Controls)
10859             {
10860                 ctl.TabStop = false;
10861             }
10862         }
10863
10864         private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
10865         {
10866             if (ListTab.SelectedTab != null)
10867             {
10868                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
10869                 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
10870             }
10871         }
10872
10873         private void StatusLabel_DoubleClick(object sender, EventArgs e)
10874         {
10875             MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
10876         }
10877
10878         private void HashManageMenuItem_Click(object sender, EventArgs e)
10879         {
10880             DialogResult rslt = DialogResult.Cancel;
10881             try
10882             {
10883                 rslt = HashMgr.ShowDialog();
10884             }
10885             catch (Exception)
10886             {
10887                 return;
10888             }
10889             this.TopMost = SettingManager.Common.AlwaysTop;
10890             if (rslt == DialogResult.Cancel) return;
10891             if (!string.IsNullOrEmpty(HashMgr.UseHash))
10892             {
10893                 HashStripSplitButton.Text = HashMgr.UseHash;
10894                 HashTogglePullDownMenuItem.Checked = true;
10895                 HashToggleMenuItem.Checked = true;
10896             }
10897             else
10898             {
10899                 HashStripSplitButton.Text = "#[-]";
10900                 HashTogglePullDownMenuItem.Checked = false;
10901                 HashToggleMenuItem.Checked = false;
10902             }
10903             //if (HashMgr.IsInsert && HashMgr.UseHash != "")
10904             //{
10905             //    int sidx = StatusText.SelectionStart;
10906             //    string hash = HashMgr.UseHash + " ";
10907             //    if (sidx > 0)
10908             //    {
10909             //        if (StatusText.Text.Substring(sidx - 1, 1) != " ")
10910             //            hash = " " + hash;
10911             //    }
10912             //    StatusText.Text = StatusText.Text.Insert(sidx, hash);
10913             //    sidx += hash.Length;
10914             //    StatusText.SelectionStart = sidx;
10915             //    StatusText.Focus();
10916             //}
10917             ModifySettingCommon = true;
10918             this.StatusText_TextChanged(null, null);
10919         }
10920
10921         private void HashToggleMenuItem_Click(object sender, EventArgs e)
10922         {
10923             HashMgr.ToggleHash();
10924             if (!string.IsNullOrEmpty(HashMgr.UseHash))
10925             {
10926                 HashStripSplitButton.Text = HashMgr.UseHash;
10927                 HashToggleMenuItem.Checked = true;
10928                 HashTogglePullDownMenuItem.Checked = true;
10929             }
10930             else
10931             {
10932                 HashStripSplitButton.Text = "#[-]";
10933                 HashToggleMenuItem.Checked = false;
10934                 HashTogglePullDownMenuItem.Checked = false;
10935             }
10936             ModifySettingCommon = true;
10937             this.StatusText_TextChanged(null, null);
10938         }
10939
10940         private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
10941         {
10942             HashToggleMenuItem_Click(null, null);
10943         }
10944
10945         public void SetPermanentHashtag(string hashtag)
10946         {
10947             HashMgr.SetPermanentHash("#" + hashtag);
10948             HashStripSplitButton.Text = HashMgr.UseHash;
10949             HashTogglePullDownMenuItem.Checked = true;
10950             HashToggleMenuItem.Checked = true;
10951             //使用ハッシュタグとして設定
10952             ModifySettingCommon = true;
10953         }
10954
10955         private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
10956         {
10957             if (ListTab.SelectedTab == null) return;
10958             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
10959             if (!this.ExistCurrentPost)
10960             {
10961                 this.ReplyOpMenuItem.Enabled = false;
10962                 this.ReplyAllOpMenuItem.Enabled = false;
10963                 this.DmOpMenuItem.Enabled = false;
10964                 this.ShowProfMenuItem.Enabled = false;
10965                 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
10966                 this.ListManageMenuItem.Enabled = false;
10967                 this.OpenFavOpMenuItem.Enabled = false;
10968                 this.CreateTabRuleOpMenuItem.Enabled = false;
10969                 this.CreateIdRuleOpMenuItem.Enabled = false;
10970                 this.CreateSourceRuleOpMenuItem.Enabled = false;
10971                 this.ReadOpMenuItem.Enabled = false;
10972                 this.UnreadOpMenuItem.Enabled = false;
10973             }
10974             else
10975             {
10976                 this.ReplyOpMenuItem.Enabled = true;
10977                 this.ReplyAllOpMenuItem.Enabled = true;
10978                 this.DmOpMenuItem.Enabled = true;
10979                 this.ShowProfMenuItem.Enabled = true;
10980                 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
10981                 this.ListManageMenuItem.Enabled = true;
10982                 this.OpenFavOpMenuItem.Enabled = true;
10983                 this.CreateTabRuleOpMenuItem.Enabled = true;
10984                 this.CreateIdRuleOpMenuItem.Enabled = true;
10985                 this.CreateSourceRuleOpMenuItem.Enabled = true;
10986                 this.ReadOpMenuItem.Enabled = true;
10987                 this.UnreadOpMenuItem.Enabled = true;
10988             }
10989
10990             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
10991             {
10992                 this.FavOpMenuItem.Enabled = false;
10993                 this.UnFavOpMenuItem.Enabled = false;
10994                 this.OpenStatusOpMenuItem.Enabled = false;
10995                 this.OpenFavotterOpMenuItem.Enabled = false;
10996                 this.ShowRelatedStatusesMenuItem2.Enabled = false;
10997                 this.RtOpMenuItem.Enabled = false;
10998                 this.RtUnOpMenuItem.Enabled = false;
10999                 this.QtOpMenuItem.Enabled = false;
11000                 this.FavoriteRetweetMenuItem.Enabled = false;
11001                 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11002             }
11003             else
11004             {
11005                 this.FavOpMenuItem.Enabled = true;
11006                 this.UnFavOpMenuItem.Enabled = true;
11007                 this.OpenStatusOpMenuItem.Enabled = true;
11008                 this.OpenFavotterOpMenuItem.Enabled = true;
11009                 this.ShowRelatedStatusesMenuItem2.Enabled = true;  //PublicSearchの時問題出るかも
11010
11011                 if (!_curPost.CanRetweetBy(this.twitterApi.CurrentUserId))
11012                 {
11013                     this.RtOpMenuItem.Enabled = false;
11014                     this.RtUnOpMenuItem.Enabled = false;
11015                     this.QtOpMenuItem.Enabled = false;
11016                     this.FavoriteRetweetMenuItem.Enabled = false;
11017                     this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
11018                 }
11019                 else
11020                 {
11021                     this.RtOpMenuItem.Enabled = true;
11022                     this.RtUnOpMenuItem.Enabled = true;
11023                     this.QtOpMenuItem.Enabled = true;
11024                     this.FavoriteRetweetMenuItem.Enabled = true;
11025                     this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
11026                 }
11027             }
11028
11029             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
11030             {
11031                 this.RefreshPrevOpMenuItem.Enabled = true;
11032             }
11033             else
11034             {
11035                 this.RefreshPrevOpMenuItem.Enabled = false;
11036             }
11037             if (!this.ExistCurrentPost
11038                 || _curPost.InReplyToStatusId == null)
11039             {
11040                 OpenRepSourceOpMenuItem.Enabled = false;
11041             }
11042             else
11043             {
11044                 OpenRepSourceOpMenuItem.Enabled = true;
11045             }
11046             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
11047             {
11048                 OpenRterHomeMenuItem.Enabled = false;
11049             }
11050             else
11051             {
11052                 OpenRterHomeMenuItem.Enabled = true;
11053             }
11054
11055             if (this.ExistCurrentPost)
11056             {
11057                 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
11058             }
11059         }
11060
11061         private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
11062         {
11063             ContextMenuTabProperty_Opening(sender, null);
11064         }
11065
11066         public Twitter TwitterInstance
11067         {
11068             get { return tw; }
11069         }
11070
11071         private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
11072         {
11073             if (this._initialLayout)
11074                 return;
11075
11076             int splitterDistance;
11077             switch (this.WindowState)
11078             {
11079                 case FormWindowState.Normal:
11080                     splitterDistance = this.SplitContainer3.SplitterDistance;
11081                     break;
11082                 case FormWindowState.Maximized:
11083                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
11084                     var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
11085                     splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
11086                     splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
11087                     break;
11088                 default:
11089                     return;
11090             }
11091
11092             this._mySpDis3 = splitterDistance;
11093             this.ModifySettingLocal = true;
11094         }
11095
11096         private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
11097         {
11098             if (_statuses.RemovedTab.Count == 0)
11099             {
11100                 UndoRemoveTabMenuItem.Enabled = false;
11101             }
11102             else
11103             {
11104                 UndoRemoveTabMenuItem.Enabled = true;
11105             }
11106             if (ListTab.SelectedTab != null)
11107             {
11108                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
11109                     PublicSearchQueryMenuItem.Enabled = true;
11110                 else
11111                     PublicSearchQueryMenuItem.Enabled = false;
11112             }
11113             else
11114             {
11115                 PublicSearchQueryMenuItem.Enabled = false;
11116             }
11117             if (!this.ExistCurrentPost)
11118             {
11119                 this.CopySTOTMenuItem.Enabled = false;
11120                 this.CopyURLMenuItem.Enabled = false;
11121                 this.CopyUserIdStripMenuItem.Enabled = false;
11122             }
11123             else
11124             {
11125                 this.CopySTOTMenuItem.Enabled = true;
11126                 this.CopyURLMenuItem.Enabled = true;
11127                 this.CopyUserIdStripMenuItem.Enabled = true;
11128                 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
11129                 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
11130             }
11131         }
11132
11133         private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
11134         {
11135             SetNotifyIconText();
11136         }
11137
11138         private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
11139         {
11140             var id = _curPost?.ScreenName ?? "";
11141
11142             await this.ShowUserStatus(id);
11143         }
11144
11145         private async Task doShowUserStatus(string id, bool ShowInputDialog)
11146         {
11147             TwitterUser user = null;
11148
11149             if (ShowInputDialog)
11150             {
11151                 using (var inputName = new InputTabName())
11152                 {
11153                     inputName.FormTitle = "Show UserStatus";
11154                     inputName.FormDescription = Properties.Resources.FRMessage1;
11155                     inputName.TabName = id;
11156
11157                     if (inputName.ShowDialog(this) != DialogResult.OK)
11158                         return;
11159                     if (string.IsNullOrWhiteSpace(inputName.TabName))
11160                         return;
11161
11162                     id = inputName.TabName.Trim();
11163                 }
11164             }
11165
11166             using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
11167             {
11168                 var cancellationToken = dialog.EnableCancellation();
11169
11170                 try
11171                 {
11172                     var task = this.twitterApi.UsersShow(id);
11173                     user = await dialog.WaitForAsync(this, task);
11174                 }
11175                 catch (WebApiException ex)
11176                 {
11177                     if (!cancellationToken.IsCancellationRequested)
11178                         MessageBox.Show($"Err:{ex.Message}(UsersShow)");
11179                     return;
11180                 }
11181
11182                 if (cancellationToken.IsCancellationRequested)
11183                     return;
11184             }
11185
11186             await this.doShowUserStatus(user);
11187         }
11188
11189         private async Task doShowUserStatus(TwitterUser user)
11190         {
11191             using (var userDialog = new UserInfoDialog(this, this.twitterApi))
11192             {
11193                 var showUserTask = userDialog.ShowUserAsync(user);
11194                 userDialog.ShowDialog(this);
11195
11196                 this.Activate();
11197                 this.BringToFront();
11198
11199                 // ユーザー情報の表示が完了するまで userDialog を破棄しない
11200                 await showUserTask;
11201             }
11202         }
11203
11204         internal Task ShowUserStatus(string id, bool ShowInputDialog)
11205         {
11206             return this.doShowUserStatus(id, ShowInputDialog);
11207         }
11208
11209         internal Task ShowUserStatus(string id)
11210         {
11211             return this.doShowUserStatus(id, true);
11212         }
11213
11214         private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
11215         {
11216             if (_curPost != null)
11217             {
11218                 await this.ShowUserStatus(_curPost.ScreenName, false);
11219             }
11220         }
11221
11222         private async void RtCountMenuItem_Click(object sender, EventArgs e)
11223         {
11224             if (!this.ExistCurrentPost)
11225                 return;
11226
11227             var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11228             TwitterStatus status;
11229
11230             using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
11231             {
11232                 var cancellationToken = dialog.EnableCancellation();
11233
11234                 try
11235                 {
11236                     var task = this.twitterApi.StatusesShow(statusId);
11237                     status = await dialog.WaitForAsync(this, task);
11238                 }
11239                 catch (WebApiException ex)
11240                 {
11241                     if (!cancellationToken.IsCancellationRequested)
11242                         MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
11243                     return;
11244                 }
11245
11246                 if (cancellationToken.IsCancellationRequested)
11247                     return;
11248             }
11249
11250             MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
11251         }
11252
11253         private HookGlobalHotkey _hookGlobalHotkey;
11254         public TweenMain()
11255         {
11256             _hookGlobalHotkey = new HookGlobalHotkey(this);
11257
11258             // この呼び出しは、Windows フォーム デザイナで必要です。
11259             InitializeComponent();
11260
11261             // InitializeComponent() 呼び出しの後で初期化を追加します。
11262
11263             if (!this.DesignMode)
11264             {
11265                 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
11266                 this.StatusText.Dock = DockStyle.Fill;
11267             }
11268
11269             this.tweetDetailsView.Owner = this;
11270
11271             this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
11272             this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
11273             this.gh.NotifyClicked += GrowlHelper_Callback;
11274
11275             // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
11276             this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
11277
11278             this.ImageSelector.Visible = false;
11279             this.ImageSelector.Enabled = false;
11280             this.ImageSelector.FilePickDialog = OpenFileDialog1;
11281
11282             this.workerProgress = new Progress<string>(x => this.StatusLabel.Text = x);
11283
11284             this.ReplaceAppName();
11285             this.InitializeShortcuts();
11286         }
11287
11288         private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
11289         {
11290             if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
11291             {
11292                 //アイコン化
11293                 this.Visible = false;
11294             }
11295             else if (Form.ActiveForm == null)
11296             {
11297                 this.Visible = true;
11298                 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
11299                 this.Activate();
11300                 this.BringToFront();
11301                 this.StatusText.Focus();
11302             }
11303         }
11304
11305         private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
11306         {
11307             this.MultiLinePullDownMenuItem.PerformClick();
11308         }
11309
11310         public PostClass CurPost
11311         {
11312             get { return _curPost; }
11313         }
11314
11315 #region "画像投稿"
11316         private void ImageSelectMenuItem_Click(object sender, EventArgs e)
11317         {
11318             if (ImageSelector.Visible)
11319                 ImageSelector.EndSelection();
11320             else
11321                 ImageSelector.BeginSelection();
11322         }
11323
11324         private void SelectMedia_DragEnter(DragEventArgs e)
11325         {
11326             if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
11327             {
11328                 e.Effect = DragDropEffects.Copy;
11329                 return;
11330             }
11331             e.Effect = DragDropEffects.None;
11332         }
11333
11334         private void SelectMedia_DragDrop(DragEventArgs e)
11335         {
11336             this.Activate();
11337             this.BringToFront();
11338             ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
11339             StatusText.Focus();
11340         }
11341
11342         private void ImageSelector_BeginSelecting(object sender, EventArgs e)
11343         {
11344             TimelinePanel.Visible = false;
11345             TimelinePanel.Enabled = false;
11346         }
11347
11348         private void ImageSelector_EndSelecting(object sender, EventArgs e)
11349         {
11350             TimelinePanel.Visible = true;
11351             TimelinePanel.Enabled = true;
11352             ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
11353         }
11354
11355         private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
11356         {
11357             this.AllowDrop = false;
11358         }
11359
11360         private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
11361         {
11362             this.AllowDrop = true;
11363         }
11364
11365         private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
11366         {
11367             if (ImageSelector.Visible)
11368             {
11369                 ModifySettingCommon = true;
11370                 SaveConfigsAll(true);
11371
11372                 this.StatusText_TextChanged(null, null);
11373             }
11374         }
11375
11376         private void ImageSelector_VisibleChanged(object sender, EventArgs e)
11377         {
11378             this.StatusText_TextChanged(null, null);
11379         }
11380
11381         /// <summary>
11382         /// StatusTextでCtrl+Vが押下された時の処理
11383         /// </summary>
11384         private void ProcClipboardFromStatusTextWhenCtrlPlusV()
11385         {
11386             try
11387             {
11388                 if (Clipboard.ContainsText())
11389                 {
11390                     // clipboardにテキストがある場合は貼り付け処理
11391                     this.StatusText.Paste(Clipboard.GetText());
11392                 }
11393                 else if (Clipboard.ContainsImage())
11394                 {
11395                     // 画像があるので投稿処理を行う
11396                     if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
11397                                        Properties.Resources.PostPictureWarn4,
11398                                        MessageBoxButtons.OKCancel,
11399                                        MessageBoxIcon.Question,
11400                                        MessageBoxDefaultButton.Button2)
11401                                    == DialogResult.OK)
11402                     {
11403                         // clipboardから画像を取得
11404                         using (var image = Clipboard.GetImage())
11405                         {
11406                             this.ImageSelector.BeginSelection(image);
11407                         }
11408                     }
11409                 }
11410             }
11411             catch (ExternalException ex)
11412             {
11413                 MessageBox.Show(ex.Message);
11414             }
11415         }
11416 #endregion
11417
11418         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
11419         {
11420             using (ListManage form = new ListManage(tw))
11421             {
11422                 form.ShowDialog(this);
11423             }
11424         }
11425
11426         public bool ModifySettingCommon { get; set; }
11427         public bool ModifySettingLocal { get; set; }
11428         public bool ModifySettingAtId { get; set; }
11429
11430         private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
11431         {
11432             if (this.ExistCurrentPost && !_curPost.IsDm)
11433                 RtCountMenuItem.Enabled = true;
11434             else
11435                 RtCountMenuItem.Enabled = false;
11436
11437             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
11438             //    TinyUrlConvertToolStripMenuItem.Enabled = false;
11439             //else
11440             //    TinyUrlConvertToolStripMenuItem.Enabled = true;
11441         }
11442
11443         private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
11444         {
11445             CopyUserId();
11446         }
11447
11448         private void CopyUserId()
11449         {
11450             if (_curPost == null) return;
11451             string clstr = _curPost.ScreenName;
11452             try
11453             {
11454                 Clipboard.SetDataObject(clstr, false, 5, 100);
11455             }
11456             catch (Exception ex)
11457             {
11458                 MessageBox.Show(ex.Message);
11459             }
11460         }
11461
11462         private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
11463         {
11464             if (this.ExistCurrentPost && !_curPost.IsDm)
11465             {
11466                 try
11467                 {
11468                     await this.OpenRelatedTab(this._curPost);
11469                 }
11470                 catch (TabException ex)
11471                 {
11472                     MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
11473                 }
11474             }
11475         }
11476
11477         /// <summary>
11478         /// 指定されたツイートに対する関連発言タブを開きます
11479         /// </summary>
11480         /// <param name="statusId">表示するツイートのID</param>
11481         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11482         public async Task OpenRelatedTab(long statusId)
11483         {
11484             var post = this._statuses[statusId];
11485             if (post == null)
11486             {
11487                 try
11488                 {
11489                     post = await this.tw.GetStatusApi(false, statusId);
11490                 }
11491                 catch (WebApiException ex)
11492                 {
11493                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
11494                     return;
11495                 }
11496             }
11497
11498             await this.OpenRelatedTab(post);
11499         }
11500
11501         /// <summary>
11502         /// 指定されたツイートに対する関連発言タブを開きます
11503         /// </summary>
11504         /// <param name="post">表示する対象となるツイート</param>
11505         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
11506         private async Task OpenRelatedTab(PostClass post)
11507         {
11508             var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
11509             if (tabRelated != null)
11510             {
11511                 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
11512             }
11513
11514             var tabName = this._statuses.MakeTabName("Related Tweets");
11515
11516             tabRelated = new RelatedPostsTabModel(tabName, post);
11517             tabRelated.UnreadManage = false;
11518             tabRelated.Notify = false;
11519
11520             this._statuses.AddTab(tabRelated);
11521             this.AddNewTab(tabRelated, startup: false);
11522
11523             TabPage tabPage;
11524             for (int i = 0; i < this.ListTab.TabPages.Count; i++)
11525             {
11526                 tabPage = this.ListTab.TabPages[i];
11527                 if (tabName == tabPage.Text)
11528                 {
11529                     this.ListTab.SelectedIndex = i;
11530                     break;
11531                 }
11532             }
11533
11534             await this.GetRelatedTweetsAsync(tabRelated);
11535
11536             tabPage = this.ListTab.TabPages.Cast<TabPage>()
11537                 .FirstOrDefault(x => x.Text == tabRelated.TabName);
11538
11539             if (tabPage != null)
11540             {
11541                 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
11542
11543                 var listView = (DetailsListView)tabPage.Tag;
11544                 var targetPost = tabRelated.TargetPost;
11545                 var index = tabRelated.IndexOf(targetPost.RetweetedId ?? targetPost.StatusId);
11546
11547                 if (index != -1 && index < listView.Items.Count)
11548                 {
11549                     listView.SelectedIndices.Add(index);
11550                     listView.Items[index].Focused = true;
11551                 }
11552             }
11553         }
11554
11555         private void CacheInfoMenuItem_Click(object sender, EventArgs e)
11556         {
11557             StringBuilder buf = new StringBuilder();
11558             //buf.AppendFormat("キャッシュメモリ容量         : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
11559             //buf.AppendFormat("物理メモリ使用割合           : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
11560             buf.AppendFormat("キャッシュエントリ保持数     : {0}" + Environment.NewLine, IconCache.CacheCount);
11561             buf.AppendFormat("キャッシュエントリ破棄数     : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
11562             MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
11563         }
11564
11565         private void tw_UserIdChanged()
11566         {
11567             this.ModifySettingCommon = true;
11568         }
11569
11570 #region "Userstream"
11571         private async void tw_PostDeleted(object sender, PostDeletedEventArgs e)
11572         {
11573             try
11574             {
11575                 if (InvokeRequired && !IsDisposed)
11576                 {
11577                     await this.InvokeAsync(async () =>
11578                     {
11579                         this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
11580                         if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
11581                         {
11582                             this.PurgeListViewItemCache();
11583                             ((DetailsListView)_curTab.Tag).Update();
11584                             if (_curPost != null && _curPost.StatusId == e.StatusId)
11585                                 await this.DispSelectedPost(true);
11586                         }
11587                     });
11588                     return;
11589                 }
11590             }
11591             catch (ObjectDisposedException)
11592             {
11593                 return;
11594             }
11595             catch (InvalidOperationException)
11596             {
11597                 return;
11598             }
11599         }
11600
11601         private int userStreamsRefreshing = 0;
11602
11603         private async void tw_NewPostFromStream(object sender, EventArgs e)
11604         {
11605             if (SettingManager.Common.ReadOldPosts)
11606             {
11607                 _statuses.SetReadHomeTab(); //新着時未読クリア
11608             }
11609
11610             this._statuses.DistributePosts();
11611
11612             if (SettingManager.Common.UserstreamPeriod > 0) return;
11613
11614             // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
11615             if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
11616             {
11617                 try
11618                 {
11619                     await this.InvokeAsync(() => this.RefreshTimeline())
11620                         .ConfigureAwait(false);
11621                 }
11622                 finally
11623                 {
11624                     Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
11625                 }
11626             }
11627         }
11628
11629         private async void tw_UserStreamStarted(object sender, EventArgs e)
11630         {
11631             try
11632             {
11633                 if (InvokeRequired && !IsDisposed)
11634                 {
11635                     await this.InvokeAsync(() => this.tw_UserStreamStarted(sender, e));
11636                     return;
11637                 }
11638             }
11639             catch (ObjectDisposedException)
11640             {
11641                 return;
11642             }
11643             catch (InvalidOperationException)
11644             {
11645                 return;
11646             }
11647
11648             this.RefreshUserStreamsMenu();
11649             this.MenuItemUserStream.Enabled = true;
11650
11651             StatusLabel.Text = "UserStream Started.";
11652         }
11653
11654         private async void tw_UserStreamStopped(object sender, EventArgs e)
11655         {
11656             try
11657             {
11658                 if (InvokeRequired && !IsDisposed)
11659                 {
11660                     await this.InvokeAsync(() => this.tw_UserStreamStopped(sender, e));
11661                     return;
11662                 }
11663             }
11664             catch (ObjectDisposedException)
11665             {
11666                 return;
11667             }
11668             catch (InvalidOperationException)
11669             {
11670                 return;
11671             }
11672
11673             this.RefreshUserStreamsMenu();
11674             this.MenuItemUserStream.Enabled = true;
11675
11676             StatusLabel.Text = "UserStream Stopped.";
11677         }
11678
11679         private void RefreshUserStreamsMenu()
11680         {
11681             if (this.tw.UserStreamActive)
11682             {
11683                 this.MenuItemUserStream.Text = "&UserStream ▶";
11684                 this.StopToolStripMenuItem.Text = "&Stop";
11685             }
11686             else
11687             {
11688                 this.MenuItemUserStream.Text = "&UserStream ■";
11689                 this.StopToolStripMenuItem.Text = "&Start";
11690             }
11691         }
11692
11693         private async void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
11694         {
11695             try
11696             {
11697                 if (InvokeRequired && !IsDisposed)
11698                 {
11699                     await this.InvokeAsync(() => this.tw_UserStreamEventArrived(sender, e));
11700                     return;
11701                 }
11702             }
11703             catch (ObjectDisposedException)
11704             {
11705                 return;
11706             }
11707             catch (InvalidOperationException)
11708             {
11709                 return;
11710             }
11711             var ev = e.EventData;
11712             StatusLabel.Text = "Event: " + ev.Event;
11713             //if (ev.Event == "favorite")
11714             //{
11715             //    NotifyFavorite(ev);
11716             //}
11717             NotifyEvent(ev);
11718             if (ev.Event == "favorite" || ev.Event == "unfavorite")
11719             {
11720                 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
11721                 {
11722                     this.PurgeListViewItemCache();
11723                     ((DetailsListView)_curTab.Tag).Update();
11724                 }
11725                 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
11726                 {
11727                     var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
11728                     favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
11729                 }
11730             }
11731         }
11732
11733         private void NotifyEvent(Twitter.FormattedEvent ev)
11734         {
11735             //新着通知 
11736             if (BalloonRequired(ev))
11737             {
11738                 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11739                 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
11740                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
11741                 StringBuilder title = new StringBuilder();
11742                 if (SettingManager.Common.DispUsername)
11743                 {
11744                     title.Append(tw.Username);
11745                     title.Append(" - ");
11746                 }
11747                 else
11748                 {
11749                     //title.Clear();
11750                 }
11751                 title.Append(Application.ProductName);
11752                 title.Append(" [");
11753                 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
11754                 title.Append("] by ");
11755                 if (!string.IsNullOrEmpty(ev.Username))
11756                 {
11757                     title.Append(ev.Username);
11758                 }
11759                 else
11760                 {
11761                     //title.Append("");
11762                 }
11763                 string text;
11764                 if (!string.IsNullOrEmpty(ev.Target))
11765                 {
11766                     //NotifyIcon1.BalloonTipText = ev.Target;
11767                     text = ev.Target;
11768                 }
11769                 else
11770                 {
11771                     //NotifyIcon1.BalloonTipText = " ";
11772                     text = " ";
11773                 }
11774                 //NotifyIcon1.ShowBalloonTip(500);
11775                 if (SettingManager.Common.IsUseNotifyGrowl)
11776                 {
11777                     gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
11778                               ev.Id.ToString(), title.ToString(), text);
11779                 }
11780                 else
11781                 {
11782                     NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
11783                     NotifyIcon1.BalloonTipTitle = title.ToString();
11784                     NotifyIcon1.BalloonTipText = text;
11785                     NotifyIcon1.ShowBalloonTip(500);
11786                 }
11787             }
11788
11789             //サウンド再生
11790             string snd = SettingManager.Common.EventSoundFile;
11791             if (!_initial && SettingManager.Common.PlaySound && !string.IsNullOrEmpty(snd))
11792             {
11793                 if ((ev.Eventtype & SettingManager.Common.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
11794                 {
11795                     try
11796                     {
11797                         string dir = Application.StartupPath;
11798                         if (Directory.Exists(Path.Combine(dir, "Sounds")))
11799                         {
11800                             dir = Path.Combine(dir, "Sounds");
11801                         }
11802                         using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
11803                         {
11804                             player.Play();
11805                         }
11806                     }
11807                     catch (Exception)
11808                     {
11809                     }
11810                 }
11811             }
11812         }
11813
11814         private void StopToolStripMenuItem_Click(object sender, EventArgs e)
11815         {
11816             MenuItemUserStream.Enabled = false;
11817             if (StopRefreshAllMenuItem.Checked)
11818             {
11819                 StopRefreshAllMenuItem.Checked = false;
11820                 return;
11821             }
11822             if (this.tw.UserStreamActive)
11823             {
11824                 tw.StopUserStream();
11825             }
11826             else
11827             {
11828                 tw.StartUserStream();
11829             }
11830         }
11831
11832         private static string inputTrack = "";
11833
11834         private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
11835         {
11836             if (TrackToolStripMenuItem.Checked)
11837             {
11838                 using (InputTabName inputForm = new InputTabName())
11839                 {
11840                     inputForm.TabName = inputTrack;
11841                     inputForm.FormTitle = "Input track word";
11842                     inputForm.FormDescription = "Track word";
11843                     if (inputForm.ShowDialog() != DialogResult.OK)
11844                     {
11845                         TrackToolStripMenuItem.Checked = false;
11846                         return;
11847                     }
11848                     inputTrack = inputForm.TabName.Trim();
11849                 }
11850                 if (!inputTrack.Equals(tw.TrackWord))
11851                 {
11852                     tw.TrackWord = inputTrack;
11853                     this.ModifySettingCommon = true;
11854                     TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
11855                     tw.ReconnectUserStream();
11856                 }
11857             }
11858             else
11859             {
11860                 tw.TrackWord = "";
11861                 tw.ReconnectUserStream();
11862             }
11863             this.ModifySettingCommon = true;
11864         }
11865
11866         private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
11867         {
11868             tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
11869             this.ModifySettingCommon = true;
11870             tw.ReconnectUserStream();
11871         }
11872
11873         private void EventViewerMenuItem_Click(object sender, EventArgs e)
11874         {
11875             if (evtDialog == null || evtDialog.IsDisposed)
11876             {
11877                 evtDialog = null;
11878                 evtDialog = new EventViewerDialog();
11879                 evtDialog.Owner = this;
11880                 //親の中央に表示
11881                 Point pos = evtDialog.Location;
11882                 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
11883                 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
11884                 evtDialog.Location = pos;
11885             }
11886             evtDialog.EventSource = tw.StoredEvent;
11887             if (!evtDialog.Visible)
11888             {
11889                 evtDialog.Show(this);
11890             }
11891             else
11892             {
11893                 evtDialog.Activate();
11894             }
11895             this.TopMost = SettingManager.Common.AlwaysTop;
11896         }
11897 #endregion
11898
11899         private void TweenRestartMenuItem_Click(object sender, EventArgs e)
11900         {
11901             MyCommon._endingFlag = true;
11902             try
11903             {
11904                 this.Close();
11905                 Application.Restart();
11906             }
11907             catch (Exception)
11908             {
11909                 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
11910             }
11911         }
11912
11913         private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
11914         {
11915             if (!string.IsNullOrEmpty(tw.Username))
11916                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
11917         }
11918
11919         private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
11920         {
11921             await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
11922         }
11923
11924         private bool ExistCurrentPost
11925         {
11926             get
11927             {
11928                 if (_curPost == null) return false;
11929                 if (_curPost.IsDeleted) return false;
11930                 return true;
11931             }
11932         }
11933
11934         private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11935         {
11936             ShowUserTimeline();
11937         }
11938
11939         private string GetUserIdFromCurPostOrInput(string caption)
11940         {
11941             var id = _curPost?.ScreenName ?? "";
11942
11943             using (InputTabName inputName = new InputTabName())
11944             {
11945                 inputName.FormTitle = caption;
11946                 inputName.FormDescription = Properties.Resources.FRMessage1;
11947                 inputName.TabName = id;
11948                 if (inputName.ShowDialog() == DialogResult.OK &&
11949                     !string.IsNullOrEmpty(inputName.TabName.Trim()))
11950                 {
11951                     id = inputName.TabName.Trim();
11952                 }
11953                 else
11954                 {
11955                     id = "";
11956                 }
11957             }
11958             return id;
11959         }
11960
11961         private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
11962         {
11963             string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
11964             if (!string.IsNullOrEmpty(id))
11965             {
11966                 AddNewTabForUserTimeline(id);
11967             }
11968         }
11969
11970         private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
11971         {
11972             string id = GetUserIdFromCurPostOrInput("Show Favstar");
11973             if (!string.IsNullOrEmpty(id))
11974             {
11975                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
11976             }
11977         }
11978
11979         private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
11980         {
11981             if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
11982         }
11983
11984         private void TimelineRefreshEnableChange(bool isEnable)
11985         {
11986             if (isEnable)
11987             {
11988                 tw.StartUserStream();
11989             }
11990             else
11991             {
11992                 tw.StopUserStream();
11993             }
11994             TimerTimeline.Enabled = isEnable;
11995         }
11996
11997         private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
11998         {
11999             TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
12000         }
12001
12002         private async Task OpenUserAppointUrl()
12003         {
12004             if (SettingManager.Common.UserAppointUrl != null)
12005             {
12006                 if (SettingManager.Common.UserAppointUrl.Contains("{ID}") || SettingManager.Common.UserAppointUrl.Contains("{STATUS}"))
12007                 {
12008                     if (_curPost != null)
12009                     {
12010                         string xUrl = SettingManager.Common.UserAppointUrl;
12011                         xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
12012
12013                         var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
12014                         xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
12015
12016                         await this.OpenUriInBrowserAsync(xUrl);
12017                     }
12018                 }
12019                 else
12020                 {
12021                     await this.OpenUriInBrowserAsync(SettingManager.Common.UserAppointUrl);
12022                 }
12023             }
12024         }
12025
12026         private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
12027         {
12028             await this.OpenUserAppointUrl();
12029         }
12030
12031         private async void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
12032         {
12033             if (Form.ActiveForm == null)
12034             {
12035                 await this.InvokeAsync(() =>
12036                 {
12037                     this.Visible = true;
12038                     if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12039                     this.Activate();
12040                     this.BringToFront();
12041                     if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
12042                     {
12043                         if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
12044                     }
12045                     else
12046                     {
12047                         if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
12048                     }
12049                 });
12050             }
12051         }
12052
12053         private void ReplaceAppName()
12054         {
12055             MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
12056             AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
12057         }
12058
12059         private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
12060         {
12061             this.SplitContainer3.Panel2Collapsed = false;
12062         }
12063
12064         private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
12065         {
12066             await this.OpenThumbnailPicture(e.Thumbnail);
12067         }
12068
12069         private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
12070         {
12071             await this.OpenUriInBrowserAsync(e.ImageUrl);
12072         }
12073
12074         private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
12075         {
12076             var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
12077
12078             await this.OpenUriInBrowserAsync(url);
12079         }
12080
12081         private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
12082         {
12083             await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
12084         }
12085
12086         private void PostButton_KeyDown(object sender, KeyEventArgs e)
12087         {
12088             if (e.KeyCode == Keys.Space)
12089             {
12090                 this.JumpUnreadMenuItem_Click(null, null);
12091
12092                 e.SuppressKeyPress = true;
12093             }
12094         }
12095
12096         private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
12097         {
12098             this.IconSizeNoneToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.IconNone;
12099             this.IconSize16ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon16;
12100             this.IconSize24ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon24;
12101             this.IconSize48ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48;
12102             this.IconSize48_2ToolStripMenuItem.Checked = SettingManager.Common.IconSize == MyCommon.IconSizes.Icon48_2;
12103
12104             this.LockListSortOrderToolStripMenuItem.Checked = SettingManager.Common.SortOrderLock;
12105         }
12106
12107         private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
12108         {
12109             ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
12110         }
12111
12112         private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
12113         {
12114             ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
12115         }
12116
12117         private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
12118         {
12119             ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
12120         }
12121
12122         private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
12123         {
12124             ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
12125         }
12126
12127         private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
12128         {
12129             ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
12130         }
12131
12132         private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
12133         {
12134             if (SettingManager.Common.IconSize == iconSize) return;
12135
12136             var oldIconCol = _iconCol;
12137
12138             SettingManager.Common.IconSize = iconSize;
12139             ApplyListViewIconSize(iconSize);
12140
12141             if (_iconCol != oldIconCol)
12142             {
12143                 foreach (TabPage tp in ListTab.TabPages)
12144                 {
12145                     ResetColumns((DetailsListView)tp.Tag);
12146                 }
12147             }
12148
12149             _curList?.Refresh();
12150
12151             ModifySettingCommon = true;
12152         }
12153
12154         private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
12155         {
12156             var state = this.LockListSortOrderToolStripMenuItem.Checked;
12157             if (SettingManager.Common.SortOrderLock == state) return;
12158
12159             SettingManager.Common.SortOrderLock = state;
12160
12161             ModifySettingCommon = true;
12162         }
12163
12164         private void tweetDetailsView_StatusChanged(object sender, TweetDetailsViewStatusChengedEventArgs e)
12165         {
12166             if (!string.IsNullOrEmpty(e.StatusText))
12167             {
12168                 this.StatusLabelUrl.Text = e.StatusText;
12169             }
12170             else
12171             {
12172                 this.SetStatusLabelUrl();
12173             }
12174         }
12175     }
12176 }