OSDN Git Service

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