OSDN Git Service

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