OSDN Git Service

TwitterApiConnection.RestApiBaseをstaticプロパティに変更
[opentween/open-tween.git] / OpenTween / Tween.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 //           (c) 2008-2011 Moz (@syo68k)
4 //           (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 //           (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 //           (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 //           (c) 2011      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
9 // 
10 // This file is part of OpenTween.
11 // 
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
15 // any later version.
16 // 
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
20 // for more details. 
21 // 
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
26
27 //コンパイル後コマンド
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
30
31 using System;
32 using System.Collections.Concurrent;
33 using System.Collections.Generic;
34 using System.ComponentModel;
35 using System.Diagnostics;
36 using System.Drawing;
37 using System.Globalization;
38 using System.IO;
39 using System.Linq;
40 using System.Media;
41 using System.Net;
42 using System.Net.Http;
43 using System.Reflection;
44 using System.Text;
45 using System.Text.RegularExpressions;
46 using System.Threading;
47 using System.Threading.Tasks;
48 using System.Windows.Forms;
49 using OpenTween.Api;
50 using OpenTween.Api.DataModel;
51 using OpenTween.Connection;
52 using OpenTween.OpenTweenCustomControl;
53 using OpenTween.Thumbnail;
54
55 namespace OpenTween
56 {
57     public partial class TweenMain : OTBaseForm
58     {
59         //各種設定
60         private Size _mySize;           //画面サイズ
61         private Point _myLoc;           //画面位置
62         private int _mySpDis;           //区切り位置
63         private int _mySpDis2;          //発言欄区切り位置
64         private int _mySpDis3;          //プレビュー区切り位置
65         private int _iconSz;            //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
66         private bool _iconCol;          //1列表示の時true(48サイズのとき)
67
68         //雑多なフラグ類
69         private bool _initial;         //true:起動時処理中
70         private bool _initialLayout = true;
71         private bool _ignoreConfigSave;         //true:起動時処理中
72         private bool _tabDrag;           //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
73         private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
74         private Point _tabMouseDownPoint;
75         private string _rclickTabName;      //右クリックしたタブの名前(Tabコントロール機能不足対応)
76         private readonly object _syncObject = new object();    //ロック用
77
78         private const string detailHtmlFormatHeaderMono = 
79             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
80             + "<style type=\"text/css\"><!-- "
81             + "body, p, pre {margin: 0;} "
82             + "pre {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
83             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
84             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
85             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
86             + ".quote-tweet.reply {border-color: #f33;} "
87             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
88             + "--></style>"
89             + "</head><body><pre>";
90         private const string detailHtmlFormatFooterMono = "</pre></body></html>";
91         private const string detailHtmlFormatHeaderColor = 
92             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
93             + "<style type=\"text/css\"><!-- "
94             + "body, p, pre {margin: 0;} "
95             + "body {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); margin: 0; word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
96             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
97             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
98             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
99             + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
100             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
101             + "--></style>"
102             + "</head><body><p>";
103         private const string detailHtmlFormatFooterColor = "</p></body></html>";
104         private string detailHtmlFormatHeader;
105         private string detailHtmlFormatFooter;
106
107         private bool _myStatusError = false;
108         private bool _myStatusOnline = false;
109         private bool soundfileListup = false;
110         private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
111
112         //設定ファイル関連
113         //private SettingToConfig _cfg; //旧
114         private SettingLocal _cfgLocal;
115         private SettingCommon _cfgCommon;
116
117         //twitter解析部
118         private TwitterApi twitterApi = new TwitterApi();
119         private Twitter tw;
120
121         //Growl呼び出し部
122         private GrowlHelper gh = new GrowlHelper(Application.ProductName);
123
124         //サブ画面インスタンス
125         private SearchWordDialog SearchDialog = new SearchWordDialog();     //検索画面インスタンス
126         private OpenURL UrlDialog = new OpenURL();
127         public AtIdSupplement AtIdSupl;     //@id補助
128         public AtIdSupplement HashSupl;    //Hashtag補助
129         public HashtagManage HashMgr;
130         private EventViewerDialog evtDialog;
131
132         //表示フォント、色、アイコン
133         private Font _fntUnread;            //未読用フォント
134         private Color _clUnread;            //未読用文字色
135         private Font _fntReaded;            //既読用フォント
136         private Color _clReaded;            //既読用文字色
137         private Color _clFav;               //Fav用文字色
138         private Color _clOWL;               //片思い用文字色
139         private Color _clRetweet;               //Retweet用文字色
140         private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText);         //選択中の行用文字色
141         private Font _fntDetail;            //発言詳細部用フォント
142         private Color _clDetail;              //発言詳細部用色
143         private Color _clDetailLink;          //発言詳細部用リンク文字色
144         private Color _clDetailBackcolor;     //発言詳細部用背景色
145         private Color _clSelf;              //自分の発言用背景色
146         private Color _clAtSelf;            //自分宛返信用背景色
147         private Color _clTarget;            //選択発言者の他の発言用背景色
148         private Color _clAtTarget;          //選択発言中の返信先用背景色
149         private Color _clAtFromTarget;      //選択発言者への返信発言用背景色
150         private Color _clAtTo;              //選択発言の唯一@先
151         private Color _clListBackcolor;       //リスト部通常発言背景色
152         private Color _clInputBackcolor;      //入力欄背景色
153         private Color _clInputFont;           //入力欄文字色
154         private Font _fntInputFont;           //入力欄フォント
155         private ImageCache IconCache;        //アイコン画像リスト
156         private Icon NIconAt;               //At.ico             タスクトレイアイコン:通常時
157         private Icon NIconAtRed;            //AtRed.ico          タスクトレイアイコン:通信エラー時
158         private Icon NIconAtSmoke;          //AtSmoke.ico        タスクトレイアイコン:オフライン時
159         private Icon[] NIconRefresh = new Icon[4];       //Refresh.ico        タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
160         private Icon TabIcon;               //Tab.ico            未読のあるタブ用アイコン
161         private Icon MainIcon;              //Main.ico           画面左上のアイコン
162         private Icon ReplyIcon;               //5g
163         private Icon ReplyIconBlink;          //6g
164
165         private ImageList _listViewImageList = new ImageList();    //ListViewItemの高さ変更用
166
167         private PostClass _anchorPost;
168         private bool _anchorFlag;        //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
169
170         private List<PostingStatus> _history = new List<PostingStatus>();   //発言履歴
171         private int _hisIdx;                  //発言履歴カレントインデックス
172
173         //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
174         private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
175
176         //時速表示用
177         private List<DateTime> _postTimestamps = new List<DateTime>();
178         private List<DateTime> _favTimestamps = new List<DateTime>();
179         private ConcurrentDictionary<DateTime, int> _tlTimestamps = new ConcurrentDictionary<DateTime, int>();
180         private int _tlCount;
181
182         // 以下DrawItem関連
183         private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
184         private SolidBrush _brsBackColorMine;
185         private SolidBrush _brsBackColorAt;
186         private SolidBrush _brsBackColorYou;
187         private SolidBrush _brsBackColorAtYou;
188         private SolidBrush _brsBackColorAtFromTarget;
189         private SolidBrush _brsBackColorAtTo;
190         private SolidBrush _brsBackColorNone;
191         private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
192         private StringFormat sfTab = new StringFormat();
193
194         //////////////////////////////////////////////////////////////////////////////////////////////////////////
195         private TabInformations _statuses;
196
197         /// <summary>
198         /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
199         /// </summary>
200         /// <remarks>
201         /// キャッシュクリアのために null が代入されることがあるため、
202         /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
203         /// 一旦ローカル変数に代入してから参照すること。
204         /// </remarks>
205         private ListViewItemCache _listItemCache = null;
206
207         internal class ListViewItemCache
208         {
209             /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
210             public ListView TargetList { get; set; }
211
212             /// <summary>キャッシュする範囲の開始インデックス</summary>
213             public int StartIndex { get; set; }
214
215             /// <summary>キャッシュする範囲の終了インデックス</summary>
216             public int EndIndex { get; set; }
217
218             /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
219             public ListViewItem[] ListItem { get; set; }
220
221             /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
222             public PostClass[] Post { get; set; }
223
224             /// <summary>キャッシュされたアイテムの件数</summary>
225             public int Count
226                 => this.EndIndex - this.StartIndex + 1;
227
228             /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
229             /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
230             public bool Contains(int index)
231                 => index >= this.StartIndex && index <= this.EndIndex;
232
233             /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
234             /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
235             public bool IsSupersetOf(int rangeStart, int rangeEnd)
236                 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
237
238             /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
239             /// <returns>取得に成功すれば true、それ以外は false</returns>
240             public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
241             {
242                 if (this.Contains(index))
243                 {
244                     item = this.ListItem[index - this.StartIndex];
245                     post = this.Post[index - this.StartIndex];
246                     return true;
247                 }
248                 else
249                 {
250                     item = null;
251                     post = null;
252                     return false;
253                 }
254             }
255         }
256
257         private TabPage _curTab;
258         private int _curItemIndex;
259         private DetailsListView _curList;
260         private PostClass _curPost;
261         private bool _isColumnChanged = false;
262
263         private const int MAX_WORKER_THREADS = 20;
264         private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
265         private CancellationTokenSource workerCts = new CancellationTokenSource();
266
267         private int UnreadCounter = -1;
268         private int UnreadAtCounter = -1;
269
270         private string[] ColumnOrgText = new string[9];
271         private string[] ColumnText = new string[9];
272
273         private bool _DoFavRetweetFlags = false;
274         private bool osResumed = false;
275
276         //////////////////////////////////////////////////////////////////////////////////////////////////////////
277         private string _postBrowserStatusText = "";
278
279         private bool _colorize = false;
280
281         private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
282
283         private ImageListViewItem displayItem;
284
285         private string recommendedStatusFooter;
286
287         //URL短縮のUndo用
288         private struct urlUndo
289         {
290             public string Before;
291             public string After;
292         }
293
294         private List<urlUndo> urlUndoBuffer = null;
295
296         private struct ReplyChain
297         {
298             public long OriginalId;
299             public long InReplyToId;
300             public TabPage OriginalTab;
301
302             public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
303             {
304                 this.OriginalId = originalId;
305                 this.InReplyToId = inReplyToId;
306                 this.OriginalTab = originalTab;
307             }
308         }
309
310         private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
311         private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
312
313         //検索処理タイプ
314         private enum SEARCHTYPE
315         {
316             DialogSearch,
317             NextSearch,
318             PrevSearch,
319         }
320
321         private class PostingStatus
322         {
323             public string status = "";
324             public long? inReplyToId = null;
325             public string inReplyToName = null;
326             public string imageService = "";      //画像投稿サービス名
327             public IMediaItem[] mediaItems = null;
328             public PostingStatus()
329             {
330             }
331             public PostingStatus(string status, long? replyToId, string replyToName)
332             {
333                 this.status = status;
334                 this.inReplyToId = replyToId;
335                 this.inReplyToName = replyToName;
336             }
337         }
338
339         private void TweenMain_Activated(object sender, EventArgs e)
340         {
341             //画面がアクティブになったら、発言欄の背景色戻す
342             if (StatusText.Focused)
343             {
344                 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
345             }
346         }
347
348         private bool disposed = false;
349
350         /// <summary>
351         /// 使用中のリソースをすべてクリーンアップします。
352         /// </summary>
353         /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
354         protected override void Dispose(bool disposing)
355         {
356             base.Dispose(disposing);
357
358             if (this.disposed)
359                 return;
360
361             if (disposing)
362             {
363                 this.components?.Dispose();
364
365                 //後始末
366                 SearchDialog.Dispose();
367                 UrlDialog.Dispose();
368                 NIconAt?.Dispose();
369                 NIconAtRed?.Dispose();
370                 NIconAtSmoke?.Dispose();
371                 foreach (var iconRefresh in this.NIconRefresh)
372                 {
373                     iconRefresh?.Dispose();
374                 }
375                 TabIcon?.Dispose();
376                 MainIcon?.Dispose();
377                 ReplyIcon?.Dispose();
378                 ReplyIconBlink?.Dispose();
379                 _listViewImageList.Dispose();
380                 _brsHighLight.Dispose();
381                 _brsBackColorMine?.Dispose();
382                 _brsBackColorAt?.Dispose();
383                 _brsBackColorYou?.Dispose();
384                 _brsBackColorAtYou?.Dispose();
385                 _brsBackColorAtFromTarget?.Dispose();
386                 _brsBackColorAtTo?.Dispose();
387                 _brsBackColorNone?.Dispose();
388                 _brsDeactiveSelection?.Dispose();
389                 //sf.Dispose();
390                 sfTab.Dispose();
391
392                 this.workerCts.Cancel();
393
394                 if (IconCache != null)
395                 {
396                     this.IconCache.CancelAsync();
397                     this.IconCache.Dispose();
398                 }
399
400                 this.thumbnailTokenSource?.Dispose();
401
402                 this.tw.Dispose();
403                 this.twitterApi.Dispose();
404                 this._hookGlobalHotkey.Dispose();
405             }
406
407             // 終了時にRemoveHandlerしておかないとメモリリークする
408             // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
409             Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
410
411             this.disposed = true;
412         }
413
414         private void LoadIcons()
415         {
416             // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
417             var iconsDir = Path.Combine(Application.StartupPath, "Icons");
418
419             // ウィンドウ左上のアイコン
420             var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
421
422             // タブ見出し未読表示アイコン
423             var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
424
425             // タスクトレイ: 通常時アイコン
426             var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
427
428             // タスクトレイ: エラー時アイコン
429             var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
430
431             // タスクトレイ: オフライン時アイコン
432             var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
433
434             // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
435             var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
436             var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
437
438             // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
439             var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
440             var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
441             var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
442             var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
443
444             // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
445
446             this.MainIcon = iconMain ?? Properties.Resources.MIcon;
447             this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
448             this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
449             this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
450             this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
451
452             if (iconReply != null && iconReplyBlink != null)
453             {
454                 this.ReplyIcon = iconReply;
455                 this.ReplyIconBlink = iconReplyBlink;
456             }
457             else
458             {
459                 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
460                 this.ReplyIconBlink = this.NIconAt;
461             }
462
463             if (iconRefresh1 == null)
464             {
465                 this.NIconRefresh = new[] {
466                     Properties.Resources.Refresh, Properties.Resources.Refresh2,
467                     Properties.Resources.Refresh3, Properties.Resources.Refresh4,
468                 };
469             }
470             else if (iconRefresh2 == null)
471             {
472                 this.NIconRefresh = new[] { iconRefresh1 };
473             }
474             else if (iconRefresh3 == null)
475             {
476                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
477             }
478             else if (iconRefresh4 == null)
479             {
480                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
481             }
482             else // iconRefresh1 から iconRefresh4 まで全て揃っている
483             {
484                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
485             }
486         }
487
488         private Icon LoadIcon(string filePath)
489         {
490             if (!File.Exists(filePath))
491                 return null;
492
493             try
494             {
495                 return new Icon(filePath);
496             }
497             catch (Exception)
498             {
499                 return null;
500             }
501         }
502
503         private void InitColumns(ListView list, bool startup)
504         {
505             this.InitColumnText();
506
507             ColumnHeader[] columns = null;
508             try
509             {
510                 if (this._iconCol)
511                 {
512                     columns = new[]
513                     {
514                         new ColumnHeader(), // アイコン
515                         new ColumnHeader(), // 本文
516                     };
517
518                     columns[0].Text = this.ColumnText[0];
519                     columns[1].Text = this.ColumnText[2];
520
521                     if (startup)
522                     {
523                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
524
525                         columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
526                         columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
527                         columns[0].DisplayIndex = 0;
528                         columns[1].DisplayIndex = 1;
529                     }
530                     else
531                     {
532                         var idx = 0;
533                         foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
534                         {
535                             columns[idx].Width = curListColumn.Width;
536                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
537                             idx++;
538                         }
539                     }
540                 }
541                 else
542                 {
543                     columns = new[]
544                     {
545                         new ColumnHeader(), // アイコン
546                         new ColumnHeader(), // ニックネーム
547                         new ColumnHeader(), // 本文
548                         new ColumnHeader(), // 日付
549                         new ColumnHeader(), // ユーザID
550                         new ColumnHeader(), // 未読
551                         new ColumnHeader(), // マーク&プロテクト
552                         new ColumnHeader(), // ソース
553                     };
554
555                     foreach (var i in Enumerable.Range(0, columns.Length))
556                         columns[i].Text = this.ColumnText[i];
557
558                     if (startup)
559                     {
560                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
561
562                         columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
563                         columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
564                         columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
565                         columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
566                         columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
567                         columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
568                         columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
569                         columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
570
571                         var displayIndex = new[] {
572                             this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
573                             this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
574                             this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
575                             this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
576                         };
577
578                         foreach (var i in Enumerable.Range(0, displayIndex.Length))
579                         {
580                             columns[i].DisplayIndex = displayIndex[i];
581                         }
582                     }
583                     else
584                     {
585                         var idx = 0;
586                         foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
587                         {
588                             columns[idx].Width = curListColumn.Width;
589                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
590                             idx++;
591                         }
592                     }
593                 }
594
595                 list.Columns.AddRange(columns);
596
597                 columns = null;
598             }
599             finally
600             {
601                 if (columns != null)
602                 {
603                     foreach (var column in columns)
604                         column?.Dispose();
605                 }
606             }
607         }
608
609         private void InitColumnText()
610         {
611             ColumnText[0] = "";
612             ColumnText[1] = Properties.Resources.AddNewTabText2;
613             ColumnText[2] = Properties.Resources.AddNewTabText3;
614             ColumnText[3] = Properties.Resources.AddNewTabText4_2;
615             ColumnText[4] = Properties.Resources.AddNewTabText5;
616             ColumnText[5] = "";
617             ColumnText[6] = "";
618             ColumnText[7] = "Source";
619
620             ColumnOrgText[0] = "";
621             ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
622             ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
623             ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
624             ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
625             ColumnOrgText[5] = "";
626             ColumnOrgText[6] = "";
627             ColumnOrgText[7] = "Source";
628
629             int c = 0;
630             switch (_statuses.SortMode)
631             {
632                 case ComparerMode.Nickname:  //ニックネーム
633                     c = 1;
634                     break;
635                 case ComparerMode.Data:  //本文
636                     c = 2;
637                     break;
638                 case ComparerMode.Id:  //時刻=発言Id
639                     c = 3;
640                     break;
641                 case ComparerMode.Name:  //名前
642                     c = 4;
643                     break;
644                 case ComparerMode.Source:  //Source
645                     c = 7;
646                     break;
647             }
648
649             if (_iconCol)
650             {
651                 if (_statuses.SortOrder == SortOrder.Descending)
652                 {
653                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
654                     ColumnText[2] = ColumnOrgText[2] + "▾";
655                 }
656                 else
657                 {
658                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
659                     ColumnText[2] = ColumnOrgText[2] + "▴";
660                 }
661             }
662             else
663             {
664                 if (_statuses.SortOrder == SortOrder.Descending)
665                 {
666                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
667                     ColumnText[c] = ColumnOrgText[c] + "▾";
668                 }
669                 else
670                 {
671                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
672                     ColumnText[c] = ColumnOrgText[c] + "▴";
673                 }
674             }
675         }
676
677         private void InitializeTraceFrag()
678         {
679 #if DEBUG
680             TraceOutToolStripMenuItem.Checked = true;
681             MyCommon.TraceFlag = true;
682 #endif
683             if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
684             {
685                 TraceOutToolStripMenuItem.Checked = true;
686                 MyCommon.TraceFlag = true;
687             }
688         }
689
690         private void TweenMain_Load(object sender, EventArgs e)
691         {
692             _ignoreConfigSave = true;
693             this.Visible = false;
694
695             if (MyApplication.StartupOptions.ContainsKey("d"))
696                 MyCommon.TraceFlag = true;
697
698             InitializeTraceFrag();
699
700             //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
701
702             new InternetSecurityManager(PostBrowser);
703             this.PostBrowser.AllowWebBrowserDrop = false;  // COMException を回避するため、ActiveX の初期化が終わってから設定する
704
705             MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
706             Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
707
708             Regex.CacheSize = 100;
709
710             //発言保持クラス
711             _statuses = TabInformations.GetInstance();
712
713             //アイコン設定
714             LoadIcons();
715             this.Icon = MainIcon;              //メインフォーム(TweenMain)
716             NotifyIcon1.Icon = NIconAt;      //タスクトレイ
717             TabImage.Images.Add(TabIcon);    //タブ見出し
718
719             //<<<<<<<<<設定関連>>>>>>>>>
720             ////設定読み出し
721             LoadConfig();
722
723             // 現在の DPI と設定保存時の DPI との比を取得する
724             var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
725
726             // UIフォント設定
727             var fontUIGlobal = this._cfgLocal.FontUIGlobal;
728             if (fontUIGlobal != null)
729             {
730                 OTBaseForm.GlobalFont = fontUIGlobal;
731                 this.Font = fontUIGlobal;
732             }
733
734             //不正値チェック
735             if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
736             {
737                 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
738                     this._cfgCommon.TimelinePeriod = 15;
739
740                 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
741                     this._cfgCommon.ReplyPeriod = 15;
742
743                 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
744                     this._cfgCommon.DMPeriod = 15;
745
746                 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
747                     this._cfgCommon.PubSearchPeriod = 30;
748
749                 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
750                     this._cfgCommon.UserTimelinePeriod = 15;
751
752                 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
753                     this._cfgCommon.ListsPeriod = 15;
754             }
755
756             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
757                 this._cfgCommon.CountApi = 60;
758             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
759                 this._cfgCommon.CountApiReply = 40;
760
761             if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
762                 this._cfgCommon.MoreCountApi = 200;
763             if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
764                 this._cfgCommon.FirstCountApi = 100;
765
766             if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
767                 this._cfgCommon.FavoritesCountApi = 40;
768             if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
769                 this._cfgCommon.ListCountApi = 100;
770             if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
771                 this._cfgCommon.SearchCountApi = 100;
772             if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
773                 this._cfgCommon.UserTimelineCountApi = 20;
774
775             //廃止サービスが選択されていた場合ux.nuへ読み替え
776             if (this._cfgCommon.AutoShortUrlFirst < 0)
777                 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
778
779             TwitterApiConnection.RestApiBase = new Uri(this._cfgCommon.TwitterUrl);
780             this.tw = new Twitter(this.twitterApi);
781
782             //認証関連
783             if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
784             tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
785
786             _initial = true;
787
788             Networking.Initialize();
789
790             bool saveRequired = false;
791             bool firstRun = false;
792
793             //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
794             if (string.IsNullOrEmpty(tw.Username))
795             {
796                 saveRequired = true;
797                 firstRun = true;
798
799                 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
800                 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
801                     string.IsNullOrEmpty(tw.Username))
802                 {
803                     Application.Exit();  //強制終了
804                     return;
805                 }
806             }
807
808             //Twitter用通信クラス初期化
809             Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
810             Networking.SetWebProxy(this._cfgLocal.ProxyType,
811                 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
812                 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
813             Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
814
815             TwitterApiConnection.RestApiBase = new Uri(this._cfgCommon.TwitterUrl);
816             tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
817             tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
818             tw.TrackWord = this._cfgCommon.TrackWord;
819             TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
820             tw.AllAtReply = this._cfgCommon.AllAtReply;
821             AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
822             ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
823             ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
824             ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
825
826             // アクセストークンが有効であるか確認する
827             // ここが Twitter API への最初のアクセスになるようにすること
828             try
829             {
830                 this.tw.VerifyCredentials();
831             }
832             catch (WebApiException ex)
833             {
834                 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
835                     Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
836             }
837
838             //サムネイル関連の初期化
839             //プロキシ設定等の通信まわりの初期化が済んでから処理する
840             ThumbnailGenerator.InitializeGenerator();
841
842             var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
843             imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
844             imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
845
846             Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
847
848             //画像投稿サービス
849             ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
850
851             //ハッシュタグ/@id関連
852             AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
853             HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
854             HashMgr = new HashtagManage(HashSupl,
855                                     _cfgCommon.HashTags.ToArray(),
856                                     _cfgCommon.HashSelected,
857                                     _cfgCommon.HashIsPermanent,
858                                     _cfgCommon.HashIsHead,
859                                     _cfgCommon.HashIsNotAddToAtReply);
860             if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
861
862             //アイコンリスト作成
863             this.IconCache = new ImageCache();
864
865             //フォント&文字色&背景色保持
866             _fntUnread = this._cfgLocal.FontUnread;
867             _clUnread = this._cfgLocal.ColorUnread;
868             _fntReaded = this._cfgLocal.FontRead;
869             _clReaded = this._cfgLocal.ColorRead;
870             _clFav = this._cfgLocal.ColorFav;
871             _clOWL = this._cfgLocal.ColorOWL;
872             _clRetweet = this._cfgLocal.ColorRetweet;
873             _fntDetail = this._cfgLocal.FontDetail;
874             _clDetail = this._cfgLocal.ColorDetail;
875             _clDetailLink = this._cfgLocal.ColorDetailLink;
876             _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
877             _clSelf = this._cfgLocal.ColorSelf;
878             _clAtSelf = this._cfgLocal.ColorAtSelf;
879             _clTarget = this._cfgLocal.ColorTarget;
880             _clAtTarget = this._cfgLocal.ColorAtTarget;
881             _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
882             _clAtTo = this._cfgLocal.ColorAtTo;
883             _clListBackcolor = this._cfgLocal.ColorListBackcolor;
884             _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
885             _clInputFont = this._cfgLocal.ColorInputFont;
886             _fntInputFont = this._cfgLocal.FontInputFont;
887
888             _brsBackColorMine = new SolidBrush(_clSelf);
889             _brsBackColorAt = new SolidBrush(_clAtSelf);
890             _brsBackColorYou = new SolidBrush(_clTarget);
891             _brsBackColorAtYou = new SolidBrush(_clAtTarget);
892             _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
893             _brsBackColorAtTo = new SolidBrush(_clAtTo);
894             //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
895             _brsBackColorNone = new SolidBrush(_clListBackcolor);
896
897             // StringFormatオブジェクトへの事前設定
898             //sf.Alignment = StringAlignment.Near;             // Textを近くへ配置(左から右の場合は左寄せ)
899             //sf.LineAlignment = StringAlignment.Near;         // Textを近くへ配置(上寄せ)
900             //sf.FormatFlags = StringFormatFlags.LineLimit;    // 
901             sfTab.Alignment = StringAlignment.Center;
902             sfTab.LineAlignment = StringAlignment.Center;
903
904             InitDetailHtmlFormat();
905
906             //Regex statregex = new Regex("^0*");
907             this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
908
909             _history.Add(new PostingStatus());
910             _hisIdx = 0;
911             this.inReplyTo = null;
912
913             //各種ダイアログ設定
914             SearchDialog.Owner = this;
915             UrlDialog.Owner = this;
916
917             //新着バルーン通知のチェック状態設定
918             NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
919             this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
920
921             //新着取得時のリストスクロールをするか。trueならスクロールしない
922             ListLockMenuItem.Checked = _cfgCommon.ListLock;
923             this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
924             //サウンド再生(タブ別設定より優先)
925             this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
926             this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
927
928             this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
929             this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
930
931             //ウィンドウ設定
932             this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
933             _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
934             _myLoc = _cfgLocal.FormLocation;
935             //タイトルバー領域
936             if (this.WindowState != FormWindowState.Minimized)
937             {
938                 this.DesktopLocation = _cfgLocal.FormLocation;
939                 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
940                 bool outOfScreen = true;
941                 if (Screen.AllScreens.Length == 1)    //ハングするとの報告
942                 {
943                     foreach (Screen scr in Screen.AllScreens)
944                     {
945                         if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
946                         {
947                             outOfScreen = false;
948                             break;
949                         }
950                     }
951                     if (outOfScreen)
952                     {
953                         this.DesktopLocation = new Point(0, 0);
954                         _myLoc = this.DesktopLocation;
955                     }
956                 }
957             }
958             this.TopMost = this._cfgCommon.AlwaysTop;
959             _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
960             _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
961             if (_cfgLocal.PreviewDistance == -1)
962             {
963                 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
964                 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
965                 _cfgLocal.PreviewDistance = _mySpDis3;
966             }
967             else
968             {
969                 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
970             }
971             MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
972             //this.Tween_ClientSizeChanged(this, null);
973             this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
974             this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
975             //入力欄
976             StatusText.Font = _fntInputFont;
977             StatusText.ForeColor = _clInputFont;
978
979             // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
980             this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
981             this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
982
983             // NameLabel のフォントを OTBaseForm.GlobalFont に変更
984             this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
985
986             // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
987             SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
988
989             //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
990             if (this._cfgCommon.UnreadManage == false)
991             {
992                 ReadedStripMenuItem.Enabled = false;
993                 UnreadStripMenuItem.Enabled = false;
994             }
995
996             //発言詳細部の初期化
997             NameLabel.Text = "";
998             DateTimeLabel.Text = "";
999             SourceLinkLabel.Text = "";
1000
1001             //リンク先URL表示部の初期化(画面左下)
1002             StatusLabelUrl.Text = "";
1003             //状態表示部の初期化(画面右下)
1004             StatusLabel.Text = "";
1005             StatusLabel.AutoToolTip = false;
1006             StatusLabel.ToolTipText = "";
1007             //文字カウンタ初期化
1008             lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
1009
1010             this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1011             CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1012             CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1013             CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1014
1015             // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1016             // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1017             // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1018             this.SplitContainer2.Panel2.AccessibleName = "";
1019
1020             ////////////////////////////////////////////////////////////////////////////////
1021             var sortOrder = (SortOrder)_cfgCommon.SortOrder;
1022             var mode = ComparerMode.Id;
1023             switch (_cfgCommon.SortColumn)
1024             {
1025                 case 0:    //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1026                 case 5:
1027                 case 6:
1028                     //ソートしない
1029                     mode = ComparerMode.Id;  //Idソートに読み替え
1030                     break;
1031                 case 1:  //ニックネーム
1032                     mode = ComparerMode.Nickname;
1033                     break;
1034                 case 2:  //本文
1035                     mode = ComparerMode.Data;
1036                     break;
1037                 case 3:  //時刻=発言Id
1038                     mode = ComparerMode.Id;
1039                     break;
1040                 case 4:  //名前
1041                     mode = ComparerMode.Name;
1042                     break;
1043                 case 7:  //Source
1044                     mode = ComparerMode.Source;
1045                     break;
1046             }
1047             _statuses.SetSortMode(mode, sortOrder);
1048             ////////////////////////////////////////////////////////////////////////////////
1049
1050             ApplyListViewIconSize(this._cfgCommon.IconSize);
1051
1052             //<<<<<<<<タブ関連>>>>>>>
1053             // タブの位置を調整する
1054             SetTabAlignment();
1055
1056             //デフォルトタブの存在チェック、ない場合には追加
1057             if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1058             {
1059                 TabClass tab;
1060                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1061                 {
1062                     _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1063                 }
1064                 else
1065                 {
1066                     tab.TabType = MyCommon.TabUsageType.Home;
1067                 }
1068             }
1069             if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1070             {
1071                 TabClass tab;
1072                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1073                 {
1074                     _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1075                 }
1076                 else
1077                 {
1078                     tab.TabType = MyCommon.TabUsageType.Mentions;
1079                 }
1080             }
1081             if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1082             {
1083                 TabClass tab;
1084                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1085                 {
1086                     _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1087                 }
1088                 else
1089                 {
1090                     tab.TabType = MyCommon.TabUsageType.DirectMessage;
1091                 }
1092             }
1093             if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1094             {
1095                 TabClass tab;
1096                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1097                 {
1098                     _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1099                 }
1100                 else
1101                 {
1102                     tab.TabType = MyCommon.TabUsageType.Favorites;
1103                 }
1104             }
1105             if (_statuses.GetTabByType(MyCommon.TabUsageType.Mute) == null)
1106             {
1107                 TabClass tab;
1108                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.MUTE, out tab))
1109                 {
1110                     _statuses.AddTab(MyCommon.DEFAULTTAB.MUTE, MyCommon.TabUsageType.Mute, null);
1111                 }
1112                 else
1113                 {
1114                     tab.TabType = MyCommon.TabUsageType.Mute;
1115                 }
1116             }
1117
1118             foreach (var tab in _statuses.Tabs.Values)
1119             {
1120                 // ミュートタブは表示しない
1121                 if (tab.TabType == MyCommon.TabUsageType.Mute)
1122                     continue;
1123
1124                 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1125                 {
1126                     tab.TabType = MyCommon.TabUsageType.UserDefined;
1127                 }
1128                 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1129                     throw new TabException(Properties.Resources.TweenMain_LoadText1);
1130             }
1131
1132             _curTab = ListTab.SelectedTab;
1133             _curItemIndex = -1;
1134             _curList = (DetailsListView)_curTab.Tag;
1135
1136             if (this._cfgCommon.TabIconDisp)
1137             {
1138                 ListTab.DrawMode = TabDrawMode.Normal;
1139             }
1140             else
1141             {
1142                 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1143                 ListTab.DrawItem += ListTab_DrawItem;
1144                 ListTab.ImageList = null;
1145             }
1146
1147             if (this._cfgCommon.HotkeyEnabled)
1148             {
1149                 //////グローバルホットキーの登録
1150                 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1151                 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1152                     modKey |= HookGlobalHotkey.ModKeys.Alt;
1153                 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1154                     modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1155                 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1156                     modKey |= HookGlobalHotkey.ModKeys.Shift;
1157                 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1158                     modKey |= HookGlobalHotkey.ModKeys.Win;
1159
1160                 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1161             }
1162
1163             if (this._cfgCommon.IsUseNotifyGrowl)
1164                 gh.RegisterGrowl();
1165
1166             StatusLabel.Text = Properties.Resources.Form1_LoadText1;       //画面右下の状態表示を変更
1167
1168             SetMainWindowTitle();
1169             SetNotifyIconText();
1170
1171             if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1172             {
1173                 this.Visible = true;
1174             }
1175
1176             //タイマー設定
1177             TimerTimeline.AutoReset = true;
1178             TimerTimeline.SynchronizingObject = this;
1179             //Recent取得間隔
1180             TimerTimeline.Interval = 1000;
1181             TimerTimeline.Enabled = true;
1182             //更新中アイコンアニメーション間隔
1183             TimerRefreshIcon.Interval = 200;
1184             TimerRefreshIcon.Enabled = true;
1185
1186             _ignoreConfigSave = false;
1187             this.TweenMain_Resize(null, null);
1188             if (saveRequired) SaveConfigsAll(false);
1189
1190             foreach (var ua in this._cfgCommon.UserAccounts)
1191             {
1192                 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1193                 {
1194                     ua.UserId = tw.UserId;
1195                     break;
1196                 }
1197             }
1198
1199             if (firstRun)
1200             {
1201                 // 初回起動時だけ右下のメニューを目立たせる
1202                 HashStripSplitButton.ShowDropDown();
1203             }
1204         }
1205
1206         private void InitDetailHtmlFormat()
1207         {
1208             if (this._cfgCommon.IsMonospace)
1209             {
1210                 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1211                 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1212             }
1213             else
1214             {
1215                 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1216                 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1217             }
1218
1219             detailHtmlFormatHeader = detailHtmlFormatHeader
1220                     .Replace("%FONT_FAMILY%", _fntDetail.Name)
1221                     .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1222                     .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1223                     .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1224                     .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString())
1225                     .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1226         }
1227
1228         private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1229         {
1230             string txt;
1231             try
1232             {
1233                 txt = ListTab.TabPages[e.Index].Text;
1234             }
1235             catch (Exception)
1236             {
1237                 return;
1238             }
1239
1240             e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1241             if (e.State == DrawItemState.Selected)
1242             {
1243                 e.DrawFocusRectangle();
1244             }
1245             Brush fore;
1246             try
1247             {
1248                 if (_statuses.Tabs[txt].UnreadCount > 0)
1249                     fore = Brushes.Red;
1250                 else
1251                     fore = System.Drawing.SystemBrushes.ControlText;
1252             }
1253             catch (Exception)
1254             {
1255                 fore = System.Drawing.SystemBrushes.ControlText;
1256             }
1257             e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1258         }
1259
1260         private void LoadConfig()
1261         {
1262             _cfgCommon = SettingCommon.Load();
1263             SettingCommon.Instance = this._cfgCommon;
1264             if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1265             {
1266                 _cfgCommon.UserAccounts = new List<UserAccount>();
1267                 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1268                 {
1269                     UserAccount account = new UserAccount();
1270                     account.Username = _cfgCommon.UserName;
1271                     account.UserId = _cfgCommon.UserId;
1272                     account.Token = _cfgCommon.Token;
1273                     account.TokenSecret = _cfgCommon.TokenSecret;
1274
1275                     _cfgCommon.UserAccounts.Add(account);
1276                 }
1277             }
1278
1279             _cfgLocal = SettingLocal.Load();
1280
1281             // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1282             if (_cfgLocal.ScaleDimension.IsEmpty)
1283                 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1284
1285             List<TabClass> tabs = SettingTabs.Load().Tabs;
1286             foreach (TabClass tb in tabs)
1287             {
1288                 try
1289                 {
1290                     tb.FilterModified = false;
1291                     _statuses.Tabs.Add(tb.TabName, tb);
1292                 }
1293                 catch (Exception)
1294                 {
1295                     tb.TabName = _statuses.MakeTabName("MyTab");
1296                     _statuses.Tabs.Add(tb.TabName, tb);
1297                 }
1298             }
1299             if (_statuses.Tabs.Count == 0)
1300             {
1301                 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1302                 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1303                 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1304                 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1305             }
1306         }
1307
1308         private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1309         {
1310             if (!TimerTimeline.Enabled) return;
1311             ResetTimers = e;
1312         }
1313
1314         private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1315
1316         private static int homeCounter = 0;
1317         private static int mentionCounter = 0;
1318         private static int dmCounter = 0;
1319         private static int pubSearchCounter = 0;
1320         private static int userTimelineCounter = 0;
1321         private static int listsCounter = 0;
1322         private static int usCounter = 0;
1323         private static int ResumeWait = 0;
1324         private static int refreshFollowers = 0;
1325
1326         private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1327         {
1328             if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1329             if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1330             if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1331             if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1332             if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1333             if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1334             if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1335             Interlocked.Increment(ref refreshFollowers);
1336
1337             var refreshTasks = new List<Task>();
1338
1339             ////タイマー初期化
1340             if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1341             {
1342                 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1343                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1344                     refreshTasks.Add(this.GetHomeTimelineAsync());
1345                 ResetTimers.Timeline = false;
1346             }
1347             if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1348             {
1349                 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1350                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1351                     refreshTasks.Add(this.GetReplyAsync());
1352                 ResetTimers.Reply = false;
1353             }
1354             if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1355             {
1356                 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1357                 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1358                     refreshTasks.Add(this.GetDirectMessagesAsync());
1359                 ResetTimers.DirectMessage = false;
1360             }
1361             if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1362             {
1363                 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1364                 if (!ResetTimers.PublicSearch)
1365                     refreshTasks.Add(this.GetPublicSearchAllAsync());
1366                 ResetTimers.PublicSearch = false;
1367             }
1368             if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1369             {
1370                 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1371                 if (!ResetTimers.UserTimeline)
1372                     refreshTasks.Add(this.GetUserTimelineAllAsync());
1373                 ResetTimers.UserTimeline = false;
1374             }
1375             if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1376             {
1377                 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1378                 if (!ResetTimers.Lists)
1379                     refreshTasks.Add(this.GetListTimelineAllAsync());
1380                 ResetTimers.Lists = false;
1381             }
1382             if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1383             {
1384                 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1385                 if (this.tw.UserStreamActive)
1386                     this.RefreshTimeline();
1387                 ResetTimers.UserStream = false;
1388             }
1389             if (refreshFollowers > 6 * 3600)
1390             {
1391                 Interlocked.Exchange(ref refreshFollowers, 0);
1392                 refreshTasks.AddRange(new[]
1393                 {
1394                     this.doGetFollowersMenu(),
1395                     this.RefreshNoRetweetIdsAsync(),
1396                     this.RefreshTwitterConfigurationAsync(),
1397                 });
1398             }
1399             if (osResumed)
1400             {
1401                 Interlocked.Increment(ref ResumeWait);
1402                 if (ResumeWait > 30)
1403                 {
1404                     osResumed = false;
1405                     Interlocked.Exchange(ref ResumeWait, 0);
1406                     refreshTasks.AddRange(new[]
1407                     {
1408                         this.GetHomeTimelineAsync(),
1409                         this.GetReplyAsync(),
1410                         this.GetDirectMessagesAsync(),
1411                         this.GetPublicSearchAllAsync(),
1412                         this.GetUserTimelineAllAsync(),
1413                         this.GetListTimelineAllAsync(),
1414                         this.doGetFollowersMenu(),
1415                         this.RefreshTwitterConfigurationAsync(),
1416                     });
1417                 }
1418             }
1419
1420             await Task.WhenAll(refreshTasks);
1421         }
1422
1423         private void RefreshTimeline()
1424         {
1425             // 現在表示中のタブのスクロール位置を退避
1426             var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1427
1428             // 各タブのリスト上の選択位置などを退避
1429             var listSelections = this.SaveListViewSelection();
1430
1431             //更新確定
1432             PostClass[] notifyPosts;
1433             string soundFile;
1434             int addCount;
1435             bool newMentionOrDm;
1436             bool isDelete;
1437             addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1438
1439             if (MyCommon._endingFlag) return;
1440
1441             //リストに反映&選択状態復元
1442             try
1443             {
1444                 foreach (TabPage tab in ListTab.TabPages)
1445                 {
1446                     DetailsListView lst = (DetailsListView)tab.Tag;
1447                     TabClass tabInfo = _statuses.Tabs[tab.Text];
1448                     if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1449                     {
1450                         using (ControlTransaction.Update(lst))
1451                         {
1452                             if (lst.Equals(_curList))
1453                             {
1454                                 this.PurgeListViewItemCache();
1455                             }
1456                             try
1457                             {
1458                                 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1459                             }
1460                             catch (Exception)
1461                             {
1462                                 //アイコン描画不具合あり?
1463                             }
1464
1465                             // 選択位置などを復元
1466                             this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1467                         }
1468                     }
1469                     if (tabInfo.UnreadCount > 0)
1470                         if (this._cfgCommon.TabIconDisp)
1471                             if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1472                 }
1473                 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1474             }
1475             catch (Exception)
1476             {
1477                 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1478                 //throw;
1479             }
1480
1481             // スクロール位置を復元
1482             this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1483
1484             //新着通知
1485             NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1486
1487             SetMainWindowTitle();
1488             if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1489
1490             HashSupl.AddRangeItem(tw.GetHashList());
1491
1492         }
1493
1494         internal struct ListViewScroll
1495         {
1496             public ScrollLockMode ScrollLockMode { get; set; }
1497             public long? TopItemStatusId { get; set; }
1498         }
1499
1500         internal enum ScrollLockMode
1501         {
1502             /// <summary>固定しない</summary>
1503             None,
1504
1505             /// <summary>最上部に固定する</summary>
1506             FixedToTop,
1507
1508             /// <summary>最下部に固定する</summary>
1509             FixedToBottom,
1510
1511             /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1512             FixedToItem,
1513         }
1514
1515         /// <summary>
1516         /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1517         /// </summary>
1518         private ListViewScroll SaveListViewScroll(DetailsListView listView, TabClass tab)
1519         {
1520             var listScroll = new ListViewScroll
1521             {
1522                 ScrollLockMode = this.GetScrollLockMode(listView),
1523             };
1524
1525             if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1526             {
1527                 var topItem = listView.TopItem;
1528                 if (topItem != null)
1529                     listScroll.TopItemStatusId = tab.GetId(topItem.Index);
1530             }
1531
1532             return listScroll;
1533         }
1534
1535         private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1536         {
1537             if (this._statuses.SortMode == ComparerMode.Id)
1538             {
1539                 if (this._statuses.SortOrder == SortOrder.Ascending)
1540                 {
1541                     // Id昇順
1542                     if (this.ListLockMenuItem.Checked)
1543                         return ScrollLockMode.None;
1544
1545                     // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1546
1547                     // 一番下に表示されているアイテム
1548                     var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1549                     if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1550                         return ScrollLockMode.FixedToBottom;
1551                     else
1552                         return ScrollLockMode.None;
1553                 }
1554                 else
1555                 {
1556                     // Id降順
1557                     if (this.ListLockMenuItem.Checked)
1558                         return ScrollLockMode.FixedToItem;
1559
1560                     // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1561                     var topItem = listView.TopItem;
1562                     if (topItem == null || topItem.Index == 0)
1563                         return ScrollLockMode.FixedToTop;
1564                     else
1565                         return ScrollLockMode.FixedToItem;
1566                 }
1567             }
1568             else
1569             {
1570                 return ScrollLockMode.FixedToItem;
1571             }
1572         }
1573
1574         internal struct ListViewSelection
1575         {
1576             public long[] SelectedStatusIds { get; set; }
1577             public long? SelectionMarkStatusId { get; set; }
1578             public long? FocusedStatusId { get; set; }
1579         }
1580
1581         /// <summary>
1582         /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1583         /// </summary>
1584         private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1585         {
1586             var listsDict = new Dictionary<string, ListViewSelection>();
1587
1588             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1589             {
1590                 var listView = (DetailsListView)tabPage.Tag;
1591                 var tab = _statuses.Tabs[tabPage.Text];
1592
1593                 ListViewSelection listStatus;
1594                 if (listView.VirtualListSize != 0)
1595                 {
1596                     listStatus = new ListViewSelection
1597                     {
1598                         SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1599                         FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1600                         SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1601                     };
1602                 }
1603                 else
1604                 {
1605                     listStatus = new ListViewSelection
1606                     {
1607                         SelectedStatusIds = new long[0],
1608                         SelectionMarkStatusId = null,
1609                         FocusedStatusId = null,
1610                     };
1611                 }
1612
1613                 listsDict[tab.TabName] = listStatus;
1614             }
1615
1616             return listsDict;
1617         }
1618
1619         private long[] GetSelectedStatusIds(DetailsListView listView, TabClass tab)
1620         {
1621             var selectedIndices = listView.SelectedIndices;
1622             if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1623                 return tab.GetId(selectedIndices);
1624             else
1625                 return null;
1626         }
1627
1628         private long? GetFocusedStatusId(DetailsListView listView, TabClass tab)
1629         {
1630             var focusedItem = listView.FocusedItem;
1631
1632             return focusedItem != null ? tab.GetId(focusedItem.Index) : (long?)null;
1633         }
1634
1635         private long? GetSelectionMarkStatusId(DetailsListView listView, TabClass tab)
1636         {
1637             var selectionMarkIndex = listView.SelectionMark;
1638
1639             return selectionMarkIndex != -1 ? tab.GetId(selectionMarkIndex) : (long?)null;
1640         }
1641
1642         /// <summary>
1643         /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1644         /// </summary>
1645         private void RestoreListViewScroll(DetailsListView listView, TabClass tab, ListViewScroll listScroll)
1646         {
1647             if (listView.VirtualListSize == 0)
1648                 return;
1649
1650             switch (listScroll.ScrollLockMode)
1651             {
1652                 case ScrollLockMode.FixedToTop:
1653                     listView.EnsureVisible(0);
1654                     break;
1655                 case ScrollLockMode.FixedToBottom:
1656                     listView.EnsureVisible(listView.VirtualListSize - 1);
1657                     break;
1658                 case ScrollLockMode.FixedToItem:
1659                     var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1660                     if (topIndex != -1)
1661                         listView.TopItem = listView.Items[topIndex];
1662                     break;
1663                 case ScrollLockMode.None:
1664                 default:
1665                     break;
1666             }
1667         }
1668
1669         /// <summary>
1670         /// <see cref="SaveListViewStatus"/> によって保存された選択状態を復元します
1671         /// </summary>
1672         private void RestoreListViewSelection(DetailsListView listView, TabClass tab, ListViewSelection listSelection)
1673         {
1674             // status_id から ListView 上のインデックスに変換
1675             int[] selectedIndices = null;
1676             if (listSelection.SelectedStatusIds != null)
1677                 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1678
1679             var focusedIndex = -1;
1680             if (listSelection.FocusedStatusId != null)
1681                 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1682
1683             var selectionMarkIndex = -1;
1684             if (listSelection.SelectionMarkStatusId != null)
1685                 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1686
1687             this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1688         }
1689
1690         private bool BalloonRequired()
1691         {
1692             Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1693             ev.Eventtype = MyCommon.EVENTTYPE.None;
1694
1695             return BalloonRequired(ev);
1696         }
1697
1698         private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1699         {
1700             if (type == MyCommon.EVENTTYPE.None)
1701                 return true;
1702
1703             if (!this._cfgCommon.EventNotifyEnabled)
1704                 return false;
1705
1706             return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1707         }
1708
1709         private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1710         {
1711             if (!ev.IsMe)
1712                 return true;
1713
1714             return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1715         }
1716
1717         private bool BalloonRequired(Twitter.FormattedEvent ev)
1718         {
1719             if (this._initial)
1720                 return false;
1721
1722             if (NativeMethods.IsScreenSaverRunning())
1723                 return false;
1724
1725             // 「新着通知」が無効
1726             if (!this.NewPostPopMenuItem.Checked)
1727             {
1728                 // 「新着通知が無効でもイベントを通知する」にも該当しない
1729                 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1730                     return false;
1731             }
1732
1733             // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1734             if (this._cfgCommon.LimitBalloon)
1735             {
1736                 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1737                     return false;
1738             }
1739
1740             return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1741         }
1742
1743         private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1744         {
1745             if (this._cfgCommon.ReadOwnPost)
1746             {
1747                 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1748                     return;
1749             }
1750
1751             //新着通知
1752             if (BalloonRequired())
1753             {
1754                 if (notifyPosts != null && notifyPosts.Length > 0)
1755                 {
1756                     //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1757                     if (this._cfgCommon.IsUseNotifyGrowl)
1758                     {
1759                         StringBuilder sb = new StringBuilder();
1760                         bool reply = false;
1761                         bool dm = false;
1762
1763                         foreach (PostClass post in notifyPosts)
1764                         {
1765                             if (!(notifyPosts.Length > 3))
1766                             {
1767                                 sb.Clear();
1768                                 reply = false;
1769                                 dm = false;
1770                             }
1771                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1772                             if (post.IsDm) dm = true;
1773                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1774                             switch (this._cfgCommon.NameBalloon)
1775                             {
1776                                 case MyCommon.NameBalloonEnum.UserID:
1777                                     sb.Append(post.ScreenName).Append(" : ");
1778                                     break;
1779                                 case MyCommon.NameBalloonEnum.NickName:
1780                                     sb.Append(post.Nickname).Append(" : ");
1781                                     break;
1782                             }
1783                             sb.Append(post.TextFromApi);
1784                             if (notifyPosts.Length > 3)
1785                             {
1786                                 if (notifyPosts.Last() != post) continue;
1787                             }
1788
1789                             StringBuilder title = new StringBuilder();
1790                             GrowlHelper.NotifyType nt;
1791                             if (this._cfgCommon.DispUsername)
1792                             {
1793                                 title.Append(tw.Username);
1794                                 title.Append(" - ");
1795                             }
1796                             else
1797                             {
1798                                 //title.Clear();
1799                             }
1800                             if (dm)
1801                             {
1802                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1803                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1804                                 title.Append(Application.ProductName);
1805                                 title.Append(" [DM] ");
1806                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1807                                 nt = GrowlHelper.NotifyType.DirectMessage;
1808                             }
1809                             else if (reply)
1810                             {
1811                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1812                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1813                                 title.Append(Application.ProductName);
1814                                 title.Append(" [Reply!] ");
1815                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1816                                 nt = GrowlHelper.NotifyType.Reply;
1817                             }
1818                             else
1819                             {
1820                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1821                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1822                                 title.Append(Application.ProductName);
1823                                 title.Append(" ");
1824                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1825                                 nt = GrowlHelper.NotifyType.Notify;
1826                             }
1827                             string bText = sb.ToString();
1828                             if (string.IsNullOrEmpty(bText)) return;
1829
1830                             var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1831                             gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1832                         }
1833                     }
1834                     else
1835                     {
1836                         StringBuilder sb = new StringBuilder();
1837                         bool reply = false;
1838                         bool dm = false;
1839                         foreach (PostClass post in notifyPosts)
1840                         {
1841                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1842                             if (post.IsDm) dm = true;
1843                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1844                             switch (this._cfgCommon.NameBalloon)
1845                             {
1846                                 case MyCommon.NameBalloonEnum.UserID:
1847                                     sb.Append(post.ScreenName).Append(" : ");
1848                                     break;
1849                                 case MyCommon.NameBalloonEnum.NickName:
1850                                     sb.Append(post.Nickname).Append(" : ");
1851                                     break;
1852                             }
1853                             sb.Append(post.TextFromApi);
1854
1855                         }
1856                         //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1857                         StringBuilder title = new StringBuilder();
1858                         ToolTipIcon ntIcon;
1859                         if (this._cfgCommon.DispUsername)
1860                         {
1861                             title.Append(tw.Username);
1862                             title.Append(" - ");
1863                         }
1864                         else
1865                         {
1866                             //title.Clear();
1867                         }
1868                         if (dm)
1869                         {
1870                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1871                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1872                             ntIcon = ToolTipIcon.Warning;
1873                             title.Append(Application.ProductName);
1874                             title.Append(" [DM] ");
1875                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1876                         }
1877                         else if (reply)
1878                         {
1879                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1880                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1881                             ntIcon = ToolTipIcon.Warning;
1882                             title.Append(Application.ProductName);
1883                             title.Append(" [Reply!] ");
1884                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1885                         }
1886                         else
1887                         {
1888                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1889                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1890                             ntIcon = ToolTipIcon.Info;
1891                             title.Append(Application.ProductName);
1892                             title.Append(" ");
1893                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1894                         }
1895                         string bText = sb.ToString();
1896                         if (string.IsNullOrEmpty(bText)) return;
1897                         //NotifyIcon1.BalloonTipText = sb.ToString();
1898                         //NotifyIcon1.ShowBalloonTip(500);
1899                         NotifyIcon1.BalloonTipTitle = title.ToString();
1900                         NotifyIcon1.BalloonTipText = bText;
1901                         NotifyIcon1.BalloonTipIcon = ntIcon;
1902                         NotifyIcon1.ShowBalloonTip(500);
1903                     }
1904                 }
1905             }
1906
1907             //サウンド再生
1908             if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1909             {
1910                 try
1911                 {
1912                     string dir = Application.StartupPath;
1913                     if (Directory.Exists(Path.Combine(dir, "Sounds")))
1914                     {
1915                         dir = Path.Combine(dir, "Sounds");
1916                     }
1917                     using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1918                     {
1919                         player.Play();
1920                     }
1921                 }
1922                 catch (Exception)
1923                 {
1924                 }
1925             }
1926
1927             //mentions新着時に画面ブリンク
1928             if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1929             {
1930                 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1931             }
1932         }
1933
1934         private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1935         {
1936             if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1937
1938             _curItemIndex = _curList.SelectedIndices[0];
1939             if (_curItemIndex > _curList.VirtualListSize - 1) return;
1940
1941             try
1942             {
1943                 this._curPost = GetCurTabPost(_curItemIndex);
1944             }
1945             catch (ArgumentException)
1946             {
1947                 return;
1948             }
1949
1950             this.PushSelectPostChain();
1951
1952             this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1953             //キャッシュの書き換え
1954             ChangeCacheStyleRead(true, _curItemIndex);   //既読へ(フォント、文字色)
1955
1956             ColorizeList();
1957             _colorize = true;
1958         }
1959
1960         private void ChangeCacheStyleRead(bool Read, int Index)
1961         {
1962             var tabInfo = _statuses.Tabs[_curTab.Text];
1963             //Read:true=既読 false=未読
1964             //未読管理していなかったら既読として扱う
1965             if (!tabInfo.UnreadManage ||
1966                !this._cfgCommon.UnreadManage) Read = true;
1967
1968             var listCache = this._listItemCache;
1969             if (listCache == null)
1970                 return;
1971
1972             // キャッシュに含まれていないアイテムは対象外
1973             ListViewItem itm;
1974             PostClass post;
1975             if (!listCache.TryGetValue(Index, out itm, out post))
1976                 return;
1977
1978             ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1979         }
1980
1981         private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1982         {
1983             Font fnt;
1984             //フォント
1985             if (Read)
1986             {
1987                 fnt = _fntReaded;
1988                 Item.SubItems[5].Text = "";
1989             }
1990             else
1991             {
1992                 fnt = _fntUnread;
1993                 Item.SubItems[5].Text = "★";
1994             }
1995             //文字色
1996             Color cl;
1997             if (Post.IsFav)
1998                 cl = _clFav;
1999             else if (Post.RetweetedId != null)
2000                 cl = _clRetweet;
2001             else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
2002                 cl = _clOWL;
2003             else if (Read || !this._cfgCommon.UseUnreadStyle)
2004                 cl = _clReaded;
2005             else
2006                 cl = _clUnread;
2007
2008             if (DList == null || Item.Index == -1)
2009             {
2010                 Item.ForeColor = cl;
2011                 if (this._cfgCommon.UseUnreadStyle)
2012                     Item.Font = fnt;
2013             }
2014             else
2015             {
2016                 DList.Update();
2017                 if (this._cfgCommon.UseUnreadStyle)
2018                     DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2019                 else
2020                     DList.ChangeItemForeColor(Item.Index, cl);
2021                 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2022             }
2023         }
2024
2025         private void ColorizeList()
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             if (_post == null) return;
2036
2037             var listCache = this._listItemCache;
2038             if (listCache == null)
2039                 return;
2040
2041             var index = listCache.StartIndex;
2042             foreach (var cachedPost in listCache.Post)
2043             {
2044                 var backColor = this.JudgeColor(_post, cachedPost);
2045                 this._curList.ChangeItemBackColor(index++, backColor);
2046             }
2047         }
2048
2049         private void ColorizeList(ListViewItem Item, int Index)
2050         {
2051             //Index:更新対象のListviewItem.Index。Colorを返す。
2052             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2053             PostClass _post;
2054             if (_anchorFlag)
2055                 _post = _anchorPost;
2056             else
2057                 _post = _curPost;
2058
2059             PostClass tPost = GetCurTabPost(Index);
2060
2061             if (_post == null) return;
2062
2063             if (Item.Index == -1)
2064                 Item.BackColor = JudgeColor(_post, tPost);
2065             else
2066                 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2067         }
2068
2069         private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2070         {
2071             Color cl;
2072             if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2073                 //@先
2074                 cl = _clAtTo;
2075             else if (TargetPost.IsMe)
2076                 //自分=発言者
2077                 cl = _clSelf;
2078             else if (TargetPost.IsReply)
2079                 //自分宛返信
2080                 cl = _clAtSelf;
2081             else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2082                 //返信先
2083                 cl = _clAtFromTarget;
2084             else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2085                 //その人への返信
2086                 cl = _clAtTarget;
2087             else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2088                 //発言者
2089                 cl = _clTarget;
2090             else
2091                 //その他
2092                 cl = _clListBackcolor;
2093
2094             return cl;
2095         }
2096
2097         private async void PostButton_Click(object sender, EventArgs e)
2098         {
2099             if (StatusText.Text.Trim().Length == 0)
2100             {
2101                 if (!ImageSelector.Enabled)
2102                 {
2103                     await this.DoRefresh();
2104                     return;
2105                 }
2106             }
2107
2108             if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2109             {
2110                 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2111                                                                "Retweet",
2112                                                                MessageBoxButtons.YesNoCancel,
2113                                                                MessageBoxIcon.Question);
2114                 switch (rtResult)
2115                 {
2116                     case DialogResult.Yes:
2117                         StatusText.Text = "";
2118                         await this.doReTweetOfficial(false);
2119                         return;
2120                     case DialogResult.Cancel:
2121                         return;
2122                 }
2123             }
2124
2125             var inReplyToStatusId = this.inReplyTo?.Item1;
2126             var inReplyToScreenName = this.inReplyTo?.Item2;
2127             _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2128
2129             if (this._cfgCommon.Nicoms)
2130             {
2131                 StatusText.SelectionStart = StatusText.Text.Length;
2132                 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2133             }
2134             //if (SettingDialog.UrlConvertAuto)
2135             //{
2136             //    StatusText.SelectionStart = StatusText.Text.Length;
2137             //    UrlConvertAutoToolStripMenuItem_Click(null, null);
2138             //}
2139             //else if (SettingDialog.Nicoms)
2140             //{
2141             //    StatusText.SelectionStart = StatusText.Text.Length;
2142             //    UrlConvert(UrlConverter.Nicoms);
2143             //}
2144             StatusText.SelectionStart = StatusText.Text.Length;
2145             CheckReplyTo(StatusText.Text);
2146
2147             var statusText = this.FormatStatusText(this.StatusText.Text);
2148
2149             if (this.GetRestStatusCount(statusText) < 0)
2150             {
2151                 // 文字数制限を超えているが強制的に投稿するか
2152                 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2153                 if (ret != DialogResult.OK)
2154                     return;
2155             }
2156
2157             var status = new PostingStatus();
2158             status.status = statusText;
2159
2160             status.inReplyToId = this.inReplyTo?.Item1;
2161             status.inReplyToName = this.inReplyTo?.Item2;
2162             if (ImageSelector.Visible)
2163             {
2164                 //画像投稿
2165                 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2166                     return;
2167             }
2168
2169             this.inReplyTo = null;
2170             StatusText.Text = "";
2171             _history.Add(new PostingStatus());
2172             _hisIdx = _history.Count - 1;
2173             if (!ToolStripFocusLockMenuItem.Checked)
2174                 ((Control)ListTab.SelectedTab.Tag).Focus();
2175             urlUndoBuffer = null;
2176             UrlUndoToolStripMenuItem.Enabled = false;  //Undoをできないように設定
2177
2178             //Google検索(試験実装)
2179             if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2180             {
2181                 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2182                 await this.OpenUriInBrowserAsync(tmp);
2183             }
2184
2185             await this.PostMessageAsync(status);
2186         }
2187
2188         private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2189         {
2190             MyCommon._endingFlag = true;
2191             this.Close();
2192         }
2193
2194         private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2195         {
2196             if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2197             {
2198                 //_endingFlag=false:フォームの×ボタン
2199                 e.Cancel = true;
2200                 this.Visible = false;
2201             }
2202             else
2203             {
2204                 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2205                 _ignoreConfigSave = true;
2206                 MyCommon._endingFlag = true;
2207                 TimerTimeline.Enabled = false;
2208                 TimerRefreshIcon.Enabled = false;
2209             }
2210         }
2211
2212         private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2213         {
2214             this.Visible = true;
2215             if (this.WindowState == FormWindowState.Minimized)
2216             {
2217                 this.WindowState = FormWindowState.Normal;
2218             }
2219             this.Activate();
2220             this.BringToFront();
2221         }
2222
2223         private static int errorCount = 0;
2224
2225         private static bool CheckAccountValid()
2226         {
2227             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2228             {
2229                 errorCount += 1;
2230                 if (errorCount > 5)
2231                 {
2232                     errorCount = 0;
2233                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2234                     return true;
2235                 }
2236                 return false;
2237             }
2238             errorCount = 0;
2239             return true;
2240         }
2241
2242         private Task GetHomeTimelineAsync()
2243         {
2244             return this.GetHomeTimelineAsync(loadMore: false);
2245         }
2246
2247         private async Task GetHomeTimelineAsync(bool loadMore)
2248         {
2249             await this.workerSemaphore.WaitAsync();
2250
2251             try
2252             {
2253                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2254
2255                 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2256             }
2257             catch (WebApiException ex)
2258             {
2259                 this._myStatusError = true;
2260                 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2261             }
2262             finally
2263             {
2264                 this.workerSemaphore.Release();
2265             }
2266         }
2267
2268         private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2269         {
2270             if (ct.IsCancellationRequested)
2271                 return;
2272
2273             if (!CheckAccountValid())
2274                 throw new WebApiException("Auth error. Check your account");
2275
2276             bool read;
2277             if (!this._cfgCommon.UnreadManage)
2278                 read = true;
2279             else
2280                 read = this._initial && this._cfgCommon.Read;
2281
2282             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5, loadMore ? -1 : 1));
2283
2284             await Task.Run(async () =>
2285             {
2286                 await this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial)
2287                     .ConfigureAwait(false);
2288
2289                 // 新着時未読クリア
2290                 if (this._cfgCommon.ReadOldPosts)
2291                     this._statuses.SetReadHomeTab();
2292
2293                 var addCount = this._statuses.DistributePosts();
2294
2295                 if (!this._initial)
2296                     this.UpdateTimelineSpeed(addCount);
2297             });
2298
2299             if (ct.IsCancellationRequested)
2300                 return;
2301
2302             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2303
2304             this.RefreshTimeline();
2305         }
2306
2307         /// <summary>
2308         /// タイムラインに追加された発言件数を反映し、タイムラインの流速を更新します
2309         /// </summary>
2310         /// <param name="addCount">直前にタイムラインに追加した発言件数</param>
2311         private void UpdateTimelineSpeed(int addCount)
2312         {
2313             var now = DateTime.Now;
2314             this._tlTimestamps.AddOrUpdate(now, addCount, (k, v) => v + addCount);
2315
2316             var removeKeys = new List<DateTime>();
2317             var oneHour = TimeSpan.FromHours(1);
2318             var tlCount = 0;
2319             foreach (var pair in this._tlTimestamps)
2320             {
2321                 if (now - pair.Key > oneHour)
2322                     removeKeys.Add(pair.Key);
2323                 else
2324                     tlCount += pair.Value;
2325             }
2326             Interlocked.Exchange(ref this._tlCount, tlCount);
2327
2328             int _;
2329             foreach (var key in removeKeys)
2330                 this._tlTimestamps.TryRemove(key, out _);
2331         }
2332
2333         private Task GetReplyAsync()
2334         {
2335             return this.GetReplyAsync(loadMore: false);
2336         }
2337
2338         private async Task GetReplyAsync(bool loadMore)
2339         {
2340             await this.workerSemaphore.WaitAsync();
2341
2342             try
2343             {
2344                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2345
2346                 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2347             }
2348             catch (WebApiException ex)
2349             {
2350                 this._myStatusError = true;
2351                 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2352             }
2353             finally
2354             {
2355                 this.workerSemaphore.Release();
2356             }
2357         }
2358
2359         private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2360         {
2361             if (ct.IsCancellationRequested)
2362                 return;
2363
2364             if (!CheckAccountValid())
2365                 throw new WebApiException("Auth error. Check your account");
2366
2367             bool read;
2368             if (!this._cfgCommon.UnreadManage)
2369                 read = true;
2370             else
2371                 read = this._initial && this._cfgCommon.Read;
2372
2373             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4, loadMore ? -1 : 1));
2374
2375             await Task.Run(async () =>
2376             {
2377                 await this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial)
2378                     .ConfigureAwait(false);
2379
2380                 this._statuses.DistributePosts();
2381             });
2382
2383             if (ct.IsCancellationRequested)
2384                 return;
2385
2386             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2387
2388             this.RefreshTimeline();
2389         }
2390
2391         private Task GetDirectMessagesAsync()
2392         {
2393             return this.GetDirectMessagesAsync(loadMore: false);
2394         }
2395
2396         private async Task GetDirectMessagesAsync(bool loadMore)
2397         {
2398             await this.workerSemaphore.WaitAsync();
2399
2400             try
2401             {
2402                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2403
2404                 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2405             }
2406             catch (WebApiException ex)
2407             {
2408                 this._myStatusError = true;
2409                 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2410             }
2411             finally
2412             {
2413                 this.workerSemaphore.Release();
2414             }
2415         }
2416
2417         private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2418         {
2419             if (ct.IsCancellationRequested)
2420                 return;
2421
2422             if (!CheckAccountValid())
2423                 throw new WebApiException("Auth error. Check your account");
2424
2425             bool read;
2426             if (!this._cfgCommon.UnreadManage)
2427                 read = true;
2428             else
2429                 read = this._initial && this._cfgCommon.Read;
2430
2431             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8, loadMore ? -1 : 1));
2432
2433             await Task.Run(async () =>
2434             {
2435                 await this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore)
2436                     .ConfigureAwait(false);
2437                 await this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore)
2438                     .ConfigureAwait(false);
2439
2440                 this._statuses.DistributePosts();
2441             });
2442
2443             if (ct.IsCancellationRequested)
2444                 return;
2445
2446             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2447
2448             this.RefreshTimeline();
2449         }
2450
2451         private Task GetFavoritesAsync()
2452         {
2453             return this.GetFavoritesAsync(loadMore: false);
2454         }
2455
2456         private async Task GetFavoritesAsync(bool loadMore)
2457         {
2458             await this.workerSemaphore.WaitAsync();
2459
2460             try
2461             {
2462                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2463
2464                 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2465             }
2466             catch (WebApiException ex)
2467             {
2468                 this._myStatusError = true;
2469                 this.StatusLabel.Text = ex.Message;
2470             }
2471             finally
2472             {
2473                 this.workerSemaphore.Release();
2474             }
2475         }
2476
2477         private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2478         {
2479             if (ct.IsCancellationRequested)
2480                 return;
2481
2482             if (!CheckAccountValid())
2483                 throw new WebApiException("Auth error. Check your account");
2484
2485             bool read;
2486             if (!this._cfgCommon.UnreadManage)
2487                 read = true;
2488             else
2489                 read = this._initial && this._cfgCommon.Read;
2490
2491             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2492
2493             await Task.Run(async () =>
2494             {
2495                 await this.tw.GetFavoritesApi(read, loadMore)
2496                     .ConfigureAwait(false);
2497
2498                 this._statuses.DistributePosts();
2499             });
2500
2501             if (ct.IsCancellationRequested)
2502                 return;
2503
2504             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2505
2506             this.RefreshTimeline();
2507         }
2508
2509         private Task GetPublicSearchAllAsync()
2510         {
2511             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch);
2512
2513             return this.GetPublicSearchAsync(tabs, loadMore: false);
2514         }
2515
2516         private Task GetPublicSearchAsync(TabClass tab)
2517         {
2518             return this.GetPublicSearchAsync(tab, loadMore: false);
2519         }
2520
2521         private Task GetPublicSearchAsync(TabClass tab, bool loadMore)
2522         {
2523             return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2524         }
2525
2526         private async Task GetPublicSearchAsync(IEnumerable<TabClass> tabs, bool loadMore)
2527         {
2528             await this.workerSemaphore.WaitAsync();
2529
2530             try
2531             {
2532                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2533
2534                 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2535             }
2536             catch (WebApiException ex)
2537             {
2538                 this._myStatusError = true;
2539                 this.StatusLabel.Text = ex.Message;
2540             }
2541             finally
2542             {
2543                 this.workerSemaphore.Release();
2544             }
2545         }
2546
2547         private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2548         {
2549             if (ct.IsCancellationRequested)
2550                 return;
2551
2552             if (!CheckAccountValid())
2553                 throw new WebApiException("Auth error. Check your account");
2554
2555             bool read;
2556             if (!this._cfgCommon.UnreadManage)
2557                 read = true;
2558             else
2559                 read = this._initial && this._cfgCommon.Read;
2560
2561             p.Report("Search refreshing...");
2562
2563             await Task.Run(async () =>
2564             {
2565                 WebApiException lastException = null;
2566
2567                 foreach (var tab in tabs)
2568                 {
2569                     try
2570                     {
2571                         if (string.IsNullOrEmpty(tab.SearchWords))
2572                             continue;
2573
2574                         await this.tw.GetSearch(read, tab, false)
2575                             .ConfigureAwait(false);
2576
2577                         if (loadMore)
2578                             await this.tw.GetSearch(read, tab, true)
2579                                 .ConfigureAwait(false);
2580                     }
2581                     catch (WebApiException ex)
2582                     {
2583                         lastException = ex;
2584                     }
2585                 }
2586
2587                 this._statuses.DistributePosts();
2588
2589                 if (lastException != null)
2590                     throw new WebApiException(lastException.Message, lastException);
2591             });
2592
2593             if (ct.IsCancellationRequested)
2594                 return;
2595
2596             p.Report("Search refreshed");
2597
2598             this.RefreshTimeline();
2599         }
2600
2601         private Task GetUserTimelineAllAsync()
2602         {
2603             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline);
2604
2605             return this.GetUserTimelineAsync(tabs, loadMore: false);
2606         }
2607
2608         private Task GetUserTimelineAsync(TabClass tab)
2609         {
2610             return this.GetUserTimelineAsync(tab, loadMore: false);
2611         }
2612
2613         private Task GetUserTimelineAsync(TabClass tab, bool loadMore)
2614         {
2615             return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2616         }
2617
2618         private async Task GetUserTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2619         {
2620             await this.workerSemaphore.WaitAsync();
2621
2622             try
2623             {
2624                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2625
2626                 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2627             }
2628             catch (WebApiException ex)
2629             {
2630                 this._myStatusError = true;
2631                 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2632             }
2633             finally
2634             {
2635                 this.workerSemaphore.Release();
2636             }
2637         }
2638
2639         private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2640         {
2641             if (ct.IsCancellationRequested)
2642                 return;
2643
2644             if (!CheckAccountValid())
2645                 throw new WebApiException("Auth error. Check your account");
2646
2647             bool read;
2648             if (!this._cfgCommon.UnreadManage)
2649                 read = true;
2650             else
2651                 read = this._initial && this._cfgCommon.Read;
2652
2653             p.Report("UserTimeline refreshing...");
2654
2655             await Task.Run(async () =>
2656             {
2657                 WebApiException lastException = null;
2658
2659                 foreach (var tab in tabs)
2660                 {
2661                     try
2662                     {
2663                         if (string.IsNullOrEmpty(tab.User))
2664                             continue;
2665
2666                         await this.tw.GetUserTimelineApi(read, tab.User, tab, loadMore)
2667                             .ConfigureAwait(false);
2668                     }
2669                     catch (WebApiException ex)
2670                     {
2671                         lastException = ex;
2672                     }
2673                 }
2674
2675                 this._statuses.DistributePosts();
2676
2677                 if (lastException != null)
2678                     throw new WebApiException(lastException.Message, lastException);
2679             });
2680
2681             if (ct.IsCancellationRequested)
2682                 return;
2683
2684             p.Report("UserTimeline refreshed");
2685
2686             this.RefreshTimeline();
2687         }
2688
2689         private Task GetListTimelineAllAsync()
2690         {
2691             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.Lists);
2692
2693             return this.GetListTimelineAsync(tabs, loadMore: false);
2694         }
2695
2696         private Task GetListTimelineAsync(TabClass tab)
2697         {
2698             return this.GetListTimelineAsync(tab, loadMore: false);
2699         }
2700
2701         private Task GetListTimelineAsync(TabClass tab, bool loadMore)
2702         {
2703             return this.GetListTimelineAsync(new[] { tab }, loadMore);
2704         }
2705
2706         private async Task GetListTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2707         {
2708             await this.workerSemaphore.WaitAsync();
2709
2710             try
2711             {
2712                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2713
2714                 await this.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2715             }
2716             catch (WebApiException ex)
2717             {
2718                 this._myStatusError = true;
2719                 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2720             }
2721             finally
2722             {
2723                 this.workerSemaphore.Release();
2724             }
2725         }
2726
2727         private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2728         {
2729             if (ct.IsCancellationRequested)
2730                 return;
2731
2732             if (!CheckAccountValid())
2733                 throw new WebApiException("Auth error. Check your account");
2734
2735             bool read;
2736             if (!this._cfgCommon.UnreadManage)
2737                 read = true;
2738             else
2739                 read = this._initial && this._cfgCommon.Read;
2740
2741             p.Report("List refreshing...");
2742
2743             await Task.Run(async () =>
2744             {
2745                 WebApiException lastException = null;
2746
2747                 foreach (var tab in tabs)
2748                 {
2749                     try
2750                     {
2751                         if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2752                             continue;
2753
2754                         await this.tw.GetListStatus(read, tab, loadMore, this._initial)
2755                             .ConfigureAwait(false);
2756                     }
2757                     catch (WebApiException ex)
2758                     {
2759                         lastException = ex;
2760                     }
2761                 }
2762
2763                 this._statuses.DistributePosts();
2764
2765                 if (lastException != null)
2766                     throw new WebApiException(lastException.Message, lastException);
2767             });
2768
2769             if (ct.IsCancellationRequested)
2770                 return;
2771
2772             p.Report("List refreshed");
2773
2774             this.RefreshTimeline();
2775         }
2776
2777         private async Task GetRelatedTweetsAsync(TabClass tab)
2778         {
2779             await this.workerSemaphore.WaitAsync();
2780
2781             try
2782             {
2783                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2784
2785                 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2786             }
2787             catch (WebApiException ex)
2788             {
2789                 this._myStatusError = true;
2790                 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2791             }
2792             finally
2793             {
2794                 this.workerSemaphore.Release();
2795             }
2796         }
2797
2798         private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, TabClass tab)
2799         {
2800             if (ct.IsCancellationRequested)
2801                 return;
2802
2803             if (!CheckAccountValid())
2804                 throw new WebApiException("Auth error. Check your account");
2805
2806             bool read;
2807             if (!this._cfgCommon.UnreadManage)
2808                 read = true;
2809             else
2810                 read = this._initial && this._cfgCommon.Read;
2811
2812             p.Report("Related refreshing...");
2813
2814             await Task.Run(async () =>
2815             {
2816                 await this.tw.GetRelatedResult(read, tab)
2817                     .ConfigureAwait(false);
2818
2819                 this._statuses.DistributePosts();
2820             });
2821
2822             if (ct.IsCancellationRequested)
2823                 return;
2824
2825             p.Report("Related refreshed");
2826
2827             this.RefreshTimeline();
2828
2829             var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2830                 .FirstOrDefault(x => x.Text == tab.TabName);
2831
2832             if (tabPage != null)
2833             {
2834                 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2835
2836                 var listView = (DetailsListView)tabPage.Tag;
2837                 var index = tab.IndexOf(tab.RelationTargetPost.RetweetedId ?? tab.RelationTargetPost.StatusId);
2838
2839                 if (index != -1 && index < listView.Items.Count)
2840                 {
2841                     listView.SelectedIndices.Add(index);
2842                     listView.Items[index].Focused = true;
2843                 }
2844             }
2845         }
2846
2847         private async Task FavAddAsync(long statusId, TabClass tab)
2848         {
2849             await this.workerSemaphore.WaitAsync();
2850
2851             try
2852             {
2853                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2854
2855                 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2856             }
2857             catch (WebApiException ex)
2858             {
2859                 this._myStatusError = true;
2860                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2861             }
2862             finally
2863             {
2864                 this.workerSemaphore.Release();
2865             }
2866         }
2867
2868         private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabClass tab)
2869         {
2870             if (ct.IsCancellationRequested)
2871                 return;
2872
2873             if (!CheckAccountValid())
2874                 throw new WebApiException("Auth error. Check your account");
2875
2876             PostClass post;
2877             if (!tab.Posts.TryGetValue(statusId, out post))
2878                 return;
2879
2880             if (post.IsFav)
2881                 return;
2882
2883             await Task.Run(async () =>
2884             {
2885                 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2886
2887                 try
2888                 {
2889                     await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2890                         .IgnoreResponse()
2891                         .ConfigureAwait(false);
2892
2893                     if (this._cfgCommon.RestrictFavCheck)
2894                     {
2895                         var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2896                             .ConfigureAwait(false);
2897
2898                         if (status.Favorited != true)
2899                             throw new WebApiException("NG(Restricted?)");
2900                     }
2901
2902                     this._favTimestamps.Add(DateTime.Now);
2903
2904                     // TLでも取得済みならfav反映
2905                     if (this._statuses.ContainsKey(statusId))
2906                     {
2907                         var postTl = this._statuses[statusId];
2908                         postTl.IsFav = true;
2909
2910                         var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2911                         favTab.AddPostQueue(statusId, postTl.IsRead);
2912                     }
2913
2914                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
2915                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
2916                     {
2917                         if (tb.Contains(statusId))
2918                             tb.Posts[statusId].IsFav = true;
2919                     }
2920
2921                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2922                 }
2923                 catch (WebApiException)
2924                 {
2925                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2926                     throw;
2927                 }
2928
2929                 // 時速表示用
2930                 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2931                 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2932                 {
2933                     if (this._favTimestamps[i] < oneHour)
2934                         this._favTimestamps.RemoveAt(i);
2935                 }
2936
2937                 this._statuses.DistributePosts();
2938             });
2939
2940             if (ct.IsCancellationRequested)
2941                 return;
2942
2943             this.RefreshTimeline();
2944
2945             if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2946             {
2947                 using (ControlTransaction.Update(this._curList))
2948                 {
2949                     var idx = tab.IndexOf(statusId);
2950                     if (idx != -1)
2951                         this.ChangeCacheStyleRead(post.IsRead, idx);
2952                 }
2953
2954                 if (statusId == this._curPost.StatusId)
2955                     await this.DispSelectedPost(true); // 選択アイテム再表示
2956             }
2957         }
2958
2959         private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabClass tab)
2960         {
2961             await this.workerSemaphore.WaitAsync();
2962
2963             try
2964             {
2965                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2966
2967                 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2968             }
2969             catch (WebApiException ex)
2970             {
2971                 this._myStatusError = true;
2972                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2973             }
2974             finally
2975             {
2976                 this.workerSemaphore.Release();
2977             }
2978         }
2979
2980         private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2981         {
2982             if (ct.IsCancellationRequested)
2983                 return;
2984
2985             if (!CheckAccountValid())
2986                 throw new WebApiException("Auth error. Check your account");
2987
2988             var successIds = new List<long>();
2989
2990             await Task.Run(async () =>
2991             {
2992                 //スレッド処理はしない
2993                 var allCount = 0;
2994                 var failedCount = 0;
2995                 foreach (var statusId in statusIds)
2996                 {
2997                     allCount++;
2998
2999                     var post = tab.Posts[statusId];
3000
3001                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
3002
3003                     if (!post.IsFav)
3004                         continue;
3005
3006                     try
3007                     {
3008                         await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
3009                             .IgnoreResponse()
3010                             .ConfigureAwait(false);
3011                     }
3012                     catch (WebApiException)
3013                     {
3014                         failedCount++;
3015                         continue;
3016                     }
3017
3018                     successIds.Add(statusId);
3019                     post.IsFav = false; // リスト再描画必要
3020
3021                     if (this._statuses.ContainsKey(statusId))
3022                     {
3023                         this._statuses[statusId].IsFav = false;
3024                     }
3025
3026                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
3027                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
3028                     {
3029                         if (tb.Contains(statusId))
3030                             tb.Posts[statusId].IsFav = false;
3031                     }
3032                 }
3033             });
3034
3035             if (ct.IsCancellationRequested)
3036                 return;
3037
3038             this.RemovePostFromFavTab(successIds.ToArray());
3039
3040             this.RefreshTimeline();
3041
3042             if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
3043             {
3044                 if (tab.TabType == MyCommon.TabUsageType.Favorites)
3045                 {
3046                     // 色変えは不要
3047                 }
3048                 else
3049                 {
3050                     using (ControlTransaction.Update(this._curList))
3051                     {
3052                         foreach (var statusId in successIds)
3053                         {
3054                             var idx = tab.IndexOf(statusId);
3055                             if (idx == -1)
3056                                 continue;
3057
3058                             var post = tab.Posts[statusId];
3059                             this.ChangeCacheStyleRead(post.IsRead, idx);
3060                         }
3061                     }
3062
3063                     if (successIds.Contains(this._curPost.StatusId))
3064                         await this.DispSelectedPost(true); // 選択アイテム再表示
3065                 }
3066             }
3067         }
3068
3069         private async Task PostMessageAsync(PostingStatus status)
3070         {
3071             await this.workerSemaphore.WaitAsync();
3072
3073             try
3074             {
3075                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3076
3077                 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
3078             }
3079             catch (WebApiException ex)
3080             {
3081                 this._myStatusError = true;
3082                 this.StatusLabel.Text = $"Err:{ex.Message}(PostMessage)";
3083             }
3084             finally
3085             {
3086                 this.workerSemaphore.Release();
3087             }
3088         }
3089
3090         private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
3091         {
3092             if (ct.IsCancellationRequested)
3093                 return;
3094
3095             if (!CheckAccountValid())
3096                 throw new WebApiException("Auth error. Check your account");
3097
3098             p.Report("Posting...");
3099
3100             var errMsg = "";
3101
3102             try
3103             {
3104                 await Task.Run(async () =>
3105                 {
3106                     if (status.mediaItems == null || status.mediaItems.Length == 0)
3107                     {
3108                         await this.tw.PostStatus(status.status, status.inReplyToId)
3109                             .ConfigureAwait(false);
3110                     }
3111                     else
3112                     {
3113                         var service = ImageSelector.GetService(status.imageService);
3114                         await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
3115                             .ConfigureAwait(false);
3116                     }
3117                 });
3118
3119                 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3120             }
3121             catch (WebApiException ex)
3122             {
3123                 // 処理は中断せずエラーの表示のみ行う
3124                 errMsg = $"Err:{ex.Message}(PostMessage)";
3125                 p.Report(errMsg);
3126                 this._myStatusError = true;
3127             }
3128             finally
3129             {
3130                 // 使い終わった MediaItem は破棄する
3131                 if (status.mediaItems != null)
3132                 {
3133                     foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
3134                     {
3135                         disposableItem.Dispose();
3136                     }
3137                 }
3138             }
3139
3140             if (ct.IsCancellationRequested)
3141                 return;
3142
3143             if (!string.IsNullOrEmpty(errMsg) &&
3144                 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
3145                 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
3146             {
3147                 var ret = MessageBox.Show(
3148                     string.Format(
3149                         "{0}   --->   [ " + errMsg + " ]" + Environment.NewLine +
3150                         "\"" + status.status + "\"" + Environment.NewLine +
3151                         "{1}",
3152                         Properties.Resources.StatusUpdateFailed1,
3153                         Properties.Resources.StatusUpdateFailed2),
3154                     "Failed to update status",
3155                     MessageBoxButtons.RetryCancel,
3156                     MessageBoxIcon.Question);
3157
3158                 if (ret == DialogResult.Retry)
3159                 {
3160                     await this.PostMessageAsync(status);
3161                 }
3162                 else
3163                 {
3164                     // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3165                     if (this.ToolStripFocusLockMenuItem.Checked)
3166                         this.StatusText_Enter(this.StatusText, EventArgs.Empty);
3167                 }
3168                 return;
3169             }
3170
3171             this._postTimestamps.Add(DateTime.Now);
3172
3173             var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3174             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3175             {
3176                 if (this._postTimestamps[i] < oneHour)
3177                     this._postTimestamps.RemoveAt(i);
3178             }
3179
3180             if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
3181             {
3182                 this.HashMgr.ClearHashtag();
3183                 this.HashStripSplitButton.Text = "#[-]";
3184                 this.HashToggleMenuItem.Checked = false;
3185                 this.HashToggleToolStripMenuItem.Checked = false;
3186             }
3187
3188             this.SetMainWindowTitle();
3189
3190             if (this._cfgCommon.PostAndGet)
3191             {
3192                 if (this.tw.UserStreamActive)
3193                     this.RefreshTimeline();
3194                 else
3195                     await this.GetHomeTimelineAsync();
3196             }
3197         }
3198
3199         private async Task RetweetAsync(IReadOnlyList<long> statusIds)
3200         {
3201             await this.workerSemaphore.WaitAsync();
3202
3203             try
3204             {
3205                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3206
3207                 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
3208             }
3209             catch (WebApiException ex)
3210             {
3211                 this._myStatusError = true;
3212                 this.StatusLabel.Text = $"Err:{ex.Message}(PostRetweet)";
3213             }
3214             finally
3215             {
3216                 this.workerSemaphore.Release();
3217             }
3218         }
3219
3220         private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
3221         {
3222             if (ct.IsCancellationRequested)
3223                 return;
3224
3225             if (!CheckAccountValid())
3226                 throw new WebApiException("Auth error. Check your account");
3227
3228             bool read;
3229             if (!this._cfgCommon.UnreadManage)
3230                 read = true;
3231             else
3232                 read = this._initial && this._cfgCommon.Read;
3233
3234             p.Report("Posting...");
3235
3236             var retweetTasks = from statusId in statusIds
3237                                select this.tw.PostRetweet(statusId, read);
3238
3239             await Task.WhenAll(retweetTasks)
3240                 .ConfigureAwait(false);
3241
3242             if (ct.IsCancellationRequested)
3243                 return;
3244
3245             p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3246
3247             this._postTimestamps.Add(DateTime.Now);
3248
3249             var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3250             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3251             {
3252                 if (this._postTimestamps[i] < oneHour)
3253                     this._postTimestamps.RemoveAt(i);
3254             }
3255
3256             if (this._cfgCommon.PostAndGet && !this.tw.UserStreamActive)
3257                 await this.GetHomeTimelineAsync();
3258         }
3259
3260         private async Task RefreshFollowerIdsAsync()
3261         {
3262             await this.workerSemaphore.WaitAsync();
3263             try
3264             {
3265                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
3266
3267                 await this.tw.RefreshFollowerIds();
3268
3269                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
3270
3271                 this.RefreshTimeline();
3272                 this.PurgeListViewItemCache();
3273                 this._curList?.Refresh();
3274             }
3275             catch (WebApiException ex)
3276             {
3277                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshFollowersIds)";
3278             }
3279             finally
3280             {
3281                 this.workerSemaphore.Release();
3282             }
3283         }
3284
3285         private async Task RefreshNoRetweetIdsAsync()
3286         {
3287             await this.workerSemaphore.WaitAsync();
3288             try
3289             {
3290                 await this.tw.RefreshNoRetweetIds();
3291
3292                 this.StatusLabel.Text = "NoRetweetIds refreshed";
3293             }
3294             catch (WebApiException ex)
3295             {
3296                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshNoRetweetIds)";
3297             }
3298             finally
3299             {
3300                 this.workerSemaphore.Release();
3301             }
3302         }
3303
3304         private async Task RefreshBlockIdsAsync()
3305         {
3306             await this.workerSemaphore.WaitAsync();
3307             try
3308             {
3309                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
3310
3311                 await this.tw.RefreshBlockIds();
3312
3313                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
3314             }
3315             catch (WebApiException ex)
3316             {
3317                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshBlockIds)";
3318             }
3319             finally
3320             {
3321                 this.workerSemaphore.Release();
3322             }
3323         }
3324
3325         private async Task RefreshTwitterConfigurationAsync()
3326         {
3327             await this.workerSemaphore.WaitAsync();
3328             try
3329             {
3330                 await this.tw.RefreshConfiguration();
3331
3332                 if (this.tw.Configuration.PhotoSizeLimit != 0)
3333                 {
3334                     foreach (var service in this.ImageSelector.GetServices())
3335                     {
3336                         service.UpdateTwitterConfiguration(this.tw.Configuration);
3337                     }
3338                 }
3339
3340                 this.PurgeListViewItemCache();
3341
3342                 this._curList?.Refresh();
3343             }
3344             catch (WebApiException ex)
3345             {
3346                 this.StatusLabel.Text = $"Err:{ex.Message}(RefreshConfiguration)";
3347             }
3348             finally
3349             {
3350                 this.workerSemaphore.Release();
3351             }
3352         }
3353
3354         private async Task RefreshMuteUserIdsAsync()
3355         {
3356             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3357
3358             try
3359             {
3360                 await tw.RefreshMuteUserIdsAsync();
3361             }
3362             catch (WebApiException ex)
3363             {
3364                 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3365                 return;
3366             }
3367
3368             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3369         }
3370
3371         private void RemovePostFromFavTab(Int64[] ids)
3372         {
3373             var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3374             string favTabName = favTab.TabName;
3375             int fidx = 0;
3376             if (_curTab.Text.Equals(favTabName))
3377             {
3378                 fidx = _curList.FocusedItem?.Index ?? _curList.TopItem?.Index ?? 0;
3379             }
3380
3381             foreach (long i in ids)
3382             {
3383                 try
3384                 {
3385                     _statuses.RemoveFavPost(i);
3386                 }
3387                 catch (Exception)
3388                 {
3389                     continue;
3390                 }
3391             }
3392             if (_curTab != null && _curTab.Text.Equals(favTabName))
3393             {
3394                 this.PurgeListViewItemCache();
3395                 _curPost = null;
3396                 //_curItemIndex = -1;
3397             }
3398             foreach (TabPage tp in ListTab.TabPages)
3399             {
3400                 if (tp.Text == favTabName)
3401                 {
3402                     ((DetailsListView)tp.Tag).VirtualListSize = favTab.AllCount;
3403                     break;
3404                 }
3405             }
3406             if (_curTab.Text.Equals(favTabName))
3407             {
3408                 do
3409                 {
3410                     _curList.SelectedIndices.Clear();
3411                 }
3412                 while (_curList.SelectedIndices.Count > 0);
3413
3414                 if (favTab.AllCount > 0)
3415                 {
3416                     if (favTab.AllCount - 1 > fidx && fidx > -1)
3417                     {
3418                         _curList.SelectedIndices.Add(fidx);
3419                     }
3420                     else
3421                     {
3422                         _curList.SelectedIndices.Add(favTab.AllCount - 1);
3423                     }
3424                     if (_curList.SelectedIndices.Count > 0)
3425                     {
3426                         _curList.EnsureVisible(_curList.SelectedIndices[0]);
3427                         _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3428                     }
3429                 }
3430             }
3431         }
3432
3433         private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3434         {
3435             if (e.Button == MouseButtons.Left)
3436             {
3437                 this.Visible = true;
3438                 if (this.WindowState == FormWindowState.Minimized)
3439                 {
3440                     this.WindowState = _formWindowState;
3441                 }
3442                 this.Activate();
3443                 this.BringToFront();
3444             }
3445         }
3446
3447         private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3448         {
3449             switch (this._cfgCommon.ListDoubleClickAction)
3450             {
3451                 case 0:
3452                     MakeReplyOrDirectStatus();
3453                     break;
3454                 case 1:
3455                     await this.FavoriteChange(true);
3456                     break;
3457                 case 2:
3458                     if (_curPost != null)
3459                         await this.ShowUserStatus(_curPost.ScreenName, false);
3460                     break;
3461                 case 3:
3462                     ShowUserTimeline();
3463                     break;
3464                 case 4:
3465                     ShowRelatedStatusesMenuItem_Click(null, null);
3466                     break;
3467                 case 5:
3468                     MoveToHomeToolStripMenuItem_Click(null, null);
3469                     break;
3470                 case 6:
3471                     StatusOpenMenuItem_Click(null, null);
3472                     break;
3473                 case 7:
3474                     //動作なし
3475                     break;
3476             }
3477         }
3478
3479         private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3480         {
3481             await this.FavoriteChange(true);
3482         }
3483
3484         private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3485         {
3486             await this.FavoriteChange(false);
3487         }
3488
3489
3490         private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3491         {
3492             await this.FavoritesRetweetOfficial();
3493         }
3494
3495         private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3496         {
3497             await this.FavoritesRetweetUnofficial();
3498         }
3499
3500         private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3501         {
3502             TabClass tab;
3503             if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3504                 return;
3505
3506             //trueでFavAdd,falseでFavRemove
3507             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3508                 || !this.ExistCurrentPost) return;
3509
3510             if (this._curList.SelectedIndices.Count > 1)
3511             {
3512                 if (FavAdd)
3513                 {
3514                     // 複数ツイートの一括ふぁぼは禁止
3515                     // https://support.twitter.com/articles/76915#favoriting
3516                     MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3517                     _DoFavRetweetFlags = false;
3518                     return;
3519                 }
3520                 else
3521                 {
3522                     if (multiFavoriteChangeDialogEnable)
3523                     {
3524                         var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3525                             Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3526                             MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3527
3528                         if (confirm == DialogResult.Cancel)
3529                             return;
3530                     }
3531                 }
3532             }
3533
3534             if (FavAdd)
3535             {
3536                 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3537                 if (selectedPost.IsFav)
3538                 {
3539                     this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3540                     return;
3541                 }
3542
3543                 await this.FavAddAsync(selectedPost.StatusId, tab);
3544             }
3545             else
3546             {
3547                 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3548                     .Select(x => this.GetCurTabPost(x))
3549                     .Where(x => x.IsFav);
3550
3551                 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3552                 if (statusIds.Length == 0)
3553                 {
3554                     this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3555                     return;
3556                 }
3557
3558                 await this.FavRemoveAsync(statusIds, tab);
3559             }
3560         }
3561
3562         private PostClass GetCurTabPost(int Index)
3563         {
3564             var listCache = this._listItemCache;
3565             if (listCache != null)
3566             {
3567                 ListViewItem item;
3568                 PostClass post;
3569                 if (listCache.TryGetValue(Index, out item, out post))
3570                     return post;
3571             }
3572
3573             return _statuses.Tabs[_curTab.Text][Index];
3574         }
3575
3576         private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3577         {
3578             if (_curList.SelectedIndices.Count > 0)
3579                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3580             else if (_curList.SelectedIndices.Count == 0)
3581                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3582         }
3583
3584         private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3585         {
3586             if (_curList.SelectedIndices.Count > 0)
3587                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3588         }
3589
3590         private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3591         {
3592             if ((!_initialLayout) && this.Visible)
3593             {
3594                 if (this.WindowState == FormWindowState.Normal)
3595                 {
3596                     _mySize = this.ClientSize;
3597                     _mySpDis = this.SplitContainer1.SplitterDistance;
3598                     _mySpDis3 = this.SplitContainer3.SplitterDistance;
3599                     if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3600                     ModifySettingLocal = true;
3601                 }
3602             }
3603         }
3604
3605         private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3606         {
3607             var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3608             if (comparerMode == null)
3609                 return;
3610
3611             this.SetSortColumn(comparerMode.Value);
3612         }
3613
3614         /// <summary>
3615         /// 列インデックスからソートを行う ComparerMode を求める
3616         /// </summary>
3617         /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3618         /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3619         private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3620         {
3621             if (this._iconCol)
3622                 return ComparerMode.Id;
3623
3624             switch (columnIndex)
3625             {
3626                 case 1: // ニックネーム
3627                     return ComparerMode.Nickname;
3628                 case 2: // 本文
3629                     return ComparerMode.Data;
3630                 case 3: // 時刻=発言Id
3631                     return ComparerMode.Id;
3632                 case 4: // 名前
3633                     return ComparerMode.Name;
3634                 case 7: // Source
3635                     return ComparerMode.Source;
3636                 default:
3637                     // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3638                     return null;
3639             }
3640         }
3641
3642         /// <summary>
3643         /// 発言一覧の指定した位置の列でソートする
3644         /// </summary>
3645         /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3646         private void SetSortColumnByDisplayIndex(int columnIndex)
3647         {
3648             // 表示上の列の位置から ColumnHeader を求める
3649             var col = this._curList.Columns.Cast<ColumnHeader>()
3650                 .Where(x => x.DisplayIndex == columnIndex)
3651                 .FirstOrDefault();
3652
3653             if (col == null)
3654                 return;
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         /// 発言一覧の最後列の項目でソートする
3665         /// </summary>
3666         private void SetSortLastColumn()
3667         {
3668             // 表示上の最後列にある ColumnHeader を求める
3669             var col = this._curList.Columns.Cast<ColumnHeader>()
3670                 .OrderByDescending(x => x.DisplayIndex)
3671                 .First();
3672
3673             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3674             if (comparerMode == null)
3675                 return;
3676
3677             this.SetSortColumn(comparerMode.Value);
3678         }
3679
3680         /// <summary>
3681         /// 発言一覧を指定された ComparerMode に基づいてソートする
3682         /// </summary>
3683         private void SetSortColumn(ComparerMode sortColumn)
3684         {
3685             if (this._cfgCommon.SortOrderLock)
3686                 return;
3687
3688             this._statuses.ToggleSortOrder(sortColumn);
3689             this.InitColumnText();
3690
3691             var list = this._curList;
3692             if (_iconCol)
3693             {
3694                 list.Columns[0].Text = this.ColumnText[0];
3695                 list.Columns[1].Text = this.ColumnText[2];
3696             }
3697             else
3698             {
3699                 for (var i = 0; i <= 7; i++)
3700                 {
3701                     list.Columns[i].Text = this.ColumnText[i];
3702                 }
3703             }
3704
3705             this.PurgeListViewItemCache();
3706
3707             var tab = this._statuses.Tabs[this._curTab.Text];
3708             if (tab.AllCount > 0 && this._curPost != null)
3709             {
3710                 var idx = tab.IndexOf(this._curPost.StatusId);
3711                 if (idx > -1)
3712                 {
3713                     this.SelectListItem(list, idx);
3714                     list.EnsureVisible(idx);
3715                 }
3716             }
3717             list.Refresh();
3718
3719             this.ModifySettingCommon = true;
3720         }
3721
3722         private void TweenMain_LocationChanged(object sender, EventArgs e)
3723         {
3724             if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3725             {
3726                 _myLoc = this.DesktopLocation;
3727                 ModifySettingLocal = true;
3728             }
3729         }
3730
3731         private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3732         {
3733             if (ListTab.SelectedTab == null) return;
3734             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3735             if (!this.ExistCurrentPost)
3736             {
3737                 ReplyStripMenuItem.Enabled = false;
3738                 ReplyAllStripMenuItem.Enabled = false;
3739                 DMStripMenuItem.Enabled = false;
3740                 ShowProfileMenuItem.Enabled = false;
3741                 ShowUserTimelineContextMenuItem.Enabled = false;
3742                 ListManageUserContextToolStripMenuItem2.Enabled = false;
3743                 MoveToFavToolStripMenuItem.Enabled = false;
3744                 TabMenuItem.Enabled = false;
3745                 IDRuleMenuItem.Enabled = false;
3746                 SourceRuleMenuItem.Enabled = false;
3747                 ReadedStripMenuItem.Enabled = false;
3748                 UnreadStripMenuItem.Enabled = false;
3749             }
3750             else
3751             {
3752                 ShowProfileMenuItem.Enabled = true;
3753                 ListManageUserContextToolStripMenuItem2.Enabled = true;
3754                 ReplyStripMenuItem.Enabled = true;
3755                 ReplyAllStripMenuItem.Enabled = true;
3756                 DMStripMenuItem.Enabled = true;
3757                 ShowUserTimelineContextMenuItem.Enabled = true;
3758                 MoveToFavToolStripMenuItem.Enabled = true;
3759                 TabMenuItem.Enabled = true;
3760                 IDRuleMenuItem.Enabled = true;
3761                 SourceRuleMenuItem.Enabled = true;
3762                 ReadedStripMenuItem.Enabled = true;
3763                 UnreadStripMenuItem.Enabled = true;
3764             }
3765             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3766             {
3767                 FavAddToolStripMenuItem.Enabled = false;
3768                 FavRemoveToolStripMenuItem.Enabled = false;
3769                 StatusOpenMenuItem.Enabled = false;
3770                 FavorareMenuItem.Enabled = false;
3771                 ShowRelatedStatusesMenuItem.Enabled = false;
3772
3773                 ReTweetStripMenuItem.Enabled = false;
3774                 ReTweetUnofficialStripMenuItem.Enabled = false;
3775                 QuoteStripMenuItem.Enabled = false;
3776                 FavoriteRetweetContextMenu.Enabled = false;
3777                 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3778             }
3779             else
3780             {
3781                 FavAddToolStripMenuItem.Enabled = true;
3782                 FavRemoveToolStripMenuItem.Enabled = true;
3783                 StatusOpenMenuItem.Enabled = true;
3784                 FavorareMenuItem.Enabled = true;
3785                 ShowRelatedStatusesMenuItem.Enabled = true;  //PublicSearchの時問題出るかも
3786
3787                 if (_curPost.IsMe)
3788                 {
3789                     ReTweetStripMenuItem.Enabled = false;  //公式RTは無効に
3790                     ReTweetUnofficialStripMenuItem.Enabled = true;
3791                     QuoteStripMenuItem.Enabled = true;
3792                     FavoriteRetweetContextMenu.Enabled = false;  //公式RTは無効に
3793                     FavoriteRetweetUnofficialContextMenu.Enabled = true;
3794                 }
3795                 else
3796                 {
3797                     if (_curPost.IsProtect)
3798                     {
3799                         ReTweetStripMenuItem.Enabled = false;
3800                         ReTweetUnofficialStripMenuItem.Enabled = false;
3801                         QuoteStripMenuItem.Enabled = false;
3802                         FavoriteRetweetContextMenu.Enabled = false;
3803                         FavoriteRetweetUnofficialContextMenu.Enabled = false;
3804                     }
3805                     else
3806                     {
3807                         ReTweetStripMenuItem.Enabled = true;
3808                         ReTweetUnofficialStripMenuItem.Enabled = true;
3809                         QuoteStripMenuItem.Enabled = true;
3810                         FavoriteRetweetContextMenu.Enabled = true;
3811                         FavoriteRetweetUnofficialContextMenu.Enabled = true;
3812                     }
3813                 }
3814             }
3815             //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3816             //{
3817             //    RefreshMoreStripMenuItem.Enabled = true;
3818             //}
3819             //else
3820             //{
3821             //    RefreshMoreStripMenuItem.Enabled = false;
3822             //}
3823             if (!this.ExistCurrentPost
3824                 || _curPost.InReplyToStatusId == null)
3825             {
3826                 RepliedStatusOpenMenuItem.Enabled = false;
3827             }
3828             else
3829             {
3830                 RepliedStatusOpenMenuItem.Enabled = true;
3831             }
3832             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3833             {
3834                 MoveToRTHomeMenuItem.Enabled = false;
3835             }
3836             else
3837             {
3838                 MoveToRTHomeMenuItem.Enabled = true;
3839             }
3840
3841             if (this.ExistCurrentPost)
3842             {
3843                 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3844                 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3845                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3846                 else
3847                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3848             }
3849         }
3850
3851         private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3852         {
3853             MakeReplyOrDirectStatus(false, true);
3854         }
3855
3856         private void DMStripMenuItem_Click(object sender, EventArgs e)
3857         {
3858             MakeReplyOrDirectStatus(false, false);
3859         }
3860
3861         private async Task doStatusDelete()
3862         {
3863             if (this._curTab == null || this._curList == null)
3864                 return;
3865
3866             if (this._curList.SelectedIndices.Count == 0)
3867                 return;
3868
3869             var posts = this._curList.SelectedIndices.Cast<int>()
3870                 .Select(x => this.GetCurTabPost(x))
3871                 .ToArray();
3872
3873             // 選択されたツイートの中に削除可能なものが一つでもあるか
3874             if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3875                 return;
3876
3877             var ret = MessageBox.Show(this,
3878                 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3879                 Properties.Resources.DeleteStripMenuItem_ClickText2,
3880                 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3881
3882             if (ret != DialogResult.OK)
3883                 return;
3884
3885             var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3886
3887             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3888             {
3889                 Exception lastException = null;
3890                 foreach (var post in posts)
3891                 {
3892                     if (!post.CanDeleteBy(this.tw.UserId))
3893                         continue;
3894
3895                     try
3896                     {
3897                         if (post.IsDm)
3898                         {
3899                             await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3900                                 .IgnoreResponse();
3901                         }
3902                         else
3903                         {
3904                             if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3905                                 // 他人に RT された自分のツイート
3906                                 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3907                                     .IgnoreResponse();
3908                             else
3909                                 // 自分のツイート or 自分が RT したツイート
3910                                 await this.twitterApi.StatusesDestroy(post.StatusId)
3911                                     .IgnoreResponse();
3912                         }
3913                     }
3914                     catch (WebApiException ex)
3915                     {
3916                         lastException = ex;
3917                         continue;
3918                     }
3919
3920                     this._statuses.RemovePost(post.StatusId);
3921                 }
3922
3923                 if (lastException == null)
3924                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3925                 else
3926                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3927
3928                 this.PurgeListViewItemCache();
3929                 this._curPost = null;
3930                 this._curItemIndex = -1;
3931
3932                 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3933                 {
3934                     var listView = (DetailsListView)tabPage.Tag;
3935                     var tab = this._statuses.Tabs[tabPage.Text];
3936
3937                     using (ControlTransaction.Update(listView))
3938                     {
3939                         listView.VirtualListSize = tab.AllCount;
3940
3941                         if (tabPage == this._curTab)
3942                         {
3943                             listView.SelectedIndices.Clear();
3944
3945                             if (tab.AllCount != 0)
3946                             {
3947                                 int selectedIndex;
3948                                 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3949                                     selectedIndex = focusedIndex;
3950                                 else
3951                                     selectedIndex = tab.AllCount - 1;
3952
3953                                 listView.SelectedIndices.Add(selectedIndex);
3954                                 listView.EnsureVisible(selectedIndex);
3955                                 listView.FocusedItem = listView.Items[selectedIndex];
3956                             }
3957                         }
3958                     }
3959
3960                     if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3961                     {
3962                         if (tabPage.ImageIndex == 0)
3963                             tabPage.ImageIndex = -1; // タブアイコン
3964                     }
3965                 }
3966
3967                 if (!this._cfgCommon.TabIconDisp)
3968                     this.ListTab.Refresh();
3969             }
3970         }
3971
3972         private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3973         {
3974             await this.doStatusDelete();
3975         }
3976
3977         private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3978         {
3979             using (ControlTransaction.Update(this._curList))
3980             {
3981                 foreach (int idx in _curList.SelectedIndices)
3982                 {
3983                     var post = this._statuses.Tabs[this._curTab.Text][idx];
3984                     this._statuses.SetReadAllTab(post.StatusId, read: true);
3985                     ChangeCacheStyleRead(true, idx);
3986                 }
3987                 ColorizeList();
3988             }
3989             foreach (TabPage tb in ListTab.TabPages)
3990             {
3991                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3992                 {
3993                     if (this._cfgCommon.TabIconDisp)
3994                     {
3995                         if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3996                     }
3997                 }
3998             }
3999             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
4000         }
4001
4002         private void UnreadStripMenuItem_Click(object sender, EventArgs e)
4003         {
4004             using (ControlTransaction.Update(this._curList))
4005             {
4006                 foreach (int idx in _curList.SelectedIndices)
4007                 {
4008                     var post = this._statuses.Tabs[this._curTab.Text][idx];
4009                     this._statuses.SetReadAllTab(post.StatusId, read: false);
4010                     ChangeCacheStyleRead(false, idx);
4011                 }
4012                 ColorizeList();
4013             }
4014             foreach (TabPage tb in ListTab.TabPages)
4015             {
4016                 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
4017                 {
4018                     if (this._cfgCommon.TabIconDisp)
4019                     {
4020                         if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
4021                     }
4022                 }
4023             }
4024             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
4025         }
4026
4027         private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
4028         {
4029             await this.DoRefresh();
4030         }
4031
4032         private async Task DoRefresh()
4033         {
4034             if (_curTab != null)
4035             {
4036                 TabClass tab;
4037                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4038                     return;
4039
4040                 switch (_statuses.Tabs[_curTab.Text].TabType)
4041                 {
4042                     case MyCommon.TabUsageType.Mentions:
4043                         await this.GetReplyAsync();
4044                         break;
4045                     case MyCommon.TabUsageType.DirectMessage:
4046                         await this.GetDirectMessagesAsync();
4047                         break;
4048                     case MyCommon.TabUsageType.Favorites:
4049                         await this.GetFavoritesAsync();
4050                         break;
4051                     //case MyCommon.TabUsageType.Profile:
4052                         //// TODO
4053                     case MyCommon.TabUsageType.PublicSearch:
4054                         //// TODO
4055                         if (string.IsNullOrEmpty(tab.SearchWords)) return;
4056                         await this.GetPublicSearchAsync(tab);
4057                         break;
4058                     case MyCommon.TabUsageType.UserTimeline:
4059                         await this.GetUserTimelineAsync(tab);
4060                         break;
4061                     case MyCommon.TabUsageType.Lists:
4062                         //// TODO
4063                         if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4064                         await this.GetListTimelineAsync(tab);
4065                         break;
4066                     default:
4067                         await this.GetHomeTimelineAsync();
4068                         break;
4069                 }
4070             }
4071             else
4072             {
4073                 await this.GetHomeTimelineAsync();
4074             }
4075         }
4076
4077         private async Task DoRefreshMore()
4078         {
4079             //ページ指定をマイナス1に
4080             if (_curTab != null)
4081             {
4082                 TabClass tab;
4083                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4084                     return;
4085
4086                 switch (_statuses.Tabs[_curTab.Text].TabType)
4087                 {
4088                     case MyCommon.TabUsageType.Mentions:
4089                         await this.GetReplyAsync(loadMore: true);
4090                         break;
4091                     case MyCommon.TabUsageType.DirectMessage:
4092                         await this.GetDirectMessagesAsync(loadMore: true);
4093                         break;
4094                     case MyCommon.TabUsageType.Favorites:
4095                         await this.GetFavoritesAsync(loadMore: true);
4096                         break;
4097                     case MyCommon.TabUsageType.Profile:
4098                         //// TODO
4099                         break;
4100                     case MyCommon.TabUsageType.PublicSearch:
4101                         // TODO
4102                         if (string.IsNullOrEmpty(tab.SearchWords)) return;
4103                         await this.GetPublicSearchAsync(tab, loadMore: true);
4104                         break;
4105                     case MyCommon.TabUsageType.UserTimeline:
4106                         await this.GetUserTimelineAsync(tab, loadMore: true);
4107                         break;
4108                     case MyCommon.TabUsageType.Lists:
4109                         //// TODO
4110                         if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4111                         await this.GetListTimelineAsync(tab, loadMore: true);
4112                         break;
4113                     default:
4114                         await this.GetHomeTimelineAsync(loadMore: true);
4115                         break;
4116                 }
4117             }
4118             else
4119             {
4120                 await this.GetHomeTimelineAsync(loadMore: true);
4121             }
4122         }
4123
4124         private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4125         {
4126             DialogResult result = DialogResult.Abort;
4127
4128             using (var settingDialog = new AppendSettingDialog())
4129             {
4130                 settingDialog.Icon = this.MainIcon;
4131                 settingDialog.Owner = this;
4132                 settingDialog.ShowInTaskbar = showTaskbarIcon;
4133                 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4134
4135                 settingDialog.tw = this.tw;
4136                 settingDialog.twitterApi = this.twitterApi;
4137
4138                 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4139
4140                 try
4141                 {
4142                     result = settingDialog.ShowDialog(this);
4143                 }
4144                 catch (Exception)
4145                 {
4146                     return DialogResult.Abort;
4147                 }
4148
4149                 if (result == DialogResult.OK)
4150                 {
4151                     lock (_syncObject)
4152                     {
4153                         settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4154                     }
4155                 }
4156             }
4157
4158             return result;
4159         }
4160
4161         private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4162         {
4163             // 設定画面表示前のユーザー情報
4164             var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4165
4166             var oldIconSz = this._cfgCommon.IconSize;
4167
4168             if (ShowSettingDialog() == DialogResult.OK)
4169             {
4170                 lock (_syncObject)
4171                 {
4172                     tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4173                     tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4174                     ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4175                     ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4176                     ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4177                     TwitterApiConnection.RestApiBase = new Uri(this._cfgCommon.TwitterUrl);
4178
4179                     Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4180                     Networking.SetWebProxy(this._cfgLocal.ProxyType,
4181                         this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4182                         this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4183                     Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
4184
4185                     ImageSelector.Reset(tw, this.tw.Configuration);
4186
4187                     try
4188                     {
4189                         if (this._cfgCommon.TabIconDisp)
4190                         {
4191                             ListTab.DrawItem -= ListTab_DrawItem;
4192                             ListTab.DrawMode = TabDrawMode.Normal;
4193                             ListTab.ImageList = this.TabImage;
4194                         }
4195                         else
4196                         {
4197                             ListTab.DrawItem -= ListTab_DrawItem;
4198                             ListTab.DrawItem += ListTab_DrawItem;
4199                             ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4200                             ListTab.ImageList = null;
4201                         }
4202                     }
4203                     catch (Exception ex)
4204                     {
4205                         ex.Data["Instance"] = "ListTab(TabIconDisp)";
4206                         ex.Data["IsTerminatePermission"] = false;
4207                         throw;
4208                     }
4209
4210                     try
4211                     {
4212                         if (!this._cfgCommon.UnreadManage)
4213                         {
4214                             ReadedStripMenuItem.Enabled = false;
4215                             UnreadStripMenuItem.Enabled = false;
4216                             if (this._cfgCommon.TabIconDisp)
4217                             {
4218                                 foreach (TabPage myTab in ListTab.TabPages)
4219                                 {
4220                                     myTab.ImageIndex = -1;
4221                                 }
4222                             }
4223                         }
4224                         else
4225                         {
4226                             ReadedStripMenuItem.Enabled = true;
4227                             UnreadStripMenuItem.Enabled = true;
4228                         }
4229                     }
4230                     catch (Exception ex)
4231                     {
4232                         ex.Data["Instance"] = "ListTab(UnreadManage)";
4233                         ex.Data["IsTerminatePermission"] = false;
4234                         throw;
4235                     }
4236
4237                     // タブの表示位置の決定
4238                     SetTabAlignment();
4239
4240                     SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4241
4242                     var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4243                     imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4244                     imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4245
4246                     this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4247                     this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4248                     _fntUnread = this._cfgLocal.FontUnread;
4249                     _clUnread = this._cfgLocal.ColorUnread;
4250                     _fntReaded = this._cfgLocal.FontRead;
4251                     _clReaded = this._cfgLocal.ColorRead;
4252                     _clFav = this._cfgLocal.ColorFav;
4253                     _clOWL = this._cfgLocal.ColorOWL;
4254                     _clRetweet = this._cfgLocal.ColorRetweet;
4255                     _fntDetail = this._cfgLocal.FontDetail;
4256                     _clDetail = this._cfgLocal.ColorDetail;
4257                     _clDetailLink = this._cfgLocal.ColorDetailLink;
4258                     _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4259                     _clSelf = this._cfgLocal.ColorSelf;
4260                     _clAtSelf = this._cfgLocal.ColorAtSelf;
4261                     _clTarget = this._cfgLocal.ColorTarget;
4262                     _clAtTarget = this._cfgLocal.ColorAtTarget;
4263                     _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4264                     _clAtTo = this._cfgLocal.ColorAtTo;
4265                     _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4266                     _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4267                     _clInputFont = this._cfgLocal.ColorInputFont;
4268                     _fntInputFont = this._cfgLocal.FontInputFont;
4269                     _brsBackColorMine.Dispose();
4270                     _brsBackColorAt.Dispose();
4271                     _brsBackColorYou.Dispose();
4272                     _brsBackColorAtYou.Dispose();
4273                     _brsBackColorAtFromTarget.Dispose();
4274                     _brsBackColorAtTo.Dispose();
4275                     _brsBackColorNone.Dispose();
4276                     _brsBackColorMine = new SolidBrush(_clSelf);
4277                     _brsBackColorAt = new SolidBrush(_clAtSelf);
4278                     _brsBackColorYou = new SolidBrush(_clTarget);
4279                     _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4280                     _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4281                     _brsBackColorAtTo = new SolidBrush(_clAtTo);
4282                     _brsBackColorNone = new SolidBrush(_clListBackcolor);
4283
4284                     try
4285                     {
4286                         if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4287                         StatusText.Font = _fntInputFont;
4288                         StatusText.ForeColor = _clInputFont;
4289                     }
4290                     catch (Exception ex)
4291                     {
4292                         MessageBox.Show(ex.Message);
4293                     }
4294
4295                     try
4296                     {
4297                         InitDetailHtmlFormat();
4298                     }
4299                     catch (Exception ex)
4300                     {
4301                         ex.Data["Instance"] = "Font";
4302                         ex.Data["IsTerminatePermission"] = false;
4303                         throw;
4304                     }
4305
4306                     try
4307                     {
4308                         foreach (TabPage tb in ListTab.TabPages)
4309                         {
4310                             if (this._cfgCommon.TabIconDisp)
4311                             {
4312                                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4313                                     tb.ImageIndex = -1;
4314                                 else
4315                                     tb.ImageIndex = 0;
4316                             }
4317                         }
4318                     }
4319                     catch (Exception ex)
4320                     {
4321                         ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4322                         ex.Data["IsTerminatePermission"] = false;
4323                         throw;
4324                     }
4325
4326                     try
4327                     {
4328                         var oldIconCol = _iconCol;
4329
4330                         if (this._cfgCommon.IconSize != oldIconSz)
4331                             ApplyListViewIconSize(this._cfgCommon.IconSize);
4332
4333                         foreach (TabPage tp in ListTab.TabPages)
4334                         {
4335                             DetailsListView lst = (DetailsListView)tp.Tag;
4336
4337                             using (ControlTransaction.Update(lst))
4338                             {
4339                                 lst.GridLines = this._cfgCommon.ShowGrid;
4340                                 lst.Font = _fntReaded;
4341                                 lst.BackColor = _clListBackcolor;
4342
4343                                 if (_iconCol != oldIconCol)
4344                                     ResetColumns(lst);
4345                             }
4346                         }
4347                     }
4348                     catch (Exception ex)
4349                     {
4350                         ex.Data["Instance"] = "ListView(IconSize)";
4351                         ex.Data["IsTerminatePermission"] = false;
4352                         throw;
4353                     }
4354
4355                     SetMainWindowTitle();
4356                     SetNotifyIconText();
4357
4358                     this.PurgeListViewItemCache();
4359                     _curList?.Refresh();
4360                     ListTab.Refresh();
4361
4362                     _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4363                     if (this._cfgCommon.HotkeyEnabled)
4364                     {
4365                         ///グローバルホットキーの登録。設定で変更可能にするかも
4366                         HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4367                         if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4368                             modKey |= HookGlobalHotkey.ModKeys.Alt;
4369                         if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4370                             modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4371                         if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4372                             modKey |=  HookGlobalHotkey.ModKeys.Shift;
4373                         if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4374                             modKey |= HookGlobalHotkey.ModKeys.Win;
4375
4376                         _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4377                     }
4378
4379                     if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4380                     try
4381                     {
4382                         StatusText_TextChanged(null, null);
4383                     }
4384                     catch (Exception)
4385                     {
4386                     }
4387                 }
4388             }
4389             else
4390             {
4391                 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4392                 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4393             }
4394
4395             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4396
4397             this.TopMost = this._cfgCommon.AlwaysTop;
4398             SaveConfigsAll(false);
4399
4400             if (tw.Username != oldUser.Username)
4401                 await this.doGetFollowersMenu();
4402         }
4403
4404         /// <summary>
4405         /// タブの表示位置を設定する
4406         /// </summary>
4407         private void SetTabAlignment()
4408         {
4409             var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4410             if (ListTab.Alignment == newAlignment) return;
4411
4412             // 各タブのリスト上の選択位置などを退避
4413             var listSelections = this.SaveListViewSelection();
4414
4415             ListTab.Alignment = newAlignment;
4416
4417             foreach (TabPage tab in ListTab.TabPages)
4418             {
4419                 DetailsListView lst = (DetailsListView)tab.Tag;
4420                 TabClass tabInfo = _statuses.Tabs[tab.Text];
4421                 using (ControlTransaction.Update(lst))
4422                 {
4423                     // 選択位置などを復元
4424                     this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4425                 }
4426             }
4427         }
4428
4429         private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4430         {
4431             // アイコンサイズの再設定
4432             _iconCol = false;
4433             switch (iconSz)
4434             {
4435                 case MyCommon.IconSizes.IconNone:
4436                     _iconSz = 0;
4437                     break;
4438                 case MyCommon.IconSizes.Icon16:
4439                     _iconSz = 16;
4440                     break;
4441                 case MyCommon.IconSizes.Icon24:
4442                     _iconSz = 26;
4443                     break;
4444                 case MyCommon.IconSizes.Icon48:
4445                     _iconSz = 48;
4446                     break;
4447                 case MyCommon.IconSizes.Icon48_2:
4448                     _iconSz = 48;
4449                     _iconCol = true;
4450                     break;
4451             }
4452
4453             if (_iconSz > 0)
4454             {
4455                 // ディスプレイの DPI 設定を考慮したサイズを設定する
4456                 _listViewImageList.ImageSize = new Size(
4457                     1,
4458                     (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4459             }
4460             else
4461             {
4462                 _listViewImageList.ImageSize = new Size(1, 1);
4463             }
4464         }
4465
4466         private void ResetColumns(DetailsListView list)
4467         {
4468             using (ControlTransaction.Update(list))
4469             using (ControlTransaction.Layout(list, false))
4470             {
4471                 // カラムヘッダの再設定
4472                 list.ColumnClick -= MyList_ColumnClick;
4473                 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4474                 list.ColumnReordered -= MyList_ColumnReordered;
4475                 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4476
4477                 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4478                 list.Columns.Clear();
4479                 cols.ForEach(col => col.Dispose());
4480                 cols.Clear();
4481
4482                 InitColumns(list, true);
4483
4484                 list.ColumnClick += MyList_ColumnClick;
4485                 list.DrawColumnHeader += MyList_DrawColumnHeader;
4486                 list.ColumnReordered += MyList_ColumnReordered;
4487                 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4488             }
4489         }
4490
4491         private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4492         {
4493             if (e.Url.AbsoluteUri != "about:blank")
4494             {
4495                 await this.DispSelectedPost();
4496                 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4497             }
4498         }
4499
4500         private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4501         {
4502             if (e.Url.Scheme == "data")
4503             {
4504                 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4505             }
4506             else if (e.Url.AbsoluteUri != "about:blank")
4507             {
4508                 e.Cancel = true;
4509                 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4510                 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4511             }
4512         }
4513
4514         public void AddNewTabForSearch(string searchWord)
4515         {
4516             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4517             foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4518             {
4519                 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4520                 {
4521                     foreach (TabPage tp in ListTab.TabPages)
4522                     {
4523                         if (tb.TabName == tp.Text)
4524                         {
4525                             ListTab.SelectedTab = tp;
4526                             return;
4527                         }
4528                     }
4529                 }
4530             }
4531             //ユニークなタブ名生成
4532             string tabName = searchWord;
4533             for (int i = 0; i <= 100; i++)
4534             {
4535                 if (_statuses.ContainsTab(tabName))
4536                     tabName += "_";
4537                 else
4538                     break;
4539             }
4540             //タブ追加
4541             _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4542             AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4543             //追加したタブをアクティブに
4544             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4545             //検索条件の設定
4546             ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4547             cmb.Items.Add(searchWord);
4548             cmb.Text = searchWord;
4549             SaveConfigsTabs();
4550             //検索実行
4551             this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4552         }
4553
4554         private void ShowUserTimeline()
4555         {
4556             if (!this.ExistCurrentPost) return;
4557             AddNewTabForUserTimeline(_curPost.ScreenName);
4558         }
4559
4560         private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4561         {
4562             if (e.KeyCode == Keys.Escape)
4563             {
4564                 TabPage relTp = ListTab.SelectedTab;
4565                 RemoveSpecifiedTab(relTp.Text, false);
4566                 SaveConfigsTabs();
4567                 e.SuppressKeyPress = true;
4568             }
4569         }
4570
4571         public void AddNewTabForUserTimeline(string user)
4572         {
4573             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4574             foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4575             {
4576                 if (tb.User == user)
4577                 {
4578                     foreach (TabPage tp in ListTab.TabPages)
4579                     {
4580                         if (tb.TabName == tp.Text)
4581                         {
4582                             ListTab.SelectedTab = tp;
4583                             return;
4584                         }
4585                     }
4586                 }
4587             }
4588             //ユニークなタブ名生成
4589             string tabName = "user:" + user;
4590             while (_statuses.ContainsTab(tabName))
4591             {
4592                 tabName += "_";
4593             }
4594             //タブ追加
4595             _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4596             var tab = this._statuses.Tabs[tabName];
4597             tab.User = user;
4598             AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4599             //追加したタブをアクティブに
4600             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4601             SaveConfigsTabs();
4602             //検索実行
4603             this.GetUserTimelineAsync(tab);
4604         }
4605
4606         public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4607         {
4608             //重複チェック
4609             foreach (TabPage tb in ListTab.TabPages)
4610             {
4611                 if (tb.Text == tabName) return false;
4612             }
4613
4614             //新規タブ名チェック
4615             if (tabName == Properties.Resources.AddNewTabText1) return false;
4616
4617             //タブタイプ重複チェック
4618             if (!startup)
4619             {
4620                 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4621                    tabType == MyCommon.TabUsageType.Favorites ||
4622                    tabType == MyCommon.TabUsageType.Home ||
4623                    tabType == MyCommon.TabUsageType.Mentions ||
4624                    tabType == MyCommon.TabUsageType.Related)
4625                 {
4626                     if (_statuses.GetTabByType(tabType) != null) return false;
4627                 }
4628             }
4629
4630             var _tabPage = new TabPage();
4631             var _listCustom = new DetailsListView();
4632
4633             int cnt = ListTab.TabPages.Count;
4634
4635             ///ToDo:Create and set controls follow tabtypes
4636
4637             using (ControlTransaction.Update(_listCustom))
4638             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4639             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4640             using (ControlTransaction.Layout(this.SplitContainer1, false))
4641             using (ControlTransaction.Layout(this.ListTab, false))
4642             using (ControlTransaction.Layout(this))
4643             using (ControlTransaction.Layout(_tabPage, false))
4644             {
4645                 _tabPage.Controls.Add(_listCustom);
4646
4647                 /// UserTimeline関連
4648                 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4649                 {
4650                     var label = new Label();
4651                     label.Dock = DockStyle.Top;
4652                     label.Name = "labelUser";
4653                     label.TabIndex = 0;
4654                     if (tabType == MyCommon.TabUsageType.Lists)
4655                     {
4656                         label.Text = listInfo.ToString();
4657                     }
4658                     else
4659                     {
4660                         label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4661                     }
4662                     label.TextAlign = ContentAlignment.MiddleLeft;
4663                     using (ComboBox tmpComboBox = new ComboBox())
4664                     {
4665                         label.Height = tmpComboBox.Height;
4666                     }
4667                     _tabPage.Controls.Add(label);
4668                 }
4669                 /// 検索関連の準備
4670                 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4671                 {
4672                     var pnl = new Panel();
4673
4674                     var lbl = new Label();
4675                     var cmb = new ComboBox();
4676                     var btn = new Button();
4677                     var cmbLang = new ComboBox();
4678
4679                     using (ControlTransaction.Layout(pnl, false))
4680                     {
4681                         pnl.Controls.Add(cmb);
4682                         pnl.Controls.Add(cmbLang);
4683                         pnl.Controls.Add(btn);
4684                         pnl.Controls.Add(lbl);
4685                         pnl.Name = "panelSearch";
4686                         pnl.TabIndex = 0;
4687                         pnl.Dock = DockStyle.Top;
4688                         pnl.Height = cmb.Height;
4689                         pnl.Enter += SearchControls_Enter;
4690                         pnl.Leave += SearchControls_Leave;
4691
4692                         cmb.Text = "";
4693                         cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4694                         cmb.Dock = DockStyle.Fill;
4695                         cmb.Name = "comboSearch";
4696                         cmb.DropDownStyle = ComboBoxStyle.DropDown;
4697                         cmb.ImeMode = ImeMode.NoControl;
4698                         cmb.TabStop = false;
4699                         cmb.TabIndex = 1;
4700                         cmb.AutoCompleteMode = AutoCompleteMode.None;
4701                         cmb.KeyDown += SearchComboBox_KeyDown;
4702
4703                         cmbLang.Text = "";
4704                         cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4705                         cmbLang.Dock = DockStyle.Right;
4706                         cmbLang.Width = 50;
4707                         cmbLang.Name = "comboLang";
4708                         cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4709                         cmbLang.TabStop = false;
4710                         cmbLang.TabIndex = 2;
4711                         cmbLang.Items.Add("");
4712                         cmbLang.Items.Add("ja");
4713                         cmbLang.Items.Add("en");
4714                         cmbLang.Items.Add("ar");
4715                         cmbLang.Items.Add("da");
4716                         cmbLang.Items.Add("nl");
4717                         cmbLang.Items.Add("fa");
4718                         cmbLang.Items.Add("fi");
4719                         cmbLang.Items.Add("fr");
4720                         cmbLang.Items.Add("de");
4721                         cmbLang.Items.Add("hu");
4722                         cmbLang.Items.Add("is");
4723                         cmbLang.Items.Add("it");
4724                         cmbLang.Items.Add("no");
4725                         cmbLang.Items.Add("pl");
4726                         cmbLang.Items.Add("pt");
4727                         cmbLang.Items.Add("ru");
4728                         cmbLang.Items.Add("es");
4729                         cmbLang.Items.Add("sv");
4730                         cmbLang.Items.Add("th");
4731
4732                         lbl.Text = "Search(C-S-f)";
4733                         lbl.Name = "label1";
4734                         lbl.Dock = DockStyle.Left;
4735                         lbl.Width = 90;
4736                         lbl.Height = cmb.Height;
4737                         lbl.TextAlign = ContentAlignment.MiddleLeft;
4738                         lbl.TabIndex = 0;
4739
4740                         btn.Text = "Search";
4741                         btn.Name = "buttonSearch";
4742                         btn.UseVisualStyleBackColor = true;
4743                         btn.Dock = DockStyle.Right;
4744                         btn.TabStop = false;
4745                         btn.TabIndex = 3;
4746                         btn.Click += SearchButton_Click;
4747
4748                         TabClass tab;
4749                         if (_statuses.Tabs.TryGetValue(tabName, out tab))
4750                         {
4751                             if (!string.IsNullOrEmpty(tab.SearchWords))
4752                             {
4753                                 cmb.Items.Add(tab.SearchWords);
4754                                 cmb.Text = tab.SearchWords;
4755                             }
4756
4757                             cmbLang.Text = tab.SearchLang;
4758                         }
4759
4760                         _tabPage.Controls.Add(pnl);
4761                     }
4762                 }
4763
4764                 _tabPage.Tag = _listCustom;
4765                 this.ListTab.Controls.Add(_tabPage);
4766
4767                 _tabPage.Location = new Point(4, 4);
4768                 _tabPage.Name = "CTab" + cnt.ToString();
4769                 _tabPage.Size = new Size(380, 260);
4770                 _tabPage.TabIndex = 2 + cnt;
4771                 _tabPage.Text = tabName;
4772                 _tabPage.UseVisualStyleBackColor = true;
4773                 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4774
4775                 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4776                 _listCustom.TabIndex = 1;
4777                 _listCustom.AllowColumnReorder = true;
4778                 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4779                 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4780                 _listCustom.Dock = DockStyle.Fill;
4781                 _listCustom.FullRowSelect = true;
4782                 _listCustom.HideSelection = false;
4783                 _listCustom.Location = new Point(0, 0);
4784                 _listCustom.Margin = new Padding(0);
4785                 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4786                 _listCustom.ShowItemToolTips = true;
4787                 _listCustom.Size = new Size(380, 260);
4788                 _listCustom.UseCompatibleStateImageBehavior = false;
4789                 _listCustom.View = View.Details;
4790                 _listCustom.OwnerDraw = true;
4791                 _listCustom.VirtualMode = true;
4792                 _listCustom.Font = _fntReaded;
4793                 _listCustom.BackColor = _clListBackcolor;
4794
4795                 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4796                 _listCustom.AllowDrop = true;
4797
4798                 _listCustom.SmallImageList = _listViewImageList;
4799
4800                 InitColumns(_listCustom, startup);
4801
4802                 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4803                 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4804                 _listCustom.ColumnClick += MyList_ColumnClick;
4805                 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4806                 _listCustom.DragDrop += TweenMain_DragDrop;
4807                 _listCustom.DragEnter += TweenMain_DragEnter;
4808                 _listCustom.DragOver += TweenMain_DragOver;
4809                 _listCustom.DrawItem += MyList_DrawItem;
4810                 _listCustom.MouseClick += MyList_MouseClick;
4811                 _listCustom.ColumnReordered += MyList_ColumnReordered;
4812                 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4813                 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4814                 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4815                 _listCustom.DrawSubItem += MyList_DrawSubItem;
4816                 _listCustom.HScrolled += MyList_HScrolled;
4817             }
4818
4819             return true;
4820         }
4821
4822         public bool RemoveSpecifiedTab(string TabName, bool confirm)
4823         {
4824             var tabInfo = _statuses.GetTabByName(TabName);
4825             if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4826
4827             if (confirm)
4828             {
4829                 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4830                 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4831                                  MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4832                 {
4833                     return false;
4834                 }
4835             }
4836
4837             var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4838             if (_tabPage == null) return false;
4839
4840             SetListProperty();   //他のタブに列幅等を反映
4841
4842             //オブジェクトインスタンスの削除
4843             DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4844             _tabPage.Tag = null;
4845
4846             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4847             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4848             using (ControlTransaction.Layout(this.SplitContainer1, false))
4849             using (ControlTransaction.Layout(this.ListTab, false))
4850             using (ControlTransaction.Layout(this))
4851             using (ControlTransaction.Layout(_tabPage, false))
4852             {
4853                 if (this.ListTab.SelectedTab == _tabPage)
4854                 {
4855                     this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4856                     this._beforeSelectedTab = null;
4857                 }
4858                 this.ListTab.Controls.Remove(_tabPage);
4859
4860                 // 後付けのコントロールを破棄
4861                 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4862                 {
4863                     using (Control label = _tabPage.Controls["labelUser"])
4864                     {
4865                         _tabPage.Controls.Remove(label);
4866                     }
4867                 }
4868                 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4869                 {
4870                     using (Control pnl = _tabPage.Controls["panelSearch"])
4871                     {
4872                         pnl.Enter -= SearchControls_Enter;
4873                         pnl.Leave -= SearchControls_Leave;
4874                         _tabPage.Controls.Remove(pnl);
4875
4876                         foreach (Control ctrl in pnl.Controls)
4877                         {
4878                             if (ctrl.Name == "buttonSearch")
4879                             {
4880                                 ctrl.Click -= SearchButton_Click;
4881                             }
4882                             else if (ctrl.Name == "comboSearch")
4883                             {
4884                                 ctrl.KeyDown -= SearchComboBox_KeyDown;
4885                             }
4886                             pnl.Controls.Remove(ctrl);
4887                             ctrl.Dispose();
4888                         }
4889                     }
4890                 }
4891
4892                 _tabPage.Controls.Remove(_listCustom);
4893
4894                 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4895                 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4896                 _listCustom.ColumnClick -= MyList_ColumnClick;
4897                 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4898                 _listCustom.DragDrop -= TweenMain_DragDrop;
4899                 _listCustom.DragEnter -= TweenMain_DragEnter;
4900                 _listCustom.DragOver -= TweenMain_DragOver;
4901                 _listCustom.DrawItem -= MyList_DrawItem;
4902                 _listCustom.MouseClick -= MyList_MouseClick;
4903                 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4904                 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4905                 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4906                 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4907                 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4908                 _listCustom.HScrolled -= MyList_HScrolled;
4909
4910                 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4911                 _listCustom.Columns.Clear();
4912                 cols.ForEach(col => col.Dispose());
4913                 cols.Clear();
4914
4915                 _listCustom.ContextMenuStrip = null;
4916                 _listCustom.ColumnHeaderContextMenuStrip = null;
4917                 _listCustom.Font = null;
4918
4919                 _listCustom.SmallImageList = null;
4920                 _listCustom.ListViewItemSorter = null;
4921
4922                 //キャッシュのクリア
4923                 if (_curTab.Equals(_tabPage))
4924                 {
4925                     _curTab = null;
4926                     _curItemIndex = -1;
4927                     _curList = null;
4928                     _curPost = null;
4929                 }
4930                 this.PurgeListViewItemCache();
4931             }
4932
4933             _tabPage.Dispose();
4934             _listCustom.Dispose();
4935             _statuses.RemoveTab(TabName);
4936
4937             foreach (TabPage tp in ListTab.TabPages)
4938             {
4939                 DetailsListView lst = (DetailsListView)tp.Tag;
4940                 var count = _statuses.Tabs[tp.Text].AllCount;
4941                 if (lst.VirtualListSize != count)
4942                 {
4943                     lst.VirtualListSize = count;
4944                 }
4945             }
4946
4947             return true;
4948         }
4949
4950         private void ListTab_Deselected(object sender, TabControlEventArgs e)
4951         {
4952             this.PurgeListViewItemCache();
4953             _beforeSelectedTab = e.TabPage;
4954         }
4955
4956         private void ListTab_MouseMove(object sender, MouseEventArgs e)
4957         {
4958             //タブのD&D
4959
4960             if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4961             {
4962                 string tn = "";
4963                 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4964                 if (!dragEnableRectangle.Contains(e.Location))
4965                 {
4966                     //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4967                     tn = ListTab.SelectedTab.Text;
4968                 }
4969
4970                 if (string.IsNullOrEmpty(tn)) return;
4971
4972                 foreach (TabPage tb in ListTab.TabPages)
4973                 {
4974                     if (tb.Text == tn)
4975                     {
4976                         ListTab.DoDragDrop(tb, DragDropEffects.All);
4977                         break;
4978                     }
4979                 }
4980             }
4981             else
4982             {
4983                 _tabDrag = false;
4984             }
4985
4986             Point cpos = new Point(e.X, e.Y);
4987             for (int i = 0; i < ListTab.TabPages.Count; i++)
4988             {
4989                 Rectangle rect = ListTab.GetTabRect(i);
4990                 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4991                    rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4992                 {
4993                     _rclickTabName = ListTab.TabPages[i].Text;
4994                     break;
4995                 }
4996             }
4997         }
4998
4999         private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
5000         {
5001             //_curList.Refresh();
5002             SetMainWindowTitle();
5003             SetStatusLabelUrl();
5004             SetApiStatusLabel();
5005             if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
5006             TabMenuControl(ListTab.SelectedTab.Text);
5007             this.PushSelectPostChain();
5008             await DispSelectedPost();
5009         }
5010
5011         private void SetListProperty()
5012         {
5013             //削除などで見つからない場合は処理せず
5014             if (_curList == null) return;
5015             if (!_isColumnChanged) return;
5016
5017             int[] dispOrder = new int[_curList.Columns.Count];
5018             for (int i = 0; i < _curList.Columns.Count; i++)
5019             {
5020                 for (int j = 0; j < _curList.Columns.Count; j++)
5021                 {
5022                     if (_curList.Columns[j].DisplayIndex == i)
5023                     {
5024                         dispOrder[i] = j;
5025                         break;
5026                     }
5027                 }
5028             }
5029
5030             //列幅、列並びを他のタブに設定
5031             foreach (TabPage tb in ListTab.TabPages)
5032             {
5033                 if (!tb.Equals(_curTab))
5034                 {
5035                     if (tb.Tag != null && tb.Controls.Count > 0)
5036                     {
5037                         DetailsListView lst = (DetailsListView)tb.Tag;
5038                         for (int i = 0; i < lst.Columns.Count; i++)
5039                         {
5040                             lst.Columns[dispOrder[i]].DisplayIndex = i;
5041                             lst.Columns[i].Width = _curList.Columns[i].Width;
5042                         }
5043                     }
5044                 }
5045             }
5046
5047             _isColumnChanged = false;
5048         }
5049
5050         private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
5051         {
5052             try
5053             {
5054                 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal)
5055                     || PostBrowser.StatusText.StartsWith("ftp", StringComparison.Ordinal)
5056                     || PostBrowser.StatusText.StartsWith("data", StringComparison.Ordinal))
5057                 {
5058                     StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
5059                 }
5060                 if (string.IsNullOrEmpty(PostBrowser.StatusText))
5061                 {
5062                     SetStatusLabelUrl();
5063                 }
5064             }
5065             catch (Exception)
5066             {
5067             }
5068         }
5069
5070         private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5071         {
5072             if (e.KeyChar == '@')
5073             {
5074                 if (!this._cfgCommon.UseAtIdSupplement) return;
5075                 //@マーク
5076                 int cnt = AtIdSupl.ItemCount;
5077                 ShowSuplDialog(StatusText, AtIdSupl);
5078                 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
5079                 e.Handled = true;
5080             }
5081             else if (e.KeyChar == '#')
5082             {
5083                 if (!this._cfgCommon.UseHashSupplement) return;
5084                 ShowSuplDialog(StatusText, HashSupl);
5085                 e.Handled = true;
5086             }
5087         }
5088
5089         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5090         {
5091             ShowSuplDialog(owner, dialog, 0, "");
5092         }
5093
5094         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5095         {
5096             ShowSuplDialog(owner, dialog, offset, "");
5097         }
5098
5099         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5100         {
5101             dialog.StartsWith = startswith;
5102             if (dialog.Visible)
5103             {
5104                 dialog.Focus();
5105             }
5106             else
5107             {
5108                 dialog.ShowDialog();
5109             }
5110             this.TopMost = this._cfgCommon.AlwaysTop;
5111             int selStart = owner.SelectionStart;
5112             string fHalf = "";
5113             string eHalf = "";
5114             if (dialog.DialogResult == DialogResult.OK)
5115             {
5116                 if (!string.IsNullOrEmpty(dialog.inputText))
5117                 {
5118                     if (selStart > 0)
5119                     {
5120                         fHalf = owner.Text.Substring(0, selStart - offset);
5121                     }
5122                     if (selStart < owner.Text.Length)
5123                     {
5124                         eHalf = owner.Text.Substring(selStart);
5125                     }
5126                     owner.Text = fHalf + dialog.inputText + eHalf;
5127                     owner.SelectionStart = selStart + dialog.inputText.Length;
5128                 }
5129             }
5130             else
5131             {
5132                 if (selStart > 0)
5133                 {
5134                     fHalf = owner.Text.Substring(0, selStart);
5135                 }
5136                 if (selStart < owner.Text.Length)
5137                 {
5138                     eHalf = owner.Text.Substring(selStart);
5139                 }
5140                 owner.Text = fHalf + eHalf;
5141                 if (selStart > 0)
5142                 {
5143                     owner.SelectionStart = selStart;
5144                 }
5145             }
5146             owner.Focus();
5147         }
5148
5149         private void StatusText_KeyUp(object sender, KeyEventArgs e)
5150         {
5151             //スペースキーで未読ジャンプ
5152             if (!e.Alt && !e.Control && !e.Shift)
5153             {
5154                 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5155                 {
5156                     bool isSpace = false;
5157                     foreach (char c in StatusText.Text.ToCharArray())
5158                     {
5159                         if (c == ' ' || c == ' ')
5160                         {
5161                             isSpace = true;
5162                         }
5163                         else
5164                         {
5165                             isSpace = false;
5166                             break;
5167                         }
5168                     }
5169                     if (isSpace)
5170                     {
5171                         e.Handled = true;
5172                         StatusText.Text = "";
5173                         JumpUnreadMenuItem_Click(null, null);
5174                     }
5175                 }
5176             }
5177             this.StatusText_TextChanged(null, null);
5178         }
5179
5180         private void StatusText_TextChanged(object sender, EventArgs e)
5181         {
5182             //文字数カウント
5183             int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
5184             lblLen.Text = pLen.ToString();
5185             if (pLen < 0)
5186             {
5187                 StatusText.ForeColor = Color.Red;
5188             }
5189             else
5190             {
5191                 StatusText.ForeColor = _clInputFont;
5192             }
5193             if (string.IsNullOrEmpty(StatusText.Text))
5194             {
5195                 this.inReplyTo = null;
5196             }
5197         }
5198
5199         /// <summary>
5200         /// ツイート投稿前のフッター付与などの前処理を行います
5201         /// </summary>
5202         private string FormatStatusText(string statusText)
5203         {
5204             statusText = statusText.Replace("\r\n", "\n");
5205
5206             if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
5207             {
5208                 // URLと全角文字の切り離し
5209                 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
5210             }
5211
5212             if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
5213             {
5214                 // 文中の全角スペースを半角スペース1個にする
5215                 statusText = statusText.Replace(" ", " ");
5216             }
5217
5218             // DM の場合はこれ以降の処理を行わない
5219             if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
5220                 return statusText;
5221
5222             bool disableFooter;
5223             if (this._cfgCommon.PostShiftEnter)
5224             {
5225                 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5226             }
5227             else
5228             {
5229                 if (this.StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
5230                     disableFooter = MyCommon.IsKeyDown(Keys.Control);
5231                 else
5232                     disableFooter = MyCommon.IsKeyDown(Keys.Shift);
5233             }
5234
5235             if (statusText.Contains("RT @"))
5236                 disableFooter = true;
5237
5238             var header = "";
5239             var footer = "";
5240
5241             var hashtag = this.HashMgr.UseHash;
5242             if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
5243             {
5244                 if (HashMgr.IsHead)
5245                     header = HashMgr.UseHash + " ";
5246                 else
5247                     footer = " " + HashMgr.UseHash;
5248             }
5249
5250             if (!disableFooter)
5251             {
5252                 if (this._cfgLocal.UseRecommendStatus)
5253                 {
5254                     // 推奨ステータスを使用する
5255                     footer += this.recommendedStatusFooter;
5256                 }
5257                 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
5258                 {
5259                     // テキストボックスに入力されている文字列を使用する
5260                     footer += " " + this._cfgLocal.StatusText.Trim();
5261                 }
5262             }
5263
5264             statusText = header + statusText + footer;
5265
5266             if (this.ToolStripMenuItemPreventSmsCommand.Checked)
5267             {
5268                 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
5269                 // 参照: https://support.twitter.com/articles/14020
5270
5271                 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
5272                     && !Twitter.DMSendTextRegex.IsMatch(statusText))
5273                 {
5274                     // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
5275                     statusText = '\u200b' + statusText;
5276                 }
5277             }
5278
5279             return statusText;
5280         }
5281
5282         /// <summary>
5283         /// 投稿欄に表示する入力可能な文字数を計算します
5284         /// </summary>
5285         private int GetRestStatusCount(string statusText)
5286         {
5287             //文字数カウント
5288             var remainCount = this.tw.GetTextLengthRemain(statusText);
5289
5290             if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
5291             {
5292                 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
5293             }
5294
5295             return remainCount;
5296         }
5297
5298         private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5299         {
5300             if (sender != this._curList)
5301                 return;
5302
5303             var listCache = this._listItemCache;
5304             if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
5305             {
5306                 // If the newly requested cache is a subset of the old cache,
5307                 // no need to rebuild everything, so do nothing.
5308                 return;
5309             }
5310
5311             // Now we need to rebuild the cache.
5312             this.CreateCache(e.StartIndex, e.EndIndex);
5313         }
5314
5315         private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5316         {
5317             var listCache = this._listItemCache;
5318             if (listCache != null && listCache.TargetList == sender)
5319             {
5320                 ListViewItem item;
5321                 PostClass cacheItemPost;
5322                 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
5323                 {
5324                     e.Item = item;
5325                     return;
5326                 }
5327             }
5328
5329             // A cache miss, so create a new ListViewItem and pass it back.
5330             TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5331             try
5332             {
5333                 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5334             }
5335             catch (Exception)
5336             {
5337                 // 不正な要求に対する間に合わせの応答
5338                 string[] sitem = {"", "", "", "", "", "", "", ""};
5339                 e.Item = new ImageListViewItem(sitem);
5340             }
5341         }
5342
5343         private void CreateCache(int startIndex, int endIndex)
5344         {
5345             var tabInfo = this._statuses.Tabs[this._curTab.Text];
5346
5347             if (tabInfo.AllCount == 0)
5348                 return;
5349
5350             // キャッシュ要求(要求範囲±30を作成)
5351             startIndex = Math.Max(startIndex - 30, 0);
5352             endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
5353
5354             var cacheLength = endIndex - startIndex + 1;
5355
5356             var posts = tabInfo[startIndex, endIndex]; //配列で取得
5357             var listItems = Enumerable.Range(0, cacheLength)
5358                 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
5359                 .ToArray();
5360
5361             var listCache = new ListViewItemCache
5362             {
5363                 TargetList = this._curList,
5364                 StartIndex = startIndex,
5365                 EndIndex = endIndex,
5366                 Post = posts,
5367                 ListItem = listItems,
5368             };
5369
5370             Interlocked.Exchange(ref this._listItemCache, listCache);
5371         }
5372
5373         /// <summary>
5374         /// DetailsListView のための ListViewItem のキャッシュを消去する
5375         /// </summary>
5376         private void PurgeListViewItemCache()
5377         {
5378             Interlocked.Exchange(ref this._listItemCache, null);
5379         }
5380
5381         private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5382         {
5383             StringBuilder mk = new StringBuilder();
5384             //if (Post.IsDeleted) mk.Append("×");
5385             //if (Post.IsMark) mk.Append("♪");
5386             //if (Post.IsProtect) mk.Append("Ю");
5387             //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5388             if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5389             ImageListViewItem itm;
5390             if (Post.RetweetedId == null)
5391             {
5392                 string[] sitem= {"",
5393                                  Post.Nickname,
5394                                  Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5395                                  Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5396                                  Post.ScreenName,
5397                                  "",
5398                                  mk.ToString(),
5399                                  Post.Source};
5400                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5401             }
5402             else
5403             {
5404                 string[] sitem = {"",
5405                                   Post.Nickname,
5406                                   Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5407                                   Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5408                                   Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5409                                   "",
5410                                   mk.ToString(),
5411                                   Post.Source};
5412                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5413             }
5414             itm.StateIndex = Post.StateIndex;
5415
5416             bool read = Post.IsRead;
5417             //未読管理していなかったら既読として扱う
5418             if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5419             ChangeItemStyleRead(read, itm, Post, null);
5420             if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5421             return itm;
5422         }
5423
5424         /// <summary>
5425         /// 全てのタブの振り分けルールを反映し直します
5426         /// </summary>
5427         private void ApplyPostFilters()
5428         {
5429             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5430             {
5431                 this.PurgeListViewItemCache();
5432                 this._curPost = null;
5433                 this._curItemIndex = -1;
5434                 this._statuses.FilterAll();
5435
5436                 foreach (TabPage tabPage in this.ListTab.TabPages)
5437                 {
5438                     var tab = this._statuses.Tabs[tabPage.Text];
5439
5440                     var listview = (DetailsListView)tabPage.Tag;
5441                     using (ControlTransaction.Update(listview))
5442                     {
5443                         listview.VirtualListSize = tab.AllCount;
5444                     }
5445
5446                     if (this._cfgCommon.TabIconDisp)
5447                     {
5448                         if (tab.UnreadCount > 0)
5449                             tabPage.ImageIndex = 0;
5450                         else
5451                             tabPage.ImageIndex = -1;
5452                     }
5453                 }
5454
5455                 if (!this._cfgCommon.TabIconDisp)
5456                     this.ListTab.Refresh();
5457
5458                 SetMainWindowTitle();
5459                 SetStatusLabelUrl();
5460             }
5461         }
5462
5463         private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5464         {
5465             e.DrawDefault = true;
5466         }
5467
5468         private void MyList_HScrolled(object sender, EventArgs e)
5469         {
5470             DetailsListView listView = (DetailsListView)sender;
5471             listView.Refresh();
5472         }
5473
5474         private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5475         {
5476             if (e.State == 0) return;
5477             e.DrawDefault = false;
5478
5479             SolidBrush brs2 = null;
5480             if (!e.Item.Selected)     //e.ItemStateでうまく判定できない???
5481             {
5482                 if (e.Item.BackColor == _clSelf)
5483                     brs2 = _brsBackColorMine;
5484                 else if (e.Item.BackColor == _clAtSelf)
5485                     brs2 = _brsBackColorAt;
5486                 else if (e.Item.BackColor == _clTarget)
5487                     brs2 = _brsBackColorYou;
5488                 else if (e.Item.BackColor == _clAtTarget)
5489                     brs2 = _brsBackColorAtYou;
5490                 else if (e.Item.BackColor == _clAtFromTarget)
5491                     brs2 = _brsBackColorAtFromTarget;
5492                 else if (e.Item.BackColor == _clAtTo)
5493                     brs2 = _brsBackColorAtTo;
5494                 else
5495                     brs2 = _brsBackColorNone;
5496             }
5497             else
5498             {
5499                 //選択中の行
5500                 if (((Control)sender).Focused)
5501                     brs2 = _brsHighLight;
5502                 else
5503                     brs2 = _brsDeactiveSelection;
5504             }
5505             e.Graphics.FillRectangle(brs2, e.Bounds);
5506             e.DrawFocusRectangle();
5507             this.DrawListViewItemIcon(e);
5508         }
5509
5510         private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5511         {
5512             if (e.ItemState == 0) return;
5513
5514             if (e.ColumnIndex > 0)
5515             {
5516                 //アイコン以外の列
5517                 RectangleF rct = e.Bounds;
5518                 rct.Width = e.Header.Width;
5519                 int fontHeight = e.Item.Font.Height;
5520                 if (_iconCol)
5521                 {
5522                     rct.Y += fontHeight;
5523                     rct.Height -= fontHeight;
5524                 }
5525
5526                 int heightDiff;
5527                 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5528
5529                 //if (heightDiff > fontHeight * 0.7)
5530                 //{
5531                 //    rct.Height += fontHeight;
5532                 //    drawLineCount += 1;
5533                 //}
5534
5535                 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5536                 if (!_iconCol && drawLineCount <= 1)
5537                 {
5538                     //rct.Inflate(0, heightDiff / -2);
5539                     //rct.Height += fontHeight / 2;
5540                 }
5541                 else if (heightDiff < fontHeight * 0.7)
5542                 {
5543                     //最終行が70%以上欠けていたら、最終行は表示しない
5544                     //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5545                     rct.Height = (fontHeight * drawLineCount) - 1;
5546                 }
5547                 else
5548                 {
5549                     drawLineCount += 1;
5550                 }
5551
5552                 //if (!_iconCol && drawLineCount > 1)
5553                 //{
5554                 //    rct.Y += fontHeight * 0.2;
5555                 //    if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5556                 //}
5557
5558                 if (rct.Width > 0)
5559                 {
5560                     Color color = (!e.Item.Selected) ? e.Item.ForeColor :   //選択されていない行
5561                         (((Control)sender).Focused) ? _clHighLight :        //選択中の行
5562                         _clUnread;
5563
5564                     if (_iconCol)
5565                     {
5566                         Rectangle rctB = e.Bounds;
5567                         rctB.Width = e.Header.Width;
5568                         rctB.Height = fontHeight;
5569
5570                         using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5571                         {
5572                             TextRenderer.DrawText(e.Graphics,
5573                                                     e.Item.SubItems[2].Text,
5574                                                     e.Item.Font,
5575                                                     Rectangle.Round(rct),
5576                                                     color,
5577                                                     TextFormatFlags.WordBreak |
5578                                                     TextFormatFlags.EndEllipsis |
5579                                                     TextFormatFlags.GlyphOverhangPadding |
5580                                                     TextFormatFlags.NoPrefix);
5581                             TextRenderer.DrawText(e.Graphics,
5582                                                     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 + "]",
5583                                                     fnt,
5584                                                     rctB,
5585                                                     color,
5586                                                     TextFormatFlags.SingleLine |
5587                                                     TextFormatFlags.EndEllipsis |
5588                                                     TextFormatFlags.GlyphOverhangPadding |
5589                                                     TextFormatFlags.NoPrefix);
5590                         }
5591                     }
5592                     else if (drawLineCount == 1)
5593                     {
5594                         TextRenderer.DrawText(e.Graphics,
5595                                                 e.SubItem.Text,
5596                                                 e.Item.Font,
5597                                                 Rectangle.Round(rct),
5598                                                 color,
5599                                                 TextFormatFlags.SingleLine |
5600                                                 TextFormatFlags.EndEllipsis |
5601                                                 TextFormatFlags.GlyphOverhangPadding |
5602                                                 TextFormatFlags.NoPrefix |
5603                                                 TextFormatFlags.VerticalCenter);
5604                     }
5605                     else
5606                     {
5607                         TextRenderer.DrawText(e.Graphics,
5608                                                 e.SubItem.Text,
5609                                                 e.Item.Font,
5610                                                 Rectangle.Round(rct),
5611                                                 color,
5612                                                 TextFormatFlags.WordBreak |
5613                                                 TextFormatFlags.EndEllipsis |
5614                                                 TextFormatFlags.GlyphOverhangPadding |
5615                                                 TextFormatFlags.NoPrefix);
5616                     }
5617                     //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5618                 }
5619             }
5620         }
5621
5622         private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5623         {
5624             if (_iconSz == 0) return;
5625
5626             ImageListViewItem item = (ImageListViewItem)e.Item;
5627
5628             //e.Bounds.Leftが常に0を指すから自前で計算
5629             Rectangle itemRect = item.Bounds;
5630             var col0 = e.Item.ListView.Columns[0];
5631             itemRect.Width = col0.Width;
5632
5633             if (col0.DisplayIndex > 0)
5634             {
5635                 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5636                 {
5637                     if (clm.DisplayIndex < col0.DisplayIndex)
5638                         itemRect.X += clm.Width;
5639                 }
5640             }
5641
5642             // ディスプレイの DPI 設定を考慮したアイコンサイズ
5643             var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5644             var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5645
5646             Rectangle iconRect;
5647             var img = item.Image;
5648             if (img != null)
5649             {
5650                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5651                 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5652
5653                 if (iconRect.Width > 0)
5654                 {
5655                     e.Graphics.FillRectangle(Brushes.White, iconRect);
5656                     e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5657                     try
5658                     {
5659                         e.Graphics.DrawImage(img.Image, iconRect);
5660                     }
5661                     catch (ArgumentException)
5662                     {
5663                         item.RefreshImageAsync();
5664                     }
5665                 }
5666             }
5667             else
5668             {
5669                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5670                 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5671
5672                 item.GetImageAsync();
5673             }
5674
5675             if (item.StateIndex > -1)
5676             {
5677                 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5678                 if (stateRect.Width > 0)
5679                 {
5680                     //e.Graphics.FillRectangle(Brushes.White, stateRect);
5681                     //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5682                     e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5683                 }
5684             }
5685         }
5686
5687         protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5688         {
5689             base.ScaleControl(factor, specified);
5690
5691             ScaleChildControl(this.TabImage, factor);
5692
5693             var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5694             var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5695
5696             foreach (var listview in listviews)
5697             {
5698                 ScaleChildControl(listview, factor);
5699             }
5700         }
5701
5702         //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5703         //{
5704         //    ImageListViewItem item = (ImageListViewItem)e.Item;
5705         //    if (item.StateImageIndex > -1)
5706         //    {
5707         //        ////e.Bounds.Leftが常に0を指すから自前で計算
5708         //        //Rectangle itemRect = item.Bounds;
5709         //        //itemRect.Width = e.Item.ListView.Columns[4].Width;
5710
5711         //        //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5712         //        //{
5713         //        //    if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5714         //        //    {
5715         //        //        itemRect.X += clm.Width;
5716         //        //    }
5717         //        //}
5718
5719         //        //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5720         //        //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5721
5722         //        if (rct.Width > 0)
5723         //        {
5724         //            RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5725         //            //e.Graphics.FillRectangle(Brushes.White, rct);
5726         //            //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5727         //            e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5728         //        }
5729         //    }
5730         //}
5731
5732         private void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5733         {
5734             var tab = this._statuses.Tabs[this._curTab.Text];
5735
5736             if (tab.AllCount == 0)
5737             {
5738                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5739                 return;
5740             }
5741
5742             var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5743
5744             int startIndex;
5745             switch (searchType)
5746             {
5747                 case SEARCHTYPE.NextSearch: // 次を検索
5748                     if (selectedIndex != -1)
5749                         startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5750                     else
5751                         startIndex = 0;
5752                     break;
5753                 case SEARCHTYPE.PrevSearch: // 前を検索
5754                     if (selectedIndex != -1)
5755                         startIndex = Math.Max(selectedIndex - 1, 0);
5756                     else
5757                         startIndex = tab.AllCount - 1;
5758                     break;
5759                 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5760                 default:
5761                     if (selectedIndex != -1)
5762                         startIndex = selectedIndex;
5763                     else
5764                         startIndex = 0;
5765                     break;
5766             }
5767
5768             Func<string, bool> stringComparer;
5769             try
5770             {
5771                 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5772             }
5773             catch (ArgumentException)
5774             {
5775                 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5776                 return;
5777             }
5778
5779             var reverse = searchType == SEARCHTYPE.PrevSearch;
5780             var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5781                 .DefaultIfEmpty(-1).First();
5782
5783             if (foundIndex == -1)
5784             {
5785                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5786                 return;
5787             }
5788
5789             this.SelectListItem(this._curList, foundIndex);
5790             this._curList.EnsureVisible(foundIndex);
5791         }
5792
5793         private void MenuItemSubSearch_Click(object sender, EventArgs e)
5794         {
5795             // 検索メニュー
5796             this.ShowSearchDialog();
5797         }
5798
5799         private void MenuItemSearchNext_Click(object sender, EventArgs e)
5800         {
5801             var previousSearch = this.SearchDialog.ResultOptions;
5802             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5803             {
5804                 this.SearchDialog.Reset();
5805                 this.ShowSearchDialog();
5806                 return;
5807             }
5808
5809             // 次を検索
5810             this.DoTabSearch(
5811                 previousSearch.Query,
5812                 previousSearch.CaseSensitive,
5813                 previousSearch.UseRegex,
5814                 SEARCHTYPE.NextSearch);
5815         }
5816
5817         private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5818         {
5819             var previousSearch = this.SearchDialog.ResultOptions;
5820             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5821             {
5822                 this.SearchDialog.Reset();
5823                 this.ShowSearchDialog();
5824                 return;
5825             }
5826
5827             // 前を検索
5828             this.DoTabSearch(
5829                 previousSearch.Query,
5830                 previousSearch.CaseSensitive,
5831                 previousSearch.UseRegex,
5832                 SEARCHTYPE.PrevSearch);
5833         }
5834
5835         /// <summary>
5836         /// 検索ダイアログを表示し、検索を実行します
5837         /// </summary>
5838         private void ShowSearchDialog()
5839         {
5840             if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5841             {
5842                 this.TopMost = this._cfgCommon.AlwaysTop;
5843                 return;
5844             }
5845             this.TopMost = this._cfgCommon.AlwaysTop;
5846
5847             var searchOptions = this.SearchDialog.ResultOptions;
5848             if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5849             {
5850                 if (searchOptions.NewTab)
5851                 {
5852                     var tabName = Properties.Resources.SearchResults_TabName;
5853
5854                     try
5855                     {
5856                         tabName = this._statuses.MakeTabName(tabName);
5857                     }
5858                     catch (TabException ex)
5859                     {
5860                         MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5861                     }
5862
5863                     this.AddNewTab(tabName, false, MyCommon.TabUsageType.SearchResults);
5864                     this._statuses.AddTab(tabName, MyCommon.TabUsageType.SearchResults, null);
5865
5866                     var targetTab = this._statuses.Tabs[this._curTab.Text];
5867
5868                     Func<string, bool> stringComparer;
5869                     try
5870                     {
5871                         stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5872                     }
5873                     catch (ArgumentException)
5874                     {
5875                         MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5876                         return;
5877                     }
5878
5879                     var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5880                     if (foundIndices.Length == 0)
5881                     {
5882                         MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5883                         return;
5884                     }
5885
5886                     var foundPosts = foundIndices.Select(x => targetTab[x]);
5887
5888                     var resultTab = this._statuses.Tabs[tabName];
5889                     foreach (var post in foundPosts)
5890                     {
5891                         resultTab.AddPostToInnerStorage(post);
5892                     }
5893
5894                     this._statuses.DistributePosts();
5895                     this.RefreshTimeline();
5896
5897                     var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5898                         .First(x => x.Text == tabName);
5899
5900                     this.ListTab.SelectedTab = tabPage;
5901                 }
5902                 else
5903                 {
5904                     this.DoTabSearch(
5905                         searchOptions.Query,
5906                         searchOptions.CaseSensitive,
5907                         searchOptions.UseRegex,
5908                         SEARCHTYPE.DialogSearch);
5909                 }
5910             }
5911             else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5912             {
5913                 this.AddNewTabForSearch(searchOptions.Query);
5914             }
5915         }
5916
5917         /// <summary>発言検索に使用するメソッドを生成します</summary>
5918         /// <exception cref="ArgumentException">
5919         /// <paramref name="useRegex"/> が true かつ、<paramref name="query"> が不正な正規表現な場合
5920         /// </exception>
5921         private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5922         {
5923             if (useRegex)
5924             {
5925                 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5926                 var regex = new Regex(query, regexOption);
5927
5928                 return x => regex.IsMatch(x);
5929             }
5930             else
5931             {
5932                 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5933
5934                 return x => x.IndexOf(query, comparisonType) != -1;
5935             }
5936         }
5937
5938         private void AboutMenuItem_Click(object sender, EventArgs e)
5939         {
5940             using (TweenAboutBox about = new TweenAboutBox())
5941             {
5942                 about.ShowDialog(this);
5943             }
5944             this.TopMost = this._cfgCommon.AlwaysTop;
5945         }
5946
5947         private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5948         {
5949             int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5950             int idx = -1;
5951             DetailsListView lst = null;
5952
5953             if (ImageSelector.Enabled)
5954                 return;
5955
5956             //現在タブから最終タブまで探索
5957             for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5958             {
5959                 //未読Index取得
5960                 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5961                 if (idx > -1)
5962                 {
5963                     ListTab.SelectedIndex = i;
5964                     lst = (DetailsListView)ListTab.TabPages[i].Tag;
5965                     //_curTab = ListTab.TabPages[i];
5966                     break;
5967                 }
5968             }
5969
5970             //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5971             if (idx == -1 && bgnIdx > 0)
5972             {
5973                 for (int i = 0; i < bgnIdx; i++)
5974                 {
5975                     idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5976                     if (idx > -1)
5977                     {
5978                         ListTab.SelectedIndex = i;
5979                         lst = (DetailsListView)ListTab.TabPages[i].Tag;
5980                         //_curTab = ListTab.TabPages[i];
5981                         break;
5982                     }
5983                 }
5984             }
5985
5986             //全部調べたが未読見つからず→先頭タブの最新発言へ
5987             if (idx == -1)
5988             {
5989                 ListTab.SelectedIndex = 0;
5990                 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5991                 //_curTab = ListTab.TabPages[0];
5992                 if (_statuses.SortOrder == SortOrder.Ascending)
5993                     idx = lst.VirtualListSize - 1;
5994                 else
5995                     idx = 0;
5996             }
5997
5998             if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5999             {
6000                 SelectListItem(lst, idx);
6001                 if (_statuses.SortMode == ComparerMode.Id)
6002                 {
6003                     if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
6004                        _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
6005                     {
6006                         MoveTop();
6007                     }
6008                     else
6009                     {
6010                         lst.EnsureVisible(idx);
6011                     }
6012                 }
6013                 else
6014                 {
6015                     lst.EnsureVisible(idx);
6016                 }
6017             }
6018             lst.Focus();
6019         }
6020
6021         private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
6022         {
6023             if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
6024             {
6025                 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6026                 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
6027             }
6028         }
6029
6030         private async void FavorareMenuItem_Click(object sender, EventArgs e)
6031         {
6032             if (_curList.SelectedIndices.Count > 0)
6033             {
6034                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6035                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
6036             }
6037         }
6038
6039         private async void VerUpMenuItem_Click(object sender, EventArgs e)
6040         {
6041             await this.CheckNewVersion(false);
6042         }
6043
6044         private void RunTweenUp()
6045         {
6046             ProcessStartInfo pinfo = new ProcessStartInfo();
6047             pinfo.UseShellExecute = true;
6048             pinfo.WorkingDirectory = MyCommon.settingPath;
6049             pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
6050             pinfo.Arguments = "\"" + Application.StartupPath + "\"";
6051             try
6052             {
6053                 Process.Start(pinfo);
6054             }
6055             catch (Exception)
6056             {
6057                 MessageBox.Show("Failed to execute TweenUp3.exe.");
6058             }
6059         }
6060
6061         public class VersionInfo
6062         {
6063             public Version Version { get; set; }
6064             public Uri DownloadUri { get; set; }
6065             public string ReleaseNote { get; set; }
6066         }
6067
6068         /// <summary>
6069         /// OpenTween の最新バージョンの情報を取得します
6070         /// </summary>
6071         public async Task<VersionInfo> GetVersionInfoAsync()
6072         {
6073             var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6074                 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6075
6076             var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6077                 .ConfigureAwait(false);
6078
6079             // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6080             var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6081
6082             var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6083             var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6084
6085             msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6086
6087             return new VersionInfo
6088             {
6089                 Version = Version.Parse(msgHeader[0]),
6090                 DownloadUri = new Uri(msgHeader[1]),
6091                 ReleaseNote = msgBody,
6092             };
6093         }
6094
6095         private async Task CheckNewVersion(bool startup = false)
6096         {
6097             if (ApplicationSettings.VersionInfoUrl == null)
6098                 return; // 更新チェック無効化
6099
6100             try
6101             {
6102                 var versionInfo = await this.GetVersionInfoAsync();
6103
6104                 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6105                 {
6106                     // 更新不要
6107                     if (!startup)
6108                     {
6109                         var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6110                             MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6111                         msgtext = MyCommon.ReplaceAppName(msgtext);
6112
6113                         MessageBox.Show(msgtext,
6114                             MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6115                             MessageBoxButtons.OK, MessageBoxIcon.Information);
6116                     }
6117                     return;
6118                 }
6119
6120                 using (var dialog = new UpdateDialog())
6121                 {
6122                     dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6123                         MyCommon.GetReadableVersion(versionInfo.Version));
6124                     dialog.DetailsText = versionInfo.ReleaseNote;
6125
6126                     if (dialog.ShowDialog(this) == DialogResult.Yes)
6127                     {
6128                         await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
6129                     }
6130                 }
6131             }
6132             catch (Exception)
6133             {
6134                 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6135                 if (!startup)
6136                 {
6137                     MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6138                         MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6139                         MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6140                 }
6141             }
6142         }
6143
6144         private async Task Colorize()
6145         {
6146             _colorize = false;
6147             await this.DispSelectedPost();
6148             //件数関連の場合、タイトル即時書き換え
6149             if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6150                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6151                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6152                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6153             {
6154                 SetMainWindowTitle();
6155             }
6156             if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6157             foreach (TabPage tb in ListTab.TabPages)
6158             {
6159                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6160                 {
6161                     if (this._cfgCommon.TabIconDisp)
6162                     {
6163                         if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6164                     }
6165                 }
6166             }
6167             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6168         }
6169
6170         public string createDetailHtml(string orgdata)
6171         {
6172             if (this._cfgLocal.UseTwemoji)
6173                 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6174
6175             return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6176         }
6177
6178         private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6179         {
6180             if (sender.Equals(displayItem))
6181             {
6182                 this.ClearUserPicture();
6183
6184                 var img = displayItem.Image;
6185                 try
6186                 {
6187                     if (img != null)
6188                         img = await img.CloneAsync();
6189
6190                     UserPicture.Image = img;
6191                 }
6192                 catch (Exception)
6193                 {
6194                     UserPicture.ShowErrorImage();
6195                 }
6196             }
6197         }
6198
6199         private Task DispSelectedPost()
6200         {
6201             return this.DispSelectedPost(false);
6202         }
6203
6204         private PostClass displayPost = new PostClass();
6205
6206         /// <summary>
6207         /// サムネイル表示に使用する CancellationToken の生成元
6208         /// </summary>
6209         private CancellationTokenSource thumbnailTokenSource = null;
6210
6211         private async Task DispSelectedPost(bool forceupdate)
6212         {
6213             if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6214                 return;
6215
6216             var oldDisplayPost = this.displayPost;
6217             this.displayPost = this._curPost;
6218
6219             if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6220                 return;
6221
6222             if (displayItem != null)
6223             {
6224                 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6225                 displayItem = null;
6226             }
6227             displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6228             displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6229
6230             using (ControlTransaction.Update(this.TableLayoutPanel1))
6231             {
6232                 SourceLinkLabel.Text = this._curPost.Source;
6233                 SourceLinkLabel.Tag = this._curPost.SourceUri;
6234                 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6235
6236                 string nameText;
6237                 if (_curPost.IsDm)
6238                 {
6239                     if (_curPost.IsOwl)
6240                         nameText = "DM FROM <- ";
6241                     else
6242                         nameText = "DM TO -> ";
6243                 }
6244                 else
6245                 {
6246                     nameText = "";
6247                 }
6248                 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6249                 if (_curPost.RetweetedId != null)
6250                     nameText += " (RT:" + _curPost.RetweetedBy + ")";
6251
6252                 NameLabel.Text = nameText;
6253                 NameLabel.Tag = _curPost.ScreenName;
6254
6255                 var nameForeColor = SystemColors.ControlText;
6256                 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6257                     nameForeColor = this._clOWL;
6258                 if (_curPost.RetweetedId != null)
6259                     nameForeColor = this._clRetweet;
6260                 if (_curPost.IsFav)
6261                     nameForeColor = this._clFav;
6262                 NameLabel.ForeColor = nameForeColor;
6263
6264                 this.ClearUserPicture();
6265
6266                 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6267                 {
6268                     var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6269                     try
6270                     {
6271                         UserPicture.Image = image?.Clone();
6272                     }
6273                     catch (Exception)
6274                     {
6275                         UserPicture.ShowErrorImage();
6276                     }
6277                 }
6278
6279                 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6280             }
6281
6282             if (DumpPostClassToolStripMenuItem.Checked)
6283             {
6284                 StringBuilder sb = new StringBuilder(512);
6285
6286                 sb.Append("-----Start PostClass Dump<br>");
6287                 sb.AppendFormat("TextFromApi           : {0}<br>", _curPost.TextFromApi);
6288                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6289                 sb.AppendFormat("StatusId             : {0}<br>", _curPost.StatusId.ToString());
6290                 //sb.AppendFormat("ImageIndex     : {0}<br>", _curPost.ImageIndex.ToString());
6291                 sb.AppendFormat("ImageUrl       : {0}<br>", _curPost.ImageUrl);
6292                 sb.AppendFormat("InReplyToStatusId    : {0}<br>", _curPost.InReplyToStatusId.ToString());
6293                 sb.AppendFormat("InReplyToUser  : {0}<br>", _curPost.InReplyToUser);
6294                 sb.AppendFormat("IsDM           : {0}<br>", _curPost.IsDm.ToString());
6295                 sb.AppendFormat("IsFav          : {0}<br>", _curPost.IsFav.ToString());
6296                 sb.AppendFormat("IsMark         : {0}<br>", _curPost.IsMark.ToString());
6297                 sb.AppendFormat("IsMe           : {0}<br>", _curPost.IsMe.ToString());
6298                 sb.AppendFormat("IsOwl          : {0}<br>", _curPost.IsOwl.ToString());
6299                 sb.AppendFormat("IsProtect      : {0}<br>", _curPost.IsProtect.ToString());
6300                 sb.AppendFormat("IsRead         : {0}<br>", _curPost.IsRead.ToString());
6301                 sb.AppendFormat("IsReply        : {0}<br>", _curPost.IsReply.ToString());
6302
6303                 foreach (string nm in _curPost.ReplyToList)
6304                 {
6305                     sb.AppendFormat("ReplyToList    : {0}<br>", nm);
6306                 }
6307
6308                 sb.AppendFormat("ScreenName           : {0}<br>", _curPost.ScreenName);
6309                 sb.AppendFormat("NickName       : {0}<br>", _curPost.Nickname);
6310                 sb.AppendFormat("Text   : {0}<br>", _curPost.Text);
6311                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.Text);
6312                 sb.AppendFormat("CreatedAt          : {0}<br>", _curPost.CreatedAt.ToString());
6313                 sb.AppendFormat("Source         : {0}<br>", _curPost.Source);
6314                 sb.AppendFormat("UserId            : {0}<br>", _curPost.UserId);
6315                 sb.AppendFormat("FilterHit      : {0}<br>", _curPost.FilterHit);
6316                 sb.AppendFormat("RetweetedBy    : {0}<br>", _curPost.RetweetedBy);
6317                 sb.AppendFormat("RetweetedId    : {0}<br>", _curPost.RetweetedId);
6318
6319                 sb.AppendFormat("Media.Count    : {0}<br>", _curPost.Media.Count);
6320                 if (_curPost.Media.Count > 0)
6321                 {
6322                     for (int i = 0; i < _curPost.Media.Count; i++)
6323                     {
6324                         var info = _curPost.Media[i];
6325                         sb.AppendFormat("Media[{0}].Url         : {1}<br>", i, info.Url);
6326                         sb.AppendFormat("Media[{0}].VideoUrl    : {1}<br>", i, info.VideoUrl ?? "---");
6327                     }
6328                 }
6329                 sb.Append("-----End PostClass Dump<br>");
6330
6331                 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6332                 return;
6333             }
6334
6335             var loadTasks = new List<Task>();
6336
6337             // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6338             // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6339             if (_curPost.StatusId != oldDisplayPost.StatusId)
6340             {
6341                 using (ControlTransaction.Update(this.PostBrowser))
6342                 {
6343                     this.PostBrowser.DocumentText =
6344                         this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6345
6346                     this.PostBrowser.Document.Window.ScrollTo(0, 0);
6347                 }
6348
6349                 this.SplitContainer3.Panel2Collapsed = true;
6350
6351                 if (this._cfgCommon.PreviewEnable)
6352                 {
6353                     var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
6354                     oldTokenSource?.Cancel();
6355
6356                     var token = this.thumbnailTokenSource.Token;
6357                     loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
6358                 }
6359
6360                 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
6361             }
6362
6363             try
6364             {
6365                 await Task.WhenAll(loadTasks);
6366             }
6367             catch (OperationCanceledException) { }
6368         }
6369
6370         /// <summary>
6371         /// 発言詳細欄のツイートURLを展開する
6372         /// </summary>
6373         private async Task AppendQuoteTweetAsync(PostClass post)
6374         {
6375             var quoteStatusIds = post.QuoteStatusIds;
6376             if (quoteStatusIds.Length == 0 && post.InReplyToStatusId == null)
6377                 return;
6378
6379             // 「読み込み中」テキストを表示
6380             var loadingQuoteHtml = quoteStatusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText, isReply: false));
6381
6382             var loadingReplyHtml = string.Empty;
6383             if (post.InReplyToStatusId != null)
6384                 loadingReplyHtml = FormatQuoteTweetHtml(post.InReplyToStatusId.Value, Properties.Resources.LoadingText, isReply: true);
6385
6386             var body = post.Text + string.Concat(loadingQuoteHtml) + loadingReplyHtml;
6387
6388             using (ControlTransaction.Update(this.PostBrowser))
6389                 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6390
6391             // 引用ツイートを読み込み
6392             var loadTweetTasks = quoteStatusIds.Select(x => this.CreateQuoteTweetHtml(x, isReply: false)).ToList();
6393
6394             if (post.InReplyToStatusId != null)
6395                 loadTweetTasks.Add(this.CreateQuoteTweetHtml(post.InReplyToStatusId.Value, isReply: true));
6396
6397             var quoteHtmls = await Task.WhenAll(loadTweetTasks);
6398
6399             // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
6400             if (this._curPost != post || this._curPost.IsDeleted)
6401                 return;
6402
6403             body = post.Text + string.Concat(quoteHtmls);
6404
6405             using (ControlTransaction.Update(this.PostBrowser))
6406                 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6407         }
6408
6409         private async Task<string> CreateQuoteTweetHtml(long statusId, bool isReply)
6410         {
6411             PostClass post = this._statuses[statusId];
6412             if (post == null)
6413             {
6414                 try
6415                 {
6416                     post = await this.tw.GetStatusApi(false, statusId)
6417                         .ConfigureAwait(false);
6418                 }
6419                 catch (WebApiException ex)
6420                 {
6421                     return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode($"Err:{ex.Message}(GetStatus)"), isReply);
6422                 }
6423
6424                 post.IsRead = true;
6425                 if (!this._statuses.AddQuoteTweet(post))
6426                     return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.", isReply);
6427             }
6428
6429             return FormatQuoteTweetHtml(post, isReply);
6430         }
6431
6432         internal static string FormatQuoteTweetHtml(PostClass post, bool isReply)
6433         {
6434             var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6435                 " &mdash; " + WebUtility.HtmlEncode(post.Nickname) +
6436                 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6437                 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6438
6439             return FormatQuoteTweetHtml(post.StatusId, innerHtml, isReply);
6440         }
6441
6442         internal static string FormatQuoteTweetHtml(long statusId, string innerHtml, bool isReply)
6443         {
6444             var blockClassName = "quote-tweet";
6445
6446             if (isReply)
6447                 blockClassName += " reply";
6448
6449             return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6450                 $"<blockquote class=\"{blockClassName}\">{innerHtml}</blockquote>" +
6451                 "</a>";
6452         }
6453
6454         /// <summary>
6455         /// 指定されたHTMLからリンクを除去します
6456         /// </summary>
6457         internal static string StripLinkTagHtml(string html)
6458         {
6459             // a 要素はネストされていない前提の正規表現パターン
6460             return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6461         }
6462
6463         private async void MatomeMenuItem_Click(object sender, EventArgs e)
6464         {
6465             await this.OpenApplicationWebsite();
6466         }
6467
6468         private async Task OpenApplicationWebsite()
6469         {
6470             await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6471         }
6472
6473         private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6474         {
6475             await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6476         }
6477
6478         private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6479         {
6480             if (ListTab.SelectedTab != null)
6481             {
6482                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6483                 {
6484                     Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6485                     if (pnl.Controls["comboSearch"].Focused ||
6486                         pnl.Controls["comboLang"].Focused ||
6487                         pnl.Controls["buttonSearch"].Focused) return;
6488                 }
6489
6490                 if (e.Control || e.Shift || e.Alt)
6491                     this._anchorFlag = false;
6492
6493                 Task asyncTask;
6494                 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6495                 {
6496                     e.Handled = true;
6497                     e.SuppressKeyPress = true;
6498                 }
6499
6500                 if (asyncTask != null)
6501                     await asyncTask;
6502             }
6503         }
6504
6505         private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6506
6507         private void InitializeShortcuts()
6508         {
6509             this.shortcutCommands = new[]
6510             {
6511                 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6512                 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6513                     .FocusedOn(FocusedControl.ListTab)
6514                     .Do(() => SendKeys.Send("{DOWN}")),
6515
6516                 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6517                     .FocusedOn(FocusedControl.ListTab)
6518                     .Do(() => SendKeys.Send("{UP}")),
6519
6520                 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6521                     .FocusedOn(FocusedControl.ListTab)
6522                     .Do(() => SendKeys.Send("{PGDN}")),
6523
6524                 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6525                     .FocusedOn(FocusedControl.ListTab)
6526                     .Do(() => SendKeys.Send("{PGUP}")),
6527
6528                 ShortcutCommand.Create(Keys.F1)
6529                     .Do(() => this.OpenApplicationWebsite()),
6530
6531                 ShortcutCommand.Create(Keys.F3)
6532                     .Do(() => this.MenuItemSearchNext_Click(null, null)),
6533
6534                 ShortcutCommand.Create(Keys.F5)
6535                     .Do(() => this.DoRefresh()),
6536
6537                 ShortcutCommand.Create(Keys.F6)
6538                     .Do(() => this.GetReplyAsync()),
6539
6540                 ShortcutCommand.Create(Keys.F7)
6541                     .Do(() => this.GetDirectMessagesAsync()),
6542
6543                 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6544                     .NotFocusedOn(FocusedControl.StatusText)
6545                     .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6546
6547                 ShortcutCommand.Create(Keys.G)
6548                     .NotFocusedOn(FocusedControl.StatusText)
6549                     .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6550
6551                 ShortcutCommand.Create(Keys.Right, Keys.N)
6552                     .FocusedOn(FocusedControl.ListTab)
6553                     .Do(() => this.GoRelPost(forward: true)),
6554
6555                 ShortcutCommand.Create(Keys.Left, Keys.P)
6556                     .FocusedOn(FocusedControl.ListTab)
6557                     .Do(() => this.GoRelPost(forward: false)),
6558
6559                 ShortcutCommand.Create(Keys.OemPeriod)
6560                     .FocusedOn(FocusedControl.ListTab)
6561                     .Do(() => this.GoAnchor()),
6562
6563                 ShortcutCommand.Create(Keys.I)
6564                     .FocusedOn(FocusedControl.ListTab)
6565                     .OnlyWhen(() => this.StatusText.Enabled)
6566                     .Do(() => this.StatusText.Focus()),
6567
6568                 ShortcutCommand.Create(Keys.Enter)
6569                     .FocusedOn(FocusedControl.ListTab)
6570                     .Do(() => this.MakeReplyOrDirectStatus()),
6571
6572                 ShortcutCommand.Create(Keys.R)
6573                     .FocusedOn(FocusedControl.ListTab)
6574                     .Do(() => this.DoRefresh()),
6575
6576                 ShortcutCommand.Create(Keys.L)
6577                     .FocusedOn(FocusedControl.ListTab)
6578                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6579
6580                 ShortcutCommand.Create(Keys.H)
6581                     .FocusedOn(FocusedControl.ListTab)
6582                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6583
6584                 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6585                     .FocusedOn(FocusedControl.ListTab)
6586                     .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6587
6588                 ShortcutCommand.Create(Keys.S)
6589                     .FocusedOn(FocusedControl.ListTab)
6590                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6591
6592                 ShortcutCommand.Create(Keys.A)
6593                     .FocusedOn(FocusedControl.ListTab)
6594                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6595
6596                 // ] in_reply_to参照元へ戻る
6597                 ShortcutCommand.Create(Keys.Oem4)
6598                     .FocusedOn(FocusedControl.ListTab)
6599                     .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6600
6601                 // [ in_reply_toへジャンプ
6602                 ShortcutCommand.Create(Keys.Oem6)
6603                     .FocusedOn(FocusedControl.ListTab)
6604                     .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6605
6606                 ShortcutCommand.Create(Keys.Escape)
6607                     .FocusedOn(FocusedControl.ListTab)
6608                     .Do(() => {
6609                         this._anchorFlag = false;
6610                         if (ListTab.SelectedTab != null)
6611                         {
6612                             var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6613                             if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6614                             {
6615                                 var relTp = ListTab.SelectedTab;
6616                                 RemoveSpecifiedTab(relTp.Text, false);
6617                                 SaveConfigsTabs();
6618                             }
6619                         }
6620                     }),
6621
6622                 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6623                 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6624                     .FocusedOn(FocusedControl.ListTab)
6625                     .Do(() => this._anchorFlag = false, preventDefault: false),
6626
6627                 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6628                 ShortcutCommand.Create(Keys.Up, Keys.Down)
6629                     .FocusedOn(FocusedControl.PostBrowser)
6630                     .Do(() => { }),
6631
6632                 ShortcutCommand.Create(Keys.Control | Keys.R)
6633                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6634
6635                 ShortcutCommand.Create(Keys.Control | Keys.D)
6636                     .Do(() => this.doStatusDelete()),
6637
6638                 ShortcutCommand.Create(Keys.Control | Keys.M)
6639                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6640
6641                 ShortcutCommand.Create(Keys.Control | Keys.S)
6642                     .Do(() => this.FavoriteChange(FavAdd: true)),
6643
6644                 ShortcutCommand.Create(Keys.Control | Keys.I)
6645                     .Do(() => this.doRepliedStatusOpen()),
6646
6647                 ShortcutCommand.Create(Keys.Control | Keys.Q)
6648                     .Do(() => this.doQuoteOfficial()),
6649
6650                 ShortcutCommand.Create(Keys.Control | Keys.B)
6651                     .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6652
6653                 ShortcutCommand.Create(Keys.Control | Keys.T)
6654                     .Do(() => this.HashManageMenuItem_Click(null, null)),
6655
6656                 ShortcutCommand.Create(Keys.Control | Keys.L)
6657                     .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6658
6659                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6660                     .NotFocusedOn(FocusedControl.PostBrowser)
6661                     .Do(() => this.MultiLineMenuItem_Click(null, null)),
6662
6663                 ShortcutCommand.Create(Keys.Control | Keys.F)
6664                     .Do(() => this.MenuItemSubSearch_Click(null, null)),
6665
6666                 ShortcutCommand.Create(Keys.Control | Keys.U)
6667                     .Do(() => this.ShowUserTimeline()),
6668
6669                 ShortcutCommand.Create(Keys.Control | Keys.H)
6670                     .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6671
6672                 ShortcutCommand.Create(Keys.Control | Keys.G)
6673                     .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6674
6675                 ShortcutCommand.Create(Keys.Control | Keys.O)
6676                     .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6677
6678                 ShortcutCommand.Create(Keys.Control | Keys.E)
6679                     .Do(() => this.OpenURLMenuItem_Click(null, null)),
6680
6681                 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6682                     .FocusedOn(FocusedControl.ListTab)
6683                     .Do(() => this._colorize = true, preventDefault: false),
6684
6685                 ShortcutCommand.Create(Keys.Control | Keys.N)
6686                     .FocusedOn(FocusedControl.ListTab)
6687                     .Do(() => this.GoNextTab(forward: true)),
6688
6689                 ShortcutCommand.Create(Keys.Control | Keys.P)
6690                     .FocusedOn(FocusedControl.ListTab)
6691                     .Do(() => this.GoNextTab(forward: false)),
6692
6693                 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6694                     .FocusedOn(FocusedControl.ListTab)
6695                     .Do(() => this.CopyStot()),
6696
6697                 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6698                 ShortcutCommand.Create(Keys.Control | Keys.D1)
6699                     .FocusedOn(FocusedControl.ListTab)
6700                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6701                     .Do(() => this.ListTab.SelectedIndex = 0),
6702
6703                 ShortcutCommand.Create(Keys.Control | Keys.D2)
6704                     .FocusedOn(FocusedControl.ListTab)
6705                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6706                     .Do(() => this.ListTab.SelectedIndex = 1),
6707
6708                 ShortcutCommand.Create(Keys.Control | Keys.D3)
6709                     .FocusedOn(FocusedControl.ListTab)
6710                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6711                     .Do(() => this.ListTab.SelectedIndex = 2),
6712
6713                 ShortcutCommand.Create(Keys.Control | Keys.D4)
6714                     .FocusedOn(FocusedControl.ListTab)
6715                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6716                     .Do(() => this.ListTab.SelectedIndex = 3),
6717
6718                 ShortcutCommand.Create(Keys.Control | Keys.D5)
6719                     .FocusedOn(FocusedControl.ListTab)
6720                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6721                     .Do(() => this.ListTab.SelectedIndex = 4),
6722
6723                 ShortcutCommand.Create(Keys.Control | Keys.D6)
6724                     .FocusedOn(FocusedControl.ListTab)
6725                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6726                     .Do(() => this.ListTab.SelectedIndex = 5),
6727
6728                 ShortcutCommand.Create(Keys.Control | Keys.D7)
6729                     .FocusedOn(FocusedControl.ListTab)
6730                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6731                     .Do(() => this.ListTab.SelectedIndex = 6),
6732
6733                 ShortcutCommand.Create(Keys.Control | Keys.D8)
6734                     .FocusedOn(FocusedControl.ListTab)
6735                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6736                     .Do(() => this.ListTab.SelectedIndex = 7),
6737
6738                 ShortcutCommand.Create(Keys.Control | Keys.D9)
6739                     .FocusedOn(FocusedControl.ListTab)
6740                     .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6741
6742                 ShortcutCommand.Create(Keys.Control | Keys.A)
6743                     .FocusedOn(FocusedControl.StatusText)
6744                     .Do(() => this.StatusText.SelectAll()),
6745
6746                 ShortcutCommand.Create(Keys.Control | Keys.V)
6747                     .FocusedOn(FocusedControl.StatusText)
6748                     .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6749
6750                 ShortcutCommand.Create(Keys.Control | Keys.Up)
6751                     .FocusedOn(FocusedControl.StatusText)
6752                     .Do(() => {
6753                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6754                         {
6755                             var inReplyToStatusId = this.inReplyTo?.Item1;
6756                             var inReplyToScreenName = this.inReplyTo?.Item2;
6757                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6758                         }
6759                         _hisIdx -= 1;
6760                         if (_hisIdx < 0) _hisIdx = 0;
6761
6762                         var historyItem = this._history[this._hisIdx];
6763                         StatusText.Text = historyItem.status;
6764                         StatusText.SelectionStart = StatusText.Text.Length;
6765                         if (historyItem.inReplyToId != null)
6766                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6767                         else
6768                             this.inReplyTo = null;
6769                     }),
6770
6771                 ShortcutCommand.Create(Keys.Control | Keys.Down)
6772                     .FocusedOn(FocusedControl.StatusText)
6773                     .Do(() => {
6774                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6775                         {
6776                             var inReplyToStatusId = this.inReplyTo?.Item1;
6777                             var inReplyToScreenName = this.inReplyTo?.Item2;
6778                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6779                         }
6780                         _hisIdx += 1;
6781                         if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6782
6783                         var historyItem = this._history[this._hisIdx];
6784                         StatusText.Text = historyItem.status;
6785                         StatusText.SelectionStart = StatusText.Text.Length;
6786                         if (historyItem.inReplyToId != null)
6787                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6788                         else
6789                             this.inReplyTo = null;
6790                     }),
6791
6792                 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6793                     .FocusedOn(FocusedControl.StatusText)
6794                     .Do(() => {
6795                         if (ListTab.SelectedIndex == 0)
6796                         {
6797                             ListTab.SelectedIndex = ListTab.TabCount - 1;
6798                         }
6799                         else
6800                         {
6801                             ListTab.SelectedIndex -= 1;
6802                         }
6803                         StatusText.Focus();
6804                     }),
6805
6806                 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6807                     .FocusedOn(FocusedControl.StatusText)
6808                     .Do(() => {
6809                         if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6810                         {
6811                             ListTab.SelectedIndex = 0;
6812                         }
6813                         else
6814                         {
6815                             ListTab.SelectedIndex += 1;
6816                         }
6817                         StatusText.Focus();
6818                     }),
6819
6820                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6821                     .FocusedOn(FocusedControl.PostBrowser)
6822                     .Do(() => {
6823                         MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6824                         MultiLineMenuItem_Click(null, null);
6825                     }),
6826
6827                 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6828                     .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6829
6830                 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6831                     .Do(() => this.DoRefreshMore()),
6832
6833                 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6834                     .Do(() => this.GetReplyAsync(loadMore: true)),
6835
6836                 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6837                     .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6838
6839                 ShortcutCommand.Create(Keys.Shift | Keys.R)
6840                     .NotFocusedOn(FocusedControl.StatusText)
6841                     .Do(() => this.DoRefreshMore()),
6842
6843                 ShortcutCommand.Create(Keys.Shift | Keys.H)
6844                     .FocusedOn(FocusedControl.ListTab)
6845                     .Do(() => this.GoTopEnd(GoTop: true)),
6846
6847                 ShortcutCommand.Create(Keys.Shift | Keys.L)
6848                     .FocusedOn(FocusedControl.ListTab)
6849                     .Do(() => this.GoTopEnd(GoTop: false)),
6850
6851                 ShortcutCommand.Create(Keys.Shift | Keys.M)
6852                     .FocusedOn(FocusedControl.ListTab)
6853                     .Do(() => this.GoMiddle()),
6854
6855                 ShortcutCommand.Create(Keys.Shift | Keys.G)
6856                     .FocusedOn(FocusedControl.ListTab)
6857                     .Do(() => this.GoLast()),
6858
6859                 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6860                     .FocusedOn(FocusedControl.ListTab)
6861                     .Do(() => this.MoveMiddle()),
6862
6863                 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6864                     .FocusedOn(FocusedControl.ListTab)
6865                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6866
6867                 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6868                     .FocusedOn(FocusedControl.ListTab)
6869                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6870
6871                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6872                 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6873                     .FocusedOn(FocusedControl.ListTab)
6874                     .Do(() => this.GoFav(forward: true)),
6875
6876                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6877                 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6878                     .FocusedOn(FocusedControl.ListTab)
6879                     .Do(() => this.GoFav(forward: false)),
6880
6881                 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6882                     .FocusedOn(FocusedControl.ListTab)
6883                     .Do(() => this.GoBackSelectPostChain()),
6884
6885                 ShortcutCommand.Create(Keys.Alt | Keys.R)
6886                     .Do(() => this.doReTweetOfficial(isConfirm: true)),
6887
6888                 ShortcutCommand.Create(Keys.Alt | Keys.P)
6889                     .OnlyWhen(() => this._curPost != null)
6890                     .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6891
6892                 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6893                     .Do(() => this.ScrollDownPostBrowser(forward: false)),
6894
6895                 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6896                     .Do(() => this.ScrollDownPostBrowser(forward: true)),
6897
6898                 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6899                     .Do(() => this.PageDownPostBrowser(forward: false)),
6900
6901                 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6902                     .Do(() => this.PageDownPostBrowser(forward: true)),
6903
6904                 // 別タブの同じ書き込みへ(ALT+←/→)
6905                 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6906                     .FocusedOn(FocusedControl.ListTab)
6907                     .Do(() => this.GoSamePostToAnotherTab(left: false)),
6908
6909                 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6910                     .FocusedOn(FocusedControl.ListTab)
6911                     .Do(() => this.GoSamePostToAnotherTab(left: true)),
6912
6913                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6914                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6915
6916                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6917                     .Do(() => this.CopyIdUri()),
6918
6919                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6920                     .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6921                         this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6922                     .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6923
6924                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6925                     .Do(() => this.FavoriteChange(FavAdd: false)),
6926
6927                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6928                     .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6929
6930                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6931                     .Do(() => this.HashToggleMenuItem_Click(null, null)),
6932
6933                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6934                     .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6935
6936                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6937                     .Do(() => this.doMoveToRTHome()),
6938
6939                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6940                     .Do(() => this.FavorareMenuItem_Click(null, null)),
6941
6942                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6943                     .FocusedOn(FocusedControl.StatusText)
6944                     .Do(() => {
6945                         if (_curList != null && _curList.VirtualListSize != 0 &&
6946                                     _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6947                         {
6948                             var idx = _curList.SelectedIndices[0] - 1;
6949                             SelectListItem(_curList, idx);
6950                             _curList.EnsureVisible(idx);
6951                         }
6952                     }),
6953
6954                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6955                     .FocusedOn(FocusedControl.StatusText)
6956                     .Do(() => {
6957                         if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6958                                     && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6959                         {
6960                             var idx = _curList.SelectedIndices[0] + 1;
6961                             SelectListItem(_curList, idx);
6962                             _curList.EnsureVisible(idx);
6963                         }
6964                     }),
6965
6966                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6967                     .FocusedOn(FocusedControl.StatusText)
6968                     .Do(() => {
6969                         if (StatusText.SelectionStart > 0)
6970                         {
6971                             int endidx = StatusText.SelectionStart - 1;
6972                             string startstr = "";
6973                             for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6974                             {
6975                                 char c = StatusText.Text[i];
6976                                 if (Char.IsLetterOrDigit(c) || c == '_')
6977                                 {
6978                                     continue;
6979                                 }
6980                                 if (c == '@')
6981                                 {
6982                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6983                                     int cnt = AtIdSupl.ItemCount;
6984                                     ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6985                                     if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6986                                 }
6987                                 else if (c == '#')
6988                                 {
6989                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6990                                     ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6991                                 }
6992                                 else
6993                                 {
6994                                     break;
6995                                 }
6996                             }
6997                         }
6998                     }),
6999
7000                 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
7001                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
7002                     .FocusedOn(FocusedControl.ListTab)
7003                     .Do(() => this.SetSortColumnByDisplayIndex(0)),
7004
7005                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
7006                     .FocusedOn(FocusedControl.ListTab)
7007                     .Do(() => this.SetSortColumnByDisplayIndex(1)),
7008
7009                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
7010                     .FocusedOn(FocusedControl.ListTab)
7011                     .Do(() => this.SetSortColumnByDisplayIndex(2)),
7012
7013                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
7014                     .FocusedOn(FocusedControl.ListTab)
7015                     .Do(() => this.SetSortColumnByDisplayIndex(3)),
7016
7017                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
7018                     .FocusedOn(FocusedControl.ListTab)
7019                     .Do(() => this.SetSortColumnByDisplayIndex(4)),
7020
7021                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
7022                     .FocusedOn(FocusedControl.ListTab)
7023                     .Do(() => this.SetSortColumnByDisplayIndex(5)),
7024
7025                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
7026                     .FocusedOn(FocusedControl.ListTab)
7027                     .Do(() => this.SetSortColumnByDisplayIndex(6)),
7028
7029                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
7030                     .FocusedOn(FocusedControl.ListTab)
7031                     .Do(() => this.SetSortColumnByDisplayIndex(7)),
7032
7033                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
7034                     .FocusedOn(FocusedControl.ListTab)
7035                     .Do(() => this.SetSortLastColumn()),
7036
7037                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
7038                     .Do(() => this.FavoritesRetweetOfficial()),
7039
7040                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
7041                     .Do(() => this.FavoritesRetweetUnofficial()),
7042
7043                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
7044                     .Do(() => this.OpenUserAppointUrl()),
7045
7046                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7047                     .FocusedOn(FocusedControl.PostBrowser)
7048                     .Do(() => this.doReTweetUnofficial()),
7049
7050                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
7051                     .OnlyWhen(() => this.ExistCurrentPost)
7052                     .Do(() => this.doTranslation(_curPost.TextFromApi)),
7053
7054                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7055                     .Do(() => this.doReTweetUnofficial()),
7056
7057                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
7058                     .Do(() => this.CopyUserId()),
7059
7060                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
7061                     .Do(() => this.tweetThumbnail1.ScrollUp()),
7062
7063                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
7064                     .Do(() => this.tweetThumbnail1.ScrollDown()),
7065
7066                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
7067                     .FocusedOn(FocusedControl.ListTab)
7068                     .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
7069                     .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
7070             };
7071         }
7072
7073         private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
7074         {
7075             // Task を返す非同期処理があれば asyncTask に代入する
7076             asyncTask = null;
7077
7078             // ShortcutCommand に対応しているコマンドはここで処理される
7079             foreach (var command in this.shortcutCommands)
7080             {
7081                 if (command.IsMatch(keyData, focusedOn))
7082                 {
7083                     asyncTask = command.RunCommand();
7084                     return command.PreventDefault;
7085                 }
7086             }
7087
7088             return false;
7089         }
7090
7091         private void ScrollDownPostBrowser(bool forward)
7092         {
7093             var doc = PostBrowser.Document;
7094             if (doc == null) return;
7095
7096             var tags = doc.GetElementsByTagName("html");
7097             if (tags.Count > 0)
7098             {
7099                 if (forward)
7100                     tags[0].ScrollTop += this._fntDetail.Height;
7101                 else
7102                     tags[0].ScrollTop -= this._fntDetail.Height;
7103             }
7104         }
7105
7106         private void PageDownPostBrowser(bool forward)
7107         {
7108             var doc = PostBrowser.Document;
7109             if (doc == null) return;
7110
7111             var tags = doc.GetElementsByTagName("html");
7112             if (tags.Count > 0)
7113             {
7114                 if (forward)
7115                     tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7116                 else
7117                     tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7118             }
7119         }
7120
7121         private void GoNextTab(bool forward)
7122         {
7123             int idx = ListTab.SelectedIndex;
7124             if (forward)
7125             {
7126                 idx += 1;
7127                 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7128             }
7129             else
7130             {
7131                 idx -= 1;
7132                 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7133             }
7134             ListTab.SelectedIndex = idx;
7135         }
7136
7137         private void CopyStot()
7138         {
7139             string clstr = "";
7140             StringBuilder sb = new StringBuilder();
7141             bool IsProtected = false;
7142             bool isDm = false;
7143             if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7144             foreach (int idx in _curList.SelectedIndices)
7145             {
7146                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7147                 if (post.IsProtect)
7148                 {
7149                     IsProtected = true;
7150                     continue;
7151                 }
7152                 if (post.IsDeleted) continue;
7153                 if (!isDm)
7154                 {
7155                     if (post.RetweetedId != null)
7156                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7157                     else
7158                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7159                 }
7160                 else
7161                 {
7162                     sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7163                 }
7164             }
7165             if (IsProtected)
7166             {
7167                 MessageBox.Show(Properties.Resources.CopyStotText1);
7168             }
7169             if (sb.Length > 0)
7170             {
7171                 clstr = sb.ToString();
7172                 try
7173                 {
7174                     Clipboard.SetDataObject(clstr, false, 5, 100);
7175                 }
7176                 catch (Exception ex)
7177                 {
7178                     MessageBox.Show(ex.Message);
7179                 }
7180             }
7181         }
7182
7183         private void CopyIdUri()
7184         {
7185             string clstr = "";
7186             StringBuilder sb = new StringBuilder();
7187             if (this._curTab == null) return;
7188             if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7189             if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7190             foreach (int idx in _curList.SelectedIndices)
7191             {
7192                 var post = _statuses.Tabs[_curTab.Text][idx];
7193                 sb.Append(MyCommon.GetStatusUrl(post));
7194                 sb.Append(Environment.NewLine);
7195             }
7196             if (sb.Length > 0)
7197             {
7198                 clstr = sb.ToString();
7199                 try
7200                 {
7201                     Clipboard.SetDataObject(clstr, false, 5, 100);
7202                 }
7203                 catch (Exception ex)
7204                 {
7205                     MessageBox.Show(ex.Message);
7206                 }
7207             }
7208         }
7209
7210         private void GoFav(bool forward)
7211         {
7212             if (_curList.VirtualListSize == 0) return;
7213             int fIdx = 0;
7214             int toIdx = 0;
7215             int stp = 1;
7216
7217             if (forward)
7218             {
7219                 if (_curList.SelectedIndices.Count == 0)
7220                 {
7221                     fIdx = 0;
7222                 }
7223                 else
7224                 {
7225                     fIdx = _curList.SelectedIndices[0] + 1;
7226                     if (fIdx > _curList.VirtualListSize - 1) return;
7227                 }
7228                 toIdx = _curList.VirtualListSize;
7229                 stp = 1;
7230             }
7231             else
7232             {
7233                 if (_curList.SelectedIndices.Count == 0)
7234                 {
7235                     fIdx = _curList.VirtualListSize - 1;
7236                 }
7237                 else
7238                 {
7239                     fIdx = _curList.SelectedIndices[0] - 1;
7240                     if (fIdx < 0) return;
7241                 }
7242                 toIdx = -1;
7243                 stp = -1;
7244             }
7245
7246             for (int idx = fIdx; idx != toIdx; idx += stp)
7247             {
7248                 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7249                 {
7250                     SelectListItem(_curList, idx);
7251                     _curList.EnsureVisible(idx);
7252                     break;
7253                 }
7254             }
7255         }
7256
7257         private void GoSamePostToAnotherTab(bool left)
7258         {
7259             if (_curList.VirtualListSize == 0) return;
7260             int fIdx = 0;
7261             int toIdx = 0;
7262             int stp = 1;
7263             long targetId = 0;
7264
7265             if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7266             if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7267
7268             targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7269
7270             if (left)
7271             {
7272                 // 左のタブへ
7273                 if (ListTab.SelectedIndex == 0)
7274                 {
7275                     return;
7276                 }
7277                 else
7278                 {
7279                     fIdx = ListTab.SelectedIndex - 1;
7280                 }
7281                 toIdx = -1;
7282                 stp = -1;
7283             }
7284             else
7285             {
7286                 // 右のタブへ
7287                 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7288                 {
7289                     return;
7290                 }
7291                 else
7292                 {
7293                     fIdx = ListTab.SelectedIndex + 1;
7294                 }
7295                 toIdx = ListTab.TabCount;
7296                 stp = 1;
7297             }
7298
7299             bool found = false;
7300             for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7301             {
7302                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7303                 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7304                 {
7305                     if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7306                     {
7307                         ListTab.SelectedIndex = tabidx;
7308                         SelectListItem(_curList, idx);
7309                         _curList.EnsureVisible(idx);
7310                         found = true;
7311                         break;
7312                     }
7313                 }
7314                 if (found) break;
7315             }
7316         }
7317
7318         private void GoPost(bool forward)
7319         {
7320             if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7321             int fIdx = 0;
7322             int toIdx = 0;
7323             int stp = 1;
7324
7325             if (forward)
7326             {
7327                 fIdx = _curList.SelectedIndices[0] + 1;
7328                 if (fIdx > _curList.VirtualListSize - 1) return;
7329                 toIdx = _curList.VirtualListSize;
7330                 stp = 1;
7331             }
7332             else
7333             {
7334                 fIdx = _curList.SelectedIndices[0] - 1;
7335                 if (fIdx < 0) return;
7336                 toIdx = -1;
7337                 stp = -1;
7338             }
7339
7340             string name = "";
7341             if (_curPost.RetweetedId == null)
7342             {
7343                 name = _curPost.ScreenName;
7344             }
7345             else
7346             {
7347                 name = _curPost.RetweetedBy;
7348             }
7349             for (int idx = fIdx; idx != toIdx; idx += stp)
7350             {
7351                 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7352                 {
7353                     if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7354                     {
7355                         SelectListItem(_curList, idx);
7356                         _curList.EnsureVisible(idx);
7357                         break;
7358                     }
7359                 }
7360                 else
7361                 {
7362                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7363                     {
7364                         SelectListItem(_curList, idx);
7365                         _curList.EnsureVisible(idx);
7366                         break;
7367                     }
7368                 }
7369             }
7370         }
7371
7372         private void GoRelPost(bool forward)
7373         {
7374             if (_curList.SelectedIndices.Count == 0) return;
7375
7376             int fIdx = 0;
7377             int toIdx = 0;
7378             int stp = 1;
7379             if (forward)
7380             {
7381                 fIdx = _curList.SelectedIndices[0] + 1;
7382                 if (fIdx > _curList.VirtualListSize - 1) return;
7383                 toIdx = _curList.VirtualListSize;
7384                 stp = 1;
7385             }
7386             else
7387             {
7388                 fIdx = _curList.SelectedIndices[0] - 1;
7389                 if (fIdx < 0) return;
7390                 toIdx = -1;
7391                 stp = -1;
7392             }
7393
7394             if (!_anchorFlag)
7395             {
7396                 if (_curPost == null) return;
7397                 _anchorPost = _curPost;
7398                 _anchorFlag = true;
7399             }
7400             else
7401             {
7402                 if (_anchorPost == null) return;
7403             }
7404
7405             for (int idx = fIdx; idx != toIdx; idx += stp)
7406             {
7407                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7408                 if (post.ScreenName == _anchorPost.ScreenName ||
7409                     post.RetweetedBy == _anchorPost.ScreenName ||
7410                     post.ScreenName == _anchorPost.RetweetedBy ||
7411                     (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7412                     _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
7413                     _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
7414                     post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
7415                     post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
7416                 {
7417                     SelectListItem(_curList, idx);
7418                     _curList.EnsureVisible(idx);
7419                     break;
7420                 }
7421             }
7422         }
7423
7424         private void GoAnchor()
7425         {
7426             if (_anchorPost == null) return;
7427             int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7428             if (idx == -1) return;
7429
7430             SelectListItem(_curList, idx);
7431             _curList.EnsureVisible(idx);
7432         }
7433
7434         private void GoTopEnd(bool GoTop)
7435         {
7436             if (_curList.VirtualListSize == 0)
7437                 return;
7438
7439             ListViewItem _item;
7440             int idx;
7441
7442             if (GoTop)
7443             {
7444                 _item = _curList.GetItemAt(0, 25);
7445                 if (_item == null)
7446                     idx = 0;
7447                 else
7448                     idx = _item.Index;
7449             }
7450             else
7451             {
7452                 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7453                 if (_item == null)
7454                     idx = _curList.VirtualListSize - 1;
7455                 else
7456                     idx = _item.Index;
7457             }
7458             SelectListItem(_curList, idx);
7459         }
7460
7461         private void GoMiddle()
7462         {
7463             if (_curList.VirtualListSize == 0)
7464                 return;
7465
7466             ListViewItem _item;
7467             int idx1;
7468             int idx2;
7469             int idx3;
7470
7471             _item = _curList.GetItemAt(0, 0);
7472             if (_item == null)
7473             {
7474                 idx1 = 0;
7475             }
7476             else
7477             {
7478                 idx1 = _item.Index;
7479             }
7480
7481             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7482             if (_item == null)
7483             {
7484                 idx2 = _curList.VirtualListSize - 1;
7485             }
7486             else
7487             {
7488                 idx2 = _item.Index;
7489             }
7490             idx3 = (idx1 + idx2) / 2;
7491
7492             SelectListItem(_curList, idx3);
7493         }
7494
7495         private void GoLast()
7496         {
7497             if (_curList.VirtualListSize == 0) return;
7498
7499             if (_statuses.SortOrder == SortOrder.Ascending)
7500             {
7501                 SelectListItem(_curList, _curList.VirtualListSize - 1);
7502                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7503             }
7504             else
7505             {
7506                 SelectListItem(_curList, 0);
7507                 _curList.EnsureVisible(0);
7508             }
7509         }
7510
7511         private void MoveTop()
7512         {
7513             if (_curList.SelectedIndices.Count == 0) return;
7514             int idx = _curList.SelectedIndices[0];
7515             if (_statuses.SortOrder == SortOrder.Ascending)
7516             {
7517                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7518             }
7519             else
7520             {
7521                 _curList.EnsureVisible(0);
7522             }
7523             _curList.EnsureVisible(idx);
7524         }
7525
7526         private async Task GoInReplyToPostTree()
7527         {
7528             if (_curPost == null) return;
7529
7530             TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7531
7532             if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7533             {
7534                 try
7535                 {
7536                     var post = await tw.GetStatusApi(false, _curPost.StatusId);
7537
7538                     _curPost.InReplyToStatusId = post.InReplyToStatusId;
7539                     _curPost.InReplyToUser = post.InReplyToUser;
7540                     _curPost.IsReply = post.IsReply;
7541                     this.PurgeListViewItemCache();
7542                     _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7543                 }
7544                 catch (WebApiException ex)
7545                 {
7546                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7547                 }
7548             }
7549
7550             if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7551
7552             if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7553             {
7554                 replyChains = new Stack<ReplyChain>();
7555             }
7556             replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7557
7558             int inReplyToIndex;
7559             string inReplyToTabName;
7560             long inReplyToId = _curPost.InReplyToStatusId.Value;
7561             string inReplyToUser = _curPost.InReplyToUser;
7562             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7563
7564             var inReplyToPosts = from tab in _statuses.Tabs.Values
7565                                  orderby tab != curTabClass
7566                                  from post in tab.Posts.Values
7567                                  where post.StatusId == inReplyToId
7568                                  let index = tab.IndexOf(post.StatusId)
7569                                  where index != -1
7570                                  select new {Tab = tab, Index = index};
7571
7572             var inReplyPost = inReplyToPosts.FirstOrDefault();
7573             if (inReplyPost == null)
7574             {
7575                 try
7576                 {
7577                     await Task.Run(async () =>
7578                     {
7579                         var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
7580                             .ConfigureAwait(false);
7581                         post.IsRead = true;
7582
7583                         _statuses.AddPost(post);
7584                         _statuses.DistributePosts();
7585                     });
7586                 }
7587                 catch (WebApiException ex)
7588                 {
7589                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7590                     await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7591                     return;
7592                 }
7593
7594                 this.RefreshTimeline();
7595
7596                 inReplyPost = inReplyToPosts.FirstOrDefault();
7597                 if (inReplyPost == null)
7598                 {
7599                     await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7600                     return;
7601                 }
7602             }
7603             inReplyToTabName = inReplyPost.Tab.TabName;
7604             inReplyToIndex = inReplyPost.Index;
7605
7606             TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7607             DetailsListView listView = (DetailsListView)tabPage.Tag;
7608
7609             if (_curTab != tabPage)
7610             {
7611                 this.ListTab.SelectTab(tabPage);
7612             }
7613
7614             this.SelectListItem(listView, inReplyToIndex);
7615             listView.EnsureVisible(inReplyToIndex);
7616         }
7617
7618         private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7619         {
7620             if (_curPost == null) return;
7621
7622             TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7623             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7624
7625             if (parallel)
7626             {
7627                 if (_curPost.InReplyToStatusId != null)
7628                 {
7629                     var posts = from t in _statuses.Tabs
7630                                 from p in t.Value.Posts
7631                                 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7632                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7633                                 where indexOf > -1
7634                                 orderby isForward ? indexOf : indexOf * -1
7635                                 orderby t.Value != curTabClass
7636                                 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7637                     try
7638                     {
7639                         var postList = posts.ToList();
7640                         for (int i = postList.Count - 1; i >= 0; i--)
7641                         {
7642                             int index = i;
7643                             if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7644                             {
7645                                 postList.RemoveAt(index);
7646                             }
7647                         }
7648                         var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7649                         if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7650                         if (post == null) post = postList.First();
7651                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7652                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7653                         SelectListItem(listView, post.Index);
7654                         listView.EnsureVisible(post.Index);
7655                     }
7656                     catch (InvalidOperationException)
7657                     {
7658                         return;
7659                     }
7660                 }
7661             }
7662             else
7663             {
7664                 if (replyChains == null || replyChains.Count < 1)
7665                 {
7666                     var posts = from t in _statuses.Tabs
7667                                 from p in t.Value.Posts
7668                                 where p.Value.InReplyToStatusId == _curPost.StatusId
7669                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7670                                 where indexOf > -1
7671                                 orderby indexOf
7672                                 orderby t.Value != curTabClass
7673                                 select new {Tab = t.Value, Index = indexOf};
7674                     try
7675                     {
7676                         var post = posts.First();
7677                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7678                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7679                         SelectListItem(listView, post.Index);
7680                         listView.EnsureVisible(post.Index);
7681                     }
7682                     catch (InvalidOperationException)
7683                     {
7684                         return;
7685                     }
7686                 }
7687                 else
7688                 {
7689                     ReplyChain chainHead = replyChains.Pop();
7690                     if (chainHead.InReplyToId == _curPost.StatusId)
7691                     {
7692                         int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7693                         if (idx == -1)
7694                         {
7695                             replyChains = null;
7696                         }
7697                         else
7698                         {
7699                             try
7700                             {
7701                                 ListTab.SelectTab(chainHead.OriginalTab);
7702                             }
7703                             catch (Exception)
7704                             {
7705                                 replyChains = null;
7706                             }
7707                             SelectListItem(_curList, idx);
7708                             _curList.EnsureVisible(idx);
7709                         }
7710                     }
7711                     else
7712                     {
7713                         replyChains = null;
7714                         this.GoBackInReplyToPostTree(parallel);
7715                     }
7716                 }
7717             }
7718         }
7719
7720         private void GoBackSelectPostChain()
7721         {
7722             if (this.selectPostChains.Count > 1)
7723             {
7724                 var idx = -1;
7725                 TabPage tp = null;
7726
7727                 do
7728                 {
7729                     try
7730                     {
7731                         this.selectPostChains.Pop();
7732                         var tabPostPair = this.selectPostChains.Peek();
7733
7734                         if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue;  //該当タブが存在しないので無視
7735
7736                         if (tabPostPair.Item2 != null)
7737                         {
7738                             idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7739                             if (idx == -1) continue;  //該当ポストが存在しないので無視
7740                         }
7741
7742                         tp = tabPostPair.Item1;
7743
7744                         this.selectPostChains.Pop();
7745                     }
7746                     catch (InvalidOperationException)
7747                     {
7748                     }
7749
7750                     break;
7751                 }
7752                 while (this.selectPostChains.Count > 1);
7753
7754                 if (tp == null)
7755                 {
7756                     //状態がおかしいので処理を中断
7757                     //履歴が残り1つであればクリアしておく
7758                     if (this.selectPostChains.Count == 1)
7759                         this.selectPostChains.Clear();
7760                     return;
7761                 }
7762
7763                 DetailsListView lst = (DetailsListView)tp.Tag;
7764                 this.ListTab.SelectedTab = tp;
7765                 if (idx > -1)
7766                 {
7767                     SelectListItem(lst, idx);
7768                     lst.EnsureVisible(idx);
7769                 }
7770                 lst.Focus();
7771             }
7772         }
7773
7774         private void PushSelectPostChain()
7775         {
7776             int count = this.selectPostChains.Count;
7777             if (count > 0)
7778             {
7779                 var p = this.selectPostChains.Peek();
7780                 if (p.Item1 == this._curTab)
7781                 {
7782                     if (p.Item2 == this._curPost) return;  //最新の履歴と同一
7783                     if (p.Item2 == null) this.selectPostChains.Pop();  //置き換えるため削除
7784                 }
7785             }
7786             if (count >= 2500) TrimPostChain();
7787             this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7788         }
7789
7790         private void TrimPostChain()
7791         {
7792             if (this.selectPostChains.Count <= 2000) return;
7793             var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7794             for (int i = 0; i < 2000; i++)
7795             {
7796                 p.Push(this.selectPostChains.Pop());
7797             }
7798             this.selectPostChains.Clear();
7799             for (int i = 0; i < 2000; i++)
7800             {
7801                 this.selectPostChains.Push(p.Pop());
7802             }
7803         }
7804
7805         private bool GoStatus(long statusId)
7806         {
7807             if (statusId == 0) return false;
7808             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7809             {
7810                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7811                 {
7812                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7813                     ListTab.SelectedIndex = tabidx;
7814                     SelectListItem(_curList, idx);
7815                     _curList.EnsureVisible(idx);
7816                     return true;
7817                 }
7818             }
7819             return false;
7820         }
7821
7822         private bool GoDirectMessage(long statusId)
7823         {
7824             if (statusId == 0) return false;
7825             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7826             {
7827                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7828                 {
7829                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7830                     ListTab.SelectedIndex = tabidx;
7831                     SelectListItem(_curList, idx);
7832                     _curList.EnsureVisible(idx);
7833                     return true;
7834                 }
7835             }
7836             return false;
7837         }
7838
7839         private void MyList_MouseClick(object sender, MouseEventArgs e)
7840         {
7841             _anchorFlag = false;
7842         }
7843
7844         private void StatusText_Enter(object sender, EventArgs e)
7845         {
7846             // フォーカスの戻り先を StatusText に設定
7847             this.Tag = StatusText;
7848             StatusText.BackColor = _clInputBackcolor;
7849         }
7850
7851         public Color InputBackColor
7852         {
7853             get { return _clInputBackcolor; }
7854             set { _clInputBackcolor = value; }
7855         }
7856
7857         private void StatusText_Leave(object sender, EventArgs e)
7858         {
7859             // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7860             if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7861             StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7862         }
7863
7864         private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7865         {
7866             Task asyncTask;
7867             if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7868             {
7869                 e.Handled = true;
7870                 e.SuppressKeyPress = true;
7871             }
7872
7873             this.StatusText_TextChanged(null, null);
7874
7875             if (asyncTask != null)
7876                 await asyncTask;
7877         }
7878
7879         private void SaveConfigsAll(bool ifModified)
7880         {
7881             if (!ifModified)
7882             {
7883                 SaveConfigsCommon();
7884                 SaveConfigsLocal();
7885                 SaveConfigsTabs();
7886                 SaveConfigsAtId();
7887             }
7888             else
7889             {
7890                 if (ModifySettingCommon) SaveConfigsCommon();
7891                 if (ModifySettingLocal) SaveConfigsLocal();
7892                 if (ModifySettingAtId) SaveConfigsAtId();
7893             }
7894         }
7895
7896         private void SaveConfigsAtId()
7897         {
7898             if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7899
7900             ModifySettingAtId = false;
7901             SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7902             cfgAtId.Save();
7903         }
7904
7905         private void SaveConfigsCommon()
7906         {
7907             if (_ignoreConfigSave) return;
7908
7909             ModifySettingCommon = false;
7910             lock (_syncObject)
7911             {
7912                 _cfgCommon.UserName = tw.Username;
7913                 _cfgCommon.UserId = tw.UserId;
7914                 _cfgCommon.Password = tw.Password;
7915                 _cfgCommon.Token = tw.AccessToken;
7916                 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7917
7918                 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7919                    IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7920                 {
7921                     _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7922                 }
7923
7924                 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7925                 switch (_statuses.SortMode)
7926                 {
7927                     case ComparerMode.Nickname:  //ニックネーム
7928                         _cfgCommon.SortColumn = 1;
7929                         break;
7930                     case ComparerMode.Data:  //本文
7931                         _cfgCommon.SortColumn = 2;
7932                         break;
7933                     case ComparerMode.Id:  //時刻=発言Id
7934                         _cfgCommon.SortColumn = 3;
7935                         break;
7936                     case ComparerMode.Name:  //名前
7937                         _cfgCommon.SortColumn = 4;
7938                         break;
7939                     case ComparerMode.Source:  //Source
7940                         _cfgCommon.SortColumn = 7;
7941                         break;
7942                 }
7943
7944                 _cfgCommon.HashTags = HashMgr.HashHistories;
7945                 if (HashMgr.IsPermanent)
7946                 {
7947                     _cfgCommon.HashSelected = HashMgr.UseHash;
7948                 }
7949                 else
7950                 {
7951                     _cfgCommon.HashSelected = "";
7952                 }
7953                 _cfgCommon.HashIsHead = HashMgr.IsHead;
7954                 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7955                 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7956                 if (ToolStripFocusLockMenuItem != null &&
7957                         ToolStripFocusLockMenuItem.IsDisposed == false)
7958                 {
7959                     _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7960                 }
7961                 _cfgCommon.TrackWord = tw.TrackWord;
7962                 _cfgCommon.AllAtReply = tw.AllAtReply;
7963                 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7964                 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7965
7966                 _cfgCommon.Save();
7967             }
7968         }
7969
7970         private void SaveConfigsLocal()
7971         {
7972             if (_ignoreConfigSave) return;
7973             lock (_syncObject)
7974             {
7975                 ModifySettingLocal = false;
7976                 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7977                 _cfgLocal.FormSize = _mySize;
7978                 _cfgLocal.FormLocation = _myLoc;
7979                 _cfgLocal.SplitterDistance = _mySpDis;
7980                 _cfgLocal.PreviewDistance = _mySpDis3;
7981                 _cfgLocal.StatusMultiline = StatusText.Multiline;
7982                 _cfgLocal.StatusTextHeight = _mySpDis2;
7983
7984                 _cfgLocal.FontUnread = _fntUnread;
7985                 _cfgLocal.ColorUnread = _clUnread;
7986                 _cfgLocal.FontRead = _fntReaded;
7987                 _cfgLocal.ColorRead = _clReaded;
7988                 _cfgLocal.FontDetail = _fntDetail;
7989                 _cfgLocal.ColorDetail = _clDetail;
7990                 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7991                 _cfgLocal.ColorDetailLink = _clDetailLink;
7992                 _cfgLocal.ColorFav = _clFav;
7993                 _cfgLocal.ColorOWL = _clOWL;
7994                 _cfgLocal.ColorRetweet = _clRetweet;
7995                 _cfgLocal.ColorSelf = _clSelf;
7996                 _cfgLocal.ColorAtSelf = _clAtSelf;
7997                 _cfgLocal.ColorTarget = _clTarget;
7998                 _cfgLocal.ColorAtTarget = _clAtTarget;
7999                 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
8000                 _cfgLocal.ColorAtTo = _clAtTo;
8001                 _cfgLocal.ColorListBackcolor = _clListBackcolor;
8002                 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
8003                 _cfgLocal.ColorInputFont = _clInputFont;
8004                 _cfgLocal.FontInputFont = _fntInputFont;
8005
8006                 if (_ignoreConfigSave) return;
8007                 _cfgLocal.Save();
8008             }
8009         }
8010
8011         private void SaveConfigsTabs()
8012         {
8013             SettingTabs tabSetting = new SettingTabs();
8014             for (int i = 0; i < ListTab.TabPages.Count; i++)
8015             {
8016                 var tab = _statuses.Tabs[ListTab.TabPages[i].Text];
8017                 if (tab.TabType != MyCommon.TabUsageType.Related && tab.TabType != MyCommon.TabUsageType.SearchResults)
8018                     tabSetting.Tabs.Add(tab);
8019             }
8020             tabSetting.Tabs.Add(this._statuses.GetTabByType(MyCommon.TabUsageType.Mute));
8021             tabSetting.Save();
8022         }
8023
8024         private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
8025         {
8026             string inputText;
8027             var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
8028             if (ret != DialogResult.OK)
8029                 return;
8030
8031             var match = Twitter.StatusUrlRegex.Match(inputText);
8032             if (!match.Success)
8033             {
8034                 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8035                     Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8036                 return;
8037             }
8038
8039             try
8040             {
8041                 var statusId = long.Parse(match.Groups["StatusId"].Value);
8042                 await this.OpenRelatedTab(statusId);
8043             }
8044             catch (TabException ex)
8045             {
8046                 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8047             }
8048         }
8049
8050         private void SaveLogMenuItem_Click(object sender, EventArgs e)
8051         {
8052             DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8053                     Properties.Resources.SaveLogMenuItem_ClickText2,
8054                     MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8055             if (rslt == DialogResult.Cancel) return;
8056
8057             SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8058             SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8059             SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8060             SaveFileDialog1.FilterIndex = 0;
8061             SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8062             SaveFileDialog1.RestoreDirectory = true;
8063
8064             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8065             {
8066                 if (!SaveFileDialog1.ValidateNames) return;
8067                 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8068                 {
8069                     if (rslt == DialogResult.Yes)
8070                     {
8071                         //All
8072                         for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8073                         {
8074                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
8075                             string protect = "";
8076                             if (post.IsProtect) protect = "Protect";
8077                             sw.WriteLine(post.Nickname + "\t" +
8078                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8079                                      post.CreatedAt.ToString() + "\t" +
8080                                      post.ScreenName + "\t" +
8081                                      post.StatusId.ToString() + "\t" +
8082                                      post.ImageUrl + "\t" +
8083                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8084                                      protect);
8085                         }
8086                     }
8087                     else
8088                     {
8089                         foreach (int idx in _curList.SelectedIndices)
8090                         {
8091                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
8092                             string protect = "";
8093                             if (post.IsProtect) protect = "Protect";
8094                             sw.WriteLine(post.Nickname + "\t" +
8095                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8096                                      post.CreatedAt.ToString() + "\t" +
8097                                      post.ScreenName + "\t" +
8098                                      post.StatusId.ToString() + "\t" +
8099                                      post.ImageUrl + "\t" +
8100                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8101                                      protect);
8102                         }
8103                     }
8104                 }
8105             }
8106             this.TopMost = this._cfgCommon.AlwaysTop;
8107         }
8108
8109         private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8110         {
8111             Task asyncTask;
8112             bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
8113             if (KeyRes)
8114             {
8115                 e.IsInputKey = true;
8116             }
8117             else
8118             {
8119                 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8120                 {
8121                     var shortcut = (Shortcut)e.KeyData;
8122                     switch (shortcut)
8123                     {
8124                         case Shortcut.CtrlA:
8125                         case Shortcut.CtrlC:
8126                         case Shortcut.CtrlIns:
8127                             // 既定の動作を有効にする
8128                             break;
8129                         default:
8130                             // その他のショートカットキーは無効にする
8131                             e.IsInputKey = true;
8132                             break;
8133                     }
8134                 }
8135             }
8136
8137             if (asyncTask != null)
8138                 await asyncTask;
8139         }
8140         public bool TabRename(ref string tabName)
8141         {
8142             //タブ名変更
8143             string newTabText = null;
8144             using (InputTabName inputName = new InputTabName())
8145             {
8146                 inputName.TabName = tabName;
8147                 inputName.ShowDialog();
8148                 if (inputName.DialogResult == DialogResult.Cancel) return false;
8149                 newTabText = inputName.TabName;
8150             }
8151             this.TopMost = this._cfgCommon.AlwaysTop;
8152             if (!string.IsNullOrEmpty(newTabText))
8153             {
8154                 //新タブ名存在チェック
8155                 for (int i = 0; i < ListTab.TabCount; i++)
8156                 {
8157                     if (ListTab.TabPages[i].Text == newTabText)
8158                     {
8159                         string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8160                         MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8161                         return false;
8162                     }
8163                 }
8164                 //タブ名を変更
8165                 for (int i = 0; i < ListTab.TabCount; i++)
8166                 {
8167                     if (ListTab.TabPages[i].Text == tabName)
8168                     {
8169                         ListTab.TabPages[i].Text = newTabText;
8170                         break;
8171                     }
8172                 }
8173                 _statuses.RenameTab(tabName, newTabText);
8174
8175                 SaveConfigsCommon();
8176                 SaveConfigsTabs();
8177                 _rclickTabName = newTabText;
8178                 tabName = newTabText;
8179                 return true;
8180             }
8181             else
8182             {
8183                 return false;
8184             }
8185         }
8186
8187         private void ListTab_MouseClick(object sender, MouseEventArgs e)
8188         {
8189             if (e.Button == MouseButtons.Middle)
8190             {
8191                 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8192                 {
8193                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8194                     {
8195                         this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8196                         this.SaveConfigsTabs();
8197                         break;
8198                     }
8199                 }
8200             }
8201         }
8202
8203         private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8204         {
8205             string tn = ListTab.SelectedTab.Text;
8206             TabRename(ref tn);
8207         }
8208
8209         private void ListTab_MouseDown(object sender, MouseEventArgs e)
8210         {
8211             if (this._cfgCommon.TabMouseLock) return;
8212             Point cpos = new Point(e.X, e.Y);
8213             if (e.Button == MouseButtons.Left)
8214             {
8215                 for (int i = 0; i < ListTab.TabPages.Count; i++)
8216                 {
8217                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8218                     {
8219                         _tabDrag = true;
8220                         _tabMouseDownPoint = e.Location;
8221                         break;
8222                     }
8223                 }
8224             }
8225             else
8226             {
8227                 _tabDrag = false;
8228             }
8229         }
8230
8231         private void ListTab_DragEnter(object sender, DragEventArgs e)
8232         {
8233             if (e.Data.GetDataPresent(typeof(TabPage)))
8234                 e.Effect = DragDropEffects.Move;
8235             else
8236                 e.Effect = DragDropEffects.None;
8237         }
8238
8239         private void ListTab_DragDrop(object sender, DragEventArgs e)
8240         {
8241             if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8242
8243             _tabDrag = false;
8244             string tn = "";
8245             bool bef = false;
8246             Point cpos = new Point(e.X, e.Y);
8247             Point spos = ListTab.PointToClient(cpos);
8248             int i;
8249             for (i = 0; i < ListTab.TabPages.Count; i++)
8250             {
8251                 Rectangle rect = ListTab.GetTabRect(i);
8252                 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8253                     rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8254                 {
8255                     tn = ListTab.TabPages[i].Text;
8256                     if (spos.X <= (rect.Left + rect.Right) / 2)
8257                         bef = true;
8258                     else
8259                         bef = false;
8260
8261                     break;
8262                 }
8263             }
8264
8265             //タブのないところにドロップ->最後尾へ移動
8266             if (string.IsNullOrEmpty(tn))
8267             {
8268                 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8269                 bef = false;
8270                 i = ListTab.TabPages.Count - 1;
8271             }
8272
8273             TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8274             if (tp.Text == tn) return;
8275
8276             ReOrderTab(tp.Text, tn, bef);
8277         }
8278
8279         public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8280         {
8281             var baseIndex = this.GetTabPageIndex(baseTabText);
8282             if (baseIndex == -1)
8283                 return;
8284
8285             var targetIndex = this.GetTabPageIndex(targetTabText);
8286             if (targetIndex == -1)
8287                 return;
8288
8289             using (ControlTransaction.Layout(this.ListTab))
8290             {
8291                 var mTp = this.ListTab.TabPages[targetIndex];
8292                 this.ListTab.TabPages.Remove(mTp);
8293
8294                 if (targetIndex < baseIndex)
8295                     baseIndex--;
8296
8297                 if (isBeforeBaseTab)
8298                     ListTab.TabPages.Insert(baseIndex, mTp);
8299                 else
8300                     ListTab.TabPages.Insert(baseIndex + 1, mTp);
8301             }
8302
8303             SaveConfigsTabs();
8304         }
8305
8306         private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8307         {
8308             //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8309             //isReply:true=@,false=DM
8310             if (!StatusText.Enabled) return;
8311             if (_curList == null) return;
8312             if (_curTab == null) return;
8313             if (!this.ExistCurrentPost) return;
8314
8315             // 複数あてリプライはReplyではなく通常ポスト
8316             //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8317             //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8318             //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8319
8320             if (_curList.SelectedIndices.Count > 0)
8321             {
8322                 // アイテムが1件以上選択されている
8323                 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8324                 {
8325                     // 単独ユーザー宛リプライまたはDM
8326                     if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8327                     {
8328                         // ダイレクトメッセージ
8329                         StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8330                         StatusText.SelectionStart = StatusText.Text.Length;
8331                         StatusText.Focus();
8332                         this.inReplyTo = null;
8333                         return;
8334                     }
8335                     if (string.IsNullOrEmpty(StatusText.Text))
8336                     {
8337                         //空の場合
8338
8339                         // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8340                         StatusText.Text = "@" + _curPost.ScreenName + " ";
8341
8342                         var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8343                         var inReplyToScreenName = this._curPost.ScreenName;
8344                         this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8345                     }
8346                     else
8347                     {
8348                         //何か入力済の場合
8349
8350                         if (isAuto)
8351                         {
8352                             //1件選んでEnter or DoubleClick
8353                             if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8354                             {
8355                                 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
8356                                 {
8357                                     //返信先書き換え
8358                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8359                                     var inReplyToScreenName = this._curPost.ScreenName;
8360                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8361                                 }
8362                                 return;
8363                             }
8364                             if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
8365                             {
8366                                 //文頭@以外
8367                                 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8368                                 {
8369                                     // 複数リプライ
8370                                     StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8371                                     this.inReplyTo = null;
8372                                 }
8373                                 else
8374                                 {
8375                                     // 単独リプライ
8376                                     StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8377                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8378                                     var inReplyToScreenName = this._curPost.ScreenName;
8379                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8380                                 }
8381                             }
8382                             else
8383                             {
8384                                 //文頭@
8385                                 // 複数リプライ
8386                                 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8387                                 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8388                                 this.inReplyTo = null;
8389                             }
8390                         }
8391                         else
8392                         {
8393                             //1件選んでCtrl-Rの場合(返信先操作せず)
8394                             int sidx = StatusText.SelectionStart;
8395                             string id = "@" + _curPost.ScreenName + " ";
8396                             if (sidx > 0)
8397                             {
8398                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8399                                 {
8400                                     id = " " + id;
8401                                 }
8402                             }
8403                             StatusText.Text = StatusText.Text.Insert(sidx, id);
8404                             sidx += id.Length;
8405                             //if (StatusText.Text.StartsWith("@"))
8406                             //{
8407                             //    //複数リプライ
8408                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8409                             //    sidx += 5 + _curPost.ScreenName.Length;
8410                             //}
8411                             //else
8412                             //{
8413                             //    // 複数リプライ
8414                             //    StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8415                             //    sidx += 3 + _curPost.ScreenName.Length;
8416                             //}
8417                             StatusText.SelectionStart = sidx;
8418                             StatusText.Focus();
8419                             //_reply_to_id = 0;
8420                             //_reply_to_name = null;
8421                             return;
8422                         }
8423                     }
8424                 }
8425                 else
8426                 {
8427                     // 複数リプライ
8428                     if (!isAuto && !isReply) return;
8429
8430                     //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8431
8432                     if (isAuto)
8433                     {
8434                         //Enter or DoubleClick
8435
8436                         string sTxt = StatusText.Text;
8437                         if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
8438                         {
8439                             sTxt = ". " + sTxt;
8440                             this.inReplyTo = null;
8441                         }
8442                         for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8443                         {
8444                             PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8445                             if (!sTxt.Contains("@" + post.ScreenName + " "))
8446                             {
8447                                 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8448                                 //sTxt = "@" + post.ScreenName + " " + sTxt;
8449                             }
8450                         }
8451                         StatusText.Text = sTxt;
8452                     }
8453                     else
8454                     {
8455                         //C-S-r or C-r
8456                         if (_curList.SelectedIndices.Count > 1)
8457                         {
8458                             //複数ポスト選択
8459
8460                             string ids = "";
8461                             int sidx = StatusText.SelectionStart;
8462                             for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8463                             {
8464                                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8465                                 if (!ids.Contains("@" + post.ScreenName + " ") &&
8466                                     !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8467                                 {
8468                                     ids += "@" + post.ScreenName + " ";
8469                                 }
8470                                 if (isAll)
8471                                 {
8472                                     foreach (string nm in post.ReplyToList)
8473                                     {
8474                                         if (!ids.Contains("@" + nm + " ") &&
8475                                             !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8476                                         {
8477                                             Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8478                                             if (m.Success)
8479                                                 ids += "@" + m.Result("${id}") + " ";
8480                                             else
8481                                                 ids += "@" + nm + " ";
8482                                         }
8483                                     }
8484                                 }
8485                             }
8486                             if (ids.Length == 0) return;
8487                             if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8488                             {
8489                                 StatusText.Text = ". " + StatusText.Text;
8490                                 sidx += 2;
8491                                 this.inReplyTo = null;
8492                             }
8493                             if (sidx > 0)
8494                             {
8495                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8496                                 {
8497                                     ids = " " + ids;
8498                                 }
8499                             }
8500                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8501                             sidx += ids.Length;
8502                             //if (StatusText.Text.StartsWith("@"))
8503                             //{
8504                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8505                             //    sidx += 2 + ids.Length;
8506                             //}
8507                             //else
8508                             //{
8509                             //    StatusText.Text = StatusText.Text.Insert(sidx, ids);
8510                             //    sidx += 1 + ids.Length;
8511                             //}
8512                             StatusText.SelectionStart = sidx;
8513                             StatusText.Focus();
8514                             return;
8515                         }
8516                         else
8517                         {
8518                             //1件のみ選択のC-S-r(返信元付加する可能性あり)
8519
8520                             string ids = "";
8521                             int sidx = StatusText.SelectionStart;
8522                             PostClass post = _curPost;
8523                             if (!ids.Contains("@" + post.ScreenName + " ") &&
8524                                 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8525                             {
8526                                 ids += "@" + post.ScreenName + " ";
8527                             }
8528                             foreach (string nm in post.ReplyToList)
8529                             {
8530                                 if (!ids.Contains("@" + nm + " ") &&
8531                                     !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8532                                 {
8533                                     Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8534                                     if (m.Success)
8535                                         ids += "@" + m.Result("${id}") + " ";
8536                                     else
8537                                         ids += "@" + nm + " ";
8538                                 }
8539                             }
8540                             if (!string.IsNullOrEmpty(post.RetweetedBy))
8541                             {
8542                                 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8543                                    !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8544                                 {
8545                                     ids += "@" + post.RetweetedBy + " ";
8546                                 }
8547                             }
8548                             if (ids.Length == 0) return;
8549                             if (string.IsNullOrEmpty(StatusText.Text))
8550                             {
8551                                 //未入力の場合のみ返信先付加
8552                                 StatusText.Text = ids;
8553                                 StatusText.SelectionStart = ids.Length;
8554                                 StatusText.Focus();
8555
8556                                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8557                                 var inReplyToScreenName = this._curPost.ScreenName;
8558                                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8559                                 return;
8560                             }
8561
8562                             if (sidx > 0)
8563                             {
8564                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8565                                 {
8566                                     ids = " " + ids;
8567                                 }
8568                             }
8569                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8570                             sidx += ids.Length;
8571                             StatusText.SelectionStart = sidx;
8572                             StatusText.Focus();
8573                             return;
8574                         }
8575                     }
8576                 }
8577                 StatusText.SelectionStart = StatusText.Text.Length;
8578                 StatusText.Focus();
8579             }
8580         }
8581
8582         private void ListTab_MouseUp(object sender, MouseEventArgs e)
8583         {
8584             _tabDrag = false;
8585         }
8586
8587         private static int iconCnt = 0;
8588         private static int blinkCnt = 0;
8589         private static bool blink = false;
8590         private static bool idle = false;
8591
8592         private async Task RefreshTasktrayIcon()
8593         {
8594             if (_colorize)
8595                 await this.Colorize();
8596
8597             if (!TimerRefreshIcon.Enabled) return;
8598             //Static usCheckCnt As int = 0
8599
8600             //Static iconDlListTopItem As ListViewItem = null
8601
8602             //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8603             //    ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8604             //else
8605             //    ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8606             //
8607             //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8608
8609             iconCnt += 1;
8610             blinkCnt += 1;
8611             //usCheckCnt += 1;
8612
8613             //if (usCheckCnt > 300)    //1min
8614             //{
8615             //    usCheckCnt = 0;
8616             //    if (!this.IsReceivedUserStream)
8617             //    {
8618             //        TraceOut("ReconnectUserStream");
8619             //        tw.ReconnectUserStream();
8620             //    }
8621             //}
8622
8623             var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8624
8625             if (iconCnt >= this.NIconRefresh.Length)
8626             {
8627                 iconCnt = 0;
8628             }
8629             if (blinkCnt > 10)
8630             {
8631                 blinkCnt = 0;
8632                 //未保存の変更を保存
8633                 SaveConfigsAll(true);
8634             }
8635
8636             if (busy)
8637             {
8638                 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8639                 idle = false;
8640                 _myStatusError = false;
8641                 return;
8642             }
8643
8644             TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8645             if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8646             {
8647                 if (blinkCnt > 0) return;
8648                 blink = !blink;
8649                 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8650                 {
8651                     NotifyIcon1.Icon = ReplyIcon;
8652                 }
8653                 else
8654                 {
8655                     NotifyIcon1.Icon = ReplyIconBlink;
8656                 }
8657                 idle = false;
8658                 return;
8659             }
8660
8661             if (idle) return;
8662             idle = true;
8663             //優先度:エラー→オフライン→アイドル
8664             //エラーは更新アイコンでクリアされる
8665             if (_myStatusError)
8666             {
8667                 NotifyIcon1.Icon = NIconAtRed;
8668                 return;
8669             }
8670             if (_myStatusOnline)
8671             {
8672                 NotifyIcon1.Icon = NIconAt;
8673             }
8674             else
8675             {
8676                 NotifyIcon1.Icon = NIconAtSmoke;
8677             }
8678         }
8679
8680         private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8681         {
8682             //200ms
8683             await this.RefreshTasktrayIcon();
8684         }
8685
8686         private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8687         {
8688             //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8689             if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8690             {
8691                 if (ListTab != null && ListTab.SelectedTab != null)
8692                     _rclickTabName = ListTab.SelectedTab.Text;
8693                 else
8694                     return;
8695             }
8696
8697             if (_statuses == null) return;
8698             if (_statuses.Tabs == null) return;
8699
8700             TabClass tb = _statuses.Tabs[_rclickTabName];
8701             if (tb == null) return;
8702
8703             NotifyDispMenuItem.Checked = tb.Notify;
8704             this.NotifyTbMenuItem.Checked = tb.Notify;
8705
8706             soundfileListup = true;
8707             SoundFileComboBox.Items.Clear();
8708             this.SoundFileTbComboBox.Items.Clear();
8709             SoundFileComboBox.Items.Add("");
8710             this.SoundFileTbComboBox.Items.Add("");
8711             DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8712             if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8713             {
8714                 oDir = oDir.GetDirectories("Sounds")[0];
8715             }
8716             foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8717             {
8718                 SoundFileComboBox.Items.Add(oFile.Name);
8719                 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8720             }
8721             int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8722             if (idx == -1) idx = 0;
8723             SoundFileComboBox.SelectedIndex = idx;
8724             this.SoundFileTbComboBox.SelectedIndex = idx;
8725             soundfileListup = false;
8726             UreadManageMenuItem.Checked = tb.UnreadManage;
8727             this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8728
8729             TabMenuControl(_rclickTabName);
8730         }
8731
8732         private void TabMenuControl(string tabName)
8733         {
8734             var tabInfo = _statuses.GetTabByName(tabName);
8735
8736             this.FilterEditMenuItem.Enabled = true;
8737             this.EditRuleTbMenuItem.Enabled = true;
8738
8739             if (tabInfo.IsDefaultTabType)
8740             {
8741                 this.ProtectTabMenuItem.Enabled = false;
8742                 this.ProtectTbMenuItem.Enabled = false;
8743             }
8744             else
8745             {
8746                 this.ProtectTabMenuItem.Enabled = true;
8747                 this.ProtectTbMenuItem.Enabled = true;
8748             }
8749
8750             if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8751             {
8752                 this.ProtectTabMenuItem.Checked = true;
8753                 this.ProtectTbMenuItem.Checked = true;
8754                 this.DeleteTabMenuItem.Enabled = false;
8755                 this.DeleteTbMenuItem.Enabled = false;
8756             }
8757             else
8758             {
8759                 this.ProtectTabMenuItem.Checked = false;
8760                 this.ProtectTbMenuItem.Checked = false;
8761                 this.DeleteTabMenuItem.Enabled = true;
8762                 this.DeleteTbMenuItem.Enabled = true;
8763             }
8764         }
8765
8766         private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8767         {
8768             var checkState = ((ToolStripMenuItem)sender).Checked;
8769
8770             // チェック状態を同期
8771             this.ProtectTbMenuItem.Checked = checkState;
8772             this.ProtectTabMenuItem.Checked = checkState;
8773
8774             // ロック中はタブの削除を無効化
8775             this.DeleteTabMenuItem.Enabled = !checkState;
8776             this.DeleteTbMenuItem.Enabled = !checkState;
8777
8778             if (string.IsNullOrEmpty(_rclickTabName)) return;
8779             _statuses.Tabs[_rclickTabName].Protected = checkState;
8780
8781             SaveConfigsTabs();
8782         }
8783
8784         private void UreadManageMenuItem_Click(object sender, EventArgs e)
8785         {
8786             UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8787             this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8788
8789             if (string.IsNullOrEmpty(_rclickTabName)) return;
8790             ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8791
8792             SaveConfigsTabs();
8793         }
8794
8795         public void ChangeTabUnreadManage(string tabName, bool isManage)
8796         {
8797             var idx = this.GetTabPageIndex(tabName);
8798             if (idx == -1)
8799                 return;
8800
8801             _statuses.Tabs[tabName].UnreadManage = isManage;
8802             if (this._cfgCommon.TabIconDisp)
8803             {
8804                 if (_statuses.Tabs[tabName].UnreadCount > 0)
8805                     ListTab.TabPages[idx].ImageIndex = 0;
8806                 else
8807                     ListTab.TabPages[idx].ImageIndex = -1;
8808             }
8809
8810             if (_curTab.Text == tabName)
8811             {
8812                 this.PurgeListViewItemCache();
8813                 _curList.Refresh();
8814             }
8815
8816             SetMainWindowTitle();
8817             SetStatusLabelUrl();
8818             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8819         }
8820
8821         private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8822         {
8823             NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8824             this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8825
8826             if (string.IsNullOrEmpty(_rclickTabName)) return;
8827
8828             _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8829
8830             SaveConfigsTabs();
8831         }
8832
8833         private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8834         {
8835             if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8836
8837             _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8838
8839             SaveConfigsTabs();
8840         }
8841
8842         private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8843         {
8844             if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8845
8846             RemoveSpecifiedTab(_rclickTabName, true);
8847             SaveConfigsTabs();
8848         }
8849
8850         private void FilterEditMenuItem_Click(object sender, EventArgs e)
8851         {
8852             if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8853
8854             using (var fltDialog = new FilterDialog())
8855             {
8856                 fltDialog.Owner = this;
8857                 fltDialog.SetCurrent(_rclickTabName);
8858                 fltDialog.ShowDialog(this);
8859             }
8860             this.TopMost = this._cfgCommon.AlwaysTop;
8861
8862             this.ApplyPostFilters();
8863             SaveConfigsTabs();
8864         }
8865
8866         private void AddTabMenuItem_Click(object sender, EventArgs e)
8867         {
8868             string tabName = null;
8869             MyCommon.TabUsageType tabUsage;
8870             using (InputTabName inputName = new InputTabName())
8871             {
8872                 inputName.TabName = _statuses.MakeTabName("MyTab");
8873                 inputName.IsShowUsage = true;
8874                 inputName.ShowDialog();
8875                 if (inputName.DialogResult == DialogResult.Cancel) return;
8876                 tabName = inputName.TabName;
8877                 tabUsage = inputName.Usage;
8878             }
8879             this.TopMost = this._cfgCommon.AlwaysTop;
8880             if (!string.IsNullOrEmpty(tabName))
8881             {
8882                 //List対応
8883                 ListElement list = null;
8884                 if (tabUsage == MyCommon.TabUsageType.Lists)
8885                 {
8886                     using (ListAvailable listAvail = new ListAvailable())
8887                     {
8888                         if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8889                         if (listAvail.SelectedList == null) return;
8890                         list = listAvail.SelectedList;
8891                     }
8892                 }
8893                 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8894                 {
8895                     string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8896                     MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8897                 }
8898                 else
8899                 {
8900                     //成功
8901                     SaveConfigsTabs();
8902                     if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8903                     {
8904                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8905                         ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8906                     }
8907                     if (tabUsage == MyCommon.TabUsageType.Lists)
8908                     {
8909                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8910                         var tab = this._statuses.Tabs[this._curTab.Text];
8911                         this.GetListTimelineAsync(tab);
8912                     }
8913                 }
8914             }
8915         }
8916
8917         private void TabMenuItem_Click(object sender, EventArgs e)
8918         {
8919             using (var fltDialog = new FilterDialog())
8920             {
8921                 fltDialog.Owner = this;
8922
8923                 //選択発言を元にフィルタ追加
8924                 foreach (int idx in _curList.SelectedIndices)
8925                 {
8926                     string tabName;
8927                     //タブ選択(or追加)
8928                     if (!SelectTab(out tabName)) return;
8929
8930                     fltDialog.SetCurrent(tabName);
8931                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8932                     {
8933                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8934                     }
8935                     else
8936                     {
8937                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8938                     }
8939                     fltDialog.ShowDialog(this);
8940                     this.TopMost = this._cfgCommon.AlwaysTop;
8941                 }
8942             }
8943
8944             this.ApplyPostFilters();
8945             SaveConfigsTabs();
8946             if (this.ListTab.SelectedTab != null &&
8947                 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8948             {
8949                 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8950             }
8951         }
8952
8953         protected override bool ProcessDialogKey(Keys keyData)
8954         {
8955             //TextBox1でEnterを押してもビープ音が鳴らないようにする
8956             if ((keyData & Keys.KeyCode) == Keys.Enter)
8957             {
8958                 if (StatusText.Focused)
8959                 {
8960                     bool _NewLine = false;
8961                     bool _Post = false;
8962
8963                     if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8964                     {
8965                         if (StatusText.Multiline)
8966                         {
8967                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8968
8969                             if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8970                         }
8971                         else
8972                         {
8973                             if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8974                         }
8975
8976                     }
8977                     else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8978                     {
8979                         if (StatusText.Multiline)
8980                         {
8981                             if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8982
8983                             if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8984                         }
8985                         else
8986                         {
8987                             if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8988                         }
8989
8990                     }
8991                     else //Enter投稿時
8992                     {
8993                         if (StatusText.Multiline)
8994                         {
8995                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8996
8997                             if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8998                                 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8999                         }
9000                         else
9001                         {
9002                             if (((keyData & Keys.Shift) == Keys.Shift) ||
9003                                 (((keyData & Keys.Control) != Keys.Control) &&
9004                                 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
9005                         }
9006                     }
9007
9008                     if (_NewLine)
9009                     {
9010                         int pos1 = StatusText.SelectionStart;
9011                         if (StatusText.SelectionLength > 0)
9012                         {
9013                             StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength);  //選択状態文字列削除
9014                         }
9015                         StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine);  //改行挿入
9016                         StatusText.SelectionStart = pos1 + Environment.NewLine.Length;    //カーソルを改行の次の文字へ移動
9017                         return true;
9018                     }
9019                     else if (_Post)
9020                     {
9021                         PostButton_Click(null, null);
9022                         return true;
9023                     }
9024                 }
9025                 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
9026                          (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
9027                          ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
9028                 {
9029                     this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9030                     return true;
9031                 }
9032             }
9033
9034             return base.ProcessDialogKey(keyData);
9035         }
9036
9037         private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9038         {
9039             MakeReplyOrDirectStatus(false, true, true);
9040         }
9041
9042         private void IDRuleMenuItem_Click(object sender, EventArgs e)
9043         {
9044             string tabName;
9045
9046             //未選択なら処理終了
9047             if (_curList.SelectedIndices.Count == 0) return;
9048
9049             //タブ選択(or追加)
9050             if (!SelectTab(out tabName)) return;
9051
9052             var tab = this._statuses.Tabs[tabName];
9053
9054             bool mv;
9055             bool mk;
9056             if (tab.TabType != MyCommon.TabUsageType.Mute)
9057             {
9058                 this.MoveOrCopy(out mv, out mk);
9059             }
9060             else
9061             {
9062                 // ミュートタブでは常に MoveMatches を true にする
9063                 mv = true;
9064                 mk = false;
9065             }
9066
9067             List<string> ids = new List<string>();
9068             foreach (int idx in _curList.SelectedIndices)
9069             {
9070                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9071                 if (!ids.Contains(post.ScreenName))
9072                 {
9073                     PostFilterRule fc = new PostFilterRule();
9074                     ids.Add(post.ScreenName);
9075                     if (post.RetweetedId == null)
9076                     {
9077                         fc.FilterName = post.ScreenName;
9078                     }
9079                     else
9080                     {
9081                         fc.FilterName = post.RetweetedBy;
9082                     }
9083                     fc.UseNameField = true;
9084                     fc.MoveMatches = mv;
9085                     fc.MarkMatches = mk;
9086                     fc.UseRegex = false;
9087                     fc.FilterByUrl = false;
9088                     tab.AddFilter(fc);
9089                 }
9090             }
9091             if (ids.Count != 0)
9092             {
9093                 List<string> atids = new List<string>();
9094                 foreach (string id in ids)
9095                 {
9096                     atids.Add("@" + id);
9097                 }
9098                 int cnt = AtIdSupl.ItemCount;
9099                 AtIdSupl.AddRangeItem(atids.ToArray());
9100                 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
9101             }
9102
9103             this.ApplyPostFilters();
9104             SaveConfigsTabs();
9105         }
9106
9107         private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9108         {
9109             if (this._curList.SelectedIndices.Count == 0)
9110                 return;
9111
9112             // タブ選択ダイアログを表示(or追加)
9113             string tabName;
9114             if (!this.SelectTab(out tabName))
9115                 return;
9116
9117             var currentTab = this._statuses.Tabs[this._curTab.Text];
9118             var filterTab = this._statuses.Tabs[tabName];
9119
9120             bool mv;
9121             bool mk;
9122             if (filterTab.TabType != MyCommon.TabUsageType.Mute)
9123             {
9124                 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9125                 this.MoveOrCopy(out mv, out mk);
9126             }
9127             else
9128             {
9129                 // ミュートタブでは常に MoveMatches を true にする
9130                 mv = true;
9131                 mk = false;
9132             }
9133
9134             // 振り分けルールに追加するSource
9135             var sources = new HashSet<string>();
9136
9137             foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9138             {
9139                 var post = currentTab[idx];
9140                 var filterSource = post.Source;
9141
9142                 if (sources.Add(filterSource))
9143                 {
9144                     var filter = new PostFilterRule
9145                     {
9146                         FilterSource = filterSource,
9147                         MoveMatches = mv,
9148                         MarkMatches = mk,
9149                         UseRegex = false,
9150                         FilterByUrl = false,
9151                     };
9152                     filterTab.AddFilter(filter);
9153                 }
9154             }
9155
9156             this.ApplyPostFilters();
9157             this.SaveConfigsTabs();
9158         }
9159
9160         private bool SelectTab(out string tabName)
9161         {
9162             do
9163             {
9164                 tabName = null;
9165
9166                 //振り分け先タブ選択
9167                 using (var dialog = new TabsDialog(_statuses))
9168                 {
9169                     if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9170
9171                     var selectedTab = dialog.SelectedTab;
9172                     tabName = selectedTab == null ? null : selectedTab.TabName;
9173                 }
9174
9175                 ListTab.SelectedTab.Focus();
9176                 //新規タブを選択→タブ作成
9177                 if (tabName == null)
9178                 {
9179                     using (InputTabName inputName = new InputTabName())
9180                     {
9181                         inputName.TabName = _statuses.MakeTabName("MyTab");
9182                         inputName.ShowDialog();
9183                         if (inputName.DialogResult == DialogResult.Cancel) return false;
9184                         tabName = inputName.TabName;
9185                     }
9186                     this.TopMost = this._cfgCommon.AlwaysTop;
9187                     if (!string.IsNullOrEmpty(tabName))
9188                     {
9189                         if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9190                         {
9191                             string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9192                             MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9193                             //もう一度タブ名入力
9194                         }
9195                         else
9196                         {
9197                             return true;
9198                         }
9199                     }
9200                 }
9201                 else
9202                 {
9203                     //既存タブを選択
9204                     return true;
9205                 }
9206             }
9207             while (true);
9208         }
9209
9210         private void MoveOrCopy(out bool move, out bool mark)
9211         {
9212             {
9213                 //移動するか?
9214                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9215                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9216                     move = false;
9217                 else
9218                     move = true;
9219             }
9220             if (!move)
9221             {
9222                 //マークするか?
9223                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9224                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9225                     mark = true;
9226                 else
9227                     mark = false;
9228             }
9229             else
9230             {
9231                 mark = false;
9232             }
9233         }
9234         private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9235         {
9236             this.CopyStot();
9237         }
9238
9239         private void CopyURLMenuItem_Click(object sender, EventArgs e)
9240         {
9241             this.CopyIdUri();
9242         }
9243
9244         private void SelectAllMenuItem_Click(object sender, EventArgs e)
9245         {
9246             if (StatusText.Focused)
9247             {
9248                 // 発言欄でのCtrl+A
9249                 StatusText.SelectAll();
9250             }
9251             else
9252             {
9253                 // ListView上でのCtrl+A
9254                 NativeMethods.SelectAllItems(this._curList);
9255             }
9256         }
9257
9258         private void MoveMiddle()
9259         {
9260             ListViewItem _item;
9261             int idx1;
9262             int idx2;
9263
9264             if (_curList.SelectedIndices.Count == 0) return;
9265
9266             int idx = _curList.SelectedIndices[0];
9267
9268             _item = _curList.GetItemAt(0, 25);
9269             if (_item == null)
9270                 idx1 = 0;
9271             else
9272                 idx1 = _item.Index;
9273
9274             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9275             if (_item == null)
9276                 idx2 = _curList.VirtualListSize - 1;
9277             else
9278                 idx2 = _item.Index;
9279
9280             idx -= Math.Abs(idx1 - idx2) / 2;
9281             if (idx < 0) idx = 0;
9282
9283             _curList.EnsureVisible(_curList.VirtualListSize - 1);
9284             _curList.EnsureVisible(idx);
9285         }
9286
9287         private async void OpenURLMenuItem_Click(object sender, EventArgs e)
9288         {
9289             var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
9290                 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
9291                 .ToArray();
9292
9293             if (linkElements.Length > 0)
9294             {
9295                 UrlDialog.ClearUrl();
9296
9297                 string openUrlStr = "";
9298
9299                 if (linkElements.Length == 1)
9300                 {
9301                     // ツイートに含まれる URL が 1 つのみの場合
9302                     //   => OpenURL ダイアログを表示せずにリンクを開く
9303
9304                     string urlStr = "";
9305                     try
9306                     {
9307                         urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
9308                     }
9309                     catch (ArgumentException)
9310                     {
9311                         //変なHTML?
9312                         return;
9313                     }
9314                     catch (Exception)
9315                     {
9316                         return;
9317                     }
9318                     if (string.IsNullOrEmpty(urlStr)) return;
9319                     openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9320
9321                     // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
9322                     await this.OpenUriAsync(new Uri(openUrlStr));
9323                 }
9324                 else
9325                 {
9326                     // ツイートに含まれる URL が複数ある場合
9327                     //   => OpenURL を表示しユーザーが選択したリンクを開く
9328
9329                     foreach (var linkElm in linkElements)
9330                     {
9331                         string urlStr = "";
9332                         string linkText = "";
9333                         string href = "";
9334                         try
9335                         {
9336                             urlStr = linkElm.GetAttribute("title");
9337                             href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9338                             if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9339                             linkText = linkElm.InnerText;
9340                         }
9341                         catch (ArgumentException)
9342                         {
9343                             //変なHTML?
9344                             return;
9345                         }
9346                         catch (Exception)
9347                         {
9348                             return;
9349                         }
9350                         if (string.IsNullOrEmpty(urlStr)) continue;
9351                         UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9352                     }
9353                     try
9354                     {
9355                         if (UrlDialog.ShowDialog() == DialogResult.OK)
9356                         {
9357                             openUrlStr = UrlDialog.SelectedUrl;
9358
9359                             // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
9360                             await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
9361                         }
9362                     }
9363                     catch (Exception)
9364                     {
9365                         return;
9366                     }
9367                     this.TopMost = this._cfgCommon.AlwaysTop;
9368                 }
9369             }
9370         }
9371
9372         private void ClearTabMenuItem_Click(object sender, EventArgs e)
9373         {
9374             if (string.IsNullOrEmpty(_rclickTabName)) return;
9375             ClearTab(_rclickTabName, true);
9376         }
9377
9378         private void ClearTab(string tabName, bool showWarning)
9379         {
9380             if (showWarning)
9381             {
9382                 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9383                 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9384                 {
9385                     return;
9386                 }
9387             }
9388
9389             _statuses.ClearTabIds(tabName);
9390             if (ListTab.SelectedTab.Text == tabName)
9391             {
9392                 _anchorPost = null;
9393                 _anchorFlag = false;
9394                 this.PurgeListViewItemCache();
9395                 _curItemIndex = -1;
9396                 _curPost = null;
9397             }
9398             foreach (TabPage tb in ListTab.TabPages)
9399             {
9400                 if (tb.Text == tabName)
9401                 {
9402                     tb.ImageIndex = -1;
9403                     ((DetailsListView)tb.Tag).VirtualListSize = 0;
9404                     break;
9405                 }
9406             }
9407             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9408
9409             SetMainWindowTitle();
9410             SetStatusLabelUrl();
9411         }
9412
9413         private static long followers = 0;
9414
9415         private void SetMainWindowTitle()
9416         {
9417             //メインウインドウタイトルの書き換え
9418             StringBuilder ttl = new StringBuilder(256);
9419             int ur = 0;
9420             int al = 0;
9421             if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9422                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9423                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9424                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9425             {
9426                 foreach (var tab in _statuses.Tabs.Values)
9427                 {
9428                     ur += tab.UnreadCount;
9429                     al += tab.AllCount;
9430                 }
9431             }
9432
9433             if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9434             ttl.Append(Application.ProductName);
9435             ttl.Append("  ");
9436             switch (this._cfgCommon.DispLatestPost)
9437             {
9438                 case MyCommon.DispTitleEnum.Ver:
9439                     ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9440                     break;
9441                 case MyCommon.DispTitleEnum.Post:
9442                     if (_history != null && _history.Count > 1)
9443                         ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9444                     break;
9445                 case MyCommon.DispTitleEnum.UnreadRepCount:
9446                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9447                     break;
9448                 case MyCommon.DispTitleEnum.UnreadAllCount:
9449                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9450                     break;
9451                 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9452                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9453                     break;
9454                 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9455                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9456                     break;
9457                 case MyCommon.DispTitleEnum.OwnStatus:
9458                     if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9459                     ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9460                     break;
9461             }
9462
9463             try
9464             {
9465                 this.Text = ttl.ToString();
9466             }
9467             catch (AccessViolationException)
9468             {
9469                 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9470             }
9471         }
9472
9473         private string GetStatusLabelText()
9474         {
9475             //ステータス欄にカウント表示
9476             //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9477             if (_statuses == null) return "";
9478             TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9479             TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9480             if (tbRep == null || tbDm == null) return "";
9481             int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9482             int ur = 0;
9483             int al = 0;
9484             int tur = 0;
9485             int tal = 0;
9486             StringBuilder slbl = new StringBuilder(256);
9487             try
9488             {
9489                 foreach (var tab in _statuses.Tabs.Values)
9490                 {
9491                     ur += tab.UnreadCount;
9492                     al += tab.AllCount;
9493                     if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9494                     {
9495                         tur = tab.UnreadCount;
9496                         tal = tab.AllCount;
9497                     }
9498                 }
9499             }
9500             catch (Exception)
9501             {
9502                 return "";
9503             }
9504
9505             UnreadCounter = ur;
9506             UnreadAtCounter = urat;
9507
9508             slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9509             if (this._cfgCommon.TimelinePeriod == 0)
9510             {
9511                 slbl.Append(Properties.Resources.SetStatusLabelText2);
9512             }
9513             else
9514             {
9515                 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9516             }
9517             return slbl.ToString();
9518         }
9519
9520         private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9521         {
9522             try
9523             {
9524                 if (this.InvokeRequired && !this.IsDisposed)
9525                 {
9526                     this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9527                 }
9528                 else
9529                 {
9530                     var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9531                     SetApiStatusLabel(endpointName);
9532                 }
9533             }
9534             catch (ObjectDisposedException)
9535             {
9536                 return;
9537             }
9538             catch (InvalidOperationException)
9539             {
9540                 return;
9541             }
9542         }
9543
9544         private void SetApiStatusLabel(string endpointName = null)
9545         {
9546             if (_curTab == null)
9547             {
9548                 this.toolStripApiGauge.ApiEndpoint = null;
9549             }
9550             else
9551             {
9552                 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9553
9554                 if (endpointName == null)
9555                 {
9556                     // 表示中のタブに応じて更新
9557                     switch (tabType)
9558                     {
9559                         case MyCommon.TabUsageType.Home:
9560                         case MyCommon.TabUsageType.UserDefined:
9561                             endpointName = "/statuses/home_timeline";
9562                             break;
9563
9564                         case MyCommon.TabUsageType.Mentions:
9565                             endpointName = "/statuses/mentions_timeline";
9566                             break;
9567
9568                         case MyCommon.TabUsageType.Favorites:
9569                             endpointName = "/favorites/list";
9570                             break;
9571
9572                         case MyCommon.TabUsageType.DirectMessage:
9573                             endpointName = "/direct_messages";
9574                             break;
9575
9576                         case MyCommon.TabUsageType.UserTimeline:
9577                             endpointName = "/statuses/user_timeline";
9578                             break;
9579
9580                         case MyCommon.TabUsageType.Lists:
9581                             endpointName = "/lists/statuses";
9582                             break;
9583
9584                         case MyCommon.TabUsageType.PublicSearch:
9585                             endpointName = "/search/tweets";
9586                             break;
9587
9588                         case MyCommon.TabUsageType.Related:
9589                             endpointName = "/statuses/show/:id";
9590                             break;
9591
9592                         default:
9593                             break;
9594                     }
9595
9596                     this.toolStripApiGauge.ApiEndpoint = endpointName;
9597                 }
9598                 else
9599                 {
9600                     // 表示中のタブに関連する endpoint であれば更新
9601                     var update = false;
9602
9603                     switch (endpointName)
9604                     {
9605                         case "/statuses/home_timeline":
9606                             update = tabType == MyCommon.TabUsageType.Home ||
9607                                      tabType == MyCommon.TabUsageType.UserDefined;
9608                             break;
9609
9610                         case "/statuses/mentions_timeline":
9611                             update = tabType == MyCommon.TabUsageType.Mentions;
9612                             break;
9613
9614                         case "/favorites/list":
9615                             update = tabType == MyCommon.TabUsageType.Favorites;
9616                             break;
9617
9618                         case "/direct_messages:":
9619                             update = tabType == MyCommon.TabUsageType.DirectMessage;
9620                             break;
9621
9622                         case "/statuses/user_timeline":
9623                             update = tabType == MyCommon.TabUsageType.UserTimeline;
9624                             break;
9625
9626                         case "/lists/statuses":
9627                             update = tabType == MyCommon.TabUsageType.Lists;
9628                             break;
9629
9630                         case "/search/tweets":
9631                             update = tabType == MyCommon.TabUsageType.PublicSearch;
9632                             break;
9633
9634                         case "/statuses/show/:id":
9635                             update = tabType == MyCommon.TabUsageType.Related;
9636                             break;
9637
9638                         default:
9639                             break;
9640                     }
9641
9642                     if (update)
9643                     {
9644                         this.toolStripApiGauge.ApiEndpoint = endpointName;
9645                     }
9646                 }
9647             }
9648         }
9649
9650         private void SetStatusLabelUrl()
9651         {
9652             StatusLabelUrl.Text = GetStatusLabelText();
9653         }
9654
9655         public void SetStatusLabel(string text)
9656         {
9657             StatusLabel.Text = text;
9658         }
9659
9660         private static StringBuilder ur = new StringBuilder(64);
9661
9662         private void SetNotifyIconText()
9663         {
9664             // タスクトレイアイコンのツールチップテキスト書き換え
9665             // Tween [未読/@]
9666             ur.Remove(0, ur.Length);
9667             if (this._cfgCommon.DispUsername)
9668             {
9669                 ur.Append(tw.Username);
9670                 ur.Append(" - ");
9671             }
9672             ur.Append(Application.ProductName);
9673 #if DEBUG
9674             ur.Append("(Debug Build)");
9675 #endif
9676             if (UnreadCounter != -1 && UnreadAtCounter != -1)
9677             {
9678                 ur.Append(" [");
9679                 ur.Append(UnreadCounter);
9680                 ur.Append("/@");
9681                 ur.Append(UnreadAtCounter);
9682                 ur.Append("]");
9683             }
9684             NotifyIcon1.Text = ur.ToString();
9685         }
9686
9687         internal void CheckReplyTo(string StatusText)
9688         {
9689             MatchCollection m;
9690             //ハッシュタグの保存
9691             m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9692             string hstr = "";
9693             foreach (Match hm in m)
9694             {
9695                 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9696                 {
9697                     hstr += "#" + hm.Result("$3") + " ";
9698                     HashSupl.AddItem("#" + hm.Result("$3"));
9699                 }
9700             }
9701             if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9702             {
9703                 hstr += HashMgr.UseHash;
9704             }
9705             if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9706
9707             // 本当にリプライ先指定すべきかどうかの判定
9708             m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9709
9710             if (this._cfgCommon.UseAtIdSupplement)
9711             {
9712                 int bCnt = AtIdSupl.ItemCount;
9713                 foreach (Match mid in m)
9714                 {
9715                     AtIdSupl.AddItem(mid.Result("${id}"));
9716                 }
9717                 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9718             }
9719
9720             // リプライ先ステータスIDの指定がない場合は指定しない
9721             if (this.inReplyTo == null)
9722                 return;
9723
9724             // 通常Reply
9725             // 次の条件を満たす場合に in_reply_to_status_id 指定
9726             // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9727             // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9728             // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9729
9730             if (m != null)
9731             {
9732                 var inReplyToScreenName = this.inReplyTo.Item2;
9733                 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9734                 {
9735                     if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9736                 }
9737                 else
9738                 {
9739                     foreach (Match mid in m)
9740                     {
9741                         if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9742                     }
9743                 }
9744             }
9745
9746             this.inReplyTo = null;
9747         }
9748
9749         private void TweenMain_Resize(object sender, EventArgs e)
9750         {
9751             if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9752             {
9753                 this.Visible = false;
9754             }
9755             if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9756             {
9757                 // 現在の DPI と設定保存時の DPI との比を取得する
9758                 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9759
9760                 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9761                 //_mySize = this.ClientSize;                     //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9762                 this.DesktopLocation = _cfgLocal.FormLocation;
9763                 //_myLoc = this.DesktopLocation;                        //位置保持(最小化・最大化されたまま終了した場合の対応用)
9764
9765                 // Splitterの位置設定
9766                 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9767                 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9768                     splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9769                 {
9770                     this.SplitContainer1.SplitterDistance = splitterDistance;
9771                 }
9772
9773                 //発言欄複数行
9774                 StatusText.Multiline = _cfgLocal.StatusMultiline;
9775                 if (StatusText.Multiline)
9776                 {
9777                     var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9778                     int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9779                     if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9780                     {
9781                         SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9782                     }
9783                     StatusText.Height = statusTextHeight;
9784                 }
9785                 else
9786                 {
9787                     if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9788                     {
9789                         SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9790                     }
9791                 }
9792
9793                 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9794                 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9795                 {
9796                     this.SplitContainer3.SplitterDistance = previewDistance;
9797                 }
9798
9799                 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9800                 this.SplitContainer3.Panel2Collapsed = true;
9801
9802                 _initialLayout = false;
9803             }
9804             if (this.WindowState != FormWindowState.Minimized)
9805             {
9806                 _formWindowState = this.WindowState;
9807             }
9808         }
9809
9810         private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9811         {
9812             PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9813             this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9814             if (PlaySoundMenuItem.Checked)
9815             {
9816                 this._cfgCommon.PlaySound = true;
9817             }
9818             else
9819             {
9820                 this._cfgCommon.PlaySound = false;
9821             }
9822             ModifySettingCommon = true;
9823         }
9824
9825         private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9826         {
9827             if (this._initialLayout)
9828                 return;
9829
9830             int splitterDistance;
9831             switch (this.WindowState)
9832             {
9833                 case FormWindowState.Normal:
9834                     splitterDistance = this.SplitContainer1.SplitterDistance;
9835                     break;
9836                 case FormWindowState.Maximized:
9837                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9838                     var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9839                     splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9840                     splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9841                     break;
9842                 default:
9843                     return;
9844             }
9845
9846             this._mySpDis = splitterDistance;
9847             this.ModifySettingLocal = true;
9848         }
9849
9850         private async Task doRepliedStatusOpen()
9851         {
9852             if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9853             {
9854                 if (MyCommon.IsKeyDown(Keys.Shift))
9855                 {
9856                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9857                     return;
9858                 }
9859                 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9860                 {
9861                     PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9862                     MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9863                 }
9864                 else
9865                 {
9866                     foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9867                     {
9868                         if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9869                         PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9870                         MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9871                         return;
9872                     }
9873                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9874                 }
9875             }
9876         }
9877
9878         private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9879         {
9880             await this.doRepliedStatusOpen();
9881         }
9882
9883         /// <summary>
9884         /// UserPicture.Image に設定されている画像を破棄します。
9885         /// </summary>
9886         private void ClearUserPicture()
9887         {
9888             if (this.UserPicture.Image != null)
9889             {
9890                 var oldImage = this.UserPicture.Image;
9891                 this.UserPicture.Image = null;
9892                 oldImage.Dispose();
9893             }
9894         }
9895
9896         private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9897         {
9898             //発言詳細のアイコン右クリック時のメニュー制御
9899             if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9900             {
9901                 string name = _curPost.ImageUrl;
9902                 if (name != null && name.Length > 0)
9903                 {
9904                     int idx = name.LastIndexOf('/');
9905                     if (idx != -1)
9906                     {
9907                         name = Path.GetFileName(name.Substring(idx));
9908                         if (name.Contains("_normal.") || name.EndsWith("_normal", StringComparison.Ordinal))
9909                         {
9910                             name = name.Replace("_normal", "");
9911                             this.IconNameToolStripMenuItem.Text = name;
9912                             this.IconNameToolStripMenuItem.Enabled = true;
9913                         }
9914                         else
9915                         {
9916                             this.IconNameToolStripMenuItem.Enabled = false;
9917                             this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9918                         }
9919                     }
9920                     else
9921                     {
9922                         this.IconNameToolStripMenuItem.Enabled = false;
9923                         this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9924                     }
9925
9926                     this.ReloadIconToolStripMenuItem.Enabled = true;
9927
9928                     if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9929                     {
9930                         this.SaveIconPictureToolStripMenuItem.Enabled = true;
9931                     }
9932                     else
9933                     {
9934                         this.SaveIconPictureToolStripMenuItem.Enabled = false;
9935                     }
9936                 }
9937                 else
9938                 {
9939                     this.IconNameToolStripMenuItem.Enabled = false;
9940                     this.ReloadIconToolStripMenuItem.Enabled = false;
9941                     this.SaveIconPictureToolStripMenuItem.Enabled = false;
9942                     this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9943                 }
9944             }
9945             else
9946             {
9947                 this.IconNameToolStripMenuItem.Enabled = false;
9948                 this.ReloadIconToolStripMenuItem.Enabled = false;
9949                 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9950                 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9951             }
9952             if (NameLabel.Tag != null)
9953             {
9954                 string id = (string)NameLabel.Tag;
9955                 if (id == tw.Username)
9956                 {
9957                     FollowToolStripMenuItem.Enabled = false;
9958                     UnFollowToolStripMenuItem.Enabled = false;
9959                     ShowFriendShipToolStripMenuItem.Enabled = false;
9960                     ShowUserStatusToolStripMenuItem.Enabled = true;
9961                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9962                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9963                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9964                 }
9965                 else
9966                 {
9967                     FollowToolStripMenuItem.Enabled = true;
9968                     UnFollowToolStripMenuItem.Enabled = true;
9969                     ShowFriendShipToolStripMenuItem.Enabled = true;
9970                     ShowUserStatusToolStripMenuItem.Enabled = true;
9971                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9972                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9973                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9974                 }
9975             }
9976             else
9977             {
9978                 FollowToolStripMenuItem.Enabled = false;
9979                 UnFollowToolStripMenuItem.Enabled = false;
9980                 ShowFriendShipToolStripMenuItem.Enabled = false;
9981                 ShowUserStatusToolStripMenuItem.Enabled = false;
9982                 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9983                 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9984                 ListManageUserContextToolStripMenuItem3.Enabled = false;
9985             }
9986         }
9987
9988         private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9989         {
9990             if (_curPost == null) return;
9991             string name = _curPost.ImageUrl;
9992             await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9993         }
9994
9995         private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9996         {
9997             if (this._curPost == null) return;
9998
9999             await this.UserPicture.SetImageFromTask(async () =>
10000             {
10001                 var imageUrl = this._curPost.ImageUrl;
10002
10003                 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
10004                     .ConfigureAwait(false);
10005
10006                 return await image.CloneAsync()
10007                     .ConfigureAwait(false);
10008             });
10009         }
10010
10011         private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10012         {
10013             if (_curPost == null) return;
10014             string name = _curPost.ImageUrl;
10015             name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
10016
10017             this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
10018
10019             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10020             {
10021                 // STUB
10022             }
10023         }
10024
10025         private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10026         {
10027             if (_curPost == null) return;
10028             string name = _curPost.ImageUrl;
10029
10030             this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
10031
10032             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10033             {
10034                 try
10035                 {
10036                     using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10037                     {
10038                         using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10039                         {
10040                             using (Graphics g = Graphics.FromImage(bmp2))
10041                             {
10042                                 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10043                                 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10044                             }
10045                             bmp2.Save(this.SaveFileDialog1.FileName);
10046                         }
10047                     }
10048                 }
10049                 catch (Exception)
10050                 {
10051                     //処理中にキャッシュアウトする可能性あり
10052                 }
10053             }
10054         }
10055
10056         private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10057         {
10058             var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10059             if (multiline != this.StatusText.Multiline)
10060             {
10061                 this.StatusText.Multiline = multiline;
10062                 MultiLineMenuItem.Checked = multiline;
10063                 ModifySettingLocal = true;
10064             }
10065         }
10066
10067         private void StatusText_MultilineChanged(object sender, EventArgs e)
10068         {
10069             if (this.StatusText.Multiline)
10070                 this.StatusText.ScrollBars = ScrollBars.Vertical;
10071             else
10072                 this.StatusText.ScrollBars = ScrollBars.None;
10073
10074             ModifySettingLocal = true;
10075         }
10076
10077         private void MultiLineMenuItem_Click(object sender, EventArgs e)
10078         {
10079             //発言欄複数行
10080             StatusText.Multiline = MultiLineMenuItem.Checked;
10081             _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10082             if (MultiLineMenuItem.Checked)
10083             {
10084                 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10085                     SplitContainer2.SplitterDistance = 0;
10086                 else
10087                     SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10088             }
10089             else
10090             {
10091                 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10092             }
10093             ModifySettingLocal = true;
10094         }
10095
10096         private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10097         {
10098             //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10099             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10100
10101             //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10102             //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10103             //Appendix A.  Collected ABNF for URI
10104             //http://www.ietf.org/rfc/rfc3986.txt
10105
10106             string result = "";
10107
10108             const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10109
10110             if (StatusText.SelectionLength > 0)
10111             {
10112                 string tmp = StatusText.SelectedText;
10113                 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10114                 if (tmp.StartsWith("http"))
10115                 {
10116                     // 文字列が選択されている場合はその文字列について処理
10117
10118                     //nico.ms使用、nicovideoにマッチしたら変換
10119                     if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10120                     {
10121                         result = nicoms.Shorten(tmp);
10122                     }
10123                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10124                     {
10125                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10126                         try
10127                         {
10128                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10129                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10130                             result = resultUri.AbsoluteUri;
10131                         }
10132                         catch (WebApiException e)
10133                         {
10134                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10135                             return false;
10136                         }
10137                         catch (UriFormatException e)
10138                         {
10139                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10140                             return false;
10141                         }
10142                     }
10143                     else
10144                     {
10145                         return true;
10146                     }
10147
10148                     if (!string.IsNullOrEmpty(result))
10149                     {
10150                         urlUndo undotmp = new urlUndo();
10151
10152                         StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10153                         StatusText.SelectedText = result;
10154
10155                         //undoバッファにセット
10156                         undotmp.Before = tmp;
10157                         undotmp.After = result;
10158
10159                         if (urlUndoBuffer == null)
10160                         {
10161                             urlUndoBuffer = new List<urlUndo>();
10162                             UrlUndoToolStripMenuItem.Enabled = true;
10163                         }
10164
10165                         urlUndoBuffer.Add(undotmp);
10166                     }
10167                 }
10168             }
10169             else
10170             {
10171                 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10172                                    @"(?<url>(?<protocol>https?://)" +
10173                                    @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10174                                    @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10175                                    @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10176                 // 正規表現にマッチしたURL文字列をtinyurl化
10177                 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10178                 {
10179                     if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10180                     string tmp = mt.Result("${url}");
10181                     if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10182                     urlUndo undotmp = new urlUndo();
10183
10184                     //選んだURLを選択(?)
10185                     StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10186
10187                     //nico.ms使用、nicovideoにマッチしたら変換
10188                     if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10189                     {
10190                         result = nicoms.Shorten(tmp);
10191                     }
10192                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10193                     {
10194                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10195                         try
10196                         {
10197                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10198                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10199                             result = resultUri.AbsoluteUri;
10200                         }
10201                         catch (HttpRequestException e)
10202                         {
10203                             // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10204                             // のように長いので「:」が含まれていればそれ以降のみを抽出する
10205                             var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10206
10207                             this.StatusLabel.Text = Converter_Type + ":" + message;
10208                             continue;
10209                         }
10210                         catch (WebApiException e)
10211                         {
10212                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10213                             continue;
10214                         }
10215                         catch (UriFormatException e)
10216                         {
10217                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10218                             continue;
10219                         }
10220                     }
10221                     else
10222                     {
10223                         continue;
10224                     }
10225
10226                     if (!string.IsNullOrEmpty(result))
10227                     {
10228                         StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10229                         StatusText.SelectedText = result;
10230                         //undoバッファにセット
10231                         undotmp.Before = mt.Result("${url}");
10232                         undotmp.After = result;
10233
10234                         if (urlUndoBuffer == null)
10235                         {
10236                             urlUndoBuffer = new List<urlUndo>();
10237                             UrlUndoToolStripMenuItem.Enabled = true;
10238                         }
10239
10240                         urlUndoBuffer.Add(undotmp);
10241                     }
10242                 }
10243             }
10244
10245             return true;
10246         }
10247
10248         private void doUrlUndo()
10249         {
10250             if (urlUndoBuffer != null)
10251             {
10252                 string tmp = StatusText.Text;
10253                 foreach (urlUndo data in urlUndoBuffer)
10254                 {
10255                     tmp = tmp.Replace(data.After, data.Before);
10256                 }
10257                 StatusText.Text = tmp;
10258                 urlUndoBuffer = null;
10259                 UrlUndoToolStripMenuItem.Enabled = false;
10260                 StatusText.SelectionStart = 0;
10261                 StatusText.SelectionLength = 0;
10262             }
10263         }
10264
10265         private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10266         {
10267             await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10268         }
10269
10270         private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10271         {
10272             await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10273         }
10274
10275         private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10276         {
10277             await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10278         }
10279
10280         private async void UxnuMenuItem_Click(object sender, EventArgs e)
10281         {
10282             await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10283         }
10284
10285         private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10286         {
10287             if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10288             {
10289                 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10290                 Random rnd = new Random();
10291                 // 前回使用した短縮URLサービス以外を選択する
10292                 do
10293                 {
10294                     svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10295                 }
10296                 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10297                 await UrlConvertAsync(svc);
10298             }
10299         }
10300
10301         private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10302         {
10303             doUrlUndo();
10304         }
10305
10306         private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10307         {
10308             this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10309             this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10310             _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10311             ModifySettingCommon = true;
10312         }
10313
10314         private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10315         {
10316             ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10317             this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10318             _cfgCommon.ListLock = ListLockMenuItem.Checked;
10319             ModifySettingCommon = true;
10320         }
10321
10322         private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10323         {
10324             // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10325             MenuStrip1.Tag = new Object();
10326             MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10327         }
10328
10329         private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10330         {
10331             if (this.Tag != null) // 設定された戻り先へ遷移
10332             {
10333                 if (this.Tag == this.ListTab.SelectedTab)
10334                     ((Control)this.ListTab.SelectedTab.Tag).Select();
10335                 else
10336                     ((Control)this.Tag).Select();
10337             }
10338             else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10339             {
10340                 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10341                 {
10342                     this.Tag = ListTab.SelectedTab.Tag;
10343                     ((Control)this.Tag).Select();
10344                 }
10345             }
10346             // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10347             MenuStrip1.Tag = null;
10348         }
10349
10350         private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10351         {
10352             DetailsListView lst = (DetailsListView)sender;
10353             if (_cfgLocal == null) return;
10354
10355             if (_iconCol)
10356             {
10357                 _cfgLocal.Width1 = lst.Columns[0].Width;
10358                 _cfgLocal.Width3 = lst.Columns[1].Width;
10359             }
10360             else
10361             {
10362                 int[] darr = new int[lst.Columns.Count];
10363                 for (int i = 0; i < lst.Columns.Count; i++)
10364                 {
10365                     darr[lst.Columns[i].DisplayIndex] = i;
10366                 }
10367                 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10368
10369                 for (int i = 0; i < lst.Columns.Count; i++)
10370                 {
10371                     switch (darr[i])
10372                     {
10373                         case 0:
10374                             _cfgLocal.DisplayIndex1 = i;
10375                             break;
10376                         case 1:
10377                             _cfgLocal.DisplayIndex2 = i;
10378                             break;
10379                         case 2:
10380                             _cfgLocal.DisplayIndex3 = i;
10381                             break;
10382                         case 3:
10383                             _cfgLocal.DisplayIndex4 = i;
10384                             break;
10385                         case 4:
10386                             _cfgLocal.DisplayIndex5 = i;
10387                             break;
10388                         case 5:
10389                             _cfgLocal.DisplayIndex6 = i;
10390                             break;
10391                         case 6:
10392                             _cfgLocal.DisplayIndex7 = i;
10393                             break;
10394                         case 7:
10395                             _cfgLocal.DisplayIndex8 = i;
10396                             break;
10397                     }
10398                 }
10399                 _cfgLocal.Width1 = lst.Columns[0].Width;
10400                 _cfgLocal.Width2 = lst.Columns[1].Width;
10401                 _cfgLocal.Width3 = lst.Columns[2].Width;
10402                 _cfgLocal.Width4 = lst.Columns[3].Width;
10403                 _cfgLocal.Width5 = lst.Columns[4].Width;
10404                 _cfgLocal.Width6 = lst.Columns[5].Width;
10405                 _cfgLocal.Width7 = lst.Columns[6].Width;
10406                 _cfgLocal.Width8 = lst.Columns[7].Width;
10407             }
10408             ModifySettingLocal = true;
10409             _isColumnChanged = true;
10410         }
10411
10412         private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10413         {
10414             DetailsListView lst = (DetailsListView)sender;
10415             if (_cfgLocal == null) return;
10416             if (_iconCol)
10417             {
10418                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10419                 {
10420                     _cfgLocal.Width1 = lst.Columns[0].Width;
10421                     ModifySettingLocal = true;
10422                     _isColumnChanged = true;
10423                 }
10424                 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10425                 {
10426                     _cfgLocal.Width3 = lst.Columns[1].Width;
10427                     ModifySettingLocal = true;
10428                     _isColumnChanged = true;
10429                 }
10430             }
10431             else
10432             {
10433                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10434                 {
10435                     _cfgLocal.Width1 = lst.Columns[0].Width;
10436                     ModifySettingLocal = true;
10437                     _isColumnChanged = true;
10438                 }
10439                 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10440                 {
10441                     _cfgLocal.Width2 = lst.Columns[1].Width;
10442                     ModifySettingLocal = true;
10443                     _isColumnChanged = true;
10444                 }
10445                 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10446                 {
10447                     _cfgLocal.Width3 = lst.Columns[2].Width;
10448                     ModifySettingLocal = true;
10449                     _isColumnChanged = true;
10450                 }
10451                 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10452                 {
10453                     _cfgLocal.Width4 = lst.Columns[3].Width;
10454                     ModifySettingLocal = true;
10455                     _isColumnChanged = true;
10456                 }
10457                 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10458                 {
10459                     _cfgLocal.Width5 = lst.Columns[4].Width;
10460                     ModifySettingLocal = true;
10461                     _isColumnChanged = true;
10462                 }
10463                 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10464                 {
10465                     _cfgLocal.Width6 = lst.Columns[5].Width;
10466                     ModifySettingLocal = true;
10467                     _isColumnChanged = true;
10468                 }
10469                 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10470                 {
10471                     _cfgLocal.Width7 = lst.Columns[6].Width;
10472                     ModifySettingLocal = true;
10473                     _isColumnChanged = true;
10474                 }
10475                 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10476                 {
10477                     _cfgLocal.Width8 = lst.Columns[7].Width;
10478                     ModifySettingLocal = true;
10479                     _isColumnChanged = true;
10480                 }
10481             }
10482             // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10483             //if (changed)
10484             //{
10485             //    SaveConfigsLocal();
10486             //}
10487         }
10488
10489         private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10490         {
10491             //発言詳細で「選択文字列をコピー」
10492             string _selText = this.PostBrowser.GetSelectedText();
10493             try
10494             {
10495                 Clipboard.SetDataObject(_selText, false, 5, 100);
10496             }
10497             catch (Exception ex)
10498             {
10499                 MessageBox.Show(ex.Message);
10500             }
10501         }
10502
10503         private async Task doSearchToolStrip(string url)
10504         {
10505             //発言詳細で「選択文字列で検索」(選択文字列取得)
10506             string _selText = this.PostBrowser.GetSelectedText();
10507
10508             if (_selText != null)
10509             {
10510                 if (url == Properties.Resources.SearchItem4Url)
10511                 {
10512                     //公式検索
10513                     AddNewTabForSearch(_selText);
10514                     return;
10515                 }
10516
10517                 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10518                 await this.OpenUriInBrowserAsync(tmp);
10519             }
10520         }
10521
10522         private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10523         {
10524             //発言詳細ですべて選択
10525             PostBrowser.Document.ExecCommand("SelectAll", false, null);
10526         }
10527
10528         private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10529         {
10530             await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10531         }
10532
10533         private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10534         {
10535             await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10536         }
10537
10538         private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10539         {
10540             await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10541         }
10542
10543         private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10544         {
10545             try
10546             {
10547                 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
10548                 {
10549                     if (link.GetAttribute("href") == this._postBrowserStatusText)
10550                     {
10551                         var linkStr = link.GetAttribute("title");
10552                         if (string.IsNullOrEmpty(linkStr))
10553                             linkStr = link.GetAttribute("href");
10554
10555                         Clipboard.SetDataObject(linkStr, false, 5, 100);
10556                         return;
10557                     }
10558                 }
10559
10560                 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10561             }
10562             catch (Exception ex)
10563             {
10564                 MessageBox.Show(ex.Message);
10565             }
10566         }
10567
10568         private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10569         {
10570             // URLコピーの項目の表示/非表示
10571             if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal))
10572             {
10573                 this._postBrowserStatusText = PostBrowser.StatusText;
10574                 string name = GetUserId();
10575                 UrlCopyContextMenuItem.Enabled = true;
10576                 if (name != null)
10577                 {
10578                     FollowContextMenuItem.Enabled = true;
10579                     RemoveContextMenuItem.Enabled = true;
10580                     FriendshipContextMenuItem.Enabled = true;
10581                     ShowUserStatusContextMenuItem.Enabled = true;
10582                     SearchPostsDetailToolStripMenuItem.Enabled = true;
10583                     IdFilterAddMenuItem.Enabled = true;
10584                     ListManageUserContextToolStripMenuItem.Enabled = true;
10585                     SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10586                 }
10587                 else
10588                 {
10589                     FollowContextMenuItem.Enabled = false;
10590                     RemoveContextMenuItem.Enabled = false;
10591                     FriendshipContextMenuItem.Enabled = false;
10592                     ShowUserStatusContextMenuItem.Enabled = false;
10593                     SearchPostsDetailToolStripMenuItem.Enabled = false;
10594                     IdFilterAddMenuItem.Enabled = false;
10595                     ListManageUserContextToolStripMenuItem.Enabled = false;
10596                     SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10597                 }
10598
10599                 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10600                     UseHashtagMenuItem.Enabled = true;
10601                 else
10602                     UseHashtagMenuItem.Enabled = false;
10603             }
10604             else
10605             {
10606                 this._postBrowserStatusText = "";
10607                 UrlCopyContextMenuItem.Enabled = false;
10608                 FollowContextMenuItem.Enabled = false;
10609                 RemoveContextMenuItem.Enabled = false;
10610                 FriendshipContextMenuItem.Enabled = false;
10611                 ShowUserStatusContextMenuItem.Enabled = false;
10612                 SearchPostsDetailToolStripMenuItem.Enabled = false;
10613                 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10614                 UseHashtagMenuItem.Enabled = false;
10615                 IdFilterAddMenuItem.Enabled = false;
10616                 ListManageUserContextToolStripMenuItem.Enabled = false;
10617             }
10618             // 文字列選択されていないときは選択文字列関係の項目を非表示に
10619             string _selText = this.PostBrowser.GetSelectedText();
10620             if (_selText == null)
10621             {
10622                 SelectionSearchContextMenuItem.Enabled = false;
10623                 SelectionCopyContextMenuItem.Enabled = false;
10624                 SelectionTranslationToolStripMenuItem.Enabled = false;
10625             }
10626             else
10627             {
10628                 SelectionSearchContextMenuItem.Enabled = true;
10629                 SelectionCopyContextMenuItem.Enabled = true;
10630                 SelectionTranslationToolStripMenuItem.Enabled = true;
10631             }
10632             //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10633             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10634             bool fAllFlag = false;
10635             foreach (Match mu in ma)
10636             {
10637                 if (mu.Result("${ScreenName}").ToLowerInvariant() != tw.Username.ToLowerInvariant())
10638                 {
10639                     fAllFlag = true;
10640                     break;
10641                 }
10642             }
10643             this.FriendshipAllMenuItem.Enabled = fAllFlag;
10644
10645             if (_curPost == null)
10646                 TranslationToolStripMenuItem.Enabled = false;
10647             else
10648                 TranslationToolStripMenuItem.Enabled = true;
10649
10650             e.Cancel = false;
10651         }
10652
10653         private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10654         {
10655             //発言詳細の選択文字列で現在のタブを検索
10656             string _selText = this.PostBrowser.GetSelectedText();
10657
10658             if (_selText != null)
10659             {
10660                 var searchOptions = new SearchWordDialog.SearchOptions(
10661                     SearchWordDialog.SearchType.Timeline,
10662                     _selText,
10663                     newTab: false,
10664                     caseSensitive: false,
10665                     useRegex: false);
10666
10667                 this.SearchDialog.ResultOptions = searchOptions;
10668
10669                 this.DoTabSearch(
10670                     searchOptions.Query,
10671                     searchOptions.CaseSensitive,
10672                     searchOptions.UseRegex,
10673                     SEARCHTYPE.NextSearch);
10674             }
10675         }
10676
10677         private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10678         {
10679             if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10680             ModifySettingLocal = true;
10681         }
10682
10683         private void TweenMain_DragDrop(object sender, DragEventArgs e)
10684         {
10685             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10686             {
10687                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10688                 {
10689                     SelectMedia_DragDrop(e);
10690                 }
10691             }
10692             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10693             {
10694                 var url = GetUrlFromDataObject(e.Data);
10695
10696                 string appendText;
10697                 if (url.Item2 == null)
10698                     appendText = url.Item1;
10699                 else
10700                     appendText = url.Item2 + " " + url.Item1;
10701
10702                 if (this.StatusText.TextLength == 0)
10703                     this.StatusText.Text = appendText;
10704                 else
10705                     this.StatusText.Text += " " + appendText;
10706             }
10707             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10708             {
10709                 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10710                 if (text != null)
10711                     this.StatusText.Text += text;
10712             }
10713             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10714             {
10715                 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10716                 if (data != null) StatusText.Text += data;
10717             }
10718         }
10719
10720         /// <summary>
10721         /// IDataObject から URL とタイトルの対を取得します
10722         /// </summary>
10723         /// <remarks>
10724         /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10725         /// </remarks>
10726         /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10727         /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10728         internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10729         {
10730             if (data.GetDataPresent("text/x-moz-url"))
10731             {
10732                 // Firefox, Google Chrome で利用可能
10733                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10734
10735                 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10736                 {
10737                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10738                     if (lines.Length < 2)
10739                         throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10740
10741                     return new Tuple<string, string>(lines[0], lines[1]);
10742                 }
10743             }
10744             else if (data.GetDataPresent("IESiteModeToUrl"))
10745             {
10746                 // Internet Exproler 用
10747                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10748
10749                 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10750                 {
10751                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10752                     if (lines.Length < 2)
10753                         throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10754
10755                     return new Tuple<string, string>(lines[0], lines[1]);
10756                 }
10757             }
10758             else if (data.GetDataPresent("UniformResourceLocatorW"))
10759             {
10760                 // それ以外のブラウザ向け
10761
10762                 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10763                 {
10764                     var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10765                     return new Tuple<string, string>(url, null);
10766                 }
10767             }
10768
10769             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10770         }
10771
10772         private void TweenMain_DragEnter(object sender, DragEventArgs e)
10773         {
10774             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10775             {
10776                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10777                 {
10778                     SelectMedia_DragEnter(e);
10779                     return;
10780                 }
10781             }
10782             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10783             {
10784                 e.Effect = DragDropEffects.Copy;
10785                 return;
10786             }
10787             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10788             {
10789                 e.Effect = DragDropEffects.Copy;
10790                 return;
10791             }
10792             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10793             {
10794                 e.Effect = DragDropEffects.Copy;
10795                 return;
10796             }
10797
10798             e.Effect = DragDropEffects.None;
10799         }
10800
10801         private void TweenMain_DragOver(object sender, DragEventArgs e)
10802         {
10803         }
10804
10805         public bool IsNetworkAvailable()
10806         {
10807             bool nw = true;
10808             nw = MyCommon.IsNetworkAvailable();
10809             _myStatusOnline = nw;
10810             return nw;
10811         }
10812
10813         public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10814         {
10815             var uriStr = uri.AbsoluteUri;
10816
10817             // OpenTween 内部で使用する URL
10818             if (uri.Authority == "opentween")
10819             {
10820                 await this.OpenInternalUriAsync(uri);
10821                 return;
10822             }
10823
10824             // ハッシュタグを含む Twitter 検索
10825             if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10826             {
10827                 // ハッシュタグの場合は、タブで開く
10828                 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10829                 var pos = unescapedQuery.IndexOf('#');
10830                 if (pos == -1) return;
10831
10832                 var hash = unescapedQuery.Substring(pos);
10833                 this.HashSupl.AddItem(hash);
10834                 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10835                 this.AddNewTabForSearch(hash);
10836                 return;
10837             }
10838
10839             // ユーザープロフィールURL
10840             // フラグが立っている場合は設定と逆の動作をする
10841             if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10842                 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10843             {
10844                 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10845                 if (userUriMatch.Success)
10846                 {
10847                     var screenName = userUriMatch.Groups["ScreenName"].Value;
10848                     if (this.IsTwitterId(screenName))
10849                     {
10850                         this.AddNewTabForUserTimeline(screenName);
10851                         return;
10852                     }
10853                 }
10854             }
10855
10856             // どのパターンにも該当しないURL
10857             await this.OpenUriInBrowserAsync(uriStr);
10858         }
10859
10860         /// <summary>
10861         /// OpenTween 内部の機能を呼び出すための URL を開きます
10862         /// </summary>
10863         private async Task OpenInternalUriAsync(Uri uri)
10864         {
10865             // ツイートを開く (//opentween/status/:status_id)
10866             var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10867             if (match.Success)
10868             {
10869                 var statusId = long.Parse(match.Groups[1].Value);
10870                 await this.OpenRelatedTab(statusId);
10871                 return;
10872             }
10873         }
10874
10875         public Task OpenUriInBrowserAsync(string UriString)
10876         {
10877             return Task.Run(() =>
10878             {
10879                 string myPath = UriString;
10880
10881                 try
10882                 {
10883                     var configBrowserPath = this._cfgLocal.BrowserPath;
10884                     if (!string.IsNullOrEmpty(configBrowserPath))
10885                     {
10886                         if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
10887                         {
10888                             int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
10889                             string browserPath = configBrowserPath.Substring(1, sep - 1);
10890                             string arg = "";
10891                             if (sep < configBrowserPath.Length - 1)
10892                             {
10893                                 arg = configBrowserPath.Substring(sep + 1);
10894                             }
10895                             myPath = arg + " " + myPath;
10896                             System.Diagnostics.Process.Start(browserPath, myPath);
10897                         }
10898                         else
10899                         {
10900                             System.Diagnostics.Process.Start(configBrowserPath, myPath);
10901                         }
10902                     }
10903                     else
10904                     {
10905                         System.Diagnostics.Process.Start(myPath);
10906                     }
10907                 }
10908                 catch (Exception)
10909                 {
10910                     //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10911                 }
10912             });
10913         }
10914
10915         private void ListTabSelect(TabPage _tab)
10916         {
10917             SetListProperty();
10918
10919             this.PurgeListViewItemCache();
10920
10921             _curTab = _tab;
10922             _curList = (DetailsListView)_tab.Tag;
10923             if (_curList.SelectedIndices.Count > 0)
10924             {
10925                 _curItemIndex = _curList.SelectedIndices[0];
10926                 _curPost = GetCurTabPost(_curItemIndex);
10927             }
10928             else
10929             {
10930                 _curItemIndex = -1;
10931                 _curPost = null;
10932             }
10933
10934             _anchorPost = null;
10935             _anchorFlag = false;
10936
10937             if (_iconCol)
10938             {
10939                 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10940             }
10941             else
10942             {
10943                 for (int i = 0; i < _curList.Columns.Count; i++)
10944                 {
10945                     ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10946                 }
10947             }
10948         }
10949
10950         private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10951         {
10952             ListTabSelect(e.TabPage);
10953         }
10954
10955         private void SelectListItem(DetailsListView LView, int Index)
10956         {
10957             //単一
10958             Rectangle bnd = new Rectangle();
10959             bool flg = false;
10960             var item = LView.FocusedItem;
10961             if (item != null)
10962             {
10963                 bnd = item.Bounds;
10964                 flg = true;
10965             }
10966
10967             do
10968             {
10969                 LView.SelectedIndices.Clear();
10970             }
10971             while (LView.SelectedIndices.Count > 0);
10972             item = LView.Items[Index];
10973             item.Selected = true;
10974             item.Focused = true;
10975
10976             if (flg) LView.Invalidate(bnd);
10977         }
10978
10979         private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10980         {
10981             //複数
10982             Rectangle bnd = new Rectangle();
10983             bool flg = false;
10984             var item = LView.FocusedItem;
10985             if (item != null)
10986             {
10987                 bnd = item.Bounds;
10988                 flg = true;
10989             }
10990
10991             if (Index != null)
10992             {
10993                 do
10994                 {
10995                     LView.SelectedIndices.Clear();
10996                 }
10997                 while (LView.SelectedIndices.Count > 0);
10998                 LView.SelectItems(Index);
10999             }
11000             if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
11001             {
11002                 LView.SelectionMark = selectionMarkIndex;
11003             }
11004             if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
11005             {
11006                 LView.Items[focusedIndex].Focused = true;
11007             }
11008             else if (Index != null && Index.Length != 0)
11009             {
11010                 LView.Items[Index.Last()].Focused = true;
11011             }
11012
11013             if (flg) LView.Invalidate(bnd);
11014         }
11015
11016         private void StartUserStream()
11017         {
11018             tw.NewPostFromStream += tw_NewPostFromStream;
11019             tw.UserStreamStarted += tw_UserStreamStarted;
11020             tw.UserStreamStopped += tw_UserStreamStopped;
11021             tw.PostDeleted += tw_PostDeleted;
11022             tw.UserStreamEventReceived += tw_UserStreamEventArrived;
11023
11024             this.RefreshUserStreamsMenu();
11025
11026             if (this._cfgCommon.UserstreamStartup)
11027                 tw.StartUserStream();
11028         }
11029
11030         private async void TweenMain_Shown(object sender, EventArgs e)
11031         {
11032             try
11033             {
11034                 using (ControlTransaction.Update(this.PostBrowser))
11035                 {
11036                     PostBrowser.Url = new Uri("about:blank");
11037                     PostBrowser.DocumentText = "";       //発言詳細部初期化
11038                 }
11039             }
11040             catch (Exception)
11041             {
11042             }
11043
11044             NotifyIcon1.Visible = true;
11045
11046             if (this.IsNetworkAvailable())
11047             {
11048                 StartUserStream();
11049
11050                 var loadTasks = new List<Task>
11051                 {
11052                     this.RefreshMuteUserIdsAsync(),
11053                     this.RefreshBlockIdsAsync(),
11054                     this.RefreshNoRetweetIdsAsync(),
11055                     this.RefreshTwitterConfigurationAsync(),
11056                     this.GetHomeTimelineAsync(),
11057                     this.GetReplyAsync(),
11058                     this.GetDirectMessagesAsync(),
11059                     this.GetPublicSearchAllAsync(),
11060                     this.GetUserTimelineAllAsync(),
11061                     this.GetListTimelineAllAsync(),
11062                 };
11063
11064                 if (this._cfgCommon.StartupFollowers)
11065                     loadTasks.Add(this.RefreshFollowerIdsAsync());
11066
11067                 if (this._cfgCommon.GetFav)
11068                     loadTasks.Add(this.GetFavoritesAsync());
11069
11070                 var allTasks = Task.WhenAll(loadTasks);
11071
11072                 var i = 0;
11073                 while (true)
11074                 {
11075                     var timeout = Task.Delay(5000);
11076                     if (await Task.WhenAny(allTasks, timeout) != timeout)
11077                         break;
11078
11079                     i += 1;
11080                     if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11081
11082                     if (MyCommon._endingFlag)
11083                         return;
11084                 }
11085
11086                 if (MyCommon._endingFlag) return;
11087
11088                 if (ApplicationSettings.VersionInfoUrl != null)
11089                 {
11090                     //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11091                     if (this._cfgCommon.StartupVersion)
11092                         await this.CheckNewVersion(true);
11093                 }
11094                 else
11095                 {
11096                     // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11097                     this.VerUpMenuItem.Enabled = false;
11098                     this.VerUpMenuItem.Available = false;
11099                     this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11100                 }
11101
11102                 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11103                 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11104                 {
11105                     MessageBox.Show(Properties.Resources.ReAuthorizeText);
11106                     SettingStripMenuItem_Click(null, null);
11107                 }
11108
11109                 // 取得失敗の場合は再試行する
11110                 var reloadTasks = new List<Task>();
11111
11112                 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11113                     reloadTasks.Add(this.RefreshFollowerIdsAsync());
11114
11115                 if (!tw.GetNoRetweetSuccess)
11116                     reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11117
11118                 if (this.tw.Configuration.PhotoSizeLimit == 0)
11119                     reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11120
11121                 await Task.WhenAll(reloadTasks);
11122             }
11123
11124             _initial = false;
11125
11126             TimerTimeline.Enabled = true;
11127         }
11128
11129         private async Task doGetFollowersMenu()
11130         {
11131             await this.RefreshFollowerIdsAsync();
11132             await this.DispSelectedPost(true);
11133         }
11134
11135         private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11136         {
11137             await this.doGetFollowersMenu();
11138         }
11139
11140         private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
11141         {
11142             doReTweetUnofficial();
11143         }
11144
11145         private async Task doReTweetOfficial(bool isConfirm)
11146         {
11147             //公式RT
11148             if (this.ExistCurrentPost)
11149             {
11150                 if (_curPost.IsProtect)
11151                 {
11152                     MessageBox.Show("Protected.");
11153                     _DoFavRetweetFlags = false;
11154                     return;
11155                 }
11156                 if (_curList.SelectedIndices.Count > 15)
11157                 {
11158                     MessageBox.Show(Properties.Resources.RetweetLimitText);
11159                     _DoFavRetweetFlags = false;
11160                     return;
11161                 }
11162                 else if (_curList.SelectedIndices.Count > 1)
11163                 {
11164                     string QuestionText = Properties.Resources.RetweetQuestion2;
11165                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11166                     switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11167                     {
11168                         case DialogResult.Cancel:
11169                         case DialogResult.No:
11170                             _DoFavRetweetFlags = false;
11171                             return;
11172                     }
11173                 }
11174                 else
11175                 {
11176                     if (_curPost.IsDm || _curPost.IsMe)
11177                     {
11178                         _DoFavRetweetFlags = false;
11179                         return;
11180                     }
11181                     if (!this._cfgCommon.RetweetNoConfirm)
11182                     {
11183                         string Questiontext = Properties.Resources.RetweetQuestion1;
11184                         if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11185                         if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11186                         {
11187                             _DoFavRetweetFlags = false;
11188                             return;
11189                         }
11190                     }
11191                 }
11192
11193                 var statusIds = new List<long>();
11194                 foreach (int idx in _curList.SelectedIndices)
11195                 {
11196                     PostClass post = GetCurTabPost(idx);
11197                     if (!post.IsMe && !post.IsProtect && !post.IsDm)
11198                         statusIds.Add(post.StatusId);
11199                 }
11200
11201                 await this.RetweetAsync(statusIds);
11202             }
11203         }
11204
11205         private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11206         {
11207             await this.doReTweetOfficial(true);
11208         }
11209
11210         private async Task FavoritesRetweetOfficial()
11211         {
11212             if (!this.ExistCurrentPost) return;
11213             _DoFavRetweetFlags = true;
11214             var retweetTask = this.doReTweetOfficial(true);
11215             if (_DoFavRetweetFlags)
11216             {
11217                 _DoFavRetweetFlags = false;
11218                 var favoriteTask = this.FavoriteChange(true, false);
11219
11220                 await Task.WhenAll(retweetTask, favoriteTask);
11221             }
11222             else
11223             {
11224                 await retweetTask;
11225             }
11226         }
11227
11228         private async Task FavoritesRetweetUnofficial()
11229         {
11230             if (this.ExistCurrentPost && !_curPost.IsDm)
11231             {
11232                 _DoFavRetweetFlags = true;
11233                 var favoriteTask = this.FavoriteChange(true);
11234                 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11235                 {
11236                     _DoFavRetweetFlags = false;
11237                     doReTweetUnofficial();
11238                 }
11239
11240                 await favoriteTask;
11241             }
11242         }
11243
11244         /// <summary>
11245         /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11246         /// </summary>
11247         /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11248         /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11249         /// <returns>復元されたツイート本文</returns>
11250         internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11251         {
11252             // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11253
11254             // 通常の URL
11255             statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11256             // メンション
11257             statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11258             // ハッシュタグ
11259             statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11260
11261             // <br> 除去
11262             if (multiline)
11263                 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11264             else
11265                 statusHtml = statusHtml.Replace("<br>", " ");
11266
11267             // &nbsp; は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11268             // 現状では半角スペースの代用として &nbsp; を使用しているため U+0020 に置換します
11269             statusHtml = statusHtml.Replace("&nbsp;", " ");
11270
11271             return WebUtility.HtmlDecode(statusHtml);
11272         }
11273
11274         private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11275         {
11276             if (_curPost != null)
11277                 await this.DispSelectedPost(true);
11278         }
11279
11280         private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11281         {
11282             if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11283                 DebugModeToolStripMenuItem.Visible = true;
11284             else
11285                 DebugModeToolStripMenuItem.Visible = false;
11286         }
11287
11288         private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11289         {
11290             this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11291         }
11292
11293         private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11294         {
11295             ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11296         }
11297
11298         private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11299         {
11300             if (TraceOutToolStripMenuItem.Checked)
11301                 MyCommon.TraceFlag = true;
11302             else
11303                 MyCommon.TraceFlag = false;
11304         }
11305
11306         private void TweenMain_Deactivate(object sender, EventArgs e)
11307         {
11308             //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11309             this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11310         }
11311
11312         private void TabRenameMenuItem_Click(object sender, EventArgs e)
11313         {
11314             if (string.IsNullOrEmpty(_rclickTabName)) return;
11315             TabRename(ref _rclickTabName);
11316         }
11317
11318         private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11319         {
11320             await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11321         }
11322
11323         private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11324         {
11325             await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11326         }
11327
11328         private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11329         {
11330             TwitterApiStatus apiStatus;
11331
11332             using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
11333             {
11334                 var cancellationToken = dialog.EnableCancellation();
11335
11336                 try
11337                 {
11338                     var task = this.tw.GetInfoApi();
11339                     apiStatus = await dialog.WaitForAsync(this, task);
11340                 }
11341                 catch (WebApiException)
11342                 {
11343                     apiStatus = null;
11344                 }
11345
11346                 if (cancellationToken.IsCancellationRequested)
11347                     return;
11348
11349                 if (apiStatus == null)
11350                 {
11351                     MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11352                     return;
11353                 }
11354             }
11355
11356             using (var apiDlg = new ApiInfoDialog())
11357             {
11358                 apiDlg.ShowDialog(this);
11359             }
11360         }
11361
11362         private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
11363         {
11364             var id = _curPost?.ScreenName ?? "";
11365
11366             await this.FollowCommand(id);
11367         }
11368
11369         private async Task FollowCommand(string id)
11370         {
11371             using (var inputName = new InputTabName())
11372             {
11373                 inputName.FormTitle = "Follow";
11374                 inputName.FormDescription = Properties.Resources.FRMessage1;
11375                 inputName.TabName = id;
11376
11377                 if (inputName.ShowDialog(this) != DialogResult.OK)
11378                     return;
11379                 if (string.IsNullOrWhiteSpace(inputName.TabName))
11380                     return;
11381
11382                 id = inputName.TabName.Trim();
11383             }
11384
11385             using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11386             {
11387                 try
11388                 {
11389                     var task = this.twitterApi.FriendshipsCreate(id);
11390                     await dialog.WaitForAsync(this, task);
11391                 }
11392                 catch (WebApiException ex)
11393                 {
11394                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11395                     return;
11396                 }
11397             }
11398
11399             MessageBox.Show(Properties.Resources.FRMessage3);
11400         }
11401
11402         private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11403         {
11404             var id = _curPost?.ScreenName ?? "";
11405
11406             await this.RemoveCommand(id, false);
11407         }
11408
11409         private async Task RemoveCommand(string id, bool skipInput)
11410         {
11411             if (!skipInput)
11412             {
11413                 using (var inputName = new InputTabName())
11414                 {
11415                     inputName.FormTitle = "Unfollow";
11416                     inputName.FormDescription = Properties.Resources.FRMessage1;
11417                     inputName.TabName = id;
11418
11419                     if (inputName.ShowDialog(this) != DialogResult.OK)
11420                         return;
11421                     if (string.IsNullOrWhiteSpace(inputName.TabName))
11422                         return;
11423
11424                     id = inputName.TabName.Trim();
11425                 }
11426             }
11427
11428             using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11429             {
11430                 try
11431                 {
11432                     var task = this.twitterApi.FriendshipsDestroy(id);
11433                     await dialog.WaitForAsync(this, task);
11434                 }
11435                 catch (WebApiException ex)
11436                 {
11437                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11438                     return;
11439                 }
11440             }
11441
11442             MessageBox.Show(Properties.Resources.FRMessage3);
11443         }
11444
11445         private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11446         {
11447             var id = _curPost?.ScreenName ?? "";
11448
11449             await this.ShowFriendship(id);
11450         }
11451
11452         private async Task ShowFriendship(string id)
11453         {
11454             using (var inputName = new InputTabName())
11455             {
11456                 inputName.FormTitle = "Show Friendships";
11457                 inputName.FormDescription = Properties.Resources.FRMessage1;
11458                 inputName.TabName = id;
11459
11460                 if (inputName.ShowDialog(this) != DialogResult.OK)
11461                     return;
11462                 if (string.IsNullOrWhiteSpace(inputName.TabName))
11463                     return;
11464
11465                 id = inputName.TabName.Trim();
11466             }
11467
11468             bool isFollowing, isFollowed;
11469
11470             using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11471             {
11472                 var cancellationToken = dialog.EnableCancellation();
11473
11474                 try
11475                 {
11476                     var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11477                     var friendship = await dialog.WaitForAsync(this, task);
11478
11479                     isFollowing = friendship.Relationship.Source.Following;
11480                     isFollowed = friendship.Relationship.Source.FollowedBy;
11481                 }
11482                 catch (WebApiException ex)
11483                 {
11484                     if (!cancellationToken.IsCancellationRequested)
11485                         MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11486                     return;
11487                 }
11488
11489                 if (cancellationToken.IsCancellationRequested)
11490                     return;
11491             }
11492
11493             string result = "";
11494             if (isFollowing)
11495             {
11496                 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11497             }
11498             else
11499             {
11500                 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11501             }
11502             if (isFollowed)
11503             {
11504                 result += Properties.Resources.GetFriendshipInfo3;
11505             }
11506             else
11507             {
11508                 result += Properties.Resources.GetFriendshipInfo4;
11509             }
11510             result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11511             MessageBox.Show(result);
11512         }
11513
11514         private async Task ShowFriendship(string[] ids)
11515         {
11516             foreach (string id in ids)
11517             {
11518                 bool isFollowing, isFollowed;
11519
11520                 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11521                 {
11522                     var cancellationToken = dialog.EnableCancellation();
11523
11524                     try
11525                     {
11526                         var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11527                         var friendship = await dialog.WaitForAsync(this, task);
11528
11529                         isFollowing = friendship.Relationship.Source.Following;
11530                         isFollowed = friendship.Relationship.Source.FollowedBy;
11531                     }
11532                     catch (WebApiException ex)
11533                     {
11534                         if (!cancellationToken.IsCancellationRequested)
11535                             MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11536                         return;
11537                     }
11538
11539                     if (cancellationToken.IsCancellationRequested)
11540                         return;
11541                 }
11542
11543                 string result = "";
11544                 string ff = "";
11545
11546                 ff = "  ";
11547                 if (isFollowing)
11548                 {
11549                     ff += Properties.Resources.GetFriendshipInfo1;
11550                 }
11551                 else
11552                 {
11553                     ff += Properties.Resources.GetFriendshipInfo2;
11554                 }
11555
11556                 ff += System.Environment.NewLine + "  ";
11557                 if (isFollowed)
11558                 {
11559                     ff += Properties.Resources.GetFriendshipInfo3;
11560                 }
11561                 else
11562                 {
11563                     ff += Properties.Resources.GetFriendshipInfo4;
11564                 }
11565                 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11566                 if (isFollowing)
11567                 {
11568                     if (MessageBox.Show(
11569                         Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11570                         MessageBoxButtons.YesNo,
11571                         MessageBoxIcon.Question,
11572                         MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11573                     {
11574                         await this.RemoveCommand(id, true);
11575                     }
11576                 }
11577                 else
11578                 {
11579                     MessageBox.Show(result);
11580                 }
11581             }
11582         }
11583
11584         private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11585         {
11586             await this.doShowUserStatus(tw.Username, false);
11587             //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11588             //{
11589             //    doShowUserStatus(tw.Username, false);
11590             //}
11591             //else
11592             //{
11593             //    MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11594             //    return;
11595             //}
11596         }
11597
11598         // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11599         // URLから切り出した文字列を渡す
11600
11601         public bool IsTwitterId(string name)
11602         {
11603             if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11604                 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11605             else
11606                 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
11607         }
11608
11609         private string GetUserId()
11610         {
11611             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11612             if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11613                 return m.Result("${ScreenName}");
11614             else
11615                 return null;
11616         }
11617
11618         private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11619         {
11620             string name = GetUserId();
11621             if (name != null)
11622                 await this.FollowCommand(name);
11623         }
11624
11625         private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11626         {
11627             string name = GetUserId();
11628             if (name != null)
11629                 await this.RemoveCommand(name, false);
11630         }
11631
11632         private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11633         {
11634             string name = GetUserId();
11635             if (name != null)
11636                 await this.ShowFriendship(name);
11637         }
11638
11639         private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11640         {
11641             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11642             List<string> ids = new List<string>();
11643             foreach (Match mu in ma)
11644             {
11645                 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11646                 {
11647                     ids.Add(mu.Result("${ScreenName}"));
11648                 }
11649             }
11650
11651             await this.ShowFriendship(ids.ToArray());
11652         }
11653
11654         private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11655         {
11656             string name = GetUserId();
11657             if (name != null)
11658                 await this.ShowUserStatus(name);
11659         }
11660
11661         private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11662         {
11663             string name = GetUserId();
11664             if (name != null) AddNewTabForUserTimeline(name);
11665         }
11666
11667         private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11668         {
11669             string name = GetUserId();
11670             if (name != null) AddNewTabForSearch("@" + name);
11671         }
11672
11673         private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11674         {
11675             ModifySettingCommon = true;
11676         }
11677
11678         private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11679         {
11680             ModifySettingCommon = true;
11681         }
11682
11683         private void doQuoteOfficial()
11684         {
11685             if (this.ExistCurrentPost)
11686             {
11687                 if (_curPost.IsDm ||
11688                     !StatusText.Enabled) return;
11689
11690                 if (_curPost.IsProtect)
11691                 {
11692                     MessageBox.Show("Protected.");
11693                     return;
11694                 }
11695
11696                 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11697
11698                 this.inReplyTo = null;
11699
11700                 StatusText.SelectionStart = 0;
11701                 StatusText.Focus();
11702             }
11703         }
11704
11705         private void doReTweetUnofficial()
11706         {
11707             //RT @id:内容
11708             if (this.ExistCurrentPost)
11709             {
11710                 if (_curPost.IsDm || !StatusText.Enabled)
11711                     return;
11712
11713                 if (_curPost.IsProtect)
11714                 {
11715                     MessageBox.Show("Protected.");
11716                     return;
11717                 }
11718                 string rtdata = _curPost.Text;
11719                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11720
11721                 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11722
11723                 // 投稿時に in_reply_to_status_id を付加する
11724                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11725                 var inReplyToScreenName = this._curPost.ScreenName;
11726                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11727
11728                 StatusText.SelectionStart = 0;
11729                 StatusText.Focus();
11730             }
11731         }
11732
11733         private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11734         {
11735             doQuoteOfficial();
11736         }
11737
11738         private void SearchButton_Click(object sender, EventArgs e)
11739         {
11740             //公式検索
11741             Control pnl = ((Control)sender).Parent;
11742             if (pnl == null) return;
11743             string tbName = pnl.Parent.Text;
11744             TabClass tb = _statuses.Tabs[tbName];
11745             ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11746             ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11747             cmb.Text = cmb.Text.Trim();
11748             // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11749             bool Quote = false;
11750             StringBuilder buf = new StringBuilder();
11751             char[] c = cmb.Text.ToCharArray();
11752             for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11753             {
11754                 if (cnt > cmb.Text.Length - 4)
11755                 {
11756                     buf.Append(cmb.Text.Substring(cnt));
11757                     break;
11758                 }
11759                 if (c[cnt] == '"')
11760                 {
11761                     Quote = !Quote;
11762                 }
11763                 else
11764                 {
11765                     if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11766                     {
11767                         buf.Append(" OR ");
11768                         cnt += 3;
11769                         continue;
11770                     }
11771                 }
11772                 buf.Append(c[cnt]);
11773             }
11774             cmb.Text = buf.ToString();
11775
11776             var listView = (DetailsListView)pnl.Parent.Tag;
11777
11778             tb.SearchWords = cmb.Text;
11779             tb.SearchLang = cmbLang.Text;
11780             if (string.IsNullOrEmpty(cmb.Text))
11781             {
11782                 listView.Focus();
11783                 SaveConfigsTabs();
11784                 return;
11785             }
11786             if (tb.IsSearchQueryChanged)
11787             {
11788                 int idx = cmb.Items.IndexOf(tb.SearchWords);
11789                 if (idx > -1) cmb.Items.RemoveAt(idx);
11790                 cmb.Items.Insert(0, tb.SearchWords);
11791                 cmb.Text = tb.SearchWords;
11792                 cmb.SelectAll();
11793                 this.PurgeListViewItemCache();
11794                 listView.VirtualListSize = 0;
11795                 _statuses.ClearTabIds(tbName);
11796                 SaveConfigsTabs();   //検索条件の保存
11797             }
11798
11799             this.GetPublicSearchAsync(tb);
11800             listView.Focus();
11801         }
11802
11803         private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11804         {
11805             //もっと前を取得
11806             await this.DoRefreshMore();
11807         }
11808
11809         /// <summary>
11810         /// 指定されたタブのListTabにおける位置を返します
11811         /// </summary>
11812         /// <remarks>
11813         /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11814         /// </remarks>
11815         public int GetTabPageIndex(string tabName)
11816         {
11817             var index = 0;
11818             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11819             {
11820                 if (tabPage.Text == tabName)
11821                     return index;
11822
11823                 index++;
11824             }
11825
11826             return -1;
11827         }
11828
11829         private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11830         {
11831             if (_statuses.RemovedTab.Count == 0)
11832             {
11833                 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11834                 return;
11835             }
11836             else
11837             {
11838                 DetailsListView listView = null;
11839
11840                 TabClass tb = _statuses.RemovedTab.Pop();
11841                 if (tb.TabType == MyCommon.TabUsageType.Related)
11842                 {
11843                     var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11844                     if (relatedTab != null)
11845                     {
11846                         // 関連発言なら既存のタブを置き換える
11847                         tb.TabName = relatedTab.TabName;
11848                         this.ClearTab(tb.TabName, false);
11849                         _statuses.Tabs[tb.TabName] = tb;
11850
11851                         for (int i = 0; i < ListTab.TabPages.Count; i++)
11852                         {
11853                             var tabPage = ListTab.TabPages[i];
11854                             if (tb.TabName == tabPage.Text)
11855                             {
11856                                 listView = (DetailsListView)tabPage.Tag;
11857                                 ListTab.SelectedIndex = i;
11858                                 break;
11859                             }
11860                         }
11861                     }
11862                     else
11863                     {
11864                         const string TabName = "Related Tweets";
11865                         string renamed = TabName;
11866                         for (int i = 2; i <= 100; i++)
11867                         {
11868                             if (!_statuses.ContainsTab(renamed)) break;
11869                             renamed = TabName + i.ToString();
11870                         }
11871                         tb.TabName = renamed;
11872                         AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11873                         _statuses.Tabs.Add(renamed, tb);  // 後に
11874
11875                         var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11876                         listView = (DetailsListView)tabPage.Tag;
11877                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11878                     }
11879                 }
11880                 else
11881                 {
11882                     string renamed = tb.TabName;
11883                     for (int i = 1; i < int.MaxValue; i++)
11884                     {
11885                         if (!_statuses.ContainsTab(renamed)) break;
11886                         renamed = tb.TabName + "(" + i.ToString() + ")";
11887                     }
11888                     tb.TabName = renamed;
11889                     _statuses.Tabs.Add(renamed, tb);  // 先に
11890                     AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11891
11892                     var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11893                     listView = (DetailsListView)tabPage.Tag;
11894                     ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11895                 }
11896                 SaveConfigsTabs();
11897
11898                 if (listView != null)
11899                 {
11900                     using (ControlTransaction.Update(listView))
11901                     {
11902                         listView.VirtualListSize = tb.AllCount;
11903                     }
11904                 }
11905             }
11906         }
11907
11908         private async Task doMoveToRTHome()
11909         {
11910             if (_curList.SelectedIndices.Count > 0)
11911             {
11912                 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11913                 if (post.RetweetedId != null)
11914                 {
11915                     await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11916                 }
11917             }
11918         }
11919
11920         private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11921         {
11922             await this.doMoveToRTHome();
11923         }
11924
11925         private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11926         {
11927             string name = GetUserId();
11928             if (name != null)
11929             {
11930                 string tabName;
11931
11932                 //未選択なら処理終了
11933                 if (_curList.SelectedIndices.Count == 0) return;
11934
11935                 //タブ選択(or追加)
11936                 if (!SelectTab(out tabName)) return;
11937
11938                 var tab = this._statuses.Tabs[tabName];
11939
11940                 bool mv;
11941                 bool mk;
11942                 if (tab.TabType != MyCommon.TabUsageType.Mute)
11943                 {
11944                     this.MoveOrCopy(out mv, out mk);
11945                 }
11946                 else
11947                 {
11948                     // ミュートタブでは常に MoveMatches を true にする
11949                     mv = true;
11950                     mk = false;
11951                 }
11952
11953                 PostFilterRule fc = new PostFilterRule();
11954                 fc.FilterName = name;
11955                 fc.UseNameField = true;
11956                 fc.MoveMatches = mv;
11957                 fc.MarkMatches = mk;
11958                 fc.UseRegex = false;
11959                 fc.FilterByUrl = false;
11960                 tab.AddFilter(fc);
11961
11962                 this.ApplyPostFilters();
11963                 SaveConfigsTabs();
11964             }
11965         }
11966
11967         private async void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11968         {
11969             string user;
11970
11971             ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11972
11973             if (menuItem.Owner == this.ContextMenuPostBrowser)
11974             {
11975                 user = GetUserId();
11976                 if (user == null) return;
11977             }
11978             else if (this._curPost != null)
11979             {
11980                 user = this._curPost.ScreenName;
11981             }
11982             else
11983             {
11984                 return;
11985             }
11986
11987             if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11988             {
11989                 try
11990                 {
11991                     using (var dialog = new WaitingDialog(Properties.Resources.ListsGetting))
11992                     {
11993                         var cancellationToken = dialog.EnableCancellation();
11994
11995                         var task = this.tw.GetListsApi();
11996                         await dialog.WaitForAsync(this, task);
11997
11998                         cancellationToken.ThrowIfCancellationRequested();
11999                     }
12000                 }
12001                 catch (OperationCanceledException) { return; }
12002                 catch (WebApiException ex)
12003                 {
12004                     MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
12005                     return;
12006                 }
12007             }
12008
12009             using (MyLists listSelectForm = new MyLists(user, this.tw))
12010             {
12011                 listSelectForm.ShowDialog(this);
12012             }
12013         }
12014
12015         private void SearchControls_Enter(object sender, EventArgs e)
12016         {
12017             Control pnl = (Control)sender;
12018             foreach (Control ctl in pnl.Controls)
12019             {
12020                 ctl.TabStop = true;
12021             }
12022         }
12023
12024         private void SearchControls_Leave(object sender, EventArgs e)
12025         {
12026             Control pnl = (Control)sender;
12027             foreach (Control ctl in pnl.Controls)
12028             {
12029                 ctl.TabStop = false;
12030             }
12031         }
12032
12033         private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12034         {
12035             if (ListTab.SelectedTab != null)
12036             {
12037                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12038                 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12039             }
12040         }
12041
12042         private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12043         {
12044             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12045             if (m.Success)
12046             {
12047                 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12048                 HashStripSplitButton.Text = HashMgr.UseHash;
12049                 HashToggleMenuItem.Checked = true;
12050                 HashToggleToolStripMenuItem.Checked = true;
12051                 //使用ハッシュタグとして設定
12052                 ModifySettingCommon = true;
12053             }
12054         }
12055
12056         private void StatusLabel_DoubleClick(object sender, EventArgs e)
12057         {
12058             MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12059         }
12060
12061         private void HashManageMenuItem_Click(object sender, EventArgs e)
12062         {
12063             DialogResult rslt = DialogResult.Cancel;
12064             try
12065             {
12066                 rslt = HashMgr.ShowDialog();
12067             }
12068             catch (Exception)
12069             {
12070                 return;
12071             }
12072             this.TopMost = this._cfgCommon.AlwaysTop;
12073             if (rslt == DialogResult.Cancel) return;
12074             if (!string.IsNullOrEmpty(HashMgr.UseHash))
12075             {
12076                 HashStripSplitButton.Text = HashMgr.UseHash;
12077                 HashToggleMenuItem.Checked = true;
12078                 HashToggleToolStripMenuItem.Checked = true;
12079             }
12080             else
12081             {
12082                 HashStripSplitButton.Text = "#[-]";
12083                 HashToggleMenuItem.Checked = false;
12084                 HashToggleToolStripMenuItem.Checked = false;
12085             }
12086             //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12087             //{
12088             //    int sidx = StatusText.SelectionStart;
12089             //    string hash = HashMgr.UseHash + " ";
12090             //    if (sidx > 0)
12091             //    {
12092             //        if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12093             //            hash = " " + hash;
12094             //    }
12095             //    StatusText.Text = StatusText.Text.Insert(sidx, hash);
12096             //    sidx += hash.Length;
12097             //    StatusText.SelectionStart = sidx;
12098             //    StatusText.Focus();
12099             //}
12100             ModifySettingCommon = true;
12101             this.StatusText_TextChanged(null, null);
12102         }
12103
12104         private void HashToggleMenuItem_Click(object sender, EventArgs e)
12105         {
12106             HashMgr.ToggleHash();
12107             if (!string.IsNullOrEmpty(HashMgr.UseHash))
12108             {
12109                 HashStripSplitButton.Text = HashMgr.UseHash;
12110                 HashToggleMenuItem.Checked = true;
12111                 HashToggleToolStripMenuItem.Checked = true;
12112             }
12113             else
12114             {
12115                 HashStripSplitButton.Text = "#[-]";
12116                 HashToggleMenuItem.Checked = false;
12117                 HashToggleToolStripMenuItem.Checked = false;
12118             }
12119             ModifySettingCommon = true;
12120             this.StatusText_TextChanged(null, null);
12121         }
12122
12123         private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12124         {
12125             HashToggleMenuItem_Click(null, null);
12126         }
12127
12128         private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12129         {
12130             if (ListTab.SelectedTab == null) return;
12131             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12132             if (!this.ExistCurrentPost)
12133             {
12134                 this.ReplyOpMenuItem.Enabled = false;
12135                 this.ReplyAllOpMenuItem.Enabled = false;
12136                 this.DmOpMenuItem.Enabled = false;
12137                 this.ShowProfMenuItem.Enabled = false;
12138                 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12139                 this.ListManageMenuItem.Enabled = false;
12140                 this.OpenFavOpMenuItem.Enabled = false;
12141                 this.CreateTabRuleOpMenuItem.Enabled = false;
12142                 this.CreateIdRuleOpMenuItem.Enabled = false;
12143                 this.CreateSourceRuleOpMenuItem.Enabled = false;
12144                 this.ReadOpMenuItem.Enabled = false;
12145                 this.UnreadOpMenuItem.Enabled = false;
12146             }
12147             else
12148             {
12149                 this.ReplyOpMenuItem.Enabled = true;
12150                 this.ReplyAllOpMenuItem.Enabled = true;
12151                 this.DmOpMenuItem.Enabled = true;
12152                 this.ShowProfMenuItem.Enabled = true;
12153                 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12154                 this.ListManageMenuItem.Enabled = true;
12155                 this.OpenFavOpMenuItem.Enabled = true;
12156                 this.CreateTabRuleOpMenuItem.Enabled = true;
12157                 this.CreateIdRuleOpMenuItem.Enabled = true;
12158                 this.CreateSourceRuleOpMenuItem.Enabled = true;
12159                 this.ReadOpMenuItem.Enabled = true;
12160                 this.UnreadOpMenuItem.Enabled = true;
12161             }
12162
12163             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12164             {
12165                 this.FavOpMenuItem.Enabled = false;
12166                 this.UnFavOpMenuItem.Enabled = false;
12167                 this.OpenStatusOpMenuItem.Enabled = false;
12168                 this.OpenFavotterOpMenuItem.Enabled = false;
12169                 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12170                 this.RtOpMenuItem.Enabled = false;
12171                 this.RtUnOpMenuItem.Enabled = false;
12172                 this.QtOpMenuItem.Enabled = false;
12173                 this.FavoriteRetweetMenuItem.Enabled = false;
12174                 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12175             }
12176             else
12177             {
12178                 this.FavOpMenuItem.Enabled = true;
12179                 this.UnFavOpMenuItem.Enabled = true;
12180                 this.OpenStatusOpMenuItem.Enabled = true;
12181                 this.OpenFavotterOpMenuItem.Enabled = true;
12182                 this.ShowRelatedStatusesMenuItem2.Enabled = true;  //PublicSearchの時問題出るかも
12183
12184                 if (_curPost.IsMe)
12185                 {
12186                     this.RtOpMenuItem.Enabled = false;  //公式RTは無効に
12187                     this.RtUnOpMenuItem.Enabled = true;
12188                     this.QtOpMenuItem.Enabled = true;
12189                     this.FavoriteRetweetMenuItem.Enabled = false;  //公式RTは無効に
12190                     this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12191                 }
12192                 else
12193                 {
12194                     if (_curPost.IsProtect)
12195                     {
12196                         this.RtOpMenuItem.Enabled = false;
12197                         this.RtUnOpMenuItem.Enabled = false;
12198                         this.QtOpMenuItem.Enabled = false;
12199                         this.FavoriteRetweetMenuItem.Enabled = false;
12200                         this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12201                     }
12202                     else
12203                     {
12204                         this.RtOpMenuItem.Enabled = true;
12205                         this.RtUnOpMenuItem.Enabled = true;
12206                         this.QtOpMenuItem.Enabled = true;
12207                         this.FavoriteRetweetMenuItem.Enabled = true;
12208                         this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12209                     }
12210                 }
12211             }
12212
12213             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12214             {
12215                 this.RefreshPrevOpMenuItem.Enabled = true;
12216             }
12217             else
12218             {
12219                 this.RefreshPrevOpMenuItem.Enabled = false;
12220             }
12221             if (!this.ExistCurrentPost
12222                 || _curPost.InReplyToStatusId == null)
12223             {
12224                 OpenRepSourceOpMenuItem.Enabled = false;
12225             }
12226             else
12227             {
12228                 OpenRepSourceOpMenuItem.Enabled = true;
12229             }
12230             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12231             {
12232                 OpenRterHomeMenuItem.Enabled = false;
12233             }
12234             else
12235             {
12236                 OpenRterHomeMenuItem.Enabled = true;
12237             }
12238
12239             if (this.ExistCurrentPost)
12240             {
12241                 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12242             }
12243         }
12244
12245         private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12246         {
12247             ContextMenuTabProperty_Opening(sender, null);
12248         }
12249
12250         public Twitter TwitterInstance
12251         {
12252             get { return tw; }
12253         }
12254
12255         private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12256         {
12257             if (this._initialLayout)
12258                 return;
12259
12260             int splitterDistance;
12261             switch (this.WindowState)
12262             {
12263                 case FormWindowState.Normal:
12264                     splitterDistance = this.SplitContainer3.SplitterDistance;
12265                     break;
12266                 case FormWindowState.Maximized:
12267                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
12268                     var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
12269                     splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
12270                     splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
12271                     break;
12272                 default:
12273                     return;
12274             }
12275
12276             this._mySpDis3 = splitterDistance;
12277             this.ModifySettingLocal = true;
12278         }
12279
12280         private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12281         {
12282             if (_statuses.RemovedTab.Count == 0)
12283             {
12284                 UndoRemoveTabMenuItem.Enabled = false;
12285             }
12286             else
12287             {
12288                 UndoRemoveTabMenuItem.Enabled = true;
12289             }
12290             if (ListTab.SelectedTab != null)
12291             {
12292                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12293                     PublicSearchQueryMenuItem.Enabled = true;
12294                 else
12295                     PublicSearchQueryMenuItem.Enabled = false;
12296             }
12297             else
12298             {
12299                 PublicSearchQueryMenuItem.Enabled = false;
12300             }
12301             if (!this.ExistCurrentPost)
12302             {
12303                 this.CopySTOTMenuItem.Enabled = false;
12304                 this.CopyURLMenuItem.Enabled = false;
12305                 this.CopyUserIdStripMenuItem.Enabled = false;
12306             }
12307             else
12308             {
12309                 this.CopySTOTMenuItem.Enabled = true;
12310                 this.CopyURLMenuItem.Enabled = true;
12311                 this.CopyUserIdStripMenuItem.Enabled = true;
12312                 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12313                 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12314             }
12315         }
12316
12317         private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12318         {
12319             SetNotifyIconText();
12320         }
12321
12322         private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12323         {
12324             var id = _curPost?.ScreenName ?? "";
12325
12326             await this.ShowUserStatus(id);
12327         }
12328
12329         private async Task doShowUserStatus(string id, bool ShowInputDialog)
12330         {
12331             TwitterUser user = null;
12332
12333             if (ShowInputDialog)
12334             {
12335                 using (var inputName = new InputTabName())
12336                 {
12337                     inputName.FormTitle = "Show UserStatus";
12338                     inputName.FormDescription = Properties.Resources.FRMessage1;
12339                     inputName.TabName = id;
12340
12341                     if (inputName.ShowDialog(this) != DialogResult.OK)
12342                         return;
12343                     if (string.IsNullOrWhiteSpace(inputName.TabName))
12344                         return;
12345
12346                     id = inputName.TabName.Trim();
12347                 }
12348             }
12349
12350             using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
12351             {
12352                 var cancellationToken = dialog.EnableCancellation();
12353
12354                 try
12355                 {
12356                     var task = this.twitterApi.UsersShow(id);
12357                     user = await dialog.WaitForAsync(this, task);
12358                 }
12359                 catch (WebApiException ex)
12360                 {
12361                     if (!cancellationToken.IsCancellationRequested)
12362                         MessageBox.Show($"Err:{ex.Message}(UsersShow)");
12363                     return;
12364                 }
12365
12366                 if (cancellationToken.IsCancellationRequested)
12367                     return;
12368             }
12369
12370             await this.doShowUserStatus(user);
12371         }
12372
12373         private async Task doShowUserStatus(TwitterUser user)
12374         {
12375             using (var userDialog = new UserInfoDialog(this, this.twitterApi))
12376             {
12377                 var showUserTask = userDialog.ShowUserAsync(user);
12378                 userDialog.ShowDialog(this);
12379
12380                 this.Activate();
12381                 this.BringToFront();
12382
12383                 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12384                 await showUserTask;
12385             }
12386         }
12387
12388         private Task ShowUserStatus(string id, bool ShowInputDialog)
12389         {
12390             return this.doShowUserStatus(id, ShowInputDialog);
12391         }
12392
12393         private Task ShowUserStatus(string id)
12394         {
12395             return this.doShowUserStatus(id, true);
12396         }
12397
12398         private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12399         {
12400             if (NameLabel.Tag != null)
12401             {
12402                 string id = (string)NameLabel.Tag;
12403                 if (id != tw.Username)
12404                 {
12405                     await this.FollowCommand(id);
12406                 }
12407             }
12408         }
12409
12410         private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12411         {
12412             if (NameLabel.Tag != null)
12413             {
12414                 string id = (string)NameLabel.Tag;
12415                 if (id != tw.Username)
12416                 {
12417                     await this.RemoveCommand(id, false);
12418                 }
12419             }
12420         }
12421
12422         private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12423         {
12424             if (NameLabel.Tag != null)
12425             {
12426                 string id = (string)NameLabel.Tag;
12427                 if (id != tw.Username)
12428                 {
12429                     await this.ShowFriendship(id);
12430                 }
12431             }
12432         }
12433
12434         private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12435         {
12436             if (NameLabel.Tag != null)
12437             {
12438                 string id = (string)NameLabel.Tag;
12439                 await this.ShowUserStatus(id, false);
12440             }
12441         }
12442
12443         private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12444         {
12445             if (NameLabel.Tag != null)
12446             {
12447                 string id = (string)NameLabel.Tag;
12448                 AddNewTabForUserTimeline(id);
12449             }
12450         }
12451
12452         private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12453         {
12454             if (NameLabel.Tag != null)
12455             {
12456                 string id = (string)NameLabel.Tag;
12457                 AddNewTabForSearch("@" + id);
12458             }
12459         }
12460
12461         private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12462         {
12463             if (_curPost != null)
12464             {
12465                 await this.ShowUserStatus(_curPost.ScreenName, false);
12466             }
12467         }
12468
12469         private async void RtCountMenuItem_Click(object sender, EventArgs e)
12470         {
12471             if (!this.ExistCurrentPost)
12472                 return;
12473
12474             var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12475             TwitterStatus status;
12476
12477             using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12478             {
12479                 var cancellationToken = dialog.EnableCancellation();
12480
12481                 try
12482                 {
12483                     var task = this.twitterApi.StatusesShow(statusId);
12484                     status = await dialog.WaitForAsync(this, task);
12485                 }
12486                 catch (WebApiException ex)
12487                 {
12488                     if (!cancellationToken.IsCancellationRequested)
12489                         MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
12490                     return;
12491                 }
12492
12493                 if (cancellationToken.IsCancellationRequested)
12494                     return;
12495             }
12496
12497             MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
12498         }
12499
12500         private HookGlobalHotkey _hookGlobalHotkey;
12501         public TweenMain()
12502         {
12503             _hookGlobalHotkey = new HookGlobalHotkey(this);
12504
12505             // この呼び出しは、Windows フォーム デザイナで必要です。
12506             InitializeComponent();
12507
12508             // InitializeComponent() 呼び出しの後で初期化を追加します。
12509
12510             if (!this.DesignMode)
12511             {
12512                 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12513                 this.StatusText.Dock = DockStyle.Fill;
12514             }
12515
12516             this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12517             this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12518             this.gh.NotifyClicked += GrowlHelper_Callback;
12519
12520             // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12521             this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12522
12523             this.ImageSelector.Visible = false;
12524             this.ImageSelector.Enabled = false;
12525             this.ImageSelector.FilePickDialog = OpenFileDialog1;
12526
12527             this.ReplaceAppName();
12528             this.InitializeShortcuts();
12529         }
12530
12531         private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12532         {
12533             if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12534             {
12535                 //アイコン化
12536                 this.Visible = false;
12537             }
12538             else if (Form.ActiveForm == null)
12539             {
12540                 this.Visible = true;
12541                 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12542                 this.Activate();
12543                 this.BringToFront();
12544                 this.StatusText.Focus();
12545             }
12546         }
12547
12548         private void UserPicture_MouseEnter(object sender, EventArgs e)
12549         {
12550             this.UserPicture.Cursor = Cursors.Hand;
12551         }
12552
12553         private void UserPicture_MouseLeave(object sender, EventArgs e)
12554         {
12555             this.UserPicture.Cursor = Cursors.Default;
12556         }
12557
12558         private async void UserPicture_DoubleClick(object sender, EventArgs e)
12559         {
12560             if (NameLabel.Tag != null)
12561             {
12562                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12563             }
12564         }
12565
12566         private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12567         {
12568             this.MultiLineMenuItem.PerformClick();
12569         }
12570
12571         public PostClass CurPost
12572         {
12573             get { return _curPost; }
12574         }
12575
12576 #region "画像投稿"
12577         private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12578         {
12579             if (ImageSelector.Visible)
12580                 ImageSelector.EndSelection();
12581             else
12582                 ImageSelector.BeginSelection();
12583         }
12584
12585         private void SelectMedia_DragEnter(DragEventArgs e)
12586         {
12587             if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12588             {
12589                 e.Effect = DragDropEffects.Copy;
12590                 return;
12591             }
12592             e.Effect = DragDropEffects.None;
12593         }
12594
12595         private void SelectMedia_DragDrop(DragEventArgs e)
12596         {
12597             this.Activate();
12598             this.BringToFront();
12599             ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12600             StatusText.Focus();
12601         }
12602
12603         private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12604         {
12605             TimelinePanel.Visible = false;
12606             TimelinePanel.Enabled = false;
12607         }
12608
12609         private void ImageSelector_EndSelecting(object sender, EventArgs e)
12610         {
12611             TimelinePanel.Visible = true;
12612             TimelinePanel.Enabled = true;
12613             ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12614         }
12615
12616         private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12617         {
12618             this.AllowDrop = false;
12619         }
12620
12621         private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12622         {
12623             this.AllowDrop = true;
12624         }
12625
12626         private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12627         {
12628             if (ImageSelector.Visible)
12629             {
12630                 ModifySettingCommon = true;
12631                 SaveConfigsAll(true);
12632
12633                 if (ImageSelector.ServiceName.Equals("Twitter"))
12634                     this.StatusText_TextChanged(null, null);
12635             }
12636         }
12637
12638         private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12639         {
12640             this.StatusText_TextChanged(null, null);
12641         }
12642
12643         /// <summary>
12644         /// StatusTextでCtrl+Vが押下された時の処理
12645         /// </summary>
12646         private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12647         {
12648             if (Clipboard.ContainsText())
12649             {
12650                 // clipboardにテキストがある場合は貼り付け処理
12651                 this.StatusText.Paste(Clipboard.GetText());
12652             }
12653             else if (Clipboard.ContainsImage())
12654             {
12655                 // 画像があるので投稿処理を行う
12656                 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12657                                    Properties.Resources.PostPictureWarn4,
12658                                    MessageBoxButtons.OKCancel,
12659                                    MessageBoxIcon.Question,
12660                                    MessageBoxDefaultButton.Button2)
12661                                == DialogResult.OK)
12662                 {
12663                     // clipboardから画像を取得
12664                     using (var image = Clipboard.GetImage())
12665                     {
12666                         this.ImageSelector.BeginSelection(image);
12667                     }
12668                 }
12669             }
12670         }
12671 #endregion
12672
12673         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12674         {
12675             using (ListManage form = new ListManage(tw))
12676             {
12677                 form.ShowDialog(this);
12678             }
12679         }
12680
12681         public bool ModifySettingCommon { get; set; }
12682         public bool ModifySettingLocal { get; set; }
12683         public bool ModifySettingAtId { get; set; }
12684
12685         private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12686         {
12687             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12688             if (sourceUri != null && e.Button == MouseButtons.Left)
12689             {
12690                 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12691             }
12692         }
12693
12694         private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12695         {
12696             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12697             if (sourceUri != null)
12698             {
12699                 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12700             }
12701         }
12702
12703         private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12704         {
12705             SetStatusLabelUrl();
12706         }
12707
12708         private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12709         {
12710             if (this.ExistCurrentPost && !_curPost.IsDm)
12711                 RtCountMenuItem.Enabled = true;
12712             else
12713                 RtCountMenuItem.Enabled = false;
12714
12715             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12716             //    TinyUrlConvertToolStripMenuItem.Enabled = false;
12717             //else
12718             //    TinyUrlConvertToolStripMenuItem.Enabled = true;
12719         }
12720
12721         private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12722         {
12723             CopyUserId();
12724         }
12725
12726         private void CopyUserId()
12727         {
12728             if (_curPost == null) return;
12729             string clstr = _curPost.ScreenName;
12730             try
12731             {
12732                 Clipboard.SetDataObject(clstr, false, 5, 100);
12733             }
12734             catch (Exception ex)
12735             {
12736                 MessageBox.Show(ex.Message);
12737             }
12738         }
12739
12740         private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12741         {
12742             if (this.ExistCurrentPost && !_curPost.IsDm)
12743             {
12744                 try
12745                 {
12746                     await this.OpenRelatedTab(this._curPost);
12747                 }
12748                 catch (TabException ex)
12749                 {
12750                     MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12751                 }
12752             }
12753         }
12754
12755         /// <summary>
12756         /// 指定されたツイートに対する関連発言タブを開きます
12757         /// </summary>
12758         /// <param name="statusId">表示するツイートのID</param>
12759         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12760         private async Task OpenRelatedTab(long statusId)
12761         {
12762             var post = this._statuses[statusId];
12763             if (post == null)
12764             {
12765                 try
12766                 {
12767                     post = await this.tw.GetStatusApi(false, statusId);
12768                 }
12769                 catch (WebApiException ex)
12770                 {
12771                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
12772                     return;
12773                 }
12774             }
12775
12776             await this.OpenRelatedTab(post);
12777         }
12778
12779         /// <summary>
12780         /// 指定されたツイートに対する関連発言タブを開きます
12781         /// </summary>
12782         /// <param name="post">表示する対象となるツイート</param>
12783         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12784         private async Task OpenRelatedTab(PostClass post)
12785         {
12786             var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12787             string tabName;
12788
12789             if (tabRelated == null)
12790             {
12791                 tabName = this._statuses.MakeTabName("Related Tweets");
12792
12793                 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12794                 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12795
12796                 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12797                 tabRelated.UnreadManage = false;
12798                 tabRelated.Notify = false;
12799             }
12800             else
12801             {
12802                 tabName = tabRelated.TabName;
12803             }
12804
12805             tabRelated.RelationTargetPost = post;
12806             this.ClearTab(tabName, false);
12807
12808             for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12809             {
12810                 var tabPage = this.ListTab.TabPages[i];
12811                 if (tabName == tabPage.Text)
12812                 {
12813                     this.ListTab.SelectedIndex = i;
12814                     break;
12815                 }
12816             }
12817
12818             await this.GetRelatedTweetsAsync(tabRelated);
12819         }
12820
12821         private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12822         {
12823             StringBuilder buf = new StringBuilder();
12824             //buf.AppendFormat("キャッシュメモリ容量         : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12825             //buf.AppendFormat("物理メモリ使用割合           : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12826             buf.AppendFormat("キャッシュエントリ保持数     : {0}" + Environment.NewLine, IconCache.CacheCount);
12827             buf.AppendFormat("キャッシュエントリ破棄数     : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12828             MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12829         }
12830
12831         private void tw_UserIdChanged()
12832         {
12833             this.ModifySettingCommon = true;
12834         }
12835
12836 #region "Userstream"
12837         private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12838         {
12839             try
12840             {
12841                 if (InvokeRequired && !IsDisposed)
12842                 {
12843                     Invoke((Action) (async () =>
12844                            {
12845                                _statuses.RemovePostReserve(e.StatusId);
12846                                if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12847                                {
12848                                    this.PurgeListViewItemCache();
12849                                    ((DetailsListView)_curTab.Tag).Update();
12850                                    if (_curPost != null && _curPost.StatusId == e.StatusId)
12851                                        await this.DispSelectedPost(true);
12852                                }
12853                            }));
12854                     return;
12855                 }
12856             }
12857             catch (ObjectDisposedException)
12858             {
12859                 return;
12860             }
12861             catch (InvalidOperationException)
12862             {
12863                 return;
12864             }
12865         }
12866
12867         private int userStreamsRefreshing = 0;
12868
12869         private async void tw_NewPostFromStream(object sender, EventArgs e)
12870         {
12871             if (this._cfgCommon.ReadOldPosts)
12872             {
12873                 _statuses.SetReadHomeTab(); //新着時未読クリア
12874             }
12875
12876             int rsltAddCount = _statuses.DistributePosts();
12877
12878             this.UpdateTimelineSpeed(rsltAddCount);
12879
12880             if (this._cfgCommon.UserstreamPeriod > 0) return;
12881
12882             // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
12883             if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
12884             {
12885                 try
12886                 {
12887                     await this.InvokeAsync(() => this.RefreshTimeline())
12888                         .ConfigureAwait(false);
12889                 }
12890                 finally
12891                 {
12892                     Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
12893                 }
12894             }
12895         }
12896
12897         private void tw_UserStreamStarted(object sender, EventArgs e)
12898         {
12899             try
12900             {
12901                 if (InvokeRequired && !IsDisposed)
12902                 {
12903                     Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12904                     return;
12905                 }
12906             }
12907             catch (ObjectDisposedException)
12908             {
12909                 return;
12910             }
12911             catch (InvalidOperationException)
12912             {
12913                 return;
12914             }
12915
12916             this.RefreshUserStreamsMenu();
12917             this.MenuItemUserStream.Enabled = true;
12918
12919             StatusLabel.Text = "UserStream Started.";
12920         }
12921
12922         private void tw_UserStreamStopped(object sender, EventArgs e)
12923         {
12924             try
12925             {
12926                 if (InvokeRequired && !IsDisposed)
12927                 {
12928                     Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12929                     return;
12930                 }
12931             }
12932             catch (ObjectDisposedException)
12933             {
12934                 return;
12935             }
12936             catch (InvalidOperationException)
12937             {
12938                 return;
12939             }
12940
12941             this.RefreshUserStreamsMenu();
12942             this.MenuItemUserStream.Enabled = true;
12943
12944             StatusLabel.Text = "UserStream Stopped.";
12945         }
12946
12947         private void RefreshUserStreamsMenu()
12948         {
12949             if (this.tw.UserStreamActive)
12950             {
12951                 this.MenuItemUserStream.Text = "&UserStream ▶";
12952                 this.StopToolStripMenuItem.Text = "&Stop";
12953             }
12954             else
12955             {
12956                 this.MenuItemUserStream.Text = "&UserStream ■";
12957                 this.StopToolStripMenuItem.Text = "&Start";
12958             }
12959         }
12960
12961         private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12962         {
12963             try
12964             {
12965                 if (InvokeRequired && !IsDisposed)
12966                 {
12967                     Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12968                     return;
12969                 }
12970             }
12971             catch (ObjectDisposedException)
12972             {
12973                 return;
12974             }
12975             catch (InvalidOperationException)
12976             {
12977                 return;
12978             }
12979             var ev = e.EventData;
12980             StatusLabel.Text = "Event: " + ev.Event;
12981             //if (ev.Event == "favorite")
12982             //{
12983             //    NotifyFavorite(ev);
12984             //}
12985             NotifyEvent(ev);
12986             if (ev.Event == "favorite" || ev.Event == "unfavorite")
12987             {
12988                 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12989                 {
12990                     this.PurgeListViewItemCache();
12991                     ((DetailsListView)_curTab.Tag).Update();
12992                 }
12993                 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
12994                 {
12995                     RemovePostFromFavTab(new long[] {ev.Id});
12996                 }
12997             }
12998         }
12999
13000         private void NotifyEvent(Twitter.FormattedEvent ev)
13001         {
13002             //新着通知 
13003             if (BalloonRequired(ev))
13004             {
13005                 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13006                 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
13007                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
13008                 StringBuilder title = new StringBuilder();
13009                 if (this._cfgCommon.DispUsername)
13010                 {
13011                     title.Append(tw.Username);
13012                     title.Append(" - ");
13013                 }
13014                 else
13015                 {
13016                     //title.Clear();
13017                 }
13018                 title.Append(Application.ProductName);
13019                 title.Append(" [");
13020                 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
13021                 title.Append("] by ");
13022                 if (!string.IsNullOrEmpty(ev.Username))
13023                 {
13024                     title.Append(ev.Username.ToString());
13025                 }
13026                 else
13027                 {
13028                     //title.Append("");
13029                 }
13030                 string text;
13031                 if (!string.IsNullOrEmpty(ev.Target))
13032                 {
13033                     //NotifyIcon1.BalloonTipText = ev.Target;
13034                     text = ev.Target;
13035                 }
13036                 else
13037                 {
13038                     //NotifyIcon1.BalloonTipText = " ";
13039                     text = " ";
13040                 }
13041                 //NotifyIcon1.ShowBalloonTip(500);
13042                 if (this._cfgCommon.IsUseNotifyGrowl)
13043                 {
13044                     gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13045                               ev.Id.ToString(), title.ToString(), text);
13046                 }
13047                 else
13048                 {
13049                     NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13050                     NotifyIcon1.BalloonTipTitle = title.ToString();
13051                     NotifyIcon1.BalloonTipText = text;
13052                     NotifyIcon1.ShowBalloonTip(500);
13053                 }
13054             }
13055
13056             //サウンド再生
13057             string snd = this._cfgCommon.EventSoundFile;
13058             if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13059             {
13060                 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13061                 {
13062                     try
13063                     {
13064                         string dir = Application.StartupPath;
13065                         if (Directory.Exists(Path.Combine(dir, "Sounds")))
13066                         {
13067                             dir = Path.Combine(dir, "Sounds");
13068                         }
13069                         using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13070                         {
13071                             player.Play();
13072                         }
13073                     }
13074                     catch (Exception)
13075                     {
13076                     }
13077                 }
13078             }
13079         }
13080
13081         private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13082         {
13083             MenuItemUserStream.Enabled = false;
13084             if (StopRefreshAllMenuItem.Checked)
13085             {
13086                 StopRefreshAllMenuItem.Checked = false;
13087                 return;
13088             }
13089             if (this.tw.UserStreamActive)
13090             {
13091                 tw.StopUserStream();
13092             }
13093             else
13094             {
13095                 tw.StartUserStream();
13096             }
13097         }
13098
13099         private static string inputTrack = "";
13100
13101         private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13102         {
13103             if (TrackToolStripMenuItem.Checked)
13104             {
13105                 using (InputTabName inputForm = new InputTabName())
13106                 {
13107                     inputForm.TabName = inputTrack;
13108                     inputForm.FormTitle = "Input track word";
13109                     inputForm.FormDescription = "Track word";
13110                     if (inputForm.ShowDialog() != DialogResult.OK)
13111                     {
13112                         TrackToolStripMenuItem.Checked = false;
13113                         return;
13114                     }
13115                     inputTrack = inputForm.TabName.Trim();
13116                 }
13117                 if (!inputTrack.Equals(tw.TrackWord))
13118                 {
13119                     tw.TrackWord = inputTrack;
13120                     this.ModifySettingCommon = true;
13121                     TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13122                     tw.ReconnectUserStream();
13123                 }
13124             }
13125             else
13126             {
13127                 tw.TrackWord = "";
13128                 tw.ReconnectUserStream();
13129             }
13130             this.ModifySettingCommon = true;
13131         }
13132
13133         private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13134         {
13135             tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13136             this.ModifySettingCommon = true;
13137             tw.ReconnectUserStream();
13138         }
13139
13140         private void EventViewerMenuItem_Click(object sender, EventArgs e)
13141         {
13142             if (evtDialog == null || evtDialog.IsDisposed)
13143             {
13144                 evtDialog = null;
13145                 evtDialog = new EventViewerDialog();
13146                 evtDialog.Owner = this;
13147                 //親の中央に表示
13148                 Point pos = evtDialog.Location;
13149                 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13150                 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13151                 evtDialog.Location = pos;
13152             }
13153             evtDialog.EventSource = tw.StoredEvent;
13154             if (!evtDialog.Visible)
13155             {
13156                 evtDialog.Show(this);
13157             }
13158             else
13159             {
13160                 evtDialog.Activate();
13161             }
13162             this.TopMost = this._cfgCommon.AlwaysTop;
13163         }
13164 #endregion
13165
13166         private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13167         {
13168             MyCommon._endingFlag = true;
13169             try
13170             {
13171                 this.Close();
13172                 Application.Restart();
13173             }
13174             catch (Exception)
13175             {
13176                 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13177             }
13178         }
13179
13180         private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13181         {
13182             if (!string.IsNullOrEmpty(tw.Username))
13183                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13184         }
13185
13186         private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13187         {
13188             await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
13189         }
13190
13191         private async Task doTranslation(string str)
13192         {
13193             if (string.IsNullOrEmpty(str))
13194                 return;
13195
13196             var bing = new Bing();
13197             try
13198             {
13199                 var translatedText = await bing.TranslateAsync(str,
13200                     langFrom: null,
13201                     langTo: this._cfgCommon.TranslateLanguage);
13202
13203                 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13204             }
13205             catch (HttpRequestException e)
13206             {
13207                 this.StatusLabel.Text = "Err:" + e.Message;
13208             }
13209             catch (OperationCanceledException)
13210             {
13211                 this.StatusLabel.Text = "Err:Timeout";
13212             }
13213         }
13214
13215         private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13216         {
13217             if (!this.ExistCurrentPost)
13218                 return;
13219
13220             await this.doTranslation(this._curPost.TextFromApi);
13221         }
13222
13223         private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13224         {
13225             var text = this.PostBrowser.GetSelectedText();
13226             await this.doTranslation(text);
13227         }
13228
13229         private bool ExistCurrentPost
13230         {
13231             get
13232             {
13233                 if (_curPost == null) return false;
13234                 if (_curPost.IsDeleted) return false;
13235                 return true;
13236             }
13237         }
13238
13239         private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13240         {
13241             ShowUserTimeline();
13242         }
13243
13244         private string GetUserIdFromCurPostOrInput(string caption)
13245         {
13246             var id = _curPost?.ScreenName ?? "";
13247
13248             using (InputTabName inputName = new InputTabName())
13249             {
13250                 inputName.FormTitle = caption;
13251                 inputName.FormDescription = Properties.Resources.FRMessage1;
13252                 inputName.TabName = id;
13253                 if (inputName.ShowDialog() == DialogResult.OK &&
13254                     !string.IsNullOrEmpty(inputName.TabName.Trim()))
13255                 {
13256                     id = inputName.TabName.Trim();
13257                 }
13258                 else
13259                 {
13260                     id = "";
13261                 }
13262             }
13263             return id;
13264         }
13265
13266         private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13267         {
13268             string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13269             if (!string.IsNullOrEmpty(id))
13270             {
13271                 AddNewTabForUserTimeline(id);
13272             }
13273         }
13274
13275         private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13276         {
13277             string id = GetUserIdFromCurPostOrInput("Show Favstar");
13278             if (!string.IsNullOrEmpty(id))
13279             {
13280                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13281             }
13282         }
13283
13284         private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13285         {
13286             if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13287         }
13288
13289         private void TimelineRefreshEnableChange(bool isEnable)
13290         {
13291             if (isEnable)
13292             {
13293                 tw.StartUserStream();
13294             }
13295             else
13296             {
13297                 tw.StopUserStream();
13298             }
13299             TimerTimeline.Enabled = isEnable;
13300         }
13301
13302         private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13303         {
13304             TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13305         }
13306
13307         private async Task OpenUserAppointUrl()
13308         {
13309             if (this._cfgCommon.UserAppointUrl != null)
13310             {
13311                 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13312                 {
13313                     if (_curPost != null)
13314                     {
13315                         string xUrl = this._cfgCommon.UserAppointUrl;
13316                         xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13317
13318                         var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
13319                         xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
13320
13321                         await this.OpenUriInBrowserAsync(xUrl);
13322                     }
13323                 }
13324                 else
13325                 {
13326                     await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
13327                 }
13328             }
13329         }
13330
13331         private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13332         {
13333             await this.OpenUserAppointUrl();
13334         }
13335
13336         private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13337         {
13338             string selText = SourceLinkLabel.Text;
13339             try
13340             {
13341                 Clipboard.SetDataObject(selText, false, 5, 100);
13342             }
13343             catch (Exception ex)
13344             {
13345                 MessageBox.Show(ex.Message);
13346             }
13347         }
13348
13349         private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13350         {
13351             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
13352             try
13353             {
13354                 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
13355             }
13356             catch (Exception ex)
13357             {
13358                 MessageBox.Show(ex.Message);
13359             }
13360         }
13361
13362         private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13363         {
13364             if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13365             {
13366                 SourceCopyMenuItem.Enabled = false;
13367                 SourceUrlCopyMenuItem.Enabled = false;
13368             }
13369             else
13370             {
13371                 SourceCopyMenuItem.Enabled = true;
13372                 SourceUrlCopyMenuItem.Enabled = true;
13373             }
13374         }
13375
13376         private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13377         {
13378             if (Form.ActiveForm == null)
13379             {
13380                 this.BeginInvoke((Action) (() =>
13381                 {
13382                     this.Visible = true;
13383                     if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13384                     this.Activate();
13385                     this.BringToFront();
13386                     if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13387                     {
13388                         if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13389                     }
13390                     else
13391                     {
13392                         if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13393                     }
13394                 }));
13395             }
13396         }
13397
13398         private void ReplaceAppName()
13399         {
13400             MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13401             AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13402         }
13403
13404         private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13405         {
13406             this.SplitContainer3.Panel2Collapsed = false;
13407         }
13408
13409         private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13410         {
13411             await this.OpenThumbnailPicture(e.Thumbnail);
13412         }
13413
13414         private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13415         {
13416             await this.OpenUriInBrowserAsync(e.ImageUrl);
13417         }
13418
13419         private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13420         {
13421             var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
13422
13423             await this.OpenUriInBrowserAsync(url);
13424         }
13425
13426         private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13427         {
13428             await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13429         }
13430
13431         private void PostButton_KeyDown(object sender, KeyEventArgs e)
13432         {
13433             if (e.KeyCode == Keys.Space)
13434             {
13435                 this.JumpUnreadMenuItem_Click(null, null);
13436
13437                 e.SuppressKeyPress = true;
13438             }
13439         }
13440
13441         private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13442         {
13443             this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13444             this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13445             this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13446             this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13447             this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13448
13449             this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13450         }
13451
13452         private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13453         {
13454             ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13455         }
13456
13457         private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13458         {
13459             ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13460         }
13461
13462         private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13463         {
13464             ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13465         }
13466
13467         private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13468         {
13469             ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13470         }
13471
13472         private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13473         {
13474             ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13475         }
13476
13477         private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13478         {
13479             if (this._cfgCommon.IconSize == iconSize) return;
13480
13481             var oldIconCol = _iconCol;
13482
13483             this._cfgCommon.IconSize = iconSize;
13484             ApplyListViewIconSize(iconSize);
13485
13486             if (_iconCol != oldIconCol)
13487             {
13488                 foreach (TabPage tp in ListTab.TabPages)
13489                 {
13490                     ResetColumns((DetailsListView)tp.Tag);
13491                 }
13492             }
13493
13494             _curList?.Refresh();
13495
13496             ModifySettingCommon = true;
13497         }
13498
13499         private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13500         {
13501             var state = this.LockListSortOrderToolStripMenuItem.Checked;
13502             if (this._cfgCommon.SortOrderLock == state) return;
13503
13504             this._cfgCommon.SortOrderLock = state;
13505
13506             ModifySettingCommon = true;
13507         }
13508     }
13509 }