OSDN Git Service

SettingTabsのシリアライズにTabClassを直接使用しない
[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.Text;
45 using System.Text.RegularExpressions;
46 using System.Threading;
47 using System.Threading.Tasks;
48 using System.Windows.Forms;
49 using OpenTween.Api;
50 using OpenTween.Api.DataModel;
51 using OpenTween.Connection;
52 using OpenTween.OpenTweenCustomControl;
53 using OpenTween.Thumbnail;
54
55 namespace OpenTween
56 {
57     public partial class TweenMain : OTBaseForm
58     {
59         //各種設定
60         private Size _mySize;           //画面サイズ
61         private Point _myLoc;           //画面位置
62         private int _mySpDis;           //区切り位置
63         private int _mySpDis2;          //発言欄区切り位置
64         private int _mySpDis3;          //プレビュー区切り位置
65         private int _iconSz;            //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
66         private bool _iconCol;          //1列表示の時true(48サイズのとき)
67
68         //雑多なフラグ類
69         private bool _initial;         //true:起動時処理中
70         private bool _initialLayout = true;
71         private bool _ignoreConfigSave;         //true:起動時処理中
72         private bool _tabDrag;           //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
73         private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
74         private Point _tabMouseDownPoint;
75         private string _rclickTabName;      //右クリックしたタブの名前(Tabコントロール機能不足対応)
76         private readonly object _syncObject = new object();    //ロック用
77
78         private const string detailHtmlFormatHeaderMono = 
79             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
80             + "<style type=\"text/css\"><!-- "
81             + "body, p, pre {margin: 0;} "
82             + "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%);} "
83             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
84             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
85             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
86             + ".quote-tweet.reply {border-color: #f33;} "
87             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
88             + "--></style>"
89             + "</head><body><pre>";
90         private const string detailHtmlFormatFooterMono = "</pre></body></html>";
91         private const string detailHtmlFormatHeaderColor = 
92             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
93             + "<style type=\"text/css\"><!-- "
94             + "body, p, pre {margin: 0;} "
95             + "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%);} "
96             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
97             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
98             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
99             + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
100             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
101             + "--></style>"
102             + "</head><body><p>";
103         private const string detailHtmlFormatFooterColor = "</p></body></html>";
104         private string detailHtmlFormatHeader;
105         private string detailHtmlFormatFooter;
106
107         private bool _myStatusError = false;
108         private bool _myStatusOnline = false;
109         private bool soundfileListup = false;
110         private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
111
112         //設定ファイル関連
113         //private SettingToConfig _cfg; //旧
114         private SettingLocal _cfgLocal;
115         private SettingCommon _cfgCommon;
116
117         //twitter解析部
118         private TwitterApi twitterApi = new TwitterApi();
119         private Twitter tw;
120
121         //Growl呼び出し部
122         private GrowlHelper gh = new GrowlHelper(Application.ProductName);
123
124         //サブ画面インスタンス
125         private SearchWordDialog SearchDialog = new SearchWordDialog();     //検索画面インスタンス
126         private OpenURL UrlDialog = new OpenURL();
127         public AtIdSupplement AtIdSupl;     //@id補助
128         public AtIdSupplement HashSupl;    //Hashtag補助
129         public HashtagManage HashMgr;
130         private EventViewerDialog evtDialog;
131
132         //表示フォント、色、アイコン
133         private Font _fntUnread;            //未読用フォント
134         private Color _clUnread;            //未読用文字色
135         private Font _fntReaded;            //既読用フォント
136         private Color _clReaded;            //既読用文字色
137         private Color _clFav;               //Fav用文字色
138         private Color _clOWL;               //片思い用文字色
139         private Color _clRetweet;               //Retweet用文字色
140         private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText);         //選択中の行用文字色
141         private Font _fntDetail;            //発言詳細部用フォント
142         private Color _clDetail;              //発言詳細部用色
143         private Color _clDetailLink;          //発言詳細部用リンク文字色
144         private Color _clDetailBackcolor;     //発言詳細部用背景色
145         private Color _clSelf;              //自分の発言用背景色
146         private Color _clAtSelf;            //自分宛返信用背景色
147         private Color _clTarget;            //選択発言者の他の発言用背景色
148         private Color _clAtTarget;          //選択発言中の返信先用背景色
149         private Color _clAtFromTarget;      //選択発言者への返信発言用背景色
150         private Color _clAtTo;              //選択発言の唯一@先
151         private Color _clListBackcolor;       //リスト部通常発言背景色
152         private Color _clInputBackcolor;      //入力欄背景色
153         private Color _clInputFont;           //入力欄文字色
154         private Font _fntInputFont;           //入力欄フォント
155         private ImageCache IconCache;        //アイコン画像リスト
156         private Icon NIconAt;               //At.ico             タスクトレイアイコン:通常時
157         private Icon NIconAtRed;            //AtRed.ico          タスクトレイアイコン:通信エラー時
158         private Icon NIconAtSmoke;          //AtSmoke.ico        タスクトレイアイコン:オフライン時
159         private Icon[] NIconRefresh = new Icon[4];       //Refresh.ico        タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
160         private Icon TabIcon;               //Tab.ico            未読のあるタブ用アイコン
161         private Icon MainIcon;              //Main.ico           画面左上のアイコン
162         private Icon ReplyIcon;               //5g
163         private Icon ReplyIconBlink;          //6g
164
165         private ImageList _listViewImageList = new ImageList();    //ListViewItemの高さ変更用
166
167         private PostClass _anchorPost;
168         private bool _anchorFlag;        //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
169
170         private List<PostingStatus> _history = new List<PostingStatus>();   //発言履歴
171         private int _hisIdx;                  //発言履歴カレントインデックス
172
173         //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
174         private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
175
176         //時速表示用
177         private List<DateTime> _postTimestamps = new List<DateTime>();
178         private List<DateTime> _favTimestamps = new List<DateTime>();
179         private ConcurrentDictionary<DateTime, int> _tlTimestamps = new ConcurrentDictionary<DateTime, int>();
180         private int _tlCount;
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         private const int MAX_WORKER_THREADS = 20;
264         private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
265         private CancellationTokenSource workerCts = new CancellationTokenSource();
266
267         private int UnreadCounter = -1;
268         private int UnreadAtCounter = -1;
269
270         private string[] ColumnOrgText = new string[9];
271         private string[] ColumnText = new string[9];
272
273         private bool _DoFavRetweetFlags = false;
274         private bool osResumed = false;
275
276         //////////////////////////////////////////////////////////////////////////////////////////////////////////
277         private string _postBrowserStatusText = "";
278
279         private bool _colorize = false;
280
281         private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
282
283         private ImageListViewItem displayItem;
284
285         private string recommendedStatusFooter;
286
287         //URL短縮のUndo用
288         private struct urlUndo
289         {
290             public string Before;
291             public string After;
292         }
293
294         private List<urlUndo> urlUndoBuffer = null;
295
296         private struct ReplyChain
297         {
298             public long OriginalId;
299             public long InReplyToId;
300             public TabPage OriginalTab;
301
302             public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
303             {
304                 this.OriginalId = originalId;
305                 this.InReplyToId = inReplyToId;
306                 this.OriginalTab = originalTab;
307             }
308         }
309
310         private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
311         private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
312
313         //検索処理タイプ
314         private enum SEARCHTYPE
315         {
316             DialogSearch,
317             NextSearch,
318             PrevSearch,
319         }
320
321         private class PostingStatus
322         {
323             public string status = "";
324             public long? inReplyToId = null;
325             public string inReplyToName = null;
326             public string imageService = "";      //画像投稿サービス名
327             public IMediaItem[] mediaItems = null;
328             public PostingStatus()
329             {
330             }
331             public PostingStatus(string status, long? replyToId, string replyToName)
332             {
333                 this.status = status;
334                 this.inReplyToId = replyToId;
335                 this.inReplyToName = replyToName;
336             }
337         }
338
339         private void TweenMain_Activated(object sender, EventArgs e)
340         {
341             //画面がアクティブになったら、発言欄の背景色戻す
342             if (StatusText.Focused)
343             {
344                 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
345             }
346         }
347
348         private bool disposed = false;
349
350         /// <summary>
351         /// 使用中のリソースをすべてクリーンアップします。
352         /// </summary>
353         /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
354         protected override void Dispose(bool disposing)
355         {
356             base.Dispose(disposing);
357
358             if (this.disposed)
359                 return;
360
361             if (disposing)
362             {
363                 this.components?.Dispose();
364
365                 //後始末
366                 SearchDialog.Dispose();
367                 UrlDialog.Dispose();
368                 NIconAt?.Dispose();
369                 NIconAtRed?.Dispose();
370                 NIconAtSmoke?.Dispose();
371                 foreach (var iconRefresh in this.NIconRefresh)
372                 {
373                     iconRefresh?.Dispose();
374                 }
375                 TabIcon?.Dispose();
376                 MainIcon?.Dispose();
377                 ReplyIcon?.Dispose();
378                 ReplyIconBlink?.Dispose();
379                 _listViewImageList.Dispose();
380                 _brsHighLight.Dispose();
381                 _brsBackColorMine?.Dispose();
382                 _brsBackColorAt?.Dispose();
383                 _brsBackColorYou?.Dispose();
384                 _brsBackColorAtYou?.Dispose();
385                 _brsBackColorAtFromTarget?.Dispose();
386                 _brsBackColorAtTo?.Dispose();
387                 _brsBackColorNone?.Dispose();
388                 _brsDeactiveSelection?.Dispose();
389                 //sf.Dispose();
390                 sfTab.Dispose();
391
392                 this.workerCts.Cancel();
393
394                 if (IconCache != null)
395                 {
396                     this.IconCache.CancelAsync();
397                     this.IconCache.Dispose();
398                 }
399
400                 this.thumbnailTokenSource?.Dispose();
401
402                 this.tw.Dispose();
403                 this.twitterApi.Dispose();
404                 this._hookGlobalHotkey.Dispose();
405             }
406
407             // 終了時にRemoveHandlerしておかないとメモリリークする
408             // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
409             Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
410
411             this.disposed = true;
412         }
413
414         private void LoadIcons()
415         {
416             // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
417             var iconsDir = Path.Combine(Application.StartupPath, "Icons");
418
419             // ウィンドウ左上のアイコン
420             var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
421
422             // タブ見出し未読表示アイコン
423             var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
424
425             // タスクトレイ: 通常時アイコン
426             var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
427
428             // タスクトレイ: エラー時アイコン
429             var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
430
431             // タスクトレイ: オフライン時アイコン
432             var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
433
434             // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
435             var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
436             var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
437
438             // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
439             var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
440             var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
441             var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
442             var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
443
444             // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
445
446             this.MainIcon = iconMain ?? Properties.Resources.MIcon;
447             this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
448             this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
449             this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
450             this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
451
452             if (iconReply != null && iconReplyBlink != null)
453             {
454                 this.ReplyIcon = iconReply;
455                 this.ReplyIconBlink = iconReplyBlink;
456             }
457             else
458             {
459                 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
460                 this.ReplyIconBlink = this.NIconAt;
461             }
462
463             if (iconRefresh1 == null)
464             {
465                 this.NIconRefresh = new[] {
466                     Properties.Resources.Refresh, Properties.Resources.Refresh2,
467                     Properties.Resources.Refresh3, Properties.Resources.Refresh4,
468                 };
469             }
470             else if (iconRefresh2 == null)
471             {
472                 this.NIconRefresh = new[] { iconRefresh1 };
473             }
474             else if (iconRefresh3 == null)
475             {
476                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
477             }
478             else if (iconRefresh4 == null)
479             {
480                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
481             }
482             else // iconRefresh1 から iconRefresh4 まで全て揃っている
483             {
484                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
485             }
486         }
487
488         private Icon LoadIcon(string filePath)
489         {
490             if (!File.Exists(filePath))
491                 return null;
492
493             try
494             {
495                 return new Icon(filePath);
496             }
497             catch (Exception)
498             {
499                 return null;
500             }
501         }
502
503         private void InitColumns(ListView list, bool startup)
504         {
505             this.InitColumnText();
506
507             ColumnHeader[] columns = null;
508             try
509             {
510                 if (this._iconCol)
511                 {
512                     columns = new[]
513                     {
514                         new ColumnHeader(), // アイコン
515                         new ColumnHeader(), // 本文
516                     };
517
518                     columns[0].Text = this.ColumnText[0];
519                     columns[1].Text = this.ColumnText[2];
520
521                     if (startup)
522                     {
523                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
524
525                         columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
526                         columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
527                         columns[0].DisplayIndex = 0;
528                         columns[1].DisplayIndex = 1;
529                     }
530                     else
531                     {
532                         var idx = 0;
533                         foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
534                         {
535                             columns[idx].Width = curListColumn.Width;
536                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
537                             idx++;
538                         }
539                     }
540                 }
541                 else
542                 {
543                     columns = new[]
544                     {
545                         new ColumnHeader(), // アイコン
546                         new ColumnHeader(), // ニックネーム
547                         new ColumnHeader(), // 本文
548                         new ColumnHeader(), // 日付
549                         new ColumnHeader(), // ユーザID
550                         new ColumnHeader(), // 未読
551                         new ColumnHeader(), // マーク&プロテクト
552                         new ColumnHeader(), // ソース
553                     };
554
555                     foreach (var i in Enumerable.Range(0, columns.Length))
556                         columns[i].Text = this.ColumnText[i];
557
558                     if (startup)
559                     {
560                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
561
562                         columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
563                         columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
564                         columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
565                         columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
566                         columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
567                         columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
568                         columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
569                         columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
570
571                         var displayIndex = new[] {
572                             this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
573                             this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
574                             this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
575                             this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
576                         };
577
578                         foreach (var i in Enumerable.Range(0, displayIndex.Length))
579                         {
580                             columns[i].DisplayIndex = displayIndex[i];
581                         }
582                     }
583                     else
584                     {
585                         var idx = 0;
586                         foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
587                         {
588                             columns[idx].Width = curListColumn.Width;
589                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
590                             idx++;
591                         }
592                     }
593                 }
594
595                 list.Columns.AddRange(columns);
596
597                 columns = null;
598             }
599             finally
600             {
601                 if (columns != null)
602                 {
603                     foreach (var column in columns)
604                         column?.Dispose();
605                 }
606             }
607         }
608
609         private void InitColumnText()
610         {
611             ColumnText[0] = "";
612             ColumnText[1] = Properties.Resources.AddNewTabText2;
613             ColumnText[2] = Properties.Resources.AddNewTabText3;
614             ColumnText[3] = Properties.Resources.AddNewTabText4_2;
615             ColumnText[4] = Properties.Resources.AddNewTabText5;
616             ColumnText[5] = "";
617             ColumnText[6] = "";
618             ColumnText[7] = "Source";
619
620             ColumnOrgText[0] = "";
621             ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
622             ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
623             ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
624             ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
625             ColumnOrgText[5] = "";
626             ColumnOrgText[6] = "";
627             ColumnOrgText[7] = "Source";
628
629             int c = 0;
630             switch (_statuses.SortMode)
631             {
632                 case ComparerMode.Nickname:  //ニックネーム
633                     c = 1;
634                     break;
635                 case ComparerMode.Data:  //本文
636                     c = 2;
637                     break;
638                 case ComparerMode.Id:  //時刻=発言Id
639                     c = 3;
640                     break;
641                 case ComparerMode.Name:  //名前
642                     c = 4;
643                     break;
644                 case ComparerMode.Source:  //Source
645                     c = 7;
646                     break;
647             }
648
649             if (_iconCol)
650             {
651                 if (_statuses.SortOrder == SortOrder.Descending)
652                 {
653                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
654                     ColumnText[2] = ColumnOrgText[2] + "▾";
655                 }
656                 else
657                 {
658                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
659                     ColumnText[2] = ColumnOrgText[2] + "▴";
660                 }
661             }
662             else
663             {
664                 if (_statuses.SortOrder == SortOrder.Descending)
665                 {
666                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
667                     ColumnText[c] = ColumnOrgText[c] + "▾";
668                 }
669                 else
670                 {
671                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
672                     ColumnText[c] = ColumnOrgText[c] + "▴";
673                 }
674             }
675         }
676
677         private void InitializeTraceFrag()
678         {
679 #if DEBUG
680             TraceOutToolStripMenuItem.Checked = true;
681             MyCommon.TraceFlag = true;
682 #endif
683             if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
684             {
685                 TraceOutToolStripMenuItem.Checked = true;
686                 MyCommon.TraceFlag = true;
687             }
688         }
689
690         private void TweenMain_Load(object sender, EventArgs e)
691         {
692             _ignoreConfigSave = true;
693             this.Visible = false;
694
695             if (MyApplication.StartupOptions.ContainsKey("d"))
696                 MyCommon.TraceFlag = true;
697
698             InitializeTraceFrag();
699
700             //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
701
702             new InternetSecurityManager(PostBrowser);
703             this.PostBrowser.AllowWebBrowserDrop = false;  // COMException を回避するため、ActiveX の初期化が終わってから設定する
704
705             MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
706             Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
707
708             Regex.CacheSize = 100;
709
710             //発言保持クラス
711             _statuses = TabInformations.GetInstance();
712
713             //アイコン設定
714             LoadIcons();
715             this.Icon = MainIcon;              //メインフォーム(TweenMain)
716             NotifyIcon1.Icon = NIconAt;      //タスクトレイ
717             TabImage.Images.Add(TabIcon);    //タブ見出し
718
719             //<<<<<<<<<設定関連>>>>>>>>>
720             ////設定読み出し
721             LoadConfig();
722
723             // 現在の DPI と設定保存時の DPI との比を取得する
724             var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
725
726             // UIフォント設定
727             var fontUIGlobal = this._cfgLocal.FontUIGlobal;
728             if (fontUIGlobal != null)
729             {
730                 OTBaseForm.GlobalFont = fontUIGlobal;
731                 this.Font = fontUIGlobal;
732             }
733
734             //不正値チェック
735             if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
736             {
737                 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
738                     this._cfgCommon.TimelinePeriod = 15;
739
740                 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
741                     this._cfgCommon.ReplyPeriod = 15;
742
743                 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
744                     this._cfgCommon.DMPeriod = 15;
745
746                 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
747                     this._cfgCommon.PubSearchPeriod = 30;
748
749                 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
750                     this._cfgCommon.UserTimelinePeriod = 15;
751
752                 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
753                     this._cfgCommon.ListsPeriod = 15;
754             }
755
756             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
757                 this._cfgCommon.CountApi = 60;
758             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
759                 this._cfgCommon.CountApiReply = 40;
760
761             if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
762                 this._cfgCommon.MoreCountApi = 200;
763             if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
764                 this._cfgCommon.FirstCountApi = 100;
765
766             if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
767                 this._cfgCommon.FavoritesCountApi = 40;
768             if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
769                 this._cfgCommon.ListCountApi = 100;
770             if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
771                 this._cfgCommon.SearchCountApi = 100;
772             if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
773                 this._cfgCommon.UserTimelineCountApi = 20;
774
775             //廃止サービスが選択されていた場合ux.nuへ読み替え
776             if (this._cfgCommon.AutoShortUrlFirst < 0)
777                 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
778
779             TwitterApiConnection.RestApiBase = this._cfgCommon.TwitterApiBaseUri;
780             this.tw = new Twitter(this.twitterApi);
781
782             //認証関連
783             if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
784             tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
785
786             _initial = true;
787
788             Networking.Initialize();
789
790             bool saveRequired = false;
791             bool firstRun = false;
792
793             //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
794             if (string.IsNullOrEmpty(tw.Username))
795             {
796                 saveRequired = true;
797                 firstRun = true;
798
799                 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
800                 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
801                     string.IsNullOrEmpty(tw.Username))
802                 {
803                     Application.Exit();  //強制終了
804                     return;
805                 }
806             }
807
808             //Twitter用通信クラス初期化
809             Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
810             Networking.SetWebProxy(this._cfgLocal.ProxyType,
811                 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
812                 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
813             Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
814
815             TwitterApiConnection.RestApiBase = this._cfgCommon.TwitterApiBaseUri;
816             tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
817             tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
818             tw.TrackWord = this._cfgCommon.TrackWord;
819             TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
820             tw.AllAtReply = this._cfgCommon.AllAtReply;
821             AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
822             ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
823             ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
824             ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
825
826             // アクセストークンが有効であるか確認する
827             // ここが Twitter API への最初のアクセスになるようにすること
828             try
829             {
830                 this.tw.VerifyCredentials();
831             }
832             catch (WebApiException ex)
833             {
834                 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
835                     Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
836             }
837
838             //サムネイル関連の初期化
839             //プロキシ設定等の通信まわりの初期化が済んでから処理する
840             ThumbnailGenerator.InitializeGenerator();
841
842             var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
843             imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
844             imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
845
846             Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
847
848             //画像投稿サービス
849             ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
850
851             //ハッシュタグ/@id関連
852             AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
853             HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
854             HashMgr = new HashtagManage(HashSupl,
855                                     _cfgCommon.HashTags.ToArray(),
856                                     _cfgCommon.HashSelected,
857                                     _cfgCommon.HashIsPermanent,
858                                     _cfgCommon.HashIsHead,
859                                     _cfgCommon.HashIsNotAddToAtReply);
860             if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
861
862             //アイコンリスト作成
863             this.IconCache = new ImageCache();
864
865             //フォント&文字色&背景色保持
866             _fntUnread = this._cfgLocal.FontUnread;
867             _clUnread = this._cfgLocal.ColorUnread;
868             _fntReaded = this._cfgLocal.FontRead;
869             _clReaded = this._cfgLocal.ColorRead;
870             _clFav = this._cfgLocal.ColorFav;
871             _clOWL = this._cfgLocal.ColorOWL;
872             _clRetweet = this._cfgLocal.ColorRetweet;
873             _fntDetail = this._cfgLocal.FontDetail;
874             _clDetail = this._cfgLocal.ColorDetail;
875             _clDetailLink = this._cfgLocal.ColorDetailLink;
876             _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
877             _clSelf = this._cfgLocal.ColorSelf;
878             _clAtSelf = this._cfgLocal.ColorAtSelf;
879             _clTarget = this._cfgLocal.ColorTarget;
880             _clAtTarget = this._cfgLocal.ColorAtTarget;
881             _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
882             _clAtTo = this._cfgLocal.ColorAtTo;
883             _clListBackcolor = this._cfgLocal.ColorListBackcolor;
884             _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
885             _clInputFont = this._cfgLocal.ColorInputFont;
886             _fntInputFont = this._cfgLocal.FontInputFont;
887
888             _brsBackColorMine = new SolidBrush(_clSelf);
889             _brsBackColorAt = new SolidBrush(_clAtSelf);
890             _brsBackColorYou = new SolidBrush(_clTarget);
891             _brsBackColorAtYou = new SolidBrush(_clAtTarget);
892             _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
893             _brsBackColorAtTo = new SolidBrush(_clAtTo);
894             //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
895             _brsBackColorNone = new SolidBrush(_clListBackcolor);
896
897             // StringFormatオブジェクトへの事前設定
898             //sf.Alignment = StringAlignment.Near;             // Textを近くへ配置(左から右の場合は左寄せ)
899             //sf.LineAlignment = StringAlignment.Near;         // Textを近くへ配置(上寄せ)
900             //sf.FormatFlags = StringFormatFlags.LineLimit;    // 
901             sfTab.Alignment = StringAlignment.Center;
902             sfTab.LineAlignment = StringAlignment.Center;
903
904             InitDetailHtmlFormat();
905
906             //Regex statregex = new Regex("^0*");
907             this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
908
909             _history.Add(new PostingStatus());
910             _hisIdx = 0;
911             this.inReplyTo = null;
912
913             //各種ダイアログ設定
914             SearchDialog.Owner = this;
915             UrlDialog.Owner = this;
916
917             //新着バルーン通知のチェック状態設定
918             NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
919             this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
920
921             //新着取得時のリストスクロールをするか。trueならスクロールしない
922             ListLockMenuItem.Checked = _cfgCommon.ListLock;
923             this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
924             //サウンド再生(タブ別設定より優先)
925             this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
926             this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
927
928             this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
929             this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
930
931             //ウィンドウ設定
932             this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
933             _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
934             _myLoc = _cfgLocal.FormLocation;
935             //タイトルバー領域
936             if (this.WindowState != FormWindowState.Minimized)
937             {
938                 this.DesktopLocation = _cfgLocal.FormLocation;
939                 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
940                 bool outOfScreen = true;
941                 if (Screen.AllScreens.Length == 1)    //ハングするとの報告
942                 {
943                     foreach (Screen scr in Screen.AllScreens)
944                     {
945                         if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
946                         {
947                             outOfScreen = false;
948                             break;
949                         }
950                     }
951                     if (outOfScreen)
952                     {
953                         this.DesktopLocation = new Point(0, 0);
954                         _myLoc = this.DesktopLocation;
955                     }
956                 }
957             }
958             this.TopMost = this._cfgCommon.AlwaysTop;
959             _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
960             _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
961             if (_cfgLocal.PreviewDistance == -1)
962             {
963                 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
964                 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
965                 _cfgLocal.PreviewDistance = _mySpDis3;
966             }
967             else
968             {
969                 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
970             }
971             MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
972             //this.Tween_ClientSizeChanged(this, null);
973             this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
974             this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
975             //入力欄
976             StatusText.Font = _fntInputFont;
977             StatusText.ForeColor = _clInputFont;
978
979             // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
980             this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
981             this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
982
983             // NameLabel のフォントを OTBaseForm.GlobalFont に変更
984             this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
985
986             // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
987             SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
988
989             //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
990             if (this._cfgCommon.UnreadManage == false)
991             {
992                 ReadedStripMenuItem.Enabled = false;
993                 UnreadStripMenuItem.Enabled = false;
994             }
995
996             //発言詳細部の初期化
997             NameLabel.Text = "";
998             DateTimeLabel.Text = "";
999             SourceLinkLabel.Text = "";
1000
1001             //リンク先URL表示部の初期化(画面左下)
1002             StatusLabelUrl.Text = "";
1003             //状態表示部の初期化(画面右下)
1004             StatusLabel.Text = "";
1005             StatusLabel.AutoToolTip = false;
1006             StatusLabel.ToolTipText = "";
1007             //文字カウンタ初期化
1008             lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
1009
1010             this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1011             CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1012             CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1013             CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1014
1015             // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1016             // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1017             // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1018             this.SplitContainer2.Panel2.AccessibleName = "";
1019
1020             ////////////////////////////////////////////////////////////////////////////////
1021             var sortOrder = (SortOrder)_cfgCommon.SortOrder;
1022             var mode = ComparerMode.Id;
1023             switch (_cfgCommon.SortColumn)
1024             {
1025                 case 0:    //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1026                 case 5:
1027                 case 6:
1028                     //ソートしない
1029                     mode = ComparerMode.Id;  //Idソートに読み替え
1030                     break;
1031                 case 1:  //ニックネーム
1032                     mode = ComparerMode.Nickname;
1033                     break;
1034                 case 2:  //本文
1035                     mode = ComparerMode.Data;
1036                     break;
1037                 case 3:  //時刻=発言Id
1038                     mode = ComparerMode.Id;
1039                     break;
1040                 case 4:  //名前
1041                     mode = ComparerMode.Name;
1042                     break;
1043                 case 7:  //Source
1044                     mode = ComparerMode.Source;
1045                     break;
1046             }
1047             _statuses.SetSortMode(mode, sortOrder);
1048             ////////////////////////////////////////////////////////////////////////////////
1049
1050             ApplyListViewIconSize(this._cfgCommon.IconSize);
1051
1052             //<<<<<<<<タブ関連>>>>>>>
1053             // タブの位置を調整する
1054             SetTabAlignment();
1055
1056             //デフォルトタブの存在チェック、ない場合には追加
1057             if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1058             {
1059                 TabClass tab;
1060                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1061                 {
1062                     _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1063                 }
1064                 else
1065                 {
1066                     tab.TabType = MyCommon.TabUsageType.Home;
1067                 }
1068             }
1069             if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1070             {
1071                 TabClass tab;
1072                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1073                 {
1074                     _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1075                 }
1076                 else
1077                 {
1078                     tab.TabType = MyCommon.TabUsageType.Mentions;
1079                 }
1080             }
1081             if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1082             {
1083                 TabClass tab;
1084                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1085                 {
1086                     _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1087                 }
1088                 else
1089                 {
1090                     tab.TabType = MyCommon.TabUsageType.DirectMessage;
1091                 }
1092             }
1093             if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1094             {
1095                 TabClass tab;
1096                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1097                 {
1098                     _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1099                 }
1100                 else
1101                 {
1102                     tab.TabType = MyCommon.TabUsageType.Favorites;
1103                 }
1104             }
1105             if (_statuses.GetTabByType(MyCommon.TabUsageType.Mute) == null)
1106             {
1107                 TabClass tab;
1108                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.MUTE, out tab))
1109                 {
1110                     _statuses.AddTab(MyCommon.DEFAULTTAB.MUTE, MyCommon.TabUsageType.Mute, null);
1111                 }
1112                 else
1113                 {
1114                     tab.TabType = MyCommon.TabUsageType.Mute;
1115                 }
1116             }
1117
1118             foreach (var tab in _statuses.Tabs.Values)
1119             {
1120                 // ミュートタブは表示しない
1121                 if (tab.TabType == MyCommon.TabUsageType.Mute)
1122                     continue;
1123
1124                 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1125                 {
1126                     tab.TabType = MyCommon.TabUsageType.UserDefined;
1127                 }
1128                 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1129                     throw new TabException(Properties.Resources.TweenMain_LoadText1);
1130             }
1131
1132             _curTab = ListTab.SelectedTab;
1133             _curItemIndex = -1;
1134             _curList = (DetailsListView)_curTab.Tag;
1135
1136             if (this._cfgCommon.TabIconDisp)
1137             {
1138                 ListTab.DrawMode = TabDrawMode.Normal;
1139             }
1140             else
1141             {
1142                 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1143                 ListTab.DrawItem += ListTab_DrawItem;
1144                 ListTab.ImageList = null;
1145             }
1146
1147             if (this._cfgCommon.HotkeyEnabled)
1148             {
1149                 //////グローバルホットキーの登録
1150                 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1151                 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1152                     modKey |= HookGlobalHotkey.ModKeys.Alt;
1153                 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1154                     modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1155                 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1156                     modKey |= HookGlobalHotkey.ModKeys.Shift;
1157                 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1158                     modKey |= HookGlobalHotkey.ModKeys.Win;
1159
1160                 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1161             }
1162
1163             if (this._cfgCommon.IsUseNotifyGrowl)
1164                 gh.RegisterGrowl();
1165
1166             StatusLabel.Text = Properties.Resources.Form1_LoadText1;       //画面右下の状態表示を変更
1167
1168             SetMainWindowTitle();
1169             SetNotifyIconText();
1170
1171             if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1172             {
1173                 this.Visible = true;
1174             }
1175
1176             //タイマー設定
1177             TimerTimeline.AutoReset = true;
1178             TimerTimeline.SynchronizingObject = this;
1179             //Recent取得間隔
1180             TimerTimeline.Interval = 1000;
1181             TimerTimeline.Enabled = true;
1182             //更新中アイコンアニメーション間隔
1183             TimerRefreshIcon.Interval = 200;
1184             TimerRefreshIcon.Enabled = true;
1185
1186             _ignoreConfigSave = false;
1187             this.TweenMain_Resize(null, null);
1188             if (saveRequired) SaveConfigsAll(false);
1189
1190             foreach (var ua in this._cfgCommon.UserAccounts)
1191             {
1192                 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1193                 {
1194                     ua.UserId = tw.UserId;
1195                     break;
1196                 }
1197             }
1198
1199             if (firstRun)
1200             {
1201                 // 初回起動時だけ右下のメニューを目立たせる
1202                 HashStripSplitButton.ShowDropDown();
1203             }
1204         }
1205
1206         private void InitDetailHtmlFormat()
1207         {
1208             if (this._cfgCommon.IsMonospace)
1209             {
1210                 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1211                 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1212             }
1213             else
1214             {
1215                 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1216                 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1217             }
1218
1219             detailHtmlFormatHeader = detailHtmlFormatHeader
1220                     .Replace("%FONT_FAMILY%", _fntDetail.Name)
1221                     .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1222                     .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1223                     .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1224                     .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString())
1225                     .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1226         }
1227
1228         private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1229         {
1230             string txt;
1231             try
1232             {
1233                 txt = ListTab.TabPages[e.Index].Text;
1234             }
1235             catch (Exception)
1236             {
1237                 return;
1238             }
1239
1240             e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1241             if (e.State == DrawItemState.Selected)
1242             {
1243                 e.DrawFocusRectangle();
1244             }
1245             Brush fore;
1246             try
1247             {
1248                 if (_statuses.Tabs[txt].UnreadCount > 0)
1249                     fore = Brushes.Red;
1250                 else
1251                     fore = System.Drawing.SystemBrushes.ControlText;
1252             }
1253             catch (Exception)
1254             {
1255                 fore = System.Drawing.SystemBrushes.ControlText;
1256             }
1257             e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1258         }
1259
1260         private void LoadConfig()
1261         {
1262             _cfgCommon = SettingCommon.Load();
1263             SettingCommon.Instance = this._cfgCommon;
1264             if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1265             {
1266                 _cfgCommon.UserAccounts = new List<UserAccount>();
1267                 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1268                 {
1269                     UserAccount account = new UserAccount();
1270                     account.Username = _cfgCommon.UserName;
1271                     account.UserId = _cfgCommon.UserId;
1272                     account.Token = _cfgCommon.Token;
1273                     account.TokenSecret = _cfgCommon.TokenSecret;
1274
1275                     _cfgCommon.UserAccounts.Add(account);
1276                 }
1277             }
1278
1279             _cfgLocal = SettingLocal.Load();
1280
1281             // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1282             if (_cfgLocal.ScaleDimension.IsEmpty)
1283                 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1284
1285             var tabsSetting = SettingTabs.Load().Tabs;
1286             foreach (var tabSetting in tabsSetting)
1287             {
1288                 var tab = new TabClass(tabSetting.TabName, tabSetting.TabType, tabSetting.ListInfo)
1289                 {
1290                     UnreadManage = tabSetting.UnreadManage,
1291                     Protected = tabSetting.Protected,
1292                     Notify = tabSetting.Notify,
1293                     SoundFile = tabSetting.SoundFile,
1294                     FilterArray = tabSetting.FilterArray,
1295                     FilterModified = false,
1296                     User = tabSetting.User,
1297                     SearchWords = tabSetting.SearchWords,
1298                     SearchLang = tabSetting.SearchLang,
1299                 };
1300
1301                 if (this._statuses.ContainsTab(tab.TabName))
1302                     tab.TabName = this._statuses.MakeTabName("MyTab");
1303
1304                 this._statuses.AddTab(tab);
1305             }
1306             if (_statuses.Tabs.Count == 0)
1307             {
1308                 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1309                 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1310                 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1311                 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1312             }
1313         }
1314
1315         private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1316         {
1317             if (!TimerTimeline.Enabled) return;
1318             ResetTimers = e;
1319         }
1320
1321         private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1322
1323         private static int homeCounter = 0;
1324         private static int mentionCounter = 0;
1325         private static int dmCounter = 0;
1326         private static int pubSearchCounter = 0;
1327         private static int userTimelineCounter = 0;
1328         private static int listsCounter = 0;
1329         private static int usCounter = 0;
1330         private static int ResumeWait = 0;
1331         private static int refreshFollowers = 0;
1332
1333         private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1334         {
1335             if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1336             if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1337             if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1338             if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1339             if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1340             if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1341             if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1342             Interlocked.Increment(ref refreshFollowers);
1343
1344             var refreshTasks = new List<Task>();
1345
1346             ////タイマー初期化
1347             if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1348             {
1349                 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1350                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1351                     refreshTasks.Add(this.GetHomeTimelineAsync());
1352                 ResetTimers.Timeline = false;
1353             }
1354             if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1355             {
1356                 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1357                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1358                     refreshTasks.Add(this.GetReplyAsync());
1359                 ResetTimers.Reply = false;
1360             }
1361             if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1362             {
1363                 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1364                 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1365                     refreshTasks.Add(this.GetDirectMessagesAsync());
1366                 ResetTimers.DirectMessage = false;
1367             }
1368             if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1369             {
1370                 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1371                 if (!ResetTimers.PublicSearch)
1372                     refreshTasks.Add(this.GetPublicSearchAllAsync());
1373                 ResetTimers.PublicSearch = false;
1374             }
1375             if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1376             {
1377                 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1378                 if (!ResetTimers.UserTimeline)
1379                     refreshTasks.Add(this.GetUserTimelineAllAsync());
1380                 ResetTimers.UserTimeline = false;
1381             }
1382             if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1383             {
1384                 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1385                 if (!ResetTimers.Lists)
1386                     refreshTasks.Add(this.GetListTimelineAllAsync());
1387                 ResetTimers.Lists = false;
1388             }
1389             if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1390             {
1391                 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1392                 if (this.tw.UserStreamActive)
1393                     this.RefreshTimeline();
1394                 ResetTimers.UserStream = false;
1395             }
1396             if (refreshFollowers > 6 * 3600)
1397             {
1398                 Interlocked.Exchange(ref refreshFollowers, 0);
1399                 refreshTasks.AddRange(new[]
1400                 {
1401                     this.doGetFollowersMenu(),
1402                     this.RefreshNoRetweetIdsAsync(),
1403                     this.RefreshTwitterConfigurationAsync(),
1404                 });
1405             }
1406             if (osResumed)
1407             {
1408                 Interlocked.Increment(ref ResumeWait);
1409                 if (ResumeWait > 30)
1410                 {
1411                     osResumed = false;
1412                     Interlocked.Exchange(ref ResumeWait, 0);
1413                     refreshTasks.AddRange(new[]
1414                     {
1415                         this.GetHomeTimelineAsync(),
1416                         this.GetReplyAsync(),
1417                         this.GetDirectMessagesAsync(),
1418                         this.GetPublicSearchAllAsync(),
1419                         this.GetUserTimelineAllAsync(),
1420                         this.GetListTimelineAllAsync(),
1421                         this.doGetFollowersMenu(),
1422                         this.RefreshTwitterConfigurationAsync(),
1423                     });
1424                 }
1425             }
1426
1427             await Task.WhenAll(refreshTasks);
1428         }
1429
1430         private void RefreshTimeline()
1431         {
1432             // 現在表示中のタブのスクロール位置を退避
1433             var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1434
1435             // 各タブのリスト上の選択位置などを退避
1436             var listSelections = this.SaveListViewSelection();
1437
1438             //更新確定
1439             PostClass[] notifyPosts;
1440             string soundFile;
1441             int addCount;
1442             bool newMentionOrDm;
1443             bool isDelete;
1444             addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1445
1446             if (MyCommon._endingFlag) return;
1447
1448             //リストに反映&選択状態復元
1449             try
1450             {
1451                 foreach (TabPage tab in ListTab.TabPages)
1452                 {
1453                     DetailsListView lst = (DetailsListView)tab.Tag;
1454                     TabClass tabInfo = _statuses.Tabs[tab.Text];
1455                     if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1456                     {
1457                         using (ControlTransaction.Update(lst))
1458                         {
1459                             if (lst.Equals(_curList))
1460                             {
1461                                 this.PurgeListViewItemCache();
1462                             }
1463                             try
1464                             {
1465                                 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1466                             }
1467                             catch (Exception)
1468                             {
1469                                 //アイコン描画不具合あり?
1470                             }
1471
1472                             // 選択位置などを復元
1473                             this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1474                         }
1475                     }
1476                     if (tabInfo.UnreadCount > 0)
1477                         if (this._cfgCommon.TabIconDisp)
1478                             if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1479                 }
1480                 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1481             }
1482             catch (Exception)
1483             {
1484                 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1485                 //throw;
1486             }
1487
1488             // スクロール位置を復元
1489             this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1490
1491             //新着通知
1492             NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1493
1494             SetMainWindowTitle();
1495             if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1496
1497             HashSupl.AddRangeItem(tw.GetHashList());
1498
1499         }
1500
1501         internal struct ListViewScroll
1502         {
1503             public ScrollLockMode ScrollLockMode { get; set; }
1504             public long? TopItemStatusId { get; set; }
1505         }
1506
1507         internal enum ScrollLockMode
1508         {
1509             /// <summary>固定しない</summary>
1510             None,
1511
1512             /// <summary>最上部に固定する</summary>
1513             FixedToTop,
1514
1515             /// <summary>最下部に固定する</summary>
1516             FixedToBottom,
1517
1518             /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1519             FixedToItem,
1520         }
1521
1522         /// <summary>
1523         /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1524         /// </summary>
1525         private ListViewScroll SaveListViewScroll(DetailsListView listView, TabClass tab)
1526         {
1527             var listScroll = new ListViewScroll
1528             {
1529                 ScrollLockMode = this.GetScrollLockMode(listView),
1530             };
1531
1532             if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1533             {
1534                 var topItem = listView.TopItem;
1535                 if (topItem != null)
1536                     listScroll.TopItemStatusId = tab.GetId(topItem.Index);
1537             }
1538
1539             return listScroll;
1540         }
1541
1542         private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1543         {
1544             if (this._statuses.SortMode == ComparerMode.Id)
1545             {
1546                 if (this._statuses.SortOrder == SortOrder.Ascending)
1547                 {
1548                     // Id昇順
1549                     if (this.ListLockMenuItem.Checked)
1550                         return ScrollLockMode.None;
1551
1552                     // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1553
1554                     // 一番下に表示されているアイテム
1555                     var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1556                     if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1557                         return ScrollLockMode.FixedToBottom;
1558                     else
1559                         return ScrollLockMode.None;
1560                 }
1561                 else
1562                 {
1563                     // Id降順
1564                     if (this.ListLockMenuItem.Checked)
1565                         return ScrollLockMode.FixedToItem;
1566
1567                     // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1568                     var topItem = listView.TopItem;
1569                     if (topItem == null || topItem.Index == 0)
1570                         return ScrollLockMode.FixedToTop;
1571                     else
1572                         return ScrollLockMode.FixedToItem;
1573                 }
1574             }
1575             else
1576             {
1577                 return ScrollLockMode.FixedToItem;
1578             }
1579         }
1580
1581         internal struct ListViewSelection
1582         {
1583             public long[] SelectedStatusIds { get; set; }
1584             public long? SelectionMarkStatusId { get; set; }
1585             public long? FocusedStatusId { get; set; }
1586         }
1587
1588         /// <summary>
1589         /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1590         /// </summary>
1591         private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1592         {
1593             var listsDict = new Dictionary<string, ListViewSelection>();
1594
1595             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1596             {
1597                 var listView = (DetailsListView)tabPage.Tag;
1598                 var tab = _statuses.Tabs[tabPage.Text];
1599
1600                 ListViewSelection listStatus;
1601                 if (listView.VirtualListSize != 0)
1602                 {
1603                     listStatus = new ListViewSelection
1604                     {
1605                         SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1606                         FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1607                         SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1608                     };
1609                 }
1610                 else
1611                 {
1612                     listStatus = new ListViewSelection
1613                     {
1614                         SelectedStatusIds = new long[0],
1615                         SelectionMarkStatusId = null,
1616                         FocusedStatusId = null,
1617                     };
1618                 }
1619
1620                 listsDict[tab.TabName] = listStatus;
1621             }
1622
1623             return listsDict;
1624         }
1625
1626         private long[] GetSelectedStatusIds(DetailsListView listView, TabClass tab)
1627         {
1628             var selectedIndices = listView.SelectedIndices;
1629             if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1630                 return tab.GetId(selectedIndices);
1631             else
1632                 return null;
1633         }
1634
1635         private long? GetFocusedStatusId(DetailsListView listView, TabClass tab)
1636         {
1637             var focusedItem = listView.FocusedItem;
1638
1639             return focusedItem != null ? tab.GetId(focusedItem.Index) : (long?)null;
1640         }
1641
1642         private long? GetSelectionMarkStatusId(DetailsListView listView, TabClass tab)
1643         {
1644             var selectionMarkIndex = listView.SelectionMark;
1645
1646             return selectionMarkIndex != -1 ? tab.GetId(selectionMarkIndex) : (long?)null;
1647         }
1648
1649         /// <summary>
1650         /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1651         /// </summary>
1652         private void RestoreListViewScroll(DetailsListView listView, TabClass tab, ListViewScroll listScroll)
1653         {
1654             if (listView.VirtualListSize == 0)
1655                 return;
1656
1657             switch (listScroll.ScrollLockMode)
1658             {
1659                 case ScrollLockMode.FixedToTop:
1660                     listView.EnsureVisible(0);
1661                     break;
1662                 case ScrollLockMode.FixedToBottom:
1663                     listView.EnsureVisible(listView.VirtualListSize - 1);
1664                     break;
1665                 case ScrollLockMode.FixedToItem:
1666                     var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1667                     if (topIndex != -1)
1668                         listView.TopItem = listView.Items[topIndex];
1669                     break;
1670                 case ScrollLockMode.None:
1671                 default:
1672                     break;
1673             }
1674         }
1675
1676         /// <summary>
1677         /// <see cref="SaveListViewStatus"/> によって保存された選択状態を復元します
1678         /// </summary>
1679         private void RestoreListViewSelection(DetailsListView listView, TabClass tab, ListViewSelection listSelection)
1680         {
1681             // status_id から ListView 上のインデックスに変換
1682             int[] selectedIndices = null;
1683             if (listSelection.SelectedStatusIds != null)
1684                 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1685
1686             var focusedIndex = -1;
1687             if (listSelection.FocusedStatusId != null)
1688                 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1689
1690             var selectionMarkIndex = -1;
1691             if (listSelection.SelectionMarkStatusId != null)
1692                 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1693
1694             this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1695         }
1696
1697         private bool BalloonRequired()
1698         {
1699             Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1700             ev.Eventtype = MyCommon.EVENTTYPE.None;
1701
1702             return BalloonRequired(ev);
1703         }
1704
1705         private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1706         {
1707             if (type == MyCommon.EVENTTYPE.None)
1708                 return true;
1709
1710             if (!this._cfgCommon.EventNotifyEnabled)
1711                 return false;
1712
1713             return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1714         }
1715
1716         private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1717         {
1718             if (!ev.IsMe)
1719                 return true;
1720
1721             return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1722         }
1723
1724         private bool BalloonRequired(Twitter.FormattedEvent ev)
1725         {
1726             if (this._initial)
1727                 return false;
1728
1729             if (NativeMethods.IsScreenSaverRunning())
1730                 return false;
1731
1732             // 「新着通知」が無効
1733             if (!this.NewPostPopMenuItem.Checked)
1734             {
1735                 // 「新着通知が無効でもイベントを通知する」にも該当しない
1736                 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1737                     return false;
1738             }
1739
1740             // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1741             if (this._cfgCommon.LimitBalloon)
1742             {
1743                 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1744                     return false;
1745             }
1746
1747             return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1748         }
1749
1750         private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1751         {
1752             if (this._cfgCommon.ReadOwnPost)
1753             {
1754                 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1755                     return;
1756             }
1757
1758             //新着通知
1759             if (BalloonRequired())
1760             {
1761                 if (notifyPosts != null && notifyPosts.Length > 0)
1762                 {
1763                     //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1764                     if (this._cfgCommon.IsUseNotifyGrowl)
1765                     {
1766                         StringBuilder sb = new StringBuilder();
1767                         bool reply = false;
1768                         bool dm = false;
1769
1770                         foreach (PostClass post in notifyPosts)
1771                         {
1772                             if (!(notifyPosts.Length > 3))
1773                             {
1774                                 sb.Clear();
1775                                 reply = false;
1776                                 dm = false;
1777                             }
1778                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1779                             if (post.IsDm) dm = true;
1780                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1781                             switch (this._cfgCommon.NameBalloon)
1782                             {
1783                                 case MyCommon.NameBalloonEnum.UserID:
1784                                     sb.Append(post.ScreenName).Append(" : ");
1785                                     break;
1786                                 case MyCommon.NameBalloonEnum.NickName:
1787                                     sb.Append(post.Nickname).Append(" : ");
1788                                     break;
1789                             }
1790                             sb.Append(post.TextFromApi);
1791                             if (notifyPosts.Length > 3)
1792                             {
1793                                 if (notifyPosts.Last() != post) continue;
1794                             }
1795
1796                             StringBuilder title = new StringBuilder();
1797                             GrowlHelper.NotifyType nt;
1798                             if (this._cfgCommon.DispUsername)
1799                             {
1800                                 title.Append(tw.Username);
1801                                 title.Append(" - ");
1802                             }
1803                             else
1804                             {
1805                                 //title.Clear();
1806                             }
1807                             if (dm)
1808                             {
1809                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1810                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1811                                 title.Append(Application.ProductName);
1812                                 title.Append(" [DM] ");
1813                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1814                                 nt = GrowlHelper.NotifyType.DirectMessage;
1815                             }
1816                             else if (reply)
1817                             {
1818                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1819                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1820                                 title.Append(Application.ProductName);
1821                                 title.Append(" [Reply!] ");
1822                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1823                                 nt = GrowlHelper.NotifyType.Reply;
1824                             }
1825                             else
1826                             {
1827                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1828                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1829                                 title.Append(Application.ProductName);
1830                                 title.Append(" ");
1831                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1832                                 nt = GrowlHelper.NotifyType.Notify;
1833                             }
1834                             string bText = sb.ToString();
1835                             if (string.IsNullOrEmpty(bText)) return;
1836
1837                             var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1838                             gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1839                         }
1840                     }
1841                     else
1842                     {
1843                         StringBuilder sb = new StringBuilder();
1844                         bool reply = false;
1845                         bool dm = false;
1846                         foreach (PostClass post in notifyPosts)
1847                         {
1848                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1849                             if (post.IsDm) dm = true;
1850                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1851                             switch (this._cfgCommon.NameBalloon)
1852                             {
1853                                 case MyCommon.NameBalloonEnum.UserID:
1854                                     sb.Append(post.ScreenName).Append(" : ");
1855                                     break;
1856                                 case MyCommon.NameBalloonEnum.NickName:
1857                                     sb.Append(post.Nickname).Append(" : ");
1858                                     break;
1859                             }
1860                             sb.Append(post.TextFromApi);
1861
1862                         }
1863                         //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1864                         StringBuilder title = new StringBuilder();
1865                         ToolTipIcon ntIcon;
1866                         if (this._cfgCommon.DispUsername)
1867                         {
1868                             title.Append(tw.Username);
1869                             title.Append(" - ");
1870                         }
1871                         else
1872                         {
1873                             //title.Clear();
1874                         }
1875                         if (dm)
1876                         {
1877                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1878                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1879                             ntIcon = ToolTipIcon.Warning;
1880                             title.Append(Application.ProductName);
1881                             title.Append(" [DM] ");
1882                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1883                         }
1884                         else if (reply)
1885                         {
1886                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1887                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1888                             ntIcon = ToolTipIcon.Warning;
1889                             title.Append(Application.ProductName);
1890                             title.Append(" [Reply!] ");
1891                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1892                         }
1893                         else
1894                         {
1895                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1896                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1897                             ntIcon = ToolTipIcon.Info;
1898                             title.Append(Application.ProductName);
1899                             title.Append(" ");
1900                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1901                         }
1902                         string bText = sb.ToString();
1903                         if (string.IsNullOrEmpty(bText)) return;
1904                         //NotifyIcon1.BalloonTipText = sb.ToString();
1905                         //NotifyIcon1.ShowBalloonTip(500);
1906                         NotifyIcon1.BalloonTipTitle = title.ToString();
1907                         NotifyIcon1.BalloonTipText = bText;
1908                         NotifyIcon1.BalloonTipIcon = ntIcon;
1909                         NotifyIcon1.ShowBalloonTip(500);
1910                     }
1911                 }
1912             }
1913
1914             //サウンド再生
1915             if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1916             {
1917                 try
1918                 {
1919                     string dir = Application.StartupPath;
1920                     if (Directory.Exists(Path.Combine(dir, "Sounds")))
1921                     {
1922                         dir = Path.Combine(dir, "Sounds");
1923                     }
1924                     using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1925                     {
1926                         player.Play();
1927                     }
1928                 }
1929                 catch (Exception)
1930                 {
1931                 }
1932             }
1933
1934             //mentions新着時に画面ブリンク
1935             if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1936             {
1937                 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1938             }
1939         }
1940
1941         private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1942         {
1943             if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1944
1945             _curItemIndex = _curList.SelectedIndices[0];
1946             if (_curItemIndex > _curList.VirtualListSize - 1) return;
1947
1948             try
1949             {
1950                 this._curPost = GetCurTabPost(_curItemIndex);
1951             }
1952             catch (ArgumentException)
1953             {
1954                 return;
1955             }
1956
1957             this.PushSelectPostChain();
1958
1959             this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1960             //キャッシュの書き換え
1961             ChangeCacheStyleRead(true, _curItemIndex);   //既読へ(フォント、文字色)
1962
1963             ColorizeList();
1964             _colorize = true;
1965         }
1966
1967         private void ChangeCacheStyleRead(bool Read, int Index)
1968         {
1969             var tabInfo = _statuses.Tabs[_curTab.Text];
1970             //Read:true=既読 false=未読
1971             //未読管理していなかったら既読として扱う
1972             if (!tabInfo.UnreadManage ||
1973                !this._cfgCommon.UnreadManage) Read = true;
1974
1975             var listCache = this._listItemCache;
1976             if (listCache == null)
1977                 return;
1978
1979             // キャッシュに含まれていないアイテムは対象外
1980             ListViewItem itm;
1981             PostClass post;
1982             if (!listCache.TryGetValue(Index, out itm, out post))
1983                 return;
1984
1985             ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1986         }
1987
1988         private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1989         {
1990             Font fnt;
1991             //フォント
1992             if (Read)
1993             {
1994                 fnt = _fntReaded;
1995                 Item.SubItems[5].Text = "";
1996             }
1997             else
1998             {
1999                 fnt = _fntUnread;
2000                 Item.SubItems[5].Text = "★";
2001             }
2002             //文字色
2003             Color cl;
2004             if (Post.IsFav)
2005                 cl = _clFav;
2006             else if (Post.RetweetedId != null)
2007                 cl = _clRetweet;
2008             else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
2009                 cl = _clOWL;
2010             else if (Read || !this._cfgCommon.UseUnreadStyle)
2011                 cl = _clReaded;
2012             else
2013                 cl = _clUnread;
2014
2015             if (DList == null || Item.Index == -1)
2016             {
2017                 Item.ForeColor = cl;
2018                 if (this._cfgCommon.UseUnreadStyle)
2019                     Item.Font = fnt;
2020             }
2021             else
2022             {
2023                 DList.Update();
2024                 if (this._cfgCommon.UseUnreadStyle)
2025                     DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2026                 else
2027                     DList.ChangeItemForeColor(Item.Index, cl);
2028                 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2029             }
2030         }
2031
2032         private void ColorizeList()
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             if (_post == null) return;
2043
2044             var listCache = this._listItemCache;
2045             if (listCache == null)
2046                 return;
2047
2048             var index = listCache.StartIndex;
2049             foreach (var cachedPost in listCache.Post)
2050             {
2051                 var backColor = this.JudgeColor(_post, cachedPost);
2052                 this._curList.ChangeItemBackColor(index++, backColor);
2053             }
2054         }
2055
2056         private void ColorizeList(ListViewItem Item, int Index)
2057         {
2058             //Index:更新対象のListviewItem.Index。Colorを返す。
2059             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2060             PostClass _post;
2061             if (_anchorFlag)
2062                 _post = _anchorPost;
2063             else
2064                 _post = _curPost;
2065
2066             PostClass tPost = GetCurTabPost(Index);
2067
2068             if (_post == null) return;
2069
2070             if (Item.Index == -1)
2071                 Item.BackColor = JudgeColor(_post, tPost);
2072             else
2073                 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2074         }
2075
2076         private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2077         {
2078             Color cl;
2079             if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2080                 //@先
2081                 cl = _clAtTo;
2082             else if (TargetPost.IsMe)
2083                 //自分=発言者
2084                 cl = _clSelf;
2085             else if (TargetPost.IsReply)
2086                 //自分宛返信
2087                 cl = _clAtSelf;
2088             else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2089                 //返信先
2090                 cl = _clAtFromTarget;
2091             else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2092                 //その人への返信
2093                 cl = _clAtTarget;
2094             else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2095                 //発言者
2096                 cl = _clTarget;
2097             else
2098                 //その他
2099                 cl = _clListBackcolor;
2100
2101             return cl;
2102         }
2103
2104         private async void PostButton_Click(object sender, EventArgs e)
2105         {
2106             if (StatusText.Text.Trim().Length == 0)
2107             {
2108                 if (!ImageSelector.Enabled)
2109                 {
2110                     await this.DoRefresh();
2111                     return;
2112                 }
2113             }
2114
2115             if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2116             {
2117                 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2118                                                                "Retweet",
2119                                                                MessageBoxButtons.YesNoCancel,
2120                                                                MessageBoxIcon.Question);
2121                 switch (rtResult)
2122                 {
2123                     case DialogResult.Yes:
2124                         StatusText.Text = "";
2125                         await this.doReTweetOfficial(false);
2126                         return;
2127                     case DialogResult.Cancel:
2128                         return;
2129                 }
2130             }
2131
2132             var inReplyToStatusId = this.inReplyTo?.Item1;
2133             var inReplyToScreenName = this.inReplyTo?.Item2;
2134             _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2135
2136             if (this._cfgCommon.Nicoms)
2137             {
2138                 StatusText.SelectionStart = StatusText.Text.Length;
2139                 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2140             }
2141             //if (SettingDialog.UrlConvertAuto)
2142             //{
2143             //    StatusText.SelectionStart = StatusText.Text.Length;
2144             //    UrlConvertAutoToolStripMenuItem_Click(null, null);
2145             //}
2146             //else if (SettingDialog.Nicoms)
2147             //{
2148             //    StatusText.SelectionStart = StatusText.Text.Length;
2149             //    UrlConvert(UrlConverter.Nicoms);
2150             //}
2151             StatusText.SelectionStart = StatusText.Text.Length;
2152             CheckReplyTo(StatusText.Text);
2153
2154             var statusText = this.FormatStatusText(this.StatusText.Text);
2155
2156             if (this.GetRestStatusCount(statusText) < 0)
2157             {
2158                 // 文字数制限を超えているが強制的に投稿するか
2159                 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2160                 if (ret != DialogResult.OK)
2161                     return;
2162             }
2163
2164             var status = new PostingStatus();
2165             status.status = statusText;
2166
2167             status.inReplyToId = this.inReplyTo?.Item1;
2168             status.inReplyToName = this.inReplyTo?.Item2;
2169             if (ImageSelector.Visible)
2170             {
2171                 //画像投稿
2172                 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2173                     return;
2174             }
2175
2176             this.inReplyTo = null;
2177             StatusText.Text = "";
2178             _history.Add(new PostingStatus());
2179             _hisIdx = _history.Count - 1;
2180             if (!ToolStripFocusLockMenuItem.Checked)
2181                 ((Control)ListTab.SelectedTab.Tag).Focus();
2182             urlUndoBuffer = null;
2183             UrlUndoToolStripMenuItem.Enabled = false;  //Undoをできないように設定
2184
2185             //Google検索(試験実装)
2186             if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2187             {
2188                 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2189                 await this.OpenUriInBrowserAsync(tmp);
2190             }
2191
2192             await this.PostMessageAsync(status);
2193         }
2194
2195         private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2196         {
2197             MyCommon._endingFlag = true;
2198             this.Close();
2199         }
2200
2201         private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2202         {
2203             if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2204             {
2205                 //_endingFlag=false:フォームの×ボタン
2206                 e.Cancel = true;
2207                 this.Visible = false;
2208             }
2209             else
2210             {
2211                 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2212                 _ignoreConfigSave = true;
2213                 MyCommon._endingFlag = true;
2214                 TimerTimeline.Enabled = false;
2215                 TimerRefreshIcon.Enabled = false;
2216             }
2217         }
2218
2219         private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2220         {
2221             this.Visible = true;
2222             if (this.WindowState == FormWindowState.Minimized)
2223             {
2224                 this.WindowState = FormWindowState.Normal;
2225             }
2226             this.Activate();
2227             this.BringToFront();
2228         }
2229
2230         private static int errorCount = 0;
2231
2232         private static bool CheckAccountValid()
2233         {
2234             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2235             {
2236                 errorCount += 1;
2237                 if (errorCount > 5)
2238                 {
2239                     errorCount = 0;
2240                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2241                     return true;
2242                 }
2243                 return false;
2244             }
2245             errorCount = 0;
2246             return true;
2247         }
2248
2249         private Task GetHomeTimelineAsync()
2250         {
2251             return this.GetHomeTimelineAsync(loadMore: false);
2252         }
2253
2254         private async Task GetHomeTimelineAsync(bool loadMore)
2255         {
2256             await this.workerSemaphore.WaitAsync();
2257
2258             try
2259             {
2260                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2261
2262                 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2263             }
2264             catch (WebApiException ex)
2265             {
2266                 this._myStatusError = true;
2267                 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2268             }
2269             finally
2270             {
2271                 this.workerSemaphore.Release();
2272             }
2273         }
2274
2275         private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2276         {
2277             if (ct.IsCancellationRequested)
2278                 return;
2279
2280             if (!CheckAccountValid())
2281                 throw new WebApiException("Auth error. Check your account");
2282
2283             bool read;
2284             if (!this._cfgCommon.UnreadManage)
2285                 read = true;
2286             else
2287                 read = this._initial && this._cfgCommon.Read;
2288
2289             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5, loadMore ? -1 : 1));
2290
2291             await Task.Run(async () =>
2292             {
2293                 await this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial)
2294                     .ConfigureAwait(false);
2295
2296                 // 新着時未読クリア
2297                 if (this._cfgCommon.ReadOldPosts)
2298                     this._statuses.SetReadHomeTab();
2299
2300                 var addCount = this._statuses.DistributePosts();
2301
2302                 if (!this._initial)
2303                     this.UpdateTimelineSpeed(addCount);
2304             });
2305
2306             if (ct.IsCancellationRequested)
2307                 return;
2308
2309             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2310
2311             this.RefreshTimeline();
2312         }
2313
2314         /// <summary>
2315         /// タイムラインに追加された発言件数を反映し、タイムラインの流速を更新します
2316         /// </summary>
2317         /// <param name="addCount">直前にタイムラインに追加した発言件数</param>
2318         private void UpdateTimelineSpeed(int addCount)
2319         {
2320             var now = DateTime.Now;
2321             this._tlTimestamps.AddOrUpdate(now, addCount, (k, v) => v + addCount);
2322
2323             var removeKeys = new List<DateTime>();
2324             var oneHour = TimeSpan.FromHours(1);
2325             var tlCount = 0;
2326             foreach (var pair in this._tlTimestamps)
2327             {
2328                 if (now - pair.Key > oneHour)
2329                     removeKeys.Add(pair.Key);
2330                 else
2331                     tlCount += pair.Value;
2332             }
2333             Interlocked.Exchange(ref this._tlCount, tlCount);
2334
2335             int _;
2336             foreach (var key in removeKeys)
2337                 this._tlTimestamps.TryRemove(key, out _);
2338         }
2339
2340         private Task GetReplyAsync()
2341         {
2342             return this.GetReplyAsync(loadMore: false);
2343         }
2344
2345         private async Task GetReplyAsync(bool loadMore)
2346         {
2347             await this.workerSemaphore.WaitAsync();
2348
2349             try
2350             {
2351                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2352
2353                 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2354             }
2355             catch (WebApiException ex)
2356             {
2357                 this._myStatusError = true;
2358                 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2359             }
2360             finally
2361             {
2362                 this.workerSemaphore.Release();
2363             }
2364         }
2365
2366         private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2367         {
2368             if (ct.IsCancellationRequested)
2369                 return;
2370
2371             if (!CheckAccountValid())
2372                 throw new WebApiException("Auth error. Check your account");
2373
2374             bool read;
2375             if (!this._cfgCommon.UnreadManage)
2376                 read = true;
2377             else
2378                 read = this._initial && this._cfgCommon.Read;
2379
2380             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4, loadMore ? -1 : 1));
2381
2382             await Task.Run(async () =>
2383             {
2384                 await this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial)
2385                     .ConfigureAwait(false);
2386
2387                 this._statuses.DistributePosts();
2388             });
2389
2390             if (ct.IsCancellationRequested)
2391                 return;
2392
2393             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2394
2395             this.RefreshTimeline();
2396         }
2397
2398         private Task GetDirectMessagesAsync()
2399         {
2400             return this.GetDirectMessagesAsync(loadMore: false);
2401         }
2402
2403         private async Task GetDirectMessagesAsync(bool loadMore)
2404         {
2405             await this.workerSemaphore.WaitAsync();
2406
2407             try
2408             {
2409                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2410
2411                 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2412             }
2413             catch (WebApiException ex)
2414             {
2415                 this._myStatusError = true;
2416                 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2417             }
2418             finally
2419             {
2420                 this.workerSemaphore.Release();
2421             }
2422         }
2423
2424         private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2425         {
2426             if (ct.IsCancellationRequested)
2427                 return;
2428
2429             if (!CheckAccountValid())
2430                 throw new WebApiException("Auth error. Check your account");
2431
2432             bool read;
2433             if (!this._cfgCommon.UnreadManage)
2434                 read = true;
2435             else
2436                 read = this._initial && this._cfgCommon.Read;
2437
2438             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8, loadMore ? -1 : 1));
2439
2440             await Task.Run(async () =>
2441             {
2442                 await this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore)
2443                     .ConfigureAwait(false);
2444                 await this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore)
2445                     .ConfigureAwait(false);
2446
2447                 this._statuses.DistributePosts();
2448             });
2449
2450             if (ct.IsCancellationRequested)
2451                 return;
2452
2453             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2454
2455             this.RefreshTimeline();
2456         }
2457
2458         private Task GetFavoritesAsync()
2459         {
2460             return this.GetFavoritesAsync(loadMore: false);
2461         }
2462
2463         private async Task GetFavoritesAsync(bool loadMore)
2464         {
2465             await this.workerSemaphore.WaitAsync();
2466
2467             try
2468             {
2469                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2470
2471                 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2472             }
2473             catch (WebApiException ex)
2474             {
2475                 this._myStatusError = true;
2476                 this.StatusLabel.Text = ex.Message;
2477             }
2478             finally
2479             {
2480                 this.workerSemaphore.Release();
2481             }
2482         }
2483
2484         private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2485         {
2486             if (ct.IsCancellationRequested)
2487                 return;
2488
2489             if (!CheckAccountValid())
2490                 throw new WebApiException("Auth error. Check your account");
2491
2492             bool read;
2493             if (!this._cfgCommon.UnreadManage)
2494                 read = true;
2495             else
2496                 read = this._initial && this._cfgCommon.Read;
2497
2498             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2499
2500             await Task.Run(async () =>
2501             {
2502                 await this.tw.GetFavoritesApi(read, loadMore)
2503                     .ConfigureAwait(false);
2504
2505                 this._statuses.DistributePosts();
2506             });
2507
2508             if (ct.IsCancellationRequested)
2509                 return;
2510
2511             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2512
2513             this.RefreshTimeline();
2514         }
2515
2516         private Task GetPublicSearchAllAsync()
2517         {
2518             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch);
2519
2520             return this.GetPublicSearchAsync(tabs, loadMore: false);
2521         }
2522
2523         private Task GetPublicSearchAsync(TabClass tab)
2524         {
2525             return this.GetPublicSearchAsync(tab, loadMore: false);
2526         }
2527
2528         private Task GetPublicSearchAsync(TabClass tab, bool loadMore)
2529         {
2530             return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2531         }
2532
2533         private async Task GetPublicSearchAsync(IEnumerable<TabClass> tabs, bool loadMore)
2534         {
2535             await this.workerSemaphore.WaitAsync();
2536
2537             try
2538             {
2539                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2540
2541                 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2542             }
2543             catch (WebApiException ex)
2544             {
2545                 this._myStatusError = true;
2546                 this.StatusLabel.Text = ex.Message;
2547             }
2548             finally
2549             {
2550                 this.workerSemaphore.Release();
2551             }
2552         }
2553
2554         private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2555         {
2556             if (ct.IsCancellationRequested)
2557                 return;
2558
2559             if (!CheckAccountValid())
2560                 throw new WebApiException("Auth error. Check your account");
2561
2562             bool read;
2563             if (!this._cfgCommon.UnreadManage)
2564                 read = true;
2565             else
2566                 read = this._initial && this._cfgCommon.Read;
2567
2568             p.Report("Search refreshing...");
2569
2570             await Task.Run(async () =>
2571             {
2572                 WebApiException lastException = null;
2573
2574                 foreach (var tab in tabs)
2575                 {
2576                     try
2577                     {
2578                         if (string.IsNullOrEmpty(tab.SearchWords))
2579                             continue;
2580
2581                         await this.tw.GetSearch(read, tab, false)
2582                             .ConfigureAwait(false);
2583
2584                         if (loadMore)
2585                             await this.tw.GetSearch(read, tab, true)
2586                                 .ConfigureAwait(false);
2587                     }
2588                     catch (WebApiException ex)
2589                     {
2590                         lastException = ex;
2591                     }
2592                 }
2593
2594                 this._statuses.DistributePosts();
2595
2596                 if (lastException != null)
2597                     throw new WebApiException(lastException.Message, lastException);
2598             });
2599
2600             if (ct.IsCancellationRequested)
2601                 return;
2602
2603             p.Report("Search refreshed");
2604
2605             this.RefreshTimeline();
2606         }
2607
2608         private Task GetUserTimelineAllAsync()
2609         {
2610             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline);
2611
2612             return this.GetUserTimelineAsync(tabs, loadMore: false);
2613         }
2614
2615         private Task GetUserTimelineAsync(TabClass tab)
2616         {
2617             return this.GetUserTimelineAsync(tab, loadMore: false);
2618         }
2619
2620         private Task GetUserTimelineAsync(TabClass tab, bool loadMore)
2621         {
2622             return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2623         }
2624
2625         private async Task GetUserTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2626         {
2627             await this.workerSemaphore.WaitAsync();
2628
2629             try
2630             {
2631                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2632
2633                 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2634             }
2635             catch (WebApiException ex)
2636             {
2637                 this._myStatusError = true;
2638                 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2639             }
2640             finally
2641             {
2642                 this.workerSemaphore.Release();
2643             }
2644         }
2645
2646         private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2647         {
2648             if (ct.IsCancellationRequested)
2649                 return;
2650
2651             if (!CheckAccountValid())
2652                 throw new WebApiException("Auth error. Check your account");
2653
2654             bool read;
2655             if (!this._cfgCommon.UnreadManage)
2656                 read = true;
2657             else
2658                 read = this._initial && this._cfgCommon.Read;
2659
2660             p.Report("UserTimeline refreshing...");
2661
2662             await Task.Run(async () =>
2663             {
2664                 WebApiException lastException = null;
2665
2666                 foreach (var tab in tabs)
2667                 {
2668                     try
2669                     {
2670                         if (string.IsNullOrEmpty(tab.User))
2671                             continue;
2672
2673                         await this.tw.GetUserTimelineApi(read, tab.User, tab, loadMore)
2674                             .ConfigureAwait(false);
2675                     }
2676                     catch (WebApiException ex)
2677                     {
2678                         lastException = ex;
2679                     }
2680                 }
2681
2682                 this._statuses.DistributePosts();
2683
2684                 if (lastException != null)
2685                     throw new WebApiException(lastException.Message, lastException);
2686             });
2687
2688             if (ct.IsCancellationRequested)
2689                 return;
2690
2691             p.Report("UserTimeline refreshed");
2692
2693             this.RefreshTimeline();
2694         }
2695
2696         private Task GetListTimelineAllAsync()
2697         {
2698             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.Lists);
2699
2700             return this.GetListTimelineAsync(tabs, loadMore: false);
2701         }
2702
2703         private Task GetListTimelineAsync(TabClass tab)
2704         {
2705             return this.GetListTimelineAsync(tab, loadMore: false);
2706         }
2707
2708         private Task GetListTimelineAsync(TabClass tab, bool loadMore)
2709         {
2710             return this.GetListTimelineAsync(new[] { tab }, loadMore);
2711         }
2712
2713         private async Task GetListTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
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.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2722             }
2723             catch (WebApiException ex)
2724             {
2725                 this._myStatusError = true;
2726                 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2727             }
2728             finally
2729             {
2730                 this.workerSemaphore.Release();
2731             }
2732         }
2733
2734         private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2735         {
2736             if (ct.IsCancellationRequested)
2737                 return;
2738
2739             if (!CheckAccountValid())
2740                 throw new WebApiException("Auth error. Check your account");
2741
2742             bool read;
2743             if (!this._cfgCommon.UnreadManage)
2744                 read = true;
2745             else
2746                 read = this._initial && this._cfgCommon.Read;
2747
2748             p.Report("List refreshing...");
2749
2750             await Task.Run(async () =>
2751             {
2752                 WebApiException lastException = null;
2753
2754                 foreach (var tab in tabs)
2755                 {
2756                     try
2757                     {
2758                         if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2759                             continue;
2760
2761                         await this.tw.GetListStatus(read, tab, loadMore, this._initial)
2762                             .ConfigureAwait(false);
2763                     }
2764                     catch (WebApiException ex)
2765                     {
2766                         lastException = ex;
2767                     }
2768                 }
2769
2770                 this._statuses.DistributePosts();
2771
2772                 if (lastException != null)
2773                     throw new WebApiException(lastException.Message, lastException);
2774             });
2775
2776             if (ct.IsCancellationRequested)
2777                 return;
2778
2779             p.Report("List refreshed");
2780
2781             this.RefreshTimeline();
2782         }
2783
2784         private async Task GetRelatedTweetsAsync(TabClass tab)
2785         {
2786             await this.workerSemaphore.WaitAsync();
2787
2788             try
2789             {
2790                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2791
2792                 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2793             }
2794             catch (WebApiException ex)
2795             {
2796                 this._myStatusError = true;
2797                 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2798             }
2799             finally
2800             {
2801                 this.workerSemaphore.Release();
2802             }
2803         }
2804
2805         private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, TabClass tab)
2806         {
2807             if (ct.IsCancellationRequested)
2808                 return;
2809
2810             if (!CheckAccountValid())
2811                 throw new WebApiException("Auth error. Check your account");
2812
2813             bool read;
2814             if (!this._cfgCommon.UnreadManage)
2815                 read = true;
2816             else
2817                 read = this._initial && this._cfgCommon.Read;
2818
2819             p.Report("Related refreshing...");
2820
2821             await Task.Run(async () =>
2822             {
2823                 await this.tw.GetRelatedResult(read, tab)
2824                     .ConfigureAwait(false);
2825
2826                 this._statuses.DistributePosts();
2827             });
2828
2829             if (ct.IsCancellationRequested)
2830                 return;
2831
2832             p.Report("Related refreshed");
2833
2834             this.RefreshTimeline();
2835
2836             var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2837                 .FirstOrDefault(x => x.Text == tab.TabName);
2838
2839             if (tabPage != null)
2840             {
2841                 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2842
2843                 var listView = (DetailsListView)tabPage.Tag;
2844                 var index = tab.IndexOf(tab.RelationTargetPost.RetweetedId ?? tab.RelationTargetPost.StatusId);
2845
2846                 if (index != -1 && index < listView.Items.Count)
2847                 {
2848                     listView.SelectedIndices.Add(index);
2849                     listView.Items[index].Focused = true;
2850                 }
2851             }
2852         }
2853
2854         private async Task FavAddAsync(long statusId, TabClass tab)
2855         {
2856             await this.workerSemaphore.WaitAsync();
2857
2858             try
2859             {
2860                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2861
2862                 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2863             }
2864             catch (WebApiException ex)
2865             {
2866                 this._myStatusError = true;
2867                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2868             }
2869             finally
2870             {
2871                 this.workerSemaphore.Release();
2872             }
2873         }
2874
2875         private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabClass tab)
2876         {
2877             if (ct.IsCancellationRequested)
2878                 return;
2879
2880             if (!CheckAccountValid())
2881                 throw new WebApiException("Auth error. Check your account");
2882
2883             PostClass post;
2884             if (!tab.Posts.TryGetValue(statusId, out post))
2885                 return;
2886
2887             if (post.IsFav)
2888                 return;
2889
2890             await Task.Run(async () =>
2891             {
2892                 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2893
2894                 try
2895                 {
2896                     await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2897                         .IgnoreResponse()
2898                         .ConfigureAwait(false);
2899
2900                     if (this._cfgCommon.RestrictFavCheck)
2901                     {
2902                         var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2903                             .ConfigureAwait(false);
2904
2905                         if (status.Favorited != true)
2906                             throw new WebApiException("NG(Restricted?)");
2907                     }
2908
2909                     this._favTimestamps.Add(DateTime.Now);
2910
2911                     // TLでも取得済みならfav反映
2912                     if (this._statuses.ContainsKey(statusId))
2913                     {
2914                         var postTl = this._statuses[statusId];
2915                         postTl.IsFav = true;
2916
2917                         var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2918                         favTab.AddPostQueue(statusId, postTl.IsRead);
2919                     }
2920
2921                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
2922                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
2923                     {
2924                         if (tb.Contains(statusId))
2925                             tb.Posts[statusId].IsFav = true;
2926                     }
2927
2928                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2929                 }
2930                 catch (WebApiException)
2931                 {
2932                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2933                     throw;
2934                 }
2935
2936                 // 時速表示用
2937                 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2938                 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2939                 {
2940                     if (this._favTimestamps[i] < oneHour)
2941                         this._favTimestamps.RemoveAt(i);
2942                 }
2943
2944                 this._statuses.DistributePosts();
2945             });
2946
2947             if (ct.IsCancellationRequested)
2948                 return;
2949
2950             this.RefreshTimeline();
2951
2952             if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2953             {
2954                 using (ControlTransaction.Update(this._curList))
2955                 {
2956                     var idx = tab.IndexOf(statusId);
2957                     if (idx != -1)
2958                         this.ChangeCacheStyleRead(post.IsRead, idx);
2959                 }
2960
2961                 if (statusId == this._curPost.StatusId)
2962                     await this.DispSelectedPost(true); // 選択アイテム再表示
2963             }
2964         }
2965
2966         private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabClass tab)
2967         {
2968             await this.workerSemaphore.WaitAsync();
2969
2970             try
2971             {
2972                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2973
2974                 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2975             }
2976             catch (WebApiException ex)
2977             {
2978                 this._myStatusError = true;
2979                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2980             }
2981             finally
2982             {
2983                 this.workerSemaphore.Release();
2984             }
2985         }
2986
2987         private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2988         {
2989             if (ct.IsCancellationRequested)
2990                 return;
2991
2992             if (!CheckAccountValid())
2993                 throw new WebApiException("Auth error. Check your account");
2994
2995             var successIds = new List<long>();
2996
2997             await Task.Run(async () =>
2998             {
2999                 //スレッド処理はしない
3000                 var allCount = 0;
3001                 var failedCount = 0;
3002                 foreach (var statusId in statusIds)
3003                 {
3004                     allCount++;
3005
3006                     var post = tab.Posts[statusId];
3007
3008                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
3009
3010                     if (!post.IsFav)
3011                         continue;
3012
3013                     try
3014                     {
3015                         await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
3016                             .IgnoreResponse()
3017                             .ConfigureAwait(false);
3018                     }
3019                     catch (WebApiException)
3020                     {
3021                         failedCount++;
3022                         continue;
3023                     }
3024
3025                     successIds.Add(statusId);
3026                     post.IsFav = false; // リスト再描画必要
3027
3028                     if (this._statuses.ContainsKey(statusId))
3029                     {
3030                         this._statuses[statusId].IsFav = false;
3031                     }
3032
3033                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
3034                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
3035                     {
3036                         if (tb.Contains(statusId))
3037                             tb.Posts[statusId].IsFav = false;
3038                     }
3039                 }
3040             });
3041
3042             if (ct.IsCancellationRequested)
3043                 return;
3044
3045             var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3046             foreach (var statusId in successIds)
3047             {
3048                 // ツイートが削除された訳ではないので IsDeleted はセットしない
3049                 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
3050             }
3051
3052             this.RefreshTimeline();
3053
3054             if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
3055             {
3056                 if (tab.TabType == MyCommon.TabUsageType.Favorites)
3057                 {
3058                     // 色変えは不要
3059                 }
3060                 else
3061                 {
3062                     using (ControlTransaction.Update(this._curList))
3063                     {
3064                         foreach (var statusId in successIds)
3065                         {
3066                             var idx = tab.IndexOf(statusId);
3067                             if (idx == -1)
3068                                 continue;
3069
3070                             var post = tab.Posts[statusId];
3071                             this.ChangeCacheStyleRead(post.IsRead, idx);
3072                         }
3073                     }
3074
3075                     if (successIds.Contains(this._curPost.StatusId))
3076                         await this.DispSelectedPost(true); // 選択アイテム再表示
3077                 }
3078             }
3079         }
3080
3081         private async Task PostMessageAsync(PostingStatus status)
3082         {
3083             await this.workerSemaphore.WaitAsync();
3084
3085             try
3086             {
3087                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3088
3089                 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
3090             }
3091             catch (WebApiException ex)
3092             {
3093                 this._myStatusError = true;
3094                 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
3095             }
3096             finally
3097             {
3098                 this.workerSemaphore.Release();
3099             }
3100         }
3101
3102         private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
3103         {
3104             if (ct.IsCancellationRequested)
3105                 return;
3106
3107             if (!CheckAccountValid())
3108                 throw new WebApiException("Auth error. Check your account");
3109
3110             p.Report("Posting...");
3111
3112             var errMsg = "";
3113
3114             try
3115             {
3116                 await Task.Run(async () =>
3117                 {
3118                     if (status.mediaItems == null || status.mediaItems.Length == 0)
3119                     {
3120                         await this.tw.PostStatus(status.status, status.inReplyToId)
3121                             .ConfigureAwait(false);
3122                     }
3123                     else
3124                     {
3125                         var service = ImageSelector.GetService(status.imageService);
3126                         await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
3127                             .ConfigureAwait(false);
3128                     }
3129                 });
3130
3131                 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3132             }
3133             catch (WebApiException ex)
3134             {
3135                 // 処理は中断せずエラーの表示のみ行う
3136                 errMsg = $"Err:{ex.Message}(PostMessage)";
3137                 p.Report(errMsg);
3138                 this._myStatusError = true;
3139             }
3140             finally
3141             {
3142                 // 使い終わった MediaItem は破棄する
3143                 if (status.mediaItems != null)
3144                 {
3145                     foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
3146                     {
3147                         disposableItem.Dispose();
3148                     }
3149                 }
3150             }
3151
3152             if (ct.IsCancellationRequested)
3153                 return;
3154
3155             if (!string.IsNullOrEmpty(errMsg) &&
3156                 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
3157                 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
3158             {
3159                 var ret = MessageBox.Show(
3160                     string.Format(
3161                         "{0}   --->   [ " + errMsg + " ]" + Environment.NewLine +
3162                         "\"" + status.status + "\"" + Environment.NewLine +
3163                         "{1}",
3164                         Properties.Resources.StatusUpdateFailed1,
3165                         Properties.Resources.StatusUpdateFailed2),
3166                     "Failed to update status",
3167                     MessageBoxButtons.RetryCancel,
3168                     MessageBoxIcon.Question);
3169
3170                 if (ret == DialogResult.Retry)
3171                 {
3172                     await this.PostMessageAsync(status);
3173                 }
3174                 else
3175                 {
3176                     // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3177                     if (this.ToolStripFocusLockMenuItem.Checked)
3178                         this.StatusText_Enter(this.StatusText, EventArgs.Empty);
3179                 }
3180                 return;
3181             }
3182
3183             this._postTimestamps.Add(DateTime.Now);
3184
3185             var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3186             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3187             {
3188                 if (this._postTimestamps[i] < oneHour)
3189                     this._postTimestamps.RemoveAt(i);
3190             }
3191
3192             if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
3193             {
3194                 this.HashMgr.ClearHashtag();
3195                 this.HashStripSplitButton.Text = "#[-]";
3196                 this.HashToggleMenuItem.Checked = false;
3197                 this.HashToggleToolStripMenuItem.Checked = false;
3198             }
3199
3200             this.SetMainWindowTitle();
3201
3202             if (this._cfgCommon.PostAndGet)
3203             {
3204                 if (this.tw.UserStreamActive)
3205                     this.RefreshTimeline();
3206                 else
3207                     await this.GetHomeTimelineAsync();
3208             }
3209         }
3210
3211         private async Task RetweetAsync(IReadOnlyList<long> statusIds)
3212         {
3213             await this.workerSemaphore.WaitAsync();
3214
3215             try
3216             {
3217                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3218
3219                 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
3220             }
3221             catch (WebApiException ex)
3222             {
3223                 this._myStatusError = true;
3224                 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
3225             }
3226             finally
3227             {
3228                 this.workerSemaphore.Release();
3229             }
3230         }
3231
3232         private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
3233         {
3234             if (ct.IsCancellationRequested)
3235                 return;
3236
3237             if (!CheckAccountValid())
3238                 throw new WebApiException("Auth error. Check your account");
3239
3240             bool read;
3241             if (!this._cfgCommon.UnreadManage)
3242                 read = true;
3243             else
3244                 read = this._initial && this._cfgCommon.Read;
3245
3246             p.Report("Posting...");
3247
3248             var retweetTasks = from statusId in statusIds
3249                                select this.tw.PostRetweet(statusId, read);
3250
3251             await Task.WhenAll(retweetTasks)
3252                 .ConfigureAwait(false);
3253
3254             if (ct.IsCancellationRequested)
3255                 return;
3256
3257             p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3258
3259             this._postTimestamps.Add(DateTime.Now);
3260
3261             var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3262             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3263             {
3264                 if (this._postTimestamps[i] < oneHour)
3265                     this._postTimestamps.RemoveAt(i);
3266             }
3267
3268             if (this._cfgCommon.PostAndGet && !this.tw.UserStreamActive)
3269                 await this.GetHomeTimelineAsync();
3270         }
3271
3272         private async Task RefreshFollowerIdsAsync()
3273         {
3274             await this.workerSemaphore.WaitAsync();
3275             try
3276             {
3277                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
3278
3279                 await this.tw.RefreshFollowerIds();
3280
3281                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
3282
3283                 this.RefreshTimeline();
3284                 this.PurgeListViewItemCache();
3285                 this._curList?.Refresh();
3286             }
3287             catch (WebApiException ex)
3288             {
3289                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
3290             }
3291             finally
3292             {
3293                 this.workerSemaphore.Release();
3294             }
3295         }
3296
3297         private async Task RefreshNoRetweetIdsAsync()
3298         {
3299             await this.workerSemaphore.WaitAsync();
3300             try
3301             {
3302                 await this.tw.RefreshNoRetweetIds();
3303
3304                 this.StatusLabel.Text = "NoRetweetIds refreshed";
3305             }
3306             catch (WebApiException ex)
3307             {
3308                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
3309             }
3310             finally
3311             {
3312                 this.workerSemaphore.Release();
3313             }
3314         }
3315
3316         private async Task RefreshBlockIdsAsync()
3317         {
3318             await this.workerSemaphore.WaitAsync();
3319             try
3320             {
3321                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
3322
3323                 await this.tw.RefreshBlockIds();
3324
3325                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
3326             }
3327             catch (WebApiException ex)
3328             {
3329                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
3330             }
3331             finally
3332             {
3333                 this.workerSemaphore.Release();
3334             }
3335         }
3336
3337         private async Task RefreshTwitterConfigurationAsync()
3338         {
3339             await this.workerSemaphore.WaitAsync();
3340             try
3341             {
3342                 await this.tw.RefreshConfiguration();
3343
3344                 if (this.tw.Configuration.PhotoSizeLimit != 0)
3345                 {
3346                     foreach (var service in this.ImageSelector.GetServices())
3347                     {
3348                         service.UpdateTwitterConfiguration(this.tw.Configuration);
3349                     }
3350                 }
3351
3352                 this.PurgeListViewItemCache();
3353
3354                 this._curList?.Refresh();
3355             }
3356             catch (WebApiException ex)
3357             {
3358                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
3359             }
3360             finally
3361             {
3362                 this.workerSemaphore.Release();
3363             }
3364         }
3365
3366         private async Task RefreshMuteUserIdsAsync()
3367         {
3368             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3369
3370             try
3371             {
3372                 await tw.RefreshMuteUserIdsAsync();
3373             }
3374             catch (WebApiException ex)
3375             {
3376                 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3377                 return;
3378             }
3379
3380             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3381         }
3382
3383         private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3384         {
3385             if (e.Button == MouseButtons.Left)
3386             {
3387                 this.Visible = true;
3388                 if (this.WindowState == FormWindowState.Minimized)
3389                 {
3390                     this.WindowState = _formWindowState;
3391                 }
3392                 this.Activate();
3393                 this.BringToFront();
3394             }
3395         }
3396
3397         private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3398         {
3399             switch (this._cfgCommon.ListDoubleClickAction)
3400             {
3401                 case 0:
3402                     MakeReplyOrDirectStatus();
3403                     break;
3404                 case 1:
3405                     await this.FavoriteChange(true);
3406                     break;
3407                 case 2:
3408                     if (_curPost != null)
3409                         await this.ShowUserStatus(_curPost.ScreenName, false);
3410                     break;
3411                 case 3:
3412                     ShowUserTimeline();
3413                     break;
3414                 case 4:
3415                     ShowRelatedStatusesMenuItem_Click(null, null);
3416                     break;
3417                 case 5:
3418                     MoveToHomeToolStripMenuItem_Click(null, null);
3419                     break;
3420                 case 6:
3421                     StatusOpenMenuItem_Click(null, null);
3422                     break;
3423                 case 7:
3424                     //動作なし
3425                     break;
3426             }
3427         }
3428
3429         private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3430         {
3431             await this.FavoriteChange(true);
3432         }
3433
3434         private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3435         {
3436             await this.FavoriteChange(false);
3437         }
3438
3439
3440         private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3441         {
3442             await this.FavoritesRetweetOfficial();
3443         }
3444
3445         private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3446         {
3447             await this.FavoritesRetweetUnofficial();
3448         }
3449
3450         private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3451         {
3452             TabClass tab;
3453             if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3454                 return;
3455
3456             //trueでFavAdd,falseでFavRemove
3457             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3458                 || !this.ExistCurrentPost) return;
3459
3460             if (this._curList.SelectedIndices.Count > 1)
3461             {
3462                 if (FavAdd)
3463                 {
3464                     // 複数ツイートの一括ふぁぼは禁止
3465                     // https://support.twitter.com/articles/76915#favoriting
3466                     MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3467                     _DoFavRetweetFlags = false;
3468                     return;
3469                 }
3470                 else
3471                 {
3472                     if (multiFavoriteChangeDialogEnable)
3473                     {
3474                         var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3475                             Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3476                             MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3477
3478                         if (confirm == DialogResult.Cancel)
3479                             return;
3480                     }
3481                 }
3482             }
3483
3484             if (FavAdd)
3485             {
3486                 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3487                 if (selectedPost.IsFav)
3488                 {
3489                     this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3490                     return;
3491                 }
3492
3493                 await this.FavAddAsync(selectedPost.StatusId, tab);
3494             }
3495             else
3496             {
3497                 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3498                     .Select(x => this.GetCurTabPost(x))
3499                     .Where(x => x.IsFav);
3500
3501                 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3502                 if (statusIds.Length == 0)
3503                 {
3504                     this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3505                     return;
3506                 }
3507
3508                 await this.FavRemoveAsync(statusIds, tab);
3509             }
3510         }
3511
3512         private PostClass GetCurTabPost(int Index)
3513         {
3514             var listCache = this._listItemCache;
3515             if (listCache != null)
3516             {
3517                 ListViewItem item;
3518                 PostClass post;
3519                 if (listCache.TryGetValue(Index, out item, out post))
3520                     return post;
3521             }
3522
3523             return _statuses.Tabs[_curTab.Text][Index];
3524         }
3525
3526         private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3527         {
3528             if (_curList.SelectedIndices.Count > 0)
3529                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3530             else if (_curList.SelectedIndices.Count == 0)
3531                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3532         }
3533
3534         private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3535         {
3536             if (_curList.SelectedIndices.Count > 0)
3537                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3538         }
3539
3540         private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3541         {
3542             if ((!_initialLayout) && this.Visible)
3543             {
3544                 if (this.WindowState == FormWindowState.Normal)
3545                 {
3546                     _mySize = this.ClientSize;
3547                     _mySpDis = this.SplitContainer1.SplitterDistance;
3548                     _mySpDis3 = this.SplitContainer3.SplitterDistance;
3549                     if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3550                     ModifySettingLocal = true;
3551                 }
3552             }
3553         }
3554
3555         private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3556         {
3557             var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3558             if (comparerMode == null)
3559                 return;
3560
3561             this.SetSortColumn(comparerMode.Value);
3562         }
3563
3564         /// <summary>
3565         /// 列インデックスからソートを行う ComparerMode を求める
3566         /// </summary>
3567         /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3568         /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3569         private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3570         {
3571             if (this._iconCol)
3572                 return ComparerMode.Id;
3573
3574             switch (columnIndex)
3575             {
3576                 case 1: // ニックネーム
3577                     return ComparerMode.Nickname;
3578                 case 2: // 本文
3579                     return ComparerMode.Data;
3580                 case 3: // 時刻=発言Id
3581                     return ComparerMode.Id;
3582                 case 4: // 名前
3583                     return ComparerMode.Name;
3584                 case 7: // Source
3585                     return ComparerMode.Source;
3586                 default:
3587                     // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3588                     return null;
3589             }
3590         }
3591
3592         /// <summary>
3593         /// 発言一覧の指定した位置の列でソートする
3594         /// </summary>
3595         /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3596         private void SetSortColumnByDisplayIndex(int columnIndex)
3597         {
3598             // 表示上の列の位置から ColumnHeader を求める
3599             var col = this._curList.Columns.Cast<ColumnHeader>()
3600                 .Where(x => x.DisplayIndex == columnIndex)
3601                 .FirstOrDefault();
3602
3603             if (col == null)
3604                 return;
3605
3606             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3607             if (comparerMode == null)
3608                 return;
3609
3610             this.SetSortColumn(comparerMode.Value);
3611         }
3612
3613         /// <summary>
3614         /// 発言一覧の最後列の項目でソートする
3615         /// </summary>
3616         private void SetSortLastColumn()
3617         {
3618             // 表示上の最後列にある ColumnHeader を求める
3619             var col = this._curList.Columns.Cast<ColumnHeader>()
3620                 .OrderByDescending(x => x.DisplayIndex)
3621                 .First();
3622
3623             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3624             if (comparerMode == null)
3625                 return;
3626
3627             this.SetSortColumn(comparerMode.Value);
3628         }
3629
3630         /// <summary>
3631         /// 発言一覧を指定された ComparerMode に基づいてソートする
3632         /// </summary>
3633         private void SetSortColumn(ComparerMode sortColumn)
3634         {
3635             if (this._cfgCommon.SortOrderLock)
3636                 return;
3637
3638             this._statuses.ToggleSortOrder(sortColumn);
3639             this.InitColumnText();
3640
3641             var list = this._curList;
3642             if (_iconCol)
3643             {
3644                 list.Columns[0].Text = this.ColumnText[0];
3645                 list.Columns[1].Text = this.ColumnText[2];
3646             }
3647             else
3648             {
3649                 for (var i = 0; i <= 7; i++)
3650                 {
3651                     list.Columns[i].Text = this.ColumnText[i];
3652                 }
3653             }
3654
3655             this.PurgeListViewItemCache();
3656
3657             var tab = this._statuses.Tabs[this._curTab.Text];
3658             if (tab.AllCount > 0 && this._curPost != null)
3659             {
3660                 var idx = tab.IndexOf(this._curPost.StatusId);
3661                 if (idx > -1)
3662                 {
3663                     this.SelectListItem(list, idx);
3664                     list.EnsureVisible(idx);
3665                 }
3666             }
3667             list.Refresh();
3668
3669             this.ModifySettingCommon = true;
3670         }
3671
3672         private void TweenMain_LocationChanged(object sender, EventArgs e)
3673         {
3674             if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3675             {
3676                 _myLoc = this.DesktopLocation;
3677                 ModifySettingLocal = true;
3678             }
3679         }
3680
3681         private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3682         {
3683             if (ListTab.SelectedTab == null) return;
3684             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3685             if (!this.ExistCurrentPost)
3686             {
3687                 ReplyStripMenuItem.Enabled = false;
3688                 ReplyAllStripMenuItem.Enabled = false;
3689                 DMStripMenuItem.Enabled = false;
3690                 ShowProfileMenuItem.Enabled = false;
3691                 ShowUserTimelineContextMenuItem.Enabled = false;
3692                 ListManageUserContextToolStripMenuItem2.Enabled = false;
3693                 MoveToFavToolStripMenuItem.Enabled = false;
3694                 TabMenuItem.Enabled = false;
3695                 IDRuleMenuItem.Enabled = false;
3696                 SourceRuleMenuItem.Enabled = false;
3697                 ReadedStripMenuItem.Enabled = false;
3698                 UnreadStripMenuItem.Enabled = false;
3699             }
3700             else
3701             {
3702                 ShowProfileMenuItem.Enabled = true;
3703                 ListManageUserContextToolStripMenuItem2.Enabled = true;
3704                 ReplyStripMenuItem.Enabled = true;
3705                 ReplyAllStripMenuItem.Enabled = true;
3706                 DMStripMenuItem.Enabled = true;
3707                 ShowUserTimelineContextMenuItem.Enabled = true;
3708                 MoveToFavToolStripMenuItem.Enabled = true;
3709                 TabMenuItem.Enabled = true;
3710                 IDRuleMenuItem.Enabled = true;
3711                 SourceRuleMenuItem.Enabled = true;
3712                 ReadedStripMenuItem.Enabled = true;
3713                 UnreadStripMenuItem.Enabled = true;
3714             }
3715             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3716             {
3717                 FavAddToolStripMenuItem.Enabled = false;
3718                 FavRemoveToolStripMenuItem.Enabled = false;
3719                 StatusOpenMenuItem.Enabled = false;
3720                 FavorareMenuItem.Enabled = false;
3721                 ShowRelatedStatusesMenuItem.Enabled = false;
3722
3723                 ReTweetStripMenuItem.Enabled = false;
3724                 ReTweetUnofficialStripMenuItem.Enabled = false;
3725                 QuoteStripMenuItem.Enabled = false;
3726                 FavoriteRetweetContextMenu.Enabled = false;
3727                 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3728             }
3729             else
3730             {
3731                 FavAddToolStripMenuItem.Enabled = true;
3732                 FavRemoveToolStripMenuItem.Enabled = true;
3733                 StatusOpenMenuItem.Enabled = true;
3734                 FavorareMenuItem.Enabled = true;
3735                 ShowRelatedStatusesMenuItem.Enabled = true;  //PublicSearchの時問題出るかも
3736
3737                 if (_curPost.IsMe)
3738                 {
3739                     ReTweetStripMenuItem.Enabled = false;  //公式RTは無効に
3740                     ReTweetUnofficialStripMenuItem.Enabled = true;
3741                     QuoteStripMenuItem.Enabled = true;
3742                     FavoriteRetweetContextMenu.Enabled = false;  //公式RTは無効に
3743                     FavoriteRetweetUnofficialContextMenu.Enabled = true;
3744                 }
3745                 else
3746                 {
3747                     if (_curPost.IsProtect)
3748                     {
3749                         ReTweetStripMenuItem.Enabled = false;
3750                         ReTweetUnofficialStripMenuItem.Enabled = false;
3751                         QuoteStripMenuItem.Enabled = false;
3752                         FavoriteRetweetContextMenu.Enabled = false;
3753                         FavoriteRetweetUnofficialContextMenu.Enabled = false;
3754                     }
3755                     else
3756                     {
3757                         ReTweetStripMenuItem.Enabled = true;
3758                         ReTweetUnofficialStripMenuItem.Enabled = true;
3759                         QuoteStripMenuItem.Enabled = true;
3760                         FavoriteRetweetContextMenu.Enabled = true;
3761                         FavoriteRetweetUnofficialContextMenu.Enabled = true;
3762                     }
3763                 }
3764             }
3765             //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3766             //{
3767             //    RefreshMoreStripMenuItem.Enabled = true;
3768             //}
3769             //else
3770             //{
3771             //    RefreshMoreStripMenuItem.Enabled = false;
3772             //}
3773             if (!this.ExistCurrentPost
3774                 || _curPost.InReplyToStatusId == null)
3775             {
3776                 RepliedStatusOpenMenuItem.Enabled = false;
3777             }
3778             else
3779             {
3780                 RepliedStatusOpenMenuItem.Enabled = true;
3781             }
3782             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3783             {
3784                 MoveToRTHomeMenuItem.Enabled = false;
3785             }
3786             else
3787             {
3788                 MoveToRTHomeMenuItem.Enabled = true;
3789             }
3790
3791             if (this.ExistCurrentPost)
3792             {
3793                 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3794                 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3795                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3796                 else
3797                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3798             }
3799         }
3800
3801         private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3802         {
3803             MakeReplyOrDirectStatus(false, true);
3804         }
3805
3806         private void DMStripMenuItem_Click(object sender, EventArgs e)
3807         {
3808             MakeReplyOrDirectStatus(false, false);
3809         }
3810
3811         private async Task doStatusDelete()
3812         {
3813             if (this._curTab == null || this._curList == null)
3814                 return;
3815
3816             if (this._curList.SelectedIndices.Count == 0)
3817                 return;
3818
3819             var posts = this._curList.SelectedIndices.Cast<int>()
3820                 .Select(x => this.GetCurTabPost(x))
3821                 .ToArray();
3822
3823             // 選択されたツイートの中に削除可能なものが一つでもあるか
3824             if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3825                 return;
3826
3827             var ret = MessageBox.Show(this,
3828                 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3829                 Properties.Resources.DeleteStripMenuItem_ClickText2,
3830                 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3831
3832             if (ret != DialogResult.OK)
3833                 return;
3834
3835             var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3836
3837             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3838             {
3839                 Exception lastException = null;
3840                 foreach (var post in posts)
3841                 {
3842                     if (!post.CanDeleteBy(this.tw.UserId))
3843                         continue;
3844
3845                     try
3846                     {
3847                         if (post.IsDm)
3848                         {
3849                             await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3850                                 .IgnoreResponse();
3851                         }
3852                         else
3853                         {
3854                             if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3855                                 // 他人に RT された自分のツイート
3856                                 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3857                                     .IgnoreResponse();
3858                             else
3859                                 // 自分のツイート or 自分が RT したツイート
3860                                 await this.twitterApi.StatusesDestroy(post.StatusId)
3861                                     .IgnoreResponse();
3862                         }
3863                     }
3864                     catch (WebApiException ex)
3865                     {
3866                         lastException = ex;
3867                         continue;
3868                     }
3869
3870                     this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3871                 }
3872
3873                 if (lastException == null)
3874                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3875                 else
3876                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3877
3878                 this.PurgeListViewItemCache();
3879                 this._curPost = null;
3880                 this._curItemIndex = -1;
3881
3882                 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3883                 {
3884                     var listView = (DetailsListView)tabPage.Tag;
3885                     var tab = this._statuses.Tabs[tabPage.Text];
3886
3887                     using (ControlTransaction.Update(listView))
3888                     {
3889                         listView.VirtualListSize = tab.AllCount;
3890
3891                         if (tabPage == this._curTab)
3892                         {
3893                             listView.SelectedIndices.Clear();
3894
3895                             if (tab.AllCount != 0)
3896                             {
3897                                 int selectedIndex;
3898                                 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3899                                     selectedIndex = focusedIndex;
3900                                 else
3901                                     selectedIndex = tab.AllCount - 1;
3902
3903                                 listView.SelectedIndices.Add(selectedIndex);
3904                                 listView.EnsureVisible(selectedIndex);
3905                                 listView.FocusedItem = listView.Items[selectedIndex];
3906                             }
3907                         }
3908                     }
3909
3910                     if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3911                     {
3912                         if (tabPage.ImageIndex == 0)
3913                             tabPage.ImageIndex = -1; // タブアイコン
3914                     }
3915                 }
3916
3917                 if (!this._cfgCommon.TabIconDisp)
3918                     this.ListTab.Refresh();
3919             }
3920         }
3921
3922         private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3923         {
3924             await this.doStatusDelete();
3925         }
3926
3927         private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3928         {
3929             using (ControlTransaction.Update(this._curList))
3930             {
3931                 foreach (int idx in _curList.SelectedIndices)
3932                 {
3933                     var post = this._statuses.Tabs[this._curTab.Text][idx];
3934                     this._statuses.SetReadAllTab(post.StatusId, read: true);
3935                     ChangeCacheStyleRead(true, idx);
3936                 }
3937                 ColorizeList();
3938             }
3939             foreach (TabPage tb in ListTab.TabPages)
3940             {
3941                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3942                 {
3943                     if (this._cfgCommon.TabIconDisp)
3944                     {
3945                         if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3946                     }
3947                 }
3948             }
3949             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3950         }
3951
3952         private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3953         {
3954             using (ControlTransaction.Update(this._curList))
3955             {
3956                 foreach (int idx in _curList.SelectedIndices)
3957                 {
3958                     var post = this._statuses.Tabs[this._curTab.Text][idx];
3959                     this._statuses.SetReadAllTab(post.StatusId, read: false);
3960                     ChangeCacheStyleRead(false, idx);
3961                 }
3962                 ColorizeList();
3963             }
3964             foreach (TabPage tb in ListTab.TabPages)
3965             {
3966                 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3967                 {
3968                     if (this._cfgCommon.TabIconDisp)
3969                     {
3970                         if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3971                     }
3972                 }
3973             }
3974             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3975         }
3976
3977         private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3978         {
3979             await this.DoRefresh();
3980         }
3981
3982         private async Task DoRefresh()
3983         {
3984             if (_curTab != null)
3985             {
3986                 TabClass tab;
3987                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3988                     return;
3989
3990                 switch (_statuses.Tabs[_curTab.Text].TabType)
3991                 {
3992                     case MyCommon.TabUsageType.Mentions:
3993                         await this.GetReplyAsync();
3994                         break;
3995                     case MyCommon.TabUsageType.DirectMessage:
3996                         await this.GetDirectMessagesAsync();
3997                         break;
3998                     case MyCommon.TabUsageType.Favorites:
3999                         await this.GetFavoritesAsync();
4000                         break;
4001                     //case MyCommon.TabUsageType.Profile:
4002                         //// TODO
4003                     case MyCommon.TabUsageType.PublicSearch:
4004                         //// TODO
4005                         if (string.IsNullOrEmpty(tab.SearchWords)) return;
4006                         await this.GetPublicSearchAsync(tab);
4007                         break;
4008                     case MyCommon.TabUsageType.UserTimeline:
4009                         await this.GetUserTimelineAsync(tab);
4010                         break;
4011                     case MyCommon.TabUsageType.Lists:
4012                         //// TODO
4013                         if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4014                         await this.GetListTimelineAsync(tab);
4015                         break;
4016                     default:
4017                         await this.GetHomeTimelineAsync();
4018                         break;
4019                 }
4020             }
4021             else
4022             {
4023                 await this.GetHomeTimelineAsync();
4024             }
4025         }
4026
4027         private async Task DoRefreshMore()
4028         {
4029             //ページ指定をマイナス1に
4030             if (_curTab != null)
4031             {
4032                 TabClass tab;
4033                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4034                     return;
4035
4036                 switch (_statuses.Tabs[_curTab.Text].TabType)
4037                 {
4038                     case MyCommon.TabUsageType.Mentions:
4039                         await this.GetReplyAsync(loadMore: true);
4040                         break;
4041                     case MyCommon.TabUsageType.DirectMessage:
4042                         await this.GetDirectMessagesAsync(loadMore: true);
4043                         break;
4044                     case MyCommon.TabUsageType.Favorites:
4045                         await this.GetFavoritesAsync(loadMore: true);
4046                         break;
4047                     case MyCommon.TabUsageType.Profile:
4048                         //// TODO
4049                         break;
4050                     case MyCommon.TabUsageType.PublicSearch:
4051                         // TODO
4052                         if (string.IsNullOrEmpty(tab.SearchWords)) return;
4053                         await this.GetPublicSearchAsync(tab, loadMore: true);
4054                         break;
4055                     case MyCommon.TabUsageType.UserTimeline:
4056                         await this.GetUserTimelineAsync(tab, loadMore: true);
4057                         break;
4058                     case MyCommon.TabUsageType.Lists:
4059                         //// TODO
4060                         if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4061                         await this.GetListTimelineAsync(tab, loadMore: true);
4062                         break;
4063                     default:
4064                         await this.GetHomeTimelineAsync(loadMore: true);
4065                         break;
4066                 }
4067             }
4068             else
4069             {
4070                 await this.GetHomeTimelineAsync(loadMore: true);
4071             }
4072         }
4073
4074         private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4075         {
4076             DialogResult result = DialogResult.Abort;
4077
4078             using (var settingDialog = new AppendSettingDialog())
4079             {
4080                 settingDialog.Icon = this.MainIcon;
4081                 settingDialog.Owner = this;
4082                 settingDialog.ShowInTaskbar = showTaskbarIcon;
4083                 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4084
4085                 settingDialog.tw = this.tw;
4086                 settingDialog.twitterApi = this.twitterApi;
4087
4088                 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4089
4090                 try
4091                 {
4092                     result = settingDialog.ShowDialog(this);
4093                 }
4094                 catch (Exception)
4095                 {
4096                     return DialogResult.Abort;
4097                 }
4098
4099                 if (result == DialogResult.OK)
4100                 {
4101                     lock (_syncObject)
4102                     {
4103                         settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4104                     }
4105                 }
4106             }
4107
4108             return result;
4109         }
4110
4111         private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4112         {
4113             // 設定画面表示前のユーザー情報
4114             var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4115
4116             var oldIconSz = this._cfgCommon.IconSize;
4117
4118             if (ShowSettingDialog() == DialogResult.OK)
4119             {
4120                 lock (_syncObject)
4121                 {
4122                     tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4123                     tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4124                     ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4125                     ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4126                     ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4127                     TwitterApiConnection.RestApiBase = this._cfgCommon.TwitterApiBaseUri;
4128
4129                     Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4130                     Networking.SetWebProxy(this._cfgLocal.ProxyType,
4131                         this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4132                         this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4133                     Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
4134
4135                     ImageSelector.Reset(tw, this.tw.Configuration);
4136
4137                     try
4138                     {
4139                         if (this._cfgCommon.TabIconDisp)
4140                         {
4141                             ListTab.DrawItem -= ListTab_DrawItem;
4142                             ListTab.DrawMode = TabDrawMode.Normal;
4143                             ListTab.ImageList = this.TabImage;
4144                         }
4145                         else
4146                         {
4147                             ListTab.DrawItem -= ListTab_DrawItem;
4148                             ListTab.DrawItem += ListTab_DrawItem;
4149                             ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4150                             ListTab.ImageList = null;
4151                         }
4152                     }
4153                     catch (Exception ex)
4154                     {
4155                         ex.Data["Instance"] = "ListTab(TabIconDisp)";
4156                         ex.Data["IsTerminatePermission"] = false;
4157                         throw;
4158                     }
4159
4160                     try
4161                     {
4162                         if (!this._cfgCommon.UnreadManage)
4163                         {
4164                             ReadedStripMenuItem.Enabled = false;
4165                             UnreadStripMenuItem.Enabled = false;
4166                             if (this._cfgCommon.TabIconDisp)
4167                             {
4168                                 foreach (TabPage myTab in ListTab.TabPages)
4169                                 {
4170                                     myTab.ImageIndex = -1;
4171                                 }
4172                             }
4173                         }
4174                         else
4175                         {
4176                             ReadedStripMenuItem.Enabled = true;
4177                             UnreadStripMenuItem.Enabled = true;
4178                         }
4179                     }
4180                     catch (Exception ex)
4181                     {
4182                         ex.Data["Instance"] = "ListTab(UnreadManage)";
4183                         ex.Data["IsTerminatePermission"] = false;
4184                         throw;
4185                     }
4186
4187                     // タブの表示位置の決定
4188                     SetTabAlignment();
4189
4190                     SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4191
4192                     var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4193                     imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4194                     imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4195
4196                     this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4197                     this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4198                     _fntUnread = this._cfgLocal.FontUnread;
4199                     _clUnread = this._cfgLocal.ColorUnread;
4200                     _fntReaded = this._cfgLocal.FontRead;
4201                     _clReaded = this._cfgLocal.ColorRead;
4202                     _clFav = this._cfgLocal.ColorFav;
4203                     _clOWL = this._cfgLocal.ColorOWL;
4204                     _clRetweet = this._cfgLocal.ColorRetweet;
4205                     _fntDetail = this._cfgLocal.FontDetail;
4206                     _clDetail = this._cfgLocal.ColorDetail;
4207                     _clDetailLink = this._cfgLocal.ColorDetailLink;
4208                     _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4209                     _clSelf = this._cfgLocal.ColorSelf;
4210                     _clAtSelf = this._cfgLocal.ColorAtSelf;
4211                     _clTarget = this._cfgLocal.ColorTarget;
4212                     _clAtTarget = this._cfgLocal.ColorAtTarget;
4213                     _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4214                     _clAtTo = this._cfgLocal.ColorAtTo;
4215                     _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4216                     _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4217                     _clInputFont = this._cfgLocal.ColorInputFont;
4218                     _fntInputFont = this._cfgLocal.FontInputFont;
4219                     _brsBackColorMine.Dispose();
4220                     _brsBackColorAt.Dispose();
4221                     _brsBackColorYou.Dispose();
4222                     _brsBackColorAtYou.Dispose();
4223                     _brsBackColorAtFromTarget.Dispose();
4224                     _brsBackColorAtTo.Dispose();
4225                     _brsBackColorNone.Dispose();
4226                     _brsBackColorMine = new SolidBrush(_clSelf);
4227                     _brsBackColorAt = new SolidBrush(_clAtSelf);
4228                     _brsBackColorYou = new SolidBrush(_clTarget);
4229                     _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4230                     _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4231                     _brsBackColorAtTo = new SolidBrush(_clAtTo);
4232                     _brsBackColorNone = new SolidBrush(_clListBackcolor);
4233
4234                     try
4235                     {
4236                         if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4237                         StatusText.Font = _fntInputFont;
4238                         StatusText.ForeColor = _clInputFont;
4239                     }
4240                     catch (Exception ex)
4241                     {
4242                         MessageBox.Show(ex.Message);
4243                     }
4244
4245                     try
4246                     {
4247                         InitDetailHtmlFormat();
4248                     }
4249                     catch (Exception ex)
4250                     {
4251                         ex.Data["Instance"] = "Font";
4252                         ex.Data["IsTerminatePermission"] = false;
4253                         throw;
4254                     }
4255
4256                     try
4257                     {
4258                         foreach (TabPage tb in ListTab.TabPages)
4259                         {
4260                             if (this._cfgCommon.TabIconDisp)
4261                             {
4262                                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4263                                     tb.ImageIndex = -1;
4264                                 else
4265                                     tb.ImageIndex = 0;
4266                             }
4267                         }
4268                     }
4269                     catch (Exception ex)
4270                     {
4271                         ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4272                         ex.Data["IsTerminatePermission"] = false;
4273                         throw;
4274                     }
4275
4276                     try
4277                     {
4278                         var oldIconCol = _iconCol;
4279
4280                         if (this._cfgCommon.IconSize != oldIconSz)
4281                             ApplyListViewIconSize(this._cfgCommon.IconSize);
4282
4283                         foreach (TabPage tp in ListTab.TabPages)
4284                         {
4285                             DetailsListView lst = (DetailsListView)tp.Tag;
4286
4287                             using (ControlTransaction.Update(lst))
4288                             {
4289                                 lst.GridLines = this._cfgCommon.ShowGrid;
4290                                 lst.Font = _fntReaded;
4291                                 lst.BackColor = _clListBackcolor;
4292
4293                                 if (_iconCol != oldIconCol)
4294                                     ResetColumns(lst);
4295                             }
4296                         }
4297                     }
4298                     catch (Exception ex)
4299                     {
4300                         ex.Data["Instance"] = "ListView(IconSize)";
4301                         ex.Data["IsTerminatePermission"] = false;
4302                         throw;
4303                     }
4304
4305                     SetMainWindowTitle();
4306                     SetNotifyIconText();
4307
4308                     this.PurgeListViewItemCache();
4309                     _curList?.Refresh();
4310                     ListTab.Refresh();
4311
4312                     _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4313                     if (this._cfgCommon.HotkeyEnabled)
4314                     {
4315                         ///グローバルホットキーの登録。設定で変更可能にするかも
4316                         HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4317                         if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4318                             modKey |= HookGlobalHotkey.ModKeys.Alt;
4319                         if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4320                             modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4321                         if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4322                             modKey |=  HookGlobalHotkey.ModKeys.Shift;
4323                         if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4324                             modKey |= HookGlobalHotkey.ModKeys.Win;
4325
4326                         _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4327                     }
4328
4329                     if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4330                     try
4331                     {
4332                         StatusText_TextChanged(null, null);
4333                     }
4334                     catch (Exception)
4335                     {
4336                     }
4337                 }
4338             }
4339             else
4340             {
4341                 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4342                 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4343             }
4344
4345             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4346
4347             this.TopMost = this._cfgCommon.AlwaysTop;
4348             SaveConfigsAll(false);
4349
4350             if (tw.Username != oldUser.Username)
4351                 await this.doGetFollowersMenu();
4352         }
4353
4354         /// <summary>
4355         /// タブの表示位置を設定する
4356         /// </summary>
4357         private void SetTabAlignment()
4358         {
4359             var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4360             if (ListTab.Alignment == newAlignment) return;
4361
4362             // 各タブのリスト上の選択位置などを退避
4363             var listSelections = this.SaveListViewSelection();
4364
4365             ListTab.Alignment = newAlignment;
4366
4367             foreach (TabPage tab in ListTab.TabPages)
4368             {
4369                 DetailsListView lst = (DetailsListView)tab.Tag;
4370                 TabClass tabInfo = _statuses.Tabs[tab.Text];
4371                 using (ControlTransaction.Update(lst))
4372                 {
4373                     // 選択位置などを復元
4374                     this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4375                 }
4376             }
4377         }
4378
4379         private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4380         {
4381             // アイコンサイズの再設定
4382             _iconCol = false;
4383             switch (iconSz)
4384             {
4385                 case MyCommon.IconSizes.IconNone:
4386                     _iconSz = 0;
4387                     break;
4388                 case MyCommon.IconSizes.Icon16:
4389                     _iconSz = 16;
4390                     break;
4391                 case MyCommon.IconSizes.Icon24:
4392                     _iconSz = 26;
4393                     break;
4394                 case MyCommon.IconSizes.Icon48:
4395                     _iconSz = 48;
4396                     break;
4397                 case MyCommon.IconSizes.Icon48_2:
4398                     _iconSz = 48;
4399                     _iconCol = true;
4400                     break;
4401             }
4402
4403             if (_iconSz > 0)
4404             {
4405                 // ディスプレイの DPI 設定を考慮したサイズを設定する
4406                 _listViewImageList.ImageSize = new Size(
4407                     1,
4408                     (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4409             }
4410             else
4411             {
4412                 _listViewImageList.ImageSize = new Size(1, 1);
4413             }
4414         }
4415
4416         private void ResetColumns(DetailsListView list)
4417         {
4418             using (ControlTransaction.Update(list))
4419             using (ControlTransaction.Layout(list, false))
4420             {
4421                 // カラムヘッダの再設定
4422                 list.ColumnClick -= MyList_ColumnClick;
4423                 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4424                 list.ColumnReordered -= MyList_ColumnReordered;
4425                 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4426
4427                 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4428                 list.Columns.Clear();
4429                 cols.ForEach(col => col.Dispose());
4430                 cols.Clear();
4431
4432                 InitColumns(list, true);
4433
4434                 list.ColumnClick += MyList_ColumnClick;
4435                 list.DrawColumnHeader += MyList_DrawColumnHeader;
4436                 list.ColumnReordered += MyList_ColumnReordered;
4437                 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4438             }
4439         }
4440
4441         private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4442         {
4443             if (e.Url.AbsoluteUri != "about:blank")
4444             {
4445                 await this.DispSelectedPost();
4446                 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4447             }
4448         }
4449
4450         private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4451         {
4452             if (e.Url.Scheme == "data")
4453             {
4454                 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4455             }
4456             else if (e.Url.AbsoluteUri != "about:blank")
4457             {
4458                 e.Cancel = true;
4459                 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4460                 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4461             }
4462         }
4463
4464         public void AddNewTabForSearch(string searchWord)
4465         {
4466             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4467             foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4468             {
4469                 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4470                 {
4471                     foreach (TabPage tp in ListTab.TabPages)
4472                     {
4473                         if (tb.TabName == tp.Text)
4474                         {
4475                             ListTab.SelectedTab = tp;
4476                             return;
4477                         }
4478                     }
4479                 }
4480             }
4481             //ユニークなタブ名生成
4482             string tabName = searchWord;
4483             for (int i = 0; i <= 100; i++)
4484             {
4485                 if (_statuses.ContainsTab(tabName))
4486                     tabName += "_";
4487                 else
4488                     break;
4489             }
4490             //タブ追加
4491             _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4492             AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4493             //追加したタブをアクティブに
4494             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4495             //検索条件の設定
4496             ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4497             cmb.Items.Add(searchWord);
4498             cmb.Text = searchWord;
4499             SaveConfigsTabs();
4500             //検索実行
4501             this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4502         }
4503
4504         private void ShowUserTimeline()
4505         {
4506             if (!this.ExistCurrentPost) return;
4507             AddNewTabForUserTimeline(_curPost.ScreenName);
4508         }
4509
4510         private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4511         {
4512             if (e.KeyCode == Keys.Escape)
4513             {
4514                 TabPage relTp = ListTab.SelectedTab;
4515                 RemoveSpecifiedTab(relTp.Text, false);
4516                 SaveConfigsTabs();
4517                 e.SuppressKeyPress = true;
4518             }
4519         }
4520
4521         public void AddNewTabForUserTimeline(string user)
4522         {
4523             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4524             foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4525             {
4526                 if (tb.User == user)
4527                 {
4528                     foreach (TabPage tp in ListTab.TabPages)
4529                     {
4530                         if (tb.TabName == tp.Text)
4531                         {
4532                             ListTab.SelectedTab = tp;
4533                             return;
4534                         }
4535                     }
4536                 }
4537             }
4538             //ユニークなタブ名生成
4539             string tabName = "user:" + user;
4540             while (_statuses.ContainsTab(tabName))
4541             {
4542                 tabName += "_";
4543             }
4544             //タブ追加
4545             var tab = new TabClass(tabName, MyCommon.TabUsageType.UserTimeline);
4546             this._statuses.AddTab(tab);
4547             tab.User = user;
4548             AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4549             //追加したタブをアクティブに
4550             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4551             SaveConfigsTabs();
4552             //検索実行
4553             this.GetUserTimelineAsync(tab);
4554         }
4555
4556         public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4557         {
4558             //重複チェック
4559             foreach (TabPage tb in ListTab.TabPages)
4560             {
4561                 if (tb.Text == tabName) return false;
4562             }
4563
4564             //新規タブ名チェック
4565             if (tabName == Properties.Resources.AddNewTabText1) return false;
4566
4567             //タブタイプ重複チェック
4568             if (!startup)
4569             {
4570                 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4571                    tabType == MyCommon.TabUsageType.Favorites ||
4572                    tabType == MyCommon.TabUsageType.Home ||
4573                    tabType == MyCommon.TabUsageType.Mentions ||
4574                    tabType == MyCommon.TabUsageType.Related)
4575                 {
4576                     if (_statuses.GetTabByType(tabType) != null) return false;
4577                 }
4578             }
4579
4580             var _tabPage = new TabPage();
4581             var _listCustom = new DetailsListView();
4582
4583             int cnt = ListTab.TabPages.Count;
4584
4585             ///ToDo:Create and set controls follow tabtypes
4586
4587             using (ControlTransaction.Update(_listCustom))
4588             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4589             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4590             using (ControlTransaction.Layout(this.SplitContainer1, false))
4591             using (ControlTransaction.Layout(this.ListTab, false))
4592             using (ControlTransaction.Layout(this))
4593             using (ControlTransaction.Layout(_tabPage, false))
4594             {
4595                 _tabPage.Controls.Add(_listCustom);
4596
4597                 /// UserTimeline関連
4598                 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4599                 {
4600                     var label = new Label();
4601                     label.Dock = DockStyle.Top;
4602                     label.Name = "labelUser";
4603                     label.TabIndex = 0;
4604                     if (tabType == MyCommon.TabUsageType.Lists)
4605                     {
4606                         label.Text = listInfo.ToString();
4607                     }
4608                     else
4609                     {
4610                         label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4611                     }
4612                     label.TextAlign = ContentAlignment.MiddleLeft;
4613                     using (ComboBox tmpComboBox = new ComboBox())
4614                     {
4615                         label.Height = tmpComboBox.Height;
4616                     }
4617                     _tabPage.Controls.Add(label);
4618                 }
4619                 /// 検索関連の準備
4620                 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4621                 {
4622                     var pnl = new Panel();
4623
4624                     var lbl = new Label();
4625                     var cmb = new ComboBox();
4626                     var btn = new Button();
4627                     var cmbLang = new ComboBox();
4628
4629                     using (ControlTransaction.Layout(pnl, false))
4630                     {
4631                         pnl.Controls.Add(cmb);
4632                         pnl.Controls.Add(cmbLang);
4633                         pnl.Controls.Add(btn);
4634                         pnl.Controls.Add(lbl);
4635                         pnl.Name = "panelSearch";
4636                         pnl.TabIndex = 0;
4637                         pnl.Dock = DockStyle.Top;
4638                         pnl.Height = cmb.Height;
4639                         pnl.Enter += SearchControls_Enter;
4640                         pnl.Leave += SearchControls_Leave;
4641
4642                         cmb.Text = "";
4643                         cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4644                         cmb.Dock = DockStyle.Fill;
4645                         cmb.Name = "comboSearch";
4646                         cmb.DropDownStyle = ComboBoxStyle.DropDown;
4647                         cmb.ImeMode = ImeMode.NoControl;
4648                         cmb.TabStop = false;
4649                         cmb.TabIndex = 1;
4650                         cmb.AutoCompleteMode = AutoCompleteMode.None;
4651                         cmb.KeyDown += SearchComboBox_KeyDown;
4652
4653                         cmbLang.Text = "";
4654                         cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4655                         cmbLang.Dock = DockStyle.Right;
4656                         cmbLang.Width = 50;
4657                         cmbLang.Name = "comboLang";
4658                         cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4659                         cmbLang.TabStop = false;
4660                         cmbLang.TabIndex = 2;
4661                         cmbLang.Items.Add("");
4662                         cmbLang.Items.Add("ja");
4663                         cmbLang.Items.Add("en");
4664                         cmbLang.Items.Add("ar");
4665                         cmbLang.Items.Add("da");
4666                         cmbLang.Items.Add("nl");
4667                         cmbLang.Items.Add("fa");
4668                         cmbLang.Items.Add("fi");
4669                         cmbLang.Items.Add("fr");
4670                         cmbLang.Items.Add("de");
4671                         cmbLang.Items.Add("hu");
4672                         cmbLang.Items.Add("is");
4673                         cmbLang.Items.Add("it");
4674                         cmbLang.Items.Add("no");
4675                         cmbLang.Items.Add("pl");
4676                         cmbLang.Items.Add("pt");
4677                         cmbLang.Items.Add("ru");
4678                         cmbLang.Items.Add("es");
4679                         cmbLang.Items.Add("sv");
4680                         cmbLang.Items.Add("th");
4681
4682                         lbl.Text = "Search(C-S-f)";
4683                         lbl.Name = "label1";
4684                         lbl.Dock = DockStyle.Left;
4685                         lbl.Width = 90;
4686                         lbl.Height = cmb.Height;
4687                         lbl.TextAlign = ContentAlignment.MiddleLeft;
4688                         lbl.TabIndex = 0;
4689
4690                         btn.Text = "Search";
4691                         btn.Name = "buttonSearch";
4692                         btn.UseVisualStyleBackColor = true;
4693                         btn.Dock = DockStyle.Right;
4694                         btn.TabStop = false;
4695                         btn.TabIndex = 3;
4696                         btn.Click += SearchButton_Click;
4697
4698                         TabClass tab;
4699                         if (_statuses.Tabs.TryGetValue(tabName, out tab))
4700                         {
4701                             if (!string.IsNullOrEmpty(tab.SearchWords))
4702                             {
4703                                 cmb.Items.Add(tab.SearchWords);
4704                                 cmb.Text = tab.SearchWords;
4705                             }
4706
4707                             cmbLang.Text = tab.SearchLang;
4708                         }
4709
4710                         _tabPage.Controls.Add(pnl);
4711                     }
4712                 }
4713
4714                 _tabPage.Tag = _listCustom;
4715                 this.ListTab.Controls.Add(_tabPage);
4716
4717                 _tabPage.Location = new Point(4, 4);
4718                 _tabPage.Name = "CTab" + cnt.ToString();
4719                 _tabPage.Size = new Size(380, 260);
4720                 _tabPage.TabIndex = 2 + cnt;
4721                 _tabPage.Text = tabName;
4722                 _tabPage.UseVisualStyleBackColor = true;
4723                 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4724
4725                 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4726                 _listCustom.TabIndex = 1;
4727                 _listCustom.AllowColumnReorder = true;
4728                 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4729                 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4730                 _listCustom.Dock = DockStyle.Fill;
4731                 _listCustom.FullRowSelect = true;
4732                 _listCustom.HideSelection = false;
4733                 _listCustom.Location = new Point(0, 0);
4734                 _listCustom.Margin = new Padding(0);
4735                 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4736                 _listCustom.ShowItemToolTips = true;
4737                 _listCustom.Size = new Size(380, 260);
4738                 _listCustom.UseCompatibleStateImageBehavior = false;
4739                 _listCustom.View = View.Details;
4740                 _listCustom.OwnerDraw = true;
4741                 _listCustom.VirtualMode = true;
4742                 _listCustom.Font = _fntReaded;
4743                 _listCustom.BackColor = _clListBackcolor;
4744
4745                 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4746                 _listCustom.AllowDrop = true;
4747
4748                 _listCustom.SmallImageList = _listViewImageList;
4749
4750                 InitColumns(_listCustom, startup);
4751
4752                 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4753                 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4754                 _listCustom.ColumnClick += MyList_ColumnClick;
4755                 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4756                 _listCustom.DragDrop += TweenMain_DragDrop;
4757                 _listCustom.DragEnter += TweenMain_DragEnter;
4758                 _listCustom.DragOver += TweenMain_DragOver;
4759                 _listCustom.DrawItem += MyList_DrawItem;
4760                 _listCustom.MouseClick += MyList_MouseClick;
4761                 _listCustom.ColumnReordered += MyList_ColumnReordered;
4762                 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4763                 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4764                 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4765                 _listCustom.DrawSubItem += MyList_DrawSubItem;
4766                 _listCustom.HScrolled += MyList_HScrolled;
4767             }
4768
4769             return true;
4770         }
4771
4772         public bool RemoveSpecifiedTab(string TabName, bool confirm)
4773         {
4774             var tabInfo = _statuses.GetTabByName(TabName);
4775             if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4776
4777             if (confirm)
4778             {
4779                 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4780                 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4781                                  MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4782                 {
4783                     return false;
4784                 }
4785             }
4786
4787             var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4788             if (_tabPage == null) return false;
4789
4790             SetListProperty();   //他のタブに列幅等を反映
4791
4792             //オブジェクトインスタンスの削除
4793             DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4794             _tabPage.Tag = null;
4795
4796             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4797             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4798             using (ControlTransaction.Layout(this.SplitContainer1, false))
4799             using (ControlTransaction.Layout(this.ListTab, false))
4800             using (ControlTransaction.Layout(this))
4801             using (ControlTransaction.Layout(_tabPage, false))
4802             {
4803                 if (this.ListTab.SelectedTab == _tabPage)
4804                 {
4805                     this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4806                     this._beforeSelectedTab = null;
4807                 }
4808                 this.ListTab.Controls.Remove(_tabPage);
4809
4810                 // 後付けのコントロールを破棄
4811                 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4812                 {
4813                     using (Control label = _tabPage.Controls["labelUser"])
4814                     {
4815                         _tabPage.Controls.Remove(label);
4816                     }
4817                 }
4818                 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4819                 {
4820                     using (Control pnl = _tabPage.Controls["panelSearch"])
4821                     {
4822                         pnl.Enter -= SearchControls_Enter;
4823                         pnl.Leave -= SearchControls_Leave;
4824                         _tabPage.Controls.Remove(pnl);
4825
4826                         foreach (Control ctrl in pnl.Controls)
4827                         {
4828                             if (ctrl.Name == "buttonSearch")
4829                             {
4830                                 ctrl.Click -= SearchButton_Click;
4831                             }
4832                             else if (ctrl.Name == "comboSearch")
4833                             {
4834                                 ctrl.KeyDown -= SearchComboBox_KeyDown;
4835                             }
4836                             pnl.Controls.Remove(ctrl);
4837                             ctrl.Dispose();
4838                         }
4839                     }
4840                 }
4841
4842                 _tabPage.Controls.Remove(_listCustom);
4843
4844                 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4845                 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4846                 _listCustom.ColumnClick -= MyList_ColumnClick;
4847                 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4848                 _listCustom.DragDrop -= TweenMain_DragDrop;
4849                 _listCustom.DragEnter -= TweenMain_DragEnter;
4850                 _listCustom.DragOver -= TweenMain_DragOver;
4851                 _listCustom.DrawItem -= MyList_DrawItem;
4852                 _listCustom.MouseClick -= MyList_MouseClick;
4853                 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4854                 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4855                 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4856                 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4857                 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4858                 _listCustom.HScrolled -= MyList_HScrolled;
4859
4860                 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4861                 _listCustom.Columns.Clear();
4862                 cols.ForEach(col => col.Dispose());
4863                 cols.Clear();
4864
4865                 _listCustom.ContextMenuStrip = null;
4866                 _listCustom.ColumnHeaderContextMenuStrip = null;
4867                 _listCustom.Font = null;
4868
4869                 _listCustom.SmallImageList = null;
4870                 _listCustom.ListViewItemSorter = null;
4871
4872                 //キャッシュのクリア
4873                 if (_curTab.Equals(_tabPage))
4874                 {
4875                     _curTab = null;
4876                     _curItemIndex = -1;
4877                     _curList = null;
4878                     _curPost = null;
4879                 }
4880                 this.PurgeListViewItemCache();
4881             }
4882
4883             _tabPage.Dispose();
4884             _listCustom.Dispose();
4885             _statuses.RemoveTab(TabName);
4886
4887             foreach (TabPage tp in ListTab.TabPages)
4888             {
4889                 DetailsListView lst = (DetailsListView)tp.Tag;
4890                 var count = _statuses.Tabs[tp.Text].AllCount;
4891                 if (lst.VirtualListSize != count)
4892                 {
4893                     lst.VirtualListSize = count;
4894                 }
4895             }
4896
4897             return true;
4898         }
4899
4900         private void ListTab_Deselected(object sender, TabControlEventArgs e)
4901         {
4902             this.PurgeListViewItemCache();
4903             _beforeSelectedTab = e.TabPage;
4904         }
4905
4906         private void ListTab_MouseMove(object sender, MouseEventArgs e)
4907         {
4908             //タブのD&D
4909
4910             if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4911             {
4912                 string tn = "";
4913                 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4914                 if (!dragEnableRectangle.Contains(e.Location))
4915                 {
4916                     //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4917                     tn = ListTab.SelectedTab.Text;
4918                 }
4919
4920                 if (string.IsNullOrEmpty(tn)) return;
4921
4922                 foreach (TabPage tb in ListTab.TabPages)
4923                 {
4924                     if (tb.Text == tn)
4925                     {
4926                         ListTab.DoDragDrop(tb, DragDropEffects.All);
4927                         break;
4928                     }
4929                 }
4930             }
4931             else
4932             {
4933                 _tabDrag = false;
4934             }
4935
4936             Point cpos = new Point(e.X, e.Y);
4937             for (int i = 0; i < ListTab.TabPages.Count; i++)
4938             {
4939                 Rectangle rect = ListTab.GetTabRect(i);
4940                 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4941                    rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4942                 {
4943                     _rclickTabName = ListTab.TabPages[i].Text;
4944                     break;
4945                 }
4946             }
4947         }
4948
4949         private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4950         {
4951             //_curList.Refresh();
4952             SetMainWindowTitle();
4953             SetStatusLabelUrl();
4954             SetApiStatusLabel();
4955             if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4956             TabMenuControl(ListTab.SelectedTab.Text);
4957             this.PushSelectPostChain();
4958             await DispSelectedPost();
4959         }
4960
4961         private void SetListProperty()
4962         {
4963             //削除などで見つからない場合は処理せず
4964             if (_curList == null) return;
4965             if (!_isColumnChanged) return;
4966
4967             int[] dispOrder = new int[_curList.Columns.Count];
4968             for (int i = 0; i < _curList.Columns.Count; i++)
4969             {
4970                 for (int j = 0; j < _curList.Columns.Count; j++)
4971                 {
4972                     if (_curList.Columns[j].DisplayIndex == i)
4973                     {
4974                         dispOrder[i] = j;
4975                         break;
4976                     }
4977                 }
4978             }
4979
4980             //列幅、列並びを他のタブに設定
4981             foreach (TabPage tb in ListTab.TabPages)
4982             {
4983                 if (!tb.Equals(_curTab))
4984                 {
4985                     if (tb.Tag != null && tb.Controls.Count > 0)
4986                     {
4987                         DetailsListView lst = (DetailsListView)tb.Tag;
4988                         for (int i = 0; i < lst.Columns.Count; i++)
4989                         {
4990                             lst.Columns[dispOrder[i]].DisplayIndex = i;
4991                             lst.Columns[i].Width = _curList.Columns[i].Width;
4992                         }
4993                     }
4994                 }
4995             }
4996
4997             _isColumnChanged = false;
4998         }
4999
5000         private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
5001         {
5002             try
5003             {
5004                 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal)
5005                     || PostBrowser.StatusText.StartsWith("ftp", StringComparison.Ordinal)
5006                     || PostBrowser.StatusText.StartsWith("data", StringComparison.Ordinal))
5007                 {
5008                     StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
5009                 }
5010                 if (string.IsNullOrEmpty(PostBrowser.StatusText))
5011                 {
5012                     SetStatusLabelUrl();
5013                 }
5014             }
5015             catch (Exception)
5016             {
5017             }
5018         }
5019
5020         private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5021         {
5022             if (e.KeyChar == '@')
5023             {
5024                 if (!this._cfgCommon.UseAtIdSupplement) return;
5025                 //@マーク
5026                 int cnt = AtIdSupl.ItemCount;
5027                 ShowSuplDialog(StatusText, AtIdSupl);
5028                 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
5029                 e.Handled = true;
5030             }
5031             else if (e.KeyChar == '#')
5032             {
5033                 if (!this._cfgCommon.UseHashSupplement) return;
5034                 ShowSuplDialog(StatusText, HashSupl);
5035                 e.Handled = true;
5036             }
5037         }
5038
5039         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5040         {
5041             ShowSuplDialog(owner, dialog, 0, "");
5042         }
5043
5044         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5045         {
5046             ShowSuplDialog(owner, dialog, offset, "");
5047         }
5048
5049         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5050         {
5051             dialog.StartsWith = startswith;
5052             if (dialog.Visible)
5053             {
5054                 dialog.Focus();
5055             }
5056             else
5057             {
5058                 dialog.ShowDialog();
5059             }
5060             this.TopMost = this._cfgCommon.AlwaysTop;
5061             int selStart = owner.SelectionStart;
5062             string fHalf = "";
5063             string eHalf = "";
5064             if (dialog.DialogResult == DialogResult.OK)
5065             {
5066                 if (!string.IsNullOrEmpty(dialog.inputText))
5067                 {
5068                     if (selStart > 0)
5069                     {
5070                         fHalf = owner.Text.Substring(0, selStart - offset);
5071                     }
5072                     if (selStart < owner.Text.Length)
5073                     {
5074                         eHalf = owner.Text.Substring(selStart);
5075                     }
5076                     owner.Text = fHalf + dialog.inputText + eHalf;
5077                     owner.SelectionStart = selStart + dialog.inputText.Length;
5078                 }
5079             }
5080             else
5081             {
5082                 if (selStart > 0)
5083                 {
5084                     fHalf = owner.Text.Substring(0, selStart);
5085                 }
5086                 if (selStart < owner.Text.Length)
5087                 {
5088                     eHalf = owner.Text.Substring(selStart);
5089                 }
5090                 owner.Text = fHalf + eHalf;
5091                 if (selStart > 0)
5092                 {
5093                     owner.SelectionStart = selStart;
5094                 }
5095             }
5096             owner.Focus();
5097         }
5098
5099         private void StatusText_KeyUp(object sender, KeyEventArgs e)
5100         {
5101             //スペースキーで未読ジャンプ
5102             if (!e.Alt && !e.Control && !e.Shift)
5103             {
5104                 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5105                 {
5106                     bool isSpace = false;
5107                     foreach (char c in StatusText.Text.ToCharArray())
5108                     {
5109                         if (c == ' ' || c == ' ')
5110                         {
5111                             isSpace = true;
5112                         }
5113                         else
5114                         {
5115                             isSpace = false;
5116                             break;
5117                         }
5118                     }
5119                     if (isSpace)
5120                     {
5121                         e.Handled = true;
5122                         StatusText.Text = "";
5123                         JumpUnreadMenuItem_Click(null, null);
5124                     }
5125                 }
5126             }
5127             this.StatusText_TextChanged(null, null);
5128         }
5129
5130         private void StatusText_TextChanged(object sender, EventArgs e)
5131         {
5132             //文字数カウント
5133             int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
5134             lblLen.Text = pLen.ToString();
5135             if (pLen < 0)
5136             {
5137                 StatusText.ForeColor = Color.Red;
5138             }
5139             else
5140             {
5141                 StatusText.ForeColor = _clInputFont;
5142             }
5143             if (string.IsNullOrEmpty(StatusText.Text))
5144             {
5145                 this.inReplyTo = null;
5146             }
5147         }
5148
5149         /// <summary>
5150         /// ツイート投稿前のフッター付与などの前処理を行います
5151         /// </summary>
5152         private string FormatStatusText(string statusText)
5153         {
5154             statusText = statusText.Replace("\r\n", "\n");
5155
5156             if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
5157             {
5158                 // URLと全角文字の切り離し
5159                 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
5160             }
5161
5162             if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
5163             {
5164                 // 文中の全角スペースを半角スペース1個にする
5165                 statusText = statusText.Replace(" ", " ");
5166             }
5167
5168             // DM の場合はこれ以降の処理を行わない
5169             if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
5170                 return statusText;
5171
5172             bool disableFooter;
5173             if (this._cfgCommon.PostShiftEnter)
5174             {
5175                 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5176             }
5177             else
5178             {
5179                 if (this.StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
5180                     disableFooter = MyCommon.IsKeyDown(Keys.Control);
5181                 else
5182                     disableFooter = MyCommon.IsKeyDown(Keys.Shift);
5183             }
5184
5185             if (statusText.Contains("RT @"))
5186                 disableFooter = true;
5187
5188             var header = "";
5189             var footer = "";
5190
5191             var hashtag = this.HashMgr.UseHash;
5192             if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
5193             {
5194                 if (HashMgr.IsHead)
5195                     header = HashMgr.UseHash + " ";
5196                 else
5197                     footer = " " + HashMgr.UseHash;
5198             }
5199
5200             if (!disableFooter)
5201             {
5202                 if (this._cfgLocal.UseRecommendStatus)
5203                 {
5204                     // 推奨ステータスを使用する
5205                     footer += this.recommendedStatusFooter;
5206                 }
5207                 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
5208                 {
5209                     // テキストボックスに入力されている文字列を使用する
5210                     footer += " " + this._cfgLocal.StatusText.Trim();
5211                 }
5212             }
5213
5214             statusText = header + statusText + footer;
5215
5216             if (this.ToolStripMenuItemPreventSmsCommand.Checked)
5217             {
5218                 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
5219                 // 参照: https://support.twitter.com/articles/14020
5220
5221                 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
5222                     && !Twitter.DMSendTextRegex.IsMatch(statusText))
5223                 {
5224                     // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
5225                     statusText = '\u200b' + statusText;
5226                 }
5227             }
5228
5229             return statusText;
5230         }
5231
5232         /// <summary>
5233         /// 投稿欄に表示する入力可能な文字数を計算します
5234         /// </summary>
5235         private int GetRestStatusCount(string statusText)
5236         {
5237             //文字数カウント
5238             var remainCount = this.tw.GetTextLengthRemain(statusText);
5239
5240             if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
5241             {
5242                 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
5243             }
5244
5245             return remainCount;
5246         }
5247
5248         private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5249         {
5250             if (sender != this._curList)
5251                 return;
5252
5253             var listCache = this._listItemCache;
5254             if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
5255             {
5256                 // If the newly requested cache is a subset of the old cache,
5257                 // no need to rebuild everything, so do nothing.
5258                 return;
5259             }
5260
5261             // Now we need to rebuild the cache.
5262             this.CreateCache(e.StartIndex, e.EndIndex);
5263         }
5264
5265         private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5266         {
5267             var listCache = this._listItemCache;
5268             if (listCache != null && listCache.TargetList == sender)
5269             {
5270                 ListViewItem item;
5271                 PostClass cacheItemPost;
5272                 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
5273                 {
5274                     e.Item = item;
5275                     return;
5276                 }
5277             }
5278
5279             // A cache miss, so create a new ListViewItem and pass it back.
5280             TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5281             try
5282             {
5283                 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5284             }
5285             catch (Exception)
5286             {
5287                 // 不正な要求に対する間に合わせの応答
5288                 string[] sitem = {"", "", "", "", "", "", "", ""};
5289                 e.Item = new ImageListViewItem(sitem);
5290             }
5291         }
5292
5293         private void CreateCache(int startIndex, int endIndex)
5294         {
5295             var tabInfo = this._statuses.Tabs[this._curTab.Text];
5296
5297             if (tabInfo.AllCount == 0)
5298                 return;
5299
5300             // キャッシュ要求(要求範囲±30を作成)
5301             startIndex = Math.Max(startIndex - 30, 0);
5302             endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
5303
5304             var cacheLength = endIndex - startIndex + 1;
5305
5306             var posts = tabInfo[startIndex, endIndex]; //配列で取得
5307             var listItems = Enumerable.Range(0, cacheLength)
5308                 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
5309                 .ToArray();
5310
5311             var listCache = new ListViewItemCache
5312             {
5313                 TargetList = this._curList,
5314                 StartIndex = startIndex,
5315                 EndIndex = endIndex,
5316                 Post = posts,
5317                 ListItem = listItems,
5318             };
5319
5320             Interlocked.Exchange(ref this._listItemCache, listCache);
5321         }
5322
5323         /// <summary>
5324         /// DetailsListView のための ListViewItem のキャッシュを消去する
5325         /// </summary>
5326         private void PurgeListViewItemCache()
5327         {
5328             Interlocked.Exchange(ref this._listItemCache, null);
5329         }
5330
5331         private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5332         {
5333             StringBuilder mk = new StringBuilder();
5334             //if (Post.IsDeleted) mk.Append("×");
5335             //if (Post.IsMark) mk.Append("♪");
5336             //if (Post.IsProtect) mk.Append("Ю");
5337             //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5338             if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5339             ImageListViewItem itm;
5340             if (Post.RetweetedId == null)
5341             {
5342                 string[] sitem= {"",
5343                                  Post.Nickname,
5344                                  Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5345                                  Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5346                                  Post.ScreenName,
5347                                  "",
5348                                  mk.ToString(),
5349                                  Post.Source};
5350                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5351             }
5352             else
5353             {
5354                 string[] sitem = {"",
5355                                   Post.Nickname,
5356                                   Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5357                                   Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5358                                   Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5359                                   "",
5360                                   mk.ToString(),
5361                                   Post.Source};
5362                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5363             }
5364             itm.StateIndex = Post.StateIndex;
5365
5366             bool read = Post.IsRead;
5367             //未読管理していなかったら既読として扱う
5368             if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5369             ChangeItemStyleRead(read, itm, Post, null);
5370             if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5371             return itm;
5372         }
5373
5374         /// <summary>
5375         /// 全てのタブの振り分けルールを反映し直します
5376         /// </summary>
5377         private void ApplyPostFilters()
5378         {
5379             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5380             {
5381                 this.PurgeListViewItemCache();
5382                 this._curPost = null;
5383                 this._curItemIndex = -1;
5384                 this._statuses.FilterAll();
5385
5386                 foreach (TabPage tabPage in this.ListTab.TabPages)
5387                 {
5388                     var tab = this._statuses.Tabs[tabPage.Text];
5389
5390                     var listview = (DetailsListView)tabPage.Tag;
5391                     using (ControlTransaction.Update(listview))
5392                     {
5393                         listview.VirtualListSize = tab.AllCount;
5394                     }
5395
5396                     if (this._cfgCommon.TabIconDisp)
5397                     {
5398                         if (tab.UnreadCount > 0)
5399                             tabPage.ImageIndex = 0;
5400                         else
5401                             tabPage.ImageIndex = -1;
5402                     }
5403                 }
5404
5405                 if (!this._cfgCommon.TabIconDisp)
5406                     this.ListTab.Refresh();
5407
5408                 SetMainWindowTitle();
5409                 SetStatusLabelUrl();
5410             }
5411         }
5412
5413         private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5414         {
5415             e.DrawDefault = true;
5416         }
5417
5418         private void MyList_HScrolled(object sender, EventArgs e)
5419         {
5420             DetailsListView listView = (DetailsListView)sender;
5421             listView.Refresh();
5422         }
5423
5424         private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5425         {
5426             if (e.State == 0) return;
5427             e.DrawDefault = false;
5428
5429             SolidBrush brs2 = null;
5430             if (!e.Item.Selected)     //e.ItemStateでうまく判定できない???
5431             {
5432                 if (e.Item.BackColor == _clSelf)
5433                     brs2 = _brsBackColorMine;
5434                 else if (e.Item.BackColor == _clAtSelf)
5435                     brs2 = _brsBackColorAt;
5436                 else if (e.Item.BackColor == _clTarget)
5437                     brs2 = _brsBackColorYou;
5438                 else if (e.Item.BackColor == _clAtTarget)
5439                     brs2 = _brsBackColorAtYou;
5440                 else if (e.Item.BackColor == _clAtFromTarget)
5441                     brs2 = _brsBackColorAtFromTarget;
5442                 else if (e.Item.BackColor == _clAtTo)
5443                     brs2 = _brsBackColorAtTo;
5444                 else
5445                     brs2 = _brsBackColorNone;
5446             }
5447             else
5448             {
5449                 //選択中の行
5450                 if (((Control)sender).Focused)
5451                     brs2 = _brsHighLight;
5452                 else
5453                     brs2 = _brsDeactiveSelection;
5454             }
5455             e.Graphics.FillRectangle(brs2, e.Bounds);
5456             e.DrawFocusRectangle();
5457             this.DrawListViewItemIcon(e);
5458         }
5459
5460         private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5461         {
5462             if (e.ItemState == 0) return;
5463
5464             if (e.ColumnIndex > 0)
5465             {
5466                 //アイコン以外の列
5467                 RectangleF rct = e.Bounds;
5468                 rct.Width = e.Header.Width;
5469                 int fontHeight = e.Item.Font.Height;
5470                 if (_iconCol)
5471                 {
5472                     rct.Y += fontHeight;
5473                     rct.Height -= fontHeight;
5474                 }
5475
5476                 int heightDiff;
5477                 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5478
5479                 //if (heightDiff > fontHeight * 0.7)
5480                 //{
5481                 //    rct.Height += fontHeight;
5482                 //    drawLineCount += 1;
5483                 //}
5484
5485                 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5486                 if (!_iconCol && drawLineCount <= 1)
5487                 {
5488                     //rct.Inflate(0, heightDiff / -2);
5489                     //rct.Height += fontHeight / 2;
5490                 }
5491                 else if (heightDiff < fontHeight * 0.7)
5492                 {
5493                     //最終行が70%以上欠けていたら、最終行は表示しない
5494                     //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5495                     rct.Height = (fontHeight * drawLineCount) - 1;
5496                 }
5497                 else
5498                 {
5499                     drawLineCount += 1;
5500                 }
5501
5502                 //if (!_iconCol && drawLineCount > 1)
5503                 //{
5504                 //    rct.Y += fontHeight * 0.2;
5505                 //    if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5506                 //}
5507
5508                 if (rct.Width > 0)
5509                 {
5510                     Color color = (!e.Item.Selected) ? e.Item.ForeColor :   //選択されていない行
5511                         (((Control)sender).Focused) ? _clHighLight :        //選択中の行
5512                         _clUnread;
5513
5514                     if (_iconCol)
5515                     {
5516                         Rectangle rctB = e.Bounds;
5517                         rctB.Width = e.Header.Width;
5518                         rctB.Height = fontHeight;
5519
5520                         using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5521                         {
5522                             TextRenderer.DrawText(e.Graphics,
5523                                                     e.Item.SubItems[2].Text,
5524                                                     e.Item.Font,
5525                                                     Rectangle.Round(rct),
5526                                                     color,
5527                                                     TextFormatFlags.WordBreak |
5528                                                     TextFormatFlags.EndEllipsis |
5529                                                     TextFormatFlags.GlyphOverhangPadding |
5530                                                     TextFormatFlags.NoPrefix);
5531                             TextRenderer.DrawText(e.Graphics,
5532                                                     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 + "]",
5533                                                     fnt,
5534                                                     rctB,
5535                                                     color,
5536                                                     TextFormatFlags.SingleLine |
5537                                                     TextFormatFlags.EndEllipsis |
5538                                                     TextFormatFlags.GlyphOverhangPadding |
5539                                                     TextFormatFlags.NoPrefix);
5540                         }
5541                     }
5542                     else if (drawLineCount == 1)
5543                     {
5544                         TextRenderer.DrawText(e.Graphics,
5545                                                 e.SubItem.Text,
5546                                                 e.Item.Font,
5547                                                 Rectangle.Round(rct),
5548                                                 color,
5549                                                 TextFormatFlags.SingleLine |
5550                                                 TextFormatFlags.EndEllipsis |
5551                                                 TextFormatFlags.GlyphOverhangPadding |
5552                                                 TextFormatFlags.NoPrefix |
5553                                                 TextFormatFlags.VerticalCenter);
5554                     }
5555                     else
5556                     {
5557                         TextRenderer.DrawText(e.Graphics,
5558                                                 e.SubItem.Text,
5559                                                 e.Item.Font,
5560                                                 Rectangle.Round(rct),
5561                                                 color,
5562                                                 TextFormatFlags.WordBreak |
5563                                                 TextFormatFlags.EndEllipsis |
5564                                                 TextFormatFlags.GlyphOverhangPadding |
5565                                                 TextFormatFlags.NoPrefix);
5566                     }
5567                     //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5568                 }
5569             }
5570         }
5571
5572         private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5573         {
5574             if (_iconSz == 0) return;
5575
5576             ImageListViewItem item = (ImageListViewItem)e.Item;
5577
5578             //e.Bounds.Leftが常に0を指すから自前で計算
5579             Rectangle itemRect = item.Bounds;
5580             var col0 = e.Item.ListView.Columns[0];
5581             itemRect.Width = col0.Width;
5582
5583             if (col0.DisplayIndex > 0)
5584             {
5585                 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5586                 {
5587                     if (clm.DisplayIndex < col0.DisplayIndex)
5588                         itemRect.X += clm.Width;
5589                 }
5590             }
5591
5592             // ディスプレイの DPI 設定を考慮したアイコンサイズ
5593             var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5594             var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5595
5596             Rectangle iconRect;
5597             var img = item.Image;
5598             if (img != null)
5599             {
5600                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5601                 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5602
5603                 if (iconRect.Width > 0)
5604                 {
5605                     e.Graphics.FillRectangle(Brushes.White, iconRect);
5606                     e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5607                     try
5608                     {
5609                         e.Graphics.DrawImage(img.Image, iconRect);
5610                     }
5611                     catch (ArgumentException)
5612                     {
5613                         item.RefreshImageAsync();
5614                     }
5615                 }
5616             }
5617             else
5618             {
5619                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5620                 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5621
5622                 item.GetImageAsync();
5623             }
5624
5625             if (item.StateIndex > -1)
5626             {
5627                 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5628                 if (stateRect.Width > 0)
5629                 {
5630                     //e.Graphics.FillRectangle(Brushes.White, stateRect);
5631                     //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5632                     e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5633                 }
5634             }
5635         }
5636
5637         protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5638         {
5639             base.ScaleControl(factor, specified);
5640
5641             ScaleChildControl(this.TabImage, factor);
5642
5643             var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5644             var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5645
5646             foreach (var listview in listviews)
5647             {
5648                 ScaleChildControl(listview, factor);
5649             }
5650         }
5651
5652         //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5653         //{
5654         //    ImageListViewItem item = (ImageListViewItem)e.Item;
5655         //    if (item.StateImageIndex > -1)
5656         //    {
5657         //        ////e.Bounds.Leftが常に0を指すから自前で計算
5658         //        //Rectangle itemRect = item.Bounds;
5659         //        //itemRect.Width = e.Item.ListView.Columns[4].Width;
5660
5661         //        //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5662         //        //{
5663         //        //    if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5664         //        //    {
5665         //        //        itemRect.X += clm.Width;
5666         //        //    }
5667         //        //}
5668
5669         //        //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5670         //        //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5671
5672         //        if (rct.Width > 0)
5673         //        {
5674         //            RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5675         //            //e.Graphics.FillRectangle(Brushes.White, rct);
5676         //            //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5677         //            e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5678         //        }
5679         //    }
5680         //}
5681
5682         private void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5683         {
5684             var tab = this._statuses.Tabs[this._curTab.Text];
5685
5686             if (tab.AllCount == 0)
5687             {
5688                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5689                 return;
5690             }
5691
5692             var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5693
5694             int startIndex;
5695             switch (searchType)
5696             {
5697                 case SEARCHTYPE.NextSearch: // 次を検索
5698                     if (selectedIndex != -1)
5699                         startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5700                     else
5701                         startIndex = 0;
5702                     break;
5703                 case SEARCHTYPE.PrevSearch: // 前を検索
5704                     if (selectedIndex != -1)
5705                         startIndex = Math.Max(selectedIndex - 1, 0);
5706                     else
5707                         startIndex = tab.AllCount - 1;
5708                     break;
5709                 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5710                 default:
5711                     if (selectedIndex != -1)
5712                         startIndex = selectedIndex;
5713                     else
5714                         startIndex = 0;
5715                     break;
5716             }
5717
5718             Func<string, bool> stringComparer;
5719             try
5720             {
5721                 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5722             }
5723             catch (ArgumentException)
5724             {
5725                 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5726                 return;
5727             }
5728
5729             var reverse = searchType == SEARCHTYPE.PrevSearch;
5730             var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5731                 .DefaultIfEmpty(-1).First();
5732
5733             if (foundIndex == -1)
5734             {
5735                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5736                 return;
5737             }
5738
5739             this.SelectListItem(this._curList, foundIndex);
5740             this._curList.EnsureVisible(foundIndex);
5741         }
5742
5743         private void MenuItemSubSearch_Click(object sender, EventArgs e)
5744         {
5745             // 検索メニュー
5746             this.ShowSearchDialog();
5747         }
5748
5749         private void MenuItemSearchNext_Click(object sender, EventArgs e)
5750         {
5751             var previousSearch = this.SearchDialog.ResultOptions;
5752             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5753             {
5754                 this.SearchDialog.Reset();
5755                 this.ShowSearchDialog();
5756                 return;
5757             }
5758
5759             // 次を検索
5760             this.DoTabSearch(
5761                 previousSearch.Query,
5762                 previousSearch.CaseSensitive,
5763                 previousSearch.UseRegex,
5764                 SEARCHTYPE.NextSearch);
5765         }
5766
5767         private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5768         {
5769             var previousSearch = this.SearchDialog.ResultOptions;
5770             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5771             {
5772                 this.SearchDialog.Reset();
5773                 this.ShowSearchDialog();
5774                 return;
5775             }
5776
5777             // 前を検索
5778             this.DoTabSearch(
5779                 previousSearch.Query,
5780                 previousSearch.CaseSensitive,
5781                 previousSearch.UseRegex,
5782                 SEARCHTYPE.PrevSearch);
5783         }
5784
5785         /// <summary>
5786         /// 検索ダイアログを表示し、検索を実行します
5787         /// </summary>
5788         private void ShowSearchDialog()
5789         {
5790             if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5791             {
5792                 this.TopMost = this._cfgCommon.AlwaysTop;
5793                 return;
5794             }
5795             this.TopMost = this._cfgCommon.AlwaysTop;
5796
5797             var searchOptions = this.SearchDialog.ResultOptions;
5798             if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5799             {
5800                 if (searchOptions.NewTab)
5801                 {
5802                     var tabName = Properties.Resources.SearchResults_TabName;
5803
5804                     try
5805                     {
5806                         tabName = this._statuses.MakeTabName(tabName);
5807                     }
5808                     catch (TabException ex)
5809                     {
5810                         MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5811                     }
5812
5813                     var resultTab = new TabClass(tabName, MyCommon.TabUsageType.SearchResults);
5814                     this.AddNewTab(tabName, false, MyCommon.TabUsageType.SearchResults);
5815                     this._statuses.AddTab(resultTab);
5816
5817                     var targetTab = this._statuses.Tabs[this._curTab.Text];
5818
5819                     Func<string, bool> stringComparer;
5820                     try
5821                     {
5822                         stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5823                     }
5824                     catch (ArgumentException)
5825                     {
5826                         MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5827                         return;
5828                     }
5829
5830                     var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5831                     if (foundIndices.Length == 0)
5832                     {
5833                         MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5834                         return;
5835                     }
5836
5837                     var foundPosts = foundIndices.Select(x => targetTab[x]);
5838                     foreach (var post in foundPosts)
5839                     {
5840                         resultTab.AddPostToInnerStorage(post);
5841                     }
5842
5843                     this._statuses.DistributePosts();
5844                     this.RefreshTimeline();
5845
5846                     var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5847                         .First(x => x.Text == tabName);
5848
5849                     this.ListTab.SelectedTab = tabPage;
5850                 }
5851                 else
5852                 {
5853                     this.DoTabSearch(
5854                         searchOptions.Query,
5855                         searchOptions.CaseSensitive,
5856                         searchOptions.UseRegex,
5857                         SEARCHTYPE.DialogSearch);
5858                 }
5859             }
5860             else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5861             {
5862                 this.AddNewTabForSearch(searchOptions.Query);
5863             }
5864         }
5865
5866         /// <summary>発言検索に使用するメソッドを生成します</summary>
5867         /// <exception cref="ArgumentException">
5868         /// <paramref name="useRegex"/> が true かつ、<paramref name="query"> が不正な正規表現な場合
5869         /// </exception>
5870         private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5871         {
5872             if (useRegex)
5873             {
5874                 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5875                 var regex = new Regex(query, regexOption);
5876
5877                 return x => regex.IsMatch(x);
5878             }
5879             else
5880             {
5881                 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5882
5883                 return x => x.IndexOf(query, comparisonType) != -1;
5884             }
5885         }
5886
5887         private void AboutMenuItem_Click(object sender, EventArgs e)
5888         {
5889             using (TweenAboutBox about = new TweenAboutBox())
5890             {
5891                 about.ShowDialog(this);
5892             }
5893             this.TopMost = this._cfgCommon.AlwaysTop;
5894         }
5895
5896         private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5897         {
5898             int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5899             int idx = -1;
5900             DetailsListView lst = null;
5901
5902             if (ImageSelector.Enabled)
5903                 return;
5904
5905             //現在タブから最終タブまで探索
5906             for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5907             {
5908                 //未読Index取得
5909                 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5910                 if (idx > -1)
5911                 {
5912                     ListTab.SelectedIndex = i;
5913                     lst = (DetailsListView)ListTab.TabPages[i].Tag;
5914                     //_curTab = ListTab.TabPages[i];
5915                     break;
5916                 }
5917             }
5918
5919             //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5920             if (idx == -1 && bgnIdx > 0)
5921             {
5922                 for (int i = 0; i < bgnIdx; i++)
5923                 {
5924                     idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5925                     if (idx > -1)
5926                     {
5927                         ListTab.SelectedIndex = i;
5928                         lst = (DetailsListView)ListTab.TabPages[i].Tag;
5929                         //_curTab = ListTab.TabPages[i];
5930                         break;
5931                     }
5932                 }
5933             }
5934
5935             //全部調べたが未読見つからず→先頭タブの最新発言へ
5936             if (idx == -1)
5937             {
5938                 ListTab.SelectedIndex = 0;
5939                 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5940                 //_curTab = ListTab.TabPages[0];
5941                 if (_statuses.SortOrder == SortOrder.Ascending)
5942                     idx = lst.VirtualListSize - 1;
5943                 else
5944                     idx = 0;
5945             }
5946
5947             if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5948             {
5949                 SelectListItem(lst, idx);
5950                 if (_statuses.SortMode == ComparerMode.Id)
5951                 {
5952                     if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5953                        _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5954                     {
5955                         MoveTop();
5956                     }
5957                     else
5958                     {
5959                         lst.EnsureVisible(idx);
5960                     }
5961                 }
5962                 else
5963                 {
5964                     lst.EnsureVisible(idx);
5965                 }
5966             }
5967             lst.Focus();
5968         }
5969
5970         private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5971         {
5972             if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5973             {
5974                 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5975                 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5976             }
5977         }
5978
5979         private async void FavorareMenuItem_Click(object sender, EventArgs e)
5980         {
5981             if (_curList.SelectedIndices.Count > 0)
5982             {
5983                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5984                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5985             }
5986         }
5987
5988         private async void VerUpMenuItem_Click(object sender, EventArgs e)
5989         {
5990             await this.CheckNewVersion(false);
5991         }
5992
5993         private void RunTweenUp()
5994         {
5995             ProcessStartInfo pinfo = new ProcessStartInfo();
5996             pinfo.UseShellExecute = true;
5997             pinfo.WorkingDirectory = MyCommon.settingPath;
5998             pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5999             pinfo.Arguments = "\"" + Application.StartupPath + "\"";
6000             try
6001             {
6002                 Process.Start(pinfo);
6003             }
6004             catch (Exception)
6005             {
6006                 MessageBox.Show("Failed to execute TweenUp3.exe.");
6007             }
6008         }
6009
6010         public class VersionInfo
6011         {
6012             public Version Version { get; set; }
6013             public Uri DownloadUri { get; set; }
6014             public string ReleaseNote { get; set; }
6015         }
6016
6017         /// <summary>
6018         /// OpenTween の最新バージョンの情報を取得します
6019         /// </summary>
6020         public async Task<VersionInfo> GetVersionInfoAsync()
6021         {
6022             var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6023                 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6024
6025             var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6026                 .ConfigureAwait(false);
6027
6028             // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6029             var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6030
6031             var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6032             var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6033
6034             msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6035
6036             return new VersionInfo
6037             {
6038                 Version = Version.Parse(msgHeader[0]),
6039                 DownloadUri = new Uri(msgHeader[1]),
6040                 ReleaseNote = msgBody,
6041             };
6042         }
6043
6044         private async Task CheckNewVersion(bool startup = false)
6045         {
6046             if (ApplicationSettings.VersionInfoUrl == null)
6047                 return; // 更新チェック無効化
6048
6049             try
6050             {
6051                 var versionInfo = await this.GetVersionInfoAsync();
6052
6053                 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6054                 {
6055                     // 更新不要
6056                     if (!startup)
6057                     {
6058                         var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6059                             MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6060                         msgtext = MyCommon.ReplaceAppName(msgtext);
6061
6062                         MessageBox.Show(msgtext,
6063                             MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6064                             MessageBoxButtons.OK, MessageBoxIcon.Information);
6065                     }
6066                     return;
6067                 }
6068
6069                 using (var dialog = new UpdateDialog())
6070                 {
6071                     dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6072                         MyCommon.GetReadableVersion(versionInfo.Version));
6073                     dialog.DetailsText = versionInfo.ReleaseNote;
6074
6075                     if (dialog.ShowDialog(this) == DialogResult.Yes)
6076                     {
6077                         await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
6078                     }
6079                 }
6080             }
6081             catch (Exception)
6082             {
6083                 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6084                 if (!startup)
6085                 {
6086                     MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6087                         MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6088                         MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6089                 }
6090             }
6091         }
6092
6093         private async Task Colorize()
6094         {
6095             _colorize = false;
6096             await this.DispSelectedPost();
6097             //件数関連の場合、タイトル即時書き換え
6098             if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6099                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6100                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6101                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6102             {
6103                 SetMainWindowTitle();
6104             }
6105             if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6106             foreach (TabPage tb in ListTab.TabPages)
6107             {
6108                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6109                 {
6110                     if (this._cfgCommon.TabIconDisp)
6111                     {
6112                         if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6113                     }
6114                 }
6115             }
6116             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6117         }
6118
6119         public string createDetailHtml(string orgdata)
6120         {
6121             if (this._cfgLocal.UseTwemoji)
6122                 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6123
6124             return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6125         }
6126
6127         private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6128         {
6129             if (sender.Equals(displayItem))
6130             {
6131                 this.ClearUserPicture();
6132
6133                 var img = displayItem.Image;
6134                 try
6135                 {
6136                     if (img != null)
6137                         img = await img.CloneAsync();
6138
6139                     UserPicture.Image = img;
6140                 }
6141                 catch (Exception)
6142                 {
6143                     UserPicture.ShowErrorImage();
6144                 }
6145             }
6146         }
6147
6148         private Task DispSelectedPost()
6149         {
6150             return this.DispSelectedPost(false);
6151         }
6152
6153         private PostClass displayPost = new PostClass();
6154
6155         /// <summary>
6156         /// サムネイル表示に使用する CancellationToken の生成元
6157         /// </summary>
6158         private CancellationTokenSource thumbnailTokenSource = null;
6159
6160         private async Task DispSelectedPost(bool forceupdate)
6161         {
6162             if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6163                 return;
6164
6165             var oldDisplayPost = this.displayPost;
6166             this.displayPost = this._curPost;
6167
6168             if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6169                 return;
6170
6171             if (displayItem != null)
6172             {
6173                 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6174                 displayItem = null;
6175             }
6176             displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6177             displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6178
6179             using (ControlTransaction.Update(this.TableLayoutPanel1))
6180             {
6181                 SourceLinkLabel.Text = this._curPost.Source;
6182                 SourceLinkLabel.Tag = this._curPost.SourceUri;
6183                 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6184
6185                 string nameText;
6186                 if (_curPost.IsDm)
6187                 {
6188                     if (_curPost.IsOwl)
6189                         nameText = "DM FROM <- ";
6190                     else
6191                         nameText = "DM TO -> ";
6192                 }
6193                 else
6194                 {
6195                     nameText = "";
6196                 }
6197                 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6198                 if (_curPost.RetweetedId != null)
6199                     nameText += " (RT:" + _curPost.RetweetedBy + ")";
6200
6201                 NameLabel.Text = nameText;
6202                 NameLabel.Tag = _curPost.ScreenName;
6203
6204                 var nameForeColor = SystemColors.ControlText;
6205                 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6206                     nameForeColor = this._clOWL;
6207                 if (_curPost.RetweetedId != null)
6208                     nameForeColor = this._clRetweet;
6209                 if (_curPost.IsFav)
6210                     nameForeColor = this._clFav;
6211                 NameLabel.ForeColor = nameForeColor;
6212
6213                 this.ClearUserPicture();
6214
6215                 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6216                 {
6217                     var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6218                     try
6219                     {
6220                         UserPicture.Image = image?.Clone();
6221                     }
6222                     catch (Exception)
6223                     {
6224                         UserPicture.ShowErrorImage();
6225                     }
6226                 }
6227
6228                 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6229             }
6230
6231             if (DumpPostClassToolStripMenuItem.Checked)
6232             {
6233                 StringBuilder sb = new StringBuilder(512);
6234
6235                 sb.Append("-----Start PostClass Dump<br>");
6236                 sb.AppendFormat("TextFromApi           : {0}<br>", _curPost.TextFromApi);
6237                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6238                 sb.AppendFormat("StatusId             : {0}<br>", _curPost.StatusId.ToString());
6239                 //sb.AppendFormat("ImageIndex     : {0}<br>", _curPost.ImageIndex.ToString());
6240                 sb.AppendFormat("ImageUrl       : {0}<br>", _curPost.ImageUrl);
6241                 sb.AppendFormat("InReplyToStatusId    : {0}<br>", _curPost.InReplyToStatusId.ToString());
6242                 sb.AppendFormat("InReplyToUser  : {0}<br>", _curPost.InReplyToUser);
6243                 sb.AppendFormat("IsDM           : {0}<br>", _curPost.IsDm.ToString());
6244                 sb.AppendFormat("IsFav          : {0}<br>", _curPost.IsFav.ToString());
6245                 sb.AppendFormat("IsMark         : {0}<br>", _curPost.IsMark.ToString());
6246                 sb.AppendFormat("IsMe           : {0}<br>", _curPost.IsMe.ToString());
6247                 sb.AppendFormat("IsOwl          : {0}<br>", _curPost.IsOwl.ToString());
6248                 sb.AppendFormat("IsProtect      : {0}<br>", _curPost.IsProtect.ToString());
6249                 sb.AppendFormat("IsRead         : {0}<br>", _curPost.IsRead.ToString());
6250                 sb.AppendFormat("IsReply        : {0}<br>", _curPost.IsReply.ToString());
6251
6252                 foreach (string nm in _curPost.ReplyToList)
6253                 {
6254                     sb.AppendFormat("ReplyToList    : {0}<br>", nm);
6255                 }
6256
6257                 sb.AppendFormat("ScreenName           : {0}<br>", _curPost.ScreenName);
6258                 sb.AppendFormat("NickName       : {0}<br>", _curPost.Nickname);
6259                 sb.AppendFormat("Text   : {0}<br>", _curPost.Text);
6260                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.Text);
6261                 sb.AppendFormat("CreatedAt          : {0}<br>", _curPost.CreatedAt.ToString());
6262                 sb.AppendFormat("Source         : {0}<br>", _curPost.Source);
6263                 sb.AppendFormat("UserId            : {0}<br>", _curPost.UserId);
6264                 sb.AppendFormat("FilterHit      : {0}<br>", _curPost.FilterHit);
6265                 sb.AppendFormat("RetweetedBy    : {0}<br>", _curPost.RetweetedBy);
6266                 sb.AppendFormat("RetweetedId    : {0}<br>", _curPost.RetweetedId);
6267
6268                 sb.AppendFormat("Media.Count    : {0}<br>", _curPost.Media.Count);
6269                 if (_curPost.Media.Count > 0)
6270                 {
6271                     for (int i = 0; i < _curPost.Media.Count; i++)
6272                     {
6273                         var info = _curPost.Media[i];
6274                         sb.AppendFormat("Media[{0}].Url         : {1}<br>", i, info.Url);
6275                         sb.AppendFormat("Media[{0}].VideoUrl    : {1}<br>", i, info.VideoUrl ?? "---");
6276                     }
6277                 }
6278                 sb.Append("-----End PostClass Dump<br>");
6279
6280                 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6281                 return;
6282             }
6283
6284             var loadTasks = new List<Task>();
6285
6286             // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6287             // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6288             if (_curPost.StatusId != oldDisplayPost.StatusId)
6289             {
6290                 using (ControlTransaction.Update(this.PostBrowser))
6291                 {
6292                     this.PostBrowser.DocumentText =
6293                         this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6294
6295                     this.PostBrowser.Document.Window.ScrollTo(0, 0);
6296                 }
6297
6298                 this.SplitContainer3.Panel2Collapsed = true;
6299
6300                 if (this._cfgCommon.PreviewEnable)
6301                 {
6302                     var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
6303                     oldTokenSource?.Cancel();
6304
6305                     var token = this.thumbnailTokenSource.Token;
6306                     loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
6307                 }
6308
6309                 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
6310             }
6311
6312             try
6313             {
6314                 await Task.WhenAll(loadTasks);
6315             }
6316             catch (OperationCanceledException) { }
6317         }
6318
6319         /// <summary>
6320         /// 発言詳細欄のツイートURLを展開する
6321         /// </summary>
6322         private async Task AppendQuoteTweetAsync(PostClass post)
6323         {
6324             var quoteStatusIds = post.QuoteStatusIds;
6325             if (quoteStatusIds.Length == 0 && post.InReplyToStatusId == null)
6326                 return;
6327
6328             // 「読み込み中」テキストを表示
6329             var loadingQuoteHtml = quoteStatusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText, isReply: false));
6330
6331             var loadingReplyHtml = string.Empty;
6332             if (post.InReplyToStatusId != null)
6333                 loadingReplyHtml = FormatQuoteTweetHtml(post.InReplyToStatusId.Value, Properties.Resources.LoadingText, isReply: true);
6334
6335             var body = post.Text + string.Concat(loadingQuoteHtml) + loadingReplyHtml;
6336
6337             using (ControlTransaction.Update(this.PostBrowser))
6338                 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6339
6340             // 引用ツイートを読み込み
6341             var loadTweetTasks = quoteStatusIds.Select(x => this.CreateQuoteTweetHtml(x, isReply: false)).ToList();
6342
6343             if (post.InReplyToStatusId != null)
6344                 loadTweetTasks.Add(this.CreateQuoteTweetHtml(post.InReplyToStatusId.Value, isReply: true));
6345
6346             var quoteHtmls = await Task.WhenAll(loadTweetTasks);
6347
6348             // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
6349             if (this._curPost != post || this._curPost.IsDeleted)
6350                 return;
6351
6352             body = post.Text + string.Concat(quoteHtmls);
6353
6354             using (ControlTransaction.Update(this.PostBrowser))
6355                 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6356         }
6357
6358         private async Task<string> CreateQuoteTweetHtml(long statusId, bool isReply)
6359         {
6360             PostClass post = this._statuses[statusId];
6361             if (post == null)
6362             {
6363                 try
6364                 {
6365                     post = await this.tw.GetStatusApi(false, statusId)
6366                         .ConfigureAwait(false);
6367                 }
6368                 catch (WebApiException ex)
6369                 {
6370                     return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode($"Err:{ex.Message}(GetStatus)"), isReply);
6371                 }
6372
6373                 post.IsRead = true;
6374                 if (!this._statuses.AddQuoteTweet(post))
6375                     return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.", isReply);
6376             }
6377
6378             return FormatQuoteTweetHtml(post, isReply);
6379         }
6380
6381         internal static string FormatQuoteTweetHtml(PostClass post, bool isReply)
6382         {
6383             var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6384                 " &mdash; " + WebUtility.HtmlEncode(post.Nickname) +
6385                 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6386                 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6387
6388             return FormatQuoteTweetHtml(post.StatusId, innerHtml, isReply);
6389         }
6390
6391         internal static string FormatQuoteTweetHtml(long statusId, string innerHtml, bool isReply)
6392         {
6393             var blockClassName = "quote-tweet";
6394
6395             if (isReply)
6396                 blockClassName += " reply";
6397
6398             return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6399                 $"<blockquote class=\"{blockClassName}\">{innerHtml}</blockquote>" +
6400                 "</a>";
6401         }
6402
6403         /// <summary>
6404         /// 指定されたHTMLからリンクを除去します
6405         /// </summary>
6406         internal static string StripLinkTagHtml(string html)
6407         {
6408             // a 要素はネストされていない前提の正規表現パターン
6409             return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6410         }
6411
6412         private async void MatomeMenuItem_Click(object sender, EventArgs e)
6413         {
6414             await this.OpenApplicationWebsite();
6415         }
6416
6417         private async Task OpenApplicationWebsite()
6418         {
6419             await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6420         }
6421
6422         private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6423         {
6424             await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6425         }
6426
6427         private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6428         {
6429             if (ListTab.SelectedTab != null)
6430             {
6431                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6432                 {
6433                     Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6434                     if (pnl.Controls["comboSearch"].Focused ||
6435                         pnl.Controls["comboLang"].Focused ||
6436                         pnl.Controls["buttonSearch"].Focused) return;
6437                 }
6438
6439                 if (e.Control || e.Shift || e.Alt)
6440                     this._anchorFlag = false;
6441
6442                 Task asyncTask;
6443                 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6444                 {
6445                     e.Handled = true;
6446                     e.SuppressKeyPress = true;
6447                 }
6448
6449                 if (asyncTask != null)
6450                     await asyncTask;
6451             }
6452         }
6453
6454         private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6455
6456         private void InitializeShortcuts()
6457         {
6458             this.shortcutCommands = new[]
6459             {
6460                 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6461                 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6462                     .FocusedOn(FocusedControl.ListTab)
6463                     .Do(() => SendKeys.Send("{DOWN}")),
6464
6465                 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6466                     .FocusedOn(FocusedControl.ListTab)
6467                     .Do(() => SendKeys.Send("{UP}")),
6468
6469                 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6470                     .FocusedOn(FocusedControl.ListTab)
6471                     .Do(() => SendKeys.Send("{PGDN}")),
6472
6473                 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6474                     .FocusedOn(FocusedControl.ListTab)
6475                     .Do(() => SendKeys.Send("{PGUP}")),
6476
6477                 ShortcutCommand.Create(Keys.F1)
6478                     .Do(() => this.OpenApplicationWebsite()),
6479
6480                 ShortcutCommand.Create(Keys.F3)
6481                     .Do(() => this.MenuItemSearchNext_Click(null, null)),
6482
6483                 ShortcutCommand.Create(Keys.F5)
6484                     .Do(() => this.DoRefresh()),
6485
6486                 ShortcutCommand.Create(Keys.F6)
6487                     .Do(() => this.GetReplyAsync()),
6488
6489                 ShortcutCommand.Create(Keys.F7)
6490                     .Do(() => this.GetDirectMessagesAsync()),
6491
6492                 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6493                     .NotFocusedOn(FocusedControl.StatusText)
6494                     .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6495
6496                 ShortcutCommand.Create(Keys.G)
6497                     .NotFocusedOn(FocusedControl.StatusText)
6498                     .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6499
6500                 ShortcutCommand.Create(Keys.Right, Keys.N)
6501                     .FocusedOn(FocusedControl.ListTab)
6502                     .Do(() => this.GoRelPost(forward: true)),
6503
6504                 ShortcutCommand.Create(Keys.Left, Keys.P)
6505                     .FocusedOn(FocusedControl.ListTab)
6506                     .Do(() => this.GoRelPost(forward: false)),
6507
6508                 ShortcutCommand.Create(Keys.OemPeriod)
6509                     .FocusedOn(FocusedControl.ListTab)
6510                     .Do(() => this.GoAnchor()),
6511
6512                 ShortcutCommand.Create(Keys.I)
6513                     .FocusedOn(FocusedControl.ListTab)
6514                     .OnlyWhen(() => this.StatusText.Enabled)
6515                     .Do(() => this.StatusText.Focus()),
6516
6517                 ShortcutCommand.Create(Keys.Enter)
6518                     .FocusedOn(FocusedControl.ListTab)
6519                     .Do(() => this.MakeReplyOrDirectStatus()),
6520
6521                 ShortcutCommand.Create(Keys.R)
6522                     .FocusedOn(FocusedControl.ListTab)
6523                     .Do(() => this.DoRefresh()),
6524
6525                 ShortcutCommand.Create(Keys.L)
6526                     .FocusedOn(FocusedControl.ListTab)
6527                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6528
6529                 ShortcutCommand.Create(Keys.H)
6530                     .FocusedOn(FocusedControl.ListTab)
6531                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6532
6533                 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6534                     .FocusedOn(FocusedControl.ListTab)
6535                     .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6536
6537                 ShortcutCommand.Create(Keys.S)
6538                     .FocusedOn(FocusedControl.ListTab)
6539                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6540
6541                 ShortcutCommand.Create(Keys.A)
6542                     .FocusedOn(FocusedControl.ListTab)
6543                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6544
6545                 // ] in_reply_to参照元へ戻る
6546                 ShortcutCommand.Create(Keys.Oem4)
6547                     .FocusedOn(FocusedControl.ListTab)
6548                     .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6549
6550                 // [ in_reply_toへジャンプ
6551                 ShortcutCommand.Create(Keys.Oem6)
6552                     .FocusedOn(FocusedControl.ListTab)
6553                     .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6554
6555                 ShortcutCommand.Create(Keys.Escape)
6556                     .FocusedOn(FocusedControl.ListTab)
6557                     .Do(() => {
6558                         this._anchorFlag = false;
6559                         if (ListTab.SelectedTab != null)
6560                         {
6561                             var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6562                             if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6563                             {
6564                                 var relTp = ListTab.SelectedTab;
6565                                 RemoveSpecifiedTab(relTp.Text, false);
6566                                 SaveConfigsTabs();
6567                             }
6568                         }
6569                     }),
6570
6571                 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6572                 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6573                     .FocusedOn(FocusedControl.ListTab)
6574                     .Do(() => this._anchorFlag = false, preventDefault: false),
6575
6576                 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6577                 ShortcutCommand.Create(Keys.Up, Keys.Down)
6578                     .FocusedOn(FocusedControl.PostBrowser)
6579                     .Do(() => { }),
6580
6581                 ShortcutCommand.Create(Keys.Control | Keys.R)
6582                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6583
6584                 ShortcutCommand.Create(Keys.Control | Keys.D)
6585                     .Do(() => this.doStatusDelete()),
6586
6587                 ShortcutCommand.Create(Keys.Control | Keys.M)
6588                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6589
6590                 ShortcutCommand.Create(Keys.Control | Keys.S)
6591                     .Do(() => this.FavoriteChange(FavAdd: true)),
6592
6593                 ShortcutCommand.Create(Keys.Control | Keys.I)
6594                     .Do(() => this.doRepliedStatusOpen()),
6595
6596                 ShortcutCommand.Create(Keys.Control | Keys.Q)
6597                     .Do(() => this.doQuoteOfficial()),
6598
6599                 ShortcutCommand.Create(Keys.Control | Keys.B)
6600                     .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6601
6602                 ShortcutCommand.Create(Keys.Control | Keys.T)
6603                     .Do(() => this.HashManageMenuItem_Click(null, null)),
6604
6605                 ShortcutCommand.Create(Keys.Control | Keys.L)
6606                     .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6607
6608                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6609                     .NotFocusedOn(FocusedControl.PostBrowser)
6610                     .Do(() => this.MultiLineMenuItem_Click(null, null)),
6611
6612                 ShortcutCommand.Create(Keys.Control | Keys.F)
6613                     .Do(() => this.MenuItemSubSearch_Click(null, null)),
6614
6615                 ShortcutCommand.Create(Keys.Control | Keys.U)
6616                     .Do(() => this.ShowUserTimeline()),
6617
6618                 ShortcutCommand.Create(Keys.Control | Keys.H)
6619                     .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6620
6621                 ShortcutCommand.Create(Keys.Control | Keys.G)
6622                     .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6623
6624                 ShortcutCommand.Create(Keys.Control | Keys.O)
6625                     .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6626
6627                 ShortcutCommand.Create(Keys.Control | Keys.E)
6628                     .Do(() => this.OpenURLMenuItem_Click(null, null)),
6629
6630                 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6631                     .FocusedOn(FocusedControl.ListTab)
6632                     .Do(() => this._colorize = true, preventDefault: false),
6633
6634                 ShortcutCommand.Create(Keys.Control | Keys.N)
6635                     .FocusedOn(FocusedControl.ListTab)
6636                     .Do(() => this.GoNextTab(forward: true)),
6637
6638                 ShortcutCommand.Create(Keys.Control | Keys.P)
6639                     .FocusedOn(FocusedControl.ListTab)
6640                     .Do(() => this.GoNextTab(forward: false)),
6641
6642                 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6643                     .FocusedOn(FocusedControl.ListTab)
6644                     .Do(() => this.CopyStot()),
6645
6646                 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6647                 ShortcutCommand.Create(Keys.Control | Keys.D1)
6648                     .FocusedOn(FocusedControl.ListTab)
6649                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6650                     .Do(() => this.ListTab.SelectedIndex = 0),
6651
6652                 ShortcutCommand.Create(Keys.Control | Keys.D2)
6653                     .FocusedOn(FocusedControl.ListTab)
6654                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6655                     .Do(() => this.ListTab.SelectedIndex = 1),
6656
6657                 ShortcutCommand.Create(Keys.Control | Keys.D3)
6658                     .FocusedOn(FocusedControl.ListTab)
6659                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6660                     .Do(() => this.ListTab.SelectedIndex = 2),
6661
6662                 ShortcutCommand.Create(Keys.Control | Keys.D4)
6663                     .FocusedOn(FocusedControl.ListTab)
6664                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6665                     .Do(() => this.ListTab.SelectedIndex = 3),
6666
6667                 ShortcutCommand.Create(Keys.Control | Keys.D5)
6668                     .FocusedOn(FocusedControl.ListTab)
6669                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6670                     .Do(() => this.ListTab.SelectedIndex = 4),
6671
6672                 ShortcutCommand.Create(Keys.Control | Keys.D6)
6673                     .FocusedOn(FocusedControl.ListTab)
6674                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6675                     .Do(() => this.ListTab.SelectedIndex = 5),
6676
6677                 ShortcutCommand.Create(Keys.Control | Keys.D7)
6678                     .FocusedOn(FocusedControl.ListTab)
6679                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6680                     .Do(() => this.ListTab.SelectedIndex = 6),
6681
6682                 ShortcutCommand.Create(Keys.Control | Keys.D8)
6683                     .FocusedOn(FocusedControl.ListTab)
6684                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6685                     .Do(() => this.ListTab.SelectedIndex = 7),
6686
6687                 ShortcutCommand.Create(Keys.Control | Keys.D9)
6688                     .FocusedOn(FocusedControl.ListTab)
6689                     .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6690
6691                 ShortcutCommand.Create(Keys.Control | Keys.A)
6692                     .FocusedOn(FocusedControl.StatusText)
6693                     .Do(() => this.StatusText.SelectAll()),
6694
6695                 ShortcutCommand.Create(Keys.Control | Keys.V)
6696                     .FocusedOn(FocusedControl.StatusText)
6697                     .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6698
6699                 ShortcutCommand.Create(Keys.Control | Keys.Up)
6700                     .FocusedOn(FocusedControl.StatusText)
6701                     .Do(() => {
6702                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6703                         {
6704                             var inReplyToStatusId = this.inReplyTo?.Item1;
6705                             var inReplyToScreenName = this.inReplyTo?.Item2;
6706                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6707                         }
6708                         _hisIdx -= 1;
6709                         if (_hisIdx < 0) _hisIdx = 0;
6710
6711                         var historyItem = this._history[this._hisIdx];
6712                         StatusText.Text = historyItem.status;
6713                         StatusText.SelectionStart = StatusText.Text.Length;
6714                         if (historyItem.inReplyToId != null)
6715                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6716                         else
6717                             this.inReplyTo = null;
6718                     }),
6719
6720                 ShortcutCommand.Create(Keys.Control | Keys.Down)
6721                     .FocusedOn(FocusedControl.StatusText)
6722                     .Do(() => {
6723                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6724                         {
6725                             var inReplyToStatusId = this.inReplyTo?.Item1;
6726                             var inReplyToScreenName = this.inReplyTo?.Item2;
6727                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6728                         }
6729                         _hisIdx += 1;
6730                         if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6731
6732                         var historyItem = this._history[this._hisIdx];
6733                         StatusText.Text = historyItem.status;
6734                         StatusText.SelectionStart = StatusText.Text.Length;
6735                         if (historyItem.inReplyToId != null)
6736                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6737                         else
6738                             this.inReplyTo = null;
6739                     }),
6740
6741                 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6742                     .FocusedOn(FocusedControl.StatusText)
6743                     .Do(() => {
6744                         if (ListTab.SelectedIndex == 0)
6745                         {
6746                             ListTab.SelectedIndex = ListTab.TabCount - 1;
6747                         }
6748                         else
6749                         {
6750                             ListTab.SelectedIndex -= 1;
6751                         }
6752                         StatusText.Focus();
6753                     }),
6754
6755                 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6756                     .FocusedOn(FocusedControl.StatusText)
6757                     .Do(() => {
6758                         if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6759                         {
6760                             ListTab.SelectedIndex = 0;
6761                         }
6762                         else
6763                         {
6764                             ListTab.SelectedIndex += 1;
6765                         }
6766                         StatusText.Focus();
6767                     }),
6768
6769                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6770                     .FocusedOn(FocusedControl.PostBrowser)
6771                     .Do(() => {
6772                         MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6773                         MultiLineMenuItem_Click(null, null);
6774                     }),
6775
6776                 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6777                     .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6778
6779                 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6780                     .Do(() => this.DoRefreshMore()),
6781
6782                 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6783                     .Do(() => this.GetReplyAsync(loadMore: true)),
6784
6785                 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6786                     .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6787
6788                 ShortcutCommand.Create(Keys.Shift | Keys.R)
6789                     .NotFocusedOn(FocusedControl.StatusText)
6790                     .Do(() => this.DoRefreshMore()),
6791
6792                 ShortcutCommand.Create(Keys.Shift | Keys.H)
6793                     .FocusedOn(FocusedControl.ListTab)
6794                     .Do(() => this.GoTopEnd(GoTop: true)),
6795
6796                 ShortcutCommand.Create(Keys.Shift | Keys.L)
6797                     .FocusedOn(FocusedControl.ListTab)
6798                     .Do(() => this.GoTopEnd(GoTop: false)),
6799
6800                 ShortcutCommand.Create(Keys.Shift | Keys.M)
6801                     .FocusedOn(FocusedControl.ListTab)
6802                     .Do(() => this.GoMiddle()),
6803
6804                 ShortcutCommand.Create(Keys.Shift | Keys.G)
6805                     .FocusedOn(FocusedControl.ListTab)
6806                     .Do(() => this.GoLast()),
6807
6808                 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6809                     .FocusedOn(FocusedControl.ListTab)
6810                     .Do(() => this.MoveMiddle()),
6811
6812                 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6813                     .FocusedOn(FocusedControl.ListTab)
6814                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6815
6816                 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6817                     .FocusedOn(FocusedControl.ListTab)
6818                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6819
6820                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6821                 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6822                     .FocusedOn(FocusedControl.ListTab)
6823                     .Do(() => this.GoFav(forward: true)),
6824
6825                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6826                 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6827                     .FocusedOn(FocusedControl.ListTab)
6828                     .Do(() => this.GoFav(forward: false)),
6829
6830                 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6831                     .FocusedOn(FocusedControl.ListTab)
6832                     .Do(() => this.GoBackSelectPostChain()),
6833
6834                 ShortcutCommand.Create(Keys.Alt | Keys.R)
6835                     .Do(() => this.doReTweetOfficial(isConfirm: true)),
6836
6837                 ShortcutCommand.Create(Keys.Alt | Keys.P)
6838                     .OnlyWhen(() => this._curPost != null)
6839                     .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6840
6841                 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6842                     .Do(() => this.ScrollDownPostBrowser(forward: false)),
6843
6844                 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6845                     .Do(() => this.ScrollDownPostBrowser(forward: true)),
6846
6847                 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6848                     .Do(() => this.PageDownPostBrowser(forward: false)),
6849
6850                 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6851                     .Do(() => this.PageDownPostBrowser(forward: true)),
6852
6853                 // 別タブの同じ書き込みへ(ALT+←/→)
6854                 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6855                     .FocusedOn(FocusedControl.ListTab)
6856                     .Do(() => this.GoSamePostToAnotherTab(left: false)),
6857
6858                 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6859                     .FocusedOn(FocusedControl.ListTab)
6860                     .Do(() => this.GoSamePostToAnotherTab(left: true)),
6861
6862                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6863                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6864
6865                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6866                     .Do(() => this.CopyIdUri()),
6867
6868                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6869                     .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6870                         this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6871                     .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6872
6873                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6874                     .Do(() => this.FavoriteChange(FavAdd: false)),
6875
6876                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6877                     .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6878
6879                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6880                     .Do(() => this.HashToggleMenuItem_Click(null, null)),
6881
6882                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6883                     .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6884
6885                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6886                     .Do(() => this.doMoveToRTHome()),
6887
6888                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6889                     .Do(() => this.FavorareMenuItem_Click(null, null)),
6890
6891                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6892                     .FocusedOn(FocusedControl.StatusText)
6893                     .Do(() => {
6894                         if (_curList != null && _curList.VirtualListSize != 0 &&
6895                                     _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6896                         {
6897                             var idx = _curList.SelectedIndices[0] - 1;
6898                             SelectListItem(_curList, idx);
6899                             _curList.EnsureVisible(idx);
6900                         }
6901                     }),
6902
6903                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6904                     .FocusedOn(FocusedControl.StatusText)
6905                     .Do(() => {
6906                         if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6907                                     && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6908                         {
6909                             var idx = _curList.SelectedIndices[0] + 1;
6910                             SelectListItem(_curList, idx);
6911                             _curList.EnsureVisible(idx);
6912                         }
6913                     }),
6914
6915                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6916                     .FocusedOn(FocusedControl.StatusText)
6917                     .Do(() => {
6918                         if (StatusText.SelectionStart > 0)
6919                         {
6920                             int endidx = StatusText.SelectionStart - 1;
6921                             string startstr = "";
6922                             for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6923                             {
6924                                 char c = StatusText.Text[i];
6925                                 if (Char.IsLetterOrDigit(c) || c == '_')
6926                                 {
6927                                     continue;
6928                                 }
6929                                 if (c == '@')
6930                                 {
6931                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6932                                     int cnt = AtIdSupl.ItemCount;
6933                                     ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6934                                     if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6935                                 }
6936                                 else if (c == '#')
6937                                 {
6938                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6939                                     ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6940                                 }
6941                                 else
6942                                 {
6943                                     break;
6944                                 }
6945                             }
6946                         }
6947                     }),
6948
6949                 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6950                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6951                     .FocusedOn(FocusedControl.ListTab)
6952                     .Do(() => this.SetSortColumnByDisplayIndex(0)),
6953
6954                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6955                     .FocusedOn(FocusedControl.ListTab)
6956                     .Do(() => this.SetSortColumnByDisplayIndex(1)),
6957
6958                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6959                     .FocusedOn(FocusedControl.ListTab)
6960                     .Do(() => this.SetSortColumnByDisplayIndex(2)),
6961
6962                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6963                     .FocusedOn(FocusedControl.ListTab)
6964                     .Do(() => this.SetSortColumnByDisplayIndex(3)),
6965
6966                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6967                     .FocusedOn(FocusedControl.ListTab)
6968                     .Do(() => this.SetSortColumnByDisplayIndex(4)),
6969
6970                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6971                     .FocusedOn(FocusedControl.ListTab)
6972                     .Do(() => this.SetSortColumnByDisplayIndex(5)),
6973
6974                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6975                     .FocusedOn(FocusedControl.ListTab)
6976                     .Do(() => this.SetSortColumnByDisplayIndex(6)),
6977
6978                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6979                     .FocusedOn(FocusedControl.ListTab)
6980                     .Do(() => this.SetSortColumnByDisplayIndex(7)),
6981
6982                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6983                     .FocusedOn(FocusedControl.ListTab)
6984                     .Do(() => this.SetSortLastColumn()),
6985
6986                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6987                     .Do(() => this.FavoritesRetweetOfficial()),
6988
6989                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6990                     .Do(() => this.FavoritesRetweetUnofficial()),
6991
6992                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6993                     .Do(() => this.OpenUserAppointUrl()),
6994
6995                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6996                     .FocusedOn(FocusedControl.PostBrowser)
6997                     .Do(() => this.doReTweetUnofficial()),
6998
6999                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
7000                     .OnlyWhen(() => this.ExistCurrentPost)
7001                     .Do(() => this.doTranslation(_curPost.TextFromApi)),
7002
7003                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7004                     .Do(() => this.doReTweetUnofficial()),
7005
7006                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
7007                     .Do(() => this.CopyUserId()),
7008
7009                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
7010                     .Do(() => this.tweetThumbnail1.ScrollUp()),
7011
7012                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
7013                     .Do(() => this.tweetThumbnail1.ScrollDown()),
7014
7015                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
7016                     .FocusedOn(FocusedControl.ListTab)
7017                     .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
7018                     .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
7019             };
7020         }
7021
7022         private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
7023         {
7024             // Task を返す非同期処理があれば asyncTask に代入する
7025             asyncTask = null;
7026
7027             // ShortcutCommand に対応しているコマンドはここで処理される
7028             foreach (var command in this.shortcutCommands)
7029             {
7030                 if (command.IsMatch(keyData, focusedOn))
7031                 {
7032                     asyncTask = command.RunCommand();
7033                     return command.PreventDefault;
7034                 }
7035             }
7036
7037             return false;
7038         }
7039
7040         private void ScrollDownPostBrowser(bool forward)
7041         {
7042             var doc = PostBrowser.Document;
7043             if (doc == null) return;
7044
7045             var tags = doc.GetElementsByTagName("html");
7046             if (tags.Count > 0)
7047             {
7048                 if (forward)
7049                     tags[0].ScrollTop += this._fntDetail.Height;
7050                 else
7051                     tags[0].ScrollTop -= this._fntDetail.Height;
7052             }
7053         }
7054
7055         private void PageDownPostBrowser(bool forward)
7056         {
7057             var doc = PostBrowser.Document;
7058             if (doc == null) return;
7059
7060             var tags = doc.GetElementsByTagName("html");
7061             if (tags.Count > 0)
7062             {
7063                 if (forward)
7064                     tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7065                 else
7066                     tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7067             }
7068         }
7069
7070         private void GoNextTab(bool forward)
7071         {
7072             int idx = ListTab.SelectedIndex;
7073             if (forward)
7074             {
7075                 idx += 1;
7076                 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7077             }
7078             else
7079             {
7080                 idx -= 1;
7081                 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7082             }
7083             ListTab.SelectedIndex = idx;
7084         }
7085
7086         private void CopyStot()
7087         {
7088             string clstr = "";
7089             StringBuilder sb = new StringBuilder();
7090             bool IsProtected = false;
7091             bool isDm = false;
7092             if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7093             foreach (int idx in _curList.SelectedIndices)
7094             {
7095                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7096                 if (post.IsProtect)
7097                 {
7098                     IsProtected = true;
7099                     continue;
7100                 }
7101                 if (post.IsDeleted) continue;
7102                 if (!isDm)
7103                 {
7104                     if (post.RetweetedId != null)
7105                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7106                     else
7107                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7108                 }
7109                 else
7110                 {
7111                     sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7112                 }
7113             }
7114             if (IsProtected)
7115             {
7116                 MessageBox.Show(Properties.Resources.CopyStotText1);
7117             }
7118             if (sb.Length > 0)
7119             {
7120                 clstr = sb.ToString();
7121                 try
7122                 {
7123                     Clipboard.SetDataObject(clstr, false, 5, 100);
7124                 }
7125                 catch (Exception ex)
7126                 {
7127                     MessageBox.Show(ex.Message);
7128                 }
7129             }
7130         }
7131
7132         private void CopyIdUri()
7133         {
7134             string clstr = "";
7135             StringBuilder sb = new StringBuilder();
7136             if (this._curTab == null) return;
7137             if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7138             if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7139             foreach (int idx in _curList.SelectedIndices)
7140             {
7141                 var post = _statuses.Tabs[_curTab.Text][idx];
7142                 sb.Append(MyCommon.GetStatusUrl(post));
7143                 sb.Append(Environment.NewLine);
7144             }
7145             if (sb.Length > 0)
7146             {
7147                 clstr = sb.ToString();
7148                 try
7149                 {
7150                     Clipboard.SetDataObject(clstr, false, 5, 100);
7151                 }
7152                 catch (Exception ex)
7153                 {
7154                     MessageBox.Show(ex.Message);
7155                 }
7156             }
7157         }
7158
7159         private void GoFav(bool forward)
7160         {
7161             if (_curList.VirtualListSize == 0) return;
7162             int fIdx = 0;
7163             int toIdx = 0;
7164             int stp = 1;
7165
7166             if (forward)
7167             {
7168                 if (_curList.SelectedIndices.Count == 0)
7169                 {
7170                     fIdx = 0;
7171                 }
7172                 else
7173                 {
7174                     fIdx = _curList.SelectedIndices[0] + 1;
7175                     if (fIdx > _curList.VirtualListSize - 1) return;
7176                 }
7177                 toIdx = _curList.VirtualListSize;
7178                 stp = 1;
7179             }
7180             else
7181             {
7182                 if (_curList.SelectedIndices.Count == 0)
7183                 {
7184                     fIdx = _curList.VirtualListSize - 1;
7185                 }
7186                 else
7187                 {
7188                     fIdx = _curList.SelectedIndices[0] - 1;
7189                     if (fIdx < 0) return;
7190                 }
7191                 toIdx = -1;
7192                 stp = -1;
7193             }
7194
7195             for (int idx = fIdx; idx != toIdx; idx += stp)
7196             {
7197                 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7198                 {
7199                     SelectListItem(_curList, idx);
7200                     _curList.EnsureVisible(idx);
7201                     break;
7202                 }
7203             }
7204         }
7205
7206         private void GoSamePostToAnotherTab(bool left)
7207         {
7208             if (_curList.VirtualListSize == 0) return;
7209             int fIdx = 0;
7210             int toIdx = 0;
7211             int stp = 1;
7212             long targetId = 0;
7213
7214             if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7215             if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7216
7217             targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7218
7219             if (left)
7220             {
7221                 // 左のタブへ
7222                 if (ListTab.SelectedIndex == 0)
7223                 {
7224                     return;
7225                 }
7226                 else
7227                 {
7228                     fIdx = ListTab.SelectedIndex - 1;
7229                 }
7230                 toIdx = -1;
7231                 stp = -1;
7232             }
7233             else
7234             {
7235                 // 右のタブへ
7236                 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7237                 {
7238                     return;
7239                 }
7240                 else
7241                 {
7242                     fIdx = ListTab.SelectedIndex + 1;
7243                 }
7244                 toIdx = ListTab.TabCount;
7245                 stp = 1;
7246             }
7247
7248             bool found = false;
7249             for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7250             {
7251                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7252                 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7253                 {
7254                     if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7255                     {
7256                         ListTab.SelectedIndex = tabidx;
7257                         SelectListItem(_curList, idx);
7258                         _curList.EnsureVisible(idx);
7259                         found = true;
7260                         break;
7261                     }
7262                 }
7263                 if (found) break;
7264             }
7265         }
7266
7267         private void GoPost(bool forward)
7268         {
7269             if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7270             int fIdx = 0;
7271             int toIdx = 0;
7272             int stp = 1;
7273
7274             if (forward)
7275             {
7276                 fIdx = _curList.SelectedIndices[0] + 1;
7277                 if (fIdx > _curList.VirtualListSize - 1) return;
7278                 toIdx = _curList.VirtualListSize;
7279                 stp = 1;
7280             }
7281             else
7282             {
7283                 fIdx = _curList.SelectedIndices[0] - 1;
7284                 if (fIdx < 0) return;
7285                 toIdx = -1;
7286                 stp = -1;
7287             }
7288
7289             string name = "";
7290             if (_curPost.RetweetedId == null)
7291             {
7292                 name = _curPost.ScreenName;
7293             }
7294             else
7295             {
7296                 name = _curPost.RetweetedBy;
7297             }
7298             for (int idx = fIdx; idx != toIdx; idx += stp)
7299             {
7300                 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7301                 {
7302                     if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7303                     {
7304                         SelectListItem(_curList, idx);
7305                         _curList.EnsureVisible(idx);
7306                         break;
7307                     }
7308                 }
7309                 else
7310                 {
7311                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7312                     {
7313                         SelectListItem(_curList, idx);
7314                         _curList.EnsureVisible(idx);
7315                         break;
7316                     }
7317                 }
7318             }
7319         }
7320
7321         private void GoRelPost(bool forward)
7322         {
7323             if (_curList.SelectedIndices.Count == 0) return;
7324
7325             int fIdx = 0;
7326             int toIdx = 0;
7327             int stp = 1;
7328             if (forward)
7329             {
7330                 fIdx = _curList.SelectedIndices[0] + 1;
7331                 if (fIdx > _curList.VirtualListSize - 1) return;
7332                 toIdx = _curList.VirtualListSize;
7333                 stp = 1;
7334             }
7335             else
7336             {
7337                 fIdx = _curList.SelectedIndices[0] - 1;
7338                 if (fIdx < 0) return;
7339                 toIdx = -1;
7340                 stp = -1;
7341             }
7342
7343             if (!_anchorFlag)
7344             {
7345                 if (_curPost == null) return;
7346                 _anchorPost = _curPost;
7347                 _anchorFlag = true;
7348             }
7349             else
7350             {
7351                 if (_anchorPost == null) return;
7352             }
7353
7354             for (int idx = fIdx; idx != toIdx; idx += stp)
7355             {
7356                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7357                 if (post.ScreenName == _anchorPost.ScreenName ||
7358                     post.RetweetedBy == _anchorPost.ScreenName ||
7359                     post.ScreenName == _anchorPost.RetweetedBy ||
7360                     (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7361                     _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
7362                     _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
7363                     post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
7364                     post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
7365                 {
7366                     SelectListItem(_curList, idx);
7367                     _curList.EnsureVisible(idx);
7368                     break;
7369                 }
7370             }
7371         }
7372
7373         private void GoAnchor()
7374         {
7375             if (_anchorPost == null) return;
7376             int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7377             if (idx == -1) return;
7378
7379             SelectListItem(_curList, idx);
7380             _curList.EnsureVisible(idx);
7381         }
7382
7383         private void GoTopEnd(bool GoTop)
7384         {
7385             if (_curList.VirtualListSize == 0)
7386                 return;
7387
7388             ListViewItem _item;
7389             int idx;
7390
7391             if (GoTop)
7392             {
7393                 _item = _curList.GetItemAt(0, 25);
7394                 if (_item == null)
7395                     idx = 0;
7396                 else
7397                     idx = _item.Index;
7398             }
7399             else
7400             {
7401                 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7402                 if (_item == null)
7403                     idx = _curList.VirtualListSize - 1;
7404                 else
7405                     idx = _item.Index;
7406             }
7407             SelectListItem(_curList, idx);
7408         }
7409
7410         private void GoMiddle()
7411         {
7412             if (_curList.VirtualListSize == 0)
7413                 return;
7414
7415             ListViewItem _item;
7416             int idx1;
7417             int idx2;
7418             int idx3;
7419
7420             _item = _curList.GetItemAt(0, 0);
7421             if (_item == null)
7422             {
7423                 idx1 = 0;
7424             }
7425             else
7426             {
7427                 idx1 = _item.Index;
7428             }
7429
7430             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7431             if (_item == null)
7432             {
7433                 idx2 = _curList.VirtualListSize - 1;
7434             }
7435             else
7436             {
7437                 idx2 = _item.Index;
7438             }
7439             idx3 = (idx1 + idx2) / 2;
7440
7441             SelectListItem(_curList, idx3);
7442         }
7443
7444         private void GoLast()
7445         {
7446             if (_curList.VirtualListSize == 0) return;
7447
7448             if (_statuses.SortOrder == SortOrder.Ascending)
7449             {
7450                 SelectListItem(_curList, _curList.VirtualListSize - 1);
7451                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7452             }
7453             else
7454             {
7455                 SelectListItem(_curList, 0);
7456                 _curList.EnsureVisible(0);
7457             }
7458         }
7459
7460         private void MoveTop()
7461         {
7462             if (_curList.SelectedIndices.Count == 0) return;
7463             int idx = _curList.SelectedIndices[0];
7464             if (_statuses.SortOrder == SortOrder.Ascending)
7465             {
7466                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7467             }
7468             else
7469             {
7470                 _curList.EnsureVisible(0);
7471             }
7472             _curList.EnsureVisible(idx);
7473         }
7474
7475         private async Task GoInReplyToPostTree()
7476         {
7477             if (_curPost == null) return;
7478
7479             TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7480
7481             if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7482             {
7483                 try
7484                 {
7485                     var post = await tw.GetStatusApi(false, _curPost.StatusId);
7486
7487                     _curPost.InReplyToStatusId = post.InReplyToStatusId;
7488                     _curPost.InReplyToUser = post.InReplyToUser;
7489                     _curPost.IsReply = post.IsReply;
7490                     this.PurgeListViewItemCache();
7491                     _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7492                 }
7493                 catch (WebApiException ex)
7494                 {
7495                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7496                 }
7497             }
7498
7499             if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7500
7501             if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7502             {
7503                 replyChains = new Stack<ReplyChain>();
7504             }
7505             replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7506
7507             int inReplyToIndex;
7508             string inReplyToTabName;
7509             long inReplyToId = _curPost.InReplyToStatusId.Value;
7510             string inReplyToUser = _curPost.InReplyToUser;
7511             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7512
7513             var inReplyToPosts = from tab in _statuses.Tabs.Values
7514                                  orderby tab != curTabClass
7515                                  from post in tab.Posts.Values
7516                                  where post.StatusId == inReplyToId
7517                                  let index = tab.IndexOf(post.StatusId)
7518                                  where index != -1
7519                                  select new {Tab = tab, Index = index};
7520
7521             var inReplyPost = inReplyToPosts.FirstOrDefault();
7522             if (inReplyPost == null)
7523             {
7524                 try
7525                 {
7526                     await Task.Run(async () =>
7527                     {
7528                         var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
7529                             .ConfigureAwait(false);
7530                         post.IsRead = true;
7531
7532                         _statuses.AddPost(post);
7533                         _statuses.DistributePosts();
7534                     });
7535                 }
7536                 catch (WebApiException ex)
7537                 {
7538                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7539                     await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7540                     return;
7541                 }
7542
7543                 this.RefreshTimeline();
7544
7545                 inReplyPost = inReplyToPosts.FirstOrDefault();
7546                 if (inReplyPost == null)
7547                 {
7548                     await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7549                     return;
7550                 }
7551             }
7552             inReplyToTabName = inReplyPost.Tab.TabName;
7553             inReplyToIndex = inReplyPost.Index;
7554
7555             TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7556             DetailsListView listView = (DetailsListView)tabPage.Tag;
7557
7558             if (_curTab != tabPage)
7559             {
7560                 this.ListTab.SelectTab(tabPage);
7561             }
7562
7563             this.SelectListItem(listView, inReplyToIndex);
7564             listView.EnsureVisible(inReplyToIndex);
7565         }
7566
7567         private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7568         {
7569             if (_curPost == null) return;
7570
7571             TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7572             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7573
7574             if (parallel)
7575             {
7576                 if (_curPost.InReplyToStatusId != null)
7577                 {
7578                     var posts = from t in _statuses.Tabs
7579                                 from p in t.Value.Posts
7580                                 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7581                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7582                                 where indexOf > -1
7583                                 orderby isForward ? indexOf : indexOf * -1
7584                                 orderby t.Value != curTabClass
7585                                 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7586                     try
7587                     {
7588                         var postList = posts.ToList();
7589                         for (int i = postList.Count - 1; i >= 0; i--)
7590                         {
7591                             int index = i;
7592                             if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7593                             {
7594                                 postList.RemoveAt(index);
7595                             }
7596                         }
7597                         var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7598                         if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7599                         if (post == null) post = postList.First();
7600                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7601                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7602                         SelectListItem(listView, post.Index);
7603                         listView.EnsureVisible(post.Index);
7604                     }
7605                     catch (InvalidOperationException)
7606                     {
7607                         return;
7608                     }
7609                 }
7610             }
7611             else
7612             {
7613                 if (replyChains == null || replyChains.Count < 1)
7614                 {
7615                     var posts = from t in _statuses.Tabs
7616                                 from p in t.Value.Posts
7617                                 where p.Value.InReplyToStatusId == _curPost.StatusId
7618                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7619                                 where indexOf > -1
7620                                 orderby indexOf
7621                                 orderby t.Value != curTabClass
7622                                 select new {Tab = t.Value, Index = indexOf};
7623                     try
7624                     {
7625                         var post = posts.First();
7626                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7627                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7628                         SelectListItem(listView, post.Index);
7629                         listView.EnsureVisible(post.Index);
7630                     }
7631                     catch (InvalidOperationException)
7632                     {
7633                         return;
7634                     }
7635                 }
7636                 else
7637                 {
7638                     ReplyChain chainHead = replyChains.Pop();
7639                     if (chainHead.InReplyToId == _curPost.StatusId)
7640                     {
7641                         int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7642                         if (idx == -1)
7643                         {
7644                             replyChains = null;
7645                         }
7646                         else
7647                         {
7648                             try
7649                             {
7650                                 ListTab.SelectTab(chainHead.OriginalTab);
7651                             }
7652                             catch (Exception)
7653                             {
7654                                 replyChains = null;
7655                             }
7656                             SelectListItem(_curList, idx);
7657                             _curList.EnsureVisible(idx);
7658                         }
7659                     }
7660                     else
7661                     {
7662                         replyChains = null;
7663                         this.GoBackInReplyToPostTree(parallel);
7664                     }
7665                 }
7666             }
7667         }
7668
7669         private void GoBackSelectPostChain()
7670         {
7671             if (this.selectPostChains.Count > 1)
7672             {
7673                 var idx = -1;
7674                 TabPage tp = null;
7675
7676                 do
7677                 {
7678                     try
7679                     {
7680                         this.selectPostChains.Pop();
7681                         var tabPostPair = this.selectPostChains.Peek();
7682
7683                         if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue;  //該当タブが存在しないので無視
7684
7685                         if (tabPostPair.Item2 != null)
7686                         {
7687                             idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7688                             if (idx == -1) continue;  //該当ポストが存在しないので無視
7689                         }
7690
7691                         tp = tabPostPair.Item1;
7692
7693                         this.selectPostChains.Pop();
7694                     }
7695                     catch (InvalidOperationException)
7696                     {
7697                     }
7698
7699                     break;
7700                 }
7701                 while (this.selectPostChains.Count > 1);
7702
7703                 if (tp == null)
7704                 {
7705                     //状態がおかしいので処理を中断
7706                     //履歴が残り1つであればクリアしておく
7707                     if (this.selectPostChains.Count == 1)
7708                         this.selectPostChains.Clear();
7709                     return;
7710                 }
7711
7712                 DetailsListView lst = (DetailsListView)tp.Tag;
7713                 this.ListTab.SelectedTab = tp;
7714                 if (idx > -1)
7715                 {
7716                     SelectListItem(lst, idx);
7717                     lst.EnsureVisible(idx);
7718                 }
7719                 lst.Focus();
7720             }
7721         }
7722
7723         private void PushSelectPostChain()
7724         {
7725             int count = this.selectPostChains.Count;
7726             if (count > 0)
7727             {
7728                 var p = this.selectPostChains.Peek();
7729                 if (p.Item1 == this._curTab)
7730                 {
7731                     if (p.Item2 == this._curPost) return;  //最新の履歴と同一
7732                     if (p.Item2 == null) this.selectPostChains.Pop();  //置き換えるため削除
7733                 }
7734             }
7735             if (count >= 2500) TrimPostChain();
7736             this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7737         }
7738
7739         private void TrimPostChain()
7740         {
7741             if (this.selectPostChains.Count <= 2000) return;
7742             var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7743             for (int i = 0; i < 2000; i++)
7744             {
7745                 p.Push(this.selectPostChains.Pop());
7746             }
7747             this.selectPostChains.Clear();
7748             for (int i = 0; i < 2000; i++)
7749             {
7750                 this.selectPostChains.Push(p.Pop());
7751             }
7752         }
7753
7754         private bool GoStatus(long statusId)
7755         {
7756             if (statusId == 0) return false;
7757             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7758             {
7759                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7760                 {
7761                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7762                     ListTab.SelectedIndex = tabidx;
7763                     SelectListItem(_curList, idx);
7764                     _curList.EnsureVisible(idx);
7765                     return true;
7766                 }
7767             }
7768             return false;
7769         }
7770
7771         private bool GoDirectMessage(long statusId)
7772         {
7773             if (statusId == 0) return false;
7774             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7775             {
7776                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7777                 {
7778                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7779                     ListTab.SelectedIndex = tabidx;
7780                     SelectListItem(_curList, idx);
7781                     _curList.EnsureVisible(idx);
7782                     return true;
7783                 }
7784             }
7785             return false;
7786         }
7787
7788         private void MyList_MouseClick(object sender, MouseEventArgs e)
7789         {
7790             _anchorFlag = false;
7791         }
7792
7793         private void StatusText_Enter(object sender, EventArgs e)
7794         {
7795             // フォーカスの戻り先を StatusText に設定
7796             this.Tag = StatusText;
7797             StatusText.BackColor = _clInputBackcolor;
7798         }
7799
7800         public Color InputBackColor
7801         {
7802             get { return _clInputBackcolor; }
7803             set { _clInputBackcolor = value; }
7804         }
7805
7806         private void StatusText_Leave(object sender, EventArgs e)
7807         {
7808             // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7809             if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7810             StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7811         }
7812
7813         private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7814         {
7815             Task asyncTask;
7816             if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7817             {
7818                 e.Handled = true;
7819                 e.SuppressKeyPress = true;
7820             }
7821
7822             this.StatusText_TextChanged(null, null);
7823
7824             if (asyncTask != null)
7825                 await asyncTask;
7826         }
7827
7828         private void SaveConfigsAll(bool ifModified)
7829         {
7830             if (!ifModified)
7831             {
7832                 SaveConfigsCommon();
7833                 SaveConfigsLocal();
7834                 SaveConfigsTabs();
7835                 SaveConfigsAtId();
7836             }
7837             else
7838             {
7839                 if (ModifySettingCommon) SaveConfigsCommon();
7840                 if (ModifySettingLocal) SaveConfigsLocal();
7841                 if (ModifySettingAtId) SaveConfigsAtId();
7842             }
7843         }
7844
7845         private void SaveConfigsAtId()
7846         {
7847             if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7848
7849             ModifySettingAtId = false;
7850             SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7851             cfgAtId.Save();
7852         }
7853
7854         private void SaveConfigsCommon()
7855         {
7856             if (_ignoreConfigSave) return;
7857
7858             ModifySettingCommon = false;
7859             lock (_syncObject)
7860             {
7861                 _cfgCommon.UserName = tw.Username;
7862                 _cfgCommon.UserId = tw.UserId;
7863                 _cfgCommon.Token = tw.AccessToken;
7864                 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7865
7866                 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7867                    IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7868                 {
7869                     _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7870                 }
7871
7872                 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7873                 switch (_statuses.SortMode)
7874                 {
7875                     case ComparerMode.Nickname:  //ニックネーム
7876                         _cfgCommon.SortColumn = 1;
7877                         break;
7878                     case ComparerMode.Data:  //本文
7879                         _cfgCommon.SortColumn = 2;
7880                         break;
7881                     case ComparerMode.Id:  //時刻=発言Id
7882                         _cfgCommon.SortColumn = 3;
7883                         break;
7884                     case ComparerMode.Name:  //名前
7885                         _cfgCommon.SortColumn = 4;
7886                         break;
7887                     case ComparerMode.Source:  //Source
7888                         _cfgCommon.SortColumn = 7;
7889                         break;
7890                 }
7891
7892                 _cfgCommon.HashTags = HashMgr.HashHistories;
7893                 if (HashMgr.IsPermanent)
7894                 {
7895                     _cfgCommon.HashSelected = HashMgr.UseHash;
7896                 }
7897                 else
7898                 {
7899                     _cfgCommon.HashSelected = "";
7900                 }
7901                 _cfgCommon.HashIsHead = HashMgr.IsHead;
7902                 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7903                 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7904                 if (ToolStripFocusLockMenuItem != null &&
7905                         ToolStripFocusLockMenuItem.IsDisposed == false)
7906                 {
7907                     _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7908                 }
7909                 _cfgCommon.TrackWord = tw.TrackWord;
7910                 _cfgCommon.AllAtReply = tw.AllAtReply;
7911                 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7912                 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7913
7914                 _cfgCommon.Save();
7915             }
7916         }
7917
7918         private void SaveConfigsLocal()
7919         {
7920             if (_ignoreConfigSave) return;
7921             lock (_syncObject)
7922             {
7923                 ModifySettingLocal = false;
7924                 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7925                 _cfgLocal.FormSize = _mySize;
7926                 _cfgLocal.FormLocation = _myLoc;
7927                 _cfgLocal.SplitterDistance = _mySpDis;
7928                 _cfgLocal.PreviewDistance = _mySpDis3;
7929                 _cfgLocal.StatusMultiline = StatusText.Multiline;
7930                 _cfgLocal.StatusTextHeight = _mySpDis2;
7931
7932                 _cfgLocal.FontUnread = _fntUnread;
7933                 _cfgLocal.ColorUnread = _clUnread;
7934                 _cfgLocal.FontRead = _fntReaded;
7935                 _cfgLocal.ColorRead = _clReaded;
7936                 _cfgLocal.FontDetail = _fntDetail;
7937                 _cfgLocal.ColorDetail = _clDetail;
7938                 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7939                 _cfgLocal.ColorDetailLink = _clDetailLink;
7940                 _cfgLocal.ColorFav = _clFav;
7941                 _cfgLocal.ColorOWL = _clOWL;
7942                 _cfgLocal.ColorRetweet = _clRetweet;
7943                 _cfgLocal.ColorSelf = _clSelf;
7944                 _cfgLocal.ColorAtSelf = _clAtSelf;
7945                 _cfgLocal.ColorTarget = _clTarget;
7946                 _cfgLocal.ColorAtTarget = _clAtTarget;
7947                 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7948                 _cfgLocal.ColorAtTo = _clAtTo;
7949                 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7950                 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7951                 _cfgLocal.ColorInputFont = _clInputFont;
7952                 _cfgLocal.FontInputFont = _fntInputFont;
7953
7954                 if (_ignoreConfigSave) return;
7955                 _cfgLocal.Save();
7956             }
7957         }
7958
7959         private void SaveConfigsTabs()
7960         {
7961             var tabsSetting = new SettingTabs();
7962
7963             var tabs = this.ListTab.TabPages.Cast<TabPage>()
7964                 .Select(x => this._statuses.Tabs[x.Text])
7965                 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7966
7967             foreach (var tab in tabs)
7968             {
7969                 if (tab.TabType == MyCommon.TabUsageType.Related || tab.TabType == MyCommon.TabUsageType.SearchResults)
7970                     continue;
7971
7972                 var tabSetting = new SettingTabs.SettingTabItem
7973                 {
7974                     TabName = tab.TabName,
7975                     TabType = tab.TabType,
7976                     UnreadManage = tab.UnreadManage,
7977                     Protected = tab.Protected,
7978                     Notify = tab.Notify,
7979                     SoundFile = tab.SoundFile,
7980                     FilterArray = tab.FilterArray,
7981                     User = tab.User,
7982                     SearchWords = tab.SearchWords,
7983                     SearchLang = tab.SearchLang,
7984                     ListInfo = tab.ListInfo,
7985                 };
7986                 tabsSetting.Tabs.Add(tabSetting);
7987             }
7988
7989             tabsSetting.Save();
7990         }
7991
7992         private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7993         {
7994             string inputText;
7995             var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7996             if (ret != DialogResult.OK)
7997                 return;
7998
7999             var match = Twitter.StatusUrlRegex.Match(inputText);
8000             if (!match.Success)
8001             {
8002                 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8003                     Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8004                 return;
8005             }
8006
8007             try
8008             {
8009                 var statusId = long.Parse(match.Groups["StatusId"].Value);
8010                 await this.OpenRelatedTab(statusId);
8011             }
8012             catch (TabException ex)
8013             {
8014                 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8015             }
8016         }
8017
8018         private void SaveLogMenuItem_Click(object sender, EventArgs e)
8019         {
8020             DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8021                     Properties.Resources.SaveLogMenuItem_ClickText2,
8022                     MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8023             if (rslt == DialogResult.Cancel) return;
8024
8025             SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8026             SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8027             SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8028             SaveFileDialog1.FilterIndex = 0;
8029             SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8030             SaveFileDialog1.RestoreDirectory = true;
8031
8032             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8033             {
8034                 if (!SaveFileDialog1.ValidateNames) return;
8035                 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8036                 {
8037                     if (rslt == DialogResult.Yes)
8038                     {
8039                         //All
8040                         for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8041                         {
8042                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
8043                             string protect = "";
8044                             if (post.IsProtect) protect = "Protect";
8045                             sw.WriteLine(post.Nickname + "\t" +
8046                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8047                                      post.CreatedAt.ToString() + "\t" +
8048                                      post.ScreenName + "\t" +
8049                                      post.StatusId.ToString() + "\t" +
8050                                      post.ImageUrl + "\t" +
8051                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8052                                      protect);
8053                         }
8054                     }
8055                     else
8056                     {
8057                         foreach (int idx in _curList.SelectedIndices)
8058                         {
8059                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
8060                             string protect = "";
8061                             if (post.IsProtect) protect = "Protect";
8062                             sw.WriteLine(post.Nickname + "\t" +
8063                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8064                                      post.CreatedAt.ToString() + "\t" +
8065                                      post.ScreenName + "\t" +
8066                                      post.StatusId.ToString() + "\t" +
8067                                      post.ImageUrl + "\t" +
8068                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8069                                      protect);
8070                         }
8071                     }
8072                 }
8073             }
8074             this.TopMost = this._cfgCommon.AlwaysTop;
8075         }
8076
8077         private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8078         {
8079             Task asyncTask;
8080             bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
8081             if (KeyRes)
8082             {
8083                 e.IsInputKey = true;
8084             }
8085             else
8086             {
8087                 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8088                 {
8089                     var shortcut = (Shortcut)e.KeyData;
8090                     switch (shortcut)
8091                     {
8092                         case Shortcut.CtrlA:
8093                         case Shortcut.CtrlC:
8094                         case Shortcut.CtrlIns:
8095                             // 既定の動作を有効にする
8096                             break;
8097                         default:
8098                             // その他のショートカットキーは無効にする
8099                             e.IsInputKey = true;
8100                             break;
8101                     }
8102                 }
8103             }
8104
8105             if (asyncTask != null)
8106                 await asyncTask;
8107         }
8108         public bool TabRename(ref string tabName)
8109         {
8110             //タブ名変更
8111             string newTabText = null;
8112             using (InputTabName inputName = new InputTabName())
8113             {
8114                 inputName.TabName = tabName;
8115                 inputName.ShowDialog();
8116                 if (inputName.DialogResult == DialogResult.Cancel) return false;
8117                 newTabText = inputName.TabName;
8118             }
8119             this.TopMost = this._cfgCommon.AlwaysTop;
8120             if (!string.IsNullOrEmpty(newTabText))
8121             {
8122                 //新タブ名存在チェック
8123                 for (int i = 0; i < ListTab.TabCount; i++)
8124                 {
8125                     if (ListTab.TabPages[i].Text == newTabText)
8126                     {
8127                         string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8128                         MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8129                         return false;
8130                     }
8131                 }
8132                 //タブ名を変更
8133                 for (int i = 0; i < ListTab.TabCount; i++)
8134                 {
8135                     if (ListTab.TabPages[i].Text == tabName)
8136                     {
8137                         ListTab.TabPages[i].Text = newTabText;
8138                         break;
8139                     }
8140                 }
8141                 _statuses.RenameTab(tabName, newTabText);
8142
8143                 SaveConfigsCommon();
8144                 SaveConfigsTabs();
8145                 _rclickTabName = newTabText;
8146                 tabName = newTabText;
8147                 return true;
8148             }
8149             else
8150             {
8151                 return false;
8152             }
8153         }
8154
8155         private void ListTab_MouseClick(object sender, MouseEventArgs e)
8156         {
8157             if (e.Button == MouseButtons.Middle)
8158             {
8159                 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8160                 {
8161                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8162                     {
8163                         this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8164                         this.SaveConfigsTabs();
8165                         break;
8166                     }
8167                 }
8168             }
8169         }
8170
8171         private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8172         {
8173             string tn = ListTab.SelectedTab.Text;
8174             TabRename(ref tn);
8175         }
8176
8177         private void ListTab_MouseDown(object sender, MouseEventArgs e)
8178         {
8179             if (this._cfgCommon.TabMouseLock) return;
8180             Point cpos = new Point(e.X, e.Y);
8181             if (e.Button == MouseButtons.Left)
8182             {
8183                 for (int i = 0; i < ListTab.TabPages.Count; i++)
8184                 {
8185                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8186                     {
8187                         _tabDrag = true;
8188                         _tabMouseDownPoint = e.Location;
8189                         break;
8190                     }
8191                 }
8192             }
8193             else
8194             {
8195                 _tabDrag = false;
8196             }
8197         }
8198
8199         private void ListTab_DragEnter(object sender, DragEventArgs e)
8200         {
8201             if (e.Data.GetDataPresent(typeof(TabPage)))
8202                 e.Effect = DragDropEffects.Move;
8203             else
8204                 e.Effect = DragDropEffects.None;
8205         }
8206
8207         private void ListTab_DragDrop(object sender, DragEventArgs e)
8208         {
8209             if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8210
8211             _tabDrag = false;
8212             string tn = "";
8213             bool bef = false;
8214             Point cpos = new Point(e.X, e.Y);
8215             Point spos = ListTab.PointToClient(cpos);
8216             int i;
8217             for (i = 0; i < ListTab.TabPages.Count; i++)
8218             {
8219                 Rectangle rect = ListTab.GetTabRect(i);
8220                 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8221                     rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8222                 {
8223                     tn = ListTab.TabPages[i].Text;
8224                     if (spos.X <= (rect.Left + rect.Right) / 2)
8225                         bef = true;
8226                     else
8227                         bef = false;
8228
8229                     break;
8230                 }
8231             }
8232
8233             //タブのないところにドロップ->最後尾へ移動
8234             if (string.IsNullOrEmpty(tn))
8235             {
8236                 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8237                 bef = false;
8238                 i = ListTab.TabPages.Count - 1;
8239             }
8240
8241             TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8242             if (tp.Text == tn) return;
8243
8244             ReOrderTab(tp.Text, tn, bef);
8245         }
8246
8247         public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8248         {
8249             var baseIndex = this.GetTabPageIndex(baseTabText);
8250             if (baseIndex == -1)
8251                 return;
8252
8253             var targetIndex = this.GetTabPageIndex(targetTabText);
8254             if (targetIndex == -1)
8255                 return;
8256
8257             using (ControlTransaction.Layout(this.ListTab))
8258             {
8259                 var mTp = this.ListTab.TabPages[targetIndex];
8260                 this.ListTab.TabPages.Remove(mTp);
8261
8262                 if (targetIndex < baseIndex)
8263                     baseIndex--;
8264
8265                 if (isBeforeBaseTab)
8266                     ListTab.TabPages.Insert(baseIndex, mTp);
8267                 else
8268                     ListTab.TabPages.Insert(baseIndex + 1, mTp);
8269             }
8270
8271             SaveConfigsTabs();
8272         }
8273
8274         private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8275         {
8276             //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8277             //isReply:true=@,false=DM
8278             if (!StatusText.Enabled) return;
8279             if (_curList == null) return;
8280             if (_curTab == null) return;
8281             if (!this.ExistCurrentPost) return;
8282
8283             // 複数あてリプライはReplyではなく通常ポスト
8284             //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8285             //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8286             //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8287
8288             if (_curList.SelectedIndices.Count > 0)
8289             {
8290                 // アイテムが1件以上選択されている
8291                 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8292                 {
8293                     // 単独ユーザー宛リプライまたはDM
8294                     if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8295                     {
8296                         // ダイレクトメッセージ
8297                         StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8298                         StatusText.SelectionStart = StatusText.Text.Length;
8299                         StatusText.Focus();
8300                         this.inReplyTo = null;
8301                         return;
8302                     }
8303                     if (string.IsNullOrEmpty(StatusText.Text))
8304                     {
8305                         //空の場合
8306
8307                         // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8308                         StatusText.Text = "@" + _curPost.ScreenName + " ";
8309
8310                         var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8311                         var inReplyToScreenName = this._curPost.ScreenName;
8312                         this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8313                     }
8314                     else
8315                     {
8316                         //何か入力済の場合
8317
8318                         if (isAuto)
8319                         {
8320                             //1件選んでEnter or DoubleClick
8321                             if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8322                             {
8323                                 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
8324                                 {
8325                                     //返信先書き換え
8326                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8327                                     var inReplyToScreenName = this._curPost.ScreenName;
8328                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8329                                 }
8330                                 return;
8331                             }
8332                             if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
8333                             {
8334                                 //文頭@以外
8335                                 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8336                                 {
8337                                     // 複数リプライ
8338                                     StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8339                                     this.inReplyTo = null;
8340                                 }
8341                                 else
8342                                 {
8343                                     // 単独リプライ
8344                                     StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8345                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8346                                     var inReplyToScreenName = this._curPost.ScreenName;
8347                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8348                                 }
8349                             }
8350                             else
8351                             {
8352                                 //文頭@
8353                                 // 複数リプライ
8354                                 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8355                                 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8356                                 this.inReplyTo = null;
8357                             }
8358                         }
8359                         else
8360                         {
8361                             //1件選んでCtrl-Rの場合(返信先操作せず)
8362                             int sidx = StatusText.SelectionStart;
8363                             string id = "@" + _curPost.ScreenName + " ";
8364                             if (sidx > 0)
8365                             {
8366                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8367                                 {
8368                                     id = " " + id;
8369                                 }
8370                             }
8371                             StatusText.Text = StatusText.Text.Insert(sidx, id);
8372                             sidx += id.Length;
8373                             //if (StatusText.Text.StartsWith("@"))
8374                             //{
8375                             //    //複数リプライ
8376                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8377                             //    sidx += 5 + _curPost.ScreenName.Length;
8378                             //}
8379                             //else
8380                             //{
8381                             //    // 複数リプライ
8382                             //    StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8383                             //    sidx += 3 + _curPost.ScreenName.Length;
8384                             //}
8385                             StatusText.SelectionStart = sidx;
8386                             StatusText.Focus();
8387                             //_reply_to_id = 0;
8388                             //_reply_to_name = null;
8389                             return;
8390                         }
8391                     }
8392                 }
8393                 else
8394                 {
8395                     // 複数リプライ
8396                     if (!isAuto && !isReply) return;
8397
8398                     //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8399
8400                     if (isAuto)
8401                     {
8402                         //Enter or DoubleClick
8403
8404                         string sTxt = StatusText.Text;
8405                         if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
8406                         {
8407                             sTxt = ". " + sTxt;
8408                             this.inReplyTo = null;
8409                         }
8410                         for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8411                         {
8412                             PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8413                             if (!sTxt.Contains("@" + post.ScreenName + " "))
8414                             {
8415                                 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8416                                 //sTxt = "@" + post.ScreenName + " " + sTxt;
8417                             }
8418                         }
8419                         StatusText.Text = sTxt;
8420                     }
8421                     else
8422                     {
8423                         //C-S-r or C-r
8424                         if (_curList.SelectedIndices.Count > 1)
8425                         {
8426                             //複数ポスト選択
8427
8428                             string ids = "";
8429                             int sidx = StatusText.SelectionStart;
8430                             for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8431                             {
8432                                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8433                                 if (!ids.Contains("@" + post.ScreenName + " ") &&
8434                                     !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8435                                 {
8436                                     ids += "@" + post.ScreenName + " ";
8437                                 }
8438                                 if (isAll)
8439                                 {
8440                                     foreach (string nm in post.ReplyToList)
8441                                     {
8442                                         if (!ids.Contains("@" + nm + " ") &&
8443                                             !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8444                                         {
8445                                             Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8446                                             if (m.Success)
8447                                                 ids += "@" + m.Result("${id}") + " ";
8448                                             else
8449                                                 ids += "@" + nm + " ";
8450                                         }
8451                                     }
8452                                 }
8453                             }
8454                             if (ids.Length == 0) return;
8455                             if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8456                             {
8457                                 StatusText.Text = ". " + StatusText.Text;
8458                                 sidx += 2;
8459                                 this.inReplyTo = null;
8460                             }
8461                             if (sidx > 0)
8462                             {
8463                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8464                                 {
8465                                     ids = " " + ids;
8466                                 }
8467                             }
8468                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8469                             sidx += ids.Length;
8470                             //if (StatusText.Text.StartsWith("@"))
8471                             //{
8472                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8473                             //    sidx += 2 + ids.Length;
8474                             //}
8475                             //else
8476                             //{
8477                             //    StatusText.Text = StatusText.Text.Insert(sidx, ids);
8478                             //    sidx += 1 + ids.Length;
8479                             //}
8480                             StatusText.SelectionStart = sidx;
8481                             StatusText.Focus();
8482                             return;
8483                         }
8484                         else
8485                         {
8486                             //1件のみ選択のC-S-r(返信元付加する可能性あり)
8487
8488                             string ids = "";
8489                             int sidx = StatusText.SelectionStart;
8490                             PostClass post = _curPost;
8491                             if (!ids.Contains("@" + post.ScreenName + " ") &&
8492                                 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8493                             {
8494                                 ids += "@" + post.ScreenName + " ";
8495                             }
8496                             foreach (string nm in post.ReplyToList)
8497                             {
8498                                 if (!ids.Contains("@" + nm + " ") &&
8499                                     !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8500                                 {
8501                                     Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8502                                     if (m.Success)
8503                                         ids += "@" + m.Result("${id}") + " ";
8504                                     else
8505                                         ids += "@" + nm + " ";
8506                                 }
8507                             }
8508                             if (!string.IsNullOrEmpty(post.RetweetedBy))
8509                             {
8510                                 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8511                                    !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8512                                 {
8513                                     ids += "@" + post.RetweetedBy + " ";
8514                                 }
8515                             }
8516                             if (ids.Length == 0) return;
8517                             if (string.IsNullOrEmpty(StatusText.Text))
8518                             {
8519                                 //未入力の場合のみ返信先付加
8520                                 StatusText.Text = ids;
8521                                 StatusText.SelectionStart = ids.Length;
8522                                 StatusText.Focus();
8523
8524                                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8525                                 var inReplyToScreenName = this._curPost.ScreenName;
8526                                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8527                                 return;
8528                             }
8529
8530                             if (sidx > 0)
8531                             {
8532                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8533                                 {
8534                                     ids = " " + ids;
8535                                 }
8536                             }
8537                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8538                             sidx += ids.Length;
8539                             StatusText.SelectionStart = sidx;
8540                             StatusText.Focus();
8541                             return;
8542                         }
8543                     }
8544                 }
8545                 StatusText.SelectionStart = StatusText.Text.Length;
8546                 StatusText.Focus();
8547             }
8548         }
8549
8550         private void ListTab_MouseUp(object sender, MouseEventArgs e)
8551         {
8552             _tabDrag = false;
8553         }
8554
8555         private static int iconCnt = 0;
8556         private static int blinkCnt = 0;
8557         private static bool blink = false;
8558         private static bool idle = false;
8559
8560         private async Task RefreshTasktrayIcon()
8561         {
8562             if (_colorize)
8563                 await this.Colorize();
8564
8565             if (!TimerRefreshIcon.Enabled) return;
8566             //Static usCheckCnt As int = 0
8567
8568             //Static iconDlListTopItem As ListViewItem = null
8569
8570             //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8571             //    ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8572             //else
8573             //    ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8574             //
8575             //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8576
8577             iconCnt += 1;
8578             blinkCnt += 1;
8579             //usCheckCnt += 1;
8580
8581             //if (usCheckCnt > 300)    //1min
8582             //{
8583             //    usCheckCnt = 0;
8584             //    if (!this.IsReceivedUserStream)
8585             //    {
8586             //        TraceOut("ReconnectUserStream");
8587             //        tw.ReconnectUserStream();
8588             //    }
8589             //}
8590
8591             var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8592
8593             if (iconCnt >= this.NIconRefresh.Length)
8594             {
8595                 iconCnt = 0;
8596             }
8597             if (blinkCnt > 10)
8598             {
8599                 blinkCnt = 0;
8600                 //未保存の変更を保存
8601                 SaveConfigsAll(true);
8602             }
8603
8604             if (busy)
8605             {
8606                 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8607                 idle = false;
8608                 _myStatusError = false;
8609                 return;
8610             }
8611
8612             TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8613             if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8614             {
8615                 if (blinkCnt > 0) return;
8616                 blink = !blink;
8617                 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8618                 {
8619                     NotifyIcon1.Icon = ReplyIcon;
8620                 }
8621                 else
8622                 {
8623                     NotifyIcon1.Icon = ReplyIconBlink;
8624                 }
8625                 idle = false;
8626                 return;
8627             }
8628
8629             if (idle) return;
8630             idle = true;
8631             //優先度:エラー→オフライン→アイドル
8632             //エラーは更新アイコンでクリアされる
8633             if (_myStatusError)
8634             {
8635                 NotifyIcon1.Icon = NIconAtRed;
8636                 return;
8637             }
8638             if (_myStatusOnline)
8639             {
8640                 NotifyIcon1.Icon = NIconAt;
8641             }
8642             else
8643             {
8644                 NotifyIcon1.Icon = NIconAtSmoke;
8645             }
8646         }
8647
8648         private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8649         {
8650             //200ms
8651             await this.RefreshTasktrayIcon();
8652         }
8653
8654         private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8655         {
8656             //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8657             if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8658             {
8659                 if (ListTab != null && ListTab.SelectedTab != null)
8660                     _rclickTabName = ListTab.SelectedTab.Text;
8661                 else
8662                     return;
8663             }
8664
8665             if (_statuses == null) return;
8666             if (_statuses.Tabs == null) return;
8667
8668             TabClass tb = _statuses.Tabs[_rclickTabName];
8669             if (tb == null) return;
8670
8671             NotifyDispMenuItem.Checked = tb.Notify;
8672             this.NotifyTbMenuItem.Checked = tb.Notify;
8673
8674             soundfileListup = true;
8675             SoundFileComboBox.Items.Clear();
8676             this.SoundFileTbComboBox.Items.Clear();
8677             SoundFileComboBox.Items.Add("");
8678             this.SoundFileTbComboBox.Items.Add("");
8679             DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8680             if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8681             {
8682                 oDir = oDir.GetDirectories("Sounds")[0];
8683             }
8684             foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8685             {
8686                 SoundFileComboBox.Items.Add(oFile.Name);
8687                 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8688             }
8689             int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8690             if (idx == -1) idx = 0;
8691             SoundFileComboBox.SelectedIndex = idx;
8692             this.SoundFileTbComboBox.SelectedIndex = idx;
8693             soundfileListup = false;
8694             UreadManageMenuItem.Checked = tb.UnreadManage;
8695             this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8696
8697             TabMenuControl(_rclickTabName);
8698         }
8699
8700         private void TabMenuControl(string tabName)
8701         {
8702             var tabInfo = _statuses.GetTabByName(tabName);
8703
8704             this.FilterEditMenuItem.Enabled = true;
8705             this.EditRuleTbMenuItem.Enabled = true;
8706
8707             if (tabInfo.IsDefaultTabType)
8708             {
8709                 this.ProtectTabMenuItem.Enabled = false;
8710                 this.ProtectTbMenuItem.Enabled = false;
8711             }
8712             else
8713             {
8714                 this.ProtectTabMenuItem.Enabled = true;
8715                 this.ProtectTbMenuItem.Enabled = true;
8716             }
8717
8718             if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8719             {
8720                 this.ProtectTabMenuItem.Checked = true;
8721                 this.ProtectTbMenuItem.Checked = true;
8722                 this.DeleteTabMenuItem.Enabled = false;
8723                 this.DeleteTbMenuItem.Enabled = false;
8724             }
8725             else
8726             {
8727                 this.ProtectTabMenuItem.Checked = false;
8728                 this.ProtectTbMenuItem.Checked = false;
8729                 this.DeleteTabMenuItem.Enabled = true;
8730                 this.DeleteTbMenuItem.Enabled = true;
8731             }
8732         }
8733
8734         private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8735         {
8736             var checkState = ((ToolStripMenuItem)sender).Checked;
8737
8738             // チェック状態を同期
8739             this.ProtectTbMenuItem.Checked = checkState;
8740             this.ProtectTabMenuItem.Checked = checkState;
8741
8742             // ロック中はタブの削除を無効化
8743             this.DeleteTabMenuItem.Enabled = !checkState;
8744             this.DeleteTbMenuItem.Enabled = !checkState;
8745
8746             if (string.IsNullOrEmpty(_rclickTabName)) return;
8747             _statuses.Tabs[_rclickTabName].Protected = checkState;
8748
8749             SaveConfigsTabs();
8750         }
8751
8752         private void UreadManageMenuItem_Click(object sender, EventArgs e)
8753         {
8754             UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8755             this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8756
8757             if (string.IsNullOrEmpty(_rclickTabName)) return;
8758             ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8759
8760             SaveConfigsTabs();
8761         }
8762
8763         public void ChangeTabUnreadManage(string tabName, bool isManage)
8764         {
8765             var idx = this.GetTabPageIndex(tabName);
8766             if (idx == -1)
8767                 return;
8768
8769             _statuses.Tabs[tabName].UnreadManage = isManage;
8770             if (this._cfgCommon.TabIconDisp)
8771             {
8772                 if (_statuses.Tabs[tabName].UnreadCount > 0)
8773                     ListTab.TabPages[idx].ImageIndex = 0;
8774                 else
8775                     ListTab.TabPages[idx].ImageIndex = -1;
8776             }
8777
8778             if (_curTab.Text == tabName)
8779             {
8780                 this.PurgeListViewItemCache();
8781                 _curList.Refresh();
8782             }
8783
8784             SetMainWindowTitle();
8785             SetStatusLabelUrl();
8786             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8787         }
8788
8789         private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8790         {
8791             NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8792             this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8793
8794             if (string.IsNullOrEmpty(_rclickTabName)) return;
8795
8796             _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8797
8798             SaveConfigsTabs();
8799         }
8800
8801         private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8802         {
8803             if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8804
8805             _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8806
8807             SaveConfigsTabs();
8808         }
8809
8810         private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8811         {
8812             if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8813
8814             RemoveSpecifiedTab(_rclickTabName, true);
8815             SaveConfigsTabs();
8816         }
8817
8818         private void FilterEditMenuItem_Click(object sender, EventArgs e)
8819         {
8820             if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8821
8822             using (var fltDialog = new FilterDialog())
8823             {
8824                 fltDialog.Owner = this;
8825                 fltDialog.SetCurrent(_rclickTabName);
8826                 fltDialog.ShowDialog(this);
8827             }
8828             this.TopMost = this._cfgCommon.AlwaysTop;
8829
8830             this.ApplyPostFilters();
8831             SaveConfigsTabs();
8832         }
8833
8834         private void AddTabMenuItem_Click(object sender, EventArgs e)
8835         {
8836             string tabName = null;
8837             MyCommon.TabUsageType tabUsage;
8838             using (InputTabName inputName = new InputTabName())
8839             {
8840                 inputName.TabName = _statuses.MakeTabName("MyTab");
8841                 inputName.IsShowUsage = true;
8842                 inputName.ShowDialog();
8843                 if (inputName.DialogResult == DialogResult.Cancel) return;
8844                 tabName = inputName.TabName;
8845                 tabUsage = inputName.Usage;
8846             }
8847             this.TopMost = this._cfgCommon.AlwaysTop;
8848             if (!string.IsNullOrEmpty(tabName))
8849             {
8850                 //List対応
8851                 ListElement list = null;
8852                 if (tabUsage == MyCommon.TabUsageType.Lists)
8853                 {
8854                     using (ListAvailable listAvail = new ListAvailable())
8855                     {
8856                         if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8857                         if (listAvail.SelectedList == null) return;
8858                         list = listAvail.SelectedList;
8859                     }
8860                 }
8861                 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8862                 {
8863                     string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8864                     MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8865                 }
8866                 else
8867                 {
8868                     //成功
8869                     SaveConfigsTabs();
8870                     if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8871                     {
8872                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8873                         ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8874                     }
8875                     if (tabUsage == MyCommon.TabUsageType.Lists)
8876                     {
8877                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8878                         var tab = this._statuses.Tabs[this._curTab.Text];
8879                         this.GetListTimelineAsync(tab);
8880                     }
8881                 }
8882             }
8883         }
8884
8885         private void TabMenuItem_Click(object sender, EventArgs e)
8886         {
8887             using (var fltDialog = new FilterDialog())
8888             {
8889                 fltDialog.Owner = this;
8890
8891                 //選択発言を元にフィルタ追加
8892                 foreach (int idx in _curList.SelectedIndices)
8893                 {
8894                     string tabName;
8895                     //タブ選択(or追加)
8896                     if (!SelectTab(out tabName)) return;
8897
8898                     fltDialog.SetCurrent(tabName);
8899                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8900                     {
8901                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8902                     }
8903                     else
8904                     {
8905                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8906                     }
8907                     fltDialog.ShowDialog(this);
8908                     this.TopMost = this._cfgCommon.AlwaysTop;
8909                 }
8910             }
8911
8912             this.ApplyPostFilters();
8913             SaveConfigsTabs();
8914             if (this.ListTab.SelectedTab != null &&
8915                 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8916             {
8917                 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8918             }
8919         }
8920
8921         protected override bool ProcessDialogKey(Keys keyData)
8922         {
8923             //TextBox1でEnterを押してもビープ音が鳴らないようにする
8924             if ((keyData & Keys.KeyCode) == Keys.Enter)
8925             {
8926                 if (StatusText.Focused)
8927                 {
8928                     bool _NewLine = false;
8929                     bool _Post = false;
8930
8931                     if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8932                     {
8933                         if (StatusText.Multiline)
8934                         {
8935                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8936
8937                             if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8938                         }
8939                         else
8940                         {
8941                             if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8942                         }
8943
8944                     }
8945                     else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8946                     {
8947                         if (StatusText.Multiline)
8948                         {
8949                             if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8950
8951                             if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8952                         }
8953                         else
8954                         {
8955                             if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8956                         }
8957
8958                     }
8959                     else //Enter投稿時
8960                     {
8961                         if (StatusText.Multiline)
8962                         {
8963                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8964
8965                             if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8966                                 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8967                         }
8968                         else
8969                         {
8970                             if (((keyData & Keys.Shift) == Keys.Shift) ||
8971                                 (((keyData & Keys.Control) != Keys.Control) &&
8972                                 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8973                         }
8974                     }
8975
8976                     if (_NewLine)
8977                     {
8978                         int pos1 = StatusText.SelectionStart;
8979                         if (StatusText.SelectionLength > 0)
8980                         {
8981                             StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength);  //選択状態文字列削除
8982                         }
8983                         StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine);  //改行挿入
8984                         StatusText.SelectionStart = pos1 + Environment.NewLine.Length;    //カーソルを改行の次の文字へ移動
8985                         return true;
8986                     }
8987                     else if (_Post)
8988                     {
8989                         PostButton_Click(null, null);
8990                         return true;
8991                     }
8992                 }
8993                 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
8994                          (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
8995                          ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
8996                 {
8997                     this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
8998                     return true;
8999                 }
9000             }
9001
9002             return base.ProcessDialogKey(keyData);
9003         }
9004
9005         private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9006         {
9007             MakeReplyOrDirectStatus(false, true, true);
9008         }
9009
9010         private void IDRuleMenuItem_Click(object sender, EventArgs e)
9011         {
9012             string tabName;
9013
9014             //未選択なら処理終了
9015             if (_curList.SelectedIndices.Count == 0) return;
9016
9017             //タブ選択(or追加)
9018             if (!SelectTab(out tabName)) return;
9019
9020             var tab = this._statuses.Tabs[tabName];
9021
9022             bool mv;
9023             bool mk;
9024             if (tab.TabType != MyCommon.TabUsageType.Mute)
9025             {
9026                 this.MoveOrCopy(out mv, out mk);
9027             }
9028             else
9029             {
9030                 // ミュートタブでは常に MoveMatches を true にする
9031                 mv = true;
9032                 mk = false;
9033             }
9034
9035             List<string> ids = new List<string>();
9036             foreach (int idx in _curList.SelectedIndices)
9037             {
9038                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9039                 if (!ids.Contains(post.ScreenName))
9040                 {
9041                     PostFilterRule fc = new PostFilterRule();
9042                     ids.Add(post.ScreenName);
9043                     if (post.RetweetedId == null)
9044                     {
9045                         fc.FilterName = post.ScreenName;
9046                     }
9047                     else
9048                     {
9049                         fc.FilterName = post.RetweetedBy;
9050                     }
9051                     fc.UseNameField = true;
9052                     fc.MoveMatches = mv;
9053                     fc.MarkMatches = mk;
9054                     fc.UseRegex = false;
9055                     fc.FilterByUrl = false;
9056                     tab.AddFilter(fc);
9057                 }
9058             }
9059             if (ids.Count != 0)
9060             {
9061                 List<string> atids = new List<string>();
9062                 foreach (string id in ids)
9063                 {
9064                     atids.Add("@" + id);
9065                 }
9066                 int cnt = AtIdSupl.ItemCount;
9067                 AtIdSupl.AddRangeItem(atids.ToArray());
9068                 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
9069             }
9070
9071             this.ApplyPostFilters();
9072             SaveConfigsTabs();
9073         }
9074
9075         private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9076         {
9077             if (this._curList.SelectedIndices.Count == 0)
9078                 return;
9079
9080             // タブ選択ダイアログを表示(or追加)
9081             string tabName;
9082             if (!this.SelectTab(out tabName))
9083                 return;
9084
9085             var currentTab = this._statuses.Tabs[this._curTab.Text];
9086             var filterTab = this._statuses.Tabs[tabName];
9087
9088             bool mv;
9089             bool mk;
9090             if (filterTab.TabType != MyCommon.TabUsageType.Mute)
9091             {
9092                 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9093                 this.MoveOrCopy(out mv, out mk);
9094             }
9095             else
9096             {
9097                 // ミュートタブでは常に MoveMatches を true にする
9098                 mv = true;
9099                 mk = false;
9100             }
9101
9102             // 振り分けルールに追加するSource
9103             var sources = new HashSet<string>();
9104
9105             foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9106             {
9107                 var post = currentTab[idx];
9108                 var filterSource = post.Source;
9109
9110                 if (sources.Add(filterSource))
9111                 {
9112                     var filter = new PostFilterRule
9113                     {
9114                         FilterSource = filterSource,
9115                         MoveMatches = mv,
9116                         MarkMatches = mk,
9117                         UseRegex = false,
9118                         FilterByUrl = false,
9119                     };
9120                     filterTab.AddFilter(filter);
9121                 }
9122             }
9123
9124             this.ApplyPostFilters();
9125             this.SaveConfigsTabs();
9126         }
9127
9128         private bool SelectTab(out string tabName)
9129         {
9130             do
9131             {
9132                 tabName = null;
9133
9134                 //振り分け先タブ選択
9135                 using (var dialog = new TabsDialog(_statuses))
9136                 {
9137                     if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9138
9139                     var selectedTab = dialog.SelectedTab;
9140                     tabName = selectedTab == null ? null : selectedTab.TabName;
9141                 }
9142
9143                 ListTab.SelectedTab.Focus();
9144                 //新規タブを選択→タブ作成
9145                 if (tabName == null)
9146                 {
9147                     using (InputTabName inputName = new InputTabName())
9148                     {
9149                         inputName.TabName = _statuses.MakeTabName("MyTab");
9150                         inputName.ShowDialog();
9151                         if (inputName.DialogResult == DialogResult.Cancel) return false;
9152                         tabName = inputName.TabName;
9153                     }
9154                     this.TopMost = this._cfgCommon.AlwaysTop;
9155                     if (!string.IsNullOrEmpty(tabName))
9156                     {
9157                         if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9158                         {
9159                             string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9160                             MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9161                             //もう一度タブ名入力
9162                         }
9163                         else
9164                         {
9165                             return true;
9166                         }
9167                     }
9168                 }
9169                 else
9170                 {
9171                     //既存タブを選択
9172                     return true;
9173                 }
9174             }
9175             while (true);
9176         }
9177
9178         private void MoveOrCopy(out bool move, out bool mark)
9179         {
9180             {
9181                 //移動するか?
9182                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9183                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9184                     move = false;
9185                 else
9186                     move = true;
9187             }
9188             if (!move)
9189             {
9190                 //マークするか?
9191                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9192                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9193                     mark = true;
9194                 else
9195                     mark = false;
9196             }
9197             else
9198             {
9199                 mark = false;
9200             }
9201         }
9202         private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9203         {
9204             this.CopyStot();
9205         }
9206
9207         private void CopyURLMenuItem_Click(object sender, EventArgs e)
9208         {
9209             this.CopyIdUri();
9210         }
9211
9212         private void SelectAllMenuItem_Click(object sender, EventArgs e)
9213         {
9214             if (StatusText.Focused)
9215             {
9216                 // 発言欄でのCtrl+A
9217                 StatusText.SelectAll();
9218             }
9219             else
9220             {
9221                 // ListView上でのCtrl+A
9222                 NativeMethods.SelectAllItems(this._curList);
9223             }
9224         }
9225
9226         private void MoveMiddle()
9227         {
9228             ListViewItem _item;
9229             int idx1;
9230             int idx2;
9231
9232             if (_curList.SelectedIndices.Count == 0) return;
9233
9234             int idx = _curList.SelectedIndices[0];
9235
9236             _item = _curList.GetItemAt(0, 25);
9237             if (_item == null)
9238                 idx1 = 0;
9239             else
9240                 idx1 = _item.Index;
9241
9242             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9243             if (_item == null)
9244                 idx2 = _curList.VirtualListSize - 1;
9245             else
9246                 idx2 = _item.Index;
9247
9248             idx -= Math.Abs(idx1 - idx2) / 2;
9249             if (idx < 0) idx = 0;
9250
9251             _curList.EnsureVisible(_curList.VirtualListSize - 1);
9252             _curList.EnsureVisible(idx);
9253         }
9254
9255         private async void OpenURLMenuItem_Click(object sender, EventArgs e)
9256         {
9257             var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
9258                 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
9259                 .ToArray();
9260
9261             if (linkElements.Length > 0)
9262             {
9263                 UrlDialog.ClearUrl();
9264
9265                 string openUrlStr = "";
9266
9267                 if (linkElements.Length == 1)
9268                 {
9269                     // ツイートに含まれる URL が 1 つのみの場合
9270                     //   => OpenURL ダイアログを表示せずにリンクを開く
9271
9272                     string urlStr = "";
9273                     try
9274                     {
9275                         urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
9276                     }
9277                     catch (ArgumentException)
9278                     {
9279                         //変なHTML?
9280                         return;
9281                     }
9282                     catch (Exception)
9283                     {
9284                         return;
9285                     }
9286                     if (string.IsNullOrEmpty(urlStr)) return;
9287                     openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9288
9289                     // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
9290                     await this.OpenUriAsync(new Uri(openUrlStr));
9291                 }
9292                 else
9293                 {
9294                     // ツイートに含まれる URL が複数ある場合
9295                     //   => OpenURL を表示しユーザーが選択したリンクを開く
9296
9297                     foreach (var linkElm in linkElements)
9298                     {
9299                         string urlStr = "";
9300                         string linkText = "";
9301                         string href = "";
9302                         try
9303                         {
9304                             urlStr = linkElm.GetAttribute("title");
9305                             href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9306                             if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9307                             linkText = linkElm.InnerText;
9308                         }
9309                         catch (ArgumentException)
9310                         {
9311                             //変なHTML?
9312                             return;
9313                         }
9314                         catch (Exception)
9315                         {
9316                             return;
9317                         }
9318                         if (string.IsNullOrEmpty(urlStr)) continue;
9319                         UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9320                     }
9321                     try
9322                     {
9323                         if (UrlDialog.ShowDialog() == DialogResult.OK)
9324                         {
9325                             openUrlStr = UrlDialog.SelectedUrl;
9326
9327                             // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
9328                             await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
9329                         }
9330                     }
9331                     catch (Exception)
9332                     {
9333                         return;
9334                     }
9335                     this.TopMost = this._cfgCommon.AlwaysTop;
9336                 }
9337             }
9338         }
9339
9340         private void ClearTabMenuItem_Click(object sender, EventArgs e)
9341         {
9342             if (string.IsNullOrEmpty(_rclickTabName)) return;
9343             ClearTab(_rclickTabName, true);
9344         }
9345
9346         private void ClearTab(string tabName, bool showWarning)
9347         {
9348             if (showWarning)
9349             {
9350                 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9351                 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9352                 {
9353                     return;
9354                 }
9355             }
9356
9357             _statuses.ClearTabIds(tabName);
9358             if (ListTab.SelectedTab.Text == tabName)
9359             {
9360                 _anchorPost = null;
9361                 _anchorFlag = false;
9362                 this.PurgeListViewItemCache();
9363                 _curItemIndex = -1;
9364                 _curPost = null;
9365             }
9366             foreach (TabPage tb in ListTab.TabPages)
9367             {
9368                 if (tb.Text == tabName)
9369                 {
9370                     tb.ImageIndex = -1;
9371                     ((DetailsListView)tb.Tag).VirtualListSize = 0;
9372                     break;
9373                 }
9374             }
9375             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9376
9377             SetMainWindowTitle();
9378             SetStatusLabelUrl();
9379         }
9380
9381         private static long followers = 0;
9382
9383         private void SetMainWindowTitle()
9384         {
9385             //メインウインドウタイトルの書き換え
9386             StringBuilder ttl = new StringBuilder(256);
9387             int ur = 0;
9388             int al = 0;
9389             if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9390                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9391                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9392                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9393             {
9394                 foreach (var tab in _statuses.Tabs.Values)
9395                 {
9396                     ur += tab.UnreadCount;
9397                     al += tab.AllCount;
9398                 }
9399             }
9400
9401             if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9402             ttl.Append(Application.ProductName);
9403             ttl.Append("  ");
9404             switch (this._cfgCommon.DispLatestPost)
9405             {
9406                 case MyCommon.DispTitleEnum.Ver:
9407                     ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9408                     break;
9409                 case MyCommon.DispTitleEnum.Post:
9410                     if (_history != null && _history.Count > 1)
9411                         ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9412                     break;
9413                 case MyCommon.DispTitleEnum.UnreadRepCount:
9414                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9415                     break;
9416                 case MyCommon.DispTitleEnum.UnreadAllCount:
9417                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9418                     break;
9419                 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9420                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9421                     break;
9422                 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9423                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9424                     break;
9425                 case MyCommon.DispTitleEnum.OwnStatus:
9426                     if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9427                     ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9428                     break;
9429             }
9430
9431             try
9432             {
9433                 this.Text = ttl.ToString();
9434             }
9435             catch (AccessViolationException)
9436             {
9437                 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9438             }
9439         }
9440
9441         private string GetStatusLabelText()
9442         {
9443             //ステータス欄にカウント表示
9444             //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9445             if (_statuses == null) return "";
9446             TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9447             TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9448             if (tbRep == null || tbDm == null) return "";
9449             int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9450             int ur = 0;
9451             int al = 0;
9452             int tur = 0;
9453             int tal = 0;
9454             StringBuilder slbl = new StringBuilder(256);
9455             try
9456             {
9457                 foreach (var tab in _statuses.Tabs.Values)
9458                 {
9459                     ur += tab.UnreadCount;
9460                     al += tab.AllCount;
9461                     if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9462                     {
9463                         tur = tab.UnreadCount;
9464                         tal = tab.AllCount;
9465                     }
9466                 }
9467             }
9468             catch (Exception)
9469             {
9470                 return "";
9471             }
9472
9473             UnreadCounter = ur;
9474             UnreadAtCounter = urat;
9475
9476             slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9477             if (this._cfgCommon.TimelinePeriod == 0)
9478             {
9479                 slbl.Append(Properties.Resources.SetStatusLabelText2);
9480             }
9481             else
9482             {
9483                 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9484             }
9485             return slbl.ToString();
9486         }
9487
9488         private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9489         {
9490             try
9491             {
9492                 if (this.InvokeRequired && !this.IsDisposed)
9493                 {
9494                     await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
9495                 }
9496                 else
9497                 {
9498                     var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9499                     SetApiStatusLabel(endpointName);
9500                 }
9501             }
9502             catch (ObjectDisposedException)
9503             {
9504                 return;
9505             }
9506             catch (InvalidOperationException)
9507             {
9508                 return;
9509             }
9510         }
9511
9512         private void SetApiStatusLabel(string endpointName = null)
9513         {
9514             if (_curTab == null)
9515             {
9516                 this.toolStripApiGauge.ApiEndpoint = null;
9517             }
9518             else
9519             {
9520                 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9521
9522                 if (endpointName == null)
9523                 {
9524                     // 表示中のタブに応じて更新
9525                     switch (tabType)
9526                     {
9527                         case MyCommon.TabUsageType.Home:
9528                         case MyCommon.TabUsageType.UserDefined:
9529                             endpointName = "/statuses/home_timeline";
9530                             break;
9531
9532                         case MyCommon.TabUsageType.Mentions:
9533                             endpointName = "/statuses/mentions_timeline";
9534                             break;
9535
9536                         case MyCommon.TabUsageType.Favorites:
9537                             endpointName = "/favorites/list";
9538                             break;
9539
9540                         case MyCommon.TabUsageType.DirectMessage:
9541                             endpointName = "/direct_messages";
9542                             break;
9543
9544                         case MyCommon.TabUsageType.UserTimeline:
9545                             endpointName = "/statuses/user_timeline";
9546                             break;
9547
9548                         case MyCommon.TabUsageType.Lists:
9549                             endpointName = "/lists/statuses";
9550                             break;
9551
9552                         case MyCommon.TabUsageType.PublicSearch:
9553                             endpointName = "/search/tweets";
9554                             break;
9555
9556                         case MyCommon.TabUsageType.Related:
9557                             endpointName = "/statuses/show/:id";
9558                             break;
9559
9560                         default:
9561                             break;
9562                     }
9563
9564                     this.toolStripApiGauge.ApiEndpoint = endpointName;
9565                 }
9566                 else
9567                 {
9568                     // 表示中のタブに関連する endpoint であれば更新
9569                     var update = false;
9570
9571                     switch (endpointName)
9572                     {
9573                         case "/statuses/home_timeline":
9574                             update = tabType == MyCommon.TabUsageType.Home ||
9575                                      tabType == MyCommon.TabUsageType.UserDefined;
9576                             break;
9577
9578                         case "/statuses/mentions_timeline":
9579                             update = tabType == MyCommon.TabUsageType.Mentions;
9580                             break;
9581
9582                         case "/favorites/list":
9583                             update = tabType == MyCommon.TabUsageType.Favorites;
9584                             break;
9585
9586                         case "/direct_messages:":
9587                             update = tabType == MyCommon.TabUsageType.DirectMessage;
9588                             break;
9589
9590                         case "/statuses/user_timeline":
9591                             update = tabType == MyCommon.TabUsageType.UserTimeline;
9592                             break;
9593
9594                         case "/lists/statuses":
9595                             update = tabType == MyCommon.TabUsageType.Lists;
9596                             break;
9597
9598                         case "/search/tweets":
9599                             update = tabType == MyCommon.TabUsageType.PublicSearch;
9600                             break;
9601
9602                         case "/statuses/show/:id":
9603                             update = tabType == MyCommon.TabUsageType.Related;
9604                             break;
9605
9606                         default:
9607                             break;
9608                     }
9609
9610                     if (update)
9611                     {
9612                         this.toolStripApiGauge.ApiEndpoint = endpointName;
9613                     }
9614                 }
9615             }
9616         }
9617
9618         private void SetStatusLabelUrl()
9619         {
9620             StatusLabelUrl.Text = GetStatusLabelText();
9621         }
9622
9623         public void SetStatusLabel(string text)
9624         {
9625             StatusLabel.Text = text;
9626         }
9627
9628         private static StringBuilder ur = new StringBuilder(64);
9629
9630         private void SetNotifyIconText()
9631         {
9632             // タスクトレイアイコンのツールチップテキスト書き換え
9633             // Tween [未読/@]
9634             ur.Remove(0, ur.Length);
9635             if (this._cfgCommon.DispUsername)
9636             {
9637                 ur.Append(tw.Username);
9638                 ur.Append(" - ");
9639             }
9640             ur.Append(Application.ProductName);
9641 #if DEBUG
9642             ur.Append("(Debug Build)");
9643 #endif
9644             if (UnreadCounter != -1 && UnreadAtCounter != -1)
9645             {
9646                 ur.Append(" [");
9647                 ur.Append(UnreadCounter);
9648                 ur.Append("/@");
9649                 ur.Append(UnreadAtCounter);
9650                 ur.Append("]");
9651             }
9652             NotifyIcon1.Text = ur.ToString();
9653         }
9654
9655         internal void CheckReplyTo(string StatusText)
9656         {
9657             MatchCollection m;
9658             //ハッシュタグの保存
9659             m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9660             string hstr = "";
9661             foreach (Match hm in m)
9662             {
9663                 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9664                 {
9665                     hstr += "#" + hm.Result("$3") + " ";
9666                     HashSupl.AddItem("#" + hm.Result("$3"));
9667                 }
9668             }
9669             if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9670             {
9671                 hstr += HashMgr.UseHash;
9672             }
9673             if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9674
9675             // 本当にリプライ先指定すべきかどうかの判定
9676             m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9677
9678             if (this._cfgCommon.UseAtIdSupplement)
9679             {
9680                 int bCnt = AtIdSupl.ItemCount;
9681                 foreach (Match mid in m)
9682                 {
9683                     AtIdSupl.AddItem(mid.Result("${id}"));
9684                 }
9685                 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9686             }
9687
9688             // リプライ先ステータスIDの指定がない場合は指定しない
9689             if (this.inReplyTo == null)
9690                 return;
9691
9692             // 通常Reply
9693             // 次の条件を満たす場合に in_reply_to_status_id 指定
9694             // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9695             // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9696             // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9697
9698             if (m != null)
9699             {
9700                 var inReplyToScreenName = this.inReplyTo.Item2;
9701                 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9702                 {
9703                     if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9704                 }
9705                 else
9706                 {
9707                     foreach (Match mid in m)
9708                     {
9709                         if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9710                     }
9711                 }
9712             }
9713
9714             this.inReplyTo = null;
9715         }
9716
9717         private void TweenMain_Resize(object sender, EventArgs e)
9718         {
9719             if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9720             {
9721                 this.Visible = false;
9722             }
9723             if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9724             {
9725                 // 現在の DPI と設定保存時の DPI との比を取得する
9726                 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9727
9728                 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9729                 //_mySize = this.ClientSize;                     //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9730                 this.DesktopLocation = _cfgLocal.FormLocation;
9731                 //_myLoc = this.DesktopLocation;                        //位置保持(最小化・最大化されたまま終了した場合の対応用)
9732
9733                 // Splitterの位置設定
9734                 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9735                 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9736                     splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9737                 {
9738                     this.SplitContainer1.SplitterDistance = splitterDistance;
9739                 }
9740
9741                 //発言欄複数行
9742                 StatusText.Multiline = _cfgLocal.StatusMultiline;
9743                 if (StatusText.Multiline)
9744                 {
9745                     var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9746                     int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9747                     if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9748                     {
9749                         SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9750                     }
9751                     StatusText.Height = statusTextHeight;
9752                 }
9753                 else
9754                 {
9755                     if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9756                     {
9757                         SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9758                     }
9759                 }
9760
9761                 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9762                 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9763                 {
9764                     this.SplitContainer3.SplitterDistance = previewDistance;
9765                 }
9766
9767                 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9768                 this.SplitContainer3.Panel2Collapsed = true;
9769
9770                 _initialLayout = false;
9771             }
9772             if (this.WindowState != FormWindowState.Minimized)
9773             {
9774                 _formWindowState = this.WindowState;
9775             }
9776         }
9777
9778         private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9779         {
9780             PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9781             this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9782             if (PlaySoundMenuItem.Checked)
9783             {
9784                 this._cfgCommon.PlaySound = true;
9785             }
9786             else
9787             {
9788                 this._cfgCommon.PlaySound = false;
9789             }
9790             ModifySettingCommon = true;
9791         }
9792
9793         private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9794         {
9795             if (this._initialLayout)
9796                 return;
9797
9798             int splitterDistance;
9799             switch (this.WindowState)
9800             {
9801                 case FormWindowState.Normal:
9802                     splitterDistance = this.SplitContainer1.SplitterDistance;
9803                     break;
9804                 case FormWindowState.Maximized:
9805                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9806                     var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9807                     splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9808                     splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9809                     break;
9810                 default:
9811                     return;
9812             }
9813
9814             this._mySpDis = splitterDistance;
9815             this.ModifySettingLocal = true;
9816         }
9817
9818         private async Task doRepliedStatusOpen()
9819         {
9820             if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9821             {
9822                 if (MyCommon.IsKeyDown(Keys.Shift))
9823                 {
9824                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9825                     return;
9826                 }
9827                 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9828                 {
9829                     PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9830                     MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9831                 }
9832                 else
9833                 {
9834                     foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9835                     {
9836                         if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9837                         PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9838                         MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9839                         return;
9840                     }
9841                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9842                 }
9843             }
9844         }
9845
9846         private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9847         {
9848             await this.doRepliedStatusOpen();
9849         }
9850
9851         /// <summary>
9852         /// UserPicture.Image に設定されている画像を破棄します。
9853         /// </summary>
9854         private void ClearUserPicture()
9855         {
9856             if (this.UserPicture.Image != null)
9857             {
9858                 var oldImage = this.UserPicture.Image;
9859                 this.UserPicture.Image = null;
9860                 oldImage.Dispose();
9861             }
9862         }
9863
9864         private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9865         {
9866             //発言詳細のアイコン右クリック時のメニュー制御
9867             if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9868             {
9869                 string name = _curPost.ImageUrl;
9870                 if (name != null && name.Length > 0)
9871                 {
9872                     int idx = name.LastIndexOf('/');
9873                     if (idx != -1)
9874                     {
9875                         name = Path.GetFileName(name.Substring(idx));
9876                         if (name.Contains("_normal.") || name.EndsWith("_normal", StringComparison.Ordinal))
9877                         {
9878                             name = name.Replace("_normal", "");
9879                             this.IconNameToolStripMenuItem.Text = name;
9880                             this.IconNameToolStripMenuItem.Enabled = true;
9881                         }
9882                         else
9883                         {
9884                             this.IconNameToolStripMenuItem.Enabled = false;
9885                             this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9886                         }
9887                     }
9888                     else
9889                     {
9890                         this.IconNameToolStripMenuItem.Enabled = false;
9891                         this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9892                     }
9893
9894                     this.ReloadIconToolStripMenuItem.Enabled = true;
9895
9896                     if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9897                     {
9898                         this.SaveIconPictureToolStripMenuItem.Enabled = true;
9899                     }
9900                     else
9901                     {
9902                         this.SaveIconPictureToolStripMenuItem.Enabled = false;
9903                     }
9904                 }
9905                 else
9906                 {
9907                     this.IconNameToolStripMenuItem.Enabled = false;
9908                     this.ReloadIconToolStripMenuItem.Enabled = false;
9909                     this.SaveIconPictureToolStripMenuItem.Enabled = false;
9910                     this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9911                 }
9912             }
9913             else
9914             {
9915                 this.IconNameToolStripMenuItem.Enabled = false;
9916                 this.ReloadIconToolStripMenuItem.Enabled = false;
9917                 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9918                 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9919             }
9920             if (NameLabel.Tag != null)
9921             {
9922                 string id = (string)NameLabel.Tag;
9923                 if (id == tw.Username)
9924                 {
9925                     FollowToolStripMenuItem.Enabled = false;
9926                     UnFollowToolStripMenuItem.Enabled = false;
9927                     ShowFriendShipToolStripMenuItem.Enabled = false;
9928                     ShowUserStatusToolStripMenuItem.Enabled = true;
9929                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9930                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9931                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9932                 }
9933                 else
9934                 {
9935                     FollowToolStripMenuItem.Enabled = true;
9936                     UnFollowToolStripMenuItem.Enabled = true;
9937                     ShowFriendShipToolStripMenuItem.Enabled = true;
9938                     ShowUserStatusToolStripMenuItem.Enabled = true;
9939                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9940                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9941                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9942                 }
9943             }
9944             else
9945             {
9946                 FollowToolStripMenuItem.Enabled = false;
9947                 UnFollowToolStripMenuItem.Enabled = false;
9948                 ShowFriendShipToolStripMenuItem.Enabled = false;
9949                 ShowUserStatusToolStripMenuItem.Enabled = false;
9950                 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9951                 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9952                 ListManageUserContextToolStripMenuItem3.Enabled = false;
9953             }
9954         }
9955
9956         private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9957         {
9958             if (_curPost == null) return;
9959             string name = _curPost.ImageUrl;
9960             await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9961         }
9962
9963         private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9964         {
9965             if (this._curPost == null) return;
9966
9967             await this.UserPicture.SetImageFromTask(async () =>
9968             {
9969                 var imageUrl = this._curPost.ImageUrl;
9970
9971                 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
9972                     .ConfigureAwait(false);
9973
9974                 return await image.CloneAsync()
9975                     .ConfigureAwait(false);
9976             });
9977         }
9978
9979         private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9980         {
9981             if (_curPost == null) return;
9982             string name = _curPost.ImageUrl;
9983             name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
9984
9985             this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
9986
9987             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
9988             {
9989                 // STUB
9990             }
9991         }
9992
9993         private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9994         {
9995             if (_curPost == null) return;
9996             string name = _curPost.ImageUrl;
9997
9998             this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
9999
10000             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10001             {
10002                 try
10003                 {
10004                     using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10005                     {
10006                         using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10007                         {
10008                             using (Graphics g = Graphics.FromImage(bmp2))
10009                             {
10010                                 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10011                                 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10012                             }
10013                             bmp2.Save(this.SaveFileDialog1.FileName);
10014                         }
10015                     }
10016                 }
10017                 catch (Exception)
10018                 {
10019                     //処理中にキャッシュアウトする可能性あり
10020                 }
10021             }
10022         }
10023
10024         private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10025         {
10026             var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10027             if (multiline != this.StatusText.Multiline)
10028             {
10029                 this.StatusText.Multiline = multiline;
10030                 MultiLineMenuItem.Checked = multiline;
10031                 ModifySettingLocal = true;
10032             }
10033         }
10034
10035         private void StatusText_MultilineChanged(object sender, EventArgs e)
10036         {
10037             if (this.StatusText.Multiline)
10038                 this.StatusText.ScrollBars = ScrollBars.Vertical;
10039             else
10040                 this.StatusText.ScrollBars = ScrollBars.None;
10041
10042             ModifySettingLocal = true;
10043         }
10044
10045         private void MultiLineMenuItem_Click(object sender, EventArgs e)
10046         {
10047             //発言欄複数行
10048             StatusText.Multiline = MultiLineMenuItem.Checked;
10049             _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10050             if (MultiLineMenuItem.Checked)
10051             {
10052                 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10053                     SplitContainer2.SplitterDistance = 0;
10054                 else
10055                     SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10056             }
10057             else
10058             {
10059                 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10060             }
10061             ModifySettingLocal = true;
10062         }
10063
10064         private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10065         {
10066             //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10067             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10068
10069             //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10070             //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10071             //Appendix A.  Collected ABNF for URI
10072             //http://www.ietf.org/rfc/rfc3986.txt
10073
10074             string result = "";
10075
10076             const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10077
10078             if (StatusText.SelectionLength > 0)
10079             {
10080                 string tmp = StatusText.SelectedText;
10081                 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10082                 if (tmp.StartsWith("http"))
10083                 {
10084                     // 文字列が選択されている場合はその文字列について処理
10085
10086                     //nico.ms使用、nicovideoにマッチしたら変換
10087                     if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10088                     {
10089                         result = nicoms.Shorten(tmp);
10090                     }
10091                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10092                     {
10093                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10094                         try
10095                         {
10096                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10097                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10098                             result = resultUri.AbsoluteUri;
10099                         }
10100                         catch (WebApiException e)
10101                         {
10102                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10103                             return false;
10104                         }
10105                         catch (UriFormatException e)
10106                         {
10107                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10108                             return false;
10109                         }
10110                     }
10111                     else
10112                     {
10113                         return true;
10114                     }
10115
10116                     if (!string.IsNullOrEmpty(result))
10117                     {
10118                         urlUndo undotmp = new urlUndo();
10119
10120                         StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10121                         StatusText.SelectedText = result;
10122
10123                         //undoバッファにセット
10124                         undotmp.Before = tmp;
10125                         undotmp.After = result;
10126
10127                         if (urlUndoBuffer == null)
10128                         {
10129                             urlUndoBuffer = new List<urlUndo>();
10130                             UrlUndoToolStripMenuItem.Enabled = true;
10131                         }
10132
10133                         urlUndoBuffer.Add(undotmp);
10134                     }
10135                 }
10136             }
10137             else
10138             {
10139                 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10140                                    @"(?<url>(?<protocol>https?://)" +
10141                                    @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10142                                    @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10143                                    @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10144                 // 正規表現にマッチしたURL文字列をtinyurl化
10145                 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10146                 {
10147                     if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10148                     string tmp = mt.Result("${url}");
10149                     if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10150                     urlUndo undotmp = new urlUndo();
10151
10152                     //選んだURLを選択(?)
10153                     StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10154
10155                     //nico.ms使用、nicovideoにマッチしたら変換
10156                     if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10157                     {
10158                         result = nicoms.Shorten(tmp);
10159                     }
10160                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10161                     {
10162                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10163                         try
10164                         {
10165                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10166                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10167                             result = resultUri.AbsoluteUri;
10168                         }
10169                         catch (HttpRequestException e)
10170                         {
10171                             // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10172                             // のように長いので「:」が含まれていればそれ以降のみを抽出する
10173                             var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10174
10175                             this.StatusLabel.Text = Converter_Type + ":" + message;
10176                             continue;
10177                         }
10178                         catch (WebApiException e)
10179                         {
10180                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10181                             continue;
10182                         }
10183                         catch (UriFormatException e)
10184                         {
10185                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10186                             continue;
10187                         }
10188                     }
10189                     else
10190                     {
10191                         continue;
10192                     }
10193
10194                     if (!string.IsNullOrEmpty(result))
10195                     {
10196                         StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10197                         StatusText.SelectedText = result;
10198                         //undoバッファにセット
10199                         undotmp.Before = mt.Result("${url}");
10200                         undotmp.After = result;
10201
10202                         if (urlUndoBuffer == null)
10203                         {
10204                             urlUndoBuffer = new List<urlUndo>();
10205                             UrlUndoToolStripMenuItem.Enabled = true;
10206                         }
10207
10208                         urlUndoBuffer.Add(undotmp);
10209                     }
10210                 }
10211             }
10212
10213             return true;
10214         }
10215
10216         private void doUrlUndo()
10217         {
10218             if (urlUndoBuffer != null)
10219             {
10220                 string tmp = StatusText.Text;
10221                 foreach (urlUndo data in urlUndoBuffer)
10222                 {
10223                     tmp = tmp.Replace(data.After, data.Before);
10224                 }
10225                 StatusText.Text = tmp;
10226                 urlUndoBuffer = null;
10227                 UrlUndoToolStripMenuItem.Enabled = false;
10228                 StatusText.SelectionStart = 0;
10229                 StatusText.SelectionLength = 0;
10230             }
10231         }
10232
10233         private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10234         {
10235             await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10236         }
10237
10238         private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10239         {
10240             await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10241         }
10242
10243         private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10244         {
10245             await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10246         }
10247
10248         private async void UxnuMenuItem_Click(object sender, EventArgs e)
10249         {
10250             await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10251         }
10252
10253         private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10254         {
10255             if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10256             {
10257                 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10258                 Random rnd = new Random();
10259                 // 前回使用した短縮URLサービス以外を選択する
10260                 do
10261                 {
10262                     svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10263                 }
10264                 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10265                 await UrlConvertAsync(svc);
10266             }
10267         }
10268
10269         private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10270         {
10271             doUrlUndo();
10272         }
10273
10274         private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10275         {
10276             this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10277             this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10278             _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10279             ModifySettingCommon = true;
10280         }
10281
10282         private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10283         {
10284             ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10285             this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10286             _cfgCommon.ListLock = ListLockMenuItem.Checked;
10287             ModifySettingCommon = true;
10288         }
10289
10290         private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10291         {
10292             // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10293             MenuStrip1.Tag = new Object();
10294             MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10295         }
10296
10297         private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10298         {
10299             if (this.Tag != null) // 設定された戻り先へ遷移
10300             {
10301                 if (this.Tag == this.ListTab.SelectedTab)
10302                     ((Control)this.ListTab.SelectedTab.Tag).Select();
10303                 else
10304                     ((Control)this.Tag).Select();
10305             }
10306             else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10307             {
10308                 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10309                 {
10310                     this.Tag = ListTab.SelectedTab.Tag;
10311                     ((Control)this.Tag).Select();
10312                 }
10313             }
10314             // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10315             MenuStrip1.Tag = null;
10316         }
10317
10318         private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10319         {
10320             DetailsListView lst = (DetailsListView)sender;
10321             if (_cfgLocal == null) return;
10322
10323             if (_iconCol)
10324             {
10325                 _cfgLocal.Width1 = lst.Columns[0].Width;
10326                 _cfgLocal.Width3 = lst.Columns[1].Width;
10327             }
10328             else
10329             {
10330                 int[] darr = new int[lst.Columns.Count];
10331                 for (int i = 0; i < lst.Columns.Count; i++)
10332                 {
10333                     darr[lst.Columns[i].DisplayIndex] = i;
10334                 }
10335                 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10336
10337                 for (int i = 0; i < lst.Columns.Count; i++)
10338                 {
10339                     switch (darr[i])
10340                     {
10341                         case 0:
10342                             _cfgLocal.DisplayIndex1 = i;
10343                             break;
10344                         case 1:
10345                             _cfgLocal.DisplayIndex2 = i;
10346                             break;
10347                         case 2:
10348                             _cfgLocal.DisplayIndex3 = i;
10349                             break;
10350                         case 3:
10351                             _cfgLocal.DisplayIndex4 = i;
10352                             break;
10353                         case 4:
10354                             _cfgLocal.DisplayIndex5 = i;
10355                             break;
10356                         case 5:
10357                             _cfgLocal.DisplayIndex6 = i;
10358                             break;
10359                         case 6:
10360                             _cfgLocal.DisplayIndex7 = i;
10361                             break;
10362                         case 7:
10363                             _cfgLocal.DisplayIndex8 = i;
10364                             break;
10365                     }
10366                 }
10367                 _cfgLocal.Width1 = lst.Columns[0].Width;
10368                 _cfgLocal.Width2 = lst.Columns[1].Width;
10369                 _cfgLocal.Width3 = lst.Columns[2].Width;
10370                 _cfgLocal.Width4 = lst.Columns[3].Width;
10371                 _cfgLocal.Width5 = lst.Columns[4].Width;
10372                 _cfgLocal.Width6 = lst.Columns[5].Width;
10373                 _cfgLocal.Width7 = lst.Columns[6].Width;
10374                 _cfgLocal.Width8 = lst.Columns[7].Width;
10375             }
10376             ModifySettingLocal = true;
10377             _isColumnChanged = true;
10378         }
10379
10380         private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10381         {
10382             DetailsListView lst = (DetailsListView)sender;
10383             if (_cfgLocal == null) return;
10384             if (_iconCol)
10385             {
10386                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10387                 {
10388                     _cfgLocal.Width1 = lst.Columns[0].Width;
10389                     ModifySettingLocal = true;
10390                     _isColumnChanged = true;
10391                 }
10392                 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10393                 {
10394                     _cfgLocal.Width3 = lst.Columns[1].Width;
10395                     ModifySettingLocal = true;
10396                     _isColumnChanged = true;
10397                 }
10398             }
10399             else
10400             {
10401                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10402                 {
10403                     _cfgLocal.Width1 = lst.Columns[0].Width;
10404                     ModifySettingLocal = true;
10405                     _isColumnChanged = true;
10406                 }
10407                 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10408                 {
10409                     _cfgLocal.Width2 = lst.Columns[1].Width;
10410                     ModifySettingLocal = true;
10411                     _isColumnChanged = true;
10412                 }
10413                 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10414                 {
10415                     _cfgLocal.Width3 = lst.Columns[2].Width;
10416                     ModifySettingLocal = true;
10417                     _isColumnChanged = true;
10418                 }
10419                 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10420                 {
10421                     _cfgLocal.Width4 = lst.Columns[3].Width;
10422                     ModifySettingLocal = true;
10423                     _isColumnChanged = true;
10424                 }
10425                 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10426                 {
10427                     _cfgLocal.Width5 = lst.Columns[4].Width;
10428                     ModifySettingLocal = true;
10429                     _isColumnChanged = true;
10430                 }
10431                 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10432                 {
10433                     _cfgLocal.Width6 = lst.Columns[5].Width;
10434                     ModifySettingLocal = true;
10435                     _isColumnChanged = true;
10436                 }
10437                 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10438                 {
10439                     _cfgLocal.Width7 = lst.Columns[6].Width;
10440                     ModifySettingLocal = true;
10441                     _isColumnChanged = true;
10442                 }
10443                 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10444                 {
10445                     _cfgLocal.Width8 = lst.Columns[7].Width;
10446                     ModifySettingLocal = true;
10447                     _isColumnChanged = true;
10448                 }
10449             }
10450             // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10451             //if (changed)
10452             //{
10453             //    SaveConfigsLocal();
10454             //}
10455         }
10456
10457         private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10458         {
10459             //発言詳細で「選択文字列をコピー」
10460             string _selText = this.PostBrowser.GetSelectedText();
10461             try
10462             {
10463                 Clipboard.SetDataObject(_selText, false, 5, 100);
10464             }
10465             catch (Exception ex)
10466             {
10467                 MessageBox.Show(ex.Message);
10468             }
10469         }
10470
10471         private async Task doSearchToolStrip(string url)
10472         {
10473             //発言詳細で「選択文字列で検索」(選択文字列取得)
10474             string _selText = this.PostBrowser.GetSelectedText();
10475
10476             if (_selText != null)
10477             {
10478                 if (url == Properties.Resources.SearchItem4Url)
10479                 {
10480                     //公式検索
10481                     AddNewTabForSearch(_selText);
10482                     return;
10483                 }
10484
10485                 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10486                 await this.OpenUriInBrowserAsync(tmp);
10487             }
10488         }
10489
10490         private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10491         {
10492             //発言詳細ですべて選択
10493             PostBrowser.Document.ExecCommand("SelectAll", false, null);
10494         }
10495
10496         private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10497         {
10498             await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10499         }
10500
10501         private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10502         {
10503             await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10504         }
10505
10506         private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10507         {
10508             await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10509         }
10510
10511         private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10512         {
10513             try
10514             {
10515                 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
10516                 {
10517                     if (link.GetAttribute("href") == this._postBrowserStatusText)
10518                     {
10519                         var linkStr = link.GetAttribute("title");
10520                         if (string.IsNullOrEmpty(linkStr))
10521                             linkStr = link.GetAttribute("href");
10522
10523                         Clipboard.SetDataObject(linkStr, false, 5, 100);
10524                         return;
10525                     }
10526                 }
10527
10528                 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10529             }
10530             catch (Exception ex)
10531             {
10532                 MessageBox.Show(ex.Message);
10533             }
10534         }
10535
10536         private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10537         {
10538             // URLコピーの項目の表示/非表示
10539             if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal))
10540             {
10541                 this._postBrowserStatusText = PostBrowser.StatusText;
10542                 string name = GetUserId();
10543                 UrlCopyContextMenuItem.Enabled = true;
10544                 if (name != null)
10545                 {
10546                     FollowContextMenuItem.Enabled = true;
10547                     RemoveContextMenuItem.Enabled = true;
10548                     FriendshipContextMenuItem.Enabled = true;
10549                     ShowUserStatusContextMenuItem.Enabled = true;
10550                     SearchPostsDetailToolStripMenuItem.Enabled = true;
10551                     IdFilterAddMenuItem.Enabled = true;
10552                     ListManageUserContextToolStripMenuItem.Enabled = true;
10553                     SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10554                 }
10555                 else
10556                 {
10557                     FollowContextMenuItem.Enabled = false;
10558                     RemoveContextMenuItem.Enabled = false;
10559                     FriendshipContextMenuItem.Enabled = false;
10560                     ShowUserStatusContextMenuItem.Enabled = false;
10561                     SearchPostsDetailToolStripMenuItem.Enabled = false;
10562                     IdFilterAddMenuItem.Enabled = false;
10563                     ListManageUserContextToolStripMenuItem.Enabled = false;
10564                     SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10565                 }
10566
10567                 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10568                     UseHashtagMenuItem.Enabled = true;
10569                 else
10570                     UseHashtagMenuItem.Enabled = false;
10571             }
10572             else
10573             {
10574                 this._postBrowserStatusText = "";
10575                 UrlCopyContextMenuItem.Enabled = false;
10576                 FollowContextMenuItem.Enabled = false;
10577                 RemoveContextMenuItem.Enabled = false;
10578                 FriendshipContextMenuItem.Enabled = false;
10579                 ShowUserStatusContextMenuItem.Enabled = false;
10580                 SearchPostsDetailToolStripMenuItem.Enabled = false;
10581                 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10582                 UseHashtagMenuItem.Enabled = false;
10583                 IdFilterAddMenuItem.Enabled = false;
10584                 ListManageUserContextToolStripMenuItem.Enabled = false;
10585             }
10586             // 文字列選択されていないときは選択文字列関係の項目を非表示に
10587             string _selText = this.PostBrowser.GetSelectedText();
10588             if (_selText == null)
10589             {
10590                 SelectionSearchContextMenuItem.Enabled = false;
10591                 SelectionCopyContextMenuItem.Enabled = false;
10592                 SelectionTranslationToolStripMenuItem.Enabled = false;
10593             }
10594             else
10595             {
10596                 SelectionSearchContextMenuItem.Enabled = true;
10597                 SelectionCopyContextMenuItem.Enabled = true;
10598                 SelectionTranslationToolStripMenuItem.Enabled = true;
10599             }
10600             //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10601             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10602             bool fAllFlag = false;
10603             foreach (Match mu in ma)
10604             {
10605                 if (mu.Result("${ScreenName}").ToLowerInvariant() != tw.Username.ToLowerInvariant())
10606                 {
10607                     fAllFlag = true;
10608                     break;
10609                 }
10610             }
10611             this.FriendshipAllMenuItem.Enabled = fAllFlag;
10612
10613             if (_curPost == null)
10614                 TranslationToolStripMenuItem.Enabled = false;
10615             else
10616                 TranslationToolStripMenuItem.Enabled = true;
10617
10618             e.Cancel = false;
10619         }
10620
10621         private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10622         {
10623             //発言詳細の選択文字列で現在のタブを検索
10624             string _selText = this.PostBrowser.GetSelectedText();
10625
10626             if (_selText != null)
10627             {
10628                 var searchOptions = new SearchWordDialog.SearchOptions(
10629                     SearchWordDialog.SearchType.Timeline,
10630                     _selText,
10631                     newTab: false,
10632                     caseSensitive: false,
10633                     useRegex: false);
10634
10635                 this.SearchDialog.ResultOptions = searchOptions;
10636
10637                 this.DoTabSearch(
10638                     searchOptions.Query,
10639                     searchOptions.CaseSensitive,
10640                     searchOptions.UseRegex,
10641                     SEARCHTYPE.NextSearch);
10642             }
10643         }
10644
10645         private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10646         {
10647             if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10648             ModifySettingLocal = true;
10649         }
10650
10651         private void TweenMain_DragDrop(object sender, DragEventArgs e)
10652         {
10653             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10654             {
10655                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10656                 {
10657                     SelectMedia_DragDrop(e);
10658                 }
10659             }
10660             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10661             {
10662                 var url = GetUrlFromDataObject(e.Data);
10663
10664                 string appendText;
10665                 if (url.Item2 == null)
10666                     appendText = url.Item1;
10667                 else
10668                     appendText = url.Item2 + " " + url.Item1;
10669
10670                 if (this.StatusText.TextLength == 0)
10671                     this.StatusText.Text = appendText;
10672                 else
10673                     this.StatusText.Text += " " + appendText;
10674             }
10675             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10676             {
10677                 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10678                 if (text != null)
10679                     this.StatusText.Text += text;
10680             }
10681             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10682             {
10683                 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10684                 if (data != null) StatusText.Text += data;
10685             }
10686         }
10687
10688         /// <summary>
10689         /// IDataObject から URL とタイトルの対を取得します
10690         /// </summary>
10691         /// <remarks>
10692         /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10693         /// </remarks>
10694         /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10695         /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10696         internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10697         {
10698             if (data.GetDataPresent("text/x-moz-url"))
10699             {
10700                 // Firefox, Google Chrome で利用可能
10701                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10702
10703                 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10704                 {
10705                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10706                     if (lines.Length < 2)
10707                         throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10708
10709                     return new Tuple<string, string>(lines[0], lines[1]);
10710                 }
10711             }
10712             else if (data.GetDataPresent("IESiteModeToUrl"))
10713             {
10714                 // Internet Exproler 用
10715                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10716
10717                 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10718                 {
10719                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10720                     if (lines.Length < 2)
10721                         throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10722
10723                     return new Tuple<string, string>(lines[0], lines[1]);
10724                 }
10725             }
10726             else if (data.GetDataPresent("UniformResourceLocatorW"))
10727             {
10728                 // それ以外のブラウザ向け
10729
10730                 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10731                 {
10732                     var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10733                     return new Tuple<string, string>(url, null);
10734                 }
10735             }
10736
10737             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10738         }
10739
10740         private void TweenMain_DragEnter(object sender, DragEventArgs e)
10741         {
10742             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10743             {
10744                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10745                 {
10746                     SelectMedia_DragEnter(e);
10747                     return;
10748                 }
10749             }
10750             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10751             {
10752                 e.Effect = DragDropEffects.Copy;
10753                 return;
10754             }
10755             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10756             {
10757                 e.Effect = DragDropEffects.Copy;
10758                 return;
10759             }
10760             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10761             {
10762                 e.Effect = DragDropEffects.Copy;
10763                 return;
10764             }
10765
10766             e.Effect = DragDropEffects.None;
10767         }
10768
10769         private void TweenMain_DragOver(object sender, DragEventArgs e)
10770         {
10771         }
10772
10773         public bool IsNetworkAvailable()
10774         {
10775             bool nw = true;
10776             nw = MyCommon.IsNetworkAvailable();
10777             _myStatusOnline = nw;
10778             return nw;
10779         }
10780
10781         public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10782         {
10783             var uriStr = uri.AbsoluteUri;
10784
10785             // OpenTween 内部で使用する URL
10786             if (uri.Authority == "opentween")
10787             {
10788                 await this.OpenInternalUriAsync(uri);
10789                 return;
10790             }
10791
10792             // ハッシュタグを含む Twitter 検索
10793             if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10794             {
10795                 // ハッシュタグの場合は、タブで開く
10796                 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10797                 var pos = unescapedQuery.IndexOf('#');
10798                 if (pos == -1) return;
10799
10800                 var hash = unescapedQuery.Substring(pos);
10801                 this.HashSupl.AddItem(hash);
10802                 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10803                 this.AddNewTabForSearch(hash);
10804                 return;
10805             }
10806
10807             // ユーザープロフィールURL
10808             // フラグが立っている場合は設定と逆の動作をする
10809             if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10810                 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10811             {
10812                 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10813                 if (userUriMatch.Success)
10814                 {
10815                     var screenName = userUriMatch.Groups["ScreenName"].Value;
10816                     if (this.IsTwitterId(screenName))
10817                     {
10818                         this.AddNewTabForUserTimeline(screenName);
10819                         return;
10820                     }
10821                 }
10822             }
10823
10824             // どのパターンにも該当しないURL
10825             await this.OpenUriInBrowserAsync(uriStr);
10826         }
10827
10828         /// <summary>
10829         /// OpenTween 内部の機能を呼び出すための URL を開きます
10830         /// </summary>
10831         private async Task OpenInternalUriAsync(Uri uri)
10832         {
10833             // ツイートを開く (//opentween/status/:status_id)
10834             var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10835             if (match.Success)
10836             {
10837                 var statusId = long.Parse(match.Groups[1].Value);
10838                 await this.OpenRelatedTab(statusId);
10839                 return;
10840             }
10841         }
10842
10843         public Task OpenUriInBrowserAsync(string UriString)
10844         {
10845             return Task.Run(() =>
10846             {
10847                 string myPath = UriString;
10848
10849                 try
10850                 {
10851                     var configBrowserPath = this._cfgLocal.BrowserPath;
10852                     if (!string.IsNullOrEmpty(configBrowserPath))
10853                     {
10854                         if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
10855                         {
10856                             int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
10857                             string browserPath = configBrowserPath.Substring(1, sep - 1);
10858                             string arg = "";
10859                             if (sep < configBrowserPath.Length - 1)
10860                             {
10861                                 arg = configBrowserPath.Substring(sep + 1);
10862                             }
10863                             myPath = arg + " " + myPath;
10864                             System.Diagnostics.Process.Start(browserPath, myPath);
10865                         }
10866                         else
10867                         {
10868                             System.Diagnostics.Process.Start(configBrowserPath, myPath);
10869                         }
10870                     }
10871                     else
10872                     {
10873                         System.Diagnostics.Process.Start(myPath);
10874                     }
10875                 }
10876                 catch (Exception)
10877                 {
10878                     //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10879                 }
10880             });
10881         }
10882
10883         private void ListTabSelect(TabPage _tab)
10884         {
10885             SetListProperty();
10886
10887             this.PurgeListViewItemCache();
10888
10889             _curTab = _tab;
10890             _curList = (DetailsListView)_tab.Tag;
10891             if (_curList.SelectedIndices.Count > 0)
10892             {
10893                 _curItemIndex = _curList.SelectedIndices[0];
10894                 _curPost = GetCurTabPost(_curItemIndex);
10895             }
10896             else
10897             {
10898                 _curItemIndex = -1;
10899                 _curPost = null;
10900             }
10901
10902             _anchorPost = null;
10903             _anchorFlag = false;
10904
10905             if (_iconCol)
10906             {
10907                 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10908             }
10909             else
10910             {
10911                 for (int i = 0; i < _curList.Columns.Count; i++)
10912                 {
10913                     ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10914                 }
10915             }
10916         }
10917
10918         private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10919         {
10920             ListTabSelect(e.TabPage);
10921         }
10922
10923         private void SelectListItem(DetailsListView LView, int Index)
10924         {
10925             //単一
10926             Rectangle bnd = new Rectangle();
10927             bool flg = false;
10928             var item = LView.FocusedItem;
10929             if (item != null)
10930             {
10931                 bnd = item.Bounds;
10932                 flg = true;
10933             }
10934
10935             do
10936             {
10937                 LView.SelectedIndices.Clear();
10938             }
10939             while (LView.SelectedIndices.Count > 0);
10940             item = LView.Items[Index];
10941             item.Selected = true;
10942             item.Focused = true;
10943
10944             if (flg) LView.Invalidate(bnd);
10945         }
10946
10947         private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10948         {
10949             //複数
10950             Rectangle bnd = new Rectangle();
10951             bool flg = false;
10952             var item = LView.FocusedItem;
10953             if (item != null)
10954             {
10955                 bnd = item.Bounds;
10956                 flg = true;
10957             }
10958
10959             if (Index != null)
10960             {
10961                 do
10962                 {
10963                     LView.SelectedIndices.Clear();
10964                 }
10965                 while (LView.SelectedIndices.Count > 0);
10966                 LView.SelectItems(Index);
10967             }
10968             if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
10969             {
10970                 LView.SelectionMark = selectionMarkIndex;
10971             }
10972             if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
10973             {
10974                 LView.Items[focusedIndex].Focused = true;
10975             }
10976             else if (Index != null && Index.Length != 0)
10977             {
10978                 LView.Items[Index.Last()].Focused = true;
10979             }
10980
10981             if (flg) LView.Invalidate(bnd);
10982         }
10983
10984         private void StartUserStream()
10985         {
10986             tw.NewPostFromStream += tw_NewPostFromStream;
10987             tw.UserStreamStarted += tw_UserStreamStarted;
10988             tw.UserStreamStopped += tw_UserStreamStopped;
10989             tw.PostDeleted += tw_PostDeleted;
10990             tw.UserStreamEventReceived += tw_UserStreamEventArrived;
10991
10992             this.RefreshUserStreamsMenu();
10993
10994             if (this._cfgCommon.UserstreamStartup)
10995                 tw.StartUserStream();
10996         }
10997
10998         private async void TweenMain_Shown(object sender, EventArgs e)
10999         {
11000             try
11001             {
11002                 using (ControlTransaction.Update(this.PostBrowser))
11003                 {
11004                     PostBrowser.Url = new Uri("about:blank");
11005                     PostBrowser.DocumentText = "";       //発言詳細部初期化
11006                 }
11007             }
11008             catch (Exception)
11009             {
11010             }
11011
11012             NotifyIcon1.Visible = true;
11013
11014             if (this.IsNetworkAvailable())
11015             {
11016                 StartUserStream();
11017
11018                 var loadTasks = new List<Task>
11019                 {
11020                     this.RefreshMuteUserIdsAsync(),
11021                     this.RefreshBlockIdsAsync(),
11022                     this.RefreshNoRetweetIdsAsync(),
11023                     this.RefreshTwitterConfigurationAsync(),
11024                     this.GetHomeTimelineAsync(),
11025                     this.GetReplyAsync(),
11026                     this.GetDirectMessagesAsync(),
11027                     this.GetPublicSearchAllAsync(),
11028                     this.GetUserTimelineAllAsync(),
11029                     this.GetListTimelineAllAsync(),
11030                 };
11031
11032                 if (this._cfgCommon.StartupFollowers)
11033                     loadTasks.Add(this.RefreshFollowerIdsAsync());
11034
11035                 if (this._cfgCommon.GetFav)
11036                     loadTasks.Add(this.GetFavoritesAsync());
11037
11038                 var allTasks = Task.WhenAll(loadTasks);
11039
11040                 var i = 0;
11041                 while (true)
11042                 {
11043                     var timeout = Task.Delay(5000);
11044                     if (await Task.WhenAny(allTasks, timeout) != timeout)
11045                         break;
11046
11047                     i += 1;
11048                     if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11049
11050                     if (MyCommon._endingFlag)
11051                         return;
11052                 }
11053
11054                 if (MyCommon._endingFlag) return;
11055
11056                 if (ApplicationSettings.VersionInfoUrl != null)
11057                 {
11058                     //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11059                     if (this._cfgCommon.StartupVersion)
11060                         await this.CheckNewVersion(true);
11061                 }
11062                 else
11063                 {
11064                     // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11065                     this.VerUpMenuItem.Enabled = false;
11066                     this.VerUpMenuItem.Available = false;
11067                     this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11068                 }
11069
11070                 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11071                 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11072                 {
11073                     MessageBox.Show(Properties.Resources.ReAuthorizeText);
11074                     SettingStripMenuItem_Click(null, null);
11075                 }
11076
11077                 // 取得失敗の場合は再試行する
11078                 var reloadTasks = new List<Task>();
11079
11080                 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11081                     reloadTasks.Add(this.RefreshFollowerIdsAsync());
11082
11083                 if (!tw.GetNoRetweetSuccess)
11084                     reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11085
11086                 if (this.tw.Configuration.PhotoSizeLimit == 0)
11087                     reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11088
11089                 await Task.WhenAll(reloadTasks);
11090             }
11091
11092             _initial = false;
11093
11094             TimerTimeline.Enabled = true;
11095         }
11096
11097         private async Task doGetFollowersMenu()
11098         {
11099             await this.RefreshFollowerIdsAsync();
11100             await this.DispSelectedPost(true);
11101         }
11102
11103         private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11104         {
11105             await this.doGetFollowersMenu();
11106         }
11107
11108         private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
11109         {
11110             doReTweetUnofficial();
11111         }
11112
11113         private async Task doReTweetOfficial(bool isConfirm)
11114         {
11115             //公式RT
11116             if (this.ExistCurrentPost)
11117             {
11118                 if (_curPost.IsProtect)
11119                 {
11120                     MessageBox.Show("Protected.");
11121                     _DoFavRetweetFlags = false;
11122                     return;
11123                 }
11124                 if (_curList.SelectedIndices.Count > 15)
11125                 {
11126                     MessageBox.Show(Properties.Resources.RetweetLimitText);
11127                     _DoFavRetweetFlags = false;
11128                     return;
11129                 }
11130                 else if (_curList.SelectedIndices.Count > 1)
11131                 {
11132                     string QuestionText = Properties.Resources.RetweetQuestion2;
11133                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11134                     switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11135                     {
11136                         case DialogResult.Cancel:
11137                         case DialogResult.No:
11138                             _DoFavRetweetFlags = false;
11139                             return;
11140                     }
11141                 }
11142                 else
11143                 {
11144                     if (_curPost.IsDm || _curPost.IsMe)
11145                     {
11146                         _DoFavRetweetFlags = false;
11147                         return;
11148                     }
11149                     if (!this._cfgCommon.RetweetNoConfirm)
11150                     {
11151                         string Questiontext = Properties.Resources.RetweetQuestion1;
11152                         if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11153                         if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11154                         {
11155                             _DoFavRetweetFlags = false;
11156                             return;
11157                         }
11158                     }
11159                 }
11160
11161                 var statusIds = new List<long>();
11162                 foreach (int idx in _curList.SelectedIndices)
11163                 {
11164                     PostClass post = GetCurTabPost(idx);
11165                     if (!post.IsMe && !post.IsProtect && !post.IsDm)
11166                         statusIds.Add(post.StatusId);
11167                 }
11168
11169                 await this.RetweetAsync(statusIds);
11170             }
11171         }
11172
11173         private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11174         {
11175             await this.doReTweetOfficial(true);
11176         }
11177
11178         private async Task FavoritesRetweetOfficial()
11179         {
11180             if (!this.ExistCurrentPost) return;
11181             _DoFavRetweetFlags = true;
11182             var retweetTask = this.doReTweetOfficial(true);
11183             if (_DoFavRetweetFlags)
11184             {
11185                 _DoFavRetweetFlags = false;
11186                 var favoriteTask = this.FavoriteChange(true, false);
11187
11188                 await Task.WhenAll(retweetTask, favoriteTask);
11189             }
11190             else
11191             {
11192                 await retweetTask;
11193             }
11194         }
11195
11196         private async Task FavoritesRetweetUnofficial()
11197         {
11198             if (this.ExistCurrentPost && !_curPost.IsDm)
11199             {
11200                 _DoFavRetweetFlags = true;
11201                 var favoriteTask = this.FavoriteChange(true);
11202                 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11203                 {
11204                     _DoFavRetweetFlags = false;
11205                     doReTweetUnofficial();
11206                 }
11207
11208                 await favoriteTask;
11209             }
11210         }
11211
11212         /// <summary>
11213         /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11214         /// </summary>
11215         /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11216         /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11217         /// <returns>復元されたツイート本文</returns>
11218         internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11219         {
11220             // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11221
11222             // 通常の URL
11223             statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11224             // メンション
11225             statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11226             // ハッシュタグ
11227             statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11228
11229             // <br> 除去
11230             if (multiline)
11231                 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11232             else
11233                 statusHtml = statusHtml.Replace("<br>", " ");
11234
11235             // &nbsp; は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11236             // 現状では半角スペースの代用として &nbsp; を使用しているため U+0020 に置換します
11237             statusHtml = statusHtml.Replace("&nbsp;", " ");
11238
11239             return WebUtility.HtmlDecode(statusHtml);
11240         }
11241
11242         private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11243         {
11244             if (_curPost != null)
11245                 await this.DispSelectedPost(true);
11246         }
11247
11248         private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11249         {
11250             if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11251                 DebugModeToolStripMenuItem.Visible = true;
11252             else
11253                 DebugModeToolStripMenuItem.Visible = false;
11254         }
11255
11256         private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11257         {
11258             this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11259         }
11260
11261         private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11262         {
11263             ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11264         }
11265
11266         private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11267         {
11268             if (TraceOutToolStripMenuItem.Checked)
11269                 MyCommon.TraceFlag = true;
11270             else
11271                 MyCommon.TraceFlag = false;
11272         }
11273
11274         private void TweenMain_Deactivate(object sender, EventArgs e)
11275         {
11276             //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11277             this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11278         }
11279
11280         private void TabRenameMenuItem_Click(object sender, EventArgs e)
11281         {
11282             if (string.IsNullOrEmpty(_rclickTabName)) return;
11283             TabRename(ref _rclickTabName);
11284         }
11285
11286         private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11287         {
11288             await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11289         }
11290
11291         private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11292         {
11293             await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11294         }
11295
11296         private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11297         {
11298             TwitterApiStatus apiStatus;
11299
11300             using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
11301             {
11302                 var cancellationToken = dialog.EnableCancellation();
11303
11304                 try
11305                 {
11306                     var task = this.tw.GetInfoApi();
11307                     apiStatus = await dialog.WaitForAsync(this, task);
11308                 }
11309                 catch (WebApiException)
11310                 {
11311                     apiStatus = null;
11312                 }
11313
11314                 if (cancellationToken.IsCancellationRequested)
11315                     return;
11316
11317                 if (apiStatus == null)
11318                 {
11319                     MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11320                     return;
11321                 }
11322             }
11323
11324             using (var apiDlg = new ApiInfoDialog())
11325             {
11326                 apiDlg.ShowDialog(this);
11327             }
11328         }
11329
11330         private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
11331         {
11332             var id = _curPost?.ScreenName ?? "";
11333
11334             await this.FollowCommand(id);
11335         }
11336
11337         private async Task FollowCommand(string id)
11338         {
11339             using (var inputName = new InputTabName())
11340             {
11341                 inputName.FormTitle = "Follow";
11342                 inputName.FormDescription = Properties.Resources.FRMessage1;
11343                 inputName.TabName = id;
11344
11345                 if (inputName.ShowDialog(this) != DialogResult.OK)
11346                     return;
11347                 if (string.IsNullOrWhiteSpace(inputName.TabName))
11348                     return;
11349
11350                 id = inputName.TabName.Trim();
11351             }
11352
11353             using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11354             {
11355                 try
11356                 {
11357                     var task = this.twitterApi.FriendshipsCreate(id);
11358                     await dialog.WaitForAsync(this, task);
11359                 }
11360                 catch (WebApiException ex)
11361                 {
11362                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11363                     return;
11364                 }
11365             }
11366
11367             MessageBox.Show(Properties.Resources.FRMessage3);
11368         }
11369
11370         private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11371         {
11372             var id = _curPost?.ScreenName ?? "";
11373
11374             await this.RemoveCommand(id, false);
11375         }
11376
11377         private async Task RemoveCommand(string id, bool skipInput)
11378         {
11379             if (!skipInput)
11380             {
11381                 using (var inputName = new InputTabName())
11382                 {
11383                     inputName.FormTitle = "Unfollow";
11384                     inputName.FormDescription = Properties.Resources.FRMessage1;
11385                     inputName.TabName = id;
11386
11387                     if (inputName.ShowDialog(this) != DialogResult.OK)
11388                         return;
11389                     if (string.IsNullOrWhiteSpace(inputName.TabName))
11390                         return;
11391
11392                     id = inputName.TabName.Trim();
11393                 }
11394             }
11395
11396             using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11397             {
11398                 try
11399                 {
11400                     var task = this.twitterApi.FriendshipsDestroy(id);
11401                     await dialog.WaitForAsync(this, task);
11402                 }
11403                 catch (WebApiException ex)
11404                 {
11405                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11406                     return;
11407                 }
11408             }
11409
11410             MessageBox.Show(Properties.Resources.FRMessage3);
11411         }
11412
11413         private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11414         {
11415             var id = _curPost?.ScreenName ?? "";
11416
11417             await this.ShowFriendship(id);
11418         }
11419
11420         private async Task ShowFriendship(string id)
11421         {
11422             using (var inputName = new InputTabName())
11423             {
11424                 inputName.FormTitle = "Show Friendships";
11425                 inputName.FormDescription = Properties.Resources.FRMessage1;
11426                 inputName.TabName = id;
11427
11428                 if (inputName.ShowDialog(this) != DialogResult.OK)
11429                     return;
11430                 if (string.IsNullOrWhiteSpace(inputName.TabName))
11431                     return;
11432
11433                 id = inputName.TabName.Trim();
11434             }
11435
11436             bool isFollowing, isFollowed;
11437
11438             using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11439             {
11440                 var cancellationToken = dialog.EnableCancellation();
11441
11442                 try
11443                 {
11444                     var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11445                     var friendship = await dialog.WaitForAsync(this, task);
11446
11447                     isFollowing = friendship.Relationship.Source.Following;
11448                     isFollowed = friendship.Relationship.Source.FollowedBy;
11449                 }
11450                 catch (WebApiException ex)
11451                 {
11452                     if (!cancellationToken.IsCancellationRequested)
11453                         MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11454                     return;
11455                 }
11456
11457                 if (cancellationToken.IsCancellationRequested)
11458                     return;
11459             }
11460
11461             string result = "";
11462             if (isFollowing)
11463             {
11464                 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11465             }
11466             else
11467             {
11468                 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11469             }
11470             if (isFollowed)
11471             {
11472                 result += Properties.Resources.GetFriendshipInfo3;
11473             }
11474             else
11475             {
11476                 result += Properties.Resources.GetFriendshipInfo4;
11477             }
11478             result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11479             MessageBox.Show(result);
11480         }
11481
11482         private async Task ShowFriendship(string[] ids)
11483         {
11484             foreach (string id in ids)
11485             {
11486                 bool isFollowing, isFollowed;
11487
11488                 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11489                 {
11490                     var cancellationToken = dialog.EnableCancellation();
11491
11492                     try
11493                     {
11494                         var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11495                         var friendship = await dialog.WaitForAsync(this, task);
11496
11497                         isFollowing = friendship.Relationship.Source.Following;
11498                         isFollowed = friendship.Relationship.Source.FollowedBy;
11499                     }
11500                     catch (WebApiException ex)
11501                     {
11502                         if (!cancellationToken.IsCancellationRequested)
11503                             MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11504                         return;
11505                     }
11506
11507                     if (cancellationToken.IsCancellationRequested)
11508                         return;
11509                 }
11510
11511                 string result = "";
11512                 string ff = "";
11513
11514                 ff = "  ";
11515                 if (isFollowing)
11516                 {
11517                     ff += Properties.Resources.GetFriendshipInfo1;
11518                 }
11519                 else
11520                 {
11521                     ff += Properties.Resources.GetFriendshipInfo2;
11522                 }
11523
11524                 ff += System.Environment.NewLine + "  ";
11525                 if (isFollowed)
11526                 {
11527                     ff += Properties.Resources.GetFriendshipInfo3;
11528                 }
11529                 else
11530                 {
11531                     ff += Properties.Resources.GetFriendshipInfo4;
11532                 }
11533                 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11534                 if (isFollowing)
11535                 {
11536                     if (MessageBox.Show(
11537                         Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11538                         MessageBoxButtons.YesNo,
11539                         MessageBoxIcon.Question,
11540                         MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11541                     {
11542                         await this.RemoveCommand(id, true);
11543                     }
11544                 }
11545                 else
11546                 {
11547                     MessageBox.Show(result);
11548                 }
11549             }
11550         }
11551
11552         private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11553         {
11554             await this.doShowUserStatus(tw.Username, false);
11555             //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11556             //{
11557             //    doShowUserStatus(tw.Username, false);
11558             //}
11559             //else
11560             //{
11561             //    MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11562             //    return;
11563             //}
11564         }
11565
11566         // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11567         // URLから切り出した文字列を渡す
11568
11569         public bool IsTwitterId(string name)
11570         {
11571             if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11572                 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11573             else
11574                 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
11575         }
11576
11577         private string GetUserId()
11578         {
11579             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11580             if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11581                 return m.Result("${ScreenName}");
11582             else
11583                 return null;
11584         }
11585
11586         private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11587         {
11588             string name = GetUserId();
11589             if (name != null)
11590                 await this.FollowCommand(name);
11591         }
11592
11593         private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11594         {
11595             string name = GetUserId();
11596             if (name != null)
11597                 await this.RemoveCommand(name, false);
11598         }
11599
11600         private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11601         {
11602             string name = GetUserId();
11603             if (name != null)
11604                 await this.ShowFriendship(name);
11605         }
11606
11607         private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11608         {
11609             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11610             List<string> ids = new List<string>();
11611             foreach (Match mu in ma)
11612             {
11613                 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11614                 {
11615                     ids.Add(mu.Result("${ScreenName}"));
11616                 }
11617             }
11618
11619             await this.ShowFriendship(ids.ToArray());
11620         }
11621
11622         private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11623         {
11624             string name = GetUserId();
11625             if (name != null)
11626                 await this.ShowUserStatus(name);
11627         }
11628
11629         private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11630         {
11631             string name = GetUserId();
11632             if (name != null) AddNewTabForUserTimeline(name);
11633         }
11634
11635         private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11636         {
11637             string name = GetUserId();
11638             if (name != null) AddNewTabForSearch("@" + name);
11639         }
11640
11641         private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11642         {
11643             ModifySettingCommon = true;
11644         }
11645
11646         private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11647         {
11648             ModifySettingCommon = true;
11649         }
11650
11651         private void doQuoteOfficial()
11652         {
11653             if (this.ExistCurrentPost)
11654             {
11655                 if (_curPost.IsDm ||
11656                     !StatusText.Enabled) return;
11657
11658                 if (_curPost.IsProtect)
11659                 {
11660                     MessageBox.Show("Protected.");
11661                     return;
11662                 }
11663
11664                 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11665
11666                 this.inReplyTo = null;
11667
11668                 StatusText.SelectionStart = 0;
11669                 StatusText.Focus();
11670             }
11671         }
11672
11673         private void doReTweetUnofficial()
11674         {
11675             //RT @id:内容
11676             if (this.ExistCurrentPost)
11677             {
11678                 if (_curPost.IsDm || !StatusText.Enabled)
11679                     return;
11680
11681                 if (_curPost.IsProtect)
11682                 {
11683                     MessageBox.Show("Protected.");
11684                     return;
11685                 }
11686                 string rtdata = _curPost.Text;
11687                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11688
11689                 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11690
11691                 // 投稿時に in_reply_to_status_id を付加する
11692                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11693                 var inReplyToScreenName = this._curPost.ScreenName;
11694                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11695
11696                 StatusText.SelectionStart = 0;
11697                 StatusText.Focus();
11698             }
11699         }
11700
11701         private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11702         {
11703             doQuoteOfficial();
11704         }
11705
11706         private void SearchButton_Click(object sender, EventArgs e)
11707         {
11708             //公式検索
11709             Control pnl = ((Control)sender).Parent;
11710             if (pnl == null) return;
11711             string tbName = pnl.Parent.Text;
11712             TabClass tb = _statuses.Tabs[tbName];
11713             ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11714             ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11715             cmb.Text = cmb.Text.Trim();
11716             // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11717             bool Quote = false;
11718             StringBuilder buf = new StringBuilder();
11719             char[] c = cmb.Text.ToCharArray();
11720             for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11721             {
11722                 if (cnt > cmb.Text.Length - 4)
11723                 {
11724                     buf.Append(cmb.Text.Substring(cnt));
11725                     break;
11726                 }
11727                 if (c[cnt] == '"')
11728                 {
11729                     Quote = !Quote;
11730                 }
11731                 else
11732                 {
11733                     if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11734                     {
11735                         buf.Append(" OR ");
11736                         cnt += 3;
11737                         continue;
11738                     }
11739                 }
11740                 buf.Append(c[cnt]);
11741             }
11742             cmb.Text = buf.ToString();
11743
11744             var listView = (DetailsListView)pnl.Parent.Tag;
11745
11746             tb.SearchWords = cmb.Text;
11747             tb.SearchLang = cmbLang.Text;
11748             if (string.IsNullOrEmpty(cmb.Text))
11749             {
11750                 listView.Focus();
11751                 SaveConfigsTabs();
11752                 return;
11753             }
11754             if (tb.IsSearchQueryChanged)
11755             {
11756                 int idx = cmb.Items.IndexOf(tb.SearchWords);
11757                 if (idx > -1) cmb.Items.RemoveAt(idx);
11758                 cmb.Items.Insert(0, tb.SearchWords);
11759                 cmb.Text = tb.SearchWords;
11760                 cmb.SelectAll();
11761                 this.PurgeListViewItemCache();
11762                 listView.VirtualListSize = 0;
11763                 _statuses.ClearTabIds(tbName);
11764                 SaveConfigsTabs();   //検索条件の保存
11765             }
11766
11767             this.GetPublicSearchAsync(tb);
11768             listView.Focus();
11769         }
11770
11771         private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11772         {
11773             //もっと前を取得
11774             await this.DoRefreshMore();
11775         }
11776
11777         /// <summary>
11778         /// 指定されたタブのListTabにおける位置を返します
11779         /// </summary>
11780         /// <remarks>
11781         /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11782         /// </remarks>
11783         public int GetTabPageIndex(string tabName)
11784         {
11785             var index = 0;
11786             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11787             {
11788                 if (tabPage.Text == tabName)
11789                     return index;
11790
11791                 index++;
11792             }
11793
11794             return -1;
11795         }
11796
11797         private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11798         {
11799             if (_statuses.RemovedTab.Count == 0)
11800             {
11801                 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11802                 return;
11803             }
11804             else
11805             {
11806                 DetailsListView listView = null;
11807
11808                 TabClass tb = _statuses.RemovedTab.Pop();
11809                 if (tb.TabType == MyCommon.TabUsageType.Related)
11810                 {
11811                     var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11812                     if (relatedTab != null)
11813                     {
11814                         // 関連発言なら既存のタブを置き換える
11815                         tb.TabName = relatedTab.TabName;
11816                         this.ClearTab(tb.TabName, false);
11817                         _statuses.Tabs[tb.TabName] = tb;
11818
11819                         for (int i = 0; i < ListTab.TabPages.Count; i++)
11820                         {
11821                             var tabPage = ListTab.TabPages[i];
11822                             if (tb.TabName == tabPage.Text)
11823                             {
11824                                 listView = (DetailsListView)tabPage.Tag;
11825                                 ListTab.SelectedIndex = i;
11826                                 break;
11827                             }
11828                         }
11829                     }
11830                     else
11831                     {
11832                         const string TabName = "Related Tweets";
11833                         string renamed = TabName;
11834                         for (int i = 2; i <= 100; i++)
11835                         {
11836                             if (!_statuses.ContainsTab(renamed)) break;
11837                             renamed = TabName + i.ToString();
11838                         }
11839                         tb.TabName = renamed;
11840                         AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11841                         _statuses.Tabs.Add(renamed, tb);  // 後に
11842
11843                         var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11844                         listView = (DetailsListView)tabPage.Tag;
11845                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11846                     }
11847                 }
11848                 else
11849                 {
11850                     string renamed = tb.TabName;
11851                     for (int i = 1; i < int.MaxValue; i++)
11852                     {
11853                         if (!_statuses.ContainsTab(renamed)) break;
11854                         renamed = tb.TabName + "(" + i.ToString() + ")";
11855                     }
11856                     tb.TabName = renamed;
11857                     _statuses.Tabs.Add(renamed, tb);  // 先に
11858                     AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11859
11860                     var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11861                     listView = (DetailsListView)tabPage.Tag;
11862                     ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11863                 }
11864                 SaveConfigsTabs();
11865
11866                 if (listView != null)
11867                 {
11868                     using (ControlTransaction.Update(listView))
11869                     {
11870                         listView.VirtualListSize = tb.AllCount;
11871                     }
11872                 }
11873             }
11874         }
11875
11876         private async Task doMoveToRTHome()
11877         {
11878             if (_curList.SelectedIndices.Count > 0)
11879             {
11880                 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11881                 if (post.RetweetedId != null)
11882                 {
11883                     await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11884                 }
11885             }
11886         }
11887
11888         private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11889         {
11890             await this.doMoveToRTHome();
11891         }
11892
11893         private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11894         {
11895             string name = GetUserId();
11896             if (name != null)
11897             {
11898                 string tabName;
11899
11900                 //未選択なら処理終了
11901                 if (_curList.SelectedIndices.Count == 0) return;
11902
11903                 //タブ選択(or追加)
11904                 if (!SelectTab(out tabName)) return;
11905
11906                 var tab = this._statuses.Tabs[tabName];
11907
11908                 bool mv;
11909                 bool mk;
11910                 if (tab.TabType != MyCommon.TabUsageType.Mute)
11911                 {
11912                     this.MoveOrCopy(out mv, out mk);
11913                 }
11914                 else
11915                 {
11916                     // ミュートタブでは常に MoveMatches を true にする
11917                     mv = true;
11918                     mk = false;
11919                 }
11920
11921                 PostFilterRule fc = new PostFilterRule();
11922                 fc.FilterName = name;
11923                 fc.UseNameField = true;
11924                 fc.MoveMatches = mv;
11925                 fc.MarkMatches = mk;
11926                 fc.UseRegex = false;
11927                 fc.FilterByUrl = false;
11928                 tab.AddFilter(fc);
11929
11930                 this.ApplyPostFilters();
11931                 SaveConfigsTabs();
11932             }
11933         }
11934
11935         private async void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11936         {
11937             string user;
11938
11939             ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11940
11941             if (menuItem.Owner == this.ContextMenuPostBrowser)
11942             {
11943                 user = GetUserId();
11944                 if (user == null) return;
11945             }
11946             else if (this._curPost != null)
11947             {
11948                 user = this._curPost.ScreenName;
11949             }
11950             else
11951             {
11952                 return;
11953             }
11954
11955             if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11956             {
11957                 try
11958                 {
11959                     using (var dialog = new WaitingDialog(Properties.Resources.ListsGetting))
11960                     {
11961                         var cancellationToken = dialog.EnableCancellation();
11962
11963                         var task = this.tw.GetListsApi();
11964                         await dialog.WaitForAsync(this, task);
11965
11966                         cancellationToken.ThrowIfCancellationRequested();
11967                     }
11968                 }
11969                 catch (OperationCanceledException) { return; }
11970                 catch (WebApiException ex)
11971                 {
11972                     MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
11973                     return;
11974                 }
11975             }
11976
11977             using (MyLists listSelectForm = new MyLists(user, this.tw))
11978             {
11979                 listSelectForm.ShowDialog(this);
11980             }
11981         }
11982
11983         private void SearchControls_Enter(object sender, EventArgs e)
11984         {
11985             Control pnl = (Control)sender;
11986             foreach (Control ctl in pnl.Controls)
11987             {
11988                 ctl.TabStop = true;
11989             }
11990         }
11991
11992         private void SearchControls_Leave(object sender, EventArgs e)
11993         {
11994             Control pnl = (Control)sender;
11995             foreach (Control ctl in pnl.Controls)
11996             {
11997                 ctl.TabStop = false;
11998             }
11999         }
12000
12001         private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12002         {
12003             if (ListTab.SelectedTab != null)
12004             {
12005                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12006                 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12007             }
12008         }
12009
12010         private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12011         {
12012             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12013             if (m.Success)
12014             {
12015                 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12016                 HashStripSplitButton.Text = HashMgr.UseHash;
12017                 HashToggleMenuItem.Checked = true;
12018                 HashToggleToolStripMenuItem.Checked = true;
12019                 //使用ハッシュタグとして設定
12020                 ModifySettingCommon = true;
12021             }
12022         }
12023
12024         private void StatusLabel_DoubleClick(object sender, EventArgs e)
12025         {
12026             MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12027         }
12028
12029         private void HashManageMenuItem_Click(object sender, EventArgs e)
12030         {
12031             DialogResult rslt = DialogResult.Cancel;
12032             try
12033             {
12034                 rslt = HashMgr.ShowDialog();
12035             }
12036             catch (Exception)
12037             {
12038                 return;
12039             }
12040             this.TopMost = this._cfgCommon.AlwaysTop;
12041             if (rslt == DialogResult.Cancel) return;
12042             if (!string.IsNullOrEmpty(HashMgr.UseHash))
12043             {
12044                 HashStripSplitButton.Text = HashMgr.UseHash;
12045                 HashToggleMenuItem.Checked = true;
12046                 HashToggleToolStripMenuItem.Checked = true;
12047             }
12048             else
12049             {
12050                 HashStripSplitButton.Text = "#[-]";
12051                 HashToggleMenuItem.Checked = false;
12052                 HashToggleToolStripMenuItem.Checked = false;
12053             }
12054             //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12055             //{
12056             //    int sidx = StatusText.SelectionStart;
12057             //    string hash = HashMgr.UseHash + " ";
12058             //    if (sidx > 0)
12059             //    {
12060             //        if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12061             //            hash = " " + hash;
12062             //    }
12063             //    StatusText.Text = StatusText.Text.Insert(sidx, hash);
12064             //    sidx += hash.Length;
12065             //    StatusText.SelectionStart = sidx;
12066             //    StatusText.Focus();
12067             //}
12068             ModifySettingCommon = true;
12069             this.StatusText_TextChanged(null, null);
12070         }
12071
12072         private void HashToggleMenuItem_Click(object sender, EventArgs e)
12073         {
12074             HashMgr.ToggleHash();
12075             if (!string.IsNullOrEmpty(HashMgr.UseHash))
12076             {
12077                 HashStripSplitButton.Text = HashMgr.UseHash;
12078                 HashToggleMenuItem.Checked = true;
12079                 HashToggleToolStripMenuItem.Checked = true;
12080             }
12081             else
12082             {
12083                 HashStripSplitButton.Text = "#[-]";
12084                 HashToggleMenuItem.Checked = false;
12085                 HashToggleToolStripMenuItem.Checked = false;
12086             }
12087             ModifySettingCommon = true;
12088             this.StatusText_TextChanged(null, null);
12089         }
12090
12091         private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12092         {
12093             HashToggleMenuItem_Click(null, null);
12094         }
12095
12096         private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12097         {
12098             if (ListTab.SelectedTab == null) return;
12099             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12100             if (!this.ExistCurrentPost)
12101             {
12102                 this.ReplyOpMenuItem.Enabled = false;
12103                 this.ReplyAllOpMenuItem.Enabled = false;
12104                 this.DmOpMenuItem.Enabled = false;
12105                 this.ShowProfMenuItem.Enabled = false;
12106                 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12107                 this.ListManageMenuItem.Enabled = false;
12108                 this.OpenFavOpMenuItem.Enabled = false;
12109                 this.CreateTabRuleOpMenuItem.Enabled = false;
12110                 this.CreateIdRuleOpMenuItem.Enabled = false;
12111                 this.CreateSourceRuleOpMenuItem.Enabled = false;
12112                 this.ReadOpMenuItem.Enabled = false;
12113                 this.UnreadOpMenuItem.Enabled = false;
12114             }
12115             else
12116             {
12117                 this.ReplyOpMenuItem.Enabled = true;
12118                 this.ReplyAllOpMenuItem.Enabled = true;
12119                 this.DmOpMenuItem.Enabled = true;
12120                 this.ShowProfMenuItem.Enabled = true;
12121                 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12122                 this.ListManageMenuItem.Enabled = true;
12123                 this.OpenFavOpMenuItem.Enabled = true;
12124                 this.CreateTabRuleOpMenuItem.Enabled = true;
12125                 this.CreateIdRuleOpMenuItem.Enabled = true;
12126                 this.CreateSourceRuleOpMenuItem.Enabled = true;
12127                 this.ReadOpMenuItem.Enabled = true;
12128                 this.UnreadOpMenuItem.Enabled = true;
12129             }
12130
12131             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12132             {
12133                 this.FavOpMenuItem.Enabled = false;
12134                 this.UnFavOpMenuItem.Enabled = false;
12135                 this.OpenStatusOpMenuItem.Enabled = false;
12136                 this.OpenFavotterOpMenuItem.Enabled = false;
12137                 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12138                 this.RtOpMenuItem.Enabled = false;
12139                 this.RtUnOpMenuItem.Enabled = false;
12140                 this.QtOpMenuItem.Enabled = false;
12141                 this.FavoriteRetweetMenuItem.Enabled = false;
12142                 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12143             }
12144             else
12145             {
12146                 this.FavOpMenuItem.Enabled = true;
12147                 this.UnFavOpMenuItem.Enabled = true;
12148                 this.OpenStatusOpMenuItem.Enabled = true;
12149                 this.OpenFavotterOpMenuItem.Enabled = true;
12150                 this.ShowRelatedStatusesMenuItem2.Enabled = true;  //PublicSearchの時問題出るかも
12151
12152                 if (_curPost.IsMe)
12153                 {
12154                     this.RtOpMenuItem.Enabled = false;  //公式RTは無効に
12155                     this.RtUnOpMenuItem.Enabled = true;
12156                     this.QtOpMenuItem.Enabled = true;
12157                     this.FavoriteRetweetMenuItem.Enabled = false;  //公式RTは無効に
12158                     this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12159                 }
12160                 else
12161                 {
12162                     if (_curPost.IsProtect)
12163                     {
12164                         this.RtOpMenuItem.Enabled = false;
12165                         this.RtUnOpMenuItem.Enabled = false;
12166                         this.QtOpMenuItem.Enabled = false;
12167                         this.FavoriteRetweetMenuItem.Enabled = false;
12168                         this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12169                     }
12170                     else
12171                     {
12172                         this.RtOpMenuItem.Enabled = true;
12173                         this.RtUnOpMenuItem.Enabled = true;
12174                         this.QtOpMenuItem.Enabled = true;
12175                         this.FavoriteRetweetMenuItem.Enabled = true;
12176                         this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12177                     }
12178                 }
12179             }
12180
12181             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12182             {
12183                 this.RefreshPrevOpMenuItem.Enabled = true;
12184             }
12185             else
12186             {
12187                 this.RefreshPrevOpMenuItem.Enabled = false;
12188             }
12189             if (!this.ExistCurrentPost
12190                 || _curPost.InReplyToStatusId == null)
12191             {
12192                 OpenRepSourceOpMenuItem.Enabled = false;
12193             }
12194             else
12195             {
12196                 OpenRepSourceOpMenuItem.Enabled = true;
12197             }
12198             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12199             {
12200                 OpenRterHomeMenuItem.Enabled = false;
12201             }
12202             else
12203             {
12204                 OpenRterHomeMenuItem.Enabled = true;
12205             }
12206
12207             if (this.ExistCurrentPost)
12208             {
12209                 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12210             }
12211         }
12212
12213         private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12214         {
12215             ContextMenuTabProperty_Opening(sender, null);
12216         }
12217
12218         public Twitter TwitterInstance
12219         {
12220             get { return tw; }
12221         }
12222
12223         private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12224         {
12225             if (this._initialLayout)
12226                 return;
12227
12228             int splitterDistance;
12229             switch (this.WindowState)
12230             {
12231                 case FormWindowState.Normal:
12232                     splitterDistance = this.SplitContainer3.SplitterDistance;
12233                     break;
12234                 case FormWindowState.Maximized:
12235                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
12236                     var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
12237                     splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
12238                     splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
12239                     break;
12240                 default:
12241                     return;
12242             }
12243
12244             this._mySpDis3 = splitterDistance;
12245             this.ModifySettingLocal = true;
12246         }
12247
12248         private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12249         {
12250             if (_statuses.RemovedTab.Count == 0)
12251             {
12252                 UndoRemoveTabMenuItem.Enabled = false;
12253             }
12254             else
12255             {
12256                 UndoRemoveTabMenuItem.Enabled = true;
12257             }
12258             if (ListTab.SelectedTab != null)
12259             {
12260                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12261                     PublicSearchQueryMenuItem.Enabled = true;
12262                 else
12263                     PublicSearchQueryMenuItem.Enabled = false;
12264             }
12265             else
12266             {
12267                 PublicSearchQueryMenuItem.Enabled = false;
12268             }
12269             if (!this.ExistCurrentPost)
12270             {
12271                 this.CopySTOTMenuItem.Enabled = false;
12272                 this.CopyURLMenuItem.Enabled = false;
12273                 this.CopyUserIdStripMenuItem.Enabled = false;
12274             }
12275             else
12276             {
12277                 this.CopySTOTMenuItem.Enabled = true;
12278                 this.CopyURLMenuItem.Enabled = true;
12279                 this.CopyUserIdStripMenuItem.Enabled = true;
12280                 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12281                 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12282             }
12283         }
12284
12285         private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12286         {
12287             SetNotifyIconText();
12288         }
12289
12290         private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12291         {
12292             var id = _curPost?.ScreenName ?? "";
12293
12294             await this.ShowUserStatus(id);
12295         }
12296
12297         private async Task doShowUserStatus(string id, bool ShowInputDialog)
12298         {
12299             TwitterUser user = null;
12300
12301             if (ShowInputDialog)
12302             {
12303                 using (var inputName = new InputTabName())
12304                 {
12305                     inputName.FormTitle = "Show UserStatus";
12306                     inputName.FormDescription = Properties.Resources.FRMessage1;
12307                     inputName.TabName = id;
12308
12309                     if (inputName.ShowDialog(this) != DialogResult.OK)
12310                         return;
12311                     if (string.IsNullOrWhiteSpace(inputName.TabName))
12312                         return;
12313
12314                     id = inputName.TabName.Trim();
12315                 }
12316             }
12317
12318             using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
12319             {
12320                 var cancellationToken = dialog.EnableCancellation();
12321
12322                 try
12323                 {
12324                     var task = this.twitterApi.UsersShow(id);
12325                     user = await dialog.WaitForAsync(this, task);
12326                 }
12327                 catch (WebApiException ex)
12328                 {
12329                     if (!cancellationToken.IsCancellationRequested)
12330                         MessageBox.Show($"Err:{ex.Message}(UsersShow)");
12331                     return;
12332                 }
12333
12334                 if (cancellationToken.IsCancellationRequested)
12335                     return;
12336             }
12337
12338             await this.doShowUserStatus(user);
12339         }
12340
12341         private async Task doShowUserStatus(TwitterUser user)
12342         {
12343             using (var userDialog = new UserInfoDialog(this, this.twitterApi))
12344             {
12345                 var showUserTask = userDialog.ShowUserAsync(user);
12346                 userDialog.ShowDialog(this);
12347
12348                 this.Activate();
12349                 this.BringToFront();
12350
12351                 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12352                 await showUserTask;
12353             }
12354         }
12355
12356         private Task ShowUserStatus(string id, bool ShowInputDialog)
12357         {
12358             return this.doShowUserStatus(id, ShowInputDialog);
12359         }
12360
12361         private Task ShowUserStatus(string id)
12362         {
12363             return this.doShowUserStatus(id, true);
12364         }
12365
12366         private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12367         {
12368             if (NameLabel.Tag != null)
12369             {
12370                 string id = (string)NameLabel.Tag;
12371                 if (id != tw.Username)
12372                 {
12373                     await this.FollowCommand(id);
12374                 }
12375             }
12376         }
12377
12378         private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12379         {
12380             if (NameLabel.Tag != null)
12381             {
12382                 string id = (string)NameLabel.Tag;
12383                 if (id != tw.Username)
12384                 {
12385                     await this.RemoveCommand(id, false);
12386                 }
12387             }
12388         }
12389
12390         private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12391         {
12392             if (NameLabel.Tag != null)
12393             {
12394                 string id = (string)NameLabel.Tag;
12395                 if (id != tw.Username)
12396                 {
12397                     await this.ShowFriendship(id);
12398                 }
12399             }
12400         }
12401
12402         private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12403         {
12404             if (NameLabel.Tag != null)
12405             {
12406                 string id = (string)NameLabel.Tag;
12407                 await this.ShowUserStatus(id, false);
12408             }
12409         }
12410
12411         private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12412         {
12413             if (NameLabel.Tag != null)
12414             {
12415                 string id = (string)NameLabel.Tag;
12416                 AddNewTabForUserTimeline(id);
12417             }
12418         }
12419
12420         private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12421         {
12422             if (NameLabel.Tag != null)
12423             {
12424                 string id = (string)NameLabel.Tag;
12425                 AddNewTabForSearch("@" + id);
12426             }
12427         }
12428
12429         private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12430         {
12431             if (_curPost != null)
12432             {
12433                 await this.ShowUserStatus(_curPost.ScreenName, false);
12434             }
12435         }
12436
12437         private async void RtCountMenuItem_Click(object sender, EventArgs e)
12438         {
12439             if (!this.ExistCurrentPost)
12440                 return;
12441
12442             var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12443             TwitterStatus status;
12444
12445             using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12446             {
12447                 var cancellationToken = dialog.EnableCancellation();
12448
12449                 try
12450                 {
12451                     var task = this.twitterApi.StatusesShow(statusId);
12452                     status = await dialog.WaitForAsync(this, task);
12453                 }
12454                 catch (WebApiException ex)
12455                 {
12456                     if (!cancellationToken.IsCancellationRequested)
12457                         MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
12458                     return;
12459                 }
12460
12461                 if (cancellationToken.IsCancellationRequested)
12462                     return;
12463             }
12464
12465             MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
12466         }
12467
12468         private HookGlobalHotkey _hookGlobalHotkey;
12469         public TweenMain()
12470         {
12471             _hookGlobalHotkey = new HookGlobalHotkey(this);
12472
12473             // この呼び出しは、Windows フォーム デザイナで必要です。
12474             InitializeComponent();
12475
12476             // InitializeComponent() 呼び出しの後で初期化を追加します。
12477
12478             if (!this.DesignMode)
12479             {
12480                 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12481                 this.StatusText.Dock = DockStyle.Fill;
12482             }
12483
12484             this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12485             this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12486             this.gh.NotifyClicked += GrowlHelper_Callback;
12487
12488             // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12489             this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12490
12491             this.ImageSelector.Visible = false;
12492             this.ImageSelector.Enabled = false;
12493             this.ImageSelector.FilePickDialog = OpenFileDialog1;
12494
12495             this.ReplaceAppName();
12496             this.InitializeShortcuts();
12497         }
12498
12499         private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12500         {
12501             if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12502             {
12503                 //アイコン化
12504                 this.Visible = false;
12505             }
12506             else if (Form.ActiveForm == null)
12507             {
12508                 this.Visible = true;
12509                 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12510                 this.Activate();
12511                 this.BringToFront();
12512                 this.StatusText.Focus();
12513             }
12514         }
12515
12516         private void UserPicture_MouseEnter(object sender, EventArgs e)
12517         {
12518             this.UserPicture.Cursor = Cursors.Hand;
12519         }
12520
12521         private void UserPicture_MouseLeave(object sender, EventArgs e)
12522         {
12523             this.UserPicture.Cursor = Cursors.Default;
12524         }
12525
12526         private async void UserPicture_DoubleClick(object sender, EventArgs e)
12527         {
12528             if (NameLabel.Tag != null)
12529             {
12530                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12531             }
12532         }
12533
12534         private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12535         {
12536             this.MultiLineMenuItem.PerformClick();
12537         }
12538
12539         public PostClass CurPost
12540         {
12541             get { return _curPost; }
12542         }
12543
12544 #region "画像投稿"
12545         private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12546         {
12547             if (ImageSelector.Visible)
12548                 ImageSelector.EndSelection();
12549             else
12550                 ImageSelector.BeginSelection();
12551         }
12552
12553         private void SelectMedia_DragEnter(DragEventArgs e)
12554         {
12555             if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12556             {
12557                 e.Effect = DragDropEffects.Copy;
12558                 return;
12559             }
12560             e.Effect = DragDropEffects.None;
12561         }
12562
12563         private void SelectMedia_DragDrop(DragEventArgs e)
12564         {
12565             this.Activate();
12566             this.BringToFront();
12567             ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12568             StatusText.Focus();
12569         }
12570
12571         private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12572         {
12573             TimelinePanel.Visible = false;
12574             TimelinePanel.Enabled = false;
12575         }
12576
12577         private void ImageSelector_EndSelecting(object sender, EventArgs e)
12578         {
12579             TimelinePanel.Visible = true;
12580             TimelinePanel.Enabled = true;
12581             ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12582         }
12583
12584         private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12585         {
12586             this.AllowDrop = false;
12587         }
12588
12589         private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12590         {
12591             this.AllowDrop = true;
12592         }
12593
12594         private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12595         {
12596             if (ImageSelector.Visible)
12597             {
12598                 ModifySettingCommon = true;
12599                 SaveConfigsAll(true);
12600
12601                 if (ImageSelector.ServiceName.Equals("Twitter"))
12602                     this.StatusText_TextChanged(null, null);
12603             }
12604         }
12605
12606         private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12607         {
12608             this.StatusText_TextChanged(null, null);
12609         }
12610
12611         /// <summary>
12612         /// StatusTextでCtrl+Vが押下された時の処理
12613         /// </summary>
12614         private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12615         {
12616             if (Clipboard.ContainsText())
12617             {
12618                 // clipboardにテキストがある場合は貼り付け処理
12619                 this.StatusText.Paste(Clipboard.GetText());
12620             }
12621             else if (Clipboard.ContainsImage())
12622             {
12623                 // 画像があるので投稿処理を行う
12624                 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12625                                    Properties.Resources.PostPictureWarn4,
12626                                    MessageBoxButtons.OKCancel,
12627                                    MessageBoxIcon.Question,
12628                                    MessageBoxDefaultButton.Button2)
12629                                == DialogResult.OK)
12630                 {
12631                     // clipboardから画像を取得
12632                     using (var image = Clipboard.GetImage())
12633                     {
12634                         this.ImageSelector.BeginSelection(image);
12635                     }
12636                 }
12637             }
12638         }
12639 #endregion
12640
12641         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12642         {
12643             using (ListManage form = new ListManage(tw))
12644             {
12645                 form.ShowDialog(this);
12646             }
12647         }
12648
12649         public bool ModifySettingCommon { get; set; }
12650         public bool ModifySettingLocal { get; set; }
12651         public bool ModifySettingAtId { get; set; }
12652
12653         private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12654         {
12655             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12656             if (sourceUri != null && e.Button == MouseButtons.Left)
12657             {
12658                 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12659             }
12660         }
12661
12662         private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12663         {
12664             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12665             if (sourceUri != null)
12666             {
12667                 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12668             }
12669         }
12670
12671         private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12672         {
12673             SetStatusLabelUrl();
12674         }
12675
12676         private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12677         {
12678             if (this.ExistCurrentPost && !_curPost.IsDm)
12679                 RtCountMenuItem.Enabled = true;
12680             else
12681                 RtCountMenuItem.Enabled = false;
12682
12683             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12684             //    TinyUrlConvertToolStripMenuItem.Enabled = false;
12685             //else
12686             //    TinyUrlConvertToolStripMenuItem.Enabled = true;
12687         }
12688
12689         private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12690         {
12691             CopyUserId();
12692         }
12693
12694         private void CopyUserId()
12695         {
12696             if (_curPost == null) return;
12697             string clstr = _curPost.ScreenName;
12698             try
12699             {
12700                 Clipboard.SetDataObject(clstr, false, 5, 100);
12701             }
12702             catch (Exception ex)
12703             {
12704                 MessageBox.Show(ex.Message);
12705             }
12706         }
12707
12708         private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12709         {
12710             if (this.ExistCurrentPost && !_curPost.IsDm)
12711             {
12712                 try
12713                 {
12714                     await this.OpenRelatedTab(this._curPost);
12715                 }
12716                 catch (TabException ex)
12717                 {
12718                     MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12719                 }
12720             }
12721         }
12722
12723         /// <summary>
12724         /// 指定されたツイートに対する関連発言タブを開きます
12725         /// </summary>
12726         /// <param name="statusId">表示するツイートのID</param>
12727         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12728         private async Task OpenRelatedTab(long statusId)
12729         {
12730             var post = this._statuses[statusId];
12731             if (post == null)
12732             {
12733                 try
12734                 {
12735                     post = await this.tw.GetStatusApi(false, statusId);
12736                 }
12737                 catch (WebApiException ex)
12738                 {
12739                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
12740                     return;
12741                 }
12742             }
12743
12744             await this.OpenRelatedTab(post);
12745         }
12746
12747         /// <summary>
12748         /// 指定されたツイートに対する関連発言タブを開きます
12749         /// </summary>
12750         /// <param name="post">表示する対象となるツイート</param>
12751         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12752         private async Task OpenRelatedTab(PostClass post)
12753         {
12754             var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12755             string tabName;
12756
12757             if (tabRelated == null)
12758             {
12759                 tabName = this._statuses.MakeTabName("Related Tweets");
12760
12761                 tabRelated = new TabClass(tabName, MyCommon.TabUsageType.Related);
12762                 tabRelated.UnreadManage = false;
12763                 tabRelated.Notify = false;
12764
12765                 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12766                 this._statuses.AddTab(tabRelated);
12767             }
12768             else
12769             {
12770                 tabName = tabRelated.TabName;
12771             }
12772
12773             tabRelated.RelationTargetPost = post;
12774             this.ClearTab(tabName, false);
12775
12776             for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12777             {
12778                 var tabPage = this.ListTab.TabPages[i];
12779                 if (tabName == tabPage.Text)
12780                 {
12781                     this.ListTab.SelectedIndex = i;
12782                     break;
12783                 }
12784             }
12785
12786             await this.GetRelatedTweetsAsync(tabRelated);
12787         }
12788
12789         private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12790         {
12791             StringBuilder buf = new StringBuilder();
12792             //buf.AppendFormat("キャッシュメモリ容量         : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12793             //buf.AppendFormat("物理メモリ使用割合           : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12794             buf.AppendFormat("キャッシュエントリ保持数     : {0}" + Environment.NewLine, IconCache.CacheCount);
12795             buf.AppendFormat("キャッシュエントリ破棄数     : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12796             MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12797         }
12798
12799         private void tw_UserIdChanged()
12800         {
12801             this.ModifySettingCommon = true;
12802         }
12803
12804 #region "Userstream"
12805         private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12806         {
12807             try
12808             {
12809                 if (InvokeRequired && !IsDisposed)
12810                 {
12811                     Invoke((Action) (async () =>
12812                            {
12813                                this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
12814                                if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12815                                {
12816                                    this.PurgeListViewItemCache();
12817                                    ((DetailsListView)_curTab.Tag).Update();
12818                                    if (_curPost != null && _curPost.StatusId == e.StatusId)
12819                                        await this.DispSelectedPost(true);
12820                                }
12821                            }));
12822                     return;
12823                 }
12824             }
12825             catch (ObjectDisposedException)
12826             {
12827                 return;
12828             }
12829             catch (InvalidOperationException)
12830             {
12831                 return;
12832             }
12833         }
12834
12835         private int userStreamsRefreshing = 0;
12836
12837         private async void tw_NewPostFromStream(object sender, EventArgs e)
12838         {
12839             if (this._cfgCommon.ReadOldPosts)
12840             {
12841                 _statuses.SetReadHomeTab(); //新着時未読クリア
12842             }
12843
12844             int rsltAddCount = _statuses.DistributePosts();
12845
12846             this.UpdateTimelineSpeed(rsltAddCount);
12847
12848             if (this._cfgCommon.UserstreamPeriod > 0) return;
12849
12850             // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
12851             if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
12852             {
12853                 try
12854                 {
12855                     await this.InvokeAsync(() => this.RefreshTimeline())
12856                         .ConfigureAwait(false);
12857                 }
12858                 finally
12859                 {
12860                     Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
12861                 }
12862             }
12863         }
12864
12865         private void tw_UserStreamStarted(object sender, EventArgs e)
12866         {
12867             try
12868             {
12869                 if (InvokeRequired && !IsDisposed)
12870                 {
12871                     Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12872                     return;
12873                 }
12874             }
12875             catch (ObjectDisposedException)
12876             {
12877                 return;
12878             }
12879             catch (InvalidOperationException)
12880             {
12881                 return;
12882             }
12883
12884             this.RefreshUserStreamsMenu();
12885             this.MenuItemUserStream.Enabled = true;
12886
12887             StatusLabel.Text = "UserStream Started.";
12888         }
12889
12890         private void tw_UserStreamStopped(object sender, EventArgs e)
12891         {
12892             try
12893             {
12894                 if (InvokeRequired && !IsDisposed)
12895                 {
12896                     Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12897                     return;
12898                 }
12899             }
12900             catch (ObjectDisposedException)
12901             {
12902                 return;
12903             }
12904             catch (InvalidOperationException)
12905             {
12906                 return;
12907             }
12908
12909             this.RefreshUserStreamsMenu();
12910             this.MenuItemUserStream.Enabled = true;
12911
12912             StatusLabel.Text = "UserStream Stopped.";
12913         }
12914
12915         private void RefreshUserStreamsMenu()
12916         {
12917             if (this.tw.UserStreamActive)
12918             {
12919                 this.MenuItemUserStream.Text = "&UserStream ▶";
12920                 this.StopToolStripMenuItem.Text = "&Stop";
12921             }
12922             else
12923             {
12924                 this.MenuItemUserStream.Text = "&UserStream ■";
12925                 this.StopToolStripMenuItem.Text = "&Start";
12926             }
12927         }
12928
12929         private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12930         {
12931             try
12932             {
12933                 if (InvokeRequired && !IsDisposed)
12934                 {
12935                     Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12936                     return;
12937                 }
12938             }
12939             catch (ObjectDisposedException)
12940             {
12941                 return;
12942             }
12943             catch (InvalidOperationException)
12944             {
12945                 return;
12946             }
12947             var ev = e.EventData;
12948             StatusLabel.Text = "Event: " + ev.Event;
12949             //if (ev.Event == "favorite")
12950             //{
12951             //    NotifyFavorite(ev);
12952             //}
12953             NotifyEvent(ev);
12954             if (ev.Event == "favorite" || ev.Event == "unfavorite")
12955             {
12956                 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12957                 {
12958                     this.PurgeListViewItemCache();
12959                     ((DetailsListView)_curTab.Tag).Update();
12960                 }
12961                 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
12962                 {
12963                     var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
12964                     favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
12965                 }
12966             }
12967         }
12968
12969         private void NotifyEvent(Twitter.FormattedEvent ev)
12970         {
12971             //新着通知 
12972             if (BalloonRequired(ev))
12973             {
12974                 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
12975                 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
12976                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
12977                 StringBuilder title = new StringBuilder();
12978                 if (this._cfgCommon.DispUsername)
12979                 {
12980                     title.Append(tw.Username);
12981                     title.Append(" - ");
12982                 }
12983                 else
12984                 {
12985                     //title.Clear();
12986                 }
12987                 title.Append(Application.ProductName);
12988                 title.Append(" [");
12989                 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
12990                 title.Append("] by ");
12991                 if (!string.IsNullOrEmpty(ev.Username))
12992                 {
12993                     title.Append(ev.Username.ToString());
12994                 }
12995                 else
12996                 {
12997                     //title.Append("");
12998                 }
12999                 string text;
13000                 if (!string.IsNullOrEmpty(ev.Target))
13001                 {
13002                     //NotifyIcon1.BalloonTipText = ev.Target;
13003                     text = ev.Target;
13004                 }
13005                 else
13006                 {
13007                     //NotifyIcon1.BalloonTipText = " ";
13008                     text = " ";
13009                 }
13010                 //NotifyIcon1.ShowBalloonTip(500);
13011                 if (this._cfgCommon.IsUseNotifyGrowl)
13012                 {
13013                     gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13014                               ev.Id.ToString(), title.ToString(), text);
13015                 }
13016                 else
13017                 {
13018                     NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13019                     NotifyIcon1.BalloonTipTitle = title.ToString();
13020                     NotifyIcon1.BalloonTipText = text;
13021                     NotifyIcon1.ShowBalloonTip(500);
13022                 }
13023             }
13024
13025             //サウンド再生
13026             string snd = this._cfgCommon.EventSoundFile;
13027             if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13028             {
13029                 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13030                 {
13031                     try
13032                     {
13033                         string dir = Application.StartupPath;
13034                         if (Directory.Exists(Path.Combine(dir, "Sounds")))
13035                         {
13036                             dir = Path.Combine(dir, "Sounds");
13037                         }
13038                         using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13039                         {
13040                             player.Play();
13041                         }
13042                     }
13043                     catch (Exception)
13044                     {
13045                     }
13046                 }
13047             }
13048         }
13049
13050         private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13051         {
13052             MenuItemUserStream.Enabled = false;
13053             if (StopRefreshAllMenuItem.Checked)
13054             {
13055                 StopRefreshAllMenuItem.Checked = false;
13056                 return;
13057             }
13058             if (this.tw.UserStreamActive)
13059             {
13060                 tw.StopUserStream();
13061             }
13062             else
13063             {
13064                 tw.StartUserStream();
13065             }
13066         }
13067
13068         private static string inputTrack = "";
13069
13070         private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13071         {
13072             if (TrackToolStripMenuItem.Checked)
13073             {
13074                 using (InputTabName inputForm = new InputTabName())
13075                 {
13076                     inputForm.TabName = inputTrack;
13077                     inputForm.FormTitle = "Input track word";
13078                     inputForm.FormDescription = "Track word";
13079                     if (inputForm.ShowDialog() != DialogResult.OK)
13080                     {
13081                         TrackToolStripMenuItem.Checked = false;
13082                         return;
13083                     }
13084                     inputTrack = inputForm.TabName.Trim();
13085                 }
13086                 if (!inputTrack.Equals(tw.TrackWord))
13087                 {
13088                     tw.TrackWord = inputTrack;
13089                     this.ModifySettingCommon = true;
13090                     TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13091                     tw.ReconnectUserStream();
13092                 }
13093             }
13094             else
13095             {
13096                 tw.TrackWord = "";
13097                 tw.ReconnectUserStream();
13098             }
13099             this.ModifySettingCommon = true;
13100         }
13101
13102         private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13103         {
13104             tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13105             this.ModifySettingCommon = true;
13106             tw.ReconnectUserStream();
13107         }
13108
13109         private void EventViewerMenuItem_Click(object sender, EventArgs e)
13110         {
13111             if (evtDialog == null || evtDialog.IsDisposed)
13112             {
13113                 evtDialog = null;
13114                 evtDialog = new EventViewerDialog();
13115                 evtDialog.Owner = this;
13116                 //親の中央に表示
13117                 Point pos = evtDialog.Location;
13118                 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13119                 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13120                 evtDialog.Location = pos;
13121             }
13122             evtDialog.EventSource = tw.StoredEvent;
13123             if (!evtDialog.Visible)
13124             {
13125                 evtDialog.Show(this);
13126             }
13127             else
13128             {
13129                 evtDialog.Activate();
13130             }
13131             this.TopMost = this._cfgCommon.AlwaysTop;
13132         }
13133 #endregion
13134
13135         private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13136         {
13137             MyCommon._endingFlag = true;
13138             try
13139             {
13140                 this.Close();
13141                 Application.Restart();
13142             }
13143             catch (Exception)
13144             {
13145                 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13146             }
13147         }
13148
13149         private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13150         {
13151             if (!string.IsNullOrEmpty(tw.Username))
13152                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13153         }
13154
13155         private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13156         {
13157             await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
13158         }
13159
13160         private async Task doTranslation(string str)
13161         {
13162             if (string.IsNullOrEmpty(str))
13163                 return;
13164
13165             var bing = new Bing();
13166             try
13167             {
13168                 var translatedText = await bing.TranslateAsync(str,
13169                     langFrom: null,
13170                     langTo: this._cfgCommon.TranslateLanguage);
13171
13172                 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13173             }
13174             catch (HttpRequestException e)
13175             {
13176                 this.StatusLabel.Text = "Err:" + e.Message;
13177             }
13178             catch (OperationCanceledException)
13179             {
13180                 this.StatusLabel.Text = "Err:Timeout";
13181             }
13182         }
13183
13184         private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13185         {
13186             if (!this.ExistCurrentPost)
13187                 return;
13188
13189             await this.doTranslation(this._curPost.TextFromApi);
13190         }
13191
13192         private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13193         {
13194             var text = this.PostBrowser.GetSelectedText();
13195             await this.doTranslation(text);
13196         }
13197
13198         private bool ExistCurrentPost
13199         {
13200             get
13201             {
13202                 if (_curPost == null) return false;
13203                 if (_curPost.IsDeleted) return false;
13204                 return true;
13205             }
13206         }
13207
13208         private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13209         {
13210             ShowUserTimeline();
13211         }
13212
13213         private string GetUserIdFromCurPostOrInput(string caption)
13214         {
13215             var id = _curPost?.ScreenName ?? "";
13216
13217             using (InputTabName inputName = new InputTabName())
13218             {
13219                 inputName.FormTitle = caption;
13220                 inputName.FormDescription = Properties.Resources.FRMessage1;
13221                 inputName.TabName = id;
13222                 if (inputName.ShowDialog() == DialogResult.OK &&
13223                     !string.IsNullOrEmpty(inputName.TabName.Trim()))
13224                 {
13225                     id = inputName.TabName.Trim();
13226                 }
13227                 else
13228                 {
13229                     id = "";
13230                 }
13231             }
13232             return id;
13233         }
13234
13235         private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13236         {
13237             string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13238             if (!string.IsNullOrEmpty(id))
13239             {
13240                 AddNewTabForUserTimeline(id);
13241             }
13242         }
13243
13244         private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13245         {
13246             string id = GetUserIdFromCurPostOrInput("Show Favstar");
13247             if (!string.IsNullOrEmpty(id))
13248             {
13249                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13250             }
13251         }
13252
13253         private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13254         {
13255             if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13256         }
13257
13258         private void TimelineRefreshEnableChange(bool isEnable)
13259         {
13260             if (isEnable)
13261             {
13262                 tw.StartUserStream();
13263             }
13264             else
13265             {
13266                 tw.StopUserStream();
13267             }
13268             TimerTimeline.Enabled = isEnable;
13269         }
13270
13271         private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13272         {
13273             TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13274         }
13275
13276         private async Task OpenUserAppointUrl()
13277         {
13278             if (this._cfgCommon.UserAppointUrl != null)
13279             {
13280                 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13281                 {
13282                     if (_curPost != null)
13283                     {
13284                         string xUrl = this._cfgCommon.UserAppointUrl;
13285                         xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13286
13287                         var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
13288                         xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
13289
13290                         await this.OpenUriInBrowserAsync(xUrl);
13291                     }
13292                 }
13293                 else
13294                 {
13295                     await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
13296                 }
13297             }
13298         }
13299
13300         private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13301         {
13302             await this.OpenUserAppointUrl();
13303         }
13304
13305         private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13306         {
13307             string selText = SourceLinkLabel.Text;
13308             try
13309             {
13310                 Clipboard.SetDataObject(selText, false, 5, 100);
13311             }
13312             catch (Exception ex)
13313             {
13314                 MessageBox.Show(ex.Message);
13315             }
13316         }
13317
13318         private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13319         {
13320             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
13321             try
13322             {
13323                 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
13324             }
13325             catch (Exception ex)
13326             {
13327                 MessageBox.Show(ex.Message);
13328             }
13329         }
13330
13331         private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13332         {
13333             if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13334             {
13335                 SourceCopyMenuItem.Enabled = false;
13336                 SourceUrlCopyMenuItem.Enabled = false;
13337             }
13338             else
13339             {
13340                 SourceCopyMenuItem.Enabled = true;
13341                 SourceUrlCopyMenuItem.Enabled = true;
13342             }
13343         }
13344
13345         private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13346         {
13347             if (Form.ActiveForm == null)
13348             {
13349                 this.BeginInvoke((Action) (() =>
13350                 {
13351                     this.Visible = true;
13352                     if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13353                     this.Activate();
13354                     this.BringToFront();
13355                     if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13356                     {
13357                         if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13358                     }
13359                     else
13360                     {
13361                         if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13362                     }
13363                 }));
13364             }
13365         }
13366
13367         private void ReplaceAppName()
13368         {
13369             MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13370             AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13371         }
13372
13373         private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13374         {
13375             this.SplitContainer3.Panel2Collapsed = false;
13376         }
13377
13378         private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13379         {
13380             await this.OpenThumbnailPicture(e.Thumbnail);
13381         }
13382
13383         private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13384         {
13385             await this.OpenUriInBrowserAsync(e.ImageUrl);
13386         }
13387
13388         private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13389         {
13390             var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
13391
13392             await this.OpenUriInBrowserAsync(url);
13393         }
13394
13395         private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13396         {
13397             await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13398         }
13399
13400         private void PostButton_KeyDown(object sender, KeyEventArgs e)
13401         {
13402             if (e.KeyCode == Keys.Space)
13403             {
13404                 this.JumpUnreadMenuItem_Click(null, null);
13405
13406                 e.SuppressKeyPress = true;
13407             }
13408         }
13409
13410         private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13411         {
13412             this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13413             this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13414             this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13415             this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13416             this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13417
13418             this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13419         }
13420
13421         private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13422         {
13423             ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13424         }
13425
13426         private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13427         {
13428             ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13429         }
13430
13431         private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13432         {
13433             ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13434         }
13435
13436         private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13437         {
13438             ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13439         }
13440
13441         private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13442         {
13443             ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13444         }
13445
13446         private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13447         {
13448             if (this._cfgCommon.IconSize == iconSize) return;
13449
13450             var oldIconCol = _iconCol;
13451
13452             this._cfgCommon.IconSize = iconSize;
13453             ApplyListViewIconSize(iconSize);
13454
13455             if (_iconCol != oldIconCol)
13456             {
13457                 foreach (TabPage tp in ListTab.TabPages)
13458                 {
13459                     ResetColumns((DetailsListView)tp.Tag);
13460                 }
13461             }
13462
13463             _curList?.Refresh();
13464
13465             ModifySettingCommon = true;
13466         }
13467
13468         private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13469         {
13470             var state = this.LockListSortOrderToolStripMenuItem.Checked;
13471             if (this._cfgCommon.SortOrderLock == state) return;
13472
13473             this._cfgCommon.SortOrderLock = state;
13474
13475             ModifySettingCommon = true;
13476         }
13477     }
13478 }