OSDN Git Service

プロパティを書き込み専用にしない (CA1044)
[opentween/open-tween.git] / OpenTween / Tween.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 //           (c) 2008-2011 Moz (@syo68k)
4 //           (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 //           (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 //           (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 //           (c) 2011      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
9 // 
10 // This file is part of OpenTween.
11 // 
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
15 // any later version.
16 // 
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
20 // for more details. 
21 // 
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
26
27 //コンパイル後コマンド
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
30
31 using System;
32 using System.Collections.Concurrent;
33 using System.Collections.Generic;
34 using System.ComponentModel;
35 using System.Diagnostics;
36 using System.Drawing;
37 using System.IO;
38 using System.Linq;
39 using System.Media;
40 using System.Net;
41 using System.Net.Http;
42 using System.Reflection;
43 using System.Text;
44 using System.Text.RegularExpressions;
45 using System.Threading;
46 using System.Threading.Tasks;
47 using System.Windows.Forms;
48 using OpenTween.Api;
49 using OpenTween.Connection;
50 using OpenTween.OpenTweenCustomControl;
51 using OpenTween.Thumbnail;
52
53 namespace OpenTween
54 {
55     public partial class TweenMain : OTBaseForm
56     {
57         //各種設定
58         private Size _mySize;           //画面サイズ
59         private Point _myLoc;           //画面位置
60         private int _mySpDis;           //区切り位置
61         private int _mySpDis2;          //発言欄区切り位置
62         private int _mySpDis3;          //プレビュー区切り位置
63         private int _iconSz;            //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
64         private bool _iconCol;          //1列表示の時true(48サイズのとき)
65
66         //雑多なフラグ類
67         private bool _initial;         //true:起動時処理中
68         private bool _initialLayout = true;
69         private bool _ignoreConfigSave;         //true:起動時処理中
70         private bool _tabDrag;           //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
71         private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
72         private Point _tabMouseDownPoint;
73         private string _rclickTabName;      //右クリックしたタブの名前(Tabコントロール機能不足対応)
74         private readonly object _syncObject = new object();    //ロック用
75
76         private const string detailHtmlFormatHeaderMono = 
77             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
78             + "<style type=\"text/css\"><!-- "
79             + "body, p, pre {margin: 0;} "
80             + "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%);} "
81             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
82             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
83             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
84             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
85             + "--></style>"
86             + "</head><body><pre>";
87         private const string detailHtmlFormatFooterMono = "</pre></body></html>";
88         private const string detailHtmlFormatHeaderColor = 
89             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
90             + "<style type=\"text/css\"><!-- "
91             + "body, p, pre {margin: 0;} "
92             + "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%);} "
93             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
94             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
95             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
96             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
97             + "--></style>"
98             + "</head><body><p>";
99         private const string detailHtmlFormatFooterColor = "</p></body></html>";
100         private string detailHtmlFormatHeader;
101         private string detailHtmlFormatFooter;
102
103         private bool _myStatusError = false;
104         private bool _myStatusOnline = false;
105         private bool soundfileListup = false;
106         private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
107
108         //設定ファイル関連
109         //private SettingToConfig _cfg; //旧
110         private SettingLocal _cfgLocal;
111         private SettingCommon _cfgCommon;
112
113         //twitter解析部
114         private Twitter tw = new Twitter();
115
116         //Growl呼び出し部
117         private GrowlHelper gh = new GrowlHelper(Application.ProductName);
118
119         //サブ画面インスタンス
120         private SearchWordDialog SearchDialog = new SearchWordDialog();     //検索画面インスタンス
121         private OpenURL UrlDialog = new OpenURL();
122         public AtIdSupplement AtIdSupl;     //@id補助
123         public AtIdSupplement HashSupl;    //Hashtag補助
124         public HashtagManage HashMgr;
125         private EventViewerDialog evtDialog;
126
127         //表示フォント、色、アイコン
128         private Font _fntUnread;            //未読用フォント
129         private Color _clUnread;            //未読用文字色
130         private Font _fntReaded;            //既読用フォント
131         private Color _clReaded;            //既読用文字色
132         private Color _clFav;               //Fav用文字色
133         private Color _clOWL;               //片思い用文字色
134         private Color _clRetweet;               //Retweet用文字色
135         private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText);         //選択中の行用文字色
136         private Font _fntDetail;            //発言詳細部用フォント
137         private Color _clDetail;              //発言詳細部用色
138         private Color _clDetailLink;          //発言詳細部用リンク文字色
139         private Color _clDetailBackcolor;     //発言詳細部用背景色
140         private Color _clSelf;              //自分の発言用背景色
141         private Color _clAtSelf;            //自分宛返信用背景色
142         private Color _clTarget;            //選択発言者の他の発言用背景色
143         private Color _clAtTarget;          //選択発言中の返信先用背景色
144         private Color _clAtFromTarget;      //選択発言者への返信発言用背景色
145         private Color _clAtTo;              //選択発言の唯一@先
146         private Color _clListBackcolor;       //リスト部通常発言背景色
147         private Color _clInputBackcolor;      //入力欄背景色
148         private Color _clInputFont;           //入力欄文字色
149         private Font _fntInputFont;           //入力欄フォント
150         private ImageCache IconCache;        //アイコン画像リスト
151         private Icon NIconAt;               //At.ico             タスクトレイアイコン:通常時
152         private Icon NIconAtRed;            //AtRed.ico          タスクトレイアイコン:通信エラー時
153         private Icon NIconAtSmoke;          //AtSmoke.ico        タスクトレイアイコン:オフライン時
154         private Icon[] NIconRefresh = new Icon[4];       //Refresh.ico        タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
155         private Icon TabIcon;               //Tab.ico            未読のあるタブ用アイコン
156         private Icon MainIcon;              //Main.ico           画面左上のアイコン
157         private Icon ReplyIcon;               //5g
158         private Icon ReplyIconBlink;          //6g
159
160         private ImageList _listViewImageList = new ImageList();    //ListViewItemの高さ変更用
161
162         private PostClass _anchorPost;
163         private bool _anchorFlag;        //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
164
165         private List<PostingStatus> _history = new List<PostingStatus>();   //発言履歴
166         private int _hisIdx;                  //発言履歴カレントインデックス
167
168         //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
169         private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
170
171         //時速表示用
172         private List<DateTime> _postTimestamps = new List<DateTime>();
173         private List<DateTime> _favTimestamps = new List<DateTime>();
174         private ConcurrentDictionary<DateTime, int> _tlTimestamps = new ConcurrentDictionary<DateTime, int>();
175         private int _tlCount;
176
177         // 以下DrawItem関連
178         private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
179         private SolidBrush _brsBackColorMine;
180         private SolidBrush _brsBackColorAt;
181         private SolidBrush _brsBackColorYou;
182         private SolidBrush _brsBackColorAtYou;
183         private SolidBrush _brsBackColorAtFromTarget;
184         private SolidBrush _brsBackColorAtTo;
185         private SolidBrush _brsBackColorNone;
186         private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
187         private StringFormat sfTab = new StringFormat();
188
189         //////////////////////////////////////////////////////////////////////////////////////////////////////////
190         private TabInformations _statuses;
191
192         /// <summary>
193         /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
194         /// </summary>
195         /// <remarks>
196         /// キャッシュクリアのために null が代入されることがあるため、
197         /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
198         /// 一旦ローカル変数に代入してから参照すること。
199         /// </remarks>
200         private ListViewItemCache _listItemCache = null;
201
202         internal class ListViewItemCache
203         {
204             /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
205             public ListView TargetList { get; set; }
206
207             /// <summary>キャッシュする範囲の開始インデックス</summary>
208             public int StartIndex { get; set; }
209
210             /// <summary>キャッシュする範囲の終了インデックス</summary>
211             public int EndIndex { get; set; }
212
213             /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
214             public ListViewItem[] ListItem { get; set; }
215
216             /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
217             public PostClass[] Post { get; set; }
218
219             /// <summary>キャッシュされたアイテムの件数</summary>
220             public int Count
221                 => this.EndIndex - this.StartIndex + 1;
222
223             /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
224             /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
225             public bool Contains(int index)
226                 => index >= this.StartIndex && index <= this.EndIndex;
227
228             /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
229             /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
230             public bool IsSupersetOf(int rangeStart, int rangeEnd)
231                 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
232
233             /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
234             /// <returns>取得に成功すれば true、それ以外は false</returns>
235             public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
236             {
237                 if (this.Contains(index))
238                 {
239                     item = this.ListItem[index - this.StartIndex];
240                     post = this.Post[index - this.StartIndex];
241                     return true;
242                 }
243                 else
244                 {
245                     item = null;
246                     post = null;
247                     return false;
248                 }
249             }
250         }
251
252         private TabPage _curTab;
253         private int _curItemIndex;
254         private DetailsListView _curList;
255         private PostClass _curPost;
256         private bool _isColumnChanged = false;
257
258         private const int MAX_WORKER_THREADS = 20;
259         private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
260         private CancellationTokenSource workerCts = new CancellationTokenSource();
261
262         private int UnreadCounter = -1;
263         private int UnreadAtCounter = -1;
264
265         private string[] ColumnOrgText = new string[9];
266         private string[] ColumnText = new string[9];
267
268         private bool _DoFavRetweetFlags = false;
269         private bool osResumed = false;
270
271         //////////////////////////////////////////////////////////////////////////////////////////////////////////
272         private string _postBrowserStatusText = "";
273
274         private bool _colorize = false;
275
276         private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
277
278         private ImageListViewItem displayItem;
279
280         private string recommendedStatusFooter;
281
282         //URL短縮のUndo用
283         private struct urlUndo
284         {
285             public string Before;
286             public string After;
287         }
288
289         private List<urlUndo> urlUndoBuffer = null;
290
291         private struct ReplyChain
292         {
293             public long OriginalId;
294             public long InReplyToId;
295             public TabPage OriginalTab;
296
297             public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
298             {
299                 this.OriginalId = originalId;
300                 this.InReplyToId = inReplyToId;
301                 this.OriginalTab = originalTab;
302             }
303         }
304
305         private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
306         private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
307
308         //検索処理タイプ
309         private enum SEARCHTYPE
310         {
311             DialogSearch,
312             NextSearch,
313             PrevSearch,
314         }
315
316         private class PostingStatus
317         {
318             public string status = "";
319             public long? inReplyToId = null;
320             public string inReplyToName = null;
321             public string imageService = "";      //画像投稿サービス名
322             public IMediaItem[] mediaItems = null;
323             public PostingStatus()
324             {
325             }
326             public PostingStatus(string status, long? replyToId, string replyToName)
327             {
328                 this.status = status;
329                 this.inReplyToId = replyToId;
330                 this.inReplyToName = replyToName;
331             }
332         }
333
334         private void TweenMain_Activated(object sender, EventArgs e)
335         {
336             //画面がアクティブになったら、発言欄の背景色戻す
337             if (StatusText.Focused)
338             {
339                 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
340             }
341         }
342
343         private bool disposed = false;
344
345         /// <summary>
346         /// 使用中のリソースをすべてクリーンアップします。
347         /// </summary>
348         /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
349         protected override void Dispose(bool disposing)
350         {
351             base.Dispose(disposing);
352
353             if (this.disposed)
354                 return;
355
356             if (disposing)
357             {
358                 this.components?.Dispose();
359
360                 //後始末
361                 SearchDialog.Dispose();
362                 UrlDialog.Dispose();
363                 NIconAt?.Dispose();
364                 NIconAtRed?.Dispose();
365                 NIconAtSmoke?.Dispose();
366                 foreach (var iconRefresh in this.NIconRefresh)
367                 {
368                     iconRefresh?.Dispose();
369                 }
370                 TabIcon?.Dispose();
371                 MainIcon?.Dispose();
372                 ReplyIcon?.Dispose();
373                 ReplyIconBlink?.Dispose();
374                 _listViewImageList.Dispose();
375                 _brsHighLight.Dispose();
376                 _brsBackColorMine?.Dispose();
377                 _brsBackColorAt?.Dispose();
378                 _brsBackColorYou?.Dispose();
379                 _brsBackColorAtYou?.Dispose();
380                 _brsBackColorAtFromTarget?.Dispose();
381                 _brsBackColorAtTo?.Dispose();
382                 _brsBackColorNone?.Dispose();
383                 _brsDeactiveSelection?.Dispose();
384                 //sf.Dispose();
385                 sfTab.Dispose();
386
387                 this.workerCts.Cancel();
388
389                 if (IconCache != null)
390                 {
391                     this.IconCache.CancelAsync();
392                     this.IconCache.Dispose();
393                 }
394
395                 this.thumbnailTokenSource?.Dispose();
396
397                 this.tw.Dispose();
398                 this._hookGlobalHotkey.Dispose();
399             }
400
401             // 終了時にRemoveHandlerしておかないとメモリリークする
402             // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
403             Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
404
405             this.disposed = true;
406         }
407
408         private void LoadIcons()
409         {
410             // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
411             var iconsDir = Path.Combine(Application.StartupPath, "Icons");
412
413             // ウィンドウ左上のアイコン
414             var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
415
416             // タブ見出し未読表示アイコン
417             var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
418
419             // タスクトレイ: 通常時アイコン
420             var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
421
422             // タスクトレイ: エラー時アイコン
423             var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
424
425             // タスクトレイ: オフライン時アイコン
426             var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
427
428             // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
429             var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
430             var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
431
432             // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
433             var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
434             var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
435             var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
436             var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
437
438             // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
439
440             this.MainIcon = iconMain ?? Properties.Resources.MIcon;
441             this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
442             this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
443             this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
444             this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
445
446             if (iconReply != null && iconReplyBlink != null)
447             {
448                 this.ReplyIcon = iconReply;
449                 this.ReplyIconBlink = iconReplyBlink;
450             }
451             else
452             {
453                 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
454                 this.ReplyIconBlink = this.NIconAt;
455             }
456
457             if (iconRefresh1 == null)
458             {
459                 this.NIconRefresh = new[] {
460                     Properties.Resources.Refresh, Properties.Resources.Refresh2,
461                     Properties.Resources.Refresh3, Properties.Resources.Refresh4,
462                 };
463             }
464             else if (iconRefresh2 == null)
465             {
466                 this.NIconRefresh = new[] { iconRefresh1 };
467             }
468             else if (iconRefresh3 == null)
469             {
470                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
471             }
472             else if (iconRefresh4 == null)
473             {
474                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
475             }
476             else // iconRefresh1 から iconRefresh4 まで全て揃っている
477             {
478                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
479             }
480         }
481
482         private Icon LoadIcon(string filePath)
483         {
484             if (!File.Exists(filePath))
485                 return null;
486
487             try
488             {
489                 return new Icon(filePath);
490             }
491             catch (Exception)
492             {
493                 return null;
494             }
495         }
496
497         private void InitColumns(ListView list, bool startup)
498         {
499             this.InitColumnText();
500
501             ColumnHeader[] columns;
502             if (this._iconCol)
503             {
504                 columns = new[]
505                 {
506                     new ColumnHeader { Text = this.ColumnText[0], Width = 48 }, // アイコン
507                     new ColumnHeader { Text = this.ColumnText[2], Width = 300 },  // 本文
508                 };
509
510                 if (startup)
511                 {
512                     var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
513
514                     columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
515                     columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
516                     columns[0].DisplayIndex = 0;
517                     columns[1].DisplayIndex = 1;
518                 }
519                 else
520                 {
521                     var idx = 0;
522                     foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
523                     {
524                         columns[idx].Width = curListColumn.Width;
525                         columns[idx].DisplayIndex = curListColumn.DisplayIndex;
526                         idx++;
527                     }
528                 }
529             }
530             else
531             {
532                 columns = new[]
533                 {
534                     new ColumnHeader { Text = this.ColumnText[0], Width = 48 }, // アイコン
535                     new ColumnHeader { Text = this.ColumnText[1], Width = 80 }, // ニックネーム
536                     new ColumnHeader { Text = this.ColumnText[2], Width = 300 }, // 本文
537                     new ColumnHeader { Text = this.ColumnText[3], Width = 50 }, // 日付
538                     new ColumnHeader { Text = this.ColumnText[4], Width = 50 }, // ユーザID
539                     new ColumnHeader { Text = this.ColumnText[5], Width = 16 }, // 未読
540                     new ColumnHeader { Text = this.ColumnText[6], Width = 16 }, // マーク&プロテクト
541                     new ColumnHeader { Text = this.ColumnText[7], Width = 50 }, // ソース
542                 };
543
544                 if (startup)
545                 {
546                     var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
547
548                     columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
549                     columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
550                     columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
551                     columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
552                     columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
553                     columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
554                     columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
555                     columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
556
557                     var displayIndex = new[] {
558                         this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
559                         this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
560                         this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
561                         this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
562                     };
563
564                     foreach (var i in Enumerable.Range(0, displayIndex.Length))
565                     {
566                         columns[i].DisplayIndex = displayIndex[i];
567                     }
568                 }
569                 else
570                 {
571                     var idx = 0;
572                     foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
573                     {
574                         columns[idx].Width = curListColumn.Width;
575                         columns[idx].DisplayIndex = curListColumn.DisplayIndex;
576                         idx++;
577                     }
578                 }
579             }
580
581             list.Columns.AddRange(columns);
582         }
583
584         private void InitColumnText()
585         {
586             ColumnText[0] = "";
587             ColumnText[1] = Properties.Resources.AddNewTabText2;
588             ColumnText[2] = Properties.Resources.AddNewTabText3;
589             ColumnText[3] = Properties.Resources.AddNewTabText4_2;
590             ColumnText[4] = Properties.Resources.AddNewTabText5;
591             ColumnText[5] = "";
592             ColumnText[6] = "";
593             ColumnText[7] = "Source";
594
595             ColumnOrgText[0] = "";
596             ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
597             ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
598             ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
599             ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
600             ColumnOrgText[5] = "";
601             ColumnOrgText[6] = "";
602             ColumnOrgText[7] = "Source";
603
604             int c = 0;
605             switch (_statuses.SortMode)
606             {
607                 case ComparerMode.Nickname:  //ニックネーム
608                     c = 1;
609                     break;
610                 case ComparerMode.Data:  //本文
611                     c = 2;
612                     break;
613                 case ComparerMode.Id:  //時刻=発言Id
614                     c = 3;
615                     break;
616                 case ComparerMode.Name:  //名前
617                     c = 4;
618                     break;
619                 case ComparerMode.Source:  //Source
620                     c = 7;
621                     break;
622             }
623
624             if (_iconCol)
625             {
626                 if (_statuses.SortOrder == SortOrder.Descending)
627                 {
628                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
629                     ColumnText[2] = ColumnOrgText[2] + "▾";
630                 }
631                 else
632                 {
633                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
634                     ColumnText[2] = ColumnOrgText[2] + "▴";
635                 }
636             }
637             else
638             {
639                 if (_statuses.SortOrder == SortOrder.Descending)
640                 {
641                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
642                     ColumnText[c] = ColumnOrgText[c] + "▾";
643                 }
644                 else
645                 {
646                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
647                     ColumnText[c] = ColumnOrgText[c] + "▴";
648                 }
649             }
650         }
651
652         private void InitializeTraceFrag()
653         {
654 #if DEBUG
655             TraceOutToolStripMenuItem.Checked = true;
656             MyCommon.TraceFlag = true;
657 #endif
658             if (!MyCommon.FileVersion.EndsWith("0"))
659             {
660                 TraceOutToolStripMenuItem.Checked = true;
661                 MyCommon.TraceFlag = true;
662             }
663         }
664
665         private void TweenMain_Load(object sender, EventArgs e)
666         {
667             _ignoreConfigSave = true;
668             this.Visible = false;
669
670             if (MyApplication.StartupOptions.ContainsKey("d"))
671                 MyCommon.TraceFlag = true;
672
673             InitializeTraceFrag();
674
675             //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
676
677             new InternetSecurityManager(PostBrowser);
678             this.PostBrowser.AllowWebBrowserDrop = false;  // COMException を回避するため、ActiveX の初期化が終わってから設定する
679
680             MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
681             Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
682
683             Regex.CacheSize = 100;
684
685             //発言保持クラス
686             _statuses = TabInformations.GetInstance();
687
688             //アイコン設定
689             LoadIcons();
690             this.Icon = MainIcon;              //メインフォーム(TweenMain)
691             NotifyIcon1.Icon = NIconAt;      //タスクトレイ
692             TabImage.Images.Add(TabIcon);    //タブ見出し
693
694             //<<<<<<<<<設定関連>>>>>>>>>
695             ////設定読み出し
696             LoadConfig();
697
698             // 現在の DPI と設定保存時の DPI との比を取得する
699             var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
700
701             // UIフォント設定
702             var fontUIGlobal = this._cfgLocal.FontUIGlobal;
703             if (fontUIGlobal != null)
704             {
705                 OTBaseForm.GlobalFont = fontUIGlobal;
706                 this.Font = fontUIGlobal;
707             }
708
709             //不正値チェック
710             if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
711             {
712                 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
713                     this._cfgCommon.TimelinePeriod = 15;
714
715                 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
716                     this._cfgCommon.ReplyPeriod = 15;
717
718                 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
719                     this._cfgCommon.DMPeriod = 15;
720
721                 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
722                     this._cfgCommon.PubSearchPeriod = 30;
723
724                 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
725                     this._cfgCommon.UserTimelinePeriod = 15;
726
727                 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
728                     this._cfgCommon.ListsPeriod = 15;
729             }
730
731             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
732                 this._cfgCommon.CountApi = 60;
733             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
734                 this._cfgCommon.CountApiReply = 40;
735
736             if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
737                 this._cfgCommon.MoreCountApi = 200;
738             if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
739                 this._cfgCommon.FirstCountApi = 100;
740
741             if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
742                 this._cfgCommon.FavoritesCountApi = 40;
743             if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
744                 this._cfgCommon.ListCountApi = 100;
745             if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
746                 this._cfgCommon.SearchCountApi = 100;
747             if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
748                 this._cfgCommon.UserTimelineCountApi = 20;
749
750             //廃止サービスが選択されていた場合ux.nuへ読み替え
751             if (this._cfgCommon.AutoShortUrlFirst < 0)
752                 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
753
754             HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
755
756             //認証関連
757             if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
758             tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
759
760             _initial = true;
761
762             Networking.Initialize();
763
764             bool saveRequired = false;
765             bool firstRun = false;
766
767             //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
768             if (string.IsNullOrEmpty(tw.Username))
769             {
770                 saveRequired = true;
771                 firstRun = true;
772
773                 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
774                 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
775                     string.IsNullOrEmpty(tw.Username))
776                 {
777                     Application.Exit();  //強制終了
778                     return;
779                 }
780             }
781
782             //Twitter用通信クラス初期化
783             Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
784             Networking.SetWebProxy(this._cfgLocal.ProxyType,
785                 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
786                 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
787             Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
788
789             HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
790             tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
791             tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
792             tw.TrackWord = this._cfgCommon.TrackWord;
793             TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
794             tw.AllAtReply = this._cfgCommon.AllAtReply;
795             AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
796             ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
797             ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
798             ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
799
800             // アクセストークンが有効であるか確認する
801             // ここが Twitter API への最初のアクセスになるようにすること
802             try
803             {
804                 this.tw.VerifyCredentials();
805             }
806             catch (WebApiException ex)
807             {
808                 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
809                     Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
810             }
811
812             //サムネイル関連の初期化
813             //プロキシ設定等の通信まわりの初期化が済んでから処理する
814             ThumbnailGenerator.InitializeGenerator();
815
816             var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
817             imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
818             imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
819
820             Thumbnail.Services.TonTwitterCom.InitializeOAuthToken = x =>
821                 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
822                     this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
823
824             //画像投稿サービス
825             ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
826
827             //ハッシュタグ/@id関連
828             AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
829             HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
830             HashMgr = new HashtagManage(HashSupl,
831                                     _cfgCommon.HashTags.ToArray(),
832                                     _cfgCommon.HashSelected,
833                                     _cfgCommon.HashIsPermanent,
834                                     _cfgCommon.HashIsHead,
835                                     _cfgCommon.HashIsNotAddToAtReply);
836             if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
837
838             //アイコンリスト作成
839             this.IconCache = new ImageCache();
840
841             //フォント&文字色&背景色保持
842             _fntUnread = this._cfgLocal.FontUnread;
843             _clUnread = this._cfgLocal.ColorUnread;
844             _fntReaded = this._cfgLocal.FontRead;
845             _clReaded = this._cfgLocal.ColorRead;
846             _clFav = this._cfgLocal.ColorFav;
847             _clOWL = this._cfgLocal.ColorOWL;
848             _clRetweet = this._cfgLocal.ColorRetweet;
849             _fntDetail = this._cfgLocal.FontDetail;
850             _clDetail = this._cfgLocal.ColorDetail;
851             _clDetailLink = this._cfgLocal.ColorDetailLink;
852             _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
853             _clSelf = this._cfgLocal.ColorSelf;
854             _clAtSelf = this._cfgLocal.ColorAtSelf;
855             _clTarget = this._cfgLocal.ColorTarget;
856             _clAtTarget = this._cfgLocal.ColorAtTarget;
857             _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
858             _clAtTo = this._cfgLocal.ColorAtTo;
859             _clListBackcolor = this._cfgLocal.ColorListBackcolor;
860             _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
861             _clInputFont = this._cfgLocal.ColorInputFont;
862             _fntInputFont = this._cfgLocal.FontInputFont;
863
864             _brsBackColorMine = new SolidBrush(_clSelf);
865             _brsBackColorAt = new SolidBrush(_clAtSelf);
866             _brsBackColorYou = new SolidBrush(_clTarget);
867             _brsBackColorAtYou = new SolidBrush(_clAtTarget);
868             _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
869             _brsBackColorAtTo = new SolidBrush(_clAtTo);
870             //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
871             _brsBackColorNone = new SolidBrush(_clListBackcolor);
872
873             // StringFormatオブジェクトへの事前設定
874             //sf.Alignment = StringAlignment.Near;             // Textを近くへ配置(左から右の場合は左寄せ)
875             //sf.LineAlignment = StringAlignment.Near;         // Textを近くへ配置(上寄せ)
876             //sf.FormatFlags = StringFormatFlags.LineLimit;    // 
877             sfTab.Alignment = StringAlignment.Center;
878             sfTab.LineAlignment = StringAlignment.Center;
879
880             InitDetailHtmlFormat();
881
882             //Regex statregex = new Regex("^0*");
883             this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
884
885             _history.Add(new PostingStatus());
886             _hisIdx = 0;
887             this.inReplyTo = null;
888
889             //各種ダイアログ設定
890             SearchDialog.Owner = this;
891             UrlDialog.Owner = this;
892
893             //新着バルーン通知のチェック状態設定
894             NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
895             this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
896
897             //新着取得時のリストスクロールをするか。trueならスクロールしない
898             ListLockMenuItem.Checked = _cfgCommon.ListLock;
899             this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
900             //サウンド再生(タブ別設定より優先)
901             this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
902             this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
903
904             this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
905             this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
906
907             //ウィンドウ設定
908             this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
909             _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
910             _myLoc = _cfgLocal.FormLocation;
911             //タイトルバー領域
912             if (this.WindowState != FormWindowState.Minimized)
913             {
914                 this.DesktopLocation = _cfgLocal.FormLocation;
915                 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
916                 bool outOfScreen = true;
917                 if (Screen.AllScreens.Length == 1)    //ハングするとの報告
918                 {
919                     foreach (Screen scr in Screen.AllScreens)
920                     {
921                         if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
922                         {
923                             outOfScreen = false;
924                             break;
925                         }
926                     }
927                     if (outOfScreen)
928                     {
929                         this.DesktopLocation = new Point(0, 0);
930                         _myLoc = this.DesktopLocation;
931                     }
932                 }
933             }
934             this.TopMost = this._cfgCommon.AlwaysTop;
935             _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
936             _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
937             if (_cfgLocal.PreviewDistance == -1)
938             {
939                 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
940                 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
941                 _cfgLocal.PreviewDistance = _mySpDis3;
942             }
943             else
944             {
945                 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
946             }
947             MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
948             //this.Tween_ClientSizeChanged(this, null);
949             this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
950             this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
951             //入力欄
952             StatusText.Font = _fntInputFont;
953             StatusText.ForeColor = _clInputFont;
954
955             // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
956             this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
957             this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
958
959             // NameLabel のフォントを OTBaseForm.GlobalFont に変更
960             this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
961
962             // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
963             SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
964
965             //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
966             if (this._cfgCommon.UnreadManage == false)
967             {
968                 ReadedStripMenuItem.Enabled = false;
969                 UnreadStripMenuItem.Enabled = false;
970             }
971
972             //発言詳細部の初期化
973             NameLabel.Text = "";
974             DateTimeLabel.Text = "";
975             SourceLinkLabel.Text = "";
976
977             //リンク先URL表示部の初期化(画面左下)
978             StatusLabelUrl.Text = "";
979             //状態表示部の初期化(画面右下)
980             StatusLabel.Text = "";
981             StatusLabel.AutoToolTip = false;
982             StatusLabel.ToolTipText = "";
983             //文字カウンタ初期化
984             lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
985
986             this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
987             CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
988             CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
989             CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
990
991             ////////////////////////////////////////////////////////////////////////////////
992             var sortOrder = (SortOrder)_cfgCommon.SortOrder;
993             var mode = ComparerMode.Id;
994             switch (_cfgCommon.SortColumn)
995             {
996                 case 0:    //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
997                 case 5:
998                 case 6:
999                     //ソートしない
1000                     mode = ComparerMode.Id;  //Idソートに読み替え
1001                     break;
1002                 case 1:  //ニックネーム
1003                     mode = ComparerMode.Nickname;
1004                     break;
1005                 case 2:  //本文
1006                     mode = ComparerMode.Data;
1007                     break;
1008                 case 3:  //時刻=発言Id
1009                     mode = ComparerMode.Id;
1010                     break;
1011                 case 4:  //名前
1012                     mode = ComparerMode.Name;
1013                     break;
1014                 case 7:  //Source
1015                     mode = ComparerMode.Source;
1016                     break;
1017             }
1018             _statuses.SetSortMode(mode, sortOrder);
1019             ////////////////////////////////////////////////////////////////////////////////
1020
1021             ApplyListViewIconSize(this._cfgCommon.IconSize);
1022
1023             //<<<<<<<<タブ関連>>>>>>>
1024             // タブの位置を調整する
1025             SetTabAlignment();
1026
1027             //デフォルトタブの存在チェック、ない場合には追加
1028             if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1029             {
1030                 TabClass tab;
1031                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1032                 {
1033                     _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1034                 }
1035                 else
1036                 {
1037                     tab.TabType = MyCommon.TabUsageType.Home;
1038                 }
1039             }
1040             if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1041             {
1042                 TabClass tab;
1043                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1044                 {
1045                     _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1046                 }
1047                 else
1048                 {
1049                     tab.TabType = MyCommon.TabUsageType.Mentions;
1050                 }
1051             }
1052             if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1053             {
1054                 TabClass tab;
1055                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1056                 {
1057                     _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1058                 }
1059                 else
1060                 {
1061                     tab.TabType = MyCommon.TabUsageType.DirectMessage;
1062                 }
1063             }
1064             if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1065             {
1066                 TabClass tab;
1067                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1068                 {
1069                     _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1070                 }
1071                 else
1072                 {
1073                     tab.TabType = MyCommon.TabUsageType.Favorites;
1074                 }
1075             }
1076             if (_statuses.GetTabByType(MyCommon.TabUsageType.Mute) == null)
1077             {
1078                 TabClass tab;
1079                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.MUTE, out tab))
1080                 {
1081                     _statuses.AddTab(MyCommon.DEFAULTTAB.MUTE, MyCommon.TabUsageType.Mute, null);
1082                 }
1083                 else
1084                 {
1085                     tab.TabType = MyCommon.TabUsageType.Mute;
1086                 }
1087             }
1088
1089             foreach (var tab in _statuses.Tabs.Values)
1090             {
1091                 // ミュートタブは表示しない
1092                 if (tab.TabType == MyCommon.TabUsageType.Mute)
1093                     continue;
1094
1095                 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1096                 {
1097                     tab.TabType = MyCommon.TabUsageType.UserDefined;
1098                 }
1099                 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1100                     throw new TabException(Properties.Resources.TweenMain_LoadText1);
1101             }
1102
1103             _curTab = ListTab.SelectedTab;
1104             _curItemIndex = -1;
1105             _curList = (DetailsListView)_curTab.Tag;
1106
1107             if (this._cfgCommon.TabIconDisp)
1108             {
1109                 ListTab.DrawMode = TabDrawMode.Normal;
1110             }
1111             else
1112             {
1113                 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1114                 ListTab.DrawItem += ListTab_DrawItem;
1115                 ListTab.ImageList = null;
1116             }
1117
1118             if (this._cfgCommon.HotkeyEnabled)
1119             {
1120                 //////グローバルホットキーの登録
1121                 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1122                 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1123                     modKey |= HookGlobalHotkey.ModKeys.Alt;
1124                 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1125                     modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1126                 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1127                     modKey |= HookGlobalHotkey.ModKeys.Shift;
1128                 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1129                     modKey |= HookGlobalHotkey.ModKeys.Win;
1130
1131                 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1132             }
1133
1134             if (this._cfgCommon.IsUseNotifyGrowl)
1135                 gh.RegisterGrowl();
1136
1137             StatusLabel.Text = Properties.Resources.Form1_LoadText1;       //画面右下の状態表示を変更
1138
1139             SetMainWindowTitle();
1140             SetNotifyIconText();
1141
1142             if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1143             {
1144                 this.Visible = true;
1145             }
1146
1147             //タイマー設定
1148             TimerTimeline.AutoReset = true;
1149             TimerTimeline.SynchronizingObject = this;
1150             //Recent取得間隔
1151             TimerTimeline.Interval = 1000;
1152             TimerTimeline.Enabled = true;
1153             //更新中アイコンアニメーション間隔
1154             TimerRefreshIcon.Interval = 200;
1155             TimerRefreshIcon.Enabled = true;
1156
1157             _ignoreConfigSave = false;
1158             this.TweenMain_Resize(null, null);
1159             if (saveRequired) SaveConfigsAll(false);
1160
1161             foreach (var ua in this._cfgCommon.UserAccounts)
1162             {
1163                 if (ua.UserId == 0 && ua.Username.ToLower() == tw.Username.ToLower())
1164                 {
1165                     ua.UserId = tw.UserId;
1166                     break;
1167                 }
1168             }
1169
1170             if (firstRun)
1171             {
1172                 // 初回起動時だけ右下のメニューを目立たせる
1173                 HashStripSplitButton.ShowDropDown();
1174             }
1175         }
1176
1177         private void InitDetailHtmlFormat()
1178         {
1179             if (this._cfgCommon.IsMonospace)
1180             {
1181                 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1182                 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1183             }
1184             else
1185             {
1186                 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1187                 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1188             }
1189
1190             detailHtmlFormatHeader = detailHtmlFormatHeader
1191                     .Replace("%FONT_FAMILY%", _fntDetail.Name)
1192                     .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1193                     .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1194                     .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1195                     .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString());
1196         }
1197
1198         private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1199         {
1200             string txt;
1201             try
1202             {
1203                 txt = ListTab.TabPages[e.Index].Text;
1204             }
1205             catch (Exception)
1206             {
1207                 return;
1208             }
1209
1210             e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1211             if (e.State == DrawItemState.Selected)
1212             {
1213                 e.DrawFocusRectangle();
1214             }
1215             Brush fore;
1216             try
1217             {
1218                 if (_statuses.Tabs[txt].UnreadCount > 0)
1219                     fore = Brushes.Red;
1220                 else
1221                     fore = System.Drawing.SystemBrushes.ControlText;
1222             }
1223             catch (Exception)
1224             {
1225                 fore = System.Drawing.SystemBrushes.ControlText;
1226             }
1227             e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1228         }
1229
1230         private void LoadConfig()
1231         {
1232             _cfgCommon = SettingCommon.Load();
1233             SettingCommon.Instance = this._cfgCommon;
1234             if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1235             {
1236                 _cfgCommon.UserAccounts = new List<UserAccount>();
1237                 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1238                 {
1239                     UserAccount account = new UserAccount();
1240                     account.Username = _cfgCommon.UserName;
1241                     account.UserId = _cfgCommon.UserId;
1242                     account.Token = _cfgCommon.Token;
1243                     account.TokenSecret = _cfgCommon.TokenSecret;
1244
1245                     _cfgCommon.UserAccounts.Add(account);
1246                 }
1247             }
1248
1249             _cfgLocal = SettingLocal.Load();
1250
1251             // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1252             if (_cfgLocal.ScaleDimension.IsEmpty)
1253                 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1254
1255             List<TabClass> tabs = SettingTabs.Load().Tabs;
1256             foreach (TabClass tb in tabs)
1257             {
1258                 try
1259                 {
1260                     tb.FilterModified = false;
1261                     _statuses.Tabs.Add(tb.TabName, tb);
1262                 }
1263                 catch (Exception)
1264                 {
1265                     tb.TabName = _statuses.MakeTabName("MyTab");
1266                     _statuses.Tabs.Add(tb.TabName, tb);
1267                 }
1268             }
1269             if (_statuses.Tabs.Count == 0)
1270             {
1271                 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1272                 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1273                 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1274                 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1275             }
1276         }
1277
1278         private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1279         {
1280             if (!TimerTimeline.Enabled) return;
1281             ResetTimers = e;
1282         }
1283
1284         private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1285
1286         private static int homeCounter = 0;
1287         private static int mentionCounter = 0;
1288         private static int dmCounter = 0;
1289         private static int pubSearchCounter = 0;
1290         private static int userTimelineCounter = 0;
1291         private static int listsCounter = 0;
1292         private static int usCounter = 0;
1293         private static int ResumeWait = 0;
1294         private static int refreshFollowers = 0;
1295
1296         private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1297         {
1298             if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1299             if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1300             if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1301             if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1302             if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1303             if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1304             if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1305             Interlocked.Increment(ref refreshFollowers);
1306
1307             var refreshTasks = new List<Task>();
1308
1309             ////タイマー初期化
1310             if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1311             {
1312                 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1313                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1314                     refreshTasks.Add(this.GetHomeTimelineAsync());
1315                 ResetTimers.Timeline = false;
1316             }
1317             if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1318             {
1319                 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1320                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1321                     refreshTasks.Add(this.GetReplyAsync());
1322                 ResetTimers.Reply = false;
1323             }
1324             if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1325             {
1326                 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1327                 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1328                     refreshTasks.Add(this.GetDirectMessagesAsync());
1329                 ResetTimers.DirectMessage = false;
1330             }
1331             if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1332             {
1333                 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1334                 if (!ResetTimers.PublicSearch)
1335                     refreshTasks.Add(this.GetPublicSearchAllAsync());
1336                 ResetTimers.PublicSearch = false;
1337             }
1338             if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1339             {
1340                 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1341                 if (!ResetTimers.UserTimeline)
1342                     refreshTasks.Add(this.GetUserTimelineAllAsync());
1343                 ResetTimers.UserTimeline = false;
1344             }
1345             if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1346             {
1347                 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1348                 if (!ResetTimers.Lists)
1349                     refreshTasks.Add(this.GetListTimelineAllAsync());
1350                 ResetTimers.Lists = false;
1351             }
1352             if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1353             {
1354                 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1355                 if (this._isActiveUserstream)
1356                     this.RefreshTimeline();
1357                 ResetTimers.UserStream = false;
1358             }
1359             if (refreshFollowers > 6 * 3600)
1360             {
1361                 Interlocked.Exchange(ref refreshFollowers, 0);
1362                 refreshTasks.AddRange(new[]
1363                 {
1364                     this.doGetFollowersMenu(),
1365                     this.RefreshNoRetweetIdsAsync(),
1366                     this.RefreshTwitterConfigurationAsync(),
1367                 });
1368             }
1369             if (osResumed)
1370             {
1371                 Interlocked.Increment(ref ResumeWait);
1372                 if (ResumeWait > 30)
1373                 {
1374                     osResumed = false;
1375                     Interlocked.Exchange(ref ResumeWait, 0);
1376                     refreshTasks.AddRange(new[]
1377                     {
1378                         this.GetHomeTimelineAsync(),
1379                         this.GetReplyAsync(),
1380                         this.GetDirectMessagesAsync(),
1381                         this.GetPublicSearchAllAsync(),
1382                         this.GetUserTimelineAllAsync(),
1383                         this.GetListTimelineAllAsync(),
1384                         this.doGetFollowersMenu(),
1385                         this.RefreshTwitterConfigurationAsync(),
1386                     });
1387                 }
1388             }
1389
1390             await Task.WhenAll(refreshTasks);
1391         }
1392
1393         private void RefreshTimeline()
1394         {
1395             // 現在表示中のタブのスクロール位置を退避
1396             var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1397
1398             // 各タブのリスト上の選択位置などを退避
1399             var listSelections = this.SaveListViewSelection();
1400
1401             //更新確定
1402             PostClass[] notifyPosts;
1403             string soundFile;
1404             int addCount;
1405             bool newMentionOrDm;
1406             bool isDelete;
1407             addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1408
1409             if (MyCommon._endingFlag) return;
1410
1411             //リストに反映&選択状態復元
1412             try
1413             {
1414                 foreach (TabPage tab in ListTab.TabPages)
1415                 {
1416                     DetailsListView lst = (DetailsListView)tab.Tag;
1417                     TabClass tabInfo = _statuses.Tabs[tab.Text];
1418                     if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1419                     {
1420                         using (ControlTransaction.Update(lst))
1421                         {
1422                             if (lst.Equals(_curList))
1423                             {
1424                                 this.PurgeListViewItemCache();
1425                             }
1426                             try
1427                             {
1428                                 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1429                             }
1430                             catch (Exception)
1431                             {
1432                                 //アイコン描画不具合あり?
1433                             }
1434
1435                             // 選択位置などを復元
1436                             this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1437                         }
1438                     }
1439                     if (tabInfo.UnreadCount > 0)
1440                         if (this._cfgCommon.TabIconDisp)
1441                             if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1442                 }
1443                 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1444             }
1445             catch (Exception)
1446             {
1447                 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1448                 //throw;
1449             }
1450
1451             // スクロール位置を復元
1452             this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1453
1454             //新着通知
1455             NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1456
1457             SetMainWindowTitle();
1458             if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
1459
1460             HashSupl.AddRangeItem(tw.GetHashList());
1461
1462         }
1463
1464         internal struct ListViewScroll
1465         {
1466             public ScrollLockMode ScrollLockMode { get; set; }
1467             public long? TopItemStatusId { get; set; }
1468         }
1469
1470         internal enum ScrollLockMode
1471         {
1472             /// <summary>固定しない</summary>
1473             None,
1474
1475             /// <summary>最上部に固定する</summary>
1476             FixedToTop,
1477
1478             /// <summary>最下部に固定する</summary>
1479             FixedToBottom,
1480
1481             /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1482             FixedToItem,
1483         }
1484
1485         /// <summary>
1486         /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1487         /// </summary>
1488         private ListViewScroll SaveListViewScroll(DetailsListView listView, TabClass tab)
1489         {
1490             var listScroll = new ListViewScroll
1491             {
1492                 ScrollLockMode = this.GetScrollLockMode(listView),
1493             };
1494
1495             if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1496             {
1497                 var topItem = listView.TopItem;
1498                 if (topItem != null)
1499                     listScroll.TopItemStatusId = tab.GetId(topItem.Index);
1500             }
1501
1502             return listScroll;
1503         }
1504
1505         private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1506         {
1507             if (this._statuses.SortMode == ComparerMode.Id)
1508             {
1509                 if (this._statuses.SortOrder == SortOrder.Ascending)
1510                 {
1511                     // Id昇順
1512                     if (this.ListLockMenuItem.Checked)
1513                         return ScrollLockMode.None;
1514
1515                     // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1516
1517                     // 一番下に表示されているアイテム
1518                     var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1519                     if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1520                         return ScrollLockMode.FixedToBottom;
1521                     else
1522                         return ScrollLockMode.None;
1523                 }
1524                 else
1525                 {
1526                     // Id降順
1527                     if (this.ListLockMenuItem.Checked)
1528                         return ScrollLockMode.FixedToItem;
1529
1530                     // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1531                     var topItem = listView.TopItem;
1532                     if (topItem == null || topItem.Index == 0)
1533                         return ScrollLockMode.FixedToTop;
1534                     else
1535                         return ScrollLockMode.FixedToItem;
1536                 }
1537             }
1538             else
1539             {
1540                 return ScrollLockMode.FixedToItem;
1541             }
1542         }
1543
1544         internal struct ListViewSelection
1545         {
1546             public long[] SelectedStatusIds { get; set; }
1547             public long? SelectionMarkStatusId { get; set; }
1548             public long? FocusedStatusId { get; set; }
1549         }
1550
1551         /// <summary>
1552         /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1553         /// </summary>
1554         private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1555         {
1556             var listsDict = new Dictionary<string, ListViewSelection>();
1557
1558             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1559             {
1560                 var listView = (DetailsListView)tabPage.Tag;
1561                 var tab = _statuses.Tabs[tabPage.Text];
1562
1563                 ListViewSelection listStatus;
1564                 if (listView.VirtualListSize != 0)
1565                 {
1566                     listStatus = new ListViewSelection
1567                     {
1568                         SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1569                         FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1570                         SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1571                     };
1572                 }
1573                 else
1574                 {
1575                     listStatus = new ListViewSelection
1576                     {
1577                         SelectedStatusIds = new long[0],
1578                         SelectionMarkStatusId = null,
1579                         FocusedStatusId = null,
1580                     };
1581                 }
1582
1583                 listsDict[tab.TabName] = listStatus;
1584             }
1585
1586             return listsDict;
1587         }
1588
1589         private long[] GetSelectedStatusIds(DetailsListView listView, TabClass tab)
1590         {
1591             var selectedIndices = listView.SelectedIndices;
1592             if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1593                 return tab.GetId(selectedIndices);
1594             else
1595                 return null;
1596         }
1597
1598         private long? GetFocusedStatusId(DetailsListView listView, TabClass tab)
1599         {
1600             var focusedItem = listView.FocusedItem;
1601
1602             return focusedItem != null ? tab.GetId(focusedItem.Index) : (long?)null;
1603         }
1604
1605         private long? GetSelectionMarkStatusId(DetailsListView listView, TabClass tab)
1606         {
1607             var selectionMarkIndex = listView.SelectionMark;
1608
1609             return selectionMarkIndex != -1 ? tab.GetId(selectionMarkIndex) : (long?)null;
1610         }
1611
1612         /// <summary>
1613         /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1614         /// </summary>
1615         private void RestoreListViewScroll(DetailsListView listView, TabClass tab, ListViewScroll listScroll)
1616         {
1617             if (listView.VirtualListSize == 0)
1618                 return;
1619
1620             switch (listScroll.ScrollLockMode)
1621             {
1622                 case ScrollLockMode.FixedToTop:
1623                     listView.EnsureVisible(0);
1624                     break;
1625                 case ScrollLockMode.FixedToBottom:
1626                     listView.EnsureVisible(listView.VirtualListSize - 1);
1627                     break;
1628                 case ScrollLockMode.FixedToItem:
1629                     var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1630                     if (topIndex != -1)
1631                         listView.TopItem = listView.Items[topIndex];
1632                     break;
1633                 case ScrollLockMode.None:
1634                 default:
1635                     break;
1636             }
1637         }
1638
1639         /// <summary>
1640         /// <see cref="SaveListViewStatus"/> によって保存された選択状態を復元します
1641         /// </summary>
1642         private void RestoreListViewSelection(DetailsListView listView, TabClass tab, ListViewSelection listSelection)
1643         {
1644             // status_id から ListView 上のインデックスに変換
1645             int[] selectedIndices = null;
1646             if (listSelection.SelectedStatusIds != null)
1647                 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1648
1649             var focusedIndex = -1;
1650             if (listSelection.FocusedStatusId != null)
1651                 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1652
1653             var selectionMarkIndex = -1;
1654             if (listSelection.SelectionMarkStatusId != null)
1655                 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1656
1657             this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1658         }
1659
1660         private bool BalloonRequired()
1661         {
1662             Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1663             ev.Eventtype = MyCommon.EVENTTYPE.None;
1664
1665             return BalloonRequired(ev);
1666         }
1667
1668         private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1669         {
1670             if (type == MyCommon.EVENTTYPE.None)
1671                 return true;
1672
1673             if (!this._cfgCommon.EventNotifyEnabled)
1674                 return false;
1675
1676             return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1677         }
1678
1679         private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1680         {
1681             if (!ev.IsMe)
1682                 return true;
1683
1684             return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1685         }
1686
1687         private bool BalloonRequired(Twitter.FormattedEvent ev)
1688         {
1689             if (this._initial)
1690                 return false;
1691
1692             if (NativeMethods.IsScreenSaverRunning())
1693                 return false;
1694
1695             // 「新着通知」が無効
1696             if (!this.NewPostPopMenuItem.Checked)
1697             {
1698                 // 「新着通知が無効でもイベントを通知する」にも該当しない
1699                 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1700                     return false;
1701             }
1702
1703             // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1704             if (this._cfgCommon.LimitBalloon)
1705             {
1706                 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1707                     return false;
1708             }
1709
1710             return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1711         }
1712
1713         private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1714         {
1715             if (this._cfgCommon.ReadOwnPost)
1716             {
1717                 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1718                     return;
1719             }
1720
1721             //新着通知
1722             if (BalloonRequired())
1723             {
1724                 if (notifyPosts != null && notifyPosts.Length > 0)
1725                 {
1726                     //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1727                     if (this._cfgCommon.IsUseNotifyGrowl)
1728                     {
1729                         StringBuilder sb = new StringBuilder();
1730                         bool reply = false;
1731                         bool dm = false;
1732
1733                         foreach (PostClass post in notifyPosts)
1734                         {
1735                             if (!(notifyPosts.Length > 3))
1736                             {
1737                                 sb.Clear();
1738                                 reply = false;
1739                                 dm = false;
1740                             }
1741                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1742                             if (post.IsDm) dm = true;
1743                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1744                             switch (this._cfgCommon.NameBalloon)
1745                             {
1746                                 case MyCommon.NameBalloonEnum.UserID:
1747                                     sb.Append(post.ScreenName).Append(" : ");
1748                                     break;
1749                                 case MyCommon.NameBalloonEnum.NickName:
1750                                     sb.Append(post.Nickname).Append(" : ");
1751                                     break;
1752                             }
1753                             sb.Append(post.TextFromApi);
1754                             if (notifyPosts.Length > 3)
1755                             {
1756                                 if (notifyPosts.Last() != post) continue;
1757                             }
1758
1759                             StringBuilder title = new StringBuilder();
1760                             GrowlHelper.NotifyType nt;
1761                             if (this._cfgCommon.DispUsername)
1762                             {
1763                                 title.Append(tw.Username);
1764                                 title.Append(" - ");
1765                             }
1766                             else
1767                             {
1768                                 //title.Clear();
1769                             }
1770                             if (dm)
1771                             {
1772                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1773                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1774                                 title.Append(Application.ProductName);
1775                                 title.Append(" [DM] ");
1776                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1777                                 nt = GrowlHelper.NotifyType.DirectMessage;
1778                             }
1779                             else if (reply)
1780                             {
1781                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1782                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1783                                 title.Append(Application.ProductName);
1784                                 title.Append(" [Reply!] ");
1785                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1786                                 nt = GrowlHelper.NotifyType.Reply;
1787                             }
1788                             else
1789                             {
1790                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1791                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1792                                 title.Append(Application.ProductName);
1793                                 title.Append(" ");
1794                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1795                                 nt = GrowlHelper.NotifyType.Notify;
1796                             }
1797                             string bText = sb.ToString();
1798                             if (string.IsNullOrEmpty(bText)) return;
1799
1800                             var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1801                             gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1802                         }
1803                     }
1804                     else
1805                     {
1806                         StringBuilder sb = new StringBuilder();
1807                         bool reply = false;
1808                         bool dm = false;
1809                         foreach (PostClass post in notifyPosts)
1810                         {
1811                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1812                             if (post.IsDm) dm = true;
1813                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1814                             switch (this._cfgCommon.NameBalloon)
1815                             {
1816                                 case MyCommon.NameBalloonEnum.UserID:
1817                                     sb.Append(post.ScreenName).Append(" : ");
1818                                     break;
1819                                 case MyCommon.NameBalloonEnum.NickName:
1820                                     sb.Append(post.Nickname).Append(" : ");
1821                                     break;
1822                             }
1823                             sb.Append(post.TextFromApi);
1824
1825                         }
1826                         //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1827                         StringBuilder title = new StringBuilder();
1828                         ToolTipIcon ntIcon;
1829                         if (this._cfgCommon.DispUsername)
1830                         {
1831                             title.Append(tw.Username);
1832                             title.Append(" - ");
1833                         }
1834                         else
1835                         {
1836                             //title.Clear();
1837                         }
1838                         if (dm)
1839                         {
1840                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1841                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1842                             ntIcon = ToolTipIcon.Warning;
1843                             title.Append(Application.ProductName);
1844                             title.Append(" [DM] ");
1845                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1846                         }
1847                         else if (reply)
1848                         {
1849                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1850                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1851                             ntIcon = ToolTipIcon.Warning;
1852                             title.Append(Application.ProductName);
1853                             title.Append(" [Reply!] ");
1854                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1855                         }
1856                         else
1857                         {
1858                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1859                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1860                             ntIcon = ToolTipIcon.Info;
1861                             title.Append(Application.ProductName);
1862                             title.Append(" ");
1863                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1864                         }
1865                         string bText = sb.ToString();
1866                         if (string.IsNullOrEmpty(bText)) return;
1867                         //NotifyIcon1.BalloonTipText = sb.ToString();
1868                         //NotifyIcon1.ShowBalloonTip(500);
1869                         NotifyIcon1.BalloonTipTitle = title.ToString();
1870                         NotifyIcon1.BalloonTipText = bText;
1871                         NotifyIcon1.BalloonTipIcon = ntIcon;
1872                         NotifyIcon1.ShowBalloonTip(500);
1873                     }
1874                 }
1875             }
1876
1877             //サウンド再生
1878             if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1879             {
1880                 try
1881                 {
1882                     string dir = Application.StartupPath;
1883                     if (Directory.Exists(Path.Combine(dir, "Sounds")))
1884                     {
1885                         dir = Path.Combine(dir, "Sounds");
1886                     }
1887                     using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1888                     {
1889                         player.Play();
1890                     }
1891                 }
1892                 catch (Exception)
1893                 {
1894                 }
1895             }
1896
1897             //mentions新着時に画面ブリンク
1898             if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1899             {
1900                 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1901             }
1902         }
1903
1904         private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1905         {
1906             if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1907
1908             _curItemIndex = _curList.SelectedIndices[0];
1909             if (_curItemIndex > _curList.VirtualListSize - 1) return;
1910
1911             PostClass selectedPost;
1912             try
1913             {
1914                 selectedPost = GetCurTabPost(_curItemIndex);
1915             }
1916             catch (ArgumentException)
1917             {
1918                 return;
1919             }
1920
1921             if (selectedPost.StatusId == this._curPost?.StatusId)
1922                 return;
1923
1924             this._curPost = selectedPost;
1925
1926             this.PushSelectPostChain();
1927
1928             this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1929             //キャッシュの書き換え
1930             ChangeCacheStyleRead(true, _curItemIndex);   //既読へ(フォント、文字色)
1931
1932             ColorizeList();
1933             _colorize = true;
1934         }
1935
1936         private void ChangeCacheStyleRead(bool Read, int Index)
1937         {
1938             var tabInfo = _statuses.Tabs[_curTab.Text];
1939             //Read:true=既読 false=未読
1940             //未読管理していなかったら既読として扱う
1941             if (!tabInfo.UnreadManage ||
1942                !this._cfgCommon.UnreadManage) Read = true;
1943
1944             var listCache = this._listItemCache;
1945             if (listCache == null)
1946                 return;
1947
1948             // キャッシュに含まれていないアイテムは対象外
1949             ListViewItem itm;
1950             PostClass post;
1951             if (!listCache.TryGetValue(Index, out itm, out post))
1952                 return;
1953
1954             ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1955         }
1956
1957         private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1958         {
1959             Font fnt;
1960             //フォント
1961             if (Read)
1962             {
1963                 fnt = _fntReaded;
1964                 Item.SubItems[5].Text = "";
1965             }
1966             else
1967             {
1968                 fnt = _fntUnread;
1969                 Item.SubItems[5].Text = "★";
1970             }
1971             //文字色
1972             Color cl;
1973             if (Post.IsFav)
1974                 cl = _clFav;
1975             else if (Post.RetweetedId != null)
1976                 cl = _clRetweet;
1977             else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1978                 cl = _clOWL;
1979             else if (Read || !this._cfgCommon.UseUnreadStyle)
1980                 cl = _clReaded;
1981             else
1982                 cl = _clUnread;
1983
1984             if (DList == null || Item.Index == -1)
1985             {
1986                 Item.ForeColor = cl;
1987                 if (this._cfgCommon.UseUnreadStyle)
1988                     Item.Font = fnt;
1989             }
1990             else
1991             {
1992                 DList.Update();
1993                 if (this._cfgCommon.UseUnreadStyle)
1994                     DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1995                 else
1996                     DList.ChangeItemForeColor(Item.Index, cl);
1997                 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
1998             }
1999         }
2000
2001         private void ColorizeList()
2002         {
2003             //Index:更新対象のListviewItem.Index。Colorを返す。
2004             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2005             PostClass _post;
2006             if (_anchorFlag)
2007                 _post = _anchorPost;
2008             else
2009                 _post = _curPost;
2010
2011             if (_post == null) return;
2012
2013             var listCache = this._listItemCache;
2014             if (listCache == null)
2015                 return;
2016
2017             var index = listCache.StartIndex;
2018             foreach (var cachedPost in listCache.Post)
2019             {
2020                 var backColor = this.JudgeColor(_post, cachedPost);
2021                 this._curList.ChangeItemBackColor(index++, backColor);
2022             }
2023         }
2024
2025         private void ColorizeList(ListViewItem Item, int Index)
2026         {
2027             //Index:更新対象のListviewItem.Index。Colorを返す。
2028             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2029             PostClass _post;
2030             if (_anchorFlag)
2031                 _post = _anchorPost;
2032             else
2033                 _post = _curPost;
2034
2035             PostClass tPost = GetCurTabPost(Index);
2036
2037             if (_post == null) return;
2038
2039             if (Item.Index == -1)
2040                 Item.BackColor = JudgeColor(_post, tPost);
2041             else
2042                 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2043         }
2044
2045         private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2046         {
2047             Color cl;
2048             if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2049                 //@先
2050                 cl = _clAtTo;
2051             else if (TargetPost.IsMe)
2052                 //自分=発言者
2053                 cl = _clSelf;
2054             else if (TargetPost.IsReply)
2055                 //自分宛返信
2056                 cl = _clAtSelf;
2057             else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLower()))
2058                 //返信先
2059                 cl = _clAtFromTarget;
2060             else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLower()))
2061                 //その人への返信
2062                 cl = _clAtTarget;
2063             else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2064                 //発言者
2065                 cl = _clTarget;
2066             else
2067                 //その他
2068                 cl = _clListBackcolor;
2069
2070             return cl;
2071         }
2072
2073         private async void PostButton_Click(object sender, EventArgs e)
2074         {
2075             if (StatusText.Text.Trim().Length == 0)
2076             {
2077                 if (!ImageSelector.Enabled)
2078                 {
2079                     await this.DoRefresh();
2080                     return;
2081                 }
2082             }
2083
2084             if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2085             {
2086                 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2087                                                                "Retweet",
2088                                                                MessageBoxButtons.YesNoCancel,
2089                                                                MessageBoxIcon.Question);
2090                 switch (rtResult)
2091                 {
2092                     case DialogResult.Yes:
2093                         StatusText.Text = "";
2094                         await this.doReTweetOfficial(false);
2095                         return;
2096                     case DialogResult.Cancel:
2097                         return;
2098                 }
2099             }
2100
2101             var inReplyToStatusId = this.inReplyTo?.Item1;
2102             var inReplyToScreenName = this.inReplyTo?.Item2;
2103             _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2104
2105             if (this._cfgCommon.Nicoms)
2106             {
2107                 StatusText.SelectionStart = StatusText.Text.Length;
2108                 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2109             }
2110             //if (SettingDialog.UrlConvertAuto)
2111             //{
2112             //    StatusText.SelectionStart = StatusText.Text.Length;
2113             //    UrlConvertAutoToolStripMenuItem_Click(null, null);
2114             //}
2115             //else if (SettingDialog.Nicoms)
2116             //{
2117             //    StatusText.SelectionStart = StatusText.Text.Length;
2118             //    UrlConvert(UrlConverter.Nicoms);
2119             //}
2120             StatusText.SelectionStart = StatusText.Text.Length;
2121             CheckReplyTo(StatusText.Text);
2122
2123             var statusText = this.FormatStatusText(this.StatusText.Text);
2124
2125             if (this.GetRestStatusCount(statusText) < 0)
2126             {
2127                 // 文字数制限を超えているが強制的に投稿するか
2128                 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2129                 if (ret != DialogResult.OK)
2130                     return;
2131             }
2132
2133             var status = new PostingStatus();
2134             status.status = statusText;
2135
2136             status.inReplyToId = this.inReplyTo?.Item1;
2137             status.inReplyToName = this.inReplyTo?.Item2;
2138             if (ImageSelector.Visible)
2139             {
2140                 //画像投稿
2141                 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2142                     return;
2143             }
2144
2145             this.inReplyTo = null;
2146             StatusText.Text = "";
2147             _history.Add(new PostingStatus());
2148             _hisIdx = _history.Count - 1;
2149             if (!ToolStripFocusLockMenuItem.Checked)
2150                 ((Control)ListTab.SelectedTab.Tag).Focus();
2151             urlUndoBuffer = null;
2152             UrlUndoToolStripMenuItem.Enabled = false;  //Undoをできないように設定
2153
2154             //Google検索(試験実装)
2155             if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2156             {
2157                 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2158                 await this.OpenUriInBrowserAsync(tmp);
2159             }
2160
2161             await this.PostMessageAsync(status);
2162         }
2163
2164         private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2165         {
2166             MyCommon._endingFlag = true;
2167             this.Close();
2168         }
2169
2170         private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2171         {
2172             if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2173             {
2174                 //_endingFlag=false:フォームの×ボタン
2175                 e.Cancel = true;
2176                 this.Visible = false;
2177             }
2178             else
2179             {
2180                 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2181                 _ignoreConfigSave = true;
2182                 MyCommon._endingFlag = true;
2183                 TimerTimeline.Enabled = false;
2184                 TimerRefreshIcon.Enabled = false;
2185             }
2186         }
2187
2188         private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2189         {
2190             this.Visible = true;
2191             if (this.WindowState == FormWindowState.Minimized)
2192             {
2193                 this.WindowState = FormWindowState.Normal;
2194             }
2195             this.Activate();
2196             this.BringToFront();
2197         }
2198
2199         private static int errorCount = 0;
2200
2201         private static bool CheckAccountValid()
2202         {
2203             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2204             {
2205                 errorCount += 1;
2206                 if (errorCount > 5)
2207                 {
2208                     errorCount = 0;
2209                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2210                     return true;
2211                 }
2212                 return false;
2213             }
2214             errorCount = 0;
2215             return true;
2216         }
2217
2218         private Task GetHomeTimelineAsync()
2219         {
2220             return this.GetHomeTimelineAsync(loadMore: false);
2221         }
2222
2223         private async Task GetHomeTimelineAsync(bool loadMore)
2224         {
2225             await this.workerSemaphore.WaitAsync();
2226
2227             try
2228             {
2229                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2230
2231                 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2232             }
2233             catch (WebApiException ex)
2234             {
2235                 this._myStatusError = true;
2236                 this.StatusLabel.Text = ex.Message;
2237             }
2238             finally
2239             {
2240                 this.workerSemaphore.Release();
2241             }
2242         }
2243
2244         private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2245         {
2246             if (ct.IsCancellationRequested)
2247                 return;
2248
2249             if (!CheckAccountValid())
2250                 throw new WebApiException("Auth error. Check your account");
2251
2252             bool read;
2253             if (!this._cfgCommon.UnreadManage)
2254                 read = true;
2255             else
2256                 read = this._initial && this._cfgCommon.Read;
2257
2258             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5, loadMore ? -1 : 1));
2259
2260             await Task.Run(() =>
2261             {
2262                 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial);
2263
2264                 // 新着時未読クリア
2265                 if (this._cfgCommon.ReadOldPosts)
2266                     this._statuses.SetReadHomeTab();
2267
2268                 var addCount = this._statuses.DistributePosts();
2269
2270                 if (!this._initial)
2271                     this.UpdateTimelineSpeed(addCount);
2272             });
2273
2274             if (ct.IsCancellationRequested)
2275                 return;
2276
2277             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2278
2279             this.RefreshTimeline();
2280         }
2281
2282         /// <summary>
2283         /// タイムラインに追加された発言件数を反映し、タイムラインの流速を更新します
2284         /// </summary>
2285         /// <param name="addCount">直前にタイムラインに追加した発言件数</param>
2286         private void UpdateTimelineSpeed(int addCount)
2287         {
2288             var now = DateTime.Now;
2289             this._tlTimestamps.AddOrUpdate(now, addCount, (k, v) => v + addCount);
2290
2291             var removeKeys = new List<DateTime>();
2292             var oneHour = TimeSpan.FromHours(1);
2293             var tlCount = 0;
2294             foreach (var pair in this._tlTimestamps)
2295             {
2296                 if (now - pair.Key > oneHour)
2297                     removeKeys.Add(pair.Key);
2298                 else
2299                     tlCount += pair.Value;
2300             }
2301             Interlocked.Exchange(ref this._tlCount, tlCount);
2302
2303             int _;
2304             foreach (var key in removeKeys)
2305                 this._tlTimestamps.TryRemove(key, out _);
2306         }
2307
2308         private Task GetReplyAsync()
2309         {
2310             return this.GetReplyAsync(loadMore: false);
2311         }
2312
2313         private async Task GetReplyAsync(bool loadMore)
2314         {
2315             await this.workerSemaphore.WaitAsync();
2316
2317             try
2318             {
2319                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2320
2321                 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2322             }
2323             catch (WebApiException ex)
2324             {
2325                 this._myStatusError = true;
2326                 this.StatusLabel.Text = ex.Message;
2327             }
2328             finally
2329             {
2330                 this.workerSemaphore.Release();
2331             }
2332         }
2333
2334         private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2335         {
2336             if (ct.IsCancellationRequested)
2337                 return;
2338
2339             if (!CheckAccountValid())
2340                 throw new WebApiException("Auth error. Check your account");
2341
2342             bool read;
2343             if (!this._cfgCommon.UnreadManage)
2344                 read = true;
2345             else
2346                 read = this._initial && this._cfgCommon.Read;
2347
2348             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4, loadMore ? -1 : 1));
2349
2350             await Task.Run(() =>
2351             {
2352                 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial);
2353
2354                 this._statuses.DistributePosts();
2355             });
2356
2357             if (ct.IsCancellationRequested)
2358                 return;
2359
2360             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2361
2362             this.RefreshTimeline();
2363         }
2364
2365         private Task GetDirectMessagesAsync()
2366         {
2367             return this.GetDirectMessagesAsync(loadMore: false);
2368         }
2369
2370         private async Task GetDirectMessagesAsync(bool loadMore)
2371         {
2372             await this.workerSemaphore.WaitAsync();
2373
2374             try
2375             {
2376                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2377
2378                 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2379             }
2380             catch (WebApiException ex)
2381             {
2382                 this._myStatusError = true;
2383                 this.StatusLabel.Text = ex.Message;
2384             }
2385             finally
2386             {
2387                 this.workerSemaphore.Release();
2388             }
2389         }
2390
2391         private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2392         {
2393             if (ct.IsCancellationRequested)
2394                 return;
2395
2396             if (!CheckAccountValid())
2397                 throw new WebApiException("Auth error. Check your account");
2398
2399             bool read;
2400             if (!this._cfgCommon.UnreadManage)
2401                 read = true;
2402             else
2403                 read = this._initial && this._cfgCommon.Read;
2404
2405             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8, loadMore ? -1 : 1));
2406
2407             await Task.Run(() =>
2408             {
2409                 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore);
2410                 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore);
2411
2412                 this._statuses.DistributePosts();
2413             });
2414
2415             if (ct.IsCancellationRequested)
2416                 return;
2417
2418             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2419
2420             this.RefreshTimeline();
2421         }
2422
2423         private Task GetFavoritesAsync()
2424         {
2425             return this.GetFavoritesAsync(loadMore: false);
2426         }
2427
2428         private async Task GetFavoritesAsync(bool loadMore)
2429         {
2430             await this.workerSemaphore.WaitAsync();
2431
2432             try
2433             {
2434                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2435
2436                 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2437             }
2438             catch (WebApiException ex)
2439             {
2440                 this._myStatusError = true;
2441                 this.StatusLabel.Text = ex.Message;
2442             }
2443             finally
2444             {
2445                 this.workerSemaphore.Release();
2446             }
2447         }
2448
2449         private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2450         {
2451             if (ct.IsCancellationRequested)
2452                 return;
2453
2454             if (!CheckAccountValid())
2455                 throw new WebApiException("Auth error. Check your account");
2456
2457             bool read;
2458             if (!this._cfgCommon.UnreadManage)
2459                 read = true;
2460             else
2461                 read = this._initial && this._cfgCommon.Read;
2462
2463             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2464
2465             await Task.Run(() =>
2466             {
2467                 this.tw.GetFavoritesApi(read, loadMore);
2468
2469                 this._statuses.DistributePosts();
2470             });
2471
2472             if (ct.IsCancellationRequested)
2473                 return;
2474
2475             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2476
2477             this.RefreshTimeline();
2478         }
2479
2480         private Task GetPublicSearchAllAsync()
2481         {
2482             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch);
2483
2484             return this.GetPublicSearchAsync(tabs, loadMore: false);
2485         }
2486
2487         private Task GetPublicSearchAsync(TabClass tab)
2488         {
2489             return this.GetPublicSearchAsync(tab, loadMore: false);
2490         }
2491
2492         private Task GetPublicSearchAsync(TabClass tab, bool loadMore)
2493         {
2494             return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2495         }
2496
2497         private async Task GetPublicSearchAsync(IEnumerable<TabClass> tabs, bool loadMore)
2498         {
2499             await this.workerSemaphore.WaitAsync();
2500
2501             try
2502             {
2503                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2504
2505                 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2506             }
2507             catch (WebApiException ex)
2508             {
2509                 this._myStatusError = true;
2510                 this.StatusLabel.Text = ex.Message;
2511             }
2512             finally
2513             {
2514                 this.workerSemaphore.Release();
2515             }
2516         }
2517
2518         private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2519         {
2520             if (ct.IsCancellationRequested)
2521                 return;
2522
2523             if (!CheckAccountValid())
2524                 throw new WebApiException("Auth error. Check your account");
2525
2526             bool read;
2527             if (!this._cfgCommon.UnreadManage)
2528                 read = true;
2529             else
2530                 read = this._initial && this._cfgCommon.Read;
2531
2532             p.Report("Search refreshing...");
2533
2534             await Task.Run(() =>
2535             {
2536                 WebApiException lastException = null;
2537
2538                 foreach (var tab in tabs)
2539                 {
2540                     try
2541                     {
2542                         if (string.IsNullOrEmpty(tab.SearchWords))
2543                             continue;
2544
2545                         this.tw.GetSearch(read, tab, false);
2546
2547                         if (loadMore)
2548                             this.tw.GetSearch(read, tab, true);
2549                     }
2550                     catch (WebApiException ex)
2551                     {
2552                         lastException = ex;
2553                     }
2554                 }
2555
2556                 this._statuses.DistributePosts();
2557
2558                 if (lastException != null)
2559                     throw new WebApiException(lastException.Message, lastException);
2560             });
2561
2562             if (ct.IsCancellationRequested)
2563                 return;
2564
2565             p.Report("Search refreshed");
2566
2567             this.RefreshTimeline();
2568         }
2569
2570         private Task GetUserTimelineAllAsync()
2571         {
2572             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline);
2573
2574             return this.GetUserTimelineAsync(tabs, loadMore: false);
2575         }
2576
2577         private Task GetUserTimelineAsync(TabClass tab)
2578         {
2579             return this.GetUserTimelineAsync(tab, loadMore: false);
2580         }
2581
2582         private Task GetUserTimelineAsync(TabClass tab, bool loadMore)
2583         {
2584             return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2585         }
2586
2587         private async Task GetUserTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2588         {
2589             await this.workerSemaphore.WaitAsync();
2590
2591             try
2592             {
2593                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2594
2595                 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2596             }
2597             catch (WebApiException ex)
2598             {
2599                 this._myStatusError = true;
2600                 this.StatusLabel.Text = ex.Message;
2601             }
2602             finally
2603             {
2604                 this.workerSemaphore.Release();
2605             }
2606         }
2607
2608         private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2609         {
2610             if (ct.IsCancellationRequested)
2611                 return;
2612
2613             if (!CheckAccountValid())
2614                 throw new WebApiException("Auth error. Check your account");
2615
2616             bool read;
2617             if (!this._cfgCommon.UnreadManage)
2618                 read = true;
2619             else
2620                 read = this._initial && this._cfgCommon.Read;
2621
2622             p.Report("UserTimeline refreshing...");
2623
2624             await Task.Run(() =>
2625             {
2626                 WebApiException lastException = null;
2627
2628                 foreach (var tab in tabs)
2629                 {
2630                     try
2631                     {
2632                         if (string.IsNullOrEmpty(tab.User))
2633                             continue;
2634
2635                         this.tw.GetUserTimelineApi(read, tab.User, tab, loadMore);
2636                     }
2637                     catch (WebApiException ex)
2638                     {
2639                         lastException = ex;
2640                     }
2641                 }
2642
2643                 this._statuses.DistributePosts();
2644
2645                 if (lastException != null)
2646                     throw new WebApiException(lastException.Message, lastException);
2647             });
2648
2649             if (ct.IsCancellationRequested)
2650                 return;
2651
2652             p.Report("UserTimeline refreshed");
2653
2654             this.RefreshTimeline();
2655         }
2656
2657         private Task GetListTimelineAllAsync()
2658         {
2659             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.Lists);
2660
2661             return this.GetListTimelineAsync(tabs, loadMore: false);
2662         }
2663
2664         private Task GetListTimelineAsync(TabClass tab)
2665         {
2666             return this.GetListTimelineAsync(tab, loadMore: false);
2667         }
2668
2669         private Task GetListTimelineAsync(TabClass tab, bool loadMore)
2670         {
2671             return this.GetListTimelineAsync(new[] { tab }, loadMore);
2672         }
2673
2674         private async Task GetListTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2675         {
2676             await this.workerSemaphore.WaitAsync();
2677
2678             try
2679             {
2680                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2681
2682                 await this.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2683             }
2684             catch (WebApiException ex)
2685             {
2686                 this._myStatusError = true;
2687                 this.StatusLabel.Text = ex.Message;
2688             }
2689             finally
2690             {
2691                 this.workerSemaphore.Release();
2692             }
2693         }
2694
2695         private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2696         {
2697             if (ct.IsCancellationRequested)
2698                 return;
2699
2700             if (!CheckAccountValid())
2701                 throw new WebApiException("Auth error. Check your account");
2702
2703             bool read;
2704             if (!this._cfgCommon.UnreadManage)
2705                 read = true;
2706             else
2707                 read = this._initial && this._cfgCommon.Read;
2708
2709             p.Report("List refreshing...");
2710
2711             await Task.Run(() =>
2712             {
2713                 WebApiException lastException = null;
2714
2715                 foreach (var tab in tabs)
2716                 {
2717                     try
2718                     {
2719                         if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2720                             continue;
2721
2722                         this.tw.GetListStatus(read, tab, loadMore, this._initial);
2723                     }
2724                     catch (WebApiException ex)
2725                     {
2726                         lastException = ex;
2727                     }
2728                 }
2729
2730                 this._statuses.DistributePosts();
2731
2732                 if (lastException != null)
2733                     throw new WebApiException(lastException.Message, lastException);
2734             });
2735
2736             if (ct.IsCancellationRequested)
2737                 return;
2738
2739             p.Report("List refreshed");
2740
2741             this.RefreshTimeline();
2742         }
2743
2744         private async Task GetRelatedTweetsAsync(TabClass tab)
2745         {
2746             await this.workerSemaphore.WaitAsync();
2747
2748             try
2749             {
2750                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2751
2752                 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2753             }
2754             catch (WebApiException ex)
2755             {
2756                 this._myStatusError = true;
2757                 this.StatusLabel.Text = ex.Message;
2758             }
2759             finally
2760             {
2761                 this.workerSemaphore.Release();
2762             }
2763         }
2764
2765         private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, TabClass tab)
2766         {
2767             if (ct.IsCancellationRequested)
2768                 return;
2769
2770             if (!CheckAccountValid())
2771                 throw new WebApiException("Auth error. Check your account");
2772
2773             bool read;
2774             if (!this._cfgCommon.UnreadManage)
2775                 read = true;
2776             else
2777                 read = this._initial && this._cfgCommon.Read;
2778
2779             p.Report("Related refreshing...");
2780
2781             await Task.Run(() =>
2782             {
2783                 this.tw.GetRelatedResult(read, tab);
2784
2785                 this._statuses.DistributePosts();
2786             });
2787
2788             if (ct.IsCancellationRequested)
2789                 return;
2790
2791             p.Report("Related refreshed");
2792
2793             this.RefreshTimeline();
2794
2795             var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2796                 .FirstOrDefault(x => x.Text == tab.TabName);
2797
2798             if (tabPage != null)
2799             {
2800                 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2801
2802                 var listView = (DetailsListView)tabPage.Tag;
2803                 var index = tab.IndexOf(tab.RelationTargetPost.RetweetedId ?? tab.RelationTargetPost.StatusId);
2804
2805                 if (index != -1 && index < listView.Items.Count)
2806                 {
2807                     listView.SelectedIndices.Add(index);
2808                     listView.Items[index].Focused = true;
2809                 }
2810             }
2811         }
2812
2813         private async Task FavAddAsync(IReadOnlyList<long> statusIds, TabClass tab)
2814         {
2815             await this.workerSemaphore.WaitAsync();
2816
2817             try
2818             {
2819                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2820
2821                 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2822             }
2823             catch (WebApiException ex)
2824             {
2825                 this._myStatusError = true;
2826                 this.StatusLabel.Text = ex.Message;
2827             }
2828             finally
2829             {
2830                 this.workerSemaphore.Release();
2831             }
2832         }
2833
2834         private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2835         {
2836             if (ct.IsCancellationRequested)
2837                 return;
2838
2839             if (!CheckAccountValid())
2840                 throw new WebApiException("Auth error. Check your account");
2841
2842             var successIds = new List<long>();
2843
2844             await Task.Run(() =>
2845             {
2846                 //スレッド処理はしない
2847                 var allCount = 0;
2848                 var failedCount = 0;
2849
2850                 foreach (var statusId in statusIds)
2851                 {
2852                     allCount++;
2853
2854                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, allCount, statusIds.Count, failedCount));
2855
2856                     var post = tab.Posts[statusId];
2857
2858                     if (post.IsFav)
2859                         continue;
2860
2861                     try
2862                     {
2863                         this.tw.PostFavAdd(post.RetweetedId ?? post.StatusId);
2864                     }
2865                     catch (WebApiException)
2866                     {
2867                         failedCount++;
2868                         continue;
2869                     }
2870
2871                     successIds.Add(statusId);
2872                     post.IsFav = true; // リスト再描画必要
2873
2874                     this._favTimestamps.Add(DateTime.Now);
2875
2876                     // TLでも取得済みならfav反映
2877                     if (this._statuses.ContainsKey(statusId))
2878                     {
2879                         var postTl = this._statuses[statusId];
2880                         postTl.IsFav = true;
2881
2882                         var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2883                         favTab.AddPostImmediately(statusId, postTl.IsRead);
2884                     }
2885
2886                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
2887                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
2888                     {
2889                         if (tb.Contains(statusId))
2890                             tb.Posts[statusId].IsFav = true;
2891                     }
2892                 }
2893
2894                 // 時速表示用
2895                 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2896                 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2897                 {
2898                     if (this._favTimestamps[i] < oneHour)
2899                         this._favTimestamps.RemoveAt(i);
2900                 }
2901
2902                 this._statuses.DistributePosts();
2903             });
2904
2905             if (ct.IsCancellationRequested)
2906                 return;
2907
2908             this.RefreshTimeline();
2909
2910             if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2911             {
2912                 using (ControlTransaction.Update(this._curList))
2913                 {
2914                     foreach (var statusId in successIds)
2915                     {
2916                         var idx = tab.IndexOf(statusId);
2917                         if (idx == -1)
2918                             continue;
2919
2920                         var post = tab.Posts[statusId];
2921                         this.ChangeCacheStyleRead(post.IsRead, idx);
2922                     }
2923                 }
2924
2925                 if (successIds.Contains(this._curPost.StatusId))
2926                     await this.DispSelectedPost(true); // 選択アイテム再表示
2927             }
2928         }
2929
2930         private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabClass tab)
2931         {
2932             await this.workerSemaphore.WaitAsync();
2933
2934             try
2935             {
2936                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2937
2938                 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2939             }
2940             catch (WebApiException ex)
2941             {
2942                 this._myStatusError = true;
2943                 this.StatusLabel.Text = ex.Message;
2944             }
2945             finally
2946             {
2947                 this.workerSemaphore.Release();
2948             }
2949         }
2950
2951         private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2952         {
2953             if (ct.IsCancellationRequested)
2954                 return;
2955
2956             if (!CheckAccountValid())
2957                 throw new WebApiException("Auth error. Check your account");
2958
2959             var successIds = new List<long>();
2960
2961             await Task.Run(() =>
2962             {
2963                 //スレッド処理はしない
2964                 var allCount = 0;
2965                 var failedCount = 0;
2966                 foreach (var statusId in statusIds)
2967                 {
2968                     allCount++;
2969
2970                     var post = tab.Posts[statusId];
2971
2972                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2973
2974                     if (!post.IsFav)
2975                         continue;
2976
2977                     try
2978                     {
2979                         this.tw.PostFavRemove(post.RetweetedId ?? post.StatusId);
2980                     }
2981                     catch (WebApiException)
2982                     {
2983                         failedCount++;
2984                         continue;
2985                     }
2986
2987                     successIds.Add(statusId);
2988                     post.IsFav = false; // リスト再描画必要
2989
2990                     if (this._statuses.ContainsKey(statusId))
2991                     {
2992                         this._statuses[statusId].IsFav = false;
2993                     }
2994
2995                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
2996                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
2997                     {
2998                         if (tb.Contains(statusId))
2999                             tb.Posts[statusId].IsFav = false;
3000                     }
3001                 }
3002             });
3003
3004             if (ct.IsCancellationRequested)
3005                 return;
3006
3007             this.RemovePostFromFavTab(successIds.ToArray());
3008
3009             this.RefreshTimeline();
3010
3011             if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
3012             {
3013                 if (tab.TabType == MyCommon.TabUsageType.Favorites)
3014                 {
3015                     // 色変えは不要
3016                 }
3017                 else
3018                 {
3019                     using (ControlTransaction.Update(this._curList))
3020                     {
3021                         foreach (var statusId in successIds)
3022                         {
3023                             var idx = tab.IndexOf(statusId);
3024                             if (idx == -1)
3025                                 continue;
3026
3027                             var post = tab.Posts[statusId];
3028                             this.ChangeCacheStyleRead(post.IsRead, idx);
3029                         }
3030                     }
3031
3032                     if (successIds.Contains(this._curPost.StatusId))
3033                         await this.DispSelectedPost(true); // 選択アイテム再表示
3034                 }
3035             }
3036         }
3037
3038         private async Task PostMessageAsync(PostingStatus status)
3039         {
3040             await this.workerSemaphore.WaitAsync();
3041
3042             try
3043             {
3044                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3045
3046                 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
3047             }
3048             catch (WebApiException ex)
3049             {
3050                 this._myStatusError = true;
3051                 this.StatusLabel.Text = ex.Message;
3052             }
3053             finally
3054             {
3055                 this.workerSemaphore.Release();
3056             }
3057         }
3058
3059         private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
3060         {
3061             if (ct.IsCancellationRequested)
3062                 return;
3063
3064             if (!CheckAccountValid())
3065                 throw new WebApiException("Auth error. Check your account");
3066
3067             p.Report("Posting...");
3068
3069             var errMsg = "";
3070
3071             try
3072             {
3073                 await Task.Run(async () =>
3074                 {
3075                     if (status.mediaItems == null || status.mediaItems.Length == 0)
3076                     {
3077                         this.tw.PostStatus(status.status, status.inReplyToId);
3078                     }
3079                     else
3080                     {
3081                         var service = ImageSelector.GetService(status.imageService);
3082                         await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
3083                             .ConfigureAwait(false);
3084                     }
3085                 });
3086
3087                 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3088             }
3089             catch (WebApiException ex)
3090             {
3091                 // 処理は中断せずエラーの表示のみ行う
3092                 errMsg = ex.Message;
3093                 p.Report(errMsg);
3094                 this._myStatusError = true;
3095             }
3096             finally
3097             {
3098                 // 使い終わった MediaItem は破棄する
3099                 if (status.mediaItems != null)
3100                 {
3101                     foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
3102                     {
3103                         disposableItem.Dispose();
3104                     }
3105                 }
3106             }
3107
3108             if (ct.IsCancellationRequested)
3109                 return;
3110
3111             if (!string.IsNullOrEmpty(errMsg) &&
3112                 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
3113                 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
3114             {
3115                 var ret = MessageBox.Show(
3116                     string.Format(
3117                         "{0}   --->   [ " + errMsg + " ]" + Environment.NewLine +
3118                         "\"" + status.status + "\"" + Environment.NewLine +
3119                         "{1}",
3120                         Properties.Resources.StatusUpdateFailed1,
3121                         Properties.Resources.StatusUpdateFailed2),
3122                     "Failed to update status",
3123                     MessageBoxButtons.RetryCancel,
3124                     MessageBoxIcon.Question);
3125
3126                 if (ret == DialogResult.Retry)
3127                 {
3128                     await this.PostMessageAsync(status);
3129                 }
3130                 else
3131                 {
3132                     // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3133                     if (this.ToolStripFocusLockMenuItem.Checked)
3134                         this.StatusText_Enter(this.StatusText, EventArgs.Empty);
3135                 }
3136                 return;
3137             }
3138
3139             this._postTimestamps.Add(DateTime.Now);
3140
3141             var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3142             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3143             {
3144                 if (this._postTimestamps[i] < oneHour)
3145                     this._postTimestamps.RemoveAt(i);
3146             }
3147
3148             if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
3149             {
3150                 this.HashMgr.ClearHashtag();
3151                 this.HashStripSplitButton.Text = "#[-]";
3152                 this.HashToggleMenuItem.Checked = false;
3153                 this.HashToggleToolStripMenuItem.Checked = false;
3154             }
3155
3156             this.SetMainWindowTitle();
3157
3158             if (this._cfgCommon.PostAndGet)
3159             {
3160                 if (this._isActiveUserstream)
3161                     this.RefreshTimeline();
3162                 else
3163                     await this.GetHomeTimelineAsync();
3164             }
3165         }
3166
3167         private async Task RetweetAsync(IReadOnlyList<long> statusIds)
3168         {
3169             await this.workerSemaphore.WaitAsync();
3170
3171             try
3172             {
3173                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3174
3175                 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
3176             }
3177             catch (WebApiException ex)
3178             {
3179                 this._myStatusError = true;
3180                 this.StatusLabel.Text = ex.Message;
3181             }
3182             finally
3183             {
3184                 this.workerSemaphore.Release();
3185             }
3186         }
3187
3188         private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
3189         {
3190             if (ct.IsCancellationRequested)
3191                 return;
3192
3193             if (!CheckAccountValid())
3194                 throw new WebApiException("Auth error. Check your account");
3195
3196             bool read;
3197             if (!this._cfgCommon.UnreadManage)
3198                 read = true;
3199             else
3200                 read = this._initial && this._cfgCommon.Read;
3201
3202             p.Report("Posting...");
3203
3204             await Task.Run(() =>
3205             {
3206                 foreach (var statusId in statusIds)
3207                 {
3208                     this.tw.PostRetweet(statusId, read);
3209                 }
3210             });
3211
3212             if (ct.IsCancellationRequested)
3213                 return;
3214
3215             p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3216
3217             this._postTimestamps.Add(DateTime.Now);
3218
3219             var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3220             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3221             {
3222                 if (this._postTimestamps[i] < oneHour)
3223                     this._postTimestamps.RemoveAt(i);
3224             }
3225
3226             if (this._cfgCommon.PostAndGet && !this._isActiveUserstream)
3227                 await this.GetHomeTimelineAsync();
3228         }
3229
3230         private async Task RefreshFollowerIdsAsync()
3231         {
3232             await this.workerSemaphore.WaitAsync();
3233             try
3234             {
3235                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
3236
3237                 await Task.Run(() => tw.RefreshFollowerIds());
3238
3239                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
3240
3241                 this.RefreshTimeline();
3242                 this.PurgeListViewItemCache();
3243                 this._curList?.Refresh();
3244             }
3245             catch (WebApiException ex)
3246             {
3247                 this.StatusLabel.Text = ex.Message;
3248             }
3249             finally
3250             {
3251                 this.workerSemaphore.Release();
3252             }
3253         }
3254
3255         private async Task RefreshNoRetweetIdsAsync()
3256         {
3257             await this.workerSemaphore.WaitAsync();
3258             try
3259             {
3260                 await Task.Run(() => tw.RefreshNoRetweetIds());
3261
3262                 this.StatusLabel.Text = "NoRetweetIds refreshed";
3263             }
3264             catch (WebApiException ex)
3265             {
3266                 this.StatusLabel.Text = ex.Message;
3267             }
3268             finally
3269             {
3270                 this.workerSemaphore.Release();
3271             }
3272         }
3273
3274         private async Task RefreshBlockIdsAsync()
3275         {
3276             await this.workerSemaphore.WaitAsync();
3277             try
3278             {
3279                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
3280
3281                 await Task.Run(() => tw.RefreshBlockIds());
3282
3283                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
3284             }
3285             catch (WebApiException ex)
3286             {
3287                 this.StatusLabel.Text = ex.Message;
3288             }
3289             finally
3290             {
3291                 this.workerSemaphore.Release();
3292             }
3293         }
3294
3295         private async Task RefreshTwitterConfigurationAsync()
3296         {
3297             await this.workerSemaphore.WaitAsync();
3298             try
3299             {
3300                 await Task.Run(() => tw.RefreshConfiguration());
3301
3302                 if (this.tw.Configuration.PhotoSizeLimit != 0)
3303                 {
3304                     foreach (var service in this.ImageSelector.GetServices())
3305                     {
3306                         service.UpdateTwitterConfiguration(this.tw.Configuration);
3307                     }
3308                 }
3309
3310                 this.PurgeListViewItemCache();
3311
3312                 this._curList?.Refresh();
3313             }
3314             catch (WebApiException ex)
3315             {
3316                 this.StatusLabel.Text = ex.Message;
3317             }
3318             finally
3319             {
3320                 this.workerSemaphore.Release();
3321             }
3322         }
3323
3324         private async Task RefreshMuteUserIdsAsync()
3325         {
3326             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3327
3328             try
3329             {
3330                 await tw.RefreshMuteUserIdsAsync();
3331             }
3332             catch (WebApiException ex)
3333             {
3334                 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3335                 return;
3336             }
3337
3338             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3339         }
3340
3341         private void RemovePostFromFavTab(Int64[] ids)
3342         {
3343             var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3344             string favTabName = favTab.TabName;
3345             int fidx = 0;
3346             if (_curTab.Text.Equals(favTabName))
3347             {
3348                 fidx = _curList.FocusedItem?.Index ?? _curList.TopItem?.Index ?? 0;
3349             }
3350
3351             foreach (long i in ids)
3352             {
3353                 try
3354                 {
3355                     _statuses.RemoveFavPost(i);
3356                 }
3357                 catch (Exception)
3358                 {
3359                     continue;
3360                 }
3361             }
3362             if (_curTab != null && _curTab.Text.Equals(favTabName))
3363             {
3364                 this.PurgeListViewItemCache();
3365                 _curPost = null;
3366                 //_curItemIndex = -1;
3367             }
3368             foreach (TabPage tp in ListTab.TabPages)
3369             {
3370                 if (tp.Text == favTabName)
3371                 {
3372                     ((DetailsListView)tp.Tag).VirtualListSize = favTab.AllCount;
3373                     break;
3374                 }
3375             }
3376             if (_curTab.Text.Equals(favTabName))
3377             {
3378                 do
3379                 {
3380                     _curList.SelectedIndices.Clear();
3381                 }
3382                 while (_curList.SelectedIndices.Count > 0);
3383
3384                 if (favTab.AllCount > 0)
3385                 {
3386                     if (favTab.AllCount - 1 > fidx && fidx > -1)
3387                     {
3388                         _curList.SelectedIndices.Add(fidx);
3389                     }
3390                     else
3391                     {
3392                         _curList.SelectedIndices.Add(favTab.AllCount - 1);
3393                     }
3394                     if (_curList.SelectedIndices.Count > 0)
3395                     {
3396                         _curList.EnsureVisible(_curList.SelectedIndices[0]);
3397                         _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3398                     }
3399                 }
3400             }
3401         }
3402
3403         private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3404         {
3405             if (e.Button == MouseButtons.Left)
3406             {
3407                 this.Visible = true;
3408                 if (this.WindowState == FormWindowState.Minimized)
3409                 {
3410                     this.WindowState = _formWindowState;
3411                 }
3412                 this.Activate();
3413                 this.BringToFront();
3414             }
3415         }
3416
3417         private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3418         {
3419             switch (this._cfgCommon.ListDoubleClickAction)
3420             {
3421                 case 0:
3422                     MakeReplyOrDirectStatus();
3423                     break;
3424                 case 1:
3425                     await this.FavoriteChange(true);
3426                     break;
3427                 case 2:
3428                     if (_curPost != null)
3429                         await this.ShowUserStatus(_curPost.ScreenName, false);
3430                     break;
3431                 case 3:
3432                     ShowUserTimeline();
3433                     break;
3434                 case 4:
3435                     ShowRelatedStatusesMenuItem_Click(null, null);
3436                     break;
3437                 case 5:
3438                     MoveToHomeToolStripMenuItem_Click(null, null);
3439                     break;
3440                 case 6:
3441                     StatusOpenMenuItem_Click(null, null);
3442                     break;
3443                 case 7:
3444                     //動作なし
3445                     break;
3446             }
3447         }
3448
3449         private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3450         {
3451             await this.FavoriteChange(true);
3452         }
3453
3454         private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3455         {
3456             await this.FavoriteChange(false);
3457         }
3458
3459
3460         private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3461         {
3462             await this.FavoritesRetweetOfficial();
3463         }
3464
3465         private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3466         {
3467             await this.FavoritesRetweetUnofficial();
3468         }
3469
3470         private async Task FavoriteChange(bool FavAdd , bool multiFavoriteChangeDialogEnable = true)
3471         {
3472             TabClass tab;
3473             if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3474                 return;
3475
3476             //trueでFavAdd,falseでFavRemove
3477             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3478                 || !this.ExistCurrentPost) return;
3479
3480             // 誤ふぁぼ・故意によるふぁぼ爆対策 (変更しないこと)
3481             // https://support.twitter.com/articles/76915#favoriting
3482             const int MultiSelectFavLimit = 1;
3483
3484             //複数fav確認msg
3485             if (_curList.SelectedIndices.Count > MultiSelectFavLimit && FavAdd)
3486             {
3487                 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, MultiSelectFavLimit));
3488                 _DoFavRetweetFlags = false;
3489                 return;
3490             }
3491             else if (multiFavoriteChangeDialogEnable && _curList.SelectedIndices.Count > 1)
3492             {
3493                 if (FavAdd)
3494                 {
3495                     string QuestionText = Properties.Resources.FavAddToolStripMenuItem_ClickText1;
3496                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText3;
3497                     if (MessageBox.Show(QuestionText, Properties.Resources.FavAddToolStripMenuItem_ClickText2,
3498                                        MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3499                     {
3500                         _DoFavRetweetFlags = false;
3501                         return;
3502                     }
3503                 }
3504                 else
3505                 {
3506                     if (MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1, Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3507                                     MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3508                     {
3509                         return;
3510                     }
3511                 }
3512             }
3513
3514             var statusIds = new List<long>();
3515             foreach (int idx in _curList.SelectedIndices)
3516             {
3517                 PostClass post = GetCurTabPost(idx);
3518                 if (FavAdd)
3519                 {
3520                     if (!post.IsFav)
3521                         statusIds.Add(post.StatusId);
3522                 }
3523                 else
3524                 {
3525                     if (post.IsFav)
3526                         statusIds.Add(post.StatusId);
3527                 }
3528             }
3529             if (statusIds.Count == 0)
3530             {
3531                 if (FavAdd)
3532                     StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3533                 else
3534                     StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3535
3536                 return;
3537             }
3538
3539             if (FavAdd)
3540                 await this.FavAddAsync(statusIds, tab);
3541             else
3542                 await this.FavRemoveAsync(statusIds, tab);
3543         }
3544
3545         private PostClass GetCurTabPost(int Index)
3546         {
3547             var listCache = this._listItemCache;
3548             if (listCache != null)
3549             {
3550                 ListViewItem item;
3551                 PostClass post;
3552                 if (listCache.TryGetValue(Index, out item, out post))
3553                     return post;
3554             }
3555
3556             return _statuses.Tabs[_curTab.Text][Index];
3557         }
3558
3559         private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3560         {
3561             if (_curList.SelectedIndices.Count > 0)
3562                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3563             else if (_curList.SelectedIndices.Count == 0)
3564                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3565         }
3566
3567         private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3568         {
3569             if (_curList.SelectedIndices.Count > 0)
3570                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3571         }
3572
3573         private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3574         {
3575             if ((!_initialLayout) && this.Visible)
3576             {
3577                 if (this.WindowState == FormWindowState.Normal)
3578                 {
3579                     _mySize = this.ClientSize;
3580                     _mySpDis = this.SplitContainer1.SplitterDistance;
3581                     _mySpDis3 = this.SplitContainer3.SplitterDistance;
3582                     if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3583                     ModifySettingLocal = true;
3584                 }
3585             }
3586         }
3587
3588         private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3589         {
3590             var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3591             if (comparerMode == null)
3592                 return;
3593
3594             this.SetSortColumn(comparerMode.Value);
3595         }
3596
3597         /// <summary>
3598         /// 列インデックスからソートを行う ComparerMode を求める
3599         /// </summary>
3600         /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3601         /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3602         private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3603         {
3604             if (this._iconCol)
3605                 return ComparerMode.Id;
3606
3607             switch (columnIndex)
3608             {
3609                 case 1: // ニックネーム
3610                     return ComparerMode.Nickname;
3611                 case 2: // 本文
3612                     return ComparerMode.Data;
3613                 case 3: // 時刻=発言Id
3614                     return ComparerMode.Id;
3615                 case 4: // 名前
3616                     return ComparerMode.Name;
3617                 case 7: // Source
3618                     return ComparerMode.Source;
3619                 default:
3620                     // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3621                     return null;
3622             }
3623         }
3624
3625         /// <summary>
3626         /// 発言一覧の指定した位置の列でソートする
3627         /// </summary>
3628         /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3629         private void SetSortColumnByDisplayIndex(int columnIndex)
3630         {
3631             // 表示上の列の位置から ColumnHeader を求める
3632             var col = this._curList.Columns.Cast<ColumnHeader>()
3633                 .Where(x => x.DisplayIndex == columnIndex)
3634                 .FirstOrDefault();
3635
3636             if (col == null)
3637                 return;
3638
3639             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3640             if (comparerMode == null)
3641                 return;
3642
3643             this.SetSortColumn(comparerMode.Value);
3644         }
3645
3646         /// <summary>
3647         /// 発言一覧の最後列の項目でソートする
3648         /// </summary>
3649         private void SetSortLastColumn()
3650         {
3651             // 表示上の最後列にある ColumnHeader を求める
3652             var col = this._curList.Columns.Cast<ColumnHeader>()
3653                 .OrderByDescending(x => x.DisplayIndex)
3654                 .First();
3655
3656             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3657             if (comparerMode == null)
3658                 return;
3659
3660             this.SetSortColumn(comparerMode.Value);
3661         }
3662
3663         /// <summary>
3664         /// 発言一覧を指定された ComparerMode に基づいてソートする
3665         /// </summary>
3666         private void SetSortColumn(ComparerMode sortColumn)
3667         {
3668             if (this._cfgCommon.SortOrderLock)
3669                 return;
3670
3671             this._statuses.ToggleSortOrder(sortColumn);
3672             this.InitColumnText();
3673
3674             var list = this._curList;
3675             if (_iconCol)
3676             {
3677                 list.Columns[0].Text = this.ColumnText[0];
3678                 list.Columns[1].Text = this.ColumnText[2];
3679             }
3680             else
3681             {
3682                 for (var i = 0; i <= 7; i++)
3683                 {
3684                     list.Columns[i].Text = this.ColumnText[i];
3685                 }
3686             }
3687
3688             this.PurgeListViewItemCache();
3689
3690             var tab = this._statuses.Tabs[this._curTab.Text];
3691             if (tab.AllCount > 0 && this._curPost != null)
3692             {
3693                 var idx = tab.IndexOf(this._curPost.StatusId);
3694                 if (idx > -1)
3695                 {
3696                     this.SelectListItem(list, idx);
3697                     list.EnsureVisible(idx);
3698                 }
3699             }
3700             list.Refresh();
3701
3702             this.ModifySettingCommon = true;
3703         }
3704
3705         private void TweenMain_LocationChanged(object sender, EventArgs e)
3706         {
3707             if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3708             {
3709                 _myLoc = this.DesktopLocation;
3710                 ModifySettingLocal = true;
3711             }
3712         }
3713
3714         private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3715         {
3716             if (ListTab.SelectedTab == null) return;
3717             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3718             if (!this.ExistCurrentPost)
3719             {
3720                 ReplyStripMenuItem.Enabled = false;
3721                 ReplyAllStripMenuItem.Enabled = false;
3722                 DMStripMenuItem.Enabled = false;
3723                 ShowProfileMenuItem.Enabled = false;
3724                 ShowUserTimelineContextMenuItem.Enabled = false;
3725                 ListManageUserContextToolStripMenuItem2.Enabled = false;
3726                 MoveToFavToolStripMenuItem.Enabled = false;
3727                 TabMenuItem.Enabled = false;
3728                 IDRuleMenuItem.Enabled = false;
3729                 SourceRuleMenuItem.Enabled = false;
3730                 ReadedStripMenuItem.Enabled = false;
3731                 UnreadStripMenuItem.Enabled = false;
3732             }
3733             else
3734             {
3735                 ShowProfileMenuItem.Enabled = true;
3736                 ListManageUserContextToolStripMenuItem2.Enabled = true;
3737                 ReplyStripMenuItem.Enabled = true;
3738                 ReplyAllStripMenuItem.Enabled = true;
3739                 DMStripMenuItem.Enabled = true;
3740                 ShowUserTimelineContextMenuItem.Enabled = true;
3741                 MoveToFavToolStripMenuItem.Enabled = true;
3742                 TabMenuItem.Enabled = true;
3743                 IDRuleMenuItem.Enabled = true;
3744                 SourceRuleMenuItem.Enabled = true;
3745                 ReadedStripMenuItem.Enabled = true;
3746                 UnreadStripMenuItem.Enabled = true;
3747             }
3748             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3749             {
3750                 FavAddToolStripMenuItem.Enabled = false;
3751                 FavRemoveToolStripMenuItem.Enabled = false;
3752                 StatusOpenMenuItem.Enabled = false;
3753                 FavorareMenuItem.Enabled = false;
3754                 ShowRelatedStatusesMenuItem.Enabled = false;
3755
3756                 ReTweetStripMenuItem.Enabled = false;
3757                 ReTweetUnofficialStripMenuItem.Enabled = false;
3758                 QuoteStripMenuItem.Enabled = false;
3759                 FavoriteRetweetContextMenu.Enabled = false;
3760                 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3761             }
3762             else
3763             {
3764                 FavAddToolStripMenuItem.Enabled = true;
3765                 FavRemoveToolStripMenuItem.Enabled = true;
3766                 StatusOpenMenuItem.Enabled = true;
3767                 FavorareMenuItem.Enabled = true;
3768                 ShowRelatedStatusesMenuItem.Enabled = true;  //PublicSearchの時問題出るかも
3769
3770                 if (_curPost.IsMe)
3771                 {
3772                     ReTweetStripMenuItem.Enabled = false;  //公式RTは無効に
3773                     ReTweetUnofficialStripMenuItem.Enabled = true;
3774                     QuoteStripMenuItem.Enabled = true;
3775                     FavoriteRetweetContextMenu.Enabled = false;  //公式RTは無効に
3776                     FavoriteRetweetUnofficialContextMenu.Enabled = true;
3777                 }
3778                 else
3779                 {
3780                     if (_curPost.IsProtect)
3781                     {
3782                         ReTweetStripMenuItem.Enabled = false;
3783                         ReTweetUnofficialStripMenuItem.Enabled = false;
3784                         QuoteStripMenuItem.Enabled = false;
3785                         FavoriteRetweetContextMenu.Enabled = false;
3786                         FavoriteRetweetUnofficialContextMenu.Enabled = false;
3787                     }
3788                     else
3789                     {
3790                         ReTweetStripMenuItem.Enabled = true;
3791                         ReTweetUnofficialStripMenuItem.Enabled = true;
3792                         QuoteStripMenuItem.Enabled = true;
3793                         FavoriteRetweetContextMenu.Enabled = true;
3794                         FavoriteRetweetUnofficialContextMenu.Enabled = true;
3795                     }
3796                 }
3797             }
3798             //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3799             //{
3800             //    RefreshMoreStripMenuItem.Enabled = true;
3801             //}
3802             //else
3803             //{
3804             //    RefreshMoreStripMenuItem.Enabled = false;
3805             //}
3806             if (!this.ExistCurrentPost
3807                 || _curPost.InReplyToStatusId == null)
3808             {
3809                 RepliedStatusOpenMenuItem.Enabled = false;
3810             }
3811             else
3812             {
3813                 RepliedStatusOpenMenuItem.Enabled = true;
3814             }
3815             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3816             {
3817                 MoveToRTHomeMenuItem.Enabled = false;
3818             }
3819             else
3820             {
3821                 MoveToRTHomeMenuItem.Enabled = true;
3822             }
3823
3824             if (this.ExistCurrentPost)
3825             {
3826                 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3827                 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3828                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3829                 else
3830                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3831             }
3832         }
3833
3834         private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3835         {
3836             MakeReplyOrDirectStatus(false, true);
3837         }
3838
3839         private void DMStripMenuItem_Click(object sender, EventArgs e)
3840         {
3841             MakeReplyOrDirectStatus(false, false);
3842         }
3843
3844         private void doStatusDelete()
3845         {
3846             if (this._curTab == null || this._curList == null)
3847                 return;
3848
3849             if (this._curList.SelectedIndices.Count == 0)
3850                 return;
3851
3852             var posts = this._curList.SelectedIndices.Cast<int>()
3853                 .Select(x => this.GetCurTabPost(x))
3854                 .ToArray();
3855
3856             // 選択されたツイートの中に削除可能なものが一つでもあるか
3857             if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3858                 return;
3859
3860             var ret = MessageBox.Show(this,
3861                 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3862                 Properties.Resources.DeleteStripMenuItem_ClickText2,
3863                 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3864
3865             if (ret != DialogResult.OK)
3866                 return;
3867
3868             var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3869
3870             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3871             {
3872                 Exception lastException = null;
3873                 foreach (var post in posts)
3874                 {
3875                     if (!post.CanDeleteBy(this.tw.UserId))
3876                         continue;
3877
3878                     try
3879                     {
3880                         if (post.IsDm)
3881                         {
3882                             this.tw.RemoveDirectMessage(post.StatusId, post);
3883                         }
3884                         else
3885                         {
3886                             if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3887                                 // 他人に RT された自分のツイート
3888                                 this.tw.RemoveStatus(post.RetweetedId.Value);
3889                             else
3890                                 // 自分のツイート or 自分が RT したツイート
3891                                 this.tw.RemoveStatus(post.StatusId);
3892                         }
3893                     }
3894                     catch (WebApiException ex)
3895                     {
3896                         lastException = ex;
3897                         continue;
3898                     }
3899
3900                     this._statuses.RemovePost(post.StatusId);
3901                 }
3902
3903                 if (lastException == null)
3904                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3905                 else
3906                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3907
3908                 this.PurgeListViewItemCache();
3909                 this._curPost = null;
3910                 this._curItemIndex = -1;
3911
3912                 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3913                 {
3914                     var listView = (DetailsListView)tabPage.Tag;
3915                     var tab = this._statuses.Tabs[tabPage.Text];
3916
3917                     using (ControlTransaction.Update(listView))
3918                     {
3919                         listView.VirtualListSize = tab.AllCount;
3920
3921                         if (tabPage == this._curTab)
3922                         {
3923                             listView.SelectedIndices.Clear();
3924
3925                             if (tab.AllCount != 0)
3926                             {
3927                                 int selectedIndex;
3928                                 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3929                                     selectedIndex = focusedIndex;
3930                                 else
3931                                     selectedIndex = tab.AllCount - 1;
3932
3933                                 listView.SelectedIndices.Add(selectedIndex);
3934                                 listView.EnsureVisible(selectedIndex);
3935                                 listView.FocusedItem = listView.Items[selectedIndex];
3936                             }
3937                         }
3938                     }
3939
3940                     if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3941                     {
3942                         if (tabPage.ImageIndex == 0)
3943                             tabPage.ImageIndex = -1; // タブアイコン
3944                     }
3945                 }
3946
3947                 if (!this._cfgCommon.TabIconDisp)
3948                     this.ListTab.Refresh();
3949             }
3950         }
3951
3952         private void DeleteStripMenuItem_Click(object sender, EventArgs e)
3953         {
3954             doStatusDelete();
3955         }
3956
3957         private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3958         {
3959             using (ControlTransaction.Update(this._curList))
3960             {
3961                 foreach (int idx in _curList.SelectedIndices)
3962                 {
3963                     var post = this._statuses.Tabs[this._curTab.Text][idx];
3964                     this._statuses.SetReadAllTab(post.StatusId, read: true);
3965                     ChangeCacheStyleRead(true, idx);
3966                 }
3967                 ColorizeList();
3968             }
3969             foreach (TabPage tb in ListTab.TabPages)
3970             {
3971                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3972                 {
3973                     if (this._cfgCommon.TabIconDisp)
3974                     {
3975                         if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3976                     }
3977                 }
3978             }
3979             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3980         }
3981
3982         private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3983         {
3984             using (ControlTransaction.Update(this._curList))
3985             {
3986                 foreach (int idx in _curList.SelectedIndices)
3987                 {
3988                     var post = this._statuses.Tabs[this._curTab.Text][idx];
3989                     this._statuses.SetReadAllTab(post.StatusId, read: false);
3990                     ChangeCacheStyleRead(false, idx);
3991                 }
3992                 ColorizeList();
3993             }
3994             foreach (TabPage tb in ListTab.TabPages)
3995             {
3996                 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3997                 {
3998                     if (this._cfgCommon.TabIconDisp)
3999                     {
4000                         if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
4001                     }
4002                 }
4003             }
4004             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
4005         }
4006
4007         private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
4008         {
4009             await this.DoRefresh();
4010         }
4011
4012         private async Task DoRefresh()
4013         {
4014             if (_curTab != null)
4015             {
4016                 TabClass tab;
4017                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4018                     return;
4019
4020                 switch (_statuses.Tabs[_curTab.Text].TabType)
4021                 {
4022                     case MyCommon.TabUsageType.Mentions:
4023                         await this.GetReplyAsync();
4024                         break;
4025                     case MyCommon.TabUsageType.DirectMessage:
4026                         await this.GetDirectMessagesAsync();
4027                         break;
4028                     case MyCommon.TabUsageType.Favorites:
4029                         await this.GetFavoritesAsync();
4030                         break;
4031                     //case MyCommon.TabUsageType.Profile:
4032                         //// TODO
4033                     case MyCommon.TabUsageType.PublicSearch:
4034                         //// TODO
4035                         if (string.IsNullOrEmpty(tab.SearchWords)) return;
4036                         await this.GetPublicSearchAsync(tab);
4037                         break;
4038                     case MyCommon.TabUsageType.UserTimeline:
4039                         await this.GetUserTimelineAsync(tab);
4040                         break;
4041                     case MyCommon.TabUsageType.Lists:
4042                         //// TODO
4043                         if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4044                         await this.GetListTimelineAsync(tab);
4045                         break;
4046                     default:
4047                         await this.GetHomeTimelineAsync();
4048                         break;
4049                 }
4050             }
4051             else
4052             {
4053                 await this.GetHomeTimelineAsync();
4054             }
4055         }
4056
4057         private async Task DoRefreshMore()
4058         {
4059             //ページ指定をマイナス1に
4060             if (_curTab != null)
4061             {
4062                 TabClass tab;
4063                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4064                     return;
4065
4066                 switch (_statuses.Tabs[_curTab.Text].TabType)
4067                 {
4068                     case MyCommon.TabUsageType.Mentions:
4069                         await this.GetReplyAsync(loadMore: true);
4070                         break;
4071                     case MyCommon.TabUsageType.DirectMessage:
4072                         await this.GetDirectMessagesAsync(loadMore: true);
4073                         break;
4074                     case MyCommon.TabUsageType.Favorites:
4075                         await this.GetFavoritesAsync(loadMore: true);
4076                         break;
4077                     case MyCommon.TabUsageType.Profile:
4078                         //// TODO
4079                         break;
4080                     case MyCommon.TabUsageType.PublicSearch:
4081                         // TODO
4082                         if (string.IsNullOrEmpty(tab.SearchWords)) return;
4083                         await this.GetPublicSearchAsync(tab, loadMore: true);
4084                         break;
4085                     case MyCommon.TabUsageType.UserTimeline:
4086                         await this.GetUserTimelineAsync(tab, loadMore: true);
4087                         break;
4088                     case MyCommon.TabUsageType.Lists:
4089                         //// TODO
4090                         if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4091                         await this.GetListTimelineAsync(tab, loadMore: true);
4092                         break;
4093                     default:
4094                         await this.GetHomeTimelineAsync(loadMore: true);
4095                         break;
4096                 }
4097             }
4098             else
4099             {
4100                 await this.GetHomeTimelineAsync(loadMore: true);
4101             }
4102         }
4103
4104         private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4105         {
4106             DialogResult result = DialogResult.Abort;
4107
4108             using (var settingDialog = new AppendSettingDialog())
4109             {
4110                 settingDialog.Icon = this.MainIcon;
4111                 settingDialog.Owner = this;
4112                 settingDialog.ShowInTaskbar = showTaskbarIcon;
4113                 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4114
4115                 settingDialog.tw = this.tw;
4116                 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4117
4118                 try
4119                 {
4120                     result = settingDialog.ShowDialog(this);
4121                 }
4122                 catch (Exception)
4123                 {
4124                     return DialogResult.Abort;
4125                 }
4126
4127                 if (result == DialogResult.OK)
4128                 {
4129                     lock (_syncObject)
4130                     {
4131                         settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4132                     }
4133                 }
4134             }
4135
4136             return result;
4137         }
4138
4139         private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4140         {
4141             // 設定画面表示前のユーザー情報
4142             var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4143
4144             var oldIconSz = this._cfgCommon.IconSize;
4145
4146             if (ShowSettingDialog() == DialogResult.OK)
4147             {
4148                 lock (_syncObject)
4149                 {
4150                     tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4151                     tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4152                     ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4153                     ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4154                     ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4155                     HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
4156
4157                     Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4158                     Networking.SetWebProxy(this._cfgLocal.ProxyType,
4159                         this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4160                         this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4161                     Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
4162
4163                     ImageSelector.Reset(tw, this.tw.Configuration);
4164
4165                     try
4166                     {
4167                         if (this._cfgCommon.TabIconDisp)
4168                         {
4169                             ListTab.DrawItem -= ListTab_DrawItem;
4170                             ListTab.DrawMode = TabDrawMode.Normal;
4171                             ListTab.ImageList = this.TabImage;
4172                         }
4173                         else
4174                         {
4175                             ListTab.DrawItem -= ListTab_DrawItem;
4176                             ListTab.DrawItem += ListTab_DrawItem;
4177                             ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4178                             ListTab.ImageList = null;
4179                         }
4180                     }
4181                     catch (Exception ex)
4182                     {
4183                         ex.Data["Instance"] = "ListTab(TabIconDisp)";
4184                         ex.Data["IsTerminatePermission"] = false;
4185                         throw;
4186                     }
4187
4188                     try
4189                     {
4190                         if (!this._cfgCommon.UnreadManage)
4191                         {
4192                             ReadedStripMenuItem.Enabled = false;
4193                             UnreadStripMenuItem.Enabled = false;
4194                             if (this._cfgCommon.TabIconDisp)
4195                             {
4196                                 foreach (TabPage myTab in ListTab.TabPages)
4197                                 {
4198                                     myTab.ImageIndex = -1;
4199                                 }
4200                             }
4201                         }
4202                         else
4203                         {
4204                             ReadedStripMenuItem.Enabled = true;
4205                             UnreadStripMenuItem.Enabled = true;
4206                         }
4207                     }
4208                     catch (Exception ex)
4209                     {
4210                         ex.Data["Instance"] = "ListTab(UnreadManage)";
4211                         ex.Data["IsTerminatePermission"] = false;
4212                         throw;
4213                     }
4214
4215                     // タブの表示位置の決定
4216                     SetTabAlignment();
4217
4218                     SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4219
4220                     var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4221                     imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4222                     imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4223
4224                     this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4225                     this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4226                     _fntUnread = this._cfgLocal.FontUnread;
4227                     _clUnread = this._cfgLocal.ColorUnread;
4228                     _fntReaded = this._cfgLocal.FontRead;
4229                     _clReaded = this._cfgLocal.ColorRead;
4230                     _clFav = this._cfgLocal.ColorFav;
4231                     _clOWL = this._cfgLocal.ColorOWL;
4232                     _clRetweet = this._cfgLocal.ColorRetweet;
4233                     _fntDetail = this._cfgLocal.FontDetail;
4234                     _clDetail = this._cfgLocal.ColorDetail;
4235                     _clDetailLink = this._cfgLocal.ColorDetailLink;
4236                     _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4237                     _clSelf = this._cfgLocal.ColorSelf;
4238                     _clAtSelf = this._cfgLocal.ColorAtSelf;
4239                     _clTarget = this._cfgLocal.ColorTarget;
4240                     _clAtTarget = this._cfgLocal.ColorAtTarget;
4241                     _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4242                     _clAtTo = this._cfgLocal.ColorAtTo;
4243                     _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4244                     _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4245                     _clInputFont = this._cfgLocal.ColorInputFont;
4246                     _fntInputFont = this._cfgLocal.FontInputFont;
4247                     _brsBackColorMine.Dispose();
4248                     _brsBackColorAt.Dispose();
4249                     _brsBackColorYou.Dispose();
4250                     _brsBackColorAtYou.Dispose();
4251                     _brsBackColorAtFromTarget.Dispose();
4252                     _brsBackColorAtTo.Dispose();
4253                     _brsBackColorNone.Dispose();
4254                     _brsBackColorMine = new SolidBrush(_clSelf);
4255                     _brsBackColorAt = new SolidBrush(_clAtSelf);
4256                     _brsBackColorYou = new SolidBrush(_clTarget);
4257                     _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4258                     _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4259                     _brsBackColorAtTo = new SolidBrush(_clAtTo);
4260                     _brsBackColorNone = new SolidBrush(_clListBackcolor);
4261
4262                     try
4263                     {
4264                         if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4265                         StatusText.Font = _fntInputFont;
4266                         StatusText.ForeColor = _clInputFont;
4267                     }
4268                     catch (Exception ex)
4269                     {
4270                         MessageBox.Show(ex.Message);
4271                     }
4272
4273                     try
4274                     {
4275                         InitDetailHtmlFormat();
4276                     }
4277                     catch (Exception ex)
4278                     {
4279                         ex.Data["Instance"] = "Font";
4280                         ex.Data["IsTerminatePermission"] = false;
4281                         throw;
4282                     }
4283
4284                     try
4285                     {
4286                         foreach (TabPage tb in ListTab.TabPages)
4287                         {
4288                             if (this._cfgCommon.TabIconDisp)
4289                             {
4290                                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4291                                     tb.ImageIndex = -1;
4292                                 else
4293                                     tb.ImageIndex = 0;
4294                             }
4295                         }
4296                     }
4297                     catch (Exception ex)
4298                     {
4299                         ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4300                         ex.Data["IsTerminatePermission"] = false;
4301                         throw;
4302                     }
4303
4304                     try
4305                     {
4306                         var oldIconCol = _iconCol;
4307
4308                         if (this._cfgCommon.IconSize != oldIconSz)
4309                             ApplyListViewIconSize(this._cfgCommon.IconSize);
4310
4311                         foreach (TabPage tp in ListTab.TabPages)
4312                         {
4313                             DetailsListView lst = (DetailsListView)tp.Tag;
4314
4315                             using (ControlTransaction.Update(lst))
4316                             {
4317                                 lst.GridLines = this._cfgCommon.ShowGrid;
4318                                 lst.Font = _fntReaded;
4319                                 lst.BackColor = _clListBackcolor;
4320
4321                                 if (_iconCol != oldIconCol)
4322                                     ResetColumns(lst);
4323                             }
4324                         }
4325                     }
4326                     catch (Exception ex)
4327                     {
4328                         ex.Data["Instance"] = "ListView(IconSize)";
4329                         ex.Data["IsTerminatePermission"] = false;
4330                         throw;
4331                     }
4332
4333                     SetMainWindowTitle();
4334                     SetNotifyIconText();
4335
4336                     this.PurgeListViewItemCache();
4337                     _curList?.Refresh();
4338                     ListTab.Refresh();
4339
4340                     _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4341                     if (this._cfgCommon.HotkeyEnabled)
4342                     {
4343                         ///グローバルホットキーの登録。設定で変更可能にするかも
4344                         HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4345                         if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4346                             modKey |= HookGlobalHotkey.ModKeys.Alt;
4347                         if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4348                             modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4349                         if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4350                             modKey |=  HookGlobalHotkey.ModKeys.Shift;
4351                         if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4352                             modKey |= HookGlobalHotkey.ModKeys.Win;
4353
4354                         _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4355                     }
4356
4357                     if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4358                     try
4359                     {
4360                         StatusText_TextChanged(null, null);
4361                     }
4362                     catch (Exception)
4363                     {
4364                     }
4365                 }
4366             }
4367             else
4368             {
4369                 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4370                 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4371             }
4372
4373             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4374
4375             this.TopMost = this._cfgCommon.AlwaysTop;
4376             SaveConfigsAll(false);
4377
4378             if (tw.Username != oldUser.Username)
4379                 await this.doGetFollowersMenu();
4380         }
4381
4382         /// <summary>
4383         /// タブの表示位置を設定する
4384         /// </summary>
4385         private void SetTabAlignment()
4386         {
4387             var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4388             if (ListTab.Alignment == newAlignment) return;
4389
4390             // 各タブのリスト上の選択位置などを退避
4391             var listSelections = this.SaveListViewSelection();
4392
4393             ListTab.Alignment = newAlignment;
4394
4395             foreach (TabPage tab in ListTab.TabPages)
4396             {
4397                 DetailsListView lst = (DetailsListView)tab.Tag;
4398                 TabClass tabInfo = _statuses.Tabs[tab.Text];
4399                 using (ControlTransaction.Update(lst))
4400                 {
4401                     // 選択位置などを復元
4402                     this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4403                 }
4404             }
4405         }
4406
4407         private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4408         {
4409             // アイコンサイズの再設定
4410             _iconCol = false;
4411             switch (iconSz)
4412             {
4413                 case MyCommon.IconSizes.IconNone:
4414                     _iconSz = 0;
4415                     break;
4416                 case MyCommon.IconSizes.Icon16:
4417                     _iconSz = 16;
4418                     break;
4419                 case MyCommon.IconSizes.Icon24:
4420                     _iconSz = 26;
4421                     break;
4422                 case MyCommon.IconSizes.Icon48:
4423                     _iconSz = 48;
4424                     break;
4425                 case MyCommon.IconSizes.Icon48_2:
4426                     _iconSz = 48;
4427                     _iconCol = true;
4428                     break;
4429             }
4430
4431             if (_iconSz > 0)
4432             {
4433                 // ディスプレイの DPI 設定を考慮したサイズを設定する
4434                 _listViewImageList.ImageSize = new Size(
4435                     1,
4436                     (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4437             }
4438             else
4439             {
4440                 _listViewImageList.ImageSize = new Size(1, 1);
4441             }
4442         }
4443
4444         private void ResetColumns(DetailsListView list)
4445         {
4446             using (ControlTransaction.Update(list))
4447             using (ControlTransaction.Layout(list, false))
4448             {
4449                 // カラムヘッダの再設定
4450                 list.ColumnClick -= MyList_ColumnClick;
4451                 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4452                 list.ColumnReordered -= MyList_ColumnReordered;
4453                 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4454
4455                 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4456                 list.Columns.Clear();
4457                 cols.ForEach(col => col.Dispose());
4458                 cols.Clear();
4459
4460                 InitColumns(list, true);
4461
4462                 list.ColumnClick += MyList_ColumnClick;
4463                 list.DrawColumnHeader += MyList_DrawColumnHeader;
4464                 list.ColumnReordered += MyList_ColumnReordered;
4465                 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4466             }
4467         }
4468
4469         private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4470         {
4471             if (e.Url.AbsoluteUri != "about:blank")
4472             {
4473                 await this.DispSelectedPost();
4474                 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4475             }
4476         }
4477
4478         private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4479         {
4480             if (e.Url.Scheme == "data")
4481             {
4482                 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4483             }
4484             else if (e.Url.AbsoluteUri != "about:blank")
4485             {
4486                 e.Cancel = true;
4487                 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4488                 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4489             }
4490         }
4491
4492         public void AddNewTabForSearch(string searchWord)
4493         {
4494             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4495             foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4496             {
4497                 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4498                 {
4499                     foreach (TabPage tp in ListTab.TabPages)
4500                     {
4501                         if (tb.TabName == tp.Text)
4502                         {
4503                             ListTab.SelectedTab = tp;
4504                             return;
4505                         }
4506                     }
4507                 }
4508             }
4509             //ユニークなタブ名生成
4510             string tabName = searchWord;
4511             for (int i = 0; i <= 100; i++)
4512             {
4513                 if (_statuses.ContainsTab(tabName))
4514                     tabName += "_";
4515                 else
4516                     break;
4517             }
4518             //タブ追加
4519             _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4520             AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4521             //追加したタブをアクティブに
4522             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4523             //検索条件の設定
4524             ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4525             cmb.Items.Add(searchWord);
4526             cmb.Text = searchWord;
4527             SaveConfigsTabs();
4528             //検索実行
4529             this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4530         }
4531
4532         private void ShowUserTimeline()
4533         {
4534             if (!this.ExistCurrentPost) return;
4535             AddNewTabForUserTimeline(_curPost.ScreenName);
4536         }
4537
4538         private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4539         {
4540             if (e.KeyCode == Keys.Escape)
4541             {
4542                 TabPage relTp = ListTab.SelectedTab;
4543                 RemoveSpecifiedTab(relTp.Text, false);
4544                 SaveConfigsTabs();
4545                 e.SuppressKeyPress = true;
4546             }
4547         }
4548
4549         public void AddNewTabForUserTimeline(string user)
4550         {
4551             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4552             foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4553             {
4554                 if (tb.User == user)
4555                 {
4556                     foreach (TabPage tp in ListTab.TabPages)
4557                     {
4558                         if (tb.TabName == tp.Text)
4559                         {
4560                             ListTab.SelectedTab = tp;
4561                             return;
4562                         }
4563                     }
4564                 }
4565             }
4566             //ユニークなタブ名生成
4567             string tabName = "user:" + user;
4568             while (_statuses.ContainsTab(tabName))
4569             {
4570                 tabName += "_";
4571             }
4572             //タブ追加
4573             _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4574             var tab = this._statuses.Tabs[tabName];
4575             tab.User = user;
4576             AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4577             //追加したタブをアクティブに
4578             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4579             SaveConfigsTabs();
4580             //検索実行
4581             this.GetUserTimelineAsync(tab);
4582         }
4583
4584         public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4585         {
4586             //重複チェック
4587             foreach (TabPage tb in ListTab.TabPages)
4588             {
4589                 if (tb.Text == tabName) return false;
4590             }
4591
4592             //新規タブ名チェック
4593             if (tabName == Properties.Resources.AddNewTabText1) return false;
4594
4595             //タブタイプ重複チェック
4596             if (!startup)
4597             {
4598                 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4599                    tabType == MyCommon.TabUsageType.Favorites ||
4600                    tabType == MyCommon.TabUsageType.Home ||
4601                    tabType == MyCommon.TabUsageType.Mentions ||
4602                    tabType == MyCommon.TabUsageType.Related)
4603                 {
4604                     if (_statuses.GetTabByType(tabType) != null) return false;
4605                 }
4606             }
4607
4608             var _tabPage = new TabPage();
4609             var _listCustom = new DetailsListView();
4610
4611             int cnt = ListTab.TabPages.Count;
4612
4613             ///ToDo:Create and set controls follow tabtypes
4614
4615             using (ControlTransaction.Update(_listCustom))
4616             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4617             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4618             using (ControlTransaction.Layout(this.SplitContainer1, false))
4619             using (ControlTransaction.Layout(this.ListTab, false))
4620             using (ControlTransaction.Layout(this))
4621             using (ControlTransaction.Layout(_tabPage, false))
4622             {
4623                 _tabPage.Controls.Add(_listCustom);
4624
4625                 /// UserTimeline関連
4626                 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4627                 {
4628                     var label = new Label();
4629                     label.Dock = DockStyle.Top;
4630                     label.Name = "labelUser";
4631                     if (tabType == MyCommon.TabUsageType.Lists)
4632                     {
4633                         label.Text = listInfo.ToString();
4634                     }
4635                     else
4636                     {
4637                         label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4638                     }
4639                     label.TextAlign = ContentAlignment.MiddleLeft;
4640                     using (ComboBox tmpComboBox = new ComboBox())
4641                     {
4642                         label.Height = tmpComboBox.Height;
4643                     }
4644                     _tabPage.Controls.Add(label);
4645                 }
4646                 /// 検索関連の準備
4647                 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4648                 {
4649                     var pnl = new Panel();
4650
4651                     var lbl = new Label();
4652                     var cmb = new ComboBox();
4653                     var btn = new Button();
4654                     var cmbLang = new ComboBox();
4655
4656                     using (ControlTransaction.Layout(pnl, false))
4657                     {
4658                         pnl.Controls.Add(cmb);
4659                         pnl.Controls.Add(cmbLang);
4660                         pnl.Controls.Add(btn);
4661                         pnl.Controls.Add(lbl);
4662                         pnl.Name = "panelSearch";
4663                         pnl.Dock = DockStyle.Top;
4664                         pnl.Height = cmb.Height;
4665                         pnl.Enter += SearchControls_Enter;
4666                         pnl.Leave += SearchControls_Leave;
4667
4668                         cmb.Text = "";
4669                         cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4670                         cmb.Dock = DockStyle.Fill;
4671                         cmb.Name = "comboSearch";
4672                         cmb.DropDownStyle = ComboBoxStyle.DropDown;
4673                         cmb.ImeMode = ImeMode.NoControl;
4674                         cmb.TabStop = false;
4675                         cmb.AutoCompleteMode = AutoCompleteMode.None;
4676                         cmb.KeyDown += SearchComboBox_KeyDown;
4677
4678                         cmbLang.Text = "";
4679                         cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4680                         cmbLang.Dock = DockStyle.Right;
4681                         cmbLang.Width = 50;
4682                         cmbLang.Name = "comboLang";
4683                         cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4684                         cmbLang.TabStop = false;
4685                         cmbLang.Items.Add("");
4686                         cmbLang.Items.Add("ja");
4687                         cmbLang.Items.Add("en");
4688                         cmbLang.Items.Add("ar");
4689                         cmbLang.Items.Add("da");
4690                         cmbLang.Items.Add("nl");
4691                         cmbLang.Items.Add("fa");
4692                         cmbLang.Items.Add("fi");
4693                         cmbLang.Items.Add("fr");
4694                         cmbLang.Items.Add("de");
4695                         cmbLang.Items.Add("hu");
4696                         cmbLang.Items.Add("is");
4697                         cmbLang.Items.Add("it");
4698                         cmbLang.Items.Add("no");
4699                         cmbLang.Items.Add("pl");
4700                         cmbLang.Items.Add("pt");
4701                         cmbLang.Items.Add("ru");
4702                         cmbLang.Items.Add("es");
4703                         cmbLang.Items.Add("sv");
4704                         cmbLang.Items.Add("th");
4705
4706                         lbl.Text = "Search(C-S-f)";
4707                         lbl.Name = "label1";
4708                         lbl.Dock = DockStyle.Left;
4709                         lbl.Width = 90;
4710                         lbl.Height = cmb.Height;
4711                         lbl.TextAlign = ContentAlignment.MiddleLeft;
4712
4713                         btn.Text = "Search";
4714                         btn.Name = "buttonSearch";
4715                         btn.UseVisualStyleBackColor = true;
4716                         btn.Dock = DockStyle.Right;
4717                         btn.TabStop = false;
4718                         btn.Click += SearchButton_Click;
4719
4720                         TabClass tab;
4721                         if (_statuses.Tabs.TryGetValue(tabName, out tab))
4722                         {
4723                             if (!string.IsNullOrEmpty(tab.SearchWords))
4724                             {
4725                                 cmb.Items.Add(tab.SearchWords);
4726                                 cmb.Text = tab.SearchWords;
4727                             }
4728
4729                             cmbLang.Text = tab.SearchLang;
4730                         }
4731
4732                         _tabPage.Controls.Add(pnl);
4733                     }
4734                 }
4735
4736                 _tabPage.Tag = _listCustom;
4737                 this.ListTab.Controls.Add(_tabPage);
4738
4739                 _tabPage.Location = new Point(4, 4);
4740                 _tabPage.Name = "CTab" + cnt.ToString();
4741                 _tabPage.Size = new Size(380, 260);
4742                 _tabPage.TabIndex = 2 + cnt;
4743                 _tabPage.Text = tabName;
4744                 _tabPage.UseVisualStyleBackColor = true;
4745                 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4746
4747                 _listCustom.AllowColumnReorder = true;
4748                 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4749                 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4750                 _listCustom.Dock = DockStyle.Fill;
4751                 _listCustom.FullRowSelect = true;
4752                 _listCustom.HideSelection = false;
4753                 _listCustom.Location = new Point(0, 0);
4754                 _listCustom.Margin = new Padding(0);
4755                 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4756                 _listCustom.ShowItemToolTips = true;
4757                 _listCustom.Size = new Size(380, 260);
4758                 _listCustom.UseCompatibleStateImageBehavior = false;
4759                 _listCustom.View = View.Details;
4760                 _listCustom.OwnerDraw = true;
4761                 _listCustom.VirtualMode = true;
4762                 _listCustom.Font = _fntReaded;
4763                 _listCustom.BackColor = _clListBackcolor;
4764
4765                 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4766                 _listCustom.AllowDrop = true;
4767
4768                 _listCustom.SmallImageList = _listViewImageList;
4769
4770                 InitColumns(_listCustom, startup);
4771
4772                 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4773                 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4774                 _listCustom.ColumnClick += MyList_ColumnClick;
4775                 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4776                 _listCustom.DragDrop += TweenMain_DragDrop;
4777                 _listCustom.DragEnter += TweenMain_DragEnter;
4778                 _listCustom.DragOver += TweenMain_DragOver;
4779                 _listCustom.DrawItem += MyList_DrawItem;
4780                 _listCustom.MouseClick += MyList_MouseClick;
4781                 _listCustom.ColumnReordered += MyList_ColumnReordered;
4782                 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4783                 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4784                 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4785                 _listCustom.DrawSubItem += MyList_DrawSubItem;
4786                 _listCustom.HScrolled += MyList_HScrolled;
4787             }
4788
4789             return true;
4790         }
4791
4792         public bool RemoveSpecifiedTab(string TabName, bool confirm)
4793         {
4794             var tabInfo = _statuses.GetTabByName(TabName);
4795             if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4796
4797             if (confirm)
4798             {
4799                 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4800                 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4801                                  MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4802                 {
4803                     return false;
4804                 }
4805             }
4806
4807             var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4808             if (_tabPage == null) return false;
4809
4810             SetListProperty();   //他のタブに列幅等を反映
4811
4812             //オブジェクトインスタンスの削除
4813             DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4814             _tabPage.Tag = null;
4815
4816             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4817             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4818             using (ControlTransaction.Layout(this.SplitContainer1, false))
4819             using (ControlTransaction.Layout(this.ListTab, false))
4820             using (ControlTransaction.Layout(this))
4821             using (ControlTransaction.Layout(_tabPage, false))
4822             {
4823                 if (this.ListTab.SelectedTab == _tabPage)
4824                 {
4825                     this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4826                     this._beforeSelectedTab = null;
4827                 }
4828                 this.ListTab.Controls.Remove(_tabPage);
4829
4830                 // 後付けのコントロールを破棄
4831                 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4832                 {
4833                     using (Control label = _tabPage.Controls["labelUser"])
4834                     {
4835                         _tabPage.Controls.Remove(label);
4836                     }
4837                 }
4838                 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4839                 {
4840                     using (Control pnl = _tabPage.Controls["panelSearch"])
4841                     {
4842                         pnl.Enter -= SearchControls_Enter;
4843                         pnl.Leave -= SearchControls_Leave;
4844                         _tabPage.Controls.Remove(pnl);
4845
4846                         foreach (Control ctrl in pnl.Controls)
4847                         {
4848                             if (ctrl.Name == "buttonSearch")
4849                             {
4850                                 ctrl.Click -= SearchButton_Click;
4851                             }
4852                             else if (ctrl.Name == "comboSearch")
4853                             {
4854                                 ctrl.KeyDown -= SearchComboBox_KeyDown;
4855                             }
4856                             pnl.Controls.Remove(ctrl);
4857                             ctrl.Dispose();
4858                         }
4859                     }
4860                 }
4861
4862                 _tabPage.Controls.Remove(_listCustom);
4863
4864                 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4865                 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4866                 _listCustom.ColumnClick -= MyList_ColumnClick;
4867                 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4868                 _listCustom.DragDrop -= TweenMain_DragDrop;
4869                 _listCustom.DragEnter -= TweenMain_DragEnter;
4870                 _listCustom.DragOver -= TweenMain_DragOver;
4871                 _listCustom.DrawItem -= MyList_DrawItem;
4872                 _listCustom.MouseClick -= MyList_MouseClick;
4873                 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4874                 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4875                 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4876                 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4877                 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4878                 _listCustom.HScrolled -= MyList_HScrolled;
4879
4880                 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4881                 _listCustom.Columns.Clear();
4882                 cols.ForEach(col => col.Dispose());
4883                 cols.Clear();
4884
4885                 _listCustom.ContextMenuStrip = null;
4886                 _listCustom.ColumnHeaderContextMenuStrip = null;
4887                 _listCustom.Font = null;
4888
4889                 _listCustom.SmallImageList = null;
4890                 _listCustom.ListViewItemSorter = null;
4891
4892                 //キャッシュのクリア
4893                 if (_curTab.Equals(_tabPage))
4894                 {
4895                     _curTab = null;
4896                     _curItemIndex = -1;
4897                     _curList = null;
4898                     _curPost = null;
4899                 }
4900                 this.PurgeListViewItemCache();
4901             }
4902
4903             _tabPage.Dispose();
4904             _listCustom.Dispose();
4905             _statuses.RemoveTab(TabName);
4906
4907             foreach (TabPage tp in ListTab.TabPages)
4908             {
4909                 DetailsListView lst = (DetailsListView)tp.Tag;
4910                 var count = _statuses.Tabs[tp.Text].AllCount;
4911                 if (lst.VirtualListSize != count)
4912                 {
4913                     lst.VirtualListSize = count;
4914                 }
4915             }
4916
4917             return true;
4918         }
4919
4920         private void ListTab_Deselected(object sender, TabControlEventArgs e)
4921         {
4922             this.PurgeListViewItemCache();
4923             _beforeSelectedTab = e.TabPage;
4924         }
4925
4926         private void ListTab_MouseMove(object sender, MouseEventArgs e)
4927         {
4928             //タブのD&D
4929
4930             if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4931             {
4932                 string tn = "";
4933                 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4934                 if (!dragEnableRectangle.Contains(e.Location))
4935                 {
4936                     //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4937                     tn = ListTab.SelectedTab.Text;
4938                 }
4939
4940                 if (string.IsNullOrEmpty(tn)) return;
4941
4942                 foreach (TabPage tb in ListTab.TabPages)
4943                 {
4944                     if (tb.Text == tn)
4945                     {
4946                         ListTab.DoDragDrop(tb, DragDropEffects.All);
4947                         break;
4948                     }
4949                 }
4950             }
4951             else
4952             {
4953                 _tabDrag = false;
4954             }
4955
4956             Point cpos = new Point(e.X, e.Y);
4957             for (int i = 0; i < ListTab.TabPages.Count; i++)
4958             {
4959                 Rectangle rect = ListTab.GetTabRect(i);
4960                 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4961                    rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4962                 {
4963                     _rclickTabName = ListTab.TabPages[i].Text;
4964                     break;
4965                 }
4966             }
4967         }
4968
4969         private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4970         {
4971             //_curList.Refresh();
4972             SetMainWindowTitle();
4973             SetStatusLabelUrl();
4974             SetApiStatusLabel();
4975             if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4976             TabMenuControl(ListTab.SelectedTab.Text);
4977             this.PushSelectPostChain();
4978             await DispSelectedPost();
4979         }
4980
4981         private void SetListProperty()
4982         {
4983             //削除などで見つからない場合は処理せず
4984             if (_curList == null) return;
4985             if (!_isColumnChanged) return;
4986
4987             int[] dispOrder = new int[_curList.Columns.Count];
4988             for (int i = 0; i < _curList.Columns.Count; i++)
4989             {
4990                 for (int j = 0; j < _curList.Columns.Count; j++)
4991                 {
4992                     if (_curList.Columns[j].DisplayIndex == i)
4993                     {
4994                         dispOrder[i] = j;
4995                         break;
4996                     }
4997                 }
4998             }
4999
5000             //列幅、列並びを他のタブに設定
5001             foreach (TabPage tb in ListTab.TabPages)
5002             {
5003                 if (!tb.Equals(_curTab))
5004                 {
5005                     if (tb.Tag != null && tb.Controls.Count > 0)
5006                     {
5007                         DetailsListView lst = (DetailsListView)tb.Tag;
5008                         for (int i = 0; i < lst.Columns.Count; i++)
5009                         {
5010                             lst.Columns[dispOrder[i]].DisplayIndex = i;
5011                             lst.Columns[i].Width = _curList.Columns[i].Width;
5012                         }
5013                     }
5014                 }
5015             }
5016
5017             _isColumnChanged = false;
5018         }
5019
5020         private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
5021         {
5022             try
5023             {
5024                 if (PostBrowser.StatusText.StartsWith("http") || PostBrowser.StatusText.StartsWith("ftp")
5025                         || PostBrowser.StatusText.StartsWith("data"))
5026                 {
5027                     StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
5028                 }
5029                 if (string.IsNullOrEmpty(PostBrowser.StatusText))
5030                 {
5031                     SetStatusLabelUrl();
5032                 }
5033             }
5034             catch (Exception)
5035             {
5036             }
5037         }
5038
5039         private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5040         {
5041             if (e.KeyChar == '@')
5042             {
5043                 if (!this._cfgCommon.UseAtIdSupplement) return;
5044                 //@マーク
5045                 int cnt = AtIdSupl.ItemCount;
5046                 ShowSuplDialog(StatusText, AtIdSupl);
5047                 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
5048                 e.Handled = true;
5049             }
5050             else if (e.KeyChar == '#')
5051             {
5052                 if (!this._cfgCommon.UseHashSupplement) return;
5053                 ShowSuplDialog(StatusText, HashSupl);
5054                 e.Handled = true;
5055             }
5056         }
5057
5058         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5059         {
5060             ShowSuplDialog(owner, dialog, 0, "");
5061         }
5062
5063         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5064         {
5065             ShowSuplDialog(owner, dialog, offset, "");
5066         }
5067
5068         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5069         {
5070             dialog.StartsWith = startswith;
5071             if (dialog.Visible)
5072             {
5073                 dialog.Focus();
5074             }
5075             else
5076             {
5077                 dialog.ShowDialog();
5078             }
5079             this.TopMost = this._cfgCommon.AlwaysTop;
5080             int selStart = owner.SelectionStart;
5081             string fHalf = "";
5082             string eHalf = "";
5083             if (dialog.DialogResult == DialogResult.OK)
5084             {
5085                 if (!string.IsNullOrEmpty(dialog.inputText))
5086                 {
5087                     if (selStart > 0)
5088                     {
5089                         fHalf = owner.Text.Substring(0, selStart - offset);
5090                     }
5091                     if (selStart < owner.Text.Length)
5092                     {
5093                         eHalf = owner.Text.Substring(selStart);
5094                     }
5095                     owner.Text = fHalf + dialog.inputText + eHalf;
5096                     owner.SelectionStart = selStart + dialog.inputText.Length;
5097                 }
5098             }
5099             else
5100             {
5101                 if (selStart > 0)
5102                 {
5103                     fHalf = owner.Text.Substring(0, selStart);
5104                 }
5105                 if (selStart < owner.Text.Length)
5106                 {
5107                     eHalf = owner.Text.Substring(selStart);
5108                 }
5109                 owner.Text = fHalf + eHalf;
5110                 if (selStart > 0)
5111                 {
5112                     owner.SelectionStart = selStart;
5113                 }
5114             }
5115             owner.Focus();
5116         }
5117
5118         private void StatusText_KeyUp(object sender, KeyEventArgs e)
5119         {
5120             //スペースキーで未読ジャンプ
5121             if (!e.Alt && !e.Control && !e.Shift)
5122             {
5123                 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5124                 {
5125                     bool isSpace = false;
5126                     foreach (char c in StatusText.Text.ToCharArray())
5127                     {
5128                         if (c == ' ' || c == ' ')
5129                         {
5130                             isSpace = true;
5131                         }
5132                         else
5133                         {
5134                             isSpace = false;
5135                             break;
5136                         }
5137                     }
5138                     if (isSpace)
5139                     {
5140                         e.Handled = true;
5141                         StatusText.Text = "";
5142                         JumpUnreadMenuItem_Click(null, null);
5143                     }
5144                 }
5145             }
5146             this.StatusText_TextChanged(null, null);
5147         }
5148
5149         private void StatusText_TextChanged(object sender, EventArgs e)
5150         {
5151             //文字数カウント
5152             int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
5153             lblLen.Text = pLen.ToString();
5154             if (pLen < 0)
5155             {
5156                 StatusText.ForeColor = Color.Red;
5157             }
5158             else
5159             {
5160                 StatusText.ForeColor = _clInputFont;
5161             }
5162             if (string.IsNullOrEmpty(StatusText.Text))
5163             {
5164                 this.inReplyTo = null;
5165             }
5166         }
5167
5168         /// <summary>
5169         /// ツイート投稿前のフッター付与などの前処理を行います
5170         /// </summary>
5171         private string FormatStatusText(string statusText)
5172         {
5173             statusText = statusText.Replace("\r\n", "\n");
5174
5175             if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
5176             {
5177                 // URLと全角文字の切り離し
5178                 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
5179             }
5180
5181             if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
5182             {
5183                 // 文中の全角スペースを半角スペース1個にする
5184                 statusText = statusText.Replace(" ", " ");
5185             }
5186
5187             // DM の場合はこれ以降の処理を行わない
5188             if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
5189                 return statusText;
5190
5191             bool disableFooter;
5192             if (this._cfgCommon.PostShiftEnter)
5193             {
5194                 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5195             }
5196             else
5197             {
5198                 if (this.StatusText.Multiline)
5199                     disableFooter = MyCommon.IsKeyDown(Keys.Control);
5200                 else
5201                     disableFooter = MyCommon.IsKeyDown(Keys.Shift);
5202             }
5203
5204             if (statusText.Contains("RT @"))
5205                 disableFooter = true;
5206
5207             var header = "";
5208             var footer = "";
5209
5210             var hashtag = this.HashMgr.UseHash;
5211             if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
5212             {
5213                 if (HashMgr.IsHead)
5214                     header = HashMgr.UseHash + " ";
5215                 else
5216                     footer = " " + HashMgr.UseHash;
5217             }
5218
5219             if (!disableFooter)
5220             {
5221                 if (this._cfgLocal.UseRecommendStatus)
5222                 {
5223                     // 推奨ステータスを使用する
5224                     footer += this.recommendedStatusFooter;
5225                 }
5226                 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
5227                 {
5228                     // テキストボックスに入力されている文字列を使用する
5229                     footer += " " + this._cfgLocal.StatusText.Trim();
5230                 }
5231             }
5232
5233             statusText = header + statusText + footer;
5234
5235             return statusText;
5236         }
5237
5238         /// <summary>
5239         /// 投稿欄に表示する入力可能な文字数を計算します
5240         /// </summary>
5241         private int GetRestStatusCount(string statusText)
5242         {
5243             //文字数カウント
5244             var remainCount = this.tw.GetTextLengthRemain(statusText);
5245
5246             if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
5247             {
5248                 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
5249             }
5250
5251             return remainCount;
5252         }
5253
5254         private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5255         {
5256             if (sender != this._curList)
5257                 return;
5258
5259             var listCache = this._listItemCache;
5260             if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
5261             {
5262                 // If the newly requested cache is a subset of the old cache,
5263                 // no need to rebuild everything, so do nothing.
5264                 return;
5265             }
5266
5267             // Now we need to rebuild the cache.
5268             this.CreateCache(e.StartIndex, e.EndIndex);
5269         }
5270
5271         private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5272         {
5273             var listCache = this._listItemCache;
5274             if (listCache != null && listCache.TargetList == sender)
5275             {
5276                 ListViewItem item;
5277                 PostClass cacheItemPost;
5278                 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
5279                 {
5280                     e.Item = item;
5281                     return;
5282                 }
5283             }
5284
5285             // A cache miss, so create a new ListViewItem and pass it back.
5286             TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5287             try
5288             {
5289                 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5290             }
5291             catch (Exception)
5292             {
5293                 // 不正な要求に対する間に合わせの応答
5294                 string[] sitem = {"", "", "", "", "", "", "", ""};
5295                 e.Item = new ImageListViewItem(sitem);
5296             }
5297         }
5298
5299         private void CreateCache(int startIndex, int endIndex)
5300         {
5301             var tabInfo = this._statuses.Tabs[this._curTab.Text];
5302
5303             // キャッシュ要求(要求範囲±30を作成)
5304             startIndex = Math.Max(startIndex - 30, 0);
5305             endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
5306
5307             var cacheLength = endIndex - startIndex + 1;
5308
5309             var posts = tabInfo[startIndex, endIndex]; //配列で取得
5310             var listItems = Enumerable.Range(0, cacheLength)
5311                 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
5312                 .ToArray();
5313
5314             var listCache = new ListViewItemCache
5315             {
5316                 TargetList = this._curList,
5317                 StartIndex = startIndex,
5318                 EndIndex = endIndex,
5319                 Post = posts,
5320                 ListItem = listItems,
5321             };
5322
5323             Interlocked.Exchange(ref this._listItemCache, listCache);
5324         }
5325
5326         /// <summary>
5327         /// DetailsListView のための ListViewItem のキャッシュを消去する
5328         /// </summary>
5329         private void PurgeListViewItemCache()
5330         {
5331             Interlocked.Exchange(ref this._listItemCache, null);
5332         }
5333
5334         private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5335         {
5336             StringBuilder mk = new StringBuilder();
5337             //if (Post.IsDeleted) mk.Append("×");
5338             //if (Post.IsMark) mk.Append("♪");
5339             //if (Post.IsProtect) mk.Append("Ю");
5340             //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5341             if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5342             ImageListViewItem itm;
5343             if (Post.RetweetedId == null)
5344             {
5345                 string[] sitem= {"",
5346                                  Post.Nickname,
5347                                  Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5348                                  Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5349                                  Post.ScreenName,
5350                                  "",
5351                                  mk.ToString(),
5352                                  Post.Source};
5353                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5354             }
5355             else
5356             {
5357                 string[] sitem = {"",
5358                                   Post.Nickname,
5359                                   Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5360                                   Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5361                                   Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5362                                   "",
5363                                   mk.ToString(),
5364                                   Post.Source};
5365                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5366             }
5367             itm.StateIndex = Post.StateIndex;
5368
5369             bool read = Post.IsRead;
5370             //未読管理していなかったら既読として扱う
5371             if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5372             ChangeItemStyleRead(read, itm, Post, null);
5373             if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5374             return itm;
5375         }
5376
5377         /// <summary>
5378         /// 全てのタブの振り分けルールを反映し直します
5379         /// </summary>
5380         private void ApplyPostFilters()
5381         {
5382             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5383             {
5384                 this.PurgeListViewItemCache();
5385                 this._curPost = null;
5386                 this._curItemIndex = -1;
5387                 this._statuses.FilterAll();
5388
5389                 foreach (TabPage tabPage in this.ListTab.TabPages)
5390                 {
5391                     var tab = this._statuses.Tabs[tabPage.Text];
5392
5393                     var listview = (DetailsListView)tabPage.Tag;
5394                     using (ControlTransaction.Update(listview))
5395                     {
5396                         listview.VirtualListSize = tab.AllCount;
5397                     }
5398
5399                     if (this._cfgCommon.TabIconDisp)
5400                     {
5401                         if (tab.UnreadCount > 0)
5402                             tabPage.ImageIndex = 0;
5403                         else
5404                             tabPage.ImageIndex = -1;
5405                     }
5406                 }
5407
5408                 if (!this._cfgCommon.TabIconDisp)
5409                     this.ListTab.Refresh();
5410
5411                 SetMainWindowTitle();
5412                 SetStatusLabelUrl();
5413             }
5414         }
5415
5416         private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5417         {
5418             e.DrawDefault = true;
5419         }
5420
5421         private void MyList_HScrolled(object sender, EventArgs e)
5422         {
5423             DetailsListView listView = (DetailsListView)sender;
5424             listView.Refresh();
5425         }
5426
5427         private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5428         {
5429             if (e.State == 0) return;
5430             e.DrawDefault = false;
5431
5432             SolidBrush brs2 = null;
5433             if (!e.Item.Selected)     //e.ItemStateでうまく判定できない???
5434             {
5435                 if (e.Item.BackColor == _clSelf)
5436                     brs2 = _brsBackColorMine;
5437                 else if (e.Item.BackColor == _clAtSelf)
5438                     brs2 = _brsBackColorAt;
5439                 else if (e.Item.BackColor == _clTarget)
5440                     brs2 = _brsBackColorYou;
5441                 else if (e.Item.BackColor == _clAtTarget)
5442                     brs2 = _brsBackColorAtYou;
5443                 else if (e.Item.BackColor == _clAtFromTarget)
5444                     brs2 = _brsBackColorAtFromTarget;
5445                 else if (e.Item.BackColor == _clAtTo)
5446                     brs2 = _brsBackColorAtTo;
5447                 else
5448                     brs2 = _brsBackColorNone;
5449             }
5450             else
5451             {
5452                 //選択中の行
5453                 if (((Control)sender).Focused)
5454                     brs2 = _brsHighLight;
5455                 else
5456                     brs2 = _brsDeactiveSelection;
5457             }
5458             e.Graphics.FillRectangle(brs2, e.Bounds);
5459             e.DrawFocusRectangle();
5460             this.DrawListViewItemIcon(e);
5461         }
5462
5463         private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5464         {
5465             if (e.ItemState == 0) return;
5466
5467             if (e.ColumnIndex > 0)
5468             {
5469                 //アイコン以外の列
5470                 RectangleF rct = e.Bounds;
5471                 rct.Width = e.Header.Width;
5472                 int fontHeight = e.Item.Font.Height;
5473                 if (_iconCol)
5474                 {
5475                     rct.Y += fontHeight;
5476                     rct.Height -= fontHeight;
5477                 }
5478
5479                 int heightDiff;
5480                 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5481
5482                 //if (heightDiff > fontHeight * 0.7)
5483                 //{
5484                 //    rct.Height += fontHeight;
5485                 //    drawLineCount += 1;
5486                 //}
5487
5488                 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5489                 if (!_iconCol && drawLineCount <= 1)
5490                 {
5491                     //rct.Inflate(0, heightDiff / -2);
5492                     //rct.Height += fontHeight / 2;
5493                 }
5494                 else if (heightDiff < fontHeight * 0.7)
5495                 {
5496                     //最終行が70%以上欠けていたら、最終行は表示しない
5497                     //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5498                     rct.Height = (fontHeight * drawLineCount) - 1;
5499                 }
5500                 else
5501                 {
5502                     drawLineCount += 1;
5503                 }
5504
5505                 //if (!_iconCol && drawLineCount > 1)
5506                 //{
5507                 //    rct.Y += fontHeight * 0.2;
5508                 //    if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5509                 //}
5510
5511                 if (rct.Width > 0)
5512                 {
5513                     Color color = (!e.Item.Selected) ? e.Item.ForeColor :   //選択されていない行
5514                         (((Control)sender).Focused) ? _clHighLight :        //選択中の行
5515                         _clUnread;
5516
5517                     if (_iconCol)
5518                     {
5519                         Rectangle rctB = e.Bounds;
5520                         rctB.Width = e.Header.Width;
5521                         rctB.Height = fontHeight;
5522
5523                         using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5524                         {
5525                             TextRenderer.DrawText(e.Graphics,
5526                                                     e.Item.SubItems[2].Text,
5527                                                     e.Item.Font,
5528                                                     Rectangle.Round(rct),
5529                                                     color,
5530                                                     TextFormatFlags.WordBreak |
5531                                                     TextFormatFlags.EndEllipsis |
5532                                                     TextFormatFlags.GlyphOverhangPadding |
5533                                                     TextFormatFlags.NoPrefix);
5534                             TextRenderer.DrawText(e.Graphics,
5535                                                     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 + "]",
5536                                                     fnt,
5537                                                     rctB,
5538                                                     color,
5539                                                     TextFormatFlags.SingleLine |
5540                                                     TextFormatFlags.EndEllipsis |
5541                                                     TextFormatFlags.GlyphOverhangPadding |
5542                                                     TextFormatFlags.NoPrefix);
5543                         }
5544                     }
5545                     else if (drawLineCount == 1)
5546                     {
5547                         TextRenderer.DrawText(e.Graphics,
5548                                                 e.SubItem.Text,
5549                                                 e.Item.Font,
5550                                                 Rectangle.Round(rct),
5551                                                 color,
5552                                                 TextFormatFlags.SingleLine |
5553                                                 TextFormatFlags.EndEllipsis |
5554                                                 TextFormatFlags.GlyphOverhangPadding |
5555                                                 TextFormatFlags.NoPrefix |
5556                                                 TextFormatFlags.VerticalCenter);
5557                     }
5558                     else
5559                     {
5560                         TextRenderer.DrawText(e.Graphics,
5561                                                 e.SubItem.Text,
5562                                                 e.Item.Font,
5563                                                 Rectangle.Round(rct),
5564                                                 color,
5565                                                 TextFormatFlags.WordBreak |
5566                                                 TextFormatFlags.EndEllipsis |
5567                                                 TextFormatFlags.GlyphOverhangPadding |
5568                                                 TextFormatFlags.NoPrefix);
5569                     }
5570                     //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5571                 }
5572             }
5573         }
5574
5575         private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5576         {
5577             if (_iconSz == 0) return;
5578
5579             ImageListViewItem item = (ImageListViewItem)e.Item;
5580
5581             //e.Bounds.Leftが常に0を指すから自前で計算
5582             Rectangle itemRect = item.Bounds;
5583             var col0 = e.Item.ListView.Columns[0];
5584             itemRect.Width = col0.Width;
5585
5586             if (col0.DisplayIndex > 0)
5587             {
5588                 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5589                 {
5590                     if (clm.DisplayIndex < col0.DisplayIndex)
5591                         itemRect.X += clm.Width;
5592                 }
5593             }
5594
5595             // ディスプレイの DPI 設定を考慮したアイコンサイズ
5596             var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5597             var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5598
5599             Rectangle iconRect;
5600             var img = item.Image;
5601             if (img != null)
5602             {
5603                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5604                 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5605
5606                 if (iconRect.Width > 0)
5607                 {
5608                     e.Graphics.FillRectangle(Brushes.White, iconRect);
5609                     e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5610                     try
5611                     {
5612                         e.Graphics.DrawImage(img.Image, iconRect);
5613                     }
5614                     catch (ArgumentException)
5615                     {
5616                         item.RefreshImageAsync();
5617                     }
5618                 }
5619             }
5620             else
5621             {
5622                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5623                 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5624
5625                 item.GetImageAsync();
5626             }
5627
5628             if (item.StateIndex > -1)
5629             {
5630                 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5631                 if (stateRect.Width > 0)
5632                 {
5633                     //e.Graphics.FillRectangle(Brushes.White, stateRect);
5634                     //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5635                     e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5636                 }
5637             }
5638         }
5639
5640         protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5641         {
5642             base.ScaleControl(factor, specified);
5643
5644             ScaleChildControl(this.TabImage, factor);
5645
5646             var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5647             var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5648
5649             foreach (var listview in listviews)
5650             {
5651                 ScaleChildControl(listview, factor);
5652             }
5653         }
5654
5655         //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5656         //{
5657         //    ImageListViewItem item = (ImageListViewItem)e.Item;
5658         //    if (item.StateImageIndex > -1)
5659         //    {
5660         //        ////e.Bounds.Leftが常に0を指すから自前で計算
5661         //        //Rectangle itemRect = item.Bounds;
5662         //        //itemRect.Width = e.Item.ListView.Columns[4].Width;
5663
5664         //        //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5665         //        //{
5666         //        //    if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5667         //        //    {
5668         //        //        itemRect.X += clm.Width;
5669         //        //    }
5670         //        //}
5671
5672         //        //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5673         //        //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5674
5675         //        if (rct.Width > 0)
5676         //        {
5677         //            RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5678         //            //e.Graphics.FillRectangle(Brushes.White, rct);
5679         //            //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5680         //            e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5681         //        }
5682         //    }
5683         //}
5684
5685         private void DoTabSearch(string _word,
5686                                  bool CaseSensitive,
5687                                  bool UseRegex,
5688                                  SEARCHTYPE SType)
5689         {
5690             int cidx = 0;
5691             bool fnd = false;
5692             int toIdx;
5693             int stp = 1;
5694
5695             if (_curList.VirtualListSize == 0)
5696             {
5697                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5698             }
5699
5700             if (_curList.SelectedIndices.Count > 0)
5701             {
5702                 cidx = _curList.SelectedIndices[0];
5703             }
5704             toIdx = _curList.VirtualListSize;
5705
5706             switch (SType)
5707             {
5708                 case SEARCHTYPE.DialogSearch:    //ダイアログからの検索
5709                     if (_curList.SelectedIndices.Count > 0)
5710                         cidx = _curList.SelectedIndices[0];
5711                     else
5712                         cidx = 0;
5713                     break;
5714                 case SEARCHTYPE.NextSearch:      //次を検索
5715                     if (_curList.SelectedIndices.Count > 0)
5716                     {
5717                         cidx = _curList.SelectedIndices[0] + 1;
5718                         if (cidx > toIdx) cidx = toIdx;
5719                     }
5720                     else
5721                     {
5722                         cidx = 0;
5723                     }
5724                     break;
5725                 case SEARCHTYPE.PrevSearch:      //前を検索
5726                     if (_curList.SelectedIndices.Count > 0)
5727                     {
5728                         cidx = _curList.SelectedIndices[0] - 1;
5729                         if (cidx < 0) cidx = 0;
5730                     }
5731                     else
5732                     {
5733                         cidx = toIdx;
5734                     }
5735                     toIdx = -1;
5736                     stp = -1;
5737                     break;
5738             }
5739
5740             RegexOptions regOpt = RegexOptions.None;
5741             StringComparison fndOpt = StringComparison.Ordinal;
5742             if (!CaseSensitive)
5743             {
5744                 regOpt = RegexOptions.IgnoreCase;
5745                 fndOpt = StringComparison.OrdinalIgnoreCase;
5746             }
5747             try
5748             {
5749     RETRY:
5750                 if (UseRegex)
5751                 {
5752                     // 正規表現検索
5753                     Regex _search;
5754                     try
5755                     {
5756                         _search = new Regex(_word, regOpt);
5757                         for (int idx = cidx; idx != toIdx; idx += stp)
5758                         {
5759                             PostClass post;
5760                             try
5761                             {
5762                                 post = _statuses.Tabs[_curTab.Text][idx];
5763                             }
5764                             catch (Exception)
5765                             {
5766                                 continue;
5767                             }
5768                             if (_search.IsMatch(post.Nickname)
5769                                 || _search.IsMatch(post.TextFromApi)
5770                                 || _search.IsMatch(post.ScreenName))
5771                             {
5772                                 SelectListItem(_curList, idx);
5773                                 _curList.EnsureVisible(idx);
5774                                 return;
5775                             }
5776                         }
5777                     }
5778                     catch (ArgumentException)
5779                     {
5780                         MessageBox.Show(Properties.Resources.DoTabSearchText1, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
5781                         return;
5782                     }
5783                 }
5784                 else
5785                 {
5786                     // 通常検索
5787                     for (int idx = cidx; idx != toIdx; idx += stp)
5788                     {
5789                         PostClass post;
5790                         try
5791                         {
5792                             post = _statuses.Tabs[_curTab.Text][idx];
5793                         }
5794                         catch (Exception)
5795                         {
5796                             continue;
5797                         }
5798                         if (post.Nickname.IndexOf(_word, fndOpt) > -1
5799                             || post.TextFromApi.IndexOf(_word, fndOpt) > -1
5800                             || post.ScreenName.IndexOf(_word, fndOpt) > -1)
5801                         {
5802                             SelectListItem(_curList, idx);
5803                             _curList.EnsureVisible(idx);
5804                             return;
5805                         }
5806                     }
5807                 }
5808
5809                 if (!fnd)
5810                 {
5811                     switch (SType)
5812                     {
5813                         case SEARCHTYPE.DialogSearch:
5814                         case SEARCHTYPE.NextSearch:
5815                             toIdx = cidx;
5816                             cidx = 0;
5817                             break;
5818                         case SEARCHTYPE.PrevSearch:
5819                             toIdx = cidx;
5820                             cidx = _curList.VirtualListSize - 1;
5821                             break;
5822                     }
5823                     fnd = true;
5824                     goto RETRY;
5825                 }
5826             }
5827             catch (ArgumentOutOfRangeException)
5828             {
5829             }
5830             MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5831         }
5832
5833         private void MenuItemSubSearch_Click(object sender, EventArgs e)
5834         {
5835             // 検索メニュー
5836             this.ShowSearchDialog();
5837         }
5838
5839         private void MenuItemSearchNext_Click(object sender, EventArgs e)
5840         {
5841             var previousSearch = this.SearchDialog.ResultOptions;
5842             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5843             {
5844                 this.SearchDialog.Reset();
5845                 this.ShowSearchDialog();
5846                 return;
5847             }
5848
5849             // 次を検索
5850             this.DoTabSearch(
5851                 previousSearch.Query,
5852                 previousSearch.CaseSensitive,
5853                 previousSearch.UseRegex,
5854                 SEARCHTYPE.NextSearch);
5855         }
5856
5857         private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5858         {
5859             var previousSearch = this.SearchDialog.ResultOptions;
5860             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5861             {
5862                 this.SearchDialog.Reset();
5863                 this.ShowSearchDialog();
5864                 return;
5865             }
5866
5867             // 前を検索
5868             this.DoTabSearch(
5869                 previousSearch.Query,
5870                 previousSearch.CaseSensitive,
5871                 previousSearch.UseRegex,
5872                 SEARCHTYPE.PrevSearch);
5873         }
5874
5875         /// <summary>
5876         /// 検索ダイアログを表示し、検索を実行します
5877         /// </summary>
5878         private void ShowSearchDialog()
5879         {
5880             if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5881             {
5882                 this.TopMost = this._cfgCommon.AlwaysTop;
5883                 return;
5884             }
5885             this.TopMost = this._cfgCommon.AlwaysTop;
5886
5887             var searchOptions = this.SearchDialog.ResultOptions;
5888             if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5889             {
5890                 if (searchOptions.NewTab)
5891                 {
5892                     var tabName = Properties.Resources.SearchResults_TabName;
5893
5894                     try
5895                     {
5896                         tabName = this._statuses.MakeTabName(tabName);
5897                     }
5898                     catch (TabException ex)
5899                     {
5900                         MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5901                     }
5902
5903                     this.AddNewTab(tabName, false, MyCommon.TabUsageType.SearchResults);
5904                     this._statuses.AddTab(tabName, MyCommon.TabUsageType.SearchResults, null);
5905
5906                     var filter = new PostFilterRule
5907                     {
5908                         FilterBody = new[] { searchOptions.Query },
5909                         UseRegex = searchOptions.UseRegex,
5910                         CaseSensitive = searchOptions.CaseSensitive,
5911                     };
5912
5913                     var targetTab = this._statuses.Tabs[this._curTab.Text];
5914                     var posts = targetTab.Posts.Values
5915                         .Where(x => filter.ExecFilter(x) == MyCommon.HITRESULT.CopyAndMark)
5916                         .Where(x => targetTab.Contains(x.StatusId));
5917
5918                     var resultTab = this._statuses.Tabs[tabName];
5919                     foreach (var post in posts)
5920                     {
5921                         resultTab.AddPostToInnerStorage(post);
5922                     }
5923
5924                     this._statuses.DistributePosts();
5925                     this.RefreshTimeline();
5926
5927                     var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5928                         .First(x => x.Text == tabName);
5929
5930                     this.ListTab.SelectedTab = tabPage;
5931                 }
5932                 else
5933                 {
5934                     this.DoTabSearch(
5935                         searchOptions.Query,
5936                         searchOptions.CaseSensitive,
5937                         searchOptions.UseRegex,
5938                         SEARCHTYPE.DialogSearch);
5939                 }
5940             }
5941             else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5942             {
5943                 this.AddNewTabForSearch(searchOptions.Query);
5944             }
5945         }
5946
5947         private void AboutMenuItem_Click(object sender, EventArgs e)
5948         {
5949             using (TweenAboutBox about = new TweenAboutBox())
5950             {
5951                 about.ShowDialog(this);
5952             }
5953             this.TopMost = this._cfgCommon.AlwaysTop;
5954         }
5955
5956         private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5957         {
5958             int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5959             int idx = -1;
5960             DetailsListView lst = null;
5961
5962             if (ImageSelector.Enabled)
5963                 return;
5964
5965             //現在タブから最終タブまで探索
5966             for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5967             {
5968                 //未読Index取得
5969                 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5970                 if (idx > -1)
5971                 {
5972                     ListTab.SelectedIndex = i;
5973                     lst = (DetailsListView)ListTab.TabPages[i].Tag;
5974                     //_curTab = ListTab.TabPages[i];
5975                     break;
5976                 }
5977             }
5978
5979             //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5980             if (idx == -1 && bgnIdx > 0)
5981             {
5982                 for (int i = 0; i < bgnIdx; i++)
5983                 {
5984                     idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5985                     if (idx > -1)
5986                     {
5987                         ListTab.SelectedIndex = i;
5988                         lst = (DetailsListView)ListTab.TabPages[i].Tag;
5989                         //_curTab = ListTab.TabPages[i];
5990                         break;
5991                     }
5992                 }
5993             }
5994
5995             //全部調べたが未読見つからず→先頭タブの最新発言へ
5996             if (idx == -1)
5997             {
5998                 ListTab.SelectedIndex = 0;
5999                 lst = (DetailsListView)ListTab.TabPages[0].Tag;
6000                 //_curTab = ListTab.TabPages[0];
6001                 if (_statuses.SortOrder == SortOrder.Ascending)
6002                     idx = lst.VirtualListSize - 1;
6003                 else
6004                     idx = 0;
6005             }
6006
6007             if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
6008             {
6009                 SelectListItem(lst, idx);
6010                 if (_statuses.SortMode == ComparerMode.Id)
6011                 {
6012                     if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
6013                        _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
6014                     {
6015                         MoveTop();
6016                     }
6017                     else
6018                     {
6019                         lst.EnsureVisible(idx);
6020                     }
6021                 }
6022                 else
6023                 {
6024                     lst.EnsureVisible(idx);
6025                 }
6026             }
6027             lst.Focus();
6028         }
6029
6030         private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
6031         {
6032             if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
6033             {
6034                 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6035                 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
6036             }
6037         }
6038
6039         private async void FavorareMenuItem_Click(object sender, EventArgs e)
6040         {
6041             if (_curList.SelectedIndices.Count > 0)
6042             {
6043                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6044                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
6045             }
6046         }
6047
6048         private async void VerUpMenuItem_Click(object sender, EventArgs e)
6049         {
6050             await this.CheckNewVersion(false);
6051         }
6052
6053         private void RunTweenUp()
6054         {
6055             ProcessStartInfo pinfo = new ProcessStartInfo();
6056             pinfo.UseShellExecute = true;
6057             pinfo.WorkingDirectory = MyCommon.settingPath;
6058             pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
6059             pinfo.Arguments = "\"" + Application.StartupPath + "\"";
6060             try
6061             {
6062                 Process.Start(pinfo);
6063             }
6064             catch (Exception)
6065             {
6066                 MessageBox.Show("Failed to execute TweenUp3.exe.");
6067             }
6068         }
6069
6070         public class VersionInfo
6071         {
6072             public Version Version { get; set; }
6073             public Uri DownloadUri { get; set; }
6074             public string ReleaseNote { get; set; }
6075         }
6076
6077         /// <summary>
6078         /// OpenTween の最新バージョンの情報を取得します
6079         /// </summary>
6080         public async Task<VersionInfo> GetVersionInfoAsync()
6081         {
6082             var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6083                 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6084
6085             var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6086                 .ConfigureAwait(false);
6087
6088             // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6089             var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6090
6091             var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6092             var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6093
6094             msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6095
6096             return new VersionInfo
6097             {
6098                 Version = Version.Parse(msgHeader[0]),
6099                 DownloadUri = new Uri(msgHeader[1]),
6100                 ReleaseNote = msgBody,
6101             };
6102         }
6103
6104         private async Task CheckNewVersion(bool startup = false)
6105         {
6106             if (ApplicationSettings.VersionInfoUrl == null)
6107                 return; // 更新チェック無効化
6108
6109             try
6110             {
6111                 var versionInfo = await this.GetVersionInfoAsync();
6112
6113                 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6114                 {
6115                     // 更新不要
6116                     if (!startup)
6117                     {
6118                         var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6119                             MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6120                         msgtext = MyCommon.ReplaceAppName(msgtext);
6121
6122                         MessageBox.Show(msgtext,
6123                             MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6124                             MessageBoxButtons.OK, MessageBoxIcon.Information);
6125                     }
6126                     return;
6127                 }
6128
6129                 using (var dialog = new UpdateDialog())
6130                 {
6131                     dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6132                         MyCommon.GetReadableVersion(versionInfo.Version));
6133                     dialog.DetailsText = versionInfo.ReleaseNote;
6134
6135                     if (dialog.ShowDialog(this) == DialogResult.Yes)
6136                     {
6137                         await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
6138                     }
6139                 }
6140             }
6141             catch (Exception)
6142             {
6143                 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6144                 if (!startup)
6145                 {
6146                     MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6147                         MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6148                         MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6149                 }
6150             }
6151         }
6152
6153         private async Task Colorize()
6154         {
6155             _colorize = false;
6156             await this.DispSelectedPost();
6157             //件数関連の場合、タイトル即時書き換え
6158             if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6159                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6160                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6161                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6162             {
6163                 SetMainWindowTitle();
6164             }
6165             if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6166             foreach (TabPage tb in ListTab.TabPages)
6167             {
6168                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6169                 {
6170                     if (this._cfgCommon.TabIconDisp)
6171                     {
6172                         if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6173                     }
6174                 }
6175             }
6176             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6177         }
6178
6179         public string createDetailHtml(string orgdata)
6180         {
6181             if (this._cfgLocal.UseTwemoji)
6182                 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6183
6184             return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6185         }
6186
6187         private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6188         {
6189             if (sender.Equals(displayItem))
6190             {
6191                 this.ClearUserPicture();
6192
6193                 var img = displayItem.Image;
6194                 try
6195                 {
6196                     if (img != null)
6197                         img = await img.CloneAsync();
6198
6199                     UserPicture.Image = img;
6200                 }
6201                 catch (Exception)
6202                 {
6203                     UserPicture.ShowErrorImage();
6204                 }
6205             }
6206         }
6207
6208         private Task DispSelectedPost()
6209         {
6210             return this.DispSelectedPost(false);
6211         }
6212
6213         private PostClass displayPost = new PostClass();
6214
6215         /// <summary>
6216         /// サムネイル表示に使用する CancellationToken の生成元
6217         /// </summary>
6218         private CancellationTokenSource thumbnailTokenSource = null;
6219
6220         private async Task DispSelectedPost(bool forceupdate)
6221         {
6222             if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6223                 return;
6224
6225             var oldDisplayPost = this.displayPost;
6226             this.displayPost = this._curPost;
6227
6228             if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6229                 return;
6230
6231             if (displayItem != null)
6232             {
6233                 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6234                 displayItem = null;
6235             }
6236             displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6237             displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6238
6239             using (ControlTransaction.Update(this.TableLayoutPanel1))
6240             {
6241                 SourceLinkLabel.Text = this._curPost.Source;
6242                 SourceLinkLabel.Tag = this._curPost.SourceUri;
6243                 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6244
6245                 string nameText;
6246                 if (_curPost.IsDm)
6247                 {
6248                     if (_curPost.IsOwl)
6249                         nameText = "DM FROM <- ";
6250                     else
6251                         nameText = "DM TO -> ";
6252                 }
6253                 else
6254                 {
6255                     nameText = "";
6256                 }
6257                 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6258                 if (_curPost.RetweetedId != null)
6259                     nameText += " (RT:" + _curPost.RetweetedBy + ")";
6260
6261                 NameLabel.Text = nameText;
6262                 NameLabel.Tag = _curPost.ScreenName;
6263
6264                 var nameForeColor = SystemColors.ControlText;
6265                 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6266                     nameForeColor = this._clOWL;
6267                 if (_curPost.RetweetedId != null)
6268                     nameForeColor = this._clRetweet;
6269                 if (_curPost.IsFav)
6270                     nameForeColor = this._clFav;
6271                 NameLabel.ForeColor = nameForeColor;
6272
6273                 this.ClearUserPicture();
6274
6275                 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6276                 {
6277                     var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6278                     try
6279                     {
6280                         UserPicture.Image = image?.Clone();
6281                     }
6282                     catch (Exception)
6283                     {
6284                         UserPicture.ShowErrorImage();
6285                     }
6286                 }
6287
6288                 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6289             }
6290
6291             if (DumpPostClassToolStripMenuItem.Checked)
6292             {
6293                 StringBuilder sb = new StringBuilder(512);
6294
6295                 sb.Append("-----Start PostClass Dump<br>");
6296                 sb.AppendFormat("TextFromApi           : {0}<br>", _curPost.TextFromApi);
6297                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6298                 sb.AppendFormat("StatusId             : {0}<br>", _curPost.StatusId.ToString());
6299                 //sb.AppendFormat("ImageIndex     : {0}<br>", _curPost.ImageIndex.ToString());
6300                 sb.AppendFormat("ImageUrl       : {0}<br>", _curPost.ImageUrl);
6301                 sb.AppendFormat("InReplyToStatusId    : {0}<br>", _curPost.InReplyToStatusId.ToString());
6302                 sb.AppendFormat("InReplyToUser  : {0}<br>", _curPost.InReplyToUser);
6303                 sb.AppendFormat("IsDM           : {0}<br>", _curPost.IsDm.ToString());
6304                 sb.AppendFormat("IsFav          : {0}<br>", _curPost.IsFav.ToString());
6305                 sb.AppendFormat("IsMark         : {0}<br>", _curPost.IsMark.ToString());
6306                 sb.AppendFormat("IsMe           : {0}<br>", _curPost.IsMe.ToString());
6307                 sb.AppendFormat("IsOwl          : {0}<br>", _curPost.IsOwl.ToString());
6308                 sb.AppendFormat("IsProtect      : {0}<br>", _curPost.IsProtect.ToString());
6309                 sb.AppendFormat("IsRead         : {0}<br>", _curPost.IsRead.ToString());
6310                 sb.AppendFormat("IsReply        : {0}<br>", _curPost.IsReply.ToString());
6311
6312                 foreach (string nm in _curPost.ReplyToList)
6313                 {
6314                     sb.AppendFormat("ReplyToList    : {0}<br>", nm);
6315                 }
6316
6317                 sb.AppendFormat("ScreenName           : {0}<br>", _curPost.ScreenName);
6318                 sb.AppendFormat("NickName       : {0}<br>", _curPost.Nickname);
6319                 sb.AppendFormat("Text   : {0}<br>", _curPost.Text);
6320                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.Text);
6321                 sb.AppendFormat("CreatedAt          : {0}<br>", _curPost.CreatedAt.ToString());
6322                 sb.AppendFormat("Source         : {0}<br>", _curPost.Source);
6323                 sb.AppendFormat("UserId            : {0}<br>", _curPost.UserId);
6324                 sb.AppendFormat("FilterHit      : {0}<br>", _curPost.FilterHit);
6325                 sb.AppendFormat("RetweetedBy    : {0}<br>", _curPost.RetweetedBy);
6326                 sb.AppendFormat("RetweetedId    : {0}<br>", _curPost.RetweetedId);
6327
6328                 sb.AppendFormat("Media.Count    : {0}<br>", _curPost.Media.Count);
6329                 if (_curPost.Media.Count > 0)
6330                 {
6331                     for (int i = 0; i < _curPost.Media.Count; i++)
6332                     {
6333                         var info = _curPost.Media[i];
6334                         sb.AppendFormat("Media[{0}].Url         : {1}<br>", i, info.Url);
6335                         sb.AppendFormat("Media[{0}].VideoUrl    : {1}<br>", i, info.VideoUrl ?? "---");
6336                     }
6337                 }
6338                 sb.Append("-----End PostClass Dump<br>");
6339
6340                 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6341                 return;
6342             }
6343
6344             var loadTasks = new List<Task>();
6345
6346             // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6347             // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6348             if (_curPost.StatusId != oldDisplayPost.StatusId)
6349             {
6350                 using (ControlTransaction.Update(this.PostBrowser))
6351                 {
6352                     this.PostBrowser.DocumentText =
6353                         this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6354
6355                     this.PostBrowser.Document.Window.ScrollTo(0, 0);
6356                 }
6357
6358                 this.SplitContainer3.Panel2Collapsed = true;
6359
6360                 if (this._cfgCommon.PreviewEnable)
6361                 {
6362                     var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
6363                     oldTokenSource?.Cancel();
6364
6365                     var token = this.thumbnailTokenSource.Token;
6366                     loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
6367                 }
6368
6369                 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
6370             }
6371
6372             try
6373             {
6374                 await Task.WhenAll(loadTasks);
6375             }
6376             catch (OperationCanceledException) { }
6377         }
6378
6379         /// <summary>
6380         /// 発言詳細欄のツイートURLを展開する
6381         /// </summary>
6382         private async Task AppendQuoteTweetAsync(PostClass post)
6383         {
6384             var statusIds = post.QuoteStatusIds;
6385             if (statusIds.Length == 0)
6386                 return;
6387
6388             // 「読み込み中」テキストを表示
6389             var loadingQuoteHtml = statusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText));
6390             var body = post.Text + string.Concat(loadingQuoteHtml);
6391
6392             using (ControlTransaction.Update(this.PostBrowser))
6393                 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6394
6395             // 引用ツイートを読み込み
6396             var quoteHtmls = await Task.WhenAll(statusIds.Select(x => this.CreateQuoteTweetHtml(x)));
6397
6398             // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
6399             if (this._curPost != post || this._curPost.IsDeleted)
6400                 return;
6401
6402             body = post.Text + string.Concat(quoteHtmls);
6403
6404             using (ControlTransaction.Update(this.PostBrowser))
6405                 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6406         }
6407
6408         private async Task<string> CreateQuoteTweetHtml(long statusId)
6409         {
6410             PostClass post = this._statuses[statusId];
6411             if (post == null)
6412             {
6413                 try
6414                 {
6415                     post = await Task.Run(() => this.tw.GetStatusApi(false, statusId))
6416                         .ConfigureAwait(false);
6417                 }
6418                 catch (WebApiException ex)
6419                 {
6420                     return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode(ex.Message));
6421                 }
6422
6423                 post.IsRead = true;
6424                 if (!this._statuses.AddQuoteTweet(post))
6425                     return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.");
6426             }
6427
6428             return FormatQuoteTweetHtml(post);
6429         }
6430
6431         internal static string FormatQuoteTweetHtml(PostClass post)
6432         {
6433             var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6434                 " &mdash; " + WebUtility.HtmlEncode(post.Nickname) +
6435                 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6436                 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6437
6438             return FormatQuoteTweetHtml(post.StatusId, innerHtml);
6439         }
6440
6441         internal static string FormatQuoteTweetHtml(long statusId, string innerHtml)
6442         {
6443             return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6444                 "<blockquote class=\"quote-tweet\">" + innerHtml + "</blockquote>" +
6445                 "</a>";
6446         }
6447
6448         /// <summary>
6449         /// 指定されたHTMLからリンクを除去します
6450         /// </summary>
6451         internal static string StripLinkTagHtml(string html)
6452         {
6453             // a 要素はネストされていない前提の正規表現パターン
6454             return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6455         }
6456
6457         private async void MatomeMenuItem_Click(object sender, EventArgs e)
6458         {
6459             await this.OpenApplicationWebsite();
6460         }
6461
6462         private async Task OpenApplicationWebsite()
6463         {
6464             await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6465         }
6466
6467         private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6468         {
6469             await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6470         }
6471
6472         private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6473         {
6474             if (ListTab.SelectedTab != null)
6475             {
6476                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6477                 {
6478                     Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6479                     if (pnl.Controls["comboSearch"].Focused ||
6480                         pnl.Controls["comboLang"].Focused ||
6481                         pnl.Controls["buttonSearch"].Focused) return;
6482                 }
6483
6484                 if (e.Control || e.Shift || e.Alt)
6485                     this._anchorFlag = false;
6486
6487                 Task asyncTask;
6488                 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6489                 {
6490                     e.Handled = true;
6491                     e.SuppressKeyPress = true;
6492                 }
6493
6494                 if (asyncTask != null)
6495                     await asyncTask;
6496             }
6497         }
6498
6499         private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6500
6501         private void InitializeShortcuts()
6502         {
6503             this.shortcutCommands = new[]
6504             {
6505                 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6506                 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6507                     .FocusedOn(FocusedControl.ListTab)
6508                     .Do(() => SendKeys.Send("{DOWN}")),
6509
6510                 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6511                     .FocusedOn(FocusedControl.ListTab)
6512                     .Do(() => SendKeys.Send("{UP}")),
6513
6514                 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6515                     .FocusedOn(FocusedControl.ListTab)
6516                     .Do(() => SendKeys.Send("{PGDN}")),
6517
6518                 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6519                     .FocusedOn(FocusedControl.ListTab)
6520                     .Do(() => SendKeys.Send("{PGUP}")),
6521
6522                 ShortcutCommand.Create(Keys.F1)
6523                     .Do(() => this.OpenApplicationWebsite()),
6524
6525                 ShortcutCommand.Create(Keys.F3)
6526                     .Do(() => this.MenuItemSearchNext_Click(null, null)),
6527
6528                 ShortcutCommand.Create(Keys.F5)
6529                     .Do(() => this.DoRefresh()),
6530
6531                 ShortcutCommand.Create(Keys.F6)
6532                     .Do(() => this.GetReplyAsync()),
6533
6534                 ShortcutCommand.Create(Keys.F7)
6535                     .Do(() => this.GetDirectMessagesAsync()),
6536
6537                 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6538                     .NotFocusedOn(FocusedControl.StatusText)
6539                     .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6540
6541                 ShortcutCommand.Create(Keys.G)
6542                     .NotFocusedOn(FocusedControl.StatusText)
6543                     .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6544
6545                 ShortcutCommand.Create(Keys.Right, Keys.N)
6546                     .FocusedOn(FocusedControl.ListTab)
6547                     .Do(() => this.GoRelPost(forward: true)),
6548
6549                 ShortcutCommand.Create(Keys.Left, Keys.P)
6550                     .FocusedOn(FocusedControl.ListTab)
6551                     .Do(() => this.GoRelPost(forward: false)),
6552
6553                 ShortcutCommand.Create(Keys.OemPeriod)
6554                     .FocusedOn(FocusedControl.ListTab)
6555                     .Do(() => this.GoAnchor()),
6556
6557                 ShortcutCommand.Create(Keys.I)
6558                     .FocusedOn(FocusedControl.ListTab)
6559                     .OnlyWhen(() => this.StatusText.Enabled)
6560                     .Do(() => this.StatusText.Focus()),
6561
6562                 ShortcutCommand.Create(Keys.Enter)
6563                     .FocusedOn(FocusedControl.ListTab)
6564                     .Do(() => this.MakeReplyOrDirectStatus()),
6565
6566                 ShortcutCommand.Create(Keys.R)
6567                     .FocusedOn(FocusedControl.ListTab)
6568                     .Do(() => this.DoRefresh()),
6569
6570                 ShortcutCommand.Create(Keys.L)
6571                     .FocusedOn(FocusedControl.ListTab)
6572                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6573
6574                 ShortcutCommand.Create(Keys.H)
6575                     .FocusedOn(FocusedControl.ListTab)
6576                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6577
6578                 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6579                     .FocusedOn(FocusedControl.ListTab)
6580                     .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6581
6582                 ShortcutCommand.Create(Keys.S)
6583                     .FocusedOn(FocusedControl.ListTab)
6584                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6585
6586                 ShortcutCommand.Create(Keys.A)
6587                     .FocusedOn(FocusedControl.ListTab)
6588                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6589
6590                 // ] in_reply_to参照元へ戻る
6591                 ShortcutCommand.Create(Keys.Oem4)
6592                     .FocusedOn(FocusedControl.ListTab)
6593                     .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6594
6595                 // [ in_reply_toへジャンプ
6596                 ShortcutCommand.Create(Keys.Oem6)
6597                     .FocusedOn(FocusedControl.ListTab)
6598                     .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6599
6600                 ShortcutCommand.Create(Keys.Escape)
6601                     .FocusedOn(FocusedControl.ListTab)
6602                     .Do(() => {
6603                         this._anchorFlag = false;
6604                         if (ListTab.SelectedTab != null)
6605                         {
6606                             var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6607                             if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6608                             {
6609                                 var relTp = ListTab.SelectedTab;
6610                                 RemoveSpecifiedTab(relTp.Text, false);
6611                                 SaveConfigsTabs();
6612                             }
6613                         }
6614                     }),
6615
6616                 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6617                 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6618                     .FocusedOn(FocusedControl.ListTab)
6619                     .Do(() => this._anchorFlag = false, preventDefault: false),
6620
6621                 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6622                 ShortcutCommand.Create(Keys.Up, Keys.Down)
6623                     .FocusedOn(FocusedControl.PostBrowser)
6624                     .Do(() => { }),
6625
6626                 ShortcutCommand.Create(Keys.Control | Keys.R)
6627                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6628
6629                 ShortcutCommand.Create(Keys.Control | Keys.D)
6630                     .Do(() => this.doStatusDelete()),
6631
6632                 ShortcutCommand.Create(Keys.Control | Keys.M)
6633                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6634
6635                 ShortcutCommand.Create(Keys.Control | Keys.S)
6636                     .Do(() => this.FavoriteChange(FavAdd: true)),
6637
6638                 ShortcutCommand.Create(Keys.Control | Keys.I)
6639                     .Do(() => this.doRepliedStatusOpen()),
6640
6641                 ShortcutCommand.Create(Keys.Control | Keys.Q)
6642                     .Do(() => this.doQuoteOfficial()),
6643
6644                 ShortcutCommand.Create(Keys.Control | Keys.B)
6645                     .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6646
6647                 ShortcutCommand.Create(Keys.Control | Keys.T)
6648                     .Do(() => this.HashManageMenuItem_Click(null, null)),
6649
6650                 ShortcutCommand.Create(Keys.Control | Keys.L)
6651                     .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6652
6653                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6654                     .NotFocusedOn(FocusedControl.PostBrowser)
6655                     .Do(() => this.MultiLineMenuItem_Click(null, null)),
6656
6657                 ShortcutCommand.Create(Keys.Control | Keys.F)
6658                     .Do(() => this.MenuItemSubSearch_Click(null, null)),
6659
6660                 ShortcutCommand.Create(Keys.Control | Keys.U)
6661                     .Do(() => this.ShowUserTimeline()),
6662
6663                 ShortcutCommand.Create(Keys.Control | Keys.H)
6664                     .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6665
6666                 ShortcutCommand.Create(Keys.Control | Keys.G)
6667                     .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6668
6669                 ShortcutCommand.Create(Keys.Control | Keys.O)
6670                     .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6671
6672                 ShortcutCommand.Create(Keys.Control | Keys.E)
6673                     .Do(() => this.OpenURLMenuItem_Click(null, null)),
6674
6675                 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6676                     .FocusedOn(FocusedControl.ListTab)
6677                     .Do(() => this._colorize = true, preventDefault: false),
6678
6679                 ShortcutCommand.Create(Keys.Control | Keys.N)
6680                     .FocusedOn(FocusedControl.ListTab)
6681                     .Do(() => this.GoNextTab(forward: true)),
6682
6683                 ShortcutCommand.Create(Keys.Control | Keys.P)
6684                     .FocusedOn(FocusedControl.ListTab)
6685                     .Do(() => this.GoNextTab(forward: false)),
6686
6687                 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6688                     .FocusedOn(FocusedControl.ListTab)
6689                     .Do(() => this.CopyStot()),
6690
6691                 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6692                 ShortcutCommand.Create(Keys.Control | Keys.D1)
6693                     .FocusedOn(FocusedControl.ListTab)
6694                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6695                     .Do(() => this.ListTab.SelectedIndex = 0),
6696
6697                 ShortcutCommand.Create(Keys.Control | Keys.D2)
6698                     .FocusedOn(FocusedControl.ListTab)
6699                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6700                     .Do(() => this.ListTab.SelectedIndex = 1),
6701
6702                 ShortcutCommand.Create(Keys.Control | Keys.D3)
6703                     .FocusedOn(FocusedControl.ListTab)
6704                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6705                     .Do(() => this.ListTab.SelectedIndex = 2),
6706
6707                 ShortcutCommand.Create(Keys.Control | Keys.D4)
6708                     .FocusedOn(FocusedControl.ListTab)
6709                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6710                     .Do(() => this.ListTab.SelectedIndex = 3),
6711
6712                 ShortcutCommand.Create(Keys.Control | Keys.D5)
6713                     .FocusedOn(FocusedControl.ListTab)
6714                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6715                     .Do(() => this.ListTab.SelectedIndex = 4),
6716
6717                 ShortcutCommand.Create(Keys.Control | Keys.D6)
6718                     .FocusedOn(FocusedControl.ListTab)
6719                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6720                     .Do(() => this.ListTab.SelectedIndex = 5),
6721
6722                 ShortcutCommand.Create(Keys.Control | Keys.D7)
6723                     .FocusedOn(FocusedControl.ListTab)
6724                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6725                     .Do(() => this.ListTab.SelectedIndex = 6),
6726
6727                 ShortcutCommand.Create(Keys.Control | Keys.D8)
6728                     .FocusedOn(FocusedControl.ListTab)
6729                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6730                     .Do(() => this.ListTab.SelectedIndex = 7),
6731
6732                 ShortcutCommand.Create(Keys.Control | Keys.D9)
6733                     .FocusedOn(FocusedControl.ListTab)
6734                     .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6735
6736                 ShortcutCommand.Create(Keys.Control | Keys.A)
6737                     .FocusedOn(FocusedControl.StatusText)
6738                     .Do(() => this.StatusText.SelectAll()),
6739
6740                 ShortcutCommand.Create(Keys.Control | Keys.V)
6741                     .FocusedOn(FocusedControl.StatusText)
6742                     .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6743
6744                 ShortcutCommand.Create(Keys.Control | Keys.Up)
6745                     .FocusedOn(FocusedControl.StatusText)
6746                     .Do(() => {
6747                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6748                         {
6749                             var inReplyToStatusId = this.inReplyTo?.Item1;
6750                             var inReplyToScreenName = this.inReplyTo?.Item2;
6751                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6752                         }
6753                         _hisIdx -= 1;
6754                         if (_hisIdx < 0) _hisIdx = 0;
6755
6756                         var historyItem = this._history[this._hisIdx];
6757                         StatusText.Text = historyItem.status;
6758                         StatusText.SelectionStart = StatusText.Text.Length;
6759                         if (historyItem.inReplyToId != null)
6760                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6761                         else
6762                             this.inReplyTo = null;
6763                     }),
6764
6765                 ShortcutCommand.Create(Keys.Control | Keys.Down)
6766                     .FocusedOn(FocusedControl.StatusText)
6767                     .Do(() => {
6768                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6769                         {
6770                             var inReplyToStatusId = this.inReplyTo?.Item1;
6771                             var inReplyToScreenName = this.inReplyTo?.Item2;
6772                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6773                         }
6774                         _hisIdx += 1;
6775                         if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6776
6777                         var historyItem = this._history[this._hisIdx];
6778                         StatusText.Text = historyItem.status;
6779                         StatusText.SelectionStart = StatusText.Text.Length;
6780                         if (historyItem.inReplyToId != null)
6781                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6782                         else
6783                             this.inReplyTo = null;
6784                     }),
6785
6786                 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6787                     .FocusedOn(FocusedControl.StatusText)
6788                     .Do(() => {
6789                         if (ListTab.SelectedIndex == 0)
6790                         {
6791                             ListTab.SelectedIndex = ListTab.TabCount - 1;
6792                         }
6793                         else
6794                         {
6795                             ListTab.SelectedIndex -= 1;
6796                         }
6797                         StatusText.Focus();
6798                     }),
6799
6800                 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6801                     .FocusedOn(FocusedControl.StatusText)
6802                     .Do(() => {
6803                         if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6804                         {
6805                             ListTab.SelectedIndex = 0;
6806                         }
6807                         else
6808                         {
6809                             ListTab.SelectedIndex += 1;
6810                         }
6811                         StatusText.Focus();
6812                     }),
6813
6814                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6815                     .FocusedOn(FocusedControl.PostBrowser)
6816                     .Do(() => {
6817                         MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6818                         MultiLineMenuItem_Click(null, null);
6819                     }),
6820
6821                 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6822                     .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6823
6824                 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6825                     .Do(() => this.DoRefreshMore()),
6826
6827                 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6828                     .Do(() => this.GetReplyAsync(loadMore: true)),
6829
6830                 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6831                     .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6832
6833                 ShortcutCommand.Create(Keys.Shift | Keys.R)
6834                     .NotFocusedOn(FocusedControl.StatusText)
6835                     .Do(() => this.DoRefreshMore()),
6836
6837                 ShortcutCommand.Create(Keys.Shift | Keys.H)
6838                     .FocusedOn(FocusedControl.ListTab)
6839                     .Do(() => this.GoTopEnd(GoTop: true)),
6840
6841                 ShortcutCommand.Create(Keys.Shift | Keys.L)
6842                     .FocusedOn(FocusedControl.ListTab)
6843                     .Do(() => this.GoTopEnd(GoTop: false)),
6844
6845                 ShortcutCommand.Create(Keys.Shift | Keys.M)
6846                     .FocusedOn(FocusedControl.ListTab)
6847                     .Do(() => this.GoMiddle()),
6848
6849                 ShortcutCommand.Create(Keys.Shift | Keys.G)
6850                     .FocusedOn(FocusedControl.ListTab)
6851                     .Do(() => this.GoLast()),
6852
6853                 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6854                     .FocusedOn(FocusedControl.ListTab)
6855                     .Do(() => this.MoveMiddle()),
6856
6857                 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6858                     .FocusedOn(FocusedControl.ListTab)
6859                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6860
6861                 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6862                     .FocusedOn(FocusedControl.ListTab)
6863                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6864
6865                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6866                 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6867                     .FocusedOn(FocusedControl.ListTab)
6868                     .Do(() => this.GoFav(forward: true)),
6869
6870                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6871                 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6872                     .FocusedOn(FocusedControl.ListTab)
6873                     .Do(() => this.GoFav(forward: false)),
6874
6875                 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6876                     .FocusedOn(FocusedControl.ListTab)
6877                     .Do(() => this.GoBackSelectPostChain()),
6878
6879                 ShortcutCommand.Create(Keys.Alt | Keys.R)
6880                     .Do(() => this.doReTweetOfficial(isConfirm: true)),
6881
6882                 ShortcutCommand.Create(Keys.Alt | Keys.P)
6883                     .OnlyWhen(() => this._curPost != null)
6884                     .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6885
6886                 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6887                     .Do(() => this.ScrollDownPostBrowser(forward: false)),
6888
6889                 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6890                     .Do(() => this.ScrollDownPostBrowser(forward: true)),
6891
6892                 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6893                     .Do(() => this.PageDownPostBrowser(forward: false)),
6894
6895                 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6896                     .Do(() => this.PageDownPostBrowser(forward: true)),
6897
6898                 // 別タブの同じ書き込みへ(ALT+←/→)
6899                 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6900                     .FocusedOn(FocusedControl.ListTab)
6901                     .Do(() => this.GoSamePostToAnotherTab(left: false)),
6902
6903                 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6904                     .FocusedOn(FocusedControl.ListTab)
6905                     .Do(() => this.GoSamePostToAnotherTab(left: true)),
6906
6907                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6908                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6909
6910                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6911                     .Do(() => this.CopyIdUri()),
6912
6913                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6914                     .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6915                         this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6916                     .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6917
6918                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6919                     .Do(() => this.FavoriteChange(FavAdd: false)),
6920
6921                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6922                     .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6923
6924                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6925                     .Do(() => this.HashToggleMenuItem_Click(null, null)),
6926
6927                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6928                     .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6929
6930                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6931                     .Do(() => this.doMoveToRTHome()),
6932
6933                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6934                     .Do(() => this.FavorareMenuItem_Click(null, null)),
6935
6936                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6937                     .FocusedOn(FocusedControl.StatusText)
6938                     .Do(() => {
6939                         if (_curList != null && _curList.VirtualListSize != 0 &&
6940                                     _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6941                         {
6942                             var idx = _curList.SelectedIndices[0] - 1;
6943                             SelectListItem(_curList, idx);
6944                             _curList.EnsureVisible(idx);
6945                         }
6946                     }),
6947
6948                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6949                     .FocusedOn(FocusedControl.StatusText)
6950                     .Do(() => {
6951                         if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6952                                     && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6953                         {
6954                             var idx = _curList.SelectedIndices[0] + 1;
6955                             SelectListItem(_curList, idx);
6956                             _curList.EnsureVisible(idx);
6957                         }
6958                     }),
6959
6960                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6961                     .FocusedOn(FocusedControl.StatusText)
6962                     .Do(() => {
6963                         if (StatusText.SelectionStart > 0)
6964                         {
6965                             int endidx = StatusText.SelectionStart - 1;
6966                             string startstr = "";
6967                             for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6968                             {
6969                                 char c = StatusText.Text[i];
6970                                 if (Char.IsLetterOrDigit(c) || c == '_')
6971                                 {
6972                                     continue;
6973                                 }
6974                                 if (c == '@')
6975                                 {
6976                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6977                                     int cnt = AtIdSupl.ItemCount;
6978                                     ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6979                                     if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6980                                 }
6981                                 else if (c == '#')
6982                                 {
6983                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6984                                     ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6985                                 }
6986                                 else
6987                                 {
6988                                     break;
6989                                 }
6990                             }
6991                         }
6992                     }),
6993
6994                 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6995                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6996                     .FocusedOn(FocusedControl.ListTab)
6997                     .Do(() => this.SetSortColumnByDisplayIndex(0)),
6998
6999                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
7000                     .FocusedOn(FocusedControl.ListTab)
7001                     .Do(() => this.SetSortColumnByDisplayIndex(1)),
7002
7003                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
7004                     .FocusedOn(FocusedControl.ListTab)
7005                     .Do(() => this.SetSortColumnByDisplayIndex(2)),
7006
7007                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
7008                     .FocusedOn(FocusedControl.ListTab)
7009                     .Do(() => this.SetSortColumnByDisplayIndex(3)),
7010
7011                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
7012                     .FocusedOn(FocusedControl.ListTab)
7013                     .Do(() => this.SetSortColumnByDisplayIndex(4)),
7014
7015                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
7016                     .FocusedOn(FocusedControl.ListTab)
7017                     .Do(() => this.SetSortColumnByDisplayIndex(5)),
7018
7019                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
7020                     .FocusedOn(FocusedControl.ListTab)
7021                     .Do(() => this.SetSortColumnByDisplayIndex(6)),
7022
7023                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
7024                     .FocusedOn(FocusedControl.ListTab)
7025                     .Do(() => this.SetSortColumnByDisplayIndex(7)),
7026
7027                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
7028                     .FocusedOn(FocusedControl.ListTab)
7029                     .Do(() => this.SetSortLastColumn()),
7030
7031                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
7032                     .Do(() => this.FavoritesRetweetOfficial()),
7033
7034                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
7035                     .Do(() => this.FavoritesRetweetUnofficial()),
7036
7037                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
7038                     .Do(() => this.OpenUserAppointUrl()),
7039
7040                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7041                     .FocusedOn(FocusedControl.PostBrowser)
7042                     .Do(() => this.doReTweetUnofficial()),
7043
7044                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
7045                     .OnlyWhen(() => this.ExistCurrentPost)
7046                     .Do(() => this.doTranslation(_curPost.TextFromApi)),
7047
7048                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7049                     .Do(() => this.doReTweetUnofficial()),
7050
7051                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
7052                     .Do(() => this.CopyUserId()),
7053
7054                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
7055                     .Do(() => this.tweetThumbnail1.ScrollUp()),
7056
7057                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
7058                     .Do(() => this.tweetThumbnail1.ScrollDown()),
7059
7060                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
7061                     .FocusedOn(FocusedControl.ListTab)
7062                     .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
7063                     .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
7064             };
7065         }
7066
7067         private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
7068         {
7069             // Task を返す非同期処理があれば asyncTask に代入する
7070             asyncTask = null;
7071
7072             // ShortcutCommand に対応しているコマンドはここで処理される
7073             foreach (var command in this.shortcutCommands)
7074             {
7075                 if (command.IsMatch(keyData, focusedOn))
7076                 {
7077                     asyncTask = command.RunCommand();
7078                     return command.PreventDefault;
7079                 }
7080             }
7081
7082             return false;
7083         }
7084
7085         private void ScrollDownPostBrowser(bool forward)
7086         {
7087             var doc = PostBrowser.Document;
7088             if (doc == null) return;
7089
7090             var tags = doc.GetElementsByTagName("html");
7091             if (tags.Count > 0)
7092             {
7093                 if (forward)
7094                     tags[0].ScrollTop += this._fntDetail.Height;
7095                 else
7096                     tags[0].ScrollTop -= this._fntDetail.Height;
7097             }
7098         }
7099
7100         private void PageDownPostBrowser(bool forward)
7101         {
7102             var doc = PostBrowser.Document;
7103             if (doc == null) return;
7104
7105             var tags = doc.GetElementsByTagName("html");
7106             if (tags.Count > 0)
7107             {
7108                 if (forward)
7109                     tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7110                 else
7111                     tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7112             }
7113         }
7114
7115         private void GoNextTab(bool forward)
7116         {
7117             int idx = ListTab.SelectedIndex;
7118             if (forward)
7119             {
7120                 idx += 1;
7121                 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7122             }
7123             else
7124             {
7125                 idx -= 1;
7126                 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7127             }
7128             ListTab.SelectedIndex = idx;
7129         }
7130
7131         private void CopyStot()
7132         {
7133             string clstr = "";
7134             StringBuilder sb = new StringBuilder();
7135             bool IsProtected = false;
7136             bool isDm = false;
7137             if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7138             foreach (int idx in _curList.SelectedIndices)
7139             {
7140                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7141                 if (post.IsProtect)
7142                 {
7143                     IsProtected = true;
7144                     continue;
7145                 }
7146                 if (post.IsDeleted) continue;
7147                 if (!isDm)
7148                 {
7149                     if (post.RetweetedId != null)
7150                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7151                     else
7152                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7153                 }
7154                 else
7155                 {
7156                     sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7157                 }
7158             }
7159             if (IsProtected)
7160             {
7161                 MessageBox.Show(Properties.Resources.CopyStotText1);
7162             }
7163             if (sb.Length > 0)
7164             {
7165                 clstr = sb.ToString();
7166                 try
7167                 {
7168                     Clipboard.SetDataObject(clstr, false, 5, 100);
7169                 }
7170                 catch (Exception ex)
7171                 {
7172                     MessageBox.Show(ex.Message);
7173                 }
7174             }
7175         }
7176
7177         private void CopyIdUri()
7178         {
7179             string clstr = "";
7180             StringBuilder sb = new StringBuilder();
7181             if (this._curTab == null) return;
7182             if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7183             if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7184             foreach (int idx in _curList.SelectedIndices)
7185             {
7186                 var post = _statuses.Tabs[_curTab.Text][idx];
7187                 sb.Append(MyCommon.GetStatusUrl(post));
7188                 sb.Append(Environment.NewLine);
7189             }
7190             if (sb.Length > 0)
7191             {
7192                 clstr = sb.ToString();
7193                 try
7194                 {
7195                     Clipboard.SetDataObject(clstr, false, 5, 100);
7196                 }
7197                 catch (Exception ex)
7198                 {
7199                     MessageBox.Show(ex.Message);
7200                 }
7201             }
7202         }
7203
7204         private void GoFav(bool forward)
7205         {
7206             if (_curList.VirtualListSize == 0) return;
7207             int fIdx = 0;
7208             int toIdx = 0;
7209             int stp = 1;
7210
7211             if (forward)
7212             {
7213                 if (_curList.SelectedIndices.Count == 0)
7214                 {
7215                     fIdx = 0;
7216                 }
7217                 else
7218                 {
7219                     fIdx = _curList.SelectedIndices[0] + 1;
7220                     if (fIdx > _curList.VirtualListSize - 1) return;
7221                 }
7222                 toIdx = _curList.VirtualListSize;
7223                 stp = 1;
7224             }
7225             else
7226             {
7227                 if (_curList.SelectedIndices.Count == 0)
7228                 {
7229                     fIdx = _curList.VirtualListSize - 1;
7230                 }
7231                 else
7232                 {
7233                     fIdx = _curList.SelectedIndices[0] - 1;
7234                     if (fIdx < 0) return;
7235                 }
7236                 toIdx = -1;
7237                 stp = -1;
7238             }
7239
7240             for (int idx = fIdx; idx != toIdx; idx += stp)
7241             {
7242                 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7243                 {
7244                     SelectListItem(_curList, idx);
7245                     _curList.EnsureVisible(idx);
7246                     break;
7247                 }
7248             }
7249         }
7250
7251         private void GoSamePostToAnotherTab(bool left)
7252         {
7253             if (_curList.VirtualListSize == 0) return;
7254             int fIdx = 0;
7255             int toIdx = 0;
7256             int stp = 1;
7257             long targetId = 0;
7258
7259             if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7260             if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7261
7262             targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7263
7264             if (left)
7265             {
7266                 // 左のタブへ
7267                 if (ListTab.SelectedIndex == 0)
7268                 {
7269                     return;
7270                 }
7271                 else
7272                 {
7273                     fIdx = ListTab.SelectedIndex - 1;
7274                 }
7275                 toIdx = -1;
7276                 stp = -1;
7277             }
7278             else
7279             {
7280                 // 右のタブへ
7281                 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7282                 {
7283                     return;
7284                 }
7285                 else
7286                 {
7287                     fIdx = ListTab.SelectedIndex + 1;
7288                 }
7289                 toIdx = ListTab.TabCount;
7290                 stp = 1;
7291             }
7292
7293             bool found = false;
7294             for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7295             {
7296                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7297                 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7298                 {
7299                     if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7300                     {
7301                         ListTab.SelectedIndex = tabidx;
7302                         SelectListItem(_curList, idx);
7303                         _curList.EnsureVisible(idx);
7304                         found = true;
7305                         break;
7306                     }
7307                 }
7308                 if (found) break;
7309             }
7310         }
7311
7312         private void GoPost(bool forward)
7313         {
7314             if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7315             int fIdx = 0;
7316             int toIdx = 0;
7317             int stp = 1;
7318
7319             if (forward)
7320             {
7321                 fIdx = _curList.SelectedIndices[0] + 1;
7322                 if (fIdx > _curList.VirtualListSize - 1) return;
7323                 toIdx = _curList.VirtualListSize;
7324                 stp = 1;
7325             }
7326             else
7327             {
7328                 fIdx = _curList.SelectedIndices[0] - 1;
7329                 if (fIdx < 0) return;
7330                 toIdx = -1;
7331                 stp = -1;
7332             }
7333
7334             string name = "";
7335             if (_curPost.RetweetedId == null)
7336             {
7337                 name = _curPost.ScreenName;
7338             }
7339             else
7340             {
7341                 name = _curPost.RetweetedBy;
7342             }
7343             for (int idx = fIdx; idx != toIdx; idx += stp)
7344             {
7345                 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7346                 {
7347                     if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7348                     {
7349                         SelectListItem(_curList, idx);
7350                         _curList.EnsureVisible(idx);
7351                         break;
7352                     }
7353                 }
7354                 else
7355                 {
7356                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7357                     {
7358                         SelectListItem(_curList, idx);
7359                         _curList.EnsureVisible(idx);
7360                         break;
7361                     }
7362                 }
7363             }
7364         }
7365
7366         private void GoRelPost(bool forward)
7367         {
7368             if (_curList.SelectedIndices.Count == 0) return;
7369
7370             int fIdx = 0;
7371             int toIdx = 0;
7372             int stp = 1;
7373             if (forward)
7374             {
7375                 fIdx = _curList.SelectedIndices[0] + 1;
7376                 if (fIdx > _curList.VirtualListSize - 1) return;
7377                 toIdx = _curList.VirtualListSize;
7378                 stp = 1;
7379             }
7380             else
7381             {
7382                 fIdx = _curList.SelectedIndices[0] - 1;
7383                 if (fIdx < 0) return;
7384                 toIdx = -1;
7385                 stp = -1;
7386             }
7387
7388             if (!_anchorFlag)
7389             {
7390                 if (_curPost == null) return;
7391                 _anchorPost = _curPost;
7392                 _anchorFlag = true;
7393             }
7394             else
7395             {
7396                 if (_anchorPost == null) return;
7397             }
7398
7399             for (int idx = fIdx; idx != toIdx; idx += stp)
7400             {
7401                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7402                 if (post.ScreenName == _anchorPost.ScreenName ||
7403                     post.RetweetedBy == _anchorPost.ScreenName ||
7404                     post.ScreenName == _anchorPost.RetweetedBy ||
7405                     (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7406                     _anchorPost.ReplyToList.Contains(post.ScreenName.ToLower()) ||
7407                     _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLower()) ||
7408                     post.ReplyToList.Contains(_anchorPost.ScreenName.ToLower()) ||
7409                     post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLower()))
7410                 {
7411                     SelectListItem(_curList, idx);
7412                     _curList.EnsureVisible(idx);
7413                     break;
7414                 }
7415             }
7416         }
7417
7418         private void GoAnchor()
7419         {
7420             if (_anchorPost == null) return;
7421             int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7422             if (idx == -1) return;
7423
7424             SelectListItem(_curList, idx);
7425             _curList.EnsureVisible(idx);
7426         }
7427
7428         private void GoTopEnd(bool GoTop)
7429         {
7430             if (_curList.VirtualListSize == 0)
7431                 return;
7432
7433             ListViewItem _item;
7434             int idx;
7435
7436             if (GoTop)
7437             {
7438                 _item = _curList.GetItemAt(0, 25);
7439                 if (_item == null)
7440                     idx = 0;
7441                 else
7442                     idx = _item.Index;
7443             }
7444             else
7445             {
7446                 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7447                 if (_item == null)
7448                     idx = _curList.VirtualListSize - 1;
7449                 else
7450                     idx = _item.Index;
7451             }
7452             SelectListItem(_curList, idx);
7453         }
7454
7455         private void GoMiddle()
7456         {
7457             if (_curList.VirtualListSize == 0)
7458                 return;
7459
7460             ListViewItem _item;
7461             int idx1;
7462             int idx2;
7463             int idx3;
7464
7465             _item = _curList.GetItemAt(0, 0);
7466             if (_item == null)
7467             {
7468                 idx1 = 0;
7469             }
7470             else
7471             {
7472                 idx1 = _item.Index;
7473             }
7474
7475             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7476             if (_item == null)
7477             {
7478                 idx2 = _curList.VirtualListSize - 1;
7479             }
7480             else
7481             {
7482                 idx2 = _item.Index;
7483             }
7484             idx3 = (idx1 + idx2) / 2;
7485
7486             SelectListItem(_curList, idx3);
7487         }
7488
7489         private void GoLast()
7490         {
7491             if (_curList.VirtualListSize == 0) return;
7492
7493             if (_statuses.SortOrder == SortOrder.Ascending)
7494             {
7495                 SelectListItem(_curList, _curList.VirtualListSize - 1);
7496                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7497             }
7498             else
7499             {
7500                 SelectListItem(_curList, 0);
7501                 _curList.EnsureVisible(0);
7502             }
7503         }
7504
7505         private void MoveTop()
7506         {
7507             if (_curList.SelectedIndices.Count == 0) return;
7508             int idx = _curList.SelectedIndices[0];
7509             if (_statuses.SortOrder == SortOrder.Ascending)
7510             {
7511                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7512             }
7513             else
7514             {
7515                 _curList.EnsureVisible(0);
7516             }
7517             _curList.EnsureVisible(idx);
7518         }
7519
7520         private async Task GoInReplyToPostTree()
7521         {
7522             if (_curPost == null) return;
7523
7524             TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7525
7526             if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7527             {
7528                 try
7529                 {
7530                     var post = tw.GetStatusApi(false, _curPost.StatusId);
7531
7532                     _curPost.InReplyToStatusId = post.InReplyToStatusId;
7533                     _curPost.InReplyToUser = post.InReplyToUser;
7534                     _curPost.IsReply = post.IsReply;
7535                     this.PurgeListViewItemCache();
7536                     _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7537                 }
7538                 catch (WebApiException ex)
7539                 {
7540                     this.StatusLabel.Text = ex.Message;
7541                 }
7542             }
7543
7544             if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7545
7546             if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7547             {
7548                 replyChains = new Stack<ReplyChain>();
7549             }
7550             replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7551
7552             int inReplyToIndex;
7553             string inReplyToTabName;
7554             long inReplyToId = _curPost.InReplyToStatusId.Value;
7555             string inReplyToUser = _curPost.InReplyToUser;
7556             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7557
7558             var inReplyToPosts = from tab in _statuses.Tabs.Values
7559                                  orderby tab != curTabClass
7560                                  from post in tab.Posts.Values
7561                                  where post.StatusId == inReplyToId
7562                                  let index = tab.IndexOf(post.StatusId)
7563                                  where index != -1
7564                                  select new {Tab = tab, Index = index};
7565
7566             var inReplyPost = inReplyToPosts.FirstOrDefault();
7567             if (inReplyPost == null)
7568             {
7569                 try
7570                 {
7571                     await Task.Run(() =>
7572                     {
7573                         var post = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value);
7574                         post.IsRead = true;
7575
7576                         _statuses.AddPost(post);
7577                         _statuses.DistributePosts();
7578                     });
7579                 }
7580                 catch (WebApiException ex)
7581                 {
7582                     this.StatusLabel.Text = ex.Message;
7583                     await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7584                     return;
7585                 }
7586
7587                 this.RefreshTimeline();
7588
7589                 inReplyPost = inReplyToPosts.FirstOrDefault();
7590                 if (inReplyPost == null)
7591                 {
7592                     await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7593                     return;
7594                 }
7595             }
7596             inReplyToTabName = inReplyPost.Tab.TabName;
7597             inReplyToIndex = inReplyPost.Index;
7598
7599             TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7600             DetailsListView listView = (DetailsListView)tabPage.Tag;
7601
7602             if (_curTab != tabPage)
7603             {
7604                 this.ListTab.SelectTab(tabPage);
7605             }
7606
7607             this.SelectListItem(listView, inReplyToIndex);
7608             listView.EnsureVisible(inReplyToIndex);
7609         }
7610
7611         private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7612         {
7613             if (_curPost == null) return;
7614
7615             TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7616             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7617
7618             if (parallel)
7619             {
7620                 if (_curPost.InReplyToStatusId != null)
7621                 {
7622                     var posts = from t in _statuses.Tabs
7623                                 from p in t.Value.Posts
7624                                 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7625                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7626                                 where indexOf > -1
7627                                 orderby isForward ? indexOf : indexOf * -1
7628                                 orderby t.Value != curTabClass
7629                                 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7630                     try
7631                     {
7632                         var postList = posts.ToList();
7633                         for (int i = postList.Count - 1; i >= 0; i--)
7634                         {
7635                             int index = i;
7636                             if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7637                             {
7638                                 postList.RemoveAt(index);
7639                             }
7640                         }
7641                         var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7642                         if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7643                         if (post == null) post = postList.First();
7644                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7645                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7646                         SelectListItem(listView, post.Index);
7647                         listView.EnsureVisible(post.Index);
7648                     }
7649                     catch (InvalidOperationException)
7650                     {
7651                         return;
7652                     }
7653                 }
7654             }
7655             else
7656             {
7657                 if (replyChains == null || replyChains.Count < 1)
7658                 {
7659                     var posts = from t in _statuses.Tabs
7660                                 from p in t.Value.Posts
7661                                 where p.Value.InReplyToStatusId == _curPost.StatusId
7662                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7663                                 where indexOf > -1
7664                                 orderby indexOf
7665                                 orderby t.Value != curTabClass
7666                                 select new {Tab = t.Value, Index = indexOf};
7667                     try
7668                     {
7669                         var post = posts.First();
7670                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7671                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7672                         SelectListItem(listView, post.Index);
7673                         listView.EnsureVisible(post.Index);
7674                     }
7675                     catch (InvalidOperationException)
7676                     {
7677                         return;
7678                     }
7679                 }
7680                 else
7681                 {
7682                     ReplyChain chainHead = replyChains.Pop();
7683                     if (chainHead.InReplyToId == _curPost.StatusId)
7684                     {
7685                         int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7686                         if (idx == -1)
7687                         {
7688                             replyChains = null;
7689                         }
7690                         else
7691                         {
7692                             try
7693                             {
7694                                 ListTab.SelectTab(chainHead.OriginalTab);
7695                             }
7696                             catch (Exception)
7697                             {
7698                                 replyChains = null;
7699                             }
7700                             SelectListItem(_curList, idx);
7701                             _curList.EnsureVisible(idx);
7702                         }
7703                     }
7704                     else
7705                     {
7706                         replyChains = null;
7707                         this.GoBackInReplyToPostTree(parallel);
7708                     }
7709                 }
7710             }
7711         }
7712
7713         private void GoBackSelectPostChain()
7714         {
7715             if (this.selectPostChains.Count > 1)
7716             {
7717                 var idx = -1;
7718                 TabPage tp = null;
7719
7720                 do
7721                 {
7722                     try
7723                     {
7724                         this.selectPostChains.Pop();
7725                         var tabPostPair = this.selectPostChains.Peek();
7726
7727                         if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue;  //該当タブが存在しないので無視
7728
7729                         if (tabPostPair.Item2 != null)
7730                         {
7731                             idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7732                             if (idx == -1) continue;  //該当ポストが存在しないので無視
7733                         }
7734
7735                         tp = tabPostPair.Item1;
7736
7737                         this.selectPostChains.Pop();
7738                     }
7739                     catch (InvalidOperationException)
7740                     {
7741                     }
7742
7743                     break;
7744                 }
7745                 while (this.selectPostChains.Count > 1);
7746
7747                 if (tp == null)
7748                 {
7749                     //状態がおかしいので処理を中断
7750                     //履歴が残り1つであればクリアしておく
7751                     if (this.selectPostChains.Count == 1)
7752                         this.selectPostChains.Clear();
7753                     return;
7754                 }
7755
7756                 DetailsListView lst = (DetailsListView)tp.Tag;
7757                 this.ListTab.SelectedTab = tp;
7758                 if (idx > -1)
7759                 {
7760                     SelectListItem(lst, idx);
7761                     lst.EnsureVisible(idx);
7762                 }
7763                 lst.Focus();
7764             }
7765         }
7766
7767         private void PushSelectPostChain()
7768         {
7769             int count = this.selectPostChains.Count;
7770             if (count > 0)
7771             {
7772                 var p = this.selectPostChains.Peek();
7773                 if (p.Item1 == this._curTab)
7774                 {
7775                     if (p.Item2 == this._curPost) return;  //最新の履歴と同一
7776                     if (p.Item2 == null) this.selectPostChains.Pop();  //置き換えるため削除
7777                 }
7778             }
7779             if (count >= 2500) TrimPostChain();
7780             this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7781         }
7782
7783         private void TrimPostChain()
7784         {
7785             if (this.selectPostChains.Count <= 2000) return;
7786             var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7787             for (int i = 0; i < 2000; i++)
7788             {
7789                 p.Push(this.selectPostChains.Pop());
7790             }
7791             this.selectPostChains.Clear();
7792             for (int i = 0; i < 2000; i++)
7793             {
7794                 this.selectPostChains.Push(p.Pop());
7795             }
7796         }
7797
7798         private bool GoStatus(long statusId)
7799         {
7800             if (statusId == 0) return false;
7801             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7802             {
7803                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7804                 {
7805                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7806                     ListTab.SelectedIndex = tabidx;
7807                     SelectListItem(_curList, idx);
7808                     _curList.EnsureVisible(idx);
7809                     return true;
7810                 }
7811             }
7812             return false;
7813         }
7814
7815         private bool GoDirectMessage(long statusId)
7816         {
7817             if (statusId == 0) return false;
7818             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7819             {
7820                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7821                 {
7822                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7823                     ListTab.SelectedIndex = tabidx;
7824                     SelectListItem(_curList, idx);
7825                     _curList.EnsureVisible(idx);
7826                     return true;
7827                 }
7828             }
7829             return false;
7830         }
7831
7832         private void MyList_MouseClick(object sender, MouseEventArgs e)
7833         {
7834             _anchorFlag = false;
7835         }
7836
7837         private void StatusText_Enter(object sender, EventArgs e)
7838         {
7839             // フォーカスの戻り先を StatusText に設定
7840             this.Tag = StatusText;
7841             StatusText.BackColor = _clInputBackcolor;
7842         }
7843
7844         public Color InputBackColor
7845         {
7846             get { return _clInputBackcolor; }
7847             set { _clInputBackcolor = value; }
7848         }
7849
7850         private void StatusText_Leave(object sender, EventArgs e)
7851         {
7852             // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7853             if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7854             StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7855         }
7856
7857         private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7858         {
7859             Task asyncTask;
7860             if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7861             {
7862                 e.Handled = true;
7863                 e.SuppressKeyPress = true;
7864             }
7865
7866             this.StatusText_TextChanged(null, null);
7867
7868             if (asyncTask != null)
7869                 await asyncTask;
7870         }
7871
7872         private void SaveConfigsAll(bool ifModified)
7873         {
7874             if (!ifModified)
7875             {
7876                 SaveConfigsCommon();
7877                 SaveConfigsLocal();
7878                 SaveConfigsTabs();
7879                 SaveConfigsAtId();
7880             }
7881             else
7882             {
7883                 if (ModifySettingCommon) SaveConfigsCommon();
7884                 if (ModifySettingLocal) SaveConfigsLocal();
7885                 if (ModifySettingAtId) SaveConfigsAtId();
7886             }
7887         }
7888
7889         private void SaveConfigsAtId()
7890         {
7891             if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7892
7893             ModifySettingAtId = false;
7894             SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7895             cfgAtId.Save();
7896         }
7897
7898         private void SaveConfigsCommon()
7899         {
7900             if (_ignoreConfigSave) return;
7901
7902             ModifySettingCommon = false;
7903             lock (_syncObject)
7904             {
7905                 _cfgCommon.UserName = tw.Username;
7906                 _cfgCommon.UserId = tw.UserId;
7907                 _cfgCommon.Password = tw.Password;
7908                 _cfgCommon.Token = tw.AccessToken;
7909                 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7910
7911                 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7912                    IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7913                 {
7914                     _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7915                 }
7916
7917                 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7918                 switch (_statuses.SortMode)
7919                 {
7920                     case ComparerMode.Nickname:  //ニックネーム
7921                         _cfgCommon.SortColumn = 1;
7922                         break;
7923                     case ComparerMode.Data:  //本文
7924                         _cfgCommon.SortColumn = 2;
7925                         break;
7926                     case ComparerMode.Id:  //時刻=発言Id
7927                         _cfgCommon.SortColumn = 3;
7928                         break;
7929                     case ComparerMode.Name:  //名前
7930                         _cfgCommon.SortColumn = 4;
7931                         break;
7932                     case ComparerMode.Source:  //Source
7933                         _cfgCommon.SortColumn = 7;
7934                         break;
7935                 }
7936
7937                 _cfgCommon.HashTags = HashMgr.HashHistories;
7938                 if (HashMgr.IsPermanent)
7939                 {
7940                     _cfgCommon.HashSelected = HashMgr.UseHash;
7941                 }
7942                 else
7943                 {
7944                     _cfgCommon.HashSelected = "";
7945                 }
7946                 _cfgCommon.HashIsHead = HashMgr.IsHead;
7947                 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7948                 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7949                 if (ToolStripFocusLockMenuItem != null &&
7950                         ToolStripFocusLockMenuItem.IsDisposed == false)
7951                 {
7952                     _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7953                 }
7954                 _cfgCommon.TrackWord = tw.TrackWord;
7955                 _cfgCommon.AllAtReply = tw.AllAtReply;
7956                 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7957                 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7958
7959                 _cfgCommon.Save();
7960             }
7961         }
7962
7963         private void SaveConfigsLocal()
7964         {
7965             if (_ignoreConfigSave) return;
7966             lock (_syncObject)
7967             {
7968                 ModifySettingLocal = false;
7969                 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7970                 _cfgLocal.FormSize = _mySize;
7971                 _cfgLocal.FormLocation = _myLoc;
7972                 _cfgLocal.SplitterDistance = _mySpDis;
7973                 _cfgLocal.PreviewDistance = _mySpDis3;
7974                 _cfgLocal.StatusMultiline = StatusText.Multiline;
7975                 _cfgLocal.StatusTextHeight = _mySpDis2;
7976
7977                 _cfgLocal.FontUnread = _fntUnread;
7978                 _cfgLocal.ColorUnread = _clUnread;
7979                 _cfgLocal.FontRead = _fntReaded;
7980                 _cfgLocal.ColorRead = _clReaded;
7981                 _cfgLocal.FontDetail = _fntDetail;
7982                 _cfgLocal.ColorDetail = _clDetail;
7983                 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7984                 _cfgLocal.ColorDetailLink = _clDetailLink;
7985                 _cfgLocal.ColorFav = _clFav;
7986                 _cfgLocal.ColorOWL = _clOWL;
7987                 _cfgLocal.ColorRetweet = _clRetweet;
7988                 _cfgLocal.ColorSelf = _clSelf;
7989                 _cfgLocal.ColorAtSelf = _clAtSelf;
7990                 _cfgLocal.ColorTarget = _clTarget;
7991                 _cfgLocal.ColorAtTarget = _clAtTarget;
7992                 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7993                 _cfgLocal.ColorAtTo = _clAtTo;
7994                 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7995                 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7996                 _cfgLocal.ColorInputFont = _clInputFont;
7997                 _cfgLocal.FontInputFont = _fntInputFont;
7998
7999                 if (_ignoreConfigSave) return;
8000                 _cfgLocal.Save();
8001             }
8002         }
8003
8004         private void SaveConfigsTabs()
8005         {
8006             SettingTabs tabSetting = new SettingTabs();
8007             for (int i = 0; i < ListTab.TabPages.Count; i++)
8008             {
8009                 var tab = _statuses.Tabs[ListTab.TabPages[i].Text];
8010                 if (tab.TabType != MyCommon.TabUsageType.Related && tab.TabType != MyCommon.TabUsageType.SearchResults)
8011                     tabSetting.Tabs.Add(tab);
8012             }
8013             tabSetting.Tabs.Add(this._statuses.GetTabByType(MyCommon.TabUsageType.Mute));
8014             tabSetting.Save();
8015         }
8016
8017         private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
8018         {
8019             string inputText;
8020             var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
8021             if (ret != DialogResult.OK)
8022                 return;
8023
8024             var match = Twitter.StatusUrlRegex.Match(inputText);
8025             if (!match.Success)
8026             {
8027                 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8028                     Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8029                 return;
8030             }
8031
8032             try
8033             {
8034                 var statusId = long.Parse(match.Groups["StatusId"].Value);
8035                 await this.OpenRelatedTab(statusId);
8036             }
8037             catch (TabException ex)
8038             {
8039                 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8040             }
8041         }
8042
8043         private void SaveLogMenuItem_Click(object sender, EventArgs e)
8044         {
8045             DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8046                     Properties.Resources.SaveLogMenuItem_ClickText2,
8047                     MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8048             if (rslt == DialogResult.Cancel) return;
8049
8050             SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8051             SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8052             SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8053             SaveFileDialog1.FilterIndex = 0;
8054             SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8055             SaveFileDialog1.RestoreDirectory = true;
8056
8057             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8058             {
8059                 if (!SaveFileDialog1.ValidateNames) return;
8060                 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8061                 {
8062                     if (rslt == DialogResult.Yes)
8063                     {
8064                         //All
8065                         for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8066                         {
8067                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
8068                             string protect = "";
8069                             if (post.IsProtect) protect = "Protect";
8070                             sw.WriteLine(post.Nickname + "\t" +
8071                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8072                                      post.CreatedAt.ToString() + "\t" +
8073                                      post.ScreenName + "\t" +
8074                                      post.StatusId.ToString() + "\t" +
8075                                      post.ImageUrl + "\t" +
8076                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8077                                      protect);
8078                         }
8079                     }
8080                     else
8081                     {
8082                         foreach (int idx in _curList.SelectedIndices)
8083                         {
8084                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
8085                             string protect = "";
8086                             if (post.IsProtect) protect = "Protect";
8087                             sw.WriteLine(post.Nickname + "\t" +
8088                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8089                                      post.CreatedAt.ToString() + "\t" +
8090                                      post.ScreenName + "\t" +
8091                                      post.StatusId.ToString() + "\t" +
8092                                      post.ImageUrl + "\t" +
8093                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8094                                      protect);
8095                         }
8096                     }
8097                 }
8098             }
8099             this.TopMost = this._cfgCommon.AlwaysTop;
8100         }
8101
8102         private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8103         {
8104             Task asyncTask;
8105             bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
8106             if (KeyRes)
8107             {
8108                 e.IsInputKey = true;
8109             }
8110             else
8111             {
8112                 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8113                 {
8114                     var shortcut = (Shortcut)e.KeyData;
8115                     switch (shortcut)
8116                     {
8117                         case Shortcut.CtrlA:
8118                         case Shortcut.CtrlC:
8119                         case Shortcut.CtrlIns:
8120                             // 既定の動作を有効にする
8121                             break;
8122                         default:
8123                             // その他のショートカットキーは無効にする
8124                             e.IsInputKey = true;
8125                             break;
8126                     }
8127                 }
8128             }
8129
8130             if (asyncTask != null)
8131                 await asyncTask;
8132         }
8133         public bool TabRename(ref string tabName)
8134         {
8135             //タブ名変更
8136             string newTabText = null;
8137             using (InputTabName inputName = new InputTabName())
8138             {
8139                 inputName.TabName = tabName;
8140                 inputName.ShowDialog();
8141                 if (inputName.DialogResult == DialogResult.Cancel) return false;
8142                 newTabText = inputName.TabName;
8143             }
8144             this.TopMost = this._cfgCommon.AlwaysTop;
8145             if (!string.IsNullOrEmpty(newTabText))
8146             {
8147                 //新タブ名存在チェック
8148                 for (int i = 0; i < ListTab.TabCount; i++)
8149                 {
8150                     if (ListTab.TabPages[i].Text == newTabText)
8151                     {
8152                         string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8153                         MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8154                         return false;
8155                     }
8156                 }
8157                 //タブ名を変更
8158                 for (int i = 0; i < ListTab.TabCount; i++)
8159                 {
8160                     if (ListTab.TabPages[i].Text == tabName)
8161                     {
8162                         ListTab.TabPages[i].Text = newTabText;
8163                         break;
8164                     }
8165                 }
8166                 _statuses.RenameTab(tabName, newTabText);
8167
8168                 SaveConfigsCommon();
8169                 SaveConfigsTabs();
8170                 _rclickTabName = newTabText;
8171                 tabName = newTabText;
8172                 return true;
8173             }
8174             else
8175             {
8176                 return false;
8177             }
8178         }
8179
8180         private void ListTab_MouseClick(object sender, MouseEventArgs e)
8181         {
8182             if (e.Button == MouseButtons.Middle)
8183             {
8184                 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8185                 {
8186                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8187                     {
8188                         this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8189                         this.SaveConfigsTabs();
8190                         break;
8191                     }
8192                 }
8193             }
8194         }
8195
8196         private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8197         {
8198             string tn = ListTab.SelectedTab.Text;
8199             TabRename(ref tn);
8200         }
8201
8202         private void ListTab_MouseDown(object sender, MouseEventArgs e)
8203         {
8204             if (this._cfgCommon.TabMouseLock) return;
8205             Point cpos = new Point(e.X, e.Y);
8206             if (e.Button == MouseButtons.Left)
8207             {
8208                 for (int i = 0; i < ListTab.TabPages.Count; i++)
8209                 {
8210                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8211                     {
8212                         _tabDrag = true;
8213                         _tabMouseDownPoint = e.Location;
8214                         break;
8215                     }
8216                 }
8217             }
8218             else
8219             {
8220                 _tabDrag = false;
8221             }
8222         }
8223
8224         private void ListTab_DragEnter(object sender, DragEventArgs e)
8225         {
8226             if (e.Data.GetDataPresent(typeof(TabPage)))
8227                 e.Effect = DragDropEffects.Move;
8228             else
8229                 e.Effect = DragDropEffects.None;
8230         }
8231
8232         private void ListTab_DragDrop(object sender, DragEventArgs e)
8233         {
8234             if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8235
8236             _tabDrag = false;
8237             string tn = "";
8238             bool bef = false;
8239             Point cpos = new Point(e.X, e.Y);
8240             Point spos = ListTab.PointToClient(cpos);
8241             int i;
8242             for (i = 0; i < ListTab.TabPages.Count; i++)
8243             {
8244                 Rectangle rect = ListTab.GetTabRect(i);
8245                 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8246                     rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8247                 {
8248                     tn = ListTab.TabPages[i].Text;
8249                     if (spos.X <= (rect.Left + rect.Right) / 2)
8250                         bef = true;
8251                     else
8252                         bef = false;
8253
8254                     break;
8255                 }
8256             }
8257
8258             //タブのないところにドロップ->最後尾へ移動
8259             if (string.IsNullOrEmpty(tn))
8260             {
8261                 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8262                 bef = false;
8263                 i = ListTab.TabPages.Count - 1;
8264             }
8265
8266             TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8267             if (tp.Text == tn) return;
8268
8269             ReOrderTab(tp.Text, tn, bef);
8270         }
8271
8272         public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8273         {
8274             var baseIndex = this.GetTabPageIndex(baseTabText);
8275             if (baseIndex == -1)
8276                 return;
8277
8278             var targetIndex = this.GetTabPageIndex(targetTabText);
8279             if (targetIndex == -1)
8280                 return;
8281
8282             using (ControlTransaction.Layout(this.ListTab))
8283             {
8284                 var mTp = this.ListTab.TabPages[targetIndex];
8285                 this.ListTab.TabPages.Remove(mTp);
8286
8287                 if (targetIndex < baseIndex)
8288                     baseIndex--;
8289
8290                 if (isBeforeBaseTab)
8291                     ListTab.TabPages.Insert(baseIndex, mTp);
8292                 else
8293                     ListTab.TabPages.Insert(baseIndex + 1, mTp);
8294             }
8295
8296             SaveConfigsTabs();
8297         }
8298
8299         private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8300         {
8301             //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8302             //isReply:true=@,false=DM
8303             if (!StatusText.Enabled) return;
8304             if (_curList == null) return;
8305             if (_curTab == null) return;
8306             if (!this.ExistCurrentPost) return;
8307
8308             // 複数あてリプライはReplyではなく通常ポスト
8309             //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8310             //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8311             //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8312
8313             if (_curList.SelectedIndices.Count > 0)
8314             {
8315                 // アイテムが1件以上選択されている
8316                 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8317                 {
8318                     // 単独ユーザー宛リプライまたはDM
8319                     if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8320                     {
8321                         // ダイレクトメッセージ
8322                         StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8323                         StatusText.SelectionStart = StatusText.Text.Length;
8324                         StatusText.Focus();
8325                         this.inReplyTo = null;
8326                         return;
8327                     }
8328                     if (string.IsNullOrEmpty(StatusText.Text))
8329                     {
8330                         //空の場合
8331
8332                         // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8333                         StatusText.Text = "@" + _curPost.ScreenName + " ";
8334
8335                         var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8336                         var inReplyToScreenName = this._curPost.ScreenName;
8337                         this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8338                     }
8339                     else
8340                     {
8341                         //何か入力済の場合
8342
8343                         if (isAuto)
8344                         {
8345                             //1件選んでEnter or DoubleClick
8346                             if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8347                             {
8348                                 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
8349                                 {
8350                                     //返信先書き換え
8351                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8352                                     var inReplyToScreenName = this._curPost.ScreenName;
8353                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8354                                 }
8355                                 return;
8356                             }
8357                             if (!StatusText.Text.StartsWith("@"))
8358                             {
8359                                 //文頭@以外
8360                                 if (StatusText.Text.StartsWith(". "))
8361                                 {
8362                                     // 複数リプライ
8363                                     StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8364                                     this.inReplyTo = null;
8365                                 }
8366                                 else
8367                                 {
8368                                     // 単独リプライ
8369                                     StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8370                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8371                                     var inReplyToScreenName = this._curPost.ScreenName;
8372                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8373                                 }
8374                             }
8375                             else
8376                             {
8377                                 //文頭@
8378                                 // 複数リプライ
8379                                 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8380                                 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8381                                 this.inReplyTo = null;
8382                             }
8383                         }
8384                         else
8385                         {
8386                             //1件選んでCtrl-Rの場合(返信先操作せず)
8387                             int sidx = StatusText.SelectionStart;
8388                             string id = "@" + _curPost.ScreenName + " ";
8389                             if (sidx > 0)
8390                             {
8391                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8392                                 {
8393                                     id = " " + id;
8394                                 }
8395                             }
8396                             StatusText.Text = StatusText.Text.Insert(sidx, id);
8397                             sidx += id.Length;
8398                             //if (StatusText.Text.StartsWith("@"))
8399                             //{
8400                             //    //複数リプライ
8401                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8402                             //    sidx += 5 + _curPost.ScreenName.Length;
8403                             //}
8404                             //else
8405                             //{
8406                             //    // 複数リプライ
8407                             //    StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8408                             //    sidx += 3 + _curPost.ScreenName.Length;
8409                             //}
8410                             StatusText.SelectionStart = sidx;
8411                             StatusText.Focus();
8412                             //_reply_to_id = 0;
8413                             //_reply_to_name = null;
8414                             return;
8415                         }
8416                     }
8417                 }
8418                 else
8419                 {
8420                     // 複数リプライ
8421                     if (!isAuto && !isReply) return;
8422
8423                     //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8424
8425                     if (isAuto)
8426                     {
8427                         //Enter or DoubleClick
8428
8429                         string sTxt = StatusText.Text;
8430                         if (!sTxt.StartsWith(". "))
8431                         {
8432                             sTxt = ". " + sTxt;
8433                             this.inReplyTo = null;
8434                         }
8435                         for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8436                         {
8437                             PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8438                             if (!sTxt.Contains("@" + post.ScreenName + " "))
8439                             {
8440                                 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8441                                 //sTxt = "@" + post.ScreenName + " " + sTxt;
8442                             }
8443                         }
8444                         StatusText.Text = sTxt;
8445                     }
8446                     else
8447                     {
8448                         //C-S-r or C-r
8449                         if (_curList.SelectedIndices.Count > 1)
8450                         {
8451                             //複数ポスト選択
8452
8453                             string ids = "";
8454                             int sidx = StatusText.SelectionStart;
8455                             for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8456                             {
8457                                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8458                                 if (!ids.Contains("@" + post.ScreenName + " ") &&
8459                                     !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8460                                 {
8461                                     ids += "@" + post.ScreenName + " ";
8462                                 }
8463                                 if (isAll)
8464                                 {
8465                                     foreach (string nm in post.ReplyToList)
8466                                     {
8467                                         if (!ids.Contains("@" + nm + " ") &&
8468                                             !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8469                                         {
8470                                             Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8471                                             if (m.Success)
8472                                                 ids += "@" + m.Result("${id}") + " ";
8473                                             else
8474                                                 ids += "@" + nm + " ";
8475                                         }
8476                                     }
8477                                 }
8478                             }
8479                             if (ids.Length == 0) return;
8480                             if (!StatusText.Text.StartsWith(". "))
8481                             {
8482                                 StatusText.Text = ". " + StatusText.Text;
8483                                 sidx += 2;
8484                                 this.inReplyTo = null;
8485                             }
8486                             if (sidx > 0)
8487                             {
8488                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8489                                 {
8490                                     ids = " " + ids;
8491                                 }
8492                             }
8493                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8494                             sidx += ids.Length;
8495                             //if (StatusText.Text.StartsWith("@"))
8496                             //{
8497                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8498                             //    sidx += 2 + ids.Length;
8499                             //}
8500                             //else
8501                             //{
8502                             //    StatusText.Text = StatusText.Text.Insert(sidx, ids);
8503                             //    sidx += 1 + ids.Length;
8504                             //}
8505                             StatusText.SelectionStart = sidx;
8506                             StatusText.Focus();
8507                             return;
8508                         }
8509                         else
8510                         {
8511                             //1件のみ選択のC-S-r(返信元付加する可能性あり)
8512
8513                             string ids = "";
8514                             int sidx = StatusText.SelectionStart;
8515                             PostClass post = _curPost;
8516                             if (!ids.Contains("@" + post.ScreenName + " ") &&
8517                                 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8518                             {
8519                                 ids += "@" + post.ScreenName + " ";
8520                             }
8521                             foreach (string nm in post.ReplyToList)
8522                             {
8523                                 if (!ids.Contains("@" + nm + " ") &&
8524                                     !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8525                                 {
8526                                     Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8527                                     if (m.Success)
8528                                         ids += "@" + m.Result("${id}") + " ";
8529                                     else
8530                                         ids += "@" + nm + " ";
8531                                 }
8532                             }
8533                             if (!string.IsNullOrEmpty(post.RetweetedBy))
8534                             {
8535                                 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8536                                    !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8537                                 {
8538                                     ids += "@" + post.RetweetedBy + " ";
8539                                 }
8540                             }
8541                             if (ids.Length == 0) return;
8542                             if (string.IsNullOrEmpty(StatusText.Text))
8543                             {
8544                                 //未入力の場合のみ返信先付加
8545                                 StatusText.Text = ids;
8546                                 StatusText.SelectionStart = ids.Length;
8547                                 StatusText.Focus();
8548
8549                                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8550                                 var inReplyToScreenName = this._curPost.ScreenName;
8551                                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8552                                 return;
8553                             }
8554
8555                             if (sidx > 0)
8556                             {
8557                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8558                                 {
8559                                     ids = " " + ids;
8560                                 }
8561                             }
8562                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8563                             sidx += ids.Length;
8564                             StatusText.SelectionStart = sidx;
8565                             StatusText.Focus();
8566                             return;
8567                         }
8568                     }
8569                 }
8570                 StatusText.SelectionStart = StatusText.Text.Length;
8571                 StatusText.Focus();
8572             }
8573         }
8574
8575         private void ListTab_MouseUp(object sender, MouseEventArgs e)
8576         {
8577             _tabDrag = false;
8578         }
8579
8580         private static int iconCnt = 0;
8581         private static int blinkCnt = 0;
8582         private static bool blink = false;
8583         private static bool idle = false;
8584
8585         private async Task RefreshTasktrayIcon()
8586         {
8587             if (_colorize)
8588                 await this.Colorize();
8589
8590             if (!TimerRefreshIcon.Enabled) return;
8591             //Static usCheckCnt As int = 0
8592
8593             //Static iconDlListTopItem As ListViewItem = null
8594
8595             //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8596             //    ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8597             //else
8598             //    ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8599             //
8600             //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8601
8602             iconCnt += 1;
8603             blinkCnt += 1;
8604             //usCheckCnt += 1;
8605
8606             //if (usCheckCnt > 300)    //1min
8607             //{
8608             //    usCheckCnt = 0;
8609             //    if (!this.IsReceivedUserStream)
8610             //    {
8611             //        TraceOut("ReconnectUserStream");
8612             //        tw.ReconnectUserStream();
8613             //    }
8614             //}
8615
8616             var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8617
8618             if (iconCnt >= this.NIconRefresh.Length)
8619             {
8620                 iconCnt = 0;
8621             }
8622             if (blinkCnt > 10)
8623             {
8624                 blinkCnt = 0;
8625                 //未保存の変更を保存
8626                 SaveConfigsAll(true);
8627             }
8628
8629             if (busy)
8630             {
8631                 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8632                 idle = false;
8633                 _myStatusError = false;
8634                 return;
8635             }
8636
8637             TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8638             if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8639             {
8640                 if (blinkCnt > 0) return;
8641                 blink = !blink;
8642                 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8643                 {
8644                     NotifyIcon1.Icon = ReplyIcon;
8645                 }
8646                 else
8647                 {
8648                     NotifyIcon1.Icon = ReplyIconBlink;
8649                 }
8650                 idle = false;
8651                 return;
8652             }
8653
8654             if (idle) return;
8655             idle = true;
8656             //優先度:エラー→オフライン→アイドル
8657             //エラーは更新アイコンでクリアされる
8658             if (_myStatusError)
8659             {
8660                 NotifyIcon1.Icon = NIconAtRed;
8661                 return;
8662             }
8663             if (_myStatusOnline)
8664             {
8665                 NotifyIcon1.Icon = NIconAt;
8666             }
8667             else
8668             {
8669                 NotifyIcon1.Icon = NIconAtSmoke;
8670             }
8671         }
8672
8673         private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8674         {
8675             //200ms
8676             await this.RefreshTasktrayIcon();
8677         }
8678
8679         private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8680         {
8681             //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8682             if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8683             {
8684                 if (ListTab != null && ListTab.SelectedTab != null)
8685                     _rclickTabName = ListTab.SelectedTab.Text;
8686                 else
8687                     return;
8688             }
8689
8690             if (_statuses == null) return;
8691             if (_statuses.Tabs == null) return;
8692
8693             TabClass tb = _statuses.Tabs[_rclickTabName];
8694             if (tb == null) return;
8695
8696             NotifyDispMenuItem.Checked = tb.Notify;
8697             this.NotifyTbMenuItem.Checked = tb.Notify;
8698
8699             soundfileListup = true;
8700             SoundFileComboBox.Items.Clear();
8701             this.SoundFileTbComboBox.Items.Clear();
8702             SoundFileComboBox.Items.Add("");
8703             this.SoundFileTbComboBox.Items.Add("");
8704             DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8705             if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8706             {
8707                 oDir = oDir.GetDirectories("Sounds")[0];
8708             }
8709             foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8710             {
8711                 SoundFileComboBox.Items.Add(oFile.Name);
8712                 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8713             }
8714             int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8715             if (idx == -1) idx = 0;
8716             SoundFileComboBox.SelectedIndex = idx;
8717             this.SoundFileTbComboBox.SelectedIndex = idx;
8718             soundfileListup = false;
8719             UreadManageMenuItem.Checked = tb.UnreadManage;
8720             this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8721
8722             TabMenuControl(_rclickTabName);
8723         }
8724
8725         private void TabMenuControl(string tabName)
8726         {
8727             var tabInfo = _statuses.GetTabByName(tabName);
8728
8729             this.FilterEditMenuItem.Enabled = true;
8730             this.EditRuleTbMenuItem.Enabled = true;
8731
8732             if (tabInfo.IsDefaultTabType)
8733             {
8734                 this.ProtectTabMenuItem.Enabled = false;
8735                 this.ProtectTbMenuItem.Enabled = false;
8736             }
8737             else
8738             {
8739                 this.ProtectTabMenuItem.Enabled = true;
8740                 this.ProtectTbMenuItem.Enabled = true;
8741             }
8742
8743             if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8744             {
8745                 this.ProtectTabMenuItem.Checked = true;
8746                 this.ProtectTbMenuItem.Checked = true;
8747                 this.DeleteTabMenuItem.Enabled = false;
8748                 this.DeleteTbMenuItem.Enabled = false;
8749             }
8750             else
8751             {
8752                 this.ProtectTabMenuItem.Checked = false;
8753                 this.ProtectTbMenuItem.Checked = false;
8754                 this.DeleteTabMenuItem.Enabled = true;
8755                 this.DeleteTbMenuItem.Enabled = true;
8756             }
8757         }
8758
8759         private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8760         {
8761             var checkState = ((ToolStripMenuItem)sender).Checked;
8762
8763             // チェック状態を同期
8764             this.ProtectTbMenuItem.Checked = checkState;
8765             this.ProtectTabMenuItem.Checked = checkState;
8766
8767             // ロック中はタブの削除を無効化
8768             this.DeleteTabMenuItem.Enabled = !checkState;
8769             this.DeleteTbMenuItem.Enabled = !checkState;
8770
8771             if (string.IsNullOrEmpty(_rclickTabName)) return;
8772             _statuses.Tabs[_rclickTabName].Protected = checkState;
8773
8774             SaveConfigsTabs();
8775         }
8776
8777         private void UreadManageMenuItem_Click(object sender, EventArgs e)
8778         {
8779             UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8780             this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8781
8782             if (string.IsNullOrEmpty(_rclickTabName)) return;
8783             ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8784
8785             SaveConfigsTabs();
8786         }
8787
8788         public void ChangeTabUnreadManage(string tabName, bool isManage)
8789         {
8790             var idx = this.GetTabPageIndex(tabName);
8791             if (idx == -1)
8792                 return;
8793
8794             _statuses.Tabs[tabName].UnreadManage = isManage;
8795             if (this._cfgCommon.TabIconDisp)
8796             {
8797                 if (_statuses.Tabs[tabName].UnreadCount > 0)
8798                     ListTab.TabPages[idx].ImageIndex = 0;
8799                 else
8800                     ListTab.TabPages[idx].ImageIndex = -1;
8801             }
8802
8803             if (_curTab.Text == tabName)
8804             {
8805                 this.PurgeListViewItemCache();
8806                 _curList.Refresh();
8807             }
8808
8809             SetMainWindowTitle();
8810             SetStatusLabelUrl();
8811             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8812         }
8813
8814         private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8815         {
8816             NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8817             this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8818
8819             if (string.IsNullOrEmpty(_rclickTabName)) return;
8820
8821             _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8822
8823             SaveConfigsTabs();
8824         }
8825
8826         private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8827         {
8828             if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8829
8830             _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8831
8832             SaveConfigsTabs();
8833         }
8834
8835         private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8836         {
8837             if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8838
8839             RemoveSpecifiedTab(_rclickTabName, true);
8840             SaveConfigsTabs();
8841         }
8842
8843         private void FilterEditMenuItem_Click(object sender, EventArgs e)
8844         {
8845             if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8846
8847             using (var fltDialog = new FilterDialog())
8848             {
8849                 fltDialog.Owner = this;
8850                 fltDialog.SetCurrent(_rclickTabName);
8851                 fltDialog.ShowDialog(this);
8852             }
8853             this.TopMost = this._cfgCommon.AlwaysTop;
8854
8855             this.ApplyPostFilters();
8856             SaveConfigsTabs();
8857         }
8858
8859         private void AddTabMenuItem_Click(object sender, EventArgs e)
8860         {
8861             string tabName = null;
8862             MyCommon.TabUsageType tabUsage;
8863             using (InputTabName inputName = new InputTabName())
8864             {
8865                 inputName.TabName = _statuses.MakeTabName("MyTab");
8866                 inputName.IsShowUsage = true;
8867                 inputName.ShowDialog();
8868                 if (inputName.DialogResult == DialogResult.Cancel) return;
8869                 tabName = inputName.TabName;
8870                 tabUsage = inputName.Usage;
8871             }
8872             this.TopMost = this._cfgCommon.AlwaysTop;
8873             if (!string.IsNullOrEmpty(tabName))
8874             {
8875                 //List対応
8876                 ListElement list = null;
8877                 if (tabUsage == MyCommon.TabUsageType.Lists)
8878                 {
8879                     using (ListAvailable listAvail = new ListAvailable())
8880                     {
8881                         if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8882                         if (listAvail.SelectedList == null) return;
8883                         list = listAvail.SelectedList;
8884                     }
8885                 }
8886                 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8887                 {
8888                     string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8889                     MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8890                 }
8891                 else
8892                 {
8893                     //成功
8894                     SaveConfigsTabs();
8895                     if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8896                     {
8897                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8898                         ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8899                     }
8900                     if (tabUsage == MyCommon.TabUsageType.Lists)
8901                     {
8902                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8903                         var tab = this._statuses.Tabs[this._curTab.Text];
8904                         this.GetListTimelineAsync(tab);
8905                     }
8906                 }
8907             }
8908         }
8909
8910         private void TabMenuItem_Click(object sender, EventArgs e)
8911         {
8912             using (var fltDialog = new FilterDialog())
8913             {
8914                 fltDialog.Owner = this;
8915
8916                 //選択発言を元にフィルタ追加
8917                 foreach (int idx in _curList.SelectedIndices)
8918                 {
8919                     string tabName;
8920                     //タブ選択(or追加)
8921                     if (!SelectTab(out tabName)) return;
8922
8923                     fltDialog.SetCurrent(tabName);
8924                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8925                     {
8926                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8927                     }
8928                     else
8929                     {
8930                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8931                     }
8932                     fltDialog.ShowDialog(this);
8933                     this.TopMost = this._cfgCommon.AlwaysTop;
8934                 }
8935             }
8936
8937             this.ApplyPostFilters();
8938             SaveConfigsTabs();
8939             if (this.ListTab.SelectedTab != null &&
8940                 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8941             {
8942                 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8943             }
8944         }
8945
8946         protected override bool ProcessDialogKey(Keys keyData)
8947         {
8948             //TextBox1でEnterを押してもビープ音が鳴らないようにする
8949             if ((keyData & Keys.KeyCode) == Keys.Enter)
8950             {
8951                 if (StatusText.Focused)
8952                 {
8953                     bool _NewLine = false;
8954                     bool _Post = false;
8955
8956                     if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8957                     {
8958                         if (StatusText.Multiline)
8959                         {
8960                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8961
8962                             if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8963                         }
8964                         else
8965                         {
8966                             if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8967                         }
8968
8969                     }
8970                     else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8971                     {
8972                         if (StatusText.Multiline)
8973                         {
8974                             if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8975
8976                             if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8977                         }
8978                         else
8979                         {
8980                             if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8981                         }
8982
8983                     }
8984                     else //Enter投稿時
8985                     {
8986                         if (StatusText.Multiline)
8987                         {
8988                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8989
8990                             if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8991                                 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8992                         }
8993                         else
8994                         {
8995                             if (((keyData & Keys.Shift) == Keys.Shift) ||
8996                                 (((keyData & Keys.Control) != Keys.Control) &&
8997                                 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8998                         }
8999                     }
9000
9001                     if (_NewLine)
9002                     {
9003                         int pos1 = StatusText.SelectionStart;
9004                         if (StatusText.SelectionLength > 0)
9005                         {
9006                             StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength);  //選択状態文字列削除
9007                         }
9008                         StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine);  //改行挿入
9009                         StatusText.SelectionStart = pos1 + Environment.NewLine.Length;    //カーソルを改行の次の文字へ移動
9010                         return true;
9011                     }
9012                     else if (_Post)
9013                     {
9014                         PostButton_Click(null, null);
9015                         return true;
9016                     }
9017                 }
9018                 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
9019                          (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
9020                          ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
9021                 {
9022                     this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9023                     return true;
9024                 }
9025             }
9026
9027             return base.ProcessDialogKey(keyData);
9028         }
9029
9030         private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9031         {
9032             MakeReplyOrDirectStatus(false, true, true);
9033         }
9034
9035         private void IDRuleMenuItem_Click(object sender, EventArgs e)
9036         {
9037             string tabName;
9038
9039             //未選択なら処理終了
9040             if (_curList.SelectedIndices.Count == 0) return;
9041
9042             //タブ選択(or追加)
9043             if (!SelectTab(out tabName)) return;
9044
9045             var tab = this._statuses.Tabs[tabName];
9046
9047             bool mv;
9048             bool mk;
9049             if (tab.TabType != MyCommon.TabUsageType.Mute)
9050             {
9051                 this.MoveOrCopy(out mv, out mk);
9052             }
9053             else
9054             {
9055                 // ミュートタブでは常に MoveMatches を true にする
9056                 mv = true;
9057                 mk = false;
9058             }
9059
9060             List<string> ids = new List<string>();
9061             foreach (int idx in _curList.SelectedIndices)
9062             {
9063                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9064                 if (!ids.Contains(post.ScreenName))
9065                 {
9066                     PostFilterRule fc = new PostFilterRule();
9067                     ids.Add(post.ScreenName);
9068                     if (post.RetweetedId == null)
9069                     {
9070                         fc.FilterName = post.ScreenName;
9071                     }
9072                     else
9073                     {
9074                         fc.FilterName = post.RetweetedBy;
9075                     }
9076                     fc.UseNameField = true;
9077                     fc.MoveMatches = mv;
9078                     fc.MarkMatches = mk;
9079                     fc.UseRegex = false;
9080                     fc.FilterByUrl = false;
9081                     tab.AddFilter(fc);
9082                 }
9083             }
9084             if (ids.Count != 0)
9085             {
9086                 List<string> atids = new List<string>();
9087                 foreach (string id in ids)
9088                 {
9089                     atids.Add("@" + id);
9090                 }
9091                 int cnt = AtIdSupl.ItemCount;
9092                 AtIdSupl.AddRangeItem(atids.ToArray());
9093                 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
9094             }
9095
9096             this.ApplyPostFilters();
9097             SaveConfigsTabs();
9098         }
9099
9100         private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9101         {
9102             if (this._curList.SelectedIndices.Count == 0)
9103                 return;
9104
9105             // タブ選択ダイアログを表示(or追加)
9106             string tabName;
9107             if (!this.SelectTab(out tabName))
9108                 return;
9109
9110             var currentTab = this._statuses.Tabs[this._curTab.Text];
9111             var filterTab = this._statuses.Tabs[tabName];
9112
9113             bool mv;
9114             bool mk;
9115             if (filterTab.TabType != MyCommon.TabUsageType.Mute)
9116             {
9117                 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9118                 this.MoveOrCopy(out mv, out mk);
9119             }
9120             else
9121             {
9122                 // ミュートタブでは常に MoveMatches を true にする
9123                 mv = true;
9124                 mk = false;
9125             }
9126
9127             // 振り分けルールに追加するSource
9128             var sources = new HashSet<string>();
9129
9130             foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9131             {
9132                 var post = currentTab[idx];
9133                 var filterSource = post.Source;
9134
9135                 if (sources.Add(filterSource))
9136                 {
9137                     var filter = new PostFilterRule
9138                     {
9139                         FilterSource = filterSource,
9140                         MoveMatches = mv,
9141                         MarkMatches = mk,
9142                         UseRegex = false,
9143                         FilterByUrl = false,
9144                     };
9145                     filterTab.AddFilter(filter);
9146                 }
9147             }
9148
9149             this.ApplyPostFilters();
9150             this.SaveConfigsTabs();
9151         }
9152
9153         private bool SelectTab(out string tabName)
9154         {
9155             do
9156             {
9157                 tabName = null;
9158
9159                 //振り分け先タブ選択
9160                 using (var dialog = new TabsDialog(_statuses))
9161                 {
9162                     if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9163
9164                     var selectedTab = dialog.SelectedTab;
9165                     tabName = selectedTab == null ? null : selectedTab.TabName;
9166                 }
9167
9168                 ListTab.SelectedTab.Focus();
9169                 //新規タブを選択→タブ作成
9170                 if (tabName == null)
9171                 {
9172                     using (InputTabName inputName = new InputTabName())
9173                     {
9174                         inputName.TabName = _statuses.MakeTabName("MyTab");
9175                         inputName.ShowDialog();
9176                         if (inputName.DialogResult == DialogResult.Cancel) return false;
9177                         tabName = inputName.TabName;
9178                     }
9179                     this.TopMost = this._cfgCommon.AlwaysTop;
9180                     if (!string.IsNullOrEmpty(tabName))
9181                     {
9182                         if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9183                         {
9184                             string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9185                             MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9186                             //もう一度タブ名入力
9187                         }
9188                         else
9189                         {
9190                             return true;
9191                         }
9192                     }
9193                 }
9194                 else
9195                 {
9196                     //既存タブを選択
9197                     return true;
9198                 }
9199             }
9200             while (true);
9201         }
9202
9203         private void MoveOrCopy(out bool move, out bool mark)
9204         {
9205             {
9206                 //移動するか?
9207                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9208                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9209                     move = false;
9210                 else
9211                     move = true;
9212             }
9213             if (!move)
9214             {
9215                 //マークするか?
9216                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9217                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9218                     mark = true;
9219                 else
9220                     mark = false;
9221             }
9222             else
9223             {
9224                 mark = false;
9225             }
9226         }
9227         private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9228         {
9229             this.CopyStot();
9230         }
9231
9232         private void CopyURLMenuItem_Click(object sender, EventArgs e)
9233         {
9234             this.CopyIdUri();
9235         }
9236
9237         private void SelectAllMenuItem_Click(object sender, EventArgs e)
9238         {
9239             if (StatusText.Focused)
9240             {
9241                 // 発言欄でのCtrl+A
9242                 StatusText.SelectAll();
9243             }
9244             else
9245             {
9246                 // ListView上でのCtrl+A
9247                 NativeMethods.SelectAllItems(this._curList);
9248             }
9249         }
9250
9251         private void MoveMiddle()
9252         {
9253             ListViewItem _item;
9254             int idx1;
9255             int idx2;
9256
9257             if (_curList.SelectedIndices.Count == 0) return;
9258
9259             int idx = _curList.SelectedIndices[0];
9260
9261             _item = _curList.GetItemAt(0, 25);
9262             if (_item == null)
9263                 idx1 = 0;
9264             else
9265                 idx1 = _item.Index;
9266
9267             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9268             if (_item == null)
9269                 idx2 = _curList.VirtualListSize - 1;
9270             else
9271                 idx2 = _item.Index;
9272
9273             idx -= Math.Abs(idx1 - idx2) / 2;
9274             if (idx < 0) idx = 0;
9275
9276             _curList.EnsureVisible(_curList.VirtualListSize - 1);
9277             _curList.EnsureVisible(idx);
9278         }
9279
9280         private async void OpenURLMenuItem_Click(object sender, EventArgs e)
9281         {
9282             var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
9283                 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
9284                 .ToArray();
9285
9286             if (linkElements.Length > 0)
9287             {
9288                 UrlDialog.ClearUrl();
9289
9290                 string openUrlStr = "";
9291
9292                 if (linkElements.Length == 1)
9293                 {
9294                     // ツイートに含まれる URL が 1 つのみの場合
9295                     //   => OpenURL ダイアログを表示せずにリンクを開く
9296
9297                     string urlStr = "";
9298                     try
9299                     {
9300                         urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
9301                     }
9302                     catch (ArgumentException)
9303                     {
9304                         //変なHTML?
9305                         return;
9306                     }
9307                     catch (Exception)
9308                     {
9309                         return;
9310                     }
9311                     if (string.IsNullOrEmpty(urlStr)) return;
9312                     openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9313
9314                     // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
9315                     await this.OpenUriAsync(new Uri(openUrlStr));
9316                 }
9317                 else
9318                 {
9319                     // ツイートに含まれる URL が複数ある場合
9320                     //   => OpenURL を表示しユーザーが選択したリンクを開く
9321
9322                     foreach (var linkElm in linkElements)
9323                     {
9324                         string urlStr = "";
9325                         string linkText = "";
9326                         string href = "";
9327                         try
9328                         {
9329                             urlStr = linkElm.GetAttribute("title");
9330                             href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9331                             if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9332                             linkText = linkElm.InnerText;
9333                         }
9334                         catch (ArgumentException)
9335                         {
9336                             //変なHTML?
9337                             return;
9338                         }
9339                         catch (Exception)
9340                         {
9341                             return;
9342                         }
9343                         if (string.IsNullOrEmpty(urlStr)) continue;
9344                         UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9345                     }
9346                     try
9347                     {
9348                         if (UrlDialog.ShowDialog() == DialogResult.OK)
9349                         {
9350                             openUrlStr = UrlDialog.SelectedUrl;
9351
9352                             // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
9353                             await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
9354                         }
9355                     }
9356                     catch (Exception)
9357                     {
9358                         return;
9359                     }
9360                     this.TopMost = this._cfgCommon.AlwaysTop;
9361                 }
9362             }
9363         }
9364
9365         private void ClearTabMenuItem_Click(object sender, EventArgs e)
9366         {
9367             if (string.IsNullOrEmpty(_rclickTabName)) return;
9368             ClearTab(_rclickTabName, true);
9369         }
9370
9371         private void ClearTab(string tabName, bool showWarning)
9372         {
9373             if (showWarning)
9374             {
9375                 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9376                 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9377                 {
9378                     return;
9379                 }
9380             }
9381
9382             _statuses.ClearTabIds(tabName);
9383             if (ListTab.SelectedTab.Text == tabName)
9384             {
9385                 _anchorPost = null;
9386                 _anchorFlag = false;
9387                 this.PurgeListViewItemCache();
9388                 _curItemIndex = -1;
9389                 _curPost = null;
9390             }
9391             foreach (TabPage tb in ListTab.TabPages)
9392             {
9393                 if (tb.Text == tabName)
9394                 {
9395                     tb.ImageIndex = -1;
9396                     ((DetailsListView)tb.Tag).VirtualListSize = 0;
9397                     break;
9398                 }
9399             }
9400             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9401
9402             SetMainWindowTitle();
9403             SetStatusLabelUrl();
9404         }
9405
9406         private static long followers = 0;
9407
9408         private void SetMainWindowTitle()
9409         {
9410             //メインウインドウタイトルの書き換え
9411             StringBuilder ttl = new StringBuilder(256);
9412             int ur = 0;
9413             int al = 0;
9414             if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9415                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9416                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9417                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9418             {
9419                 foreach (var tab in _statuses.Tabs.Values)
9420                 {
9421                     ur += tab.UnreadCount;
9422                     al += tab.AllCount;
9423                 }
9424             }
9425
9426             if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9427             ttl.Append(Application.ProductName);
9428             ttl.Append("  ");
9429             switch (this._cfgCommon.DispLatestPost)
9430             {
9431                 case MyCommon.DispTitleEnum.Ver:
9432                     ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9433                     break;
9434                 case MyCommon.DispTitleEnum.Post:
9435                     if (_history != null && _history.Count > 1)
9436                         ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9437                     break;
9438                 case MyCommon.DispTitleEnum.UnreadRepCount:
9439                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9440                     break;
9441                 case MyCommon.DispTitleEnum.UnreadAllCount:
9442                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9443                     break;
9444                 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9445                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9446                     break;
9447                 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9448                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9449                     break;
9450                 case MyCommon.DispTitleEnum.OwnStatus:
9451                     if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9452                     ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9453                     break;
9454             }
9455
9456             try
9457             {
9458                 this.Text = ttl.ToString();
9459             }
9460             catch (AccessViolationException)
9461             {
9462                 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9463             }
9464         }
9465
9466         private string GetStatusLabelText()
9467         {
9468             //ステータス欄にカウント表示
9469             //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9470             if (_statuses == null) return "";
9471             TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9472             TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9473             if (tbRep == null || tbDm == null) return "";
9474             int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9475             int ur = 0;
9476             int al = 0;
9477             int tur = 0;
9478             int tal = 0;
9479             StringBuilder slbl = new StringBuilder(256);
9480             try
9481             {
9482                 foreach (var tab in _statuses.Tabs.Values)
9483                 {
9484                     ur += tab.UnreadCount;
9485                     al += tab.AllCount;
9486                     if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9487                     {
9488                         tur = tab.UnreadCount;
9489                         tal = tab.AllCount;
9490                     }
9491                 }
9492             }
9493             catch (Exception)
9494             {
9495                 return "";
9496             }
9497
9498             UnreadCounter = ur;
9499             UnreadAtCounter = urat;
9500
9501             slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9502             if (this._cfgCommon.TimelinePeriod == 0)
9503             {
9504                 slbl.Append(Properties.Resources.SetStatusLabelText2);
9505             }
9506             else
9507             {
9508                 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9509             }
9510             return slbl.ToString();
9511         }
9512
9513         private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9514         {
9515             try
9516             {
9517                 if (this.InvokeRequired && !this.IsDisposed)
9518                 {
9519                     this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9520                 }
9521                 else
9522                 {
9523                     var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9524                     SetApiStatusLabel(endpointName);
9525                 }
9526             }
9527             catch (ObjectDisposedException)
9528             {
9529                 return;
9530             }
9531             catch (InvalidOperationException)
9532             {
9533                 return;
9534             }
9535         }
9536
9537         private void SetApiStatusLabel(string endpointName = null)
9538         {
9539             if (_curTab == null)
9540             {
9541                 this.toolStripApiGauge.ApiEndpoint = null;
9542             }
9543             else
9544             {
9545                 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9546
9547                 if (endpointName == null)
9548                 {
9549                     // 表示中のタブに応じて更新
9550                     switch (tabType)
9551                     {
9552                         case MyCommon.TabUsageType.Home:
9553                         case MyCommon.TabUsageType.UserDefined:
9554                             endpointName = "/statuses/home_timeline";
9555                             break;
9556
9557                         case MyCommon.TabUsageType.Mentions:
9558                             endpointName = "/statuses/mentions_timeline";
9559                             break;
9560
9561                         case MyCommon.TabUsageType.Favorites:
9562                             endpointName = "/favorites/list";
9563                             break;
9564
9565                         case MyCommon.TabUsageType.DirectMessage:
9566                             endpointName = "/direct_messages";
9567                             break;
9568
9569                         case MyCommon.TabUsageType.UserTimeline:
9570                             endpointName = "/statuses/user_timeline";
9571                             break;
9572
9573                         case MyCommon.TabUsageType.Lists:
9574                             endpointName = "/lists/statuses";
9575                             break;
9576
9577                         case MyCommon.TabUsageType.PublicSearch:
9578                             endpointName = "/search/tweets";
9579                             break;
9580
9581                         case MyCommon.TabUsageType.Related:
9582                             endpointName = "/statuses/show/:id";
9583                             break;
9584
9585                         default:
9586                             break;
9587                     }
9588
9589                     this.toolStripApiGauge.ApiEndpoint = endpointName;
9590                 }
9591                 else
9592                 {
9593                     // 表示中のタブに関連する endpoint であれば更新
9594                     var update = false;
9595
9596                     switch (endpointName)
9597                     {
9598                         case "/statuses/home_timeline":
9599                             update = tabType == MyCommon.TabUsageType.Home ||
9600                                      tabType == MyCommon.TabUsageType.UserDefined;
9601                             break;
9602
9603                         case "/statuses/mentions_timeline":
9604                             update = tabType == MyCommon.TabUsageType.Mentions;
9605                             break;
9606
9607                         case "/favorites/list":
9608                             update = tabType == MyCommon.TabUsageType.Favorites;
9609                             break;
9610
9611                         case "/direct_messages:":
9612                             update = tabType == MyCommon.TabUsageType.DirectMessage;
9613                             break;
9614
9615                         case "/statuses/user_timeline":
9616                             update = tabType == MyCommon.TabUsageType.UserTimeline;
9617                             break;
9618
9619                         case "/lists/statuses":
9620                             update = tabType == MyCommon.TabUsageType.Lists;
9621                             break;
9622
9623                         case "/search/tweets":
9624                             update = tabType == MyCommon.TabUsageType.PublicSearch;
9625                             break;
9626
9627                         case "/statuses/show/:id":
9628                             update = tabType == MyCommon.TabUsageType.Related;
9629                             break;
9630
9631                         default:
9632                             break;
9633                     }
9634
9635                     if (update)
9636                     {
9637                         this.toolStripApiGauge.ApiEndpoint = endpointName;
9638                     }
9639                 }
9640             }
9641         }
9642
9643         private void SetStatusLabelUrl()
9644         {
9645             StatusLabelUrl.Text = GetStatusLabelText();
9646         }
9647
9648         public void SetStatusLabel(string text)
9649         {
9650             StatusLabel.Text = text;
9651         }
9652
9653         private static StringBuilder ur = new StringBuilder(64);
9654
9655         private void SetNotifyIconText()
9656         {
9657             // タスクトレイアイコンのツールチップテキスト書き換え
9658             // Tween [未読/@]
9659             ur.Remove(0, ur.Length);
9660             if (this._cfgCommon.DispUsername)
9661             {
9662                 ur.Append(tw.Username);
9663                 ur.Append(" - ");
9664             }
9665             ur.Append(Application.ProductName);
9666 #if DEBUG
9667             ur.Append("(Debug Build)");
9668 #endif
9669             if (UnreadCounter != -1 && UnreadAtCounter != -1)
9670             {
9671                 ur.Append(" [");
9672                 ur.Append(UnreadCounter);
9673                 ur.Append("/@");
9674                 ur.Append(UnreadAtCounter);
9675                 ur.Append("]");
9676             }
9677             NotifyIcon1.Text = ur.ToString();
9678         }
9679
9680         internal void CheckReplyTo(string StatusText)
9681         {
9682             MatchCollection m;
9683             //ハッシュタグの保存
9684             m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9685             string hstr = "";
9686             foreach (Match hm in m)
9687             {
9688                 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9689                 {
9690                     hstr += "#" + hm.Result("$3") + " ";
9691                     HashSupl.AddItem("#" + hm.Result("$3"));
9692                 }
9693             }
9694             if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9695             {
9696                 hstr += HashMgr.UseHash;
9697             }
9698             if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9699
9700             // 本当にリプライ先指定すべきかどうかの判定
9701             m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9702
9703             if (this._cfgCommon.UseAtIdSupplement)
9704             {
9705                 int bCnt = AtIdSupl.ItemCount;
9706                 foreach (Match mid in m)
9707                 {
9708                     AtIdSupl.AddItem(mid.Result("${id}"));
9709                 }
9710                 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9711             }
9712
9713             // リプライ先ステータスIDの指定がない場合は指定しない
9714             if (this.inReplyTo == null)
9715                 return;
9716
9717             // 通常Reply
9718             // 次の条件を満たす場合に in_reply_to_status_id 指定
9719             // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9720             // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9721             // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9722
9723             if (m != null)
9724             {
9725                 var inReplyToScreenName = this.inReplyTo.Item2;
9726                 if (StatusText.StartsWith("@"))
9727                 {
9728                     if (StatusText.StartsWith("@" + inReplyToScreenName)) return;
9729                 }
9730                 else
9731                 {
9732                     foreach (Match mid in m)
9733                     {
9734                         if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9735                     }
9736                 }
9737             }
9738
9739             this.inReplyTo = null;
9740         }
9741
9742         private void TweenMain_Resize(object sender, EventArgs e)
9743         {
9744             if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9745             {
9746                 this.Visible = false;
9747             }
9748             if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9749             {
9750                 // 現在の DPI と設定保存時の DPI との比を取得する
9751                 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9752
9753                 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9754                 //_mySize = this.ClientSize;                     //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9755                 this.DesktopLocation = _cfgLocal.FormLocation;
9756                 //_myLoc = this.DesktopLocation;                        //位置保持(最小化・最大化されたまま終了した場合の対応用)
9757
9758                 // Splitterの位置設定
9759                 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9760                 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9761                     splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9762                 {
9763                     this.SplitContainer1.SplitterDistance = splitterDistance;
9764                 }
9765
9766                 //発言欄複数行
9767                 StatusText.Multiline = _cfgLocal.StatusMultiline;
9768                 if (StatusText.Multiline)
9769                 {
9770                     var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9771                     int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9772                     if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9773                     {
9774                         SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9775                     }
9776                     StatusText.Height = statusTextHeight;
9777                 }
9778                 else
9779                 {
9780                     if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9781                     {
9782                         SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9783                     }
9784                 }
9785
9786                 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9787                 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9788                 {
9789                     this.SplitContainer3.SplitterDistance = previewDistance;
9790                 }
9791
9792                 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9793                 this.SplitContainer3.Panel2Collapsed = true;
9794
9795                 _initialLayout = false;
9796             }
9797             if (this.WindowState != FormWindowState.Minimized)
9798             {
9799                 _formWindowState = this.WindowState;
9800             }
9801         }
9802
9803         private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9804         {
9805             PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9806             this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9807             if (PlaySoundMenuItem.Checked)
9808             {
9809                 this._cfgCommon.PlaySound = true;
9810             }
9811             else
9812             {
9813                 this._cfgCommon.PlaySound = false;
9814             }
9815             ModifySettingCommon = true;
9816         }
9817
9818         private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9819         {
9820             if (this._initialLayout)
9821                 return;
9822
9823             int splitterDistance;
9824             switch (this.WindowState)
9825             {
9826                 case FormWindowState.Normal:
9827                     splitterDistance = this.SplitContainer1.SplitterDistance;
9828                     break;
9829                 case FormWindowState.Maximized:
9830                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9831                     var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9832                     splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9833                     splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9834                     break;
9835                 default:
9836                     return;
9837             }
9838
9839             this._mySpDis = splitterDistance;
9840             this.ModifySettingLocal = true;
9841         }
9842
9843         private async Task doRepliedStatusOpen()
9844         {
9845             if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9846             {
9847                 if (MyCommon.IsKeyDown(Keys.Shift))
9848                 {
9849                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9850                     return;
9851                 }
9852                 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9853                 {
9854                     PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9855                     MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9856                 }
9857                 else
9858                 {
9859                     foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9860                     {
9861                         if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9862                         PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9863                         MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9864                         return;
9865                     }
9866                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9867                 }
9868             }
9869         }
9870
9871         private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9872         {
9873             await this.doRepliedStatusOpen();
9874         }
9875
9876         /// <summary>
9877         /// UserPicture.Image に設定されている画像を破棄します。
9878         /// </summary>
9879         private void ClearUserPicture()
9880         {
9881             if (this.UserPicture.Image != null)
9882             {
9883                 var oldImage = this.UserPicture.Image;
9884                 this.UserPicture.Image = null;
9885                 oldImage.Dispose();
9886             }
9887         }
9888
9889         private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9890         {
9891             //発言詳細のアイコン右クリック時のメニュー制御
9892             if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9893             {
9894                 string name = _curPost.ImageUrl;
9895                 if (name != null && name.Length > 0)
9896                 {
9897                     int idx = name.LastIndexOf('/');
9898                     if (idx != -1)
9899                     {
9900                         name = Path.GetFileName(name.Substring(idx));
9901                         if (name.Contains("_normal.") || name.EndsWith("_normal"))
9902                         {
9903                             name = name.Replace("_normal", "");
9904                             this.IconNameToolStripMenuItem.Text = name;
9905                             this.IconNameToolStripMenuItem.Enabled = true;
9906                         }
9907                         else
9908                         {
9909                             this.IconNameToolStripMenuItem.Enabled = false;
9910                             this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9911                         }
9912                     }
9913                     else
9914                     {
9915                         this.IconNameToolStripMenuItem.Enabled = false;
9916                         this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9917                     }
9918
9919                     this.ReloadIconToolStripMenuItem.Enabled = true;
9920
9921                     if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9922                     {
9923                         this.SaveIconPictureToolStripMenuItem.Enabled = true;
9924                     }
9925                     else
9926                     {
9927                         this.SaveIconPictureToolStripMenuItem.Enabled = false;
9928                     }
9929                 }
9930                 else
9931                 {
9932                     this.IconNameToolStripMenuItem.Enabled = false;
9933                     this.ReloadIconToolStripMenuItem.Enabled = false;
9934                     this.SaveIconPictureToolStripMenuItem.Enabled = false;
9935                     this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9936                 }
9937             }
9938             else
9939             {
9940                 this.IconNameToolStripMenuItem.Enabled = false;
9941                 this.ReloadIconToolStripMenuItem.Enabled = false;
9942                 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9943                 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9944             }
9945             if (NameLabel.Tag != null)
9946             {
9947                 string id = (string)NameLabel.Tag;
9948                 if (id == tw.Username)
9949                 {
9950                     FollowToolStripMenuItem.Enabled = false;
9951                     UnFollowToolStripMenuItem.Enabled = false;
9952                     ShowFriendShipToolStripMenuItem.Enabled = false;
9953                     ShowUserStatusToolStripMenuItem.Enabled = true;
9954                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9955                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9956                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9957                 }
9958                 else
9959                 {
9960                     FollowToolStripMenuItem.Enabled = true;
9961                     UnFollowToolStripMenuItem.Enabled = true;
9962                     ShowFriendShipToolStripMenuItem.Enabled = true;
9963                     ShowUserStatusToolStripMenuItem.Enabled = true;
9964                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9965                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9966                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9967                 }
9968             }
9969             else
9970             {
9971                 FollowToolStripMenuItem.Enabled = false;
9972                 UnFollowToolStripMenuItem.Enabled = false;
9973                 ShowFriendShipToolStripMenuItem.Enabled = false;
9974                 ShowUserStatusToolStripMenuItem.Enabled = false;
9975                 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9976                 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9977                 ListManageUserContextToolStripMenuItem3.Enabled = false;
9978             }
9979         }
9980
9981         private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9982         {
9983             if (_curPost == null) return;
9984             string name = _curPost.ImageUrl;
9985             await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9986         }
9987
9988         private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9989         {
9990             if (this._curPost == null) return;
9991
9992             await this.UserPicture.SetImageFromTask(async () =>
9993             {
9994                 var imageUrl = this._curPost.ImageUrl;
9995
9996                 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
9997                     .ConfigureAwait(false);
9998
9999                 return await image.CloneAsync()
10000                     .ConfigureAwait(false);
10001             });
10002         }
10003
10004         private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10005         {
10006             if (_curPost == null) return;
10007             string name = _curPost.ImageUrl;
10008             name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
10009
10010             this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
10011
10012             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10013             {
10014                 // STUB
10015             }
10016         }
10017
10018         private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10019         {
10020             if (_curPost == null) return;
10021             string name = _curPost.ImageUrl;
10022
10023             this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
10024
10025             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10026             {
10027                 try
10028                 {
10029                     using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10030                     {
10031                         using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10032                         {
10033                             using (Graphics g = Graphics.FromImage(bmp2))
10034                             {
10035                                 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10036                                 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10037                             }
10038                             bmp2.Save(this.SaveFileDialog1.FileName);
10039                         }
10040                     }
10041                 }
10042                 catch (Exception)
10043                 {
10044                     //処理中にキャッシュアウトする可能性あり
10045                 }
10046             }
10047         }
10048
10049         private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10050         {
10051             var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10052             if (multiline != this.StatusText.Multiline)
10053             {
10054                 this.StatusText.Multiline = multiline;
10055                 MultiLineMenuItem.Checked = multiline;
10056                 ModifySettingLocal = true;
10057             }
10058         }
10059
10060         private void StatusText_MultilineChanged(object sender, EventArgs e)
10061         {
10062             if (this.StatusText.Multiline)
10063                 this.StatusText.ScrollBars = ScrollBars.Vertical;
10064             else
10065                 this.StatusText.ScrollBars = ScrollBars.None;
10066
10067             ModifySettingLocal = true;
10068         }
10069
10070         private void MultiLineMenuItem_Click(object sender, EventArgs e)
10071         {
10072             //発言欄複数行
10073             StatusText.Multiline = MultiLineMenuItem.Checked;
10074             _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10075             if (MultiLineMenuItem.Checked)
10076             {
10077                 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10078                     SplitContainer2.SplitterDistance = 0;
10079                 else
10080                     SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10081             }
10082             else
10083             {
10084                 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10085             }
10086             ModifySettingLocal = true;
10087         }
10088
10089         private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10090         {
10091             //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10092             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10093
10094             //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10095             //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10096             //Appendix A.  Collected ABNF for URI
10097             //http://www.ietf.org/rfc/rfc3986.txt
10098
10099             string result = "";
10100
10101             const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10102
10103             if (StatusText.SelectionLength > 0)
10104             {
10105                 string tmp = StatusText.SelectedText;
10106                 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10107                 if (tmp.StartsWith("http"))
10108                 {
10109                     // 文字列が選択されている場合はその文字列について処理
10110
10111                     //nico.ms使用、nicovideoにマッチしたら変換
10112                     if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10113                     {
10114                         result = nicoms.Shorten(tmp);
10115                     }
10116                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10117                     {
10118                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10119                         try
10120                         {
10121                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10122                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10123                             result = resultUri.AbsoluteUri;
10124                         }
10125                         catch (WebApiException e)
10126                         {
10127                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10128                             return false;
10129                         }
10130                         catch (UriFormatException e)
10131                         {
10132                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10133                             return false;
10134                         }
10135                     }
10136                     else
10137                     {
10138                         return true;
10139                     }
10140
10141                     if (!string.IsNullOrEmpty(result))
10142                     {
10143                         urlUndo undotmp = new urlUndo();
10144
10145                         StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10146                         StatusText.SelectedText = result;
10147
10148                         //undoバッファにセット
10149                         undotmp.Before = tmp;
10150                         undotmp.After = result;
10151
10152                         if (urlUndoBuffer == null)
10153                         {
10154                             urlUndoBuffer = new List<urlUndo>();
10155                             UrlUndoToolStripMenuItem.Enabled = true;
10156                         }
10157
10158                         urlUndoBuffer.Add(undotmp);
10159                     }
10160                 }
10161             }
10162             else
10163             {
10164                 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10165                                    @"(?<url>(?<protocol>https?://)" +
10166                                    @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10167                                    @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10168                                    @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10169                 // 正規表現にマッチしたURL文字列をtinyurl化
10170                 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10171                 {
10172                     if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10173                     string tmp = mt.Result("${url}");
10174                     if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10175                     urlUndo undotmp = new urlUndo();
10176
10177                     //選んだURLを選択(?)
10178                     StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10179
10180                     //nico.ms使用、nicovideoにマッチしたら変換
10181                     if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10182                     {
10183                         result = nicoms.Shorten(tmp);
10184                     }
10185                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10186                     {
10187                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10188                         try
10189                         {
10190                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10191                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10192                             result = resultUri.AbsoluteUri;
10193                         }
10194                         catch (HttpRequestException e)
10195                         {
10196                             // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10197                             // のように長いので「:」が含まれていればそれ以降のみを抽出する
10198                             var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10199
10200                             this.StatusLabel.Text = Converter_Type + ":" + message;
10201                             continue;
10202                         }
10203                         catch (WebApiException e)
10204                         {
10205                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10206                             continue;
10207                         }
10208                         catch (UriFormatException e)
10209                         {
10210                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10211                             continue;
10212                         }
10213                     }
10214                     else
10215                     {
10216                         continue;
10217                     }
10218
10219                     if (!string.IsNullOrEmpty(result))
10220                     {
10221                         StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10222                         StatusText.SelectedText = result;
10223                         //undoバッファにセット
10224                         undotmp.Before = mt.Result("${url}");
10225                         undotmp.After = result;
10226
10227                         if (urlUndoBuffer == null)
10228                         {
10229                             urlUndoBuffer = new List<urlUndo>();
10230                             UrlUndoToolStripMenuItem.Enabled = true;
10231                         }
10232
10233                         urlUndoBuffer.Add(undotmp);
10234                     }
10235                 }
10236             }
10237
10238             return true;
10239         }
10240
10241         private void doUrlUndo()
10242         {
10243             if (urlUndoBuffer != null)
10244             {
10245                 string tmp = StatusText.Text;
10246                 foreach (urlUndo data in urlUndoBuffer)
10247                 {
10248                     tmp = tmp.Replace(data.After, data.Before);
10249                 }
10250                 StatusText.Text = tmp;
10251                 urlUndoBuffer = null;
10252                 UrlUndoToolStripMenuItem.Enabled = false;
10253                 StatusText.SelectionStart = 0;
10254                 StatusText.SelectionLength = 0;
10255             }
10256         }
10257
10258         private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10259         {
10260             await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10261         }
10262
10263         private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10264         {
10265             await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10266         }
10267
10268         private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10269         {
10270             await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10271         }
10272
10273         private async void UxnuMenuItem_Click(object sender, EventArgs e)
10274         {
10275             await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10276         }
10277
10278         private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10279         {
10280             if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10281             {
10282                 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10283                 Random rnd = new Random();
10284                 // 前回使用した短縮URLサービス以外を選択する
10285                 do
10286                 {
10287                     svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10288                 }
10289                 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10290                 await UrlConvertAsync(svc);
10291             }
10292         }
10293
10294         private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10295         {
10296             doUrlUndo();
10297         }
10298
10299         private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10300         {
10301             this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10302             this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10303             _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10304             ModifySettingCommon = true;
10305         }
10306
10307         private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10308         {
10309             ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10310             this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10311             _cfgCommon.ListLock = ListLockMenuItem.Checked;
10312             ModifySettingCommon = true;
10313         }
10314
10315         private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10316         {
10317             // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10318             MenuStrip1.Tag = new Object();
10319             MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10320         }
10321
10322         private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10323         {
10324             if (this.Tag != null) // 設定された戻り先へ遷移
10325             {
10326                 if (this.Tag == this.ListTab.SelectedTab)
10327                     ((Control)this.ListTab.SelectedTab.Tag).Select();
10328                 else
10329                     ((Control)this.Tag).Select();
10330             }
10331             else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10332             {
10333                 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10334                 {
10335                     this.Tag = ListTab.SelectedTab.Tag;
10336                     ((Control)this.Tag).Select();
10337                 }
10338             }
10339             // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10340             MenuStrip1.Tag = null;
10341         }
10342
10343         private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10344         {
10345             DetailsListView lst = (DetailsListView)sender;
10346             if (_cfgLocal == null) return;
10347
10348             if (_iconCol)
10349             {
10350                 _cfgLocal.Width1 = lst.Columns[0].Width;
10351                 _cfgLocal.Width3 = lst.Columns[1].Width;
10352             }
10353             else
10354             {
10355                 int[] darr = new int[lst.Columns.Count];
10356                 for (int i = 0; i < lst.Columns.Count; i++)
10357                 {
10358                     darr[lst.Columns[i].DisplayIndex] = i;
10359                 }
10360                 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10361
10362                 for (int i = 0; i < lst.Columns.Count; i++)
10363                 {
10364                     switch (darr[i])
10365                     {
10366                         case 0:
10367                             _cfgLocal.DisplayIndex1 = i;
10368                             break;
10369                         case 1:
10370                             _cfgLocal.DisplayIndex2 = i;
10371                             break;
10372                         case 2:
10373                             _cfgLocal.DisplayIndex3 = i;
10374                             break;
10375                         case 3:
10376                             _cfgLocal.DisplayIndex4 = i;
10377                             break;
10378                         case 4:
10379                             _cfgLocal.DisplayIndex5 = i;
10380                             break;
10381                         case 5:
10382                             _cfgLocal.DisplayIndex6 = i;
10383                             break;
10384                         case 6:
10385                             _cfgLocal.DisplayIndex7 = i;
10386                             break;
10387                         case 7:
10388                             _cfgLocal.DisplayIndex8 = i;
10389                             break;
10390                     }
10391                 }
10392                 _cfgLocal.Width1 = lst.Columns[0].Width;
10393                 _cfgLocal.Width2 = lst.Columns[1].Width;
10394                 _cfgLocal.Width3 = lst.Columns[2].Width;
10395                 _cfgLocal.Width4 = lst.Columns[3].Width;
10396                 _cfgLocal.Width5 = lst.Columns[4].Width;
10397                 _cfgLocal.Width6 = lst.Columns[5].Width;
10398                 _cfgLocal.Width7 = lst.Columns[6].Width;
10399                 _cfgLocal.Width8 = lst.Columns[7].Width;
10400             }
10401             ModifySettingLocal = true;
10402             _isColumnChanged = true;
10403         }
10404
10405         private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10406         {
10407             DetailsListView lst = (DetailsListView)sender;
10408             if (_cfgLocal == null) return;
10409             if (_iconCol)
10410             {
10411                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10412                 {
10413                     _cfgLocal.Width1 = lst.Columns[0].Width;
10414                     ModifySettingLocal = true;
10415                     _isColumnChanged = true;
10416                 }
10417                 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10418                 {
10419                     _cfgLocal.Width3 = lst.Columns[1].Width;
10420                     ModifySettingLocal = true;
10421                     _isColumnChanged = true;
10422                 }
10423             }
10424             else
10425             {
10426                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10427                 {
10428                     _cfgLocal.Width1 = lst.Columns[0].Width;
10429                     ModifySettingLocal = true;
10430                     _isColumnChanged = true;
10431                 }
10432                 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10433                 {
10434                     _cfgLocal.Width2 = lst.Columns[1].Width;
10435                     ModifySettingLocal = true;
10436                     _isColumnChanged = true;
10437                 }
10438                 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10439                 {
10440                     _cfgLocal.Width3 = lst.Columns[2].Width;
10441                     ModifySettingLocal = true;
10442                     _isColumnChanged = true;
10443                 }
10444                 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10445                 {
10446                     _cfgLocal.Width4 = lst.Columns[3].Width;
10447                     ModifySettingLocal = true;
10448                     _isColumnChanged = true;
10449                 }
10450                 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10451                 {
10452                     _cfgLocal.Width5 = lst.Columns[4].Width;
10453                     ModifySettingLocal = true;
10454                     _isColumnChanged = true;
10455                 }
10456                 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10457                 {
10458                     _cfgLocal.Width6 = lst.Columns[5].Width;
10459                     ModifySettingLocal = true;
10460                     _isColumnChanged = true;
10461                 }
10462                 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10463                 {
10464                     _cfgLocal.Width7 = lst.Columns[6].Width;
10465                     ModifySettingLocal = true;
10466                     _isColumnChanged = true;
10467                 }
10468                 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10469                 {
10470                     _cfgLocal.Width8 = lst.Columns[7].Width;
10471                     ModifySettingLocal = true;
10472                     _isColumnChanged = true;
10473                 }
10474             }
10475             // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10476             //if (changed)
10477             //{
10478             //    SaveConfigsLocal();
10479             //}
10480         }
10481
10482         private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10483         {
10484             //発言詳細で「選択文字列をコピー」
10485             string _selText = this.PostBrowser.GetSelectedText();
10486             try
10487             {
10488                 Clipboard.SetDataObject(_selText, false, 5, 100);
10489             }
10490             catch (Exception ex)
10491             {
10492                 MessageBox.Show(ex.Message);
10493             }
10494         }
10495
10496         private async Task doSearchToolStrip(string url)
10497         {
10498             //発言詳細で「選択文字列で検索」(選択文字列取得)
10499             string _selText = this.PostBrowser.GetSelectedText();
10500
10501             if (_selText != null)
10502             {
10503                 if (url == Properties.Resources.SearchItem4Url)
10504                 {
10505                     //公式検索
10506                     AddNewTabForSearch(_selText);
10507                     return;
10508                 }
10509
10510                 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10511                 await this.OpenUriInBrowserAsync(tmp);
10512             }
10513         }
10514
10515         private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10516         {
10517             //発言詳細ですべて選択
10518             PostBrowser.Document.ExecCommand("SelectAll", false, null);
10519         }
10520
10521         private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10522         {
10523             await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10524         }
10525
10526         private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10527         {
10528             await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10529         }
10530
10531         private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10532         {
10533             await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10534         }
10535
10536         private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10537         {
10538             try
10539             {
10540                 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
10541                 {
10542                     if (link.GetAttribute("href") == this._postBrowserStatusText)
10543                     {
10544                         Clipboard.SetDataObject(link.GetAttribute("title"), false, 5, 100);
10545                         return;
10546                     }
10547                 }
10548
10549                 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10550             }
10551             catch (Exception ex)
10552             {
10553                 MessageBox.Show(ex.Message);
10554             }
10555         }
10556
10557         private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10558         {
10559             // URLコピーの項目の表示/非表示
10560             if (PostBrowser.StatusText.StartsWith("http"))
10561             {
10562                 this._postBrowserStatusText = PostBrowser.StatusText;
10563                 string name = GetUserId();
10564                 UrlCopyContextMenuItem.Enabled = true;
10565                 if (name != null)
10566                 {
10567                     FollowContextMenuItem.Enabled = true;
10568                     RemoveContextMenuItem.Enabled = true;
10569                     FriendshipContextMenuItem.Enabled = true;
10570                     ShowUserStatusContextMenuItem.Enabled = true;
10571                     SearchPostsDetailToolStripMenuItem.Enabled = true;
10572                     IdFilterAddMenuItem.Enabled = true;
10573                     ListManageUserContextToolStripMenuItem.Enabled = true;
10574                     SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10575                 }
10576                 else
10577                 {
10578                     FollowContextMenuItem.Enabled = false;
10579                     RemoveContextMenuItem.Enabled = false;
10580                     FriendshipContextMenuItem.Enabled = false;
10581                     ShowUserStatusContextMenuItem.Enabled = false;
10582                     SearchPostsDetailToolStripMenuItem.Enabled = false;
10583                     IdFilterAddMenuItem.Enabled = false;
10584                     ListManageUserContextToolStripMenuItem.Enabled = false;
10585                     SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10586                 }
10587
10588                 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10589                     UseHashtagMenuItem.Enabled = true;
10590                 else
10591                     UseHashtagMenuItem.Enabled = false;
10592             }
10593             else
10594             {
10595                 this._postBrowserStatusText = "";
10596                 UrlCopyContextMenuItem.Enabled = false;
10597                 FollowContextMenuItem.Enabled = false;
10598                 RemoveContextMenuItem.Enabled = false;
10599                 FriendshipContextMenuItem.Enabled = false;
10600                 ShowUserStatusContextMenuItem.Enabled = false;
10601                 SearchPostsDetailToolStripMenuItem.Enabled = false;
10602                 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10603                 UseHashtagMenuItem.Enabled = false;
10604                 IdFilterAddMenuItem.Enabled = false;
10605                 ListManageUserContextToolStripMenuItem.Enabled = false;
10606             }
10607             // 文字列選択されていないときは選択文字列関係の項目を非表示に
10608             string _selText = this.PostBrowser.GetSelectedText();
10609             if (_selText == null)
10610             {
10611                 SelectionSearchContextMenuItem.Enabled = false;
10612                 SelectionCopyContextMenuItem.Enabled = false;
10613                 SelectionTranslationToolStripMenuItem.Enabled = false;
10614             }
10615             else
10616             {
10617                 SelectionSearchContextMenuItem.Enabled = true;
10618                 SelectionCopyContextMenuItem.Enabled = true;
10619                 SelectionTranslationToolStripMenuItem.Enabled = true;
10620             }
10621             //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10622             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10623             bool fAllFlag = false;
10624             foreach (Match mu in ma)
10625             {
10626                 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
10627                 {
10628                     fAllFlag = true;
10629                     break;
10630                 }
10631             }
10632             this.FriendshipAllMenuItem.Enabled = fAllFlag;
10633
10634             if (_curPost == null)
10635                 TranslationToolStripMenuItem.Enabled = false;
10636             else
10637                 TranslationToolStripMenuItem.Enabled = true;
10638
10639             e.Cancel = false;
10640         }
10641
10642         private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10643         {
10644             //発言詳細の選択文字列で現在のタブを検索
10645             string _selText = this.PostBrowser.GetSelectedText();
10646
10647             if (_selText != null)
10648             {
10649                 var searchOptions = new SearchWordDialog.SearchOptions(
10650                     SearchWordDialog.SearchType.Timeline,
10651                     _selText,
10652                     newTab: false,
10653                     caseSensitive: false,
10654                     useRegex: false);
10655
10656                 this.SearchDialog.ResultOptions = searchOptions;
10657
10658                 this.DoTabSearch(
10659                     searchOptions.Query,
10660                     searchOptions.CaseSensitive,
10661                     searchOptions.UseRegex,
10662                     SEARCHTYPE.NextSearch);
10663             }
10664         }
10665
10666         private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10667         {
10668             if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10669             ModifySettingLocal = true;
10670         }
10671
10672         private void TweenMain_DragDrop(object sender, DragEventArgs e)
10673         {
10674             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10675             {
10676                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10677                 {
10678                     SelectMedia_DragDrop(e);
10679                 }
10680             }
10681             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10682             {
10683                 var url = GetUrlFromDataObject(e.Data);
10684
10685                 string appendText;
10686                 if (url.Item2 == null)
10687                     appendText = url.Item1;
10688                 else
10689                     appendText = url.Item2 + " " + url.Item1;
10690
10691                 if (this.StatusText.TextLength == 0)
10692                     this.StatusText.Text = appendText;
10693                 else
10694                     this.StatusText.Text += " " + appendText;
10695             }
10696             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10697             {
10698                 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10699                 if (text != null)
10700                     this.StatusText.Text += text;
10701             }
10702             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10703             {
10704                 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10705                 if (data != null) StatusText.Text += data;
10706             }
10707         }
10708
10709         /// <summary>
10710         /// IDataObject から URL とタイトルの対を取得します
10711         /// </summary>
10712         /// <remarks>
10713         /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10714         /// </remarks>
10715         /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10716         /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10717         internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10718         {
10719             if (data.GetDataPresent("text/x-moz-url"))
10720             {
10721                 // Firefox, Google Chrome で利用可能
10722                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10723
10724                 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10725                 {
10726                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10727                     if (lines.Length < 2)
10728                         throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10729
10730                     return new Tuple<string, string>(lines[0], lines[1]);
10731                 }
10732             }
10733             else if (data.GetDataPresent("IESiteModeToUrl"))
10734             {
10735                 // Internet Exproler 用
10736                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10737
10738                 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10739                 {
10740                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10741                     if (lines.Length < 2)
10742                         throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10743
10744                     return new Tuple<string, string>(lines[0], lines[1]);
10745                 }
10746             }
10747             else if (data.GetDataPresent("UniformResourceLocatorW"))
10748             {
10749                 // それ以外のブラウザ向け
10750
10751                 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10752                 {
10753                     var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10754                     return new Tuple<string, string>(url, null);
10755                 }
10756             }
10757
10758             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10759         }
10760
10761         private void TweenMain_DragEnter(object sender, DragEventArgs e)
10762         {
10763             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10764             {
10765                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10766                 {
10767                     SelectMedia_DragEnter(e);
10768                     return;
10769                 }
10770             }
10771             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10772             {
10773                 e.Effect = DragDropEffects.Copy;
10774                 return;
10775             }
10776             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10777             {
10778                 e.Effect = DragDropEffects.Copy;
10779                 return;
10780             }
10781             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10782             {
10783                 e.Effect = DragDropEffects.Copy;
10784                 return;
10785             }
10786
10787             e.Effect = DragDropEffects.None;
10788         }
10789
10790         private void TweenMain_DragOver(object sender, DragEventArgs e)
10791         {
10792         }
10793
10794         public bool IsNetworkAvailable()
10795         {
10796             bool nw = true;
10797             nw = MyCommon.IsNetworkAvailable();
10798             _myStatusOnline = nw;
10799             return nw;
10800         }
10801
10802         public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10803         {
10804             var uriStr = uri.AbsoluteUri;
10805
10806             // OpenTween 内部で使用する URL
10807             if (uri.Authority == "opentween")
10808             {
10809                 await this.OpenInternalUriAsync(uri);
10810                 return;
10811             }
10812
10813             // ハッシュタグを含む Twitter 検索
10814             if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10815             {
10816                 // ハッシュタグの場合は、タブで開く
10817                 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10818                 var pos = unescapedQuery.IndexOf('#');
10819                 if (pos == -1) return;
10820
10821                 var hash = unescapedQuery.Substring(pos);
10822                 this.HashSupl.AddItem(hash);
10823                 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10824                 this.AddNewTabForSearch(hash);
10825                 return;
10826             }
10827
10828             // ユーザープロフィールURL
10829             // フラグが立っている場合は設定と逆の動作をする
10830             if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10831                 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10832             {
10833                 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10834                 if (userUriMatch.Success)
10835                 {
10836                     var screenName = userUriMatch.Groups["ScreenName"].Value;
10837                     if (this.IsTwitterId(screenName))
10838                     {
10839                         this.AddNewTabForUserTimeline(screenName);
10840                         return;
10841                     }
10842                 }
10843             }
10844
10845             // どのパターンにも該当しないURL
10846             await this.OpenUriInBrowserAsync(uriStr);
10847         }
10848
10849         /// <summary>
10850         /// OpenTween 内部の機能を呼び出すための URL を開きます
10851         /// </summary>
10852         private async Task OpenInternalUriAsync(Uri uri)
10853         {
10854             // ツイートを開く (//opentween/status/:status_id)
10855             var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10856             if (match.Success)
10857             {
10858                 var statusId = long.Parse(match.Groups[1].Value);
10859                 await this.OpenRelatedTab(statusId);
10860                 return;
10861             }
10862         }
10863
10864         public Task OpenUriInBrowserAsync(string UriString)
10865         {
10866             return Task.Run(() =>
10867             {
10868                 string myPath = UriString;
10869
10870                 try
10871                 {
10872                     var configBrowserPath = this._cfgLocal.BrowserPath;
10873                     if (!string.IsNullOrEmpty(configBrowserPath))
10874                     {
10875                         if (configBrowserPath.StartsWith("\"") && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2) > -1)
10876                         {
10877                             int sep = configBrowserPath.IndexOf("\"", 2);
10878                             string browserPath = configBrowserPath.Substring(1, sep - 1);
10879                             string arg = "";
10880                             if (sep < configBrowserPath.Length - 1)
10881                             {
10882                                 arg = configBrowserPath.Substring(sep + 1);
10883                             }
10884                             myPath = arg + " " + myPath;
10885                             System.Diagnostics.Process.Start(browserPath, myPath);
10886                         }
10887                         else
10888                         {
10889                             System.Diagnostics.Process.Start(configBrowserPath, myPath);
10890                         }
10891                     }
10892                     else
10893                     {
10894                         System.Diagnostics.Process.Start(myPath);
10895                     }
10896                 }
10897                 catch (Exception)
10898                 {
10899                     //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10900                 }
10901             });
10902         }
10903
10904         private void ListTabSelect(TabPage _tab)
10905         {
10906             SetListProperty();
10907
10908             this.PurgeListViewItemCache();
10909
10910             _curTab = _tab;
10911             _curList = (DetailsListView)_tab.Tag;
10912             if (_curList.SelectedIndices.Count > 0)
10913             {
10914                 _curItemIndex = _curList.SelectedIndices[0];
10915                 _curPost = GetCurTabPost(_curItemIndex);
10916             }
10917             else
10918             {
10919                 _curItemIndex = -1;
10920                 _curPost = null;
10921             }
10922
10923             _anchorPost = null;
10924             _anchorFlag = false;
10925
10926             if (_iconCol)
10927             {
10928                 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10929             }
10930             else
10931             {
10932                 for (int i = 0; i < _curList.Columns.Count; i++)
10933                 {
10934                     ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10935                 }
10936             }
10937         }
10938
10939         private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10940         {
10941             ListTabSelect(e.TabPage);
10942         }
10943
10944         private void SelectListItem(DetailsListView LView, int Index)
10945         {
10946             //単一
10947             Rectangle bnd = new Rectangle();
10948             bool flg = false;
10949             var item = LView.FocusedItem;
10950             if (item != null)
10951             {
10952                 bnd = item.Bounds;
10953                 flg = true;
10954             }
10955
10956             do
10957             {
10958                 LView.SelectedIndices.Clear();
10959             }
10960             while (LView.SelectedIndices.Count > 0);
10961             item = LView.Items[Index];
10962             item.Selected = true;
10963             item.Focused = true;
10964
10965             if (flg) LView.Invalidate(bnd);
10966         }
10967
10968         private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10969         {
10970             //複数
10971             Rectangle bnd = new Rectangle();
10972             bool flg = false;
10973             var item = LView.FocusedItem;
10974             if (item != null)
10975             {
10976                 bnd = item.Bounds;
10977                 flg = true;
10978             }
10979
10980             if (Index != null)
10981             {
10982                 do
10983                 {
10984                     LView.SelectedIndices.Clear();
10985                 }
10986                 while (LView.SelectedIndices.Count > 0);
10987                 LView.SelectItems(Index);
10988             }
10989             if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
10990             {
10991                 LView.SelectionMark = selectionMarkIndex;
10992             }
10993             if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
10994             {
10995                 LView.Items[focusedIndex].Focused = true;
10996             }
10997             else if (Index != null && Index.Length != 0)
10998             {
10999                 LView.Items[Index.Last()].Focused = true;
11000             }
11001
11002             if (flg) LView.Invalidate(bnd);
11003         }
11004
11005         private void StartUserStream()
11006         {
11007             tw.NewPostFromStream += tw_NewPostFromStream;
11008             tw.UserStreamStarted += tw_UserStreamStarted;
11009             tw.UserStreamStopped += tw_UserStreamStopped;
11010             tw.PostDeleted += tw_PostDeleted;
11011             tw.UserStreamEventReceived += tw_UserStreamEventArrived;
11012
11013             MenuItemUserStream.Text = "&UserStream ■";
11014             MenuItemUserStream.Enabled = true;
11015             StopToolStripMenuItem.Text = "&Start";
11016             StopToolStripMenuItem.Enabled = true;
11017             if (this._cfgCommon.UserstreamStartup) tw.StartUserStream();
11018         }
11019
11020         private async void TweenMain_Shown(object sender, EventArgs e)
11021         {
11022             try
11023             {
11024                 using (ControlTransaction.Update(this.PostBrowser))
11025                 {
11026                     PostBrowser.Url = new Uri("about:blank");
11027                     PostBrowser.DocumentText = "";       //発言詳細部初期化
11028                 }
11029             }
11030             catch (Exception)
11031             {
11032             }
11033
11034             NotifyIcon1.Visible = true;
11035
11036             if (this.IsNetworkAvailable())
11037             {
11038                 StartUserStream();
11039
11040                 var loadTasks = new List<Task>
11041                 {
11042                     this.RefreshMuteUserIdsAsync(),
11043                     this.RefreshBlockIdsAsync(),
11044                     this.RefreshNoRetweetIdsAsync(),
11045                     this.RefreshTwitterConfigurationAsync(),
11046                     this.GetHomeTimelineAsync(),
11047                     this.GetReplyAsync(),
11048                     this.GetDirectMessagesAsync(),
11049                     this.GetPublicSearchAllAsync(),
11050                     this.GetUserTimelineAllAsync(),
11051                     this.GetListTimelineAllAsync(),
11052                 };
11053
11054                 if (this._cfgCommon.StartupFollowers)
11055                     loadTasks.Add(this.RefreshFollowerIdsAsync());
11056
11057                 if (this._cfgCommon.GetFav)
11058                     loadTasks.Add(this.GetFavoritesAsync());
11059
11060                 var allTasks = Task.WhenAll(loadTasks);
11061
11062                 var i = 0;
11063                 while (true)
11064                 {
11065                     var timeout = Task.Delay(5000);
11066                     if (await Task.WhenAny(allTasks, timeout) != timeout)
11067                         break;
11068
11069                     i += 1;
11070                     if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11071
11072                     if (MyCommon._endingFlag)
11073                         return;
11074                 }
11075
11076                 if (MyCommon._endingFlag) return;
11077
11078                 if (ApplicationSettings.VersionInfoUrl != null)
11079                 {
11080                     //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11081                     if (this._cfgCommon.StartupVersion)
11082                         await this.CheckNewVersion(true);
11083                 }
11084                 else
11085                 {
11086                     // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11087                     this.VerUpMenuItem.Enabled = false;
11088                     this.VerUpMenuItem.Available = false;
11089                     this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11090                 }
11091
11092                 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11093                 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11094                 {
11095                     MessageBox.Show(Properties.Resources.ReAuthorizeText);
11096                     SettingStripMenuItem_Click(null, null);
11097                 }
11098
11099                 // 取得失敗の場合は再試行する
11100                 var reloadTasks = new List<Task>();
11101
11102                 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11103                     reloadTasks.Add(this.RefreshFollowerIdsAsync());
11104
11105                 if (!tw.GetNoRetweetSuccess)
11106                     reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11107
11108                 if (this.tw.Configuration.PhotoSizeLimit == 0)
11109                     reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11110
11111                 await Task.WhenAll(reloadTasks);
11112             }
11113
11114             _initial = false;
11115
11116             TimerTimeline.Enabled = true;
11117         }
11118
11119         private async Task doGetFollowersMenu()
11120         {
11121             await this.RefreshFollowerIdsAsync();
11122             await this.DispSelectedPost(true);
11123         }
11124
11125         private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11126         {
11127             await this.doGetFollowersMenu();
11128         }
11129
11130         private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
11131         {
11132             doReTweetUnofficial();
11133         }
11134
11135         private async Task doReTweetOfficial(bool isConfirm)
11136         {
11137             //公式RT
11138             if (this.ExistCurrentPost)
11139             {
11140                 if (_curPost.IsProtect)
11141                 {
11142                     MessageBox.Show("Protected.");
11143                     _DoFavRetweetFlags = false;
11144                     return;
11145                 }
11146                 if (_curList.SelectedIndices.Count > 15)
11147                 {
11148                     MessageBox.Show(Properties.Resources.RetweetLimitText);
11149                     _DoFavRetweetFlags = false;
11150                     return;
11151                 }
11152                 else if (_curList.SelectedIndices.Count > 1)
11153                 {
11154                     string QuestionText = Properties.Resources.RetweetQuestion2;
11155                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11156                     switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11157                     {
11158                         case DialogResult.Cancel:
11159                         case DialogResult.No:
11160                             _DoFavRetweetFlags = false;
11161                             return;
11162                     }
11163                 }
11164                 else
11165                 {
11166                     if (_curPost.IsDm || _curPost.IsMe)
11167                     {
11168                         _DoFavRetweetFlags = false;
11169                         return;
11170                     }
11171                     if (!this._cfgCommon.RetweetNoConfirm)
11172                     {
11173                         string Questiontext = Properties.Resources.RetweetQuestion1;
11174                         if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11175                         if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11176                         {
11177                             _DoFavRetweetFlags = false;
11178                             return;
11179                         }
11180                     }
11181                 }
11182
11183                 var statusIds = new List<long>();
11184                 foreach (int idx in _curList.SelectedIndices)
11185                 {
11186                     PostClass post = GetCurTabPost(idx);
11187                     if (!post.IsMe && !post.IsProtect && !post.IsDm)
11188                         statusIds.Add(post.StatusId);
11189                 }
11190
11191                 await this.RetweetAsync(statusIds);
11192             }
11193         }
11194
11195         private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11196         {
11197             await this.doReTweetOfficial(true);
11198         }
11199
11200         private async Task FavoritesRetweetOfficial()
11201         {
11202             if (!this.ExistCurrentPost) return;
11203             _DoFavRetweetFlags = true;
11204             var retweetTask = this.doReTweetOfficial(true);
11205             if (_DoFavRetweetFlags)
11206             {
11207                 _DoFavRetweetFlags = false;
11208                 var favoriteTask = this.FavoriteChange(true, false);
11209
11210                 await Task.WhenAll(retweetTask, favoriteTask);
11211             }
11212             else
11213             {
11214                 await retweetTask;
11215             }
11216         }
11217
11218         private async Task FavoritesRetweetUnofficial()
11219         {
11220             if (this.ExistCurrentPost && !_curPost.IsDm)
11221             {
11222                 _DoFavRetweetFlags = true;
11223                 var favoriteTask = this.FavoriteChange(true);
11224                 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11225                 {
11226                     _DoFavRetweetFlags = false;
11227                     doReTweetUnofficial();
11228                 }
11229
11230                 await favoriteTask;
11231             }
11232         }
11233
11234         /// <summary>
11235         /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11236         /// </summary>
11237         /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11238         /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11239         /// <returns>復元されたツイート本文</returns>
11240         internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11241         {
11242             // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11243
11244             // 通常の URL
11245             statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11246             // メンション
11247             statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11248             // ハッシュタグ
11249             statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11250
11251             // <br> 除去
11252             if (multiline)
11253                 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11254             else
11255                 statusHtml = statusHtml.Replace("<br>", " ");
11256
11257             // &nbsp; は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11258             // 現状では半角スペースの代用として &nbsp; を使用しているため U+0020 に置換します
11259             statusHtml = statusHtml.Replace("&nbsp;", " ");
11260
11261             return WebUtility.HtmlDecode(statusHtml);
11262         }
11263
11264         private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11265         {
11266             if (_curPost != null)
11267                 await this.DispSelectedPost(true);
11268         }
11269
11270         private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11271         {
11272             if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11273                 DebugModeToolStripMenuItem.Visible = true;
11274             else
11275                 DebugModeToolStripMenuItem.Visible = false;
11276         }
11277
11278         private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11279         {
11280             this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11281         }
11282
11283         private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11284         {
11285             ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11286         }
11287
11288         private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11289         {
11290             if (TraceOutToolStripMenuItem.Checked)
11291                 MyCommon.TraceFlag = true;
11292             else
11293                 MyCommon.TraceFlag = false;
11294         }
11295
11296         private void TweenMain_Deactivate(object sender, EventArgs e)
11297         {
11298             //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11299             this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11300         }
11301
11302         private void TabRenameMenuItem_Click(object sender, EventArgs e)
11303         {
11304             if (string.IsNullOrEmpty(_rclickTabName)) return;
11305             TabRename(ref _rclickTabName);
11306         }
11307
11308         private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11309         {
11310             await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11311         }
11312
11313         private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11314         {
11315             await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11316         }
11317
11318         private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11319         {
11320             TwitterApiStatus apiStatus;
11321
11322             using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
11323             {
11324                 var cancellationToken = dialog.EnableCancellation();
11325
11326                 try
11327                 {
11328                     var task = Task.Run(() => this.tw.GetInfoApi());
11329                     apiStatus = await dialog.WaitForAsync(this, task);
11330                 }
11331                 catch (WebApiException)
11332                 {
11333                     apiStatus = null;
11334                 }
11335
11336                 if (cancellationToken.IsCancellationRequested)
11337                     return;
11338
11339                 if (apiStatus == null)
11340                 {
11341                     MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11342                     return;
11343                 }
11344             }
11345
11346             using (var apiDlg = new ApiInfoDialog())
11347             {
11348                 apiDlg.ShowDialog(this);
11349             }
11350         }
11351
11352         private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
11353         {
11354             var id = _curPost?.ScreenName ?? "";
11355
11356             await this.FollowCommand(id);
11357         }
11358
11359         private async Task FollowCommand(string id)
11360         {
11361             using (var inputName = new InputTabName())
11362             {
11363                 inputName.FormTitle = "Follow";
11364                 inputName.FormDescription = Properties.Resources.FRMessage1;
11365                 inputName.TabName = id;
11366
11367                 if (inputName.ShowDialog(this) != DialogResult.OK)
11368                     return;
11369                 if (string.IsNullOrWhiteSpace(inputName.TabName))
11370                     return;
11371
11372                 id = inputName.TabName.Trim();
11373             }
11374
11375             using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11376             {
11377                 try
11378                 {
11379                     var task = Task.Run(() => this.tw.PostFollowCommand(id));
11380                     await dialog.WaitForAsync(this, task);
11381                 }
11382                 catch (WebApiException ex)
11383                 {
11384                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11385                     return;
11386                 }
11387             }
11388
11389             MessageBox.Show(Properties.Resources.FRMessage3);
11390         }
11391
11392         private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11393         {
11394             var id = _curPost?.ScreenName ?? "";
11395
11396             await this.RemoveCommand(id, false);
11397         }
11398
11399         private async Task RemoveCommand(string id, bool skipInput)
11400         {
11401             if (!skipInput)
11402             {
11403                 using (var inputName = new InputTabName())
11404                 {
11405                     inputName.FormTitle = "Unfollow";
11406                     inputName.FormDescription = Properties.Resources.FRMessage1;
11407                     inputName.TabName = id;
11408
11409                     if (inputName.ShowDialog(this) != DialogResult.OK)
11410                         return;
11411                     if (string.IsNullOrWhiteSpace(inputName.TabName))
11412                         return;
11413
11414                     id = inputName.TabName.Trim();
11415                 }
11416             }
11417
11418             using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11419             {
11420                 try
11421                 {
11422                     var task = Task.Run(() => this.tw.PostRemoveCommand(id));
11423                     await dialog.WaitForAsync(this, task);
11424                 }
11425                 catch (WebApiException ex)
11426                 {
11427                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11428                     return;
11429                 }
11430             }
11431
11432             MessageBox.Show(Properties.Resources.FRMessage3);
11433         }
11434
11435         private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11436         {
11437             var id = _curPost?.ScreenName ?? "";
11438
11439             await this.ShowFriendship(id);
11440         }
11441
11442         private async Task ShowFriendship(string id)
11443         {
11444             using (var inputName = new InputTabName())
11445             {
11446                 inputName.FormTitle = "Show Friendships";
11447                 inputName.FormDescription = Properties.Resources.FRMessage1;
11448                 inputName.TabName = id;
11449
11450                 if (inputName.ShowDialog(this) != DialogResult.OK)
11451                     return;
11452                 if (string.IsNullOrWhiteSpace(inputName.TabName))
11453                     return;
11454
11455                 id = inputName.TabName.Trim();
11456             }
11457
11458             bool isFollowing, isFollowed;
11459
11460             using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11461             {
11462                 var cancellationToken = dialog.EnableCancellation();
11463
11464                 try
11465                 {
11466                     var task = Task.Run(() => this.tw.GetFriendshipInfo(id));
11467                     var friendship = await dialog.WaitForAsync(this, task);
11468
11469                     isFollowing = friendship.Relationship.Source.Following;
11470                     isFollowed = friendship.Relationship.Source.FollowedBy;
11471                 }
11472                 catch (WebApiException ex)
11473                 {
11474                     if (!cancellationToken.IsCancellationRequested)
11475                         MessageBox.Show(ex.Message);
11476                     return;
11477                 }
11478
11479                 if (cancellationToken.IsCancellationRequested)
11480                     return;
11481             }
11482
11483             string result = "";
11484             if (isFollowing)
11485             {
11486                 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11487             }
11488             else
11489             {
11490                 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11491             }
11492             if (isFollowed)
11493             {
11494                 result += Properties.Resources.GetFriendshipInfo3;
11495             }
11496             else
11497             {
11498                 result += Properties.Resources.GetFriendshipInfo4;
11499             }
11500             result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11501             MessageBox.Show(result);
11502         }
11503
11504         private async Task ShowFriendship(string[] ids)
11505         {
11506             foreach (string id in ids)
11507             {
11508                 bool isFollowing, isFollowed;
11509
11510                 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11511                 {
11512                     var cancellationToken = dialog.EnableCancellation();
11513
11514                     try
11515                     {
11516                         var task = Task.Run(() => this.tw.GetFriendshipInfo(id));
11517                         var friendship = await dialog.WaitForAsync(this, task);
11518
11519                         isFollowing = friendship.Relationship.Source.Following;
11520                         isFollowed = friendship.Relationship.Source.FollowedBy;
11521                     }
11522                     catch (WebApiException ex)
11523                     {
11524                         if (!cancellationToken.IsCancellationRequested)
11525                             MessageBox.Show(ex.Message);
11526                         return;
11527                     }
11528
11529                     if (cancellationToken.IsCancellationRequested)
11530                         return;
11531                 }
11532
11533                 string result = "";
11534                 string ff = "";
11535
11536                 ff = "  ";
11537                 if (isFollowing)
11538                 {
11539                     ff += Properties.Resources.GetFriendshipInfo1;
11540                 }
11541                 else
11542                 {
11543                     ff += Properties.Resources.GetFriendshipInfo2;
11544                 }
11545
11546                 ff += System.Environment.NewLine + "  ";
11547                 if (isFollowed)
11548                 {
11549                     ff += Properties.Resources.GetFriendshipInfo3;
11550                 }
11551                 else
11552                 {
11553                     ff += Properties.Resources.GetFriendshipInfo4;
11554                 }
11555                 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11556                 if (isFollowing)
11557                 {
11558                     if (MessageBox.Show(
11559                         Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11560                         MessageBoxButtons.YesNo,
11561                         MessageBoxIcon.Question,
11562                         MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11563                     {
11564                         await this.RemoveCommand(id, true);
11565                     }
11566                 }
11567                 else
11568                 {
11569                     MessageBox.Show(result);
11570                 }
11571             }
11572         }
11573
11574         private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11575         {
11576             await this.doShowUserStatus(tw.Username, false);
11577             //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11578             //{
11579             //    doShowUserStatus(tw.Username, false);
11580             //}
11581             //else
11582             //{
11583             //    MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11584             //    return;
11585             //}
11586         }
11587
11588         // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11589         // URLから切り出した文字列を渡す
11590
11591         public bool IsTwitterId(string name)
11592         {
11593             if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11594                 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11595             else
11596                 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLower());
11597         }
11598
11599         private string GetUserId()
11600         {
11601             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11602             if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11603                 return m.Result("${ScreenName}");
11604             else
11605                 return null;
11606         }
11607
11608         private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11609         {
11610             string name = GetUserId();
11611             if (name != null)
11612                 await this.FollowCommand(name);
11613         }
11614
11615         private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11616         {
11617             string name = GetUserId();
11618             if (name != null)
11619                 await this.RemoveCommand(name, false);
11620         }
11621
11622         private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11623         {
11624             string name = GetUserId();
11625             if (name != null)
11626                 await this.ShowFriendship(name);
11627         }
11628
11629         private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11630         {
11631             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11632             List<string> ids = new List<string>();
11633             foreach (Match mu in ma)
11634             {
11635                 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11636                 {
11637                     ids.Add(mu.Result("${ScreenName}"));
11638                 }
11639             }
11640
11641             await this.ShowFriendship(ids.ToArray());
11642         }
11643
11644         private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11645         {
11646             string name = GetUserId();
11647             if (name != null)
11648                 await this.ShowUserStatus(name);
11649         }
11650
11651         private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11652         {
11653             string name = GetUserId();
11654             if (name != null) AddNewTabForUserTimeline(name);
11655         }
11656
11657         private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11658         {
11659             string name = GetUserId();
11660             if (name != null) AddNewTabForSearch("@" + name);
11661         }
11662
11663         private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11664         {
11665             ModifySettingCommon = true;
11666         }
11667
11668         private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11669         {
11670             ModifySettingCommon = true;
11671         }
11672
11673         private void doQuoteOfficial()
11674         {
11675             if (this.ExistCurrentPost)
11676             {
11677                 if (_curPost.IsDm ||
11678                     !StatusText.Enabled) return;
11679
11680                 if (_curPost.IsProtect)
11681                 {
11682                     MessageBox.Show("Protected.");
11683                     return;
11684                 }
11685
11686                 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11687
11688                 this.inReplyTo = null;
11689
11690                 StatusText.SelectionStart = 0;
11691                 StatusText.Focus();
11692             }
11693         }
11694
11695         private void doReTweetUnofficial()
11696         {
11697             //RT @id:内容
11698             if (this.ExistCurrentPost)
11699             {
11700                 if (_curPost.IsDm || !StatusText.Enabled)
11701                     return;
11702
11703                 if (_curPost.IsProtect)
11704                 {
11705                     MessageBox.Show("Protected.");
11706                     return;
11707                 }
11708                 string rtdata = _curPost.Text;
11709                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11710
11711                 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11712
11713                 // 投稿時に in_reply_to_status_id を付加する
11714                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11715                 var inReplyToScreenName = this._curPost.ScreenName;
11716                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11717
11718                 StatusText.SelectionStart = 0;
11719                 StatusText.Focus();
11720             }
11721         }
11722
11723         private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11724         {
11725             doQuoteOfficial();
11726         }
11727
11728         private void SearchButton_Click(object sender, EventArgs e)
11729         {
11730             //公式検索
11731             Control pnl = ((Control)sender).Parent;
11732             if (pnl == null) return;
11733             string tbName = pnl.Parent.Text;
11734             TabClass tb = _statuses.Tabs[tbName];
11735             ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11736             ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11737             cmb.Text = cmb.Text.Trim();
11738             // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11739             bool Quote = false;
11740             StringBuilder buf = new StringBuilder();
11741             char[] c = cmb.Text.ToCharArray();
11742             for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11743             {
11744                 if (cnt > cmb.Text.Length - 4)
11745                 {
11746                     buf.Append(cmb.Text.Substring(cnt));
11747                     break;
11748                 }
11749                 if (c[cnt] == '"')
11750                 {
11751                     Quote = !Quote;
11752                 }
11753                 else
11754                 {
11755                     if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11756                     {
11757                         buf.Append(" OR ");
11758                         cnt += 3;
11759                         continue;
11760                     }
11761                 }
11762                 buf.Append(c[cnt]);
11763             }
11764             cmb.Text = buf.ToString();
11765
11766             var listView = (DetailsListView)pnl.Parent.Tag;
11767
11768             tb.SearchWords = cmb.Text;
11769             tb.SearchLang = cmbLang.Text;
11770             if (string.IsNullOrEmpty(cmb.Text))
11771             {
11772                 listView.Focus();
11773                 SaveConfigsTabs();
11774                 return;
11775             }
11776             if (tb.IsSearchQueryChanged)
11777             {
11778                 int idx = cmb.Items.IndexOf(tb.SearchWords);
11779                 if (idx > -1) cmb.Items.RemoveAt(idx);
11780                 cmb.Items.Insert(0, tb.SearchWords);
11781                 cmb.Text = tb.SearchWords;
11782                 cmb.SelectAll();
11783                 this.PurgeListViewItemCache();
11784                 listView.VirtualListSize = 0;
11785                 _statuses.ClearTabIds(tbName);
11786                 SaveConfigsTabs();   //検索条件の保存
11787             }
11788
11789             this.GetPublicSearchAsync(tb);
11790             listView.Focus();
11791         }
11792
11793         private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11794         {
11795             //もっと前を取得
11796             await this.DoRefreshMore();
11797         }
11798
11799         /// <summary>
11800         /// 指定されたタブのListTabにおける位置を返します
11801         /// </summary>
11802         /// <remarks>
11803         /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11804         /// </remarks>
11805         public int GetTabPageIndex(string tabName)
11806         {
11807             var index = 0;
11808             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11809             {
11810                 if (tabPage.Text == tabName)
11811                     return index;
11812
11813                 index++;
11814             }
11815
11816             return -1;
11817         }
11818
11819         private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11820         {
11821             if (_statuses.RemovedTab.Count == 0)
11822             {
11823                 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11824                 return;
11825             }
11826             else
11827             {
11828                 DetailsListView listView = null;
11829
11830                 TabClass tb = _statuses.RemovedTab.Pop();
11831                 if (tb.TabType == MyCommon.TabUsageType.Related)
11832                 {
11833                     var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11834                     if (relatedTab != null)
11835                     {
11836                         // 関連発言なら既存のタブを置き換える
11837                         tb.TabName = relatedTab.TabName;
11838                         this.ClearTab(tb.TabName, false);
11839                         _statuses.Tabs[tb.TabName] = tb;
11840
11841                         for (int i = 0; i < ListTab.TabPages.Count; i++)
11842                         {
11843                             var tabPage = ListTab.TabPages[i];
11844                             if (tb.TabName == tabPage.Text)
11845                             {
11846                                 listView = (DetailsListView)tabPage.Tag;
11847                                 ListTab.SelectedIndex = i;
11848                                 break;
11849                             }
11850                         }
11851                     }
11852                     else
11853                     {
11854                         const string TabName = "Related Tweets";
11855                         string renamed = TabName;
11856                         for (int i = 2; i <= 100; i++)
11857                         {
11858                             if (!_statuses.ContainsTab(renamed)) break;
11859                             renamed = TabName + i.ToString();
11860                         }
11861                         tb.TabName = renamed;
11862                         AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11863                         _statuses.Tabs.Add(renamed, tb);  // 後に
11864
11865                         var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11866                         listView = (DetailsListView)tabPage.Tag;
11867                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11868                     }
11869                 }
11870                 else
11871                 {
11872                     string renamed = tb.TabName;
11873                     for (int i = 1; i < int.MaxValue; i++)
11874                     {
11875                         if (!_statuses.ContainsTab(renamed)) break;
11876                         renamed = tb.TabName + "(" + i.ToString() + ")";
11877                     }
11878                     tb.TabName = renamed;
11879                     _statuses.Tabs.Add(renamed, tb);  // 先に
11880                     AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11881
11882                     var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11883                     listView = (DetailsListView)tabPage.Tag;
11884                     ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11885                 }
11886                 SaveConfigsTabs();
11887
11888                 if (listView != null)
11889                 {
11890                     using (ControlTransaction.Update(listView))
11891                     {
11892                         listView.VirtualListSize = tb.AllCount;
11893                     }
11894                 }
11895             }
11896         }
11897
11898         private async Task doMoveToRTHome()
11899         {
11900             if (_curList.SelectedIndices.Count > 0)
11901             {
11902                 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11903                 if (post.RetweetedId != null)
11904                 {
11905                     await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11906                 }
11907             }
11908         }
11909
11910         private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11911         {
11912             await this.doMoveToRTHome();
11913         }
11914
11915         private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11916         {
11917             string name = GetUserId();
11918             if (name != null)
11919             {
11920                 string tabName;
11921
11922                 //未選択なら処理終了
11923                 if (_curList.SelectedIndices.Count == 0) return;
11924
11925                 //タブ選択(or追加)
11926                 if (!SelectTab(out tabName)) return;
11927
11928                 var tab = this._statuses.Tabs[tabName];
11929
11930                 bool mv;
11931                 bool mk;
11932                 if (tab.TabType != MyCommon.TabUsageType.Mute)
11933                 {
11934                     this.MoveOrCopy(out mv, out mk);
11935                 }
11936                 else
11937                 {
11938                     // ミュートタブでは常に MoveMatches を true にする
11939                     mv = true;
11940                     mk = false;
11941                 }
11942
11943                 PostFilterRule fc = new PostFilterRule();
11944                 fc.FilterName = name;
11945                 fc.UseNameField = true;
11946                 fc.MoveMatches = mv;
11947                 fc.MarkMatches = mk;
11948                 fc.UseRegex = false;
11949                 fc.FilterByUrl = false;
11950                 tab.AddFilter(fc);
11951
11952                 this.ApplyPostFilters();
11953                 SaveConfigsTabs();
11954             }
11955         }
11956
11957         private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11958         {
11959             string user;
11960
11961             ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11962
11963             if (menuItem.Owner == this.ContextMenuPostBrowser)
11964             {
11965                 user = GetUserId();
11966                 if (user == null) return;
11967             }
11968             else if (this._curPost != null)
11969             {
11970                 user = this._curPost.ScreenName;
11971             }
11972             else
11973             {
11974                 return;
11975             }
11976
11977             if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11978             {
11979                 try
11980                 {
11981                     this.tw.GetListsApi();
11982                 }
11983                 catch (WebApiException ex)
11984                 {
11985                     MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
11986                     return;
11987                 }
11988             }
11989
11990             using (MyLists listSelectForm = new MyLists(user, this.tw))
11991             {
11992                 listSelectForm.ShowDialog(this);
11993             }
11994         }
11995
11996         private void SearchControls_Enter(object sender, EventArgs e)
11997         {
11998             Control pnl = (Control)sender;
11999             foreach (Control ctl in pnl.Controls)
12000             {
12001                 ctl.TabStop = true;
12002             }
12003         }
12004
12005         private void SearchControls_Leave(object sender, EventArgs e)
12006         {
12007             Control pnl = (Control)sender;
12008             foreach (Control ctl in pnl.Controls)
12009             {
12010                 ctl.TabStop = false;
12011             }
12012         }
12013
12014         private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12015         {
12016             if (ListTab.SelectedTab != null)
12017             {
12018                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12019                 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12020             }
12021         }
12022
12023         private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12024         {
12025             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12026             if (m.Success)
12027             {
12028                 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12029                 HashStripSplitButton.Text = HashMgr.UseHash;
12030                 HashToggleMenuItem.Checked = true;
12031                 HashToggleToolStripMenuItem.Checked = true;
12032                 //使用ハッシュタグとして設定
12033                 ModifySettingCommon = true;
12034             }
12035         }
12036
12037         private void StatusLabel_DoubleClick(object sender, EventArgs e)
12038         {
12039             MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12040         }
12041
12042         private void HashManageMenuItem_Click(object sender, EventArgs e)
12043         {
12044             DialogResult rslt = DialogResult.Cancel;
12045             try
12046             {
12047                 rslt = HashMgr.ShowDialog();
12048             }
12049             catch (Exception)
12050             {
12051                 return;
12052             }
12053             this.TopMost = this._cfgCommon.AlwaysTop;
12054             if (rslt == DialogResult.Cancel) return;
12055             if (!string.IsNullOrEmpty(HashMgr.UseHash))
12056             {
12057                 HashStripSplitButton.Text = HashMgr.UseHash;
12058                 HashToggleMenuItem.Checked = true;
12059                 HashToggleToolStripMenuItem.Checked = true;
12060             }
12061             else
12062             {
12063                 HashStripSplitButton.Text = "#[-]";
12064                 HashToggleMenuItem.Checked = false;
12065                 HashToggleToolStripMenuItem.Checked = false;
12066             }
12067             //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12068             //{
12069             //    int sidx = StatusText.SelectionStart;
12070             //    string hash = HashMgr.UseHash + " ";
12071             //    if (sidx > 0)
12072             //    {
12073             //        if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12074             //            hash = " " + hash;
12075             //    }
12076             //    StatusText.Text = StatusText.Text.Insert(sidx, hash);
12077             //    sidx += hash.Length;
12078             //    StatusText.SelectionStart = sidx;
12079             //    StatusText.Focus();
12080             //}
12081             ModifySettingCommon = true;
12082             this.StatusText_TextChanged(null, null);
12083         }
12084
12085         private void HashToggleMenuItem_Click(object sender, EventArgs e)
12086         {
12087             HashMgr.ToggleHash();
12088             if (!string.IsNullOrEmpty(HashMgr.UseHash))
12089             {
12090                 HashStripSplitButton.Text = HashMgr.UseHash;
12091                 HashToggleMenuItem.Checked = true;
12092                 HashToggleToolStripMenuItem.Checked = true;
12093             }
12094             else
12095             {
12096                 HashStripSplitButton.Text = "#[-]";
12097                 HashToggleMenuItem.Checked = false;
12098                 HashToggleToolStripMenuItem.Checked = false;
12099             }
12100             ModifySettingCommon = true;
12101             this.StatusText_TextChanged(null, null);
12102         }
12103
12104         private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12105         {
12106             HashToggleMenuItem_Click(null, null);
12107         }
12108
12109         private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12110         {
12111             if (ListTab.SelectedTab == null) return;
12112             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12113             if (!this.ExistCurrentPost)
12114             {
12115                 this.ReplyOpMenuItem.Enabled = false;
12116                 this.ReplyAllOpMenuItem.Enabled = false;
12117                 this.DmOpMenuItem.Enabled = false;
12118                 this.ShowProfMenuItem.Enabled = false;
12119                 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12120                 this.ListManageMenuItem.Enabled = false;
12121                 this.OpenFavOpMenuItem.Enabled = false;
12122                 this.CreateTabRuleOpMenuItem.Enabled = false;
12123                 this.CreateIdRuleOpMenuItem.Enabled = false;
12124                 this.CreateSourceRuleOpMenuItem.Enabled = false;
12125                 this.ReadOpMenuItem.Enabled = false;
12126                 this.UnreadOpMenuItem.Enabled = false;
12127             }
12128             else
12129             {
12130                 this.ReplyOpMenuItem.Enabled = true;
12131                 this.ReplyAllOpMenuItem.Enabled = true;
12132                 this.DmOpMenuItem.Enabled = true;
12133                 this.ShowProfMenuItem.Enabled = true;
12134                 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12135                 this.ListManageMenuItem.Enabled = true;
12136                 this.OpenFavOpMenuItem.Enabled = true;
12137                 this.CreateTabRuleOpMenuItem.Enabled = true;
12138                 this.CreateIdRuleOpMenuItem.Enabled = true;
12139                 this.CreateSourceRuleOpMenuItem.Enabled = true;
12140                 this.ReadOpMenuItem.Enabled = true;
12141                 this.UnreadOpMenuItem.Enabled = true;
12142             }
12143
12144             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12145             {
12146                 this.FavOpMenuItem.Enabled = false;
12147                 this.UnFavOpMenuItem.Enabled = false;
12148                 this.OpenStatusOpMenuItem.Enabled = false;
12149                 this.OpenFavotterOpMenuItem.Enabled = false;
12150                 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12151                 this.RtOpMenuItem.Enabled = false;
12152                 this.RtUnOpMenuItem.Enabled = false;
12153                 this.QtOpMenuItem.Enabled = false;
12154                 this.FavoriteRetweetMenuItem.Enabled = false;
12155                 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12156             }
12157             else
12158             {
12159                 this.FavOpMenuItem.Enabled = true;
12160                 this.UnFavOpMenuItem.Enabled = true;
12161                 this.OpenStatusOpMenuItem.Enabled = true;
12162                 this.OpenFavotterOpMenuItem.Enabled = true;
12163                 this.ShowRelatedStatusesMenuItem2.Enabled = true;  //PublicSearchの時問題出るかも
12164
12165                 if (_curPost.IsMe)
12166                 {
12167                     this.RtOpMenuItem.Enabled = false;  //公式RTは無効に
12168                     this.RtUnOpMenuItem.Enabled = true;
12169                     this.QtOpMenuItem.Enabled = true;
12170                     this.FavoriteRetweetMenuItem.Enabled = false;  //公式RTは無効に
12171                     this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12172                 }
12173                 else
12174                 {
12175                     if (_curPost.IsProtect)
12176                     {
12177                         this.RtOpMenuItem.Enabled = false;
12178                         this.RtUnOpMenuItem.Enabled = false;
12179                         this.QtOpMenuItem.Enabled = false;
12180                         this.FavoriteRetweetMenuItem.Enabled = false;
12181                         this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12182                     }
12183                     else
12184                     {
12185                         this.RtOpMenuItem.Enabled = true;
12186                         this.RtUnOpMenuItem.Enabled = true;
12187                         this.QtOpMenuItem.Enabled = true;
12188                         this.FavoriteRetweetMenuItem.Enabled = true;
12189                         this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12190                     }
12191                 }
12192             }
12193
12194             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12195             {
12196                 this.RefreshPrevOpMenuItem.Enabled = true;
12197             }
12198             else
12199             {
12200                 this.RefreshPrevOpMenuItem.Enabled = false;
12201             }
12202             if (!this.ExistCurrentPost
12203                 || _curPost.InReplyToStatusId == null)
12204             {
12205                 OpenRepSourceOpMenuItem.Enabled = false;
12206             }
12207             else
12208             {
12209                 OpenRepSourceOpMenuItem.Enabled = true;
12210             }
12211             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12212             {
12213                 OpenRterHomeMenuItem.Enabled = false;
12214             }
12215             else
12216             {
12217                 OpenRterHomeMenuItem.Enabled = true;
12218             }
12219
12220             if (this.ExistCurrentPost)
12221             {
12222                 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12223             }
12224         }
12225
12226         private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12227         {
12228             ContextMenuTabProperty_Opening(sender, null);
12229         }
12230
12231         public Twitter TwitterInstance
12232         {
12233             get { return tw; }
12234         }
12235
12236         private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12237         {
12238             if (this._initialLayout)
12239                 return;
12240
12241             int splitterDistance;
12242             switch (this.WindowState)
12243             {
12244                 case FormWindowState.Normal:
12245                     splitterDistance = this.SplitContainer3.SplitterDistance;
12246                     break;
12247                 case FormWindowState.Maximized:
12248                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
12249                     var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
12250                     splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
12251                     splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
12252                     break;
12253                 default:
12254                     return;
12255             }
12256
12257             this._mySpDis3 = splitterDistance;
12258             this.ModifySettingLocal = true;
12259         }
12260
12261         private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12262         {
12263             if (_statuses.RemovedTab.Count == 0)
12264             {
12265                 UndoRemoveTabMenuItem.Enabled = false;
12266             }
12267             else
12268             {
12269                 UndoRemoveTabMenuItem.Enabled = true;
12270             }
12271             if (ListTab.SelectedTab != null)
12272             {
12273                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12274                     PublicSearchQueryMenuItem.Enabled = true;
12275                 else
12276                     PublicSearchQueryMenuItem.Enabled = false;
12277             }
12278             else
12279             {
12280                 PublicSearchQueryMenuItem.Enabled = false;
12281             }
12282             if (!this.ExistCurrentPost)
12283             {
12284                 this.CopySTOTMenuItem.Enabled = false;
12285                 this.CopyURLMenuItem.Enabled = false;
12286                 this.CopyUserIdStripMenuItem.Enabled = false;
12287             }
12288             else
12289             {
12290                 this.CopySTOTMenuItem.Enabled = true;
12291                 this.CopyURLMenuItem.Enabled = true;
12292                 this.CopyUserIdStripMenuItem.Enabled = true;
12293                 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12294                 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12295             }
12296         }
12297
12298         private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12299         {
12300             SetNotifyIconText();
12301         }
12302
12303         private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12304         {
12305             var id = _curPost?.ScreenName ?? "";
12306
12307             await this.ShowUserStatus(id);
12308         }
12309
12310         private async Task doShowUserStatus(string id, bool ShowInputDialog)
12311         {
12312             TwitterUser user = null;
12313
12314             if (ShowInputDialog)
12315             {
12316                 using (var inputName = new InputTabName())
12317                 {
12318                     inputName.FormTitle = "Show UserStatus";
12319                     inputName.FormDescription = Properties.Resources.FRMessage1;
12320                     inputName.TabName = id;
12321
12322                     if (inputName.ShowDialog(this) != DialogResult.OK)
12323                         return;
12324                     if (string.IsNullOrWhiteSpace(inputName.TabName))
12325                         return;
12326
12327                     id = inputName.TabName.Trim();
12328                 }
12329             }
12330
12331             using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
12332             {
12333                 var cancellationToken = dialog.EnableCancellation();
12334
12335                 try
12336                 {
12337                     var task = Task.Run(() => this.tw.GetUserInfo(id));
12338                     user = await dialog.WaitForAsync(this, task);
12339                 }
12340                 catch (WebApiException ex)
12341                 {
12342                     if (!cancellationToken.IsCancellationRequested)
12343                         MessageBox.Show(ex.Message);
12344                     return;
12345                 }
12346
12347                 if (cancellationToken.IsCancellationRequested)
12348                     return;
12349             }
12350
12351             await this.doShowUserStatus(user);
12352         }
12353
12354         private async Task doShowUserStatus(TwitterUser user)
12355         {
12356             using (var userDialog = new UserInfoDialog(this, this.tw))
12357             {
12358                 var showUserTask = userDialog.ShowUserAsync(user);
12359                 userDialog.ShowDialog(this);
12360
12361                 this.Activate();
12362                 this.BringToFront();
12363
12364                 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12365                 await showUserTask;
12366             }
12367         }
12368
12369         private Task ShowUserStatus(string id, bool ShowInputDialog)
12370         {
12371             return this.doShowUserStatus(id, ShowInputDialog);
12372         }
12373
12374         private Task ShowUserStatus(string id)
12375         {
12376             return this.doShowUserStatus(id, true);
12377         }
12378
12379         private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12380         {
12381             if (NameLabel.Tag != null)
12382             {
12383                 string id = (string)NameLabel.Tag;
12384                 if (id != tw.Username)
12385                 {
12386                     await this.FollowCommand(id);
12387                 }
12388             }
12389         }
12390
12391         private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12392         {
12393             if (NameLabel.Tag != null)
12394             {
12395                 string id = (string)NameLabel.Tag;
12396                 if (id != tw.Username)
12397                 {
12398                     await this.RemoveCommand(id, false);
12399                 }
12400             }
12401         }
12402
12403         private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12404         {
12405             if (NameLabel.Tag != null)
12406             {
12407                 string id = (string)NameLabel.Tag;
12408                 if (id != tw.Username)
12409                 {
12410                     await this.ShowFriendship(id);
12411                 }
12412             }
12413         }
12414
12415         private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12416         {
12417             if (NameLabel.Tag != null)
12418             {
12419                 string id = (string)NameLabel.Tag;
12420                 await this.ShowUserStatus(id, false);
12421             }
12422         }
12423
12424         private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12425         {
12426             if (NameLabel.Tag != null)
12427             {
12428                 string id = (string)NameLabel.Tag;
12429                 AddNewTabForUserTimeline(id);
12430             }
12431         }
12432
12433         private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12434         {
12435             if (NameLabel.Tag != null)
12436             {
12437                 string id = (string)NameLabel.Tag;
12438                 AddNewTabForSearch("@" + id);
12439             }
12440         }
12441
12442         private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12443         {
12444             if (_curPost != null)
12445             {
12446                 await this.ShowUserStatus(_curPost.ScreenName, false);
12447             }
12448         }
12449
12450         private async void RtCountMenuItem_Click(object sender, EventArgs e)
12451         {
12452             if (!this.ExistCurrentPost)
12453                 return;
12454
12455             var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12456             int retweetCount = 0;
12457
12458             using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12459             {
12460                 var cancellationToken = dialog.EnableCancellation();
12461
12462                 try
12463                 {
12464                     var task = Task.Run(() => this.tw.GetStatus_Retweeted_Count(statusId));
12465                     retweetCount = await dialog.WaitForAsync(this, task);
12466                 }
12467                 catch (WebApiException ex)
12468                 {
12469                     if (!cancellationToken.IsCancellationRequested)
12470                         MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + ex.Message);
12471                     return;
12472                 }
12473
12474                 if (cancellationToken.IsCancellationRequested)
12475                     return;
12476             }
12477
12478             MessageBox.Show(retweetCount + Properties.Resources.RtCountText1);
12479         }
12480
12481         private HookGlobalHotkey _hookGlobalHotkey;
12482         public TweenMain()
12483         {
12484             _hookGlobalHotkey = new HookGlobalHotkey(this);
12485
12486             // この呼び出しは、Windows フォーム デザイナで必要です。
12487             InitializeComponent();
12488
12489             // InitializeComponent() 呼び出しの後で初期化を追加します。
12490
12491             if (!this.DesignMode)
12492             {
12493                 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12494                 this.StatusText.Dock = DockStyle.Fill;
12495             }
12496
12497             this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12498             this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12499             this.gh.NotifyClicked += GrowlHelper_Callback;
12500
12501             // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12502             this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12503
12504             this.ImageSelector.Visible = false;
12505             this.ImageSelector.Enabled = false;
12506             this.ImageSelector.FilePickDialog = OpenFileDialog1;
12507
12508             this.ReplaceAppName();
12509             this.InitializeShortcuts();
12510         }
12511
12512         private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12513         {
12514             if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12515             {
12516                 //アイコン化
12517                 this.Visible = false;
12518             }
12519             else if (Form.ActiveForm == null)
12520             {
12521                 this.Visible = true;
12522                 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12523                 this.Activate();
12524                 this.BringToFront();
12525                 this.StatusText.Focus();
12526             }
12527         }
12528
12529         private void UserPicture_MouseEnter(object sender, EventArgs e)
12530         {
12531             this.UserPicture.Cursor = Cursors.Hand;
12532         }
12533
12534         private void UserPicture_MouseLeave(object sender, EventArgs e)
12535         {
12536             this.UserPicture.Cursor = Cursors.Default;
12537         }
12538
12539         private async void UserPicture_DoubleClick(object sender, EventArgs e)
12540         {
12541             if (NameLabel.Tag != null)
12542             {
12543                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12544             }
12545         }
12546
12547         private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12548         {
12549             this.MultiLineMenuItem.PerformClick();
12550         }
12551
12552         public PostClass CurPost
12553         {
12554             get { return _curPost; }
12555         }
12556
12557 #region "画像投稿"
12558         private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12559         {
12560             if (ImageSelector.Visible)
12561                 ImageSelector.EndSelection();
12562             else
12563                 ImageSelector.BeginSelection();
12564         }
12565
12566         private void SelectMedia_DragEnter(DragEventArgs e)
12567         {
12568             if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12569             {
12570                 e.Effect = DragDropEffects.Copy;
12571                 return;
12572             }
12573             e.Effect = DragDropEffects.None;
12574         }
12575
12576         private void SelectMedia_DragDrop(DragEventArgs e)
12577         {
12578             this.Activate();
12579             this.BringToFront();
12580             ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12581             StatusText.Focus();
12582         }
12583
12584         private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12585         {
12586             TimelinePanel.Visible = false;
12587             TimelinePanel.Enabled = false;
12588         }
12589
12590         private void ImageSelector_EndSelecting(object sender, EventArgs e)
12591         {
12592             TimelinePanel.Visible = true;
12593             TimelinePanel.Enabled = true;
12594             ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12595         }
12596
12597         private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12598         {
12599             this.AllowDrop = false;
12600         }
12601
12602         private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12603         {
12604             this.AllowDrop = true;
12605         }
12606
12607         private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12608         {
12609             if (ImageSelector.Visible)
12610             {
12611                 ModifySettingCommon = true;
12612                 SaveConfigsAll(true);
12613
12614                 if (ImageSelector.ServiceName.Equals("Twitter"))
12615                     this.StatusText_TextChanged(null, null);
12616             }
12617         }
12618
12619         private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12620         {
12621             this.StatusText_TextChanged(null, null);
12622         }
12623
12624         /// <summary>
12625         /// StatusTextでCtrl+Vが押下された時の処理
12626         /// </summary>
12627         private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12628         {
12629             if (Clipboard.ContainsText())
12630             {
12631                 // clipboardにテキストがある場合は貼り付け処理
12632                 this.StatusText.Paste(Clipboard.GetText());
12633             }
12634             else if (Clipboard.ContainsImage())
12635             {
12636                 // 画像があるので投稿処理を行う
12637                 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12638                                    Properties.Resources.PostPictureWarn4,
12639                                    MessageBoxButtons.OKCancel,
12640                                    MessageBoxIcon.Question,
12641                                    MessageBoxDefaultButton.Button2)
12642                                == DialogResult.OK)
12643                 {
12644                     // clipboardから画像を取得
12645                     using (var image = Clipboard.GetImage())
12646                     {
12647                         this.ImageSelector.BeginSelection(image);
12648                     }
12649                 }
12650             }
12651         }
12652 #endregion
12653
12654         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12655         {
12656             using (ListManage form = new ListManage(tw))
12657             {
12658                 form.ShowDialog(this);
12659             }
12660         }
12661
12662         public bool ModifySettingCommon { get; set; }
12663         public bool ModifySettingLocal { get; set; }
12664         public bool ModifySettingAtId { get; set; }
12665
12666         private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12667         {
12668             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12669             if (sourceUri != null && e.Button == MouseButtons.Left)
12670             {
12671                 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12672             }
12673         }
12674
12675         private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12676         {
12677             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12678             if (sourceUri != null)
12679             {
12680                 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12681             }
12682         }
12683
12684         private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12685         {
12686             SetStatusLabelUrl();
12687         }
12688
12689         private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12690         {
12691             if (this.ExistCurrentPost && !_curPost.IsDm)
12692                 RtCountMenuItem.Enabled = true;
12693             else
12694                 RtCountMenuItem.Enabled = false;
12695
12696             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12697             //    TinyUrlConvertToolStripMenuItem.Enabled = false;
12698             //else
12699             //    TinyUrlConvertToolStripMenuItem.Enabled = true;
12700         }
12701
12702         private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12703         {
12704             CopyUserId();
12705         }
12706
12707         private void CopyUserId()
12708         {
12709             if (_curPost == null) return;
12710             string clstr = _curPost.ScreenName;
12711             try
12712             {
12713                 Clipboard.SetDataObject(clstr, false, 5, 100);
12714             }
12715             catch (Exception ex)
12716             {
12717                 MessageBox.Show(ex.Message);
12718             }
12719         }
12720
12721         private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12722         {
12723             if (this.ExistCurrentPost && !_curPost.IsDm)
12724             {
12725                 try
12726                 {
12727                     await this.OpenRelatedTab(this._curPost);
12728                 }
12729                 catch (TabException ex)
12730                 {
12731                     MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12732                 }
12733             }
12734         }
12735
12736         /// <summary>
12737         /// 指定されたツイートに対する関連発言タブを開きます
12738         /// </summary>
12739         /// <param name="statusId">表示するツイートのID</param>
12740         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12741         private async Task OpenRelatedTab(long statusId)
12742         {
12743             var post = this._statuses[statusId];
12744             if (post == null)
12745             {
12746                 try
12747                 {
12748                     post = await Task.Run(() => this.tw.GetStatusApi(false, statusId));
12749                 }
12750                 catch (WebApiException ex)
12751                 {
12752                     this.StatusLabel.Text = ex.Message;
12753                     return;
12754                 }
12755             }
12756
12757             await this.OpenRelatedTab(post);
12758         }
12759
12760         /// <summary>
12761         /// 指定されたツイートに対する関連発言タブを開きます
12762         /// </summary>
12763         /// <param name="post">表示する対象となるツイート</param>
12764         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12765         private async Task OpenRelatedTab(PostClass post)
12766         {
12767             var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12768             string tabName;
12769
12770             if (tabRelated == null)
12771             {
12772                 tabName = this._statuses.MakeTabName("Related Tweets");
12773
12774                 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12775                 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12776
12777                 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12778                 tabRelated.UnreadManage = false;
12779                 tabRelated.Notify = false;
12780             }
12781             else
12782             {
12783                 tabName = tabRelated.TabName;
12784             }
12785
12786             tabRelated.RelationTargetPost = post;
12787             this.ClearTab(tabName, false);
12788
12789             for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12790             {
12791                 var tabPage = this.ListTab.TabPages[i];
12792                 if (tabName == tabPage.Text)
12793                 {
12794                     this.ListTab.SelectedIndex = i;
12795                     break;
12796                 }
12797             }
12798
12799             await this.GetRelatedTweetsAsync(tabRelated);
12800         }
12801
12802         private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12803         {
12804             StringBuilder buf = new StringBuilder();
12805             //buf.AppendFormat("キャッシュメモリ容量         : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12806             //buf.AppendFormat("物理メモリ使用割合           : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12807             buf.AppendFormat("キャッシュエントリ保持数     : {0}" + Environment.NewLine, IconCache.CacheCount);
12808             buf.AppendFormat("キャッシュエントリ破棄数     : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12809             MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12810         }
12811
12812         private void tw_UserIdChanged()
12813         {
12814             this.ModifySettingCommon = true;
12815         }
12816
12817 #region "Userstream"
12818         private bool _isActiveUserstream = false;
12819
12820         private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12821         {
12822             try
12823             {
12824                 if (InvokeRequired && !IsDisposed)
12825                 {
12826                     Invoke((Action) (async () =>
12827                            {
12828                                _statuses.RemovePostReserve(e.StatusId);
12829                                if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12830                                {
12831                                    this.PurgeListViewItemCache();
12832                                    ((DetailsListView)_curTab.Tag).Update();
12833                                    if (_curPost != null && _curPost.StatusId == e.StatusId)
12834                                        await this.DispSelectedPost(true);
12835                                }
12836                            }));
12837                     return;
12838                 }
12839             }
12840             catch (ObjectDisposedException)
12841             {
12842                 return;
12843             }
12844             catch (InvalidOperationException)
12845             {
12846                 return;
12847             }
12848         }
12849
12850         private int userStreamsRefreshing = 0;
12851
12852         private async void tw_NewPostFromStream(object sender, EventArgs e)
12853         {
12854             if (this._cfgCommon.ReadOldPosts)
12855             {
12856                 _statuses.SetReadHomeTab(); //新着時未読クリア
12857             }
12858
12859             int rsltAddCount = _statuses.DistributePosts();
12860
12861             this.UpdateTimelineSpeed(rsltAddCount);
12862
12863             if (this._cfgCommon.UserstreamPeriod > 0) return;
12864
12865             // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
12866             if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
12867             {
12868                 try
12869                 {
12870                     await this.InvokeAsync(() => this.RefreshTimeline())
12871                         .ConfigureAwait(false);
12872                 }
12873                 finally
12874                 {
12875                     Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
12876                 }
12877             }
12878         }
12879
12880         private void tw_UserStreamStarted(object sender, EventArgs e)
12881         {
12882             this._isActiveUserstream = true;
12883             try
12884             {
12885                 if (InvokeRequired && !IsDisposed)
12886                 {
12887                     Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12888                     return;
12889                 }
12890             }
12891             catch (ObjectDisposedException)
12892             {
12893                 return;
12894             }
12895             catch (InvalidOperationException)
12896             {
12897                 return;
12898             }
12899
12900             MenuItemUserStream.Text = "&UserStream ▶";
12901             MenuItemUserStream.Enabled = true;
12902             StopToolStripMenuItem.Text = "&Stop";
12903             StopToolStripMenuItem.Enabled = true;
12904
12905             StatusLabel.Text = "UserStream Started.";
12906         }
12907
12908         private void tw_UserStreamStopped(object sender, EventArgs e)
12909         {
12910             this._isActiveUserstream = false;
12911             try
12912             {
12913                 if (InvokeRequired && !IsDisposed)
12914                 {
12915                     Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12916                     return;
12917                 }
12918             }
12919             catch (ObjectDisposedException)
12920             {
12921                 return;
12922             }
12923             catch (InvalidOperationException)
12924             {
12925                 return;
12926             }
12927
12928             MenuItemUserStream.Text = "&UserStream ■";
12929             MenuItemUserStream.Enabled = true;
12930             StopToolStripMenuItem.Text = "&Start";
12931             StopToolStripMenuItem.Enabled = true;
12932
12933             StatusLabel.Text = "UserStream Stopped.";
12934         }
12935
12936         private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12937         {
12938             try
12939             {
12940                 if (InvokeRequired && !IsDisposed)
12941                 {
12942                     Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12943                     return;
12944                 }
12945             }
12946             catch (ObjectDisposedException)
12947             {
12948                 return;
12949             }
12950             catch (InvalidOperationException)
12951             {
12952                 return;
12953             }
12954             var ev = e.EventData;
12955             StatusLabel.Text = "Event: " + ev.Event;
12956             //if (ev.Event == "favorite")
12957             //{
12958             //    NotifyFavorite(ev);
12959             //}
12960             NotifyEvent(ev);
12961             if (ev.Event == "favorite" || ev.Event == "unfavorite")
12962             {
12963                 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12964                 {
12965                     this.PurgeListViewItemCache();
12966                     ((DetailsListView)_curTab.Tag).Update();
12967                 }
12968                 if (ev.Event == "unfavorite" && ev.Username.ToLower().Equals(tw.Username.ToLower()))
12969                 {
12970                     RemovePostFromFavTab(new long[] {ev.Id});
12971                 }
12972             }
12973         }
12974
12975         private void NotifyEvent(Twitter.FormattedEvent ev)
12976         {
12977             //新着通知 
12978             if (BalloonRequired(ev))
12979             {
12980                 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
12981                 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
12982                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
12983                 StringBuilder title = new StringBuilder();
12984                 if (this._cfgCommon.DispUsername)
12985                 {
12986                     title.Append(tw.Username);
12987                     title.Append(" - ");
12988                 }
12989                 else
12990                 {
12991                     //title.Clear();
12992                 }
12993                 title.Append(Application.ProductName);
12994                 title.Append(" [");
12995                 title.Append(ev.Event.ToUpper());
12996                 title.Append("] by ");
12997                 if (!string.IsNullOrEmpty(ev.Username))
12998                 {
12999                     title.Append(ev.Username.ToString());
13000                 }
13001                 else
13002                 {
13003                     //title.Append("");
13004                 }
13005                 string text;
13006                 if (!string.IsNullOrEmpty(ev.Target))
13007                 {
13008                     //NotifyIcon1.BalloonTipText = ev.Target;
13009                     text = ev.Target;
13010                 }
13011                 else
13012                 {
13013                     //NotifyIcon1.BalloonTipText = " ";
13014                     text = " ";
13015                 }
13016                 //NotifyIcon1.ShowBalloonTip(500);
13017                 if (this._cfgCommon.IsUseNotifyGrowl)
13018                 {
13019                     gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13020                               ev.Id.ToString(), title.ToString(), text);
13021                 }
13022                 else
13023                 {
13024                     NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13025                     NotifyIcon1.BalloonTipTitle = title.ToString();
13026                     NotifyIcon1.BalloonTipText = text;
13027                     NotifyIcon1.ShowBalloonTip(500);
13028                 }
13029             }
13030
13031             //サウンド再生
13032             string snd = this._cfgCommon.EventSoundFile;
13033             if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13034             {
13035                 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13036                 {
13037                     try
13038                     {
13039                         string dir = Application.StartupPath;
13040                         if (Directory.Exists(Path.Combine(dir, "Sounds")))
13041                         {
13042                             dir = Path.Combine(dir, "Sounds");
13043                         }
13044                         using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13045                         {
13046                             player.Play();
13047                         }
13048                     }
13049                     catch (Exception)
13050                     {
13051                     }
13052                 }
13053             }
13054         }
13055
13056         private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13057         {
13058             MenuItemUserStream.Enabled = false;
13059             if (StopRefreshAllMenuItem.Checked)
13060             {
13061                 StopRefreshAllMenuItem.Checked = false;
13062                 return;
13063             }
13064             if (this._isActiveUserstream)
13065             {
13066                 tw.StopUserStream();
13067             }
13068             else
13069             {
13070                 tw.StartUserStream();
13071             }
13072         }
13073
13074         private static string inputTrack = "";
13075
13076         private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13077         {
13078             if (TrackToolStripMenuItem.Checked)
13079             {
13080                 using (InputTabName inputForm = new InputTabName())
13081                 {
13082                     inputForm.TabName = inputTrack;
13083                     inputForm.FormTitle = "Input track word";
13084                     inputForm.FormDescription = "Track word";
13085                     if (inputForm.ShowDialog() != DialogResult.OK)
13086                     {
13087                         TrackToolStripMenuItem.Checked = false;
13088                         return;
13089                     }
13090                     inputTrack = inputForm.TabName.Trim();
13091                 }
13092                 if (!inputTrack.Equals(tw.TrackWord))
13093                 {
13094                     tw.TrackWord = inputTrack;
13095                     this.ModifySettingCommon = true;
13096                     TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13097                     tw.ReconnectUserStream();
13098                 }
13099             }
13100             else
13101             {
13102                 tw.TrackWord = "";
13103                 tw.ReconnectUserStream();
13104             }
13105             this.ModifySettingCommon = true;
13106         }
13107
13108         private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13109         {
13110             tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13111             this.ModifySettingCommon = true;
13112             tw.ReconnectUserStream();
13113         }
13114
13115         private void EventViewerMenuItem_Click(object sender, EventArgs e)
13116         {
13117             if (evtDialog == null || evtDialog.IsDisposed)
13118             {
13119                 evtDialog = null;
13120                 evtDialog = new EventViewerDialog();
13121                 evtDialog.Owner = this;
13122                 //親の中央に表示
13123                 Point pos = evtDialog.Location;
13124                 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13125                 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13126                 evtDialog.Location = pos;
13127             }
13128             evtDialog.EventSource = tw.StoredEvent;
13129             if (!evtDialog.Visible)
13130             {
13131                 evtDialog.Show(this);
13132             }
13133             else
13134             {
13135                 evtDialog.Activate();
13136             }
13137             this.TopMost = this._cfgCommon.AlwaysTop;
13138         }
13139 #endregion
13140
13141         private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13142         {
13143             MyCommon._endingFlag = true;
13144             try
13145             {
13146                 this.Close();
13147                 Application.Restart();
13148             }
13149             catch (Exception)
13150             {
13151                 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13152             }
13153         }
13154
13155         private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13156         {
13157             if (!string.IsNullOrEmpty(tw.Username))
13158                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13159         }
13160
13161         private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13162         {
13163             await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
13164         }
13165
13166         private async Task doTranslation(string str)
13167         {
13168             if (string.IsNullOrEmpty(str))
13169                 return;
13170
13171             var bing = new Bing();
13172             try
13173             {
13174                 var translatedText = await bing.TranslateAsync(str,
13175                     langFrom: null,
13176                     langTo: this._cfgCommon.TranslateLanguage);
13177
13178                 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13179             }
13180             catch (HttpRequestException e)
13181             {
13182                 this.StatusLabel.Text = "Err:" + e.Message;
13183             }
13184         }
13185
13186         private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13187         {
13188             if (!this.ExistCurrentPost)
13189                 return;
13190
13191             await this.doTranslation(this._curPost.TextFromApi);
13192         }
13193
13194         private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13195         {
13196             var text = this.PostBrowser.GetSelectedText();
13197             await this.doTranslation(text);
13198         }
13199
13200         private bool ExistCurrentPost
13201         {
13202             get
13203             {
13204                 if (_curPost == null) return false;
13205                 if (_curPost.IsDeleted) return false;
13206                 return true;
13207             }
13208         }
13209
13210         private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13211         {
13212             ShowUserTimeline();
13213         }
13214
13215         private string GetUserIdFromCurPostOrInput(string caption)
13216         {
13217             var id = _curPost?.ScreenName ?? "";
13218
13219             using (InputTabName inputName = new InputTabName())
13220             {
13221                 inputName.FormTitle = caption;
13222                 inputName.FormDescription = Properties.Resources.FRMessage1;
13223                 inputName.TabName = id;
13224                 if (inputName.ShowDialog() == DialogResult.OK &&
13225                     !string.IsNullOrEmpty(inputName.TabName.Trim()))
13226                 {
13227                     id = inputName.TabName.Trim();
13228                 }
13229                 else
13230                 {
13231                     id = "";
13232                 }
13233             }
13234             return id;
13235         }
13236
13237         private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13238         {
13239             string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13240             if (!string.IsNullOrEmpty(id))
13241             {
13242                 AddNewTabForUserTimeline(id);
13243             }
13244         }
13245
13246         private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13247         {
13248             string id = GetUserIdFromCurPostOrInput("Show Favstar");
13249             if (!string.IsNullOrEmpty(id))
13250             {
13251                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13252             }
13253         }
13254
13255         private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13256         {
13257             if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13258         }
13259
13260         private void TimelineRefreshEnableChange(bool isEnable)
13261         {
13262             if (isEnable)
13263             {
13264                 tw.StartUserStream();
13265             }
13266             else
13267             {
13268                 tw.StopUserStream();
13269             }
13270             TimerTimeline.Enabled = isEnable;
13271         }
13272
13273         private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13274         {
13275             TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13276         }
13277
13278         private async Task OpenUserAppointUrl()
13279         {
13280             if (this._cfgCommon.UserAppointUrl != null)
13281             {
13282                 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13283                 {
13284                     if (_curPost != null)
13285                     {
13286                         string xUrl = this._cfgCommon.UserAppointUrl;
13287                         xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13288
13289                         var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
13290                         xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
13291
13292                         await this.OpenUriInBrowserAsync(xUrl);
13293                     }
13294                 }
13295                 else
13296                 {
13297                     await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
13298                 }
13299             }
13300         }
13301
13302         private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13303         {
13304             await this.OpenUserAppointUrl();
13305         }
13306
13307         private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13308         {
13309             string selText = SourceLinkLabel.Text;
13310             try
13311             {
13312                 Clipboard.SetDataObject(selText, false, 5, 100);
13313             }
13314             catch (Exception ex)
13315             {
13316                 MessageBox.Show(ex.Message);
13317             }
13318         }
13319
13320         private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13321         {
13322             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
13323             try
13324             {
13325                 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
13326             }
13327             catch (Exception ex)
13328             {
13329                 MessageBox.Show(ex.Message);
13330             }
13331         }
13332
13333         private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13334         {
13335             if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13336             {
13337                 SourceCopyMenuItem.Enabled = false;
13338                 SourceUrlCopyMenuItem.Enabled = false;
13339             }
13340             else
13341             {
13342                 SourceCopyMenuItem.Enabled = true;
13343                 SourceUrlCopyMenuItem.Enabled = true;
13344             }
13345         }
13346
13347         private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13348         {
13349             if (Form.ActiveForm == null)
13350             {
13351                 this.BeginInvoke((Action) (() =>
13352                 {
13353                     this.Visible = true;
13354                     if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13355                     this.Activate();
13356                     this.BringToFront();
13357                     if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13358                     {
13359                         if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13360                     }
13361                     else
13362                     {
13363                         if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13364                     }
13365                 }));
13366             }
13367         }
13368
13369         private void ReplaceAppName()
13370         {
13371             MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13372             AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13373         }
13374
13375         private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13376         {
13377             this.SplitContainer3.Panel2Collapsed = false;
13378         }
13379
13380         private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13381         {
13382             await this.OpenThumbnailPicture(e.Thumbnail);
13383         }
13384
13385         private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13386         {
13387             await this.OpenUriInBrowserAsync(e.ImageUrl);
13388         }
13389
13390         private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13391         {
13392             var url = thumbnail.FullSizeImageUrl ?? thumbnail.ImageUrl;
13393
13394             await this.OpenUriInBrowserAsync(url);
13395         }
13396
13397         private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13398         {
13399             await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13400         }
13401
13402         private void PostButton_KeyDown(object sender, KeyEventArgs e)
13403         {
13404             if (e.KeyCode == Keys.Space)
13405             {
13406                 this.JumpUnreadMenuItem_Click(null, null);
13407
13408                 e.SuppressKeyPress = true;
13409             }
13410         }
13411
13412         private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13413         {
13414             this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13415             this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13416             this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13417             this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13418             this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13419
13420             this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13421         }
13422
13423         private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13424         {
13425             ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13426         }
13427
13428         private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13429         {
13430             ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13431         }
13432
13433         private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13434         {
13435             ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13436         }
13437
13438         private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13439         {
13440             ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13441         }
13442
13443         private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13444         {
13445             ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13446         }
13447
13448         private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13449         {
13450             if (this._cfgCommon.IconSize == iconSize) return;
13451
13452             var oldIconCol = _iconCol;
13453
13454             this._cfgCommon.IconSize = iconSize;
13455             ApplyListViewIconSize(iconSize);
13456
13457             if (_iconCol != oldIconCol)
13458             {
13459                 foreach (TabPage tp in ListTab.TabPages)
13460                 {
13461                     ResetColumns((DetailsListView)tp.Tag);
13462                 }
13463             }
13464
13465             _curList?.Refresh();
13466
13467             ModifySettingCommon = true;
13468         }
13469
13470         private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13471         {
13472             var state = this.LockListSortOrderToolStripMenuItem.Checked;
13473             if (this._cfgCommon.SortOrderLock == state) return;
13474
13475             this._cfgCommon.SortOrderLock = state;
13476
13477             ModifySettingCommon = true;
13478         }
13479     }
13480 }