OSDN Git Service

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