OSDN Git Service

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