OSDN Git Service

TabClassをタブの種類別のクラスに分離
[opentween/open-tween.git] / OpenTween / Tween.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 //           (c) 2008-2011 Moz (@syo68k)
4 //           (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 //           (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 //           (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 //           (c) 2011      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
9 // 
10 // This file is part of OpenTween.
11 // 
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
15 // any later version.
16 // 
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
20 // for more details. 
21 // 
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
26
27 //コンパイル後コマンド
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
30
31 using System;
32 using System.Collections.Concurrent;
33 using System.Collections.Generic;
34 using System.ComponentModel;
35 using System.Diagnostics;
36 using System.Drawing;
37 using System.Globalization;
38 using System.IO;
39 using System.Linq;
40 using System.Media;
41 using System.Net;
42 using System.Net.Http;
43 using System.Reflection;
44 using System.Text;
45 using System.Text.RegularExpressions;
46 using System.Threading;
47 using System.Threading.Tasks;
48 using System.Windows.Forms;
49 using OpenTween.Api;
50 using OpenTween.Api.DataModel;
51 using OpenTween.Connection;
52 using OpenTween.Models;
53 using OpenTween.OpenTweenCustomControl;
54 using OpenTween.Thumbnail;
55
56 namespace OpenTween
57 {
58     public partial class TweenMain : OTBaseForm
59     {
60         //各種設定
61         private Size _mySize;           //画面サイズ
62         private Point _myLoc;           //画面位置
63         private int _mySpDis;           //区切り位置
64         private int _mySpDis2;          //発言欄区切り位置
65         private int _mySpDis3;          //プレビュー区切り位置
66         private int _iconSz;            //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
67         private bool _iconCol;          //1列表示の時true(48サイズのとき)
68
69         //雑多なフラグ類
70         private bool _initial;         //true:起動時処理中
71         private bool _initialLayout = true;
72         private bool _ignoreConfigSave;         //true:起動時処理中
73         private bool _tabDrag;           //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
74         private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
75         private Point _tabMouseDownPoint;
76         private string _rclickTabName;      //右クリックしたタブの名前(Tabコントロール機能不足対応)
77         private readonly object _syncObject = new object();    //ロック用
78
79         private const string detailHtmlFormatHeaderMono = 
80             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
81             + "<style type=\"text/css\"><!-- "
82             + "body, p, pre {margin: 0;} "
83             + "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%);} "
84             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
85             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
86             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
87             + ".quote-tweet.reply {border-color: #f33;} "
88             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
89             + "--></style>"
90             + "</head><body><pre>";
91         private const string detailHtmlFormatFooterMono = "</pre></body></html>";
92         private const string detailHtmlFormatHeaderColor = 
93             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
94             + "<style type=\"text/css\"><!-- "
95             + "body, p, pre {margin: 0;} "
96             + "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%);} "
97             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
98             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
99             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
100             + ".quote-tweet.reply {border-color: rgb(%BG_REPLY_COLOR%);} "
101             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
102             + "--></style>"
103             + "</head><body><p>";
104         private const string detailHtmlFormatFooterColor = "</p></body></html>";
105         private string detailHtmlFormatHeader;
106         private string detailHtmlFormatFooter;
107
108         private bool _myStatusError = false;
109         private bool _myStatusOnline = false;
110         private bool soundfileListup = false;
111         private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
112
113         //設定ファイル関連
114         //private SettingToConfig _cfg; //旧
115         private SettingLocal _cfgLocal;
116         private SettingCommon _cfgCommon;
117
118         //twitter解析部
119         private TwitterApi twitterApi = new TwitterApi();
120         private Twitter tw;
121
122         //Growl呼び出し部
123         private GrowlHelper gh = new GrowlHelper(Application.ProductName);
124
125         //サブ画面インスタンス
126         private SearchWordDialog SearchDialog = new SearchWordDialog();     //検索画面インスタンス
127         private OpenURL UrlDialog = new OpenURL();
128         public AtIdSupplement AtIdSupl;     //@id補助
129         public AtIdSupplement HashSupl;    //Hashtag補助
130         public HashtagManage HashMgr;
131         private EventViewerDialog evtDialog;
132
133         //表示フォント、色、アイコン
134         private Font _fntUnread;            //未読用フォント
135         private Color _clUnread;            //未読用文字色
136         private Font _fntReaded;            //既読用フォント
137         private Color _clReaded;            //既読用文字色
138         private Color _clFav;               //Fav用文字色
139         private Color _clOWL;               //片思い用文字色
140         private Color _clRetweet;               //Retweet用文字色
141         private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText);         //選択中の行用文字色
142         private Font _fntDetail;            //発言詳細部用フォント
143         private Color _clDetail;              //発言詳細部用色
144         private Color _clDetailLink;          //発言詳細部用リンク文字色
145         private Color _clDetailBackcolor;     //発言詳細部用背景色
146         private Color _clSelf;              //自分の発言用背景色
147         private Color _clAtSelf;            //自分宛返信用背景色
148         private Color _clTarget;            //選択発言者の他の発言用背景色
149         private Color _clAtTarget;          //選択発言中の返信先用背景色
150         private Color _clAtFromTarget;      //選択発言者への返信発言用背景色
151         private Color _clAtTo;              //選択発言の唯一@先
152         private Color _clListBackcolor;       //リスト部通常発言背景色
153         private Color _clInputBackcolor;      //入力欄背景色
154         private Color _clInputFont;           //入力欄文字色
155         private Font _fntInputFont;           //入力欄フォント
156         private ImageCache IconCache;        //アイコン画像リスト
157         private Icon NIconAt;               //At.ico             タスクトレイアイコン:通常時
158         private Icon NIconAtRed;            //AtRed.ico          タスクトレイアイコン:通信エラー時
159         private Icon NIconAtSmoke;          //AtSmoke.ico        タスクトレイアイコン:オフライン時
160         private Icon[] NIconRefresh = new Icon[4];       //Refresh.ico        タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
161         private Icon TabIcon;               //Tab.ico            未読のあるタブ用アイコン
162         private Icon MainIcon;              //Main.ico           画面左上のアイコン
163         private Icon ReplyIcon;               //5g
164         private Icon ReplyIconBlink;          //6g
165
166         private ImageList _listViewImageList = new ImageList();    //ListViewItemの高さ変更用
167
168         private PostClass _anchorPost;
169         private bool _anchorFlag;        //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
170
171         private List<PostingStatus> _history = new List<PostingStatus>();   //発言履歴
172         private int _hisIdx;                  //発言履歴カレントインデックス
173
174         //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
175         private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
176
177         //時速表示用
178         private List<DateTime> _postTimestamps = new List<DateTime>();
179         private List<DateTime> _favTimestamps = new List<DateTime>();
180         private ConcurrentDictionary<DateTime, int> _tlTimestamps = new ConcurrentDictionary<DateTime, int>();
181         private int _tlCount;
182
183         // 以下DrawItem関連
184         private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
185         private SolidBrush _brsBackColorMine;
186         private SolidBrush _brsBackColorAt;
187         private SolidBrush _brsBackColorYou;
188         private SolidBrush _brsBackColorAtYou;
189         private SolidBrush _brsBackColorAtFromTarget;
190         private SolidBrush _brsBackColorAtTo;
191         private SolidBrush _brsBackColorNone;
192         private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
193         private StringFormat sfTab = new StringFormat();
194
195         //////////////////////////////////////////////////////////////////////////////////////////////////////////
196         private TabInformations _statuses;
197
198         /// <summary>
199         /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
200         /// </summary>
201         /// <remarks>
202         /// キャッシュクリアのために null が代入されることがあるため、
203         /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
204         /// 一旦ローカル変数に代入してから参照すること。
205         /// </remarks>
206         private ListViewItemCache _listItemCache = null;
207
208         internal class ListViewItemCache
209         {
210             /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
211             public ListView TargetList { get; set; }
212
213             /// <summary>キャッシュする範囲の開始インデックス</summary>
214             public int StartIndex { get; set; }
215
216             /// <summary>キャッシュする範囲の終了インデックス</summary>
217             public int EndIndex { get; set; }
218
219             /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
220             public ListViewItem[] ListItem { get; set; }
221
222             /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
223             public PostClass[] Post { get; set; }
224
225             /// <summary>キャッシュされたアイテムの件数</summary>
226             public int Count
227                 => this.EndIndex - this.StartIndex + 1;
228
229             /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
230             /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
231             public bool Contains(int index)
232                 => index >= this.StartIndex && index <= this.EndIndex;
233
234             /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
235             /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
236             public bool IsSupersetOf(int rangeStart, int rangeEnd)
237                 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
238
239             /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
240             /// <returns>取得に成功すれば true、それ以外は false</returns>
241             public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
242             {
243                 if (this.Contains(index))
244                 {
245                     item = this.ListItem[index - this.StartIndex];
246                     post = this.Post[index - this.StartIndex];
247                     return true;
248                 }
249                 else
250                 {
251                     item = null;
252                     post = null;
253                     return false;
254                 }
255             }
256         }
257
258         private TabPage _curTab;
259         private int _curItemIndex;
260         private DetailsListView _curList;
261         private PostClass _curPost;
262         private bool _isColumnChanged = false;
263
264         private const int MAX_WORKER_THREADS = 20;
265         private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
266         private CancellationTokenSource workerCts = new CancellationTokenSource();
267
268         private int UnreadCounter = -1;
269         private int UnreadAtCounter = -1;
270
271         private string[] ColumnOrgText = new string[9];
272         private string[] ColumnText = new string[9];
273
274         private bool _DoFavRetweetFlags = false;
275         private bool osResumed = false;
276
277         //////////////////////////////////////////////////////////////////////////////////////////////////////////
278         private string _postBrowserStatusText = "";
279
280         private bool _colorize = false;
281
282         private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
283
284         private ImageListViewItem displayItem;
285
286         private string recommendedStatusFooter;
287
288         //URL短縮のUndo用
289         private struct urlUndo
290         {
291             public string Before;
292             public string After;
293         }
294
295         private List<urlUndo> urlUndoBuffer = null;
296
297         private struct ReplyChain
298         {
299             public long OriginalId;
300             public long InReplyToId;
301             public TabPage OriginalTab;
302
303             public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
304             {
305                 this.OriginalId = originalId;
306                 this.InReplyToId = inReplyToId;
307                 this.OriginalTab = originalTab;
308             }
309         }
310
311         private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
312         private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
313
314         //検索処理タイプ
315         private enum SEARCHTYPE
316         {
317             DialogSearch,
318             NextSearch,
319             PrevSearch,
320         }
321
322         private class PostingStatus
323         {
324             public string status = "";
325             public long? inReplyToId = null;
326             public string inReplyToName = null;
327             public string imageService = "";      //画像投稿サービス名
328             public IMediaItem[] mediaItems = null;
329             public PostingStatus()
330             {
331             }
332             public PostingStatus(string status, long? replyToId, string replyToName)
333             {
334                 this.status = status;
335                 this.inReplyToId = replyToId;
336                 this.inReplyToName = replyToName;
337             }
338         }
339
340         private void TweenMain_Activated(object sender, EventArgs e)
341         {
342             //画面がアクティブになったら、発言欄の背景色戻す
343             if (StatusText.Focused)
344             {
345                 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
346             }
347         }
348
349         private bool disposed = false;
350
351         /// <summary>
352         /// 使用中のリソースをすべてクリーンアップします。
353         /// </summary>
354         /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
355         protected override void Dispose(bool disposing)
356         {
357             base.Dispose(disposing);
358
359             if (this.disposed)
360                 return;
361
362             if (disposing)
363             {
364                 this.components?.Dispose();
365
366                 //後始末
367                 SearchDialog.Dispose();
368                 UrlDialog.Dispose();
369                 NIconAt?.Dispose();
370                 NIconAtRed?.Dispose();
371                 NIconAtSmoke?.Dispose();
372                 foreach (var iconRefresh in this.NIconRefresh)
373                 {
374                     iconRefresh?.Dispose();
375                 }
376                 TabIcon?.Dispose();
377                 MainIcon?.Dispose();
378                 ReplyIcon?.Dispose();
379                 ReplyIconBlink?.Dispose();
380                 _listViewImageList.Dispose();
381                 _brsHighLight.Dispose();
382                 _brsBackColorMine?.Dispose();
383                 _brsBackColorAt?.Dispose();
384                 _brsBackColorYou?.Dispose();
385                 _brsBackColorAtYou?.Dispose();
386                 _brsBackColorAtFromTarget?.Dispose();
387                 _brsBackColorAtTo?.Dispose();
388                 _brsBackColorNone?.Dispose();
389                 _brsDeactiveSelection?.Dispose();
390                 //sf.Dispose();
391                 sfTab.Dispose();
392
393                 this.workerCts.Cancel();
394
395                 if (IconCache != null)
396                 {
397                     this.IconCache.CancelAsync();
398                     this.IconCache.Dispose();
399                 }
400
401                 this.thumbnailTokenSource?.Dispose();
402
403                 this.tw.Dispose();
404                 this.twitterApi.Dispose();
405                 this._hookGlobalHotkey.Dispose();
406             }
407
408             // 終了時にRemoveHandlerしておかないとメモリリークする
409             // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
410             Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
411
412             this.disposed = true;
413         }
414
415         private void LoadIcons()
416         {
417             // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
418             var iconsDir = Path.Combine(Application.StartupPath, "Icons");
419
420             // ウィンドウ左上のアイコン
421             var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
422
423             // タブ見出し未読表示アイコン
424             var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
425
426             // タスクトレイ: 通常時アイコン
427             var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
428
429             // タスクトレイ: エラー時アイコン
430             var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
431
432             // タスクトレイ: オフライン時アイコン
433             var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
434
435             // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
436             var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
437             var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
438
439             // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
440             var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
441             var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
442             var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
443             var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
444
445             // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
446
447             this.MainIcon = iconMain ?? Properties.Resources.MIcon;
448             this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
449             this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
450             this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
451             this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
452
453             if (iconReply != null && iconReplyBlink != null)
454             {
455                 this.ReplyIcon = iconReply;
456                 this.ReplyIconBlink = iconReplyBlink;
457             }
458             else
459             {
460                 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
461                 this.ReplyIconBlink = this.NIconAt;
462             }
463
464             if (iconRefresh1 == null)
465             {
466                 this.NIconRefresh = new[] {
467                     Properties.Resources.Refresh, Properties.Resources.Refresh2,
468                     Properties.Resources.Refresh3, Properties.Resources.Refresh4,
469                 };
470             }
471             else if (iconRefresh2 == null)
472             {
473                 this.NIconRefresh = new[] { iconRefresh1 };
474             }
475             else if (iconRefresh3 == null)
476             {
477                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
478             }
479             else if (iconRefresh4 == null)
480             {
481                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
482             }
483             else // iconRefresh1 から iconRefresh4 まで全て揃っている
484             {
485                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
486             }
487         }
488
489         private Icon LoadIcon(string filePath)
490         {
491             if (!File.Exists(filePath))
492                 return null;
493
494             try
495             {
496                 return new Icon(filePath);
497             }
498             catch (Exception)
499             {
500                 return null;
501             }
502         }
503
504         private void InitColumns(ListView list, bool startup)
505         {
506             this.InitColumnText();
507
508             ColumnHeader[] columns = null;
509             try
510             {
511                 if (this._iconCol)
512                 {
513                     columns = new[]
514                     {
515                         new ColumnHeader(), // アイコン
516                         new ColumnHeader(), // 本文
517                     };
518
519                     columns[0].Text = this.ColumnText[0];
520                     columns[1].Text = this.ColumnText[2];
521
522                     if (startup)
523                     {
524                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
525
526                         columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
527                         columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
528                         columns[0].DisplayIndex = 0;
529                         columns[1].DisplayIndex = 1;
530                     }
531                     else
532                     {
533                         var idx = 0;
534                         foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
535                         {
536                             columns[idx].Width = curListColumn.Width;
537                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
538                             idx++;
539                         }
540                     }
541                 }
542                 else
543                 {
544                     columns = new[]
545                     {
546                         new ColumnHeader(), // アイコン
547                         new ColumnHeader(), // ニックネーム
548                         new ColumnHeader(), // 本文
549                         new ColumnHeader(), // 日付
550                         new ColumnHeader(), // ユーザID
551                         new ColumnHeader(), // 未読
552                         new ColumnHeader(), // マーク&プロテクト
553                         new ColumnHeader(), // ソース
554                     };
555
556                     foreach (var i in Enumerable.Range(0, columns.Length))
557                         columns[i].Text = this.ColumnText[i];
558
559                     if (startup)
560                     {
561                         var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
562
563                         columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
564                         columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
565                         columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
566                         columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
567                         columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
568                         columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
569                         columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
570                         columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
571
572                         var displayIndex = new[] {
573                             this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
574                             this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
575                             this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
576                             this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
577                         };
578
579                         foreach (var i in Enumerable.Range(0, displayIndex.Length))
580                         {
581                             columns[i].DisplayIndex = displayIndex[i];
582                         }
583                     }
584                     else
585                     {
586                         var idx = 0;
587                         foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
588                         {
589                             columns[idx].Width = curListColumn.Width;
590                             columns[idx].DisplayIndex = curListColumn.DisplayIndex;
591                             idx++;
592                         }
593                     }
594                 }
595
596                 list.Columns.AddRange(columns);
597
598                 columns = null;
599             }
600             finally
601             {
602                 if (columns != null)
603                 {
604                     foreach (var column in columns)
605                         column?.Dispose();
606                 }
607             }
608         }
609
610         private void InitColumnText()
611         {
612             ColumnText[0] = "";
613             ColumnText[1] = Properties.Resources.AddNewTabText2;
614             ColumnText[2] = Properties.Resources.AddNewTabText3;
615             ColumnText[3] = Properties.Resources.AddNewTabText4_2;
616             ColumnText[4] = Properties.Resources.AddNewTabText5;
617             ColumnText[5] = "";
618             ColumnText[6] = "";
619             ColumnText[7] = "Source";
620
621             ColumnOrgText[0] = "";
622             ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
623             ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
624             ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
625             ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
626             ColumnOrgText[5] = "";
627             ColumnOrgText[6] = "";
628             ColumnOrgText[7] = "Source";
629
630             int c = 0;
631             switch (_statuses.SortMode)
632             {
633                 case ComparerMode.Nickname:  //ニックネーム
634                     c = 1;
635                     break;
636                 case ComparerMode.Data:  //本文
637                     c = 2;
638                     break;
639                 case ComparerMode.Id:  //時刻=発言Id
640                     c = 3;
641                     break;
642                 case ComparerMode.Name:  //名前
643                     c = 4;
644                     break;
645                 case ComparerMode.Source:  //Source
646                     c = 7;
647                     break;
648             }
649
650             if (_iconCol)
651             {
652                 if (_statuses.SortOrder == SortOrder.Descending)
653                 {
654                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
655                     ColumnText[2] = ColumnOrgText[2] + "▾";
656                 }
657                 else
658                 {
659                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
660                     ColumnText[2] = ColumnOrgText[2] + "▴";
661                 }
662             }
663             else
664             {
665                 if (_statuses.SortOrder == SortOrder.Descending)
666                 {
667                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
668                     ColumnText[c] = ColumnOrgText[c] + "▾";
669                 }
670                 else
671                 {
672                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
673                     ColumnText[c] = ColumnOrgText[c] + "▴";
674                 }
675             }
676         }
677
678         private void InitializeTraceFrag()
679         {
680 #if DEBUG
681             TraceOutToolStripMenuItem.Checked = true;
682             MyCommon.TraceFlag = true;
683 #endif
684             if (!MyCommon.FileVersion.EndsWith("0", StringComparison.Ordinal))
685             {
686                 TraceOutToolStripMenuItem.Checked = true;
687                 MyCommon.TraceFlag = true;
688             }
689         }
690
691         private void TweenMain_Load(object sender, EventArgs e)
692         {
693             _ignoreConfigSave = true;
694             this.Visible = false;
695
696             if (MyApplication.StartupOptions.ContainsKey("d"))
697                 MyCommon.TraceFlag = true;
698
699             InitializeTraceFrag();
700
701             //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
702
703             new InternetSecurityManager(PostBrowser);
704             this.PostBrowser.AllowWebBrowserDrop = false;  // COMException を回避するため、ActiveX の初期化が終わってから設定する
705
706             MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
707             Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
708
709             Regex.CacheSize = 100;
710
711             //発言保持クラス
712             _statuses = TabInformations.GetInstance();
713
714             //アイコン設定
715             LoadIcons();
716             this.Icon = MainIcon;              //メインフォーム(TweenMain)
717             NotifyIcon1.Icon = NIconAt;      //タスクトレイ
718             TabImage.Images.Add(TabIcon);    //タブ見出し
719
720             //<<<<<<<<<設定関連>>>>>>>>>
721             ////設定読み出し
722             LoadConfig();
723
724             // 現在の DPI と設定保存時の DPI との比を取得する
725             var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
726
727             // UIフォント設定
728             var fontUIGlobal = this._cfgLocal.FontUIGlobal;
729             if (fontUIGlobal != null)
730             {
731                 OTBaseForm.GlobalFont = fontUIGlobal;
732                 this.Font = fontUIGlobal;
733             }
734
735             //不正値チェック
736             if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
737             {
738                 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
739                     this._cfgCommon.TimelinePeriod = 15;
740
741                 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
742                     this._cfgCommon.ReplyPeriod = 15;
743
744                 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
745                     this._cfgCommon.DMPeriod = 15;
746
747                 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
748                     this._cfgCommon.PubSearchPeriod = 30;
749
750                 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
751                     this._cfgCommon.UserTimelinePeriod = 15;
752
753                 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
754                     this._cfgCommon.ListsPeriod = 15;
755             }
756
757             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
758                 this._cfgCommon.CountApi = 60;
759             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
760                 this._cfgCommon.CountApiReply = 40;
761
762             if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
763                 this._cfgCommon.MoreCountApi = 200;
764             if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
765                 this._cfgCommon.FirstCountApi = 100;
766
767             if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
768                 this._cfgCommon.FavoritesCountApi = 40;
769             if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
770                 this._cfgCommon.ListCountApi = 100;
771             if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
772                 this._cfgCommon.SearchCountApi = 100;
773             if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
774                 this._cfgCommon.UserTimelineCountApi = 20;
775
776             //廃止サービスが選択されていた場合ux.nuへ読み替え
777             if (this._cfgCommon.AutoShortUrlFirst < 0)
778                 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
779
780             TwitterApiConnection.RestApiBase = this._cfgCommon.TwitterApiBaseUri;
781             this.tw = new Twitter(this.twitterApi);
782
783             //認証関連
784             if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
785             tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
786
787             _initial = true;
788
789             Networking.Initialize();
790
791             bool saveRequired = false;
792             bool firstRun = false;
793
794             //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
795             if (string.IsNullOrEmpty(tw.Username))
796             {
797                 saveRequired = true;
798                 firstRun = true;
799
800                 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
801                 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
802                     string.IsNullOrEmpty(tw.Username))
803                 {
804                     Application.Exit();  //強制終了
805                     return;
806                 }
807             }
808
809             //Twitter用通信クラス初期化
810             Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
811             Networking.SetWebProxy(this._cfgLocal.ProxyType,
812                 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
813                 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
814             Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
815
816             TwitterApiConnection.RestApiBase = this._cfgCommon.TwitterApiBaseUri;
817             tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
818             tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
819             tw.TrackWord = this._cfgCommon.TrackWord;
820             TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
821             tw.AllAtReply = this._cfgCommon.AllAtReply;
822             AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
823             ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
824             ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
825             ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
826
827             // アクセストークンが有効であるか確認する
828             // ここが Twitter API への最初のアクセスになるようにすること
829             try
830             {
831                 this.tw.VerifyCredentials();
832             }
833             catch (WebApiException ex)
834             {
835                 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
836                     Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
837             }
838
839             //サムネイル関連の初期化
840             //プロキシ設定等の通信まわりの初期化が済んでから処理する
841             ThumbnailGenerator.InitializeGenerator();
842
843             var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
844             imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
845             imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
846
847             Thumbnail.Services.TonTwitterCom.GetApiConnection = () => this.twitterApi.Connection;
848
849             //画像投稿サービス
850             ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
851
852             //ハッシュタグ/@id関連
853             AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
854             HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
855             HashMgr = new HashtagManage(HashSupl,
856                                     _cfgCommon.HashTags.ToArray(),
857                                     _cfgCommon.HashSelected,
858                                     _cfgCommon.HashIsPermanent,
859                                     _cfgCommon.HashIsHead,
860                                     _cfgCommon.HashIsNotAddToAtReply);
861             if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
862
863             //アイコンリスト作成
864             this.IconCache = new ImageCache();
865
866             //フォント&文字色&背景色保持
867             _fntUnread = this._cfgLocal.FontUnread;
868             _clUnread = this._cfgLocal.ColorUnread;
869             _fntReaded = this._cfgLocal.FontRead;
870             _clReaded = this._cfgLocal.ColorRead;
871             _clFav = this._cfgLocal.ColorFav;
872             _clOWL = this._cfgLocal.ColorOWL;
873             _clRetweet = this._cfgLocal.ColorRetweet;
874             _fntDetail = this._cfgLocal.FontDetail;
875             _clDetail = this._cfgLocal.ColorDetail;
876             _clDetailLink = this._cfgLocal.ColorDetailLink;
877             _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
878             _clSelf = this._cfgLocal.ColorSelf;
879             _clAtSelf = this._cfgLocal.ColorAtSelf;
880             _clTarget = this._cfgLocal.ColorTarget;
881             _clAtTarget = this._cfgLocal.ColorAtTarget;
882             _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
883             _clAtTo = this._cfgLocal.ColorAtTo;
884             _clListBackcolor = this._cfgLocal.ColorListBackcolor;
885             _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
886             _clInputFont = this._cfgLocal.ColorInputFont;
887             _fntInputFont = this._cfgLocal.FontInputFont;
888
889             _brsBackColorMine = new SolidBrush(_clSelf);
890             _brsBackColorAt = new SolidBrush(_clAtSelf);
891             _brsBackColorYou = new SolidBrush(_clTarget);
892             _brsBackColorAtYou = new SolidBrush(_clAtTarget);
893             _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
894             _brsBackColorAtTo = new SolidBrush(_clAtTo);
895             //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
896             _brsBackColorNone = new SolidBrush(_clListBackcolor);
897
898             // StringFormatオブジェクトへの事前設定
899             //sf.Alignment = StringAlignment.Near;             // Textを近くへ配置(左から右の場合は左寄せ)
900             //sf.LineAlignment = StringAlignment.Near;         // Textを近くへ配置(上寄せ)
901             //sf.FormatFlags = StringFormatFlags.LineLimit;    // 
902             sfTab.Alignment = StringAlignment.Center;
903             sfTab.LineAlignment = StringAlignment.Center;
904
905             InitDetailHtmlFormat();
906
907             //Regex statregex = new Regex("^0*");
908             this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
909
910             _history.Add(new PostingStatus());
911             _hisIdx = 0;
912             this.inReplyTo = null;
913
914             //各種ダイアログ設定
915             SearchDialog.Owner = this;
916             UrlDialog.Owner = this;
917
918             //新着バルーン通知のチェック状態設定
919             NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
920             this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
921
922             //新着取得時のリストスクロールをするか。trueならスクロールしない
923             ListLockMenuItem.Checked = _cfgCommon.ListLock;
924             this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
925             //サウンド再生(タブ別設定より優先)
926             this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
927             this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
928
929             this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
930             this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
931
932             //ウィンドウ設定
933             this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
934             _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
935             _myLoc = _cfgLocal.FormLocation;
936             //タイトルバー領域
937             if (this.WindowState != FormWindowState.Minimized)
938             {
939                 this.DesktopLocation = _cfgLocal.FormLocation;
940                 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
941                 bool outOfScreen = true;
942                 if (Screen.AllScreens.Length == 1)    //ハングするとの報告
943                 {
944                     foreach (Screen scr in Screen.AllScreens)
945                     {
946                         if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
947                         {
948                             outOfScreen = false;
949                             break;
950                         }
951                     }
952                     if (outOfScreen)
953                     {
954                         this.DesktopLocation = new Point(0, 0);
955                         _myLoc = this.DesktopLocation;
956                     }
957                 }
958             }
959             this.TopMost = this._cfgCommon.AlwaysTop;
960             _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
961             _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
962             if (_cfgLocal.PreviewDistance == -1)
963             {
964                 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
965                 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
966                 _cfgLocal.PreviewDistance = _mySpDis3;
967             }
968             else
969             {
970                 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
971             }
972             MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
973             //this.Tween_ClientSizeChanged(this, null);
974             this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
975             this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
976             //入力欄
977             StatusText.Font = _fntInputFont;
978             StatusText.ForeColor = _clInputFont;
979
980             // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
981             this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
982             this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
983
984             // NameLabel のフォントを OTBaseForm.GlobalFont に変更
985             this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
986
987             // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
988             SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
989
990             //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
991             if (this._cfgCommon.UnreadManage == false)
992             {
993                 ReadedStripMenuItem.Enabled = false;
994                 UnreadStripMenuItem.Enabled = false;
995             }
996
997             //発言詳細部の初期化
998             NameLabel.Text = "";
999             DateTimeLabel.Text = "";
1000             SourceLinkLabel.Text = "";
1001
1002             //リンク先URL表示部の初期化(画面左下)
1003             StatusLabelUrl.Text = "";
1004             //状態表示部の初期化(画面右下)
1005             StatusLabel.Text = "";
1006             StatusLabel.AutoToolTip = false;
1007             StatusLabel.ToolTipText = "";
1008             //文字カウンタ初期化
1009             lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
1010
1011             this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
1012             CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
1013             CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
1014             CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
1015
1016             // SourceLinkLabel のテキストが SplitContainer2.Panel2.AccessibleName にセットされるのを防ぐ
1017             // (タブオーダー順で SourceLinkLabel の次にある PostBrowser が TabStop = false となっているため、
1018             // さらに次のコントロールである SplitContainer2.Panel2 の AccessibleName がデフォルトで SourceLinkLabel のテキストになってしまう)
1019             this.SplitContainer2.Panel2.AccessibleName = "";
1020
1021             ////////////////////////////////////////////////////////////////////////////////
1022             var sortOrder = (SortOrder)_cfgCommon.SortOrder;
1023             var mode = ComparerMode.Id;
1024             switch (_cfgCommon.SortColumn)
1025             {
1026                 case 0:    //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
1027                 case 5:
1028                 case 6:
1029                     //ソートしない
1030                     mode = ComparerMode.Id;  //Idソートに読み替え
1031                     break;
1032                 case 1:  //ニックネーム
1033                     mode = ComparerMode.Nickname;
1034                     break;
1035                 case 2:  //本文
1036                     mode = ComparerMode.Data;
1037                     break;
1038                 case 3:  //時刻=発言Id
1039                     mode = ComparerMode.Id;
1040                     break;
1041                 case 4:  //名前
1042                     mode = ComparerMode.Name;
1043                     break;
1044                 case 7:  //Source
1045                     mode = ComparerMode.Source;
1046                     break;
1047             }
1048             _statuses.SetSortMode(mode, sortOrder);
1049             ////////////////////////////////////////////////////////////////////////////////
1050
1051             ApplyListViewIconSize(this._cfgCommon.IconSize);
1052
1053             //<<<<<<<<タブ関連>>>>>>>
1054             // タブの位置を調整する
1055             SetTabAlignment();
1056
1057             //デフォルトタブの存在チェック、ない場合には追加
1058             if (this._statuses.GetTabByType<HomeTabModel>() == null)
1059                 this._statuses.AddTab(new HomeTabModel());
1060
1061             if (this._statuses.GetTabByType<MentionsTabModel>() == null)
1062                 this._statuses.AddTab(new MentionsTabModel());
1063
1064             if (this._statuses.GetTabByType<DirectMessagesTabModel>() == null)
1065                 this._statuses.AddTab(new DirectMessagesTabModel());
1066
1067             if (this._statuses.GetTabByType<FavoritesTabModel>() == null)
1068                 this._statuses.AddTab(new FavoritesTabModel());
1069
1070             if (this._statuses.GetTabByType<MuteTabModel>() == null)
1071                 this._statuses.AddTab(new MuteTabModel());
1072
1073             foreach (var tab in _statuses.Tabs.Values)
1074             {
1075                 // ミュートタブは表示しない
1076                 if (tab.TabType == MyCommon.TabUsageType.Mute)
1077                     continue;
1078
1079                 if (!AddNewTab(tab, startup: true))
1080                     throw new TabException(Properties.Resources.TweenMain_LoadText1);
1081             }
1082
1083             _curTab = ListTab.SelectedTab;
1084             _curItemIndex = -1;
1085             _curList = (DetailsListView)_curTab.Tag;
1086
1087             if (this._cfgCommon.TabIconDisp)
1088             {
1089                 ListTab.DrawMode = TabDrawMode.Normal;
1090             }
1091             else
1092             {
1093                 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1094                 ListTab.DrawItem += ListTab_DrawItem;
1095                 ListTab.ImageList = null;
1096             }
1097
1098             if (this._cfgCommon.HotkeyEnabled)
1099             {
1100                 //////グローバルホットキーの登録
1101                 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1102                 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1103                     modKey |= HookGlobalHotkey.ModKeys.Alt;
1104                 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1105                     modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1106                 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1107                     modKey |= HookGlobalHotkey.ModKeys.Shift;
1108                 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1109                     modKey |= HookGlobalHotkey.ModKeys.Win;
1110
1111                 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1112             }
1113
1114             if (this._cfgCommon.IsUseNotifyGrowl)
1115                 gh.RegisterGrowl();
1116
1117             StatusLabel.Text = Properties.Resources.Form1_LoadText1;       //画面右下の状態表示を変更
1118
1119             SetMainWindowTitle();
1120             SetNotifyIconText();
1121
1122             if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1123             {
1124                 this.Visible = true;
1125             }
1126
1127             //タイマー設定
1128             TimerTimeline.AutoReset = true;
1129             TimerTimeline.SynchronizingObject = this;
1130             //Recent取得間隔
1131             TimerTimeline.Interval = 1000;
1132             TimerTimeline.Enabled = true;
1133             //更新中アイコンアニメーション間隔
1134             TimerRefreshIcon.Interval = 200;
1135             TimerRefreshIcon.Enabled = true;
1136
1137             _ignoreConfigSave = false;
1138             this.TweenMain_Resize(null, null);
1139             if (saveRequired) SaveConfigsAll(false);
1140
1141             foreach (var ua in this._cfgCommon.UserAccounts)
1142             {
1143                 if (ua.UserId == 0 && ua.Username.ToLowerInvariant() == tw.Username.ToLowerInvariant())
1144                 {
1145                     ua.UserId = tw.UserId;
1146                     break;
1147                 }
1148             }
1149
1150             if (firstRun)
1151             {
1152                 // 初回起動時だけ右下のメニューを目立たせる
1153                 HashStripSplitButton.ShowDropDown();
1154             }
1155         }
1156
1157         private void InitDetailHtmlFormat()
1158         {
1159             if (this._cfgCommon.IsMonospace)
1160             {
1161                 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1162                 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1163             }
1164             else
1165             {
1166                 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1167                 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1168             }
1169
1170             detailHtmlFormatHeader = detailHtmlFormatHeader
1171                     .Replace("%FONT_FAMILY%", _fntDetail.Name)
1172                     .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1173                     .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1174                     .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1175                     .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString())
1176                     .Replace("%BG_REPLY_COLOR%", $"{_clAtTo.R}, {_clAtTo.G}, {_clAtTo.B}");
1177         }
1178
1179         private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1180         {
1181             string txt;
1182             try
1183             {
1184                 txt = ListTab.TabPages[e.Index].Text;
1185             }
1186             catch (Exception)
1187             {
1188                 return;
1189             }
1190
1191             e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1192             if (e.State == DrawItemState.Selected)
1193             {
1194                 e.DrawFocusRectangle();
1195             }
1196             Brush fore;
1197             try
1198             {
1199                 if (_statuses.Tabs[txt].UnreadCount > 0)
1200                     fore = Brushes.Red;
1201                 else
1202                     fore = System.Drawing.SystemBrushes.ControlText;
1203             }
1204             catch (Exception)
1205             {
1206                 fore = System.Drawing.SystemBrushes.ControlText;
1207             }
1208             e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1209         }
1210
1211         private void LoadConfig()
1212         {
1213             _cfgCommon = SettingCommon.Load();
1214             SettingCommon.Instance = this._cfgCommon;
1215             if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1216             {
1217                 _cfgCommon.UserAccounts = new List<UserAccount>();
1218                 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1219                 {
1220                     UserAccount account = new UserAccount();
1221                     account.Username = _cfgCommon.UserName;
1222                     account.UserId = _cfgCommon.UserId;
1223                     account.Token = _cfgCommon.Token;
1224                     account.TokenSecret = _cfgCommon.TokenSecret;
1225
1226                     _cfgCommon.UserAccounts.Add(account);
1227                 }
1228             }
1229
1230             _cfgLocal = SettingLocal.Load();
1231
1232             // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1233             if (_cfgLocal.ScaleDimension.IsEmpty)
1234                 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1235
1236             var tabsSetting = SettingTabs.Load().Tabs;
1237             foreach (var tabSetting in tabsSetting)
1238             {
1239                 TabModel tab;
1240                 switch (tabSetting.TabType)
1241                 {
1242                     case MyCommon.TabUsageType.Home:
1243                         tab = new HomeTabModel(tabSetting.TabName);
1244                         break;
1245                     case MyCommon.TabUsageType.Mentions:
1246                         tab = new MentionsTabModel(tabSetting.TabName);
1247                         break;
1248                     case MyCommon.TabUsageType.DirectMessage:
1249                         tab = new DirectMessagesTabModel(tabSetting.TabName);
1250                         break;
1251                     case MyCommon.TabUsageType.Favorites:
1252                         tab = new FavoritesTabModel(tabSetting.TabName);
1253                         break;
1254                     case MyCommon.TabUsageType.UserDefined:
1255                         tab = new FilterTabModel(tabSetting.TabName);
1256                         break;
1257                     case MyCommon.TabUsageType.UserTimeline:
1258                         tab = new UserTimelineTabModel(tabSetting.TabName, tabSetting.User);
1259                         break;
1260                     case MyCommon.TabUsageType.PublicSearch:
1261                         tab = new PublicSearchTabModel(tabSetting.TabName)
1262                         {
1263                             SearchWords = tabSetting.SearchWords,
1264                             SearchLang = tabSetting.SearchLang,
1265                         };
1266                         break;
1267                     case MyCommon.TabUsageType.Lists:
1268                         tab = new ListTimelineTabModel(tabSetting.TabName, tabSetting.ListInfo);
1269                         break;
1270                     case MyCommon.TabUsageType.Mute:
1271                         tab = new MuteTabModel(tabSetting.TabName);
1272                         break;
1273                     default:
1274                         continue;
1275                 }
1276
1277                 tab.UnreadManage = tabSetting.UnreadManage;
1278                 tab.Protected = tabSetting.Protected;
1279                 tab.Notify = tabSetting.Notify;
1280                 tab.SoundFile = tabSetting.SoundFile;
1281
1282                 if (tab.IsDistributableTabType)
1283                 {
1284                     var filterTab = (FilterTabModel)tab;
1285                     filterTab.FilterArray = tabSetting.FilterArray;
1286                     filterTab.FilterModified = false;
1287                 }
1288
1289                 if (this._statuses.ContainsTab(tab.TabName))
1290                     tab.TabName = this._statuses.MakeTabName("MyTab");
1291
1292                 this._statuses.AddTab(tab);
1293             }
1294             if (_statuses.Tabs.Count == 0)
1295             {
1296                 _statuses.AddTab(new HomeTabModel());
1297                 _statuses.AddTab(new MentionsTabModel());
1298                 _statuses.AddTab(new DirectMessagesTabModel());
1299                 _statuses.AddTab(new FavoritesTabModel());
1300             }
1301         }
1302
1303         private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1304         {
1305             if (!TimerTimeline.Enabled) return;
1306             ResetTimers = e;
1307         }
1308
1309         private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1310
1311         private static int homeCounter = 0;
1312         private static int mentionCounter = 0;
1313         private static int dmCounter = 0;
1314         private static int pubSearchCounter = 0;
1315         private static int userTimelineCounter = 0;
1316         private static int listsCounter = 0;
1317         private static int usCounter = 0;
1318         private static int ResumeWait = 0;
1319         private static int refreshFollowers = 0;
1320
1321         private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1322         {
1323             if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1324             if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1325             if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1326             if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1327             if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1328             if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1329             if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1330             Interlocked.Increment(ref refreshFollowers);
1331
1332             var refreshTasks = new List<Task>();
1333
1334             ////タイマー初期化
1335             if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1336             {
1337                 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1338                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1339                     refreshTasks.Add(this.GetHomeTimelineAsync());
1340                 ResetTimers.Timeline = false;
1341             }
1342             if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1343             {
1344                 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1345                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1346                     refreshTasks.Add(this.GetReplyAsync());
1347                 ResetTimers.Reply = false;
1348             }
1349             if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1350             {
1351                 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1352                 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1353                     refreshTasks.Add(this.GetDirectMessagesAsync());
1354                 ResetTimers.DirectMessage = false;
1355             }
1356             if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1357             {
1358                 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1359                 if (!ResetTimers.PublicSearch)
1360                     refreshTasks.Add(this.GetPublicSearchAllAsync());
1361                 ResetTimers.PublicSearch = false;
1362             }
1363             if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1364             {
1365                 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1366                 if (!ResetTimers.UserTimeline)
1367                     refreshTasks.Add(this.GetUserTimelineAllAsync());
1368                 ResetTimers.UserTimeline = false;
1369             }
1370             if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1371             {
1372                 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1373                 if (!ResetTimers.Lists)
1374                     refreshTasks.Add(this.GetListTimelineAllAsync());
1375                 ResetTimers.Lists = false;
1376             }
1377             if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1378             {
1379                 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1380                 if (this.tw.UserStreamActive)
1381                     this.RefreshTimeline();
1382                 ResetTimers.UserStream = false;
1383             }
1384             if (refreshFollowers > 6 * 3600)
1385             {
1386                 Interlocked.Exchange(ref refreshFollowers, 0);
1387                 refreshTasks.AddRange(new[]
1388                 {
1389                     this.doGetFollowersMenu(),
1390                     this.RefreshNoRetweetIdsAsync(),
1391                     this.RefreshTwitterConfigurationAsync(),
1392                 });
1393             }
1394             if (osResumed)
1395             {
1396                 Interlocked.Increment(ref ResumeWait);
1397                 if (ResumeWait > 30)
1398                 {
1399                     osResumed = false;
1400                     Interlocked.Exchange(ref ResumeWait, 0);
1401                     refreshTasks.AddRange(new[]
1402                     {
1403                         this.GetHomeTimelineAsync(),
1404                         this.GetReplyAsync(),
1405                         this.GetDirectMessagesAsync(),
1406                         this.GetPublicSearchAllAsync(),
1407                         this.GetUserTimelineAllAsync(),
1408                         this.GetListTimelineAllAsync(),
1409                         this.doGetFollowersMenu(),
1410                         this.RefreshTwitterConfigurationAsync(),
1411                     });
1412                 }
1413             }
1414
1415             await Task.WhenAll(refreshTasks);
1416         }
1417
1418         private void RefreshTimeline()
1419         {
1420             // 現在表示中のタブのスクロール位置を退避
1421             var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1422
1423             // 各タブのリスト上の選択位置などを退避
1424             var listSelections = this.SaveListViewSelection();
1425
1426             //更新確定
1427             PostClass[] notifyPosts;
1428             string soundFile;
1429             int addCount;
1430             bool newMentionOrDm;
1431             bool isDelete;
1432             addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1433
1434             if (MyCommon._endingFlag) return;
1435
1436             //リストに反映&選択状態復元
1437             try
1438             {
1439                 foreach (TabPage tab in ListTab.TabPages)
1440                 {
1441                     DetailsListView lst = (DetailsListView)tab.Tag;
1442                     TabModel tabInfo = _statuses.Tabs[tab.Text];
1443                     if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1444                     {
1445                         using (ControlTransaction.Update(lst))
1446                         {
1447                             if (lst.Equals(_curList))
1448                             {
1449                                 this.PurgeListViewItemCache();
1450                             }
1451                             try
1452                             {
1453                                 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1454                             }
1455                             catch (Exception)
1456                             {
1457                                 //アイコン描画不具合あり?
1458                             }
1459
1460                             // 選択位置などを復元
1461                             this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1462                         }
1463                     }
1464                     if (tabInfo.UnreadCount > 0)
1465                         if (this._cfgCommon.TabIconDisp)
1466                             if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1467                 }
1468                 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1469             }
1470             catch (Exception)
1471             {
1472                 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1473                 //throw;
1474             }
1475
1476             // スクロール位置を復元
1477             this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1478
1479             //新着通知
1480             NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1481
1482             SetMainWindowTitle();
1483             if (!StatusLabelUrl.Text.StartsWith("http", StringComparison.Ordinal)) SetStatusLabelUrl();
1484
1485             HashSupl.AddRangeItem(tw.GetHashList());
1486
1487         }
1488
1489         internal struct ListViewScroll
1490         {
1491             public ScrollLockMode ScrollLockMode { get; set; }
1492             public long? TopItemStatusId { get; set; }
1493         }
1494
1495         internal enum ScrollLockMode
1496         {
1497             /// <summary>固定しない</summary>
1498             None,
1499
1500             /// <summary>最上部に固定する</summary>
1501             FixedToTop,
1502
1503             /// <summary>最下部に固定する</summary>
1504             FixedToBottom,
1505
1506             /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1507             FixedToItem,
1508         }
1509
1510         /// <summary>
1511         /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1512         /// </summary>
1513         private ListViewScroll SaveListViewScroll(DetailsListView listView, TabModel tab)
1514         {
1515             var listScroll = new ListViewScroll
1516             {
1517                 ScrollLockMode = this.GetScrollLockMode(listView),
1518             };
1519
1520             if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1521             {
1522                 var topItem = listView.TopItem;
1523                 if (topItem != null)
1524                     listScroll.TopItemStatusId = tab.GetStatusIdAt(topItem.Index);
1525             }
1526
1527             return listScroll;
1528         }
1529
1530         private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1531         {
1532             if (this._statuses.SortMode == ComparerMode.Id)
1533             {
1534                 if (this._statuses.SortOrder == SortOrder.Ascending)
1535                 {
1536                     // Id昇順
1537                     if (this.ListLockMenuItem.Checked)
1538                         return ScrollLockMode.None;
1539
1540                     // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1541
1542                     // 一番下に表示されているアイテム
1543                     var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1544                     if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1545                         return ScrollLockMode.FixedToBottom;
1546                     else
1547                         return ScrollLockMode.None;
1548                 }
1549                 else
1550                 {
1551                     // Id降順
1552                     if (this.ListLockMenuItem.Checked)
1553                         return ScrollLockMode.FixedToItem;
1554
1555                     // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1556                     var topItem = listView.TopItem;
1557                     if (topItem == null || topItem.Index == 0)
1558                         return ScrollLockMode.FixedToTop;
1559                     else
1560                         return ScrollLockMode.FixedToItem;
1561                 }
1562             }
1563             else
1564             {
1565                 return ScrollLockMode.FixedToItem;
1566             }
1567         }
1568
1569         internal struct ListViewSelection
1570         {
1571             public long[] SelectedStatusIds { get; set; }
1572             public long? SelectionMarkStatusId { get; set; }
1573             public long? FocusedStatusId { get; set; }
1574         }
1575
1576         /// <summary>
1577         /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1578         /// </summary>
1579         private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1580         {
1581             var listsDict = new Dictionary<string, ListViewSelection>();
1582
1583             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1584             {
1585                 var listView = (DetailsListView)tabPage.Tag;
1586                 var tab = _statuses.Tabs[tabPage.Text];
1587
1588                 ListViewSelection listStatus;
1589                 if (listView.VirtualListSize != 0)
1590                 {
1591                     listStatus = new ListViewSelection
1592                     {
1593                         SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1594                         FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1595                         SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1596                     };
1597                 }
1598                 else
1599                 {
1600                     listStatus = new ListViewSelection
1601                     {
1602                         SelectedStatusIds = new long[0],
1603                         SelectionMarkStatusId = null,
1604                         FocusedStatusId = null,
1605                     };
1606                 }
1607
1608                 listsDict[tab.TabName] = listStatus;
1609             }
1610
1611             return listsDict;
1612         }
1613
1614         private long[] GetSelectedStatusIds(DetailsListView listView, TabModel tab)
1615         {
1616             var selectedIndices = listView.SelectedIndices;
1617             if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1618                 return tab.GetStatusIdAt(selectedIndices.Cast<int>());
1619             else
1620                 return null;
1621         }
1622
1623         private long? GetFocusedStatusId(DetailsListView listView, TabModel tab)
1624         {
1625             var focusedItem = listView.FocusedItem;
1626
1627             return focusedItem != null ? tab.GetStatusIdAt(focusedItem.Index) : (long?)null;
1628         }
1629
1630         private long? GetSelectionMarkStatusId(DetailsListView listView, TabModel tab)
1631         {
1632             var selectionMarkIndex = listView.SelectionMark;
1633
1634             return selectionMarkIndex != -1 ? tab.GetStatusIdAt(selectionMarkIndex) : (long?)null;
1635         }
1636
1637         /// <summary>
1638         /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1639         /// </summary>
1640         private void RestoreListViewScroll(DetailsListView listView, TabModel tab, ListViewScroll listScroll)
1641         {
1642             if (listView.VirtualListSize == 0)
1643                 return;
1644
1645             switch (listScroll.ScrollLockMode)
1646             {
1647                 case ScrollLockMode.FixedToTop:
1648                     listView.EnsureVisible(0);
1649                     break;
1650                 case ScrollLockMode.FixedToBottom:
1651                     listView.EnsureVisible(listView.VirtualListSize - 1);
1652                     break;
1653                 case ScrollLockMode.FixedToItem:
1654                     var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1655                     if (topIndex != -1)
1656                         listView.TopItem = listView.Items[topIndex];
1657                     break;
1658                 case ScrollLockMode.None:
1659                 default:
1660                     break;
1661             }
1662         }
1663
1664         /// <summary>
1665         /// <see cref="SaveListViewStatus"/> によって保存された選択状態を復元します
1666         /// </summary>
1667         private void RestoreListViewSelection(DetailsListView listView, TabModel tab, ListViewSelection listSelection)
1668         {
1669             // status_id から ListView 上のインデックスに変換
1670             int[] selectedIndices = null;
1671             if (listSelection.SelectedStatusIds != null)
1672                 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1673
1674             var focusedIndex = -1;
1675             if (listSelection.FocusedStatusId != null)
1676                 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1677
1678             var selectionMarkIndex = -1;
1679             if (listSelection.SelectionMarkStatusId != null)
1680                 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1681
1682             this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1683         }
1684
1685         private bool BalloonRequired()
1686         {
1687             Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1688             ev.Eventtype = MyCommon.EVENTTYPE.None;
1689
1690             return BalloonRequired(ev);
1691         }
1692
1693         private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1694         {
1695             if (type == MyCommon.EVENTTYPE.None)
1696                 return true;
1697
1698             if (!this._cfgCommon.EventNotifyEnabled)
1699                 return false;
1700
1701             return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1702         }
1703
1704         private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1705         {
1706             if (!ev.IsMe)
1707                 return true;
1708
1709             return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1710         }
1711
1712         private bool BalloonRequired(Twitter.FormattedEvent ev)
1713         {
1714             if (this._initial)
1715                 return false;
1716
1717             if (NativeMethods.IsScreenSaverRunning())
1718                 return false;
1719
1720             // 「新着通知」が無効
1721             if (!this.NewPostPopMenuItem.Checked)
1722             {
1723                 // 「新着通知が無効でもイベントを通知する」にも該当しない
1724                 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1725                     return false;
1726             }
1727
1728             // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1729             if (this._cfgCommon.LimitBalloon)
1730             {
1731                 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1732                     return false;
1733             }
1734
1735             return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1736         }
1737
1738         private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1739         {
1740             if (this._cfgCommon.ReadOwnPost)
1741             {
1742                 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1743                     return;
1744             }
1745
1746             //新着通知
1747             if (BalloonRequired())
1748             {
1749                 if (notifyPosts != null && notifyPosts.Length > 0)
1750                 {
1751                     //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1752                     if (this._cfgCommon.IsUseNotifyGrowl)
1753                     {
1754                         StringBuilder sb = new StringBuilder();
1755                         bool reply = false;
1756                         bool dm = false;
1757
1758                         foreach (PostClass post in notifyPosts)
1759                         {
1760                             if (!(notifyPosts.Length > 3))
1761                             {
1762                                 sb.Clear();
1763                                 reply = false;
1764                                 dm = false;
1765                             }
1766                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1767                             if (post.IsDm) dm = true;
1768                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1769                             switch (this._cfgCommon.NameBalloon)
1770                             {
1771                                 case MyCommon.NameBalloonEnum.UserID:
1772                                     sb.Append(post.ScreenName).Append(" : ");
1773                                     break;
1774                                 case MyCommon.NameBalloonEnum.NickName:
1775                                     sb.Append(post.Nickname).Append(" : ");
1776                                     break;
1777                             }
1778                             sb.Append(post.TextFromApi);
1779                             if (notifyPosts.Length > 3)
1780                             {
1781                                 if (notifyPosts.Last() != post) continue;
1782                             }
1783
1784                             StringBuilder title = new StringBuilder();
1785                             GrowlHelper.NotifyType nt;
1786                             if (this._cfgCommon.DispUsername)
1787                             {
1788                                 title.Append(tw.Username);
1789                                 title.Append(" - ");
1790                             }
1791                             else
1792                             {
1793                                 //title.Clear();
1794                             }
1795                             if (dm)
1796                             {
1797                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1798                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1799                                 title.Append(Application.ProductName);
1800                                 title.Append(" [DM] ");
1801                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1802                                 nt = GrowlHelper.NotifyType.DirectMessage;
1803                             }
1804                             else if (reply)
1805                             {
1806                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1807                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1808                                 title.Append(Application.ProductName);
1809                                 title.Append(" [Reply!] ");
1810                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1811                                 nt = GrowlHelper.NotifyType.Reply;
1812                             }
1813                             else
1814                             {
1815                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1816                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1817                                 title.Append(Application.ProductName);
1818                                 title.Append(" ");
1819                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1820                                 nt = GrowlHelper.NotifyType.Notify;
1821                             }
1822                             string bText = sb.ToString();
1823                             if (string.IsNullOrEmpty(bText)) return;
1824
1825                             var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1826                             gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1827                         }
1828                     }
1829                     else
1830                     {
1831                         StringBuilder sb = new StringBuilder();
1832                         bool reply = false;
1833                         bool dm = false;
1834                         foreach (PostClass post in notifyPosts)
1835                         {
1836                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1837                             if (post.IsDm) dm = true;
1838                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1839                             switch (this._cfgCommon.NameBalloon)
1840                             {
1841                                 case MyCommon.NameBalloonEnum.UserID:
1842                                     sb.Append(post.ScreenName).Append(" : ");
1843                                     break;
1844                                 case MyCommon.NameBalloonEnum.NickName:
1845                                     sb.Append(post.Nickname).Append(" : ");
1846                                     break;
1847                             }
1848                             sb.Append(post.TextFromApi);
1849
1850                         }
1851                         //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1852                         StringBuilder title = new StringBuilder();
1853                         ToolTipIcon ntIcon;
1854                         if (this._cfgCommon.DispUsername)
1855                         {
1856                             title.Append(tw.Username);
1857                             title.Append(" - ");
1858                         }
1859                         else
1860                         {
1861                             //title.Clear();
1862                         }
1863                         if (dm)
1864                         {
1865                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1866                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1867                             ntIcon = ToolTipIcon.Warning;
1868                             title.Append(Application.ProductName);
1869                             title.Append(" [DM] ");
1870                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1871                         }
1872                         else if (reply)
1873                         {
1874                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1875                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1876                             ntIcon = ToolTipIcon.Warning;
1877                             title.Append(Application.ProductName);
1878                             title.Append(" [Reply!] ");
1879                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1880                         }
1881                         else
1882                         {
1883                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1884                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1885                             ntIcon = ToolTipIcon.Info;
1886                             title.Append(Application.ProductName);
1887                             title.Append(" ");
1888                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1889                         }
1890                         string bText = sb.ToString();
1891                         if (string.IsNullOrEmpty(bText)) return;
1892                         //NotifyIcon1.BalloonTipText = sb.ToString();
1893                         //NotifyIcon1.ShowBalloonTip(500);
1894                         NotifyIcon1.BalloonTipTitle = title.ToString();
1895                         NotifyIcon1.BalloonTipText = bText;
1896                         NotifyIcon1.BalloonTipIcon = ntIcon;
1897                         NotifyIcon1.ShowBalloonTip(500);
1898                     }
1899                 }
1900             }
1901
1902             //サウンド再生
1903             if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1904             {
1905                 try
1906                 {
1907                     string dir = Application.StartupPath;
1908                     if (Directory.Exists(Path.Combine(dir, "Sounds")))
1909                     {
1910                         dir = Path.Combine(dir, "Sounds");
1911                     }
1912                     using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1913                     {
1914                         player.Play();
1915                     }
1916                 }
1917                 catch (Exception)
1918                 {
1919                 }
1920             }
1921
1922             //mentions新着時に画面ブリンク
1923             if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1924             {
1925                 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1926             }
1927         }
1928
1929         private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1930         {
1931             if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1932
1933             _curItemIndex = _curList.SelectedIndices[0];
1934             if (_curItemIndex > _curList.VirtualListSize - 1) return;
1935
1936             try
1937             {
1938                 this._curPost = GetCurTabPost(_curItemIndex);
1939             }
1940             catch (ArgumentException)
1941             {
1942                 return;
1943             }
1944
1945             this.PushSelectPostChain();
1946
1947             this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1948             //キャッシュの書き換え
1949             ChangeCacheStyleRead(true, _curItemIndex);   //既読へ(フォント、文字色)
1950
1951             ColorizeList();
1952             _colorize = true;
1953         }
1954
1955         private void ChangeCacheStyleRead(bool Read, int Index)
1956         {
1957             var tabInfo = _statuses.Tabs[_curTab.Text];
1958             //Read:true=既読 false=未読
1959             //未読管理していなかったら既読として扱う
1960             if (!tabInfo.UnreadManage ||
1961                !this._cfgCommon.UnreadManage) Read = true;
1962
1963             var listCache = this._listItemCache;
1964             if (listCache == null)
1965                 return;
1966
1967             // キャッシュに含まれていないアイテムは対象外
1968             ListViewItem itm;
1969             PostClass post;
1970             if (!listCache.TryGetValue(Index, out itm, out post))
1971                 return;
1972
1973             ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1974         }
1975
1976         private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1977         {
1978             Font fnt;
1979             //フォント
1980             if (Read)
1981             {
1982                 fnt = _fntReaded;
1983                 Item.SubItems[5].Text = "";
1984             }
1985             else
1986             {
1987                 fnt = _fntUnread;
1988                 Item.SubItems[5].Text = "★";
1989             }
1990             //文字色
1991             Color cl;
1992             if (Post.IsFav)
1993                 cl = _clFav;
1994             else if (Post.RetweetedId != null)
1995                 cl = _clRetweet;
1996             else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1997                 cl = _clOWL;
1998             else if (Read || !this._cfgCommon.UseUnreadStyle)
1999                 cl = _clReaded;
2000             else
2001                 cl = _clUnread;
2002
2003             if (DList == null || Item.Index == -1)
2004             {
2005                 Item.ForeColor = cl;
2006                 if (this._cfgCommon.UseUnreadStyle)
2007                     Item.Font = fnt;
2008             }
2009             else
2010             {
2011                 DList.Update();
2012                 if (this._cfgCommon.UseUnreadStyle)
2013                     DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
2014                 else
2015                     DList.ChangeItemForeColor(Item.Index, cl);
2016                 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
2017             }
2018         }
2019
2020         private void ColorizeList()
2021         {
2022             //Index:更新対象のListviewItem.Index。Colorを返す。
2023             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2024             PostClass _post;
2025             if (_anchorFlag)
2026                 _post = _anchorPost;
2027             else
2028                 _post = _curPost;
2029
2030             if (_post == null) return;
2031
2032             var listCache = this._listItemCache;
2033             if (listCache == null)
2034                 return;
2035
2036             var index = listCache.StartIndex;
2037             foreach (var cachedPost in listCache.Post)
2038             {
2039                 var backColor = this.JudgeColor(_post, cachedPost);
2040                 this._curList.ChangeItemBackColor(index++, backColor);
2041             }
2042         }
2043
2044         private void ColorizeList(ListViewItem Item, int Index)
2045         {
2046             //Index:更新対象のListviewItem.Index。Colorを返す。
2047             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2048             PostClass _post;
2049             if (_anchorFlag)
2050                 _post = _anchorPost;
2051             else
2052                 _post = _curPost;
2053
2054             PostClass tPost = GetCurTabPost(Index);
2055
2056             if (_post == null) return;
2057
2058             if (Item.Index == -1)
2059                 Item.BackColor = JudgeColor(_post, tPost);
2060             else
2061                 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2062         }
2063
2064         private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2065         {
2066             Color cl;
2067             if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2068                 //@先
2069                 cl = _clAtTo;
2070             else if (TargetPost.IsMe)
2071                 //自分=発言者
2072                 cl = _clSelf;
2073             else if (TargetPost.IsReply)
2074                 //自分宛返信
2075                 cl = _clAtSelf;
2076             else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLowerInvariant()))
2077                 //返信先
2078                 cl = _clAtFromTarget;
2079             else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLowerInvariant()))
2080                 //その人への返信
2081                 cl = _clAtTarget;
2082             else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2083                 //発言者
2084                 cl = _clTarget;
2085             else
2086                 //その他
2087                 cl = _clListBackcolor;
2088
2089             return cl;
2090         }
2091
2092         private async void PostButton_Click(object sender, EventArgs e)
2093         {
2094             if (StatusText.Text.Trim().Length == 0)
2095             {
2096                 if (!ImageSelector.Enabled)
2097                 {
2098                     await this.DoRefresh();
2099                     return;
2100                 }
2101             }
2102
2103             if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2104             {
2105                 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2106                                                                "Retweet",
2107                                                                MessageBoxButtons.YesNoCancel,
2108                                                                MessageBoxIcon.Question);
2109                 switch (rtResult)
2110                 {
2111                     case DialogResult.Yes:
2112                         StatusText.Text = "";
2113                         await this.doReTweetOfficial(false);
2114                         return;
2115                     case DialogResult.Cancel:
2116                         return;
2117                 }
2118             }
2119
2120             var inReplyToStatusId = this.inReplyTo?.Item1;
2121             var inReplyToScreenName = this.inReplyTo?.Item2;
2122             _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2123
2124             if (this._cfgCommon.Nicoms)
2125             {
2126                 StatusText.SelectionStart = StatusText.Text.Length;
2127                 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2128             }
2129             //if (SettingDialog.UrlConvertAuto)
2130             //{
2131             //    StatusText.SelectionStart = StatusText.Text.Length;
2132             //    UrlConvertAutoToolStripMenuItem_Click(null, null);
2133             //}
2134             //else if (SettingDialog.Nicoms)
2135             //{
2136             //    StatusText.SelectionStart = StatusText.Text.Length;
2137             //    UrlConvert(UrlConverter.Nicoms);
2138             //}
2139             StatusText.SelectionStart = StatusText.Text.Length;
2140             CheckReplyTo(StatusText.Text);
2141
2142             var statusText = this.FormatStatusText(this.StatusText.Text);
2143
2144             if (this.GetRestStatusCount(statusText) < 0)
2145             {
2146                 // 文字数制限を超えているが強制的に投稿するか
2147                 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2148                 if (ret != DialogResult.OK)
2149                     return;
2150             }
2151
2152             var status = new PostingStatus();
2153             status.status = statusText;
2154
2155             status.inReplyToId = this.inReplyTo?.Item1;
2156             status.inReplyToName = this.inReplyTo?.Item2;
2157             if (ImageSelector.Visible)
2158             {
2159                 //画像投稿
2160                 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2161                     return;
2162             }
2163
2164             this.inReplyTo = null;
2165             StatusText.Text = "";
2166             _history.Add(new PostingStatus());
2167             _hisIdx = _history.Count - 1;
2168             if (!ToolStripFocusLockMenuItem.Checked)
2169                 ((Control)ListTab.SelectedTab.Tag).Focus();
2170             urlUndoBuffer = null;
2171             UrlUndoToolStripMenuItem.Enabled = false;  //Undoをできないように設定
2172
2173             //Google検索(試験実装)
2174             if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2175             {
2176                 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2177                 await this.OpenUriInBrowserAsync(tmp);
2178             }
2179
2180             await this.PostMessageAsync(status);
2181         }
2182
2183         private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2184         {
2185             MyCommon._endingFlag = true;
2186             this.Close();
2187         }
2188
2189         private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2190         {
2191             if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2192             {
2193                 //_endingFlag=false:フォームの×ボタン
2194                 e.Cancel = true;
2195                 this.Visible = false;
2196             }
2197             else
2198             {
2199                 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2200                 _ignoreConfigSave = true;
2201                 MyCommon._endingFlag = true;
2202                 TimerTimeline.Enabled = false;
2203                 TimerRefreshIcon.Enabled = false;
2204             }
2205         }
2206
2207         private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2208         {
2209             this.Visible = true;
2210             if (this.WindowState == FormWindowState.Minimized)
2211             {
2212                 this.WindowState = FormWindowState.Normal;
2213             }
2214             this.Activate();
2215             this.BringToFront();
2216         }
2217
2218         private static int errorCount = 0;
2219
2220         private static bool CheckAccountValid()
2221         {
2222             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2223             {
2224                 errorCount += 1;
2225                 if (errorCount > 5)
2226                 {
2227                     errorCount = 0;
2228                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2229                     return true;
2230                 }
2231                 return false;
2232             }
2233             errorCount = 0;
2234             return true;
2235         }
2236
2237         private Task GetHomeTimelineAsync()
2238         {
2239             return this.GetHomeTimelineAsync(loadMore: false);
2240         }
2241
2242         private async Task GetHomeTimelineAsync(bool loadMore)
2243         {
2244             await this.workerSemaphore.WaitAsync();
2245
2246             try
2247             {
2248                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2249
2250                 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2251             }
2252             catch (WebApiException ex)
2253             {
2254                 this._myStatusError = true;
2255                 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2256             }
2257             finally
2258             {
2259                 this.workerSemaphore.Release();
2260             }
2261         }
2262
2263         private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2264         {
2265             if (ct.IsCancellationRequested)
2266                 return;
2267
2268             if (!CheckAccountValid())
2269                 throw new WebApiException("Auth error. Check your account");
2270
2271             bool read;
2272             if (!this._cfgCommon.UnreadManage)
2273                 read = true;
2274             else
2275                 read = this._initial && this._cfgCommon.Read;
2276
2277             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5, loadMore ? -1 : 1));
2278
2279             await Task.Run(async () =>
2280             {
2281                 await this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial)
2282                     .ConfigureAwait(false);
2283
2284                 // 新着時未読クリア
2285                 if (this._cfgCommon.ReadOldPosts)
2286                     this._statuses.SetReadHomeTab();
2287
2288                 var addCount = this._statuses.DistributePosts();
2289
2290                 if (!this._initial)
2291                     this.UpdateTimelineSpeed(addCount);
2292             });
2293
2294             if (ct.IsCancellationRequested)
2295                 return;
2296
2297             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2298
2299             this.RefreshTimeline();
2300         }
2301
2302         /// <summary>
2303         /// タイムラインに追加された発言件数を反映し、タイムラインの流速を更新します
2304         /// </summary>
2305         /// <param name="addCount">直前にタイムラインに追加した発言件数</param>
2306         private void UpdateTimelineSpeed(int addCount)
2307         {
2308             var now = DateTime.Now;
2309             this._tlTimestamps.AddOrUpdate(now, addCount, (k, v) => v + addCount);
2310
2311             var removeKeys = new List<DateTime>();
2312             var oneHour = TimeSpan.FromHours(1);
2313             var tlCount = 0;
2314             foreach (var pair in this._tlTimestamps)
2315             {
2316                 if (now - pair.Key > oneHour)
2317                     removeKeys.Add(pair.Key);
2318                 else
2319                     tlCount += pair.Value;
2320             }
2321             Interlocked.Exchange(ref this._tlCount, tlCount);
2322
2323             int _;
2324             foreach (var key in removeKeys)
2325                 this._tlTimestamps.TryRemove(key, out _);
2326         }
2327
2328         private Task GetReplyAsync()
2329         {
2330             return this.GetReplyAsync(loadMore: false);
2331         }
2332
2333         private async Task GetReplyAsync(bool loadMore)
2334         {
2335             await this.workerSemaphore.WaitAsync();
2336
2337             try
2338             {
2339                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2340
2341                 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2342             }
2343             catch (WebApiException ex)
2344             {
2345                 this._myStatusError = true;
2346                 this.StatusLabel.Text = $"Err:{ex.Message}(GetTimeline)";
2347             }
2348             finally
2349             {
2350                 this.workerSemaphore.Release();
2351             }
2352         }
2353
2354         private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2355         {
2356             if (ct.IsCancellationRequested)
2357                 return;
2358
2359             if (!CheckAccountValid())
2360                 throw new WebApiException("Auth error. Check your account");
2361
2362             bool read;
2363             if (!this._cfgCommon.UnreadManage)
2364                 read = true;
2365             else
2366                 read = this._initial && this._cfgCommon.Read;
2367
2368             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4, loadMore ? -1 : 1));
2369
2370             await Task.Run(async () =>
2371             {
2372                 await this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial)
2373                     .ConfigureAwait(false);
2374
2375                 this._statuses.DistributePosts();
2376             });
2377
2378             if (ct.IsCancellationRequested)
2379                 return;
2380
2381             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2382
2383             this.RefreshTimeline();
2384         }
2385
2386         private Task GetDirectMessagesAsync()
2387         {
2388             return this.GetDirectMessagesAsync(loadMore: false);
2389         }
2390
2391         private async Task GetDirectMessagesAsync(bool loadMore)
2392         {
2393             await this.workerSemaphore.WaitAsync();
2394
2395             try
2396             {
2397                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2398
2399                 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2400             }
2401             catch (WebApiException ex)
2402             {
2403                 this._myStatusError = true;
2404                 this.StatusLabel.Text = $"Err:{ex.Message}(GetDirectMessage)";
2405             }
2406             finally
2407             {
2408                 this.workerSemaphore.Release();
2409             }
2410         }
2411
2412         private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2413         {
2414             if (ct.IsCancellationRequested)
2415                 return;
2416
2417             if (!CheckAccountValid())
2418                 throw new WebApiException("Auth error. Check your account");
2419
2420             bool read;
2421             if (!this._cfgCommon.UnreadManage)
2422                 read = true;
2423             else
2424                 read = this._initial && this._cfgCommon.Read;
2425
2426             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8, loadMore ? -1 : 1));
2427
2428             await Task.Run(async () =>
2429             {
2430                 await this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore)
2431                     .ConfigureAwait(false);
2432                 await this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore)
2433                     .ConfigureAwait(false);
2434
2435                 this._statuses.DistributePosts();
2436             });
2437
2438             if (ct.IsCancellationRequested)
2439                 return;
2440
2441             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2442
2443             this.RefreshTimeline();
2444         }
2445
2446         private Task GetFavoritesAsync()
2447         {
2448             return this.GetFavoritesAsync(loadMore: false);
2449         }
2450
2451         private async Task GetFavoritesAsync(bool loadMore)
2452         {
2453             await this.workerSemaphore.WaitAsync();
2454
2455             try
2456             {
2457                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2458
2459                 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2460             }
2461             catch (WebApiException ex)
2462             {
2463                 this._myStatusError = true;
2464                 this.StatusLabel.Text = ex.Message;
2465             }
2466             finally
2467             {
2468                 this.workerSemaphore.Release();
2469             }
2470         }
2471
2472         private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2473         {
2474             if (ct.IsCancellationRequested)
2475                 return;
2476
2477             if (!CheckAccountValid())
2478                 throw new WebApiException("Auth error. Check your account");
2479
2480             bool read;
2481             if (!this._cfgCommon.UnreadManage)
2482                 read = true;
2483             else
2484                 read = this._initial && this._cfgCommon.Read;
2485
2486             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2487
2488             await Task.Run(async () =>
2489             {
2490                 await this.tw.GetFavoritesApi(read, loadMore)
2491                     .ConfigureAwait(false);
2492
2493                 this._statuses.DistributePosts();
2494             });
2495
2496             if (ct.IsCancellationRequested)
2497                 return;
2498
2499             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2500
2501             this.RefreshTimeline();
2502         }
2503
2504         private Task GetPublicSearchAllAsync()
2505         {
2506             var tabs = this._statuses.GetTabsByType<PublicSearchTabModel>();
2507
2508             return this.GetPublicSearchAsync(tabs, loadMore: false);
2509         }
2510
2511         private Task GetPublicSearchAsync(PublicSearchTabModel tab)
2512         {
2513             return this.GetPublicSearchAsync(tab, loadMore: false);
2514         }
2515
2516         private Task GetPublicSearchAsync(PublicSearchTabModel tab, bool loadMore)
2517         {
2518             return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2519         }
2520
2521         private async Task GetPublicSearchAsync(IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2522         {
2523             await this.workerSemaphore.WaitAsync();
2524
2525             try
2526             {
2527                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2528
2529                 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2530             }
2531             catch (WebApiException ex)
2532             {
2533                 this._myStatusError = true;
2534                 this.StatusLabel.Text = ex.Message;
2535             }
2536             finally
2537             {
2538                 this.workerSemaphore.Release();
2539             }
2540         }
2541
2542         private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<PublicSearchTabModel> tabs, bool loadMore)
2543         {
2544             if (ct.IsCancellationRequested)
2545                 return;
2546
2547             if (!CheckAccountValid())
2548                 throw new WebApiException("Auth error. Check your account");
2549
2550             bool read;
2551             if (!this._cfgCommon.UnreadManage)
2552                 read = true;
2553             else
2554                 read = this._initial && this._cfgCommon.Read;
2555
2556             p.Report("Search refreshing...");
2557
2558             await Task.Run(async () =>
2559             {
2560                 WebApiException lastException = null;
2561
2562                 foreach (var tab in tabs)
2563                 {
2564                     try
2565                     {
2566                         if (string.IsNullOrEmpty(tab.SearchWords))
2567                             continue;
2568
2569                         await this.tw.GetSearch(read, tab, false)
2570                             .ConfigureAwait(false);
2571
2572                         if (loadMore)
2573                             await this.tw.GetSearch(read, tab, true)
2574                                 .ConfigureAwait(false);
2575                     }
2576                     catch (WebApiException ex)
2577                     {
2578                         lastException = ex;
2579                     }
2580                 }
2581
2582                 this._statuses.DistributePosts();
2583
2584                 if (lastException != null)
2585                     throw new WebApiException(lastException.Message, lastException);
2586             });
2587
2588             if (ct.IsCancellationRequested)
2589                 return;
2590
2591             p.Report("Search refreshed");
2592
2593             this.RefreshTimeline();
2594         }
2595
2596         private Task GetUserTimelineAllAsync()
2597         {
2598             var tabs = this._statuses.GetTabsByType<UserTimelineTabModel>();
2599
2600             return this.GetUserTimelineAsync(tabs, loadMore: false);
2601         }
2602
2603         private Task GetUserTimelineAsync(UserTimelineTabModel tab)
2604         {
2605             return this.GetUserTimelineAsync(tab, loadMore: false);
2606         }
2607
2608         private Task GetUserTimelineAsync(UserTimelineTabModel tab, bool loadMore)
2609         {
2610             return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2611         }
2612
2613         private async Task GetUserTimelineAsync(IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2614         {
2615             await this.workerSemaphore.WaitAsync();
2616
2617             try
2618             {
2619                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2620
2621                 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2622             }
2623             catch (WebApiException ex)
2624             {
2625                 this._myStatusError = true;
2626                 this.StatusLabel.Text = $"Err:{ex.Message}(GetUserTimeline)";
2627             }
2628             finally
2629             {
2630                 this.workerSemaphore.Release();
2631             }
2632         }
2633
2634         private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<UserTimelineTabModel> tabs, bool loadMore)
2635         {
2636             if (ct.IsCancellationRequested)
2637                 return;
2638
2639             if (!CheckAccountValid())
2640                 throw new WebApiException("Auth error. Check your account");
2641
2642             bool read;
2643             if (!this._cfgCommon.UnreadManage)
2644                 read = true;
2645             else
2646                 read = this._initial && this._cfgCommon.Read;
2647
2648             p.Report("UserTimeline refreshing...");
2649
2650             await Task.Run(async () =>
2651             {
2652                 WebApiException lastException = null;
2653
2654                 foreach (var tab in tabs)
2655                 {
2656                     try
2657                     {
2658                         if (string.IsNullOrEmpty(tab.ScreenName))
2659                             continue;
2660
2661                         await this.tw.GetUserTimelineApi(read, tab.ScreenName, tab, loadMore)
2662                             .ConfigureAwait(false);
2663                     }
2664                     catch (WebApiException ex)
2665                     {
2666                         lastException = ex;
2667                     }
2668                 }
2669
2670                 this._statuses.DistributePosts();
2671
2672                 if (lastException != null)
2673                     throw new WebApiException(lastException.Message, lastException);
2674             });
2675
2676             if (ct.IsCancellationRequested)
2677                 return;
2678
2679             p.Report("UserTimeline refreshed");
2680
2681             this.RefreshTimeline();
2682         }
2683
2684         private Task GetListTimelineAllAsync()
2685         {
2686             var tabs = this._statuses.GetTabsByType<ListTimelineTabModel>();
2687
2688             return this.GetListTimelineAsync(tabs, loadMore: false);
2689         }
2690
2691         private Task GetListTimelineAsync(ListTimelineTabModel tab)
2692         {
2693             return this.GetListTimelineAsync(tab, loadMore: false);
2694         }
2695
2696         private Task GetListTimelineAsync(ListTimelineTabModel tab, bool loadMore)
2697         {
2698             return this.GetListTimelineAsync(new[] { tab }, loadMore);
2699         }
2700
2701         private async Task GetListTimelineAsync(IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2702         {
2703             await this.workerSemaphore.WaitAsync();
2704
2705             try
2706             {
2707                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2708
2709                 await this.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2710             }
2711             catch (WebApiException ex)
2712             {
2713                 this._myStatusError = true;
2714                 this.StatusLabel.Text = $"Err:{ex.Message}(GetListStatus)";
2715             }
2716             finally
2717             {
2718                 this.workerSemaphore.Release();
2719             }
2720         }
2721
2722         private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<ListTimelineTabModel> tabs, bool loadMore)
2723         {
2724             if (ct.IsCancellationRequested)
2725                 return;
2726
2727             if (!CheckAccountValid())
2728                 throw new WebApiException("Auth error. Check your account");
2729
2730             bool read;
2731             if (!this._cfgCommon.UnreadManage)
2732                 read = true;
2733             else
2734                 read = this._initial && this._cfgCommon.Read;
2735
2736             p.Report("List refreshing...");
2737
2738             await Task.Run(async () =>
2739             {
2740                 WebApiException lastException = null;
2741
2742                 foreach (var tab in tabs)
2743                 {
2744                     try
2745                     {
2746                         if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2747                             continue;
2748
2749                         await this.tw.GetListStatus(read, tab, loadMore, this._initial)
2750                             .ConfigureAwait(false);
2751                     }
2752                     catch (WebApiException ex)
2753                     {
2754                         lastException = ex;
2755                     }
2756                 }
2757
2758                 this._statuses.DistributePosts();
2759
2760                 if (lastException != null)
2761                     throw new WebApiException(lastException.Message, lastException);
2762             });
2763
2764             if (ct.IsCancellationRequested)
2765                 return;
2766
2767             p.Report("List refreshed");
2768
2769             this.RefreshTimeline();
2770         }
2771
2772         private async Task GetRelatedTweetsAsync(RelatedPostsTabModel tab)
2773         {
2774             await this.workerSemaphore.WaitAsync();
2775
2776             try
2777             {
2778                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2779
2780                 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2781             }
2782             catch (WebApiException ex)
2783             {
2784                 this._myStatusError = true;
2785                 this.StatusLabel.Text = $"Err:{ex.Message}(GetRelatedTweets)";
2786             }
2787             finally
2788             {
2789                 this.workerSemaphore.Release();
2790             }
2791         }
2792
2793         private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, RelatedPostsTabModel tab)
2794         {
2795             if (ct.IsCancellationRequested)
2796                 return;
2797
2798             if (!CheckAccountValid())
2799                 throw new WebApiException("Auth error. Check your account");
2800
2801             bool read;
2802             if (!this._cfgCommon.UnreadManage)
2803                 read = true;
2804             else
2805                 read = this._initial && this._cfgCommon.Read;
2806
2807             p.Report("Related refreshing...");
2808
2809             await Task.Run(async () =>
2810             {
2811                 await this.tw.GetRelatedResult(read, tab)
2812                     .ConfigureAwait(false);
2813
2814                 this._statuses.DistributePosts();
2815             });
2816
2817             if (ct.IsCancellationRequested)
2818                 return;
2819
2820             p.Report("Related refreshed");
2821
2822             this.RefreshTimeline();
2823
2824             var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2825                 .FirstOrDefault(x => x.Text == tab.TabName);
2826
2827             if (tabPage != null)
2828             {
2829                 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2830
2831                 var listView = (DetailsListView)tabPage.Tag;
2832                 var index = tab.IndexOf(tab.TargetPost.RetweetedId ?? tab.TargetPost.StatusId);
2833
2834                 if (index != -1 && index < listView.Items.Count)
2835                 {
2836                     listView.SelectedIndices.Add(index);
2837                     listView.Items[index].Focused = true;
2838                 }
2839             }
2840         }
2841
2842         private async Task FavAddAsync(long statusId, TabModel tab)
2843         {
2844             await this.workerSemaphore.WaitAsync();
2845
2846             try
2847             {
2848                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2849
2850                 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusId, tab);
2851             }
2852             catch (WebApiException ex)
2853             {
2854                 this._myStatusError = true;
2855                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavAdd)";
2856             }
2857             finally
2858             {
2859                 this.workerSemaphore.Release();
2860             }
2861         }
2862
2863         private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, long statusId, TabModel tab)
2864         {
2865             if (ct.IsCancellationRequested)
2866                 return;
2867
2868             if (!CheckAccountValid())
2869                 throw new WebApiException("Auth error. Check your account");
2870
2871             PostClass post;
2872             if (!tab.Posts.TryGetValue(statusId, out post))
2873                 return;
2874
2875             if (post.IsFav)
2876                 return;
2877
2878             await Task.Run(async () =>
2879             {
2880                 p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 0, 1, 0));
2881
2882                 try
2883                 {
2884                     await this.twitterApi.FavoritesCreate(post.RetweetedId ?? post.StatusId)
2885                         .IgnoreResponse()
2886                         .ConfigureAwait(false);
2887
2888                     if (this._cfgCommon.RestrictFavCheck)
2889                     {
2890                         var status = await this.twitterApi.StatusesShow(post.RetweetedId ?? post.StatusId)
2891                             .ConfigureAwait(false);
2892
2893                         if (status.Favorited != true)
2894                             throw new WebApiException("NG(Restricted?)");
2895                     }
2896
2897                     this._favTimestamps.Add(DateTime.Now);
2898
2899                     // TLでも取得済みならfav反映
2900                     if (this._statuses.ContainsKey(statusId))
2901                     {
2902                         var postTl = this._statuses[statusId];
2903                         postTl.IsFav = true;
2904
2905                         var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2906                         favTab.AddPostQueue(postTl);
2907                     }
2908
2909                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
2910                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
2911                     {
2912                         if (tb.Contains(statusId))
2913                             tb.Posts[statusId].IsFav = true;
2914                     }
2915
2916                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 0));
2917                 }
2918                 catch (WebApiException)
2919                 {
2920                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, 1, 1, 1));
2921                     throw;
2922                 }
2923
2924                 // 時速表示用
2925                 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2926                 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2927                 {
2928                     if (this._favTimestamps[i] < oneHour)
2929                         this._favTimestamps.RemoveAt(i);
2930                 }
2931
2932                 this._statuses.DistributePosts();
2933             });
2934
2935             if (ct.IsCancellationRequested)
2936                 return;
2937
2938             this.RefreshTimeline();
2939
2940             if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2941             {
2942                 using (ControlTransaction.Update(this._curList))
2943                 {
2944                     var idx = tab.IndexOf(statusId);
2945                     if (idx != -1)
2946                         this.ChangeCacheStyleRead(post.IsRead, idx);
2947                 }
2948
2949                 if (statusId == this._curPost.StatusId)
2950                     await this.DispSelectedPost(true); // 選択アイテム再表示
2951             }
2952         }
2953
2954         private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabModel tab)
2955         {
2956             await this.workerSemaphore.WaitAsync();
2957
2958             try
2959             {
2960                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2961
2962                 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2963             }
2964             catch (WebApiException ex)
2965             {
2966                 this._myStatusError = true;
2967                 this.StatusLabel.Text = $"Err:{ex.Message}(PostFavRemove)";
2968             }
2969             finally
2970             {
2971                 this.workerSemaphore.Release();
2972             }
2973         }
2974
2975         private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabModel tab)
2976         {
2977             if (ct.IsCancellationRequested)
2978                 return;
2979
2980             if (!CheckAccountValid())
2981                 throw new WebApiException("Auth error. Check your account");
2982
2983             var successIds = new List<long>();
2984
2985             await Task.Run(async () =>
2986             {
2987                 //スレッド処理はしない
2988                 var allCount = 0;
2989                 var failedCount = 0;
2990                 foreach (var statusId in statusIds)
2991                 {
2992                     allCount++;
2993
2994                     var post = tab.Posts[statusId];
2995
2996                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2997
2998                     if (!post.IsFav)
2999                         continue;
3000
3001                     try
3002                     {
3003                         await this.twitterApi.FavoritesDestroy(post.RetweetedId ?? post.StatusId)
3004                             .IgnoreResponse()
3005                             .ConfigureAwait(false);
3006                     }
3007                     catch (WebApiException)
3008                     {
3009                         failedCount++;
3010                         continue;
3011                     }
3012
3013                     successIds.Add(statusId);
3014                     post.IsFav = false; // リスト再描画必要
3015
3016                     if (this._statuses.ContainsKey(statusId))
3017                     {
3018                         this._statuses[statusId].IsFav = false;
3019                     }
3020
3021                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
3022                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
3023                     {
3024                         if (tb.Contains(statusId))
3025                             tb.Posts[statusId].IsFav = false;
3026                     }
3027                 }
3028             });
3029
3030             if (ct.IsCancellationRequested)
3031                 return;
3032
3033             var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3034             foreach (var statusId in successIds)
3035             {
3036                 // ツイートが削除された訳ではないので IsDeleted はセットしない
3037                 favTab.EnqueueRemovePost(statusId, setIsDeleted: false);
3038             }
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 NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3372         {
3373             if (e.Button == MouseButtons.Left)
3374             {
3375                 this.Visible = true;
3376                 if (this.WindowState == FormWindowState.Minimized)
3377                 {
3378                     this.WindowState = _formWindowState;
3379                 }
3380                 this.Activate();
3381                 this.BringToFront();
3382             }
3383         }
3384
3385         private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3386         {
3387             switch (this._cfgCommon.ListDoubleClickAction)
3388             {
3389                 case 0:
3390                     MakeReplyOrDirectStatus();
3391                     break;
3392                 case 1:
3393                     await this.FavoriteChange(true);
3394                     break;
3395                 case 2:
3396                     if (_curPost != null)
3397                         await this.ShowUserStatus(_curPost.ScreenName, false);
3398                     break;
3399                 case 3:
3400                     ShowUserTimeline();
3401                     break;
3402                 case 4:
3403                     ShowRelatedStatusesMenuItem_Click(null, null);
3404                     break;
3405                 case 5:
3406                     MoveToHomeToolStripMenuItem_Click(null, null);
3407                     break;
3408                 case 6:
3409                     StatusOpenMenuItem_Click(null, null);
3410                     break;
3411                 case 7:
3412                     //動作なし
3413                     break;
3414             }
3415         }
3416
3417         private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3418         {
3419             await this.FavoriteChange(true);
3420         }
3421
3422         private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3423         {
3424             await this.FavoriteChange(false);
3425         }
3426
3427
3428         private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3429         {
3430             await this.FavoritesRetweetOfficial();
3431         }
3432
3433         private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3434         {
3435             await this.FavoritesRetweetUnofficial();
3436         }
3437
3438         private async Task FavoriteChange(bool FavAdd, bool multiFavoriteChangeDialogEnable = true)
3439         {
3440             TabModel tab;
3441             if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3442                 return;
3443
3444             //trueでFavAdd,falseでFavRemove
3445             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3446                 || !this.ExistCurrentPost) return;
3447
3448             if (this._curList.SelectedIndices.Count > 1)
3449             {
3450                 if (FavAdd)
3451                 {
3452                     // 複数ツイートの一括ふぁぼは禁止
3453                     // https://support.twitter.com/articles/76915#favoriting
3454                     MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, 1));
3455                     _DoFavRetweetFlags = false;
3456                     return;
3457                 }
3458                 else
3459                 {
3460                     if (multiFavoriteChangeDialogEnable)
3461                     {
3462                         var confirm = MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1,
3463                             Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3464                             MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3465
3466                         if (confirm == DialogResult.Cancel)
3467                             return;
3468                     }
3469                 }
3470             }
3471
3472             if (FavAdd)
3473             {
3474                 var selectedPost = this.GetCurTabPost(_curList.SelectedIndices[0]);
3475                 if (selectedPost.IsFav)
3476                 {
3477                     this.StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3478                     return;
3479                 }
3480
3481                 await this.FavAddAsync(selectedPost.StatusId, tab);
3482             }
3483             else
3484             {
3485                 var selectedPosts = this._curList.SelectedIndices.Cast<int>()
3486                     .Select(x => this.GetCurTabPost(x))
3487                     .Where(x => x.IsFav);
3488
3489                 var statusIds = selectedPosts.Select(x => x.StatusId).ToArray();
3490                 if (statusIds.Length == 0)
3491                 {
3492                     this.StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3493                     return;
3494                 }
3495
3496                 await this.FavRemoveAsync(statusIds, tab);
3497             }
3498         }
3499
3500         private PostClass GetCurTabPost(int Index)
3501         {
3502             var listCache = this._listItemCache;
3503             if (listCache != null)
3504             {
3505                 ListViewItem item;
3506                 PostClass post;
3507                 if (listCache.TryGetValue(Index, out item, out post))
3508                     return post;
3509             }
3510
3511             return _statuses.Tabs[_curTab.Text][Index];
3512         }
3513
3514         private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3515         {
3516             if (_curList.SelectedIndices.Count > 0)
3517                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3518             else if (_curList.SelectedIndices.Count == 0)
3519                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3520         }
3521
3522         private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3523         {
3524             if (_curList.SelectedIndices.Count > 0)
3525                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3526         }
3527
3528         private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3529         {
3530             if ((!_initialLayout) && this.Visible)
3531             {
3532                 if (this.WindowState == FormWindowState.Normal)
3533                 {
3534                     _mySize = this.ClientSize;
3535                     _mySpDis = this.SplitContainer1.SplitterDistance;
3536                     _mySpDis3 = this.SplitContainer3.SplitterDistance;
3537                     if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3538                     ModifySettingLocal = true;
3539                 }
3540             }
3541         }
3542
3543         private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3544         {
3545             var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3546             if (comparerMode == null)
3547                 return;
3548
3549             this.SetSortColumn(comparerMode.Value);
3550         }
3551
3552         /// <summary>
3553         /// 列インデックスからソートを行う ComparerMode を求める
3554         /// </summary>
3555         /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3556         /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3557         private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3558         {
3559             if (this._iconCol)
3560                 return ComparerMode.Id;
3561
3562             switch (columnIndex)
3563             {
3564                 case 1: // ニックネーム
3565                     return ComparerMode.Nickname;
3566                 case 2: // 本文
3567                     return ComparerMode.Data;
3568                 case 3: // 時刻=発言Id
3569                     return ComparerMode.Id;
3570                 case 4: // 名前
3571                     return ComparerMode.Name;
3572                 case 7: // Source
3573                     return ComparerMode.Source;
3574                 default:
3575                     // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3576                     return null;
3577             }
3578         }
3579
3580         /// <summary>
3581         /// 発言一覧の指定した位置の列でソートする
3582         /// </summary>
3583         /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3584         private void SetSortColumnByDisplayIndex(int columnIndex)
3585         {
3586             // 表示上の列の位置から ColumnHeader を求める
3587             var col = this._curList.Columns.Cast<ColumnHeader>()
3588                 .Where(x => x.DisplayIndex == columnIndex)
3589                 .FirstOrDefault();
3590
3591             if (col == null)
3592                 return;
3593
3594             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3595             if (comparerMode == null)
3596                 return;
3597
3598             this.SetSortColumn(comparerMode.Value);
3599         }
3600
3601         /// <summary>
3602         /// 発言一覧の最後列の項目でソートする
3603         /// </summary>
3604         private void SetSortLastColumn()
3605         {
3606             // 表示上の最後列にある ColumnHeader を求める
3607             var col = this._curList.Columns.Cast<ColumnHeader>()
3608                 .OrderByDescending(x => x.DisplayIndex)
3609                 .First();
3610
3611             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3612             if (comparerMode == null)
3613                 return;
3614
3615             this.SetSortColumn(comparerMode.Value);
3616         }
3617
3618         /// <summary>
3619         /// 発言一覧を指定された ComparerMode に基づいてソートする
3620         /// </summary>
3621         private void SetSortColumn(ComparerMode sortColumn)
3622         {
3623             if (this._cfgCommon.SortOrderLock)
3624                 return;
3625
3626             this._statuses.ToggleSortOrder(sortColumn);
3627             this.InitColumnText();
3628
3629             var list = this._curList;
3630             if (_iconCol)
3631             {
3632                 list.Columns[0].Text = this.ColumnText[0];
3633                 list.Columns[1].Text = this.ColumnText[2];
3634             }
3635             else
3636             {
3637                 for (var i = 0; i <= 7; i++)
3638                 {
3639                     list.Columns[i].Text = this.ColumnText[i];
3640                 }
3641             }
3642
3643             this.PurgeListViewItemCache();
3644
3645             var tab = this._statuses.Tabs[this._curTab.Text];
3646             if (tab.AllCount > 0 && this._curPost != null)
3647             {
3648                 var idx = tab.IndexOf(this._curPost.StatusId);
3649                 if (idx > -1)
3650                 {
3651                     this.SelectListItem(list, idx);
3652                     list.EnsureVisible(idx);
3653                 }
3654             }
3655             list.Refresh();
3656
3657             this.ModifySettingCommon = true;
3658         }
3659
3660         private void TweenMain_LocationChanged(object sender, EventArgs e)
3661         {
3662             if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3663             {
3664                 _myLoc = this.DesktopLocation;
3665                 ModifySettingLocal = true;
3666             }
3667         }
3668
3669         private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3670         {
3671             if (ListTab.SelectedTab == null) return;
3672             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3673             if (!this.ExistCurrentPost)
3674             {
3675                 ReplyStripMenuItem.Enabled = false;
3676                 ReplyAllStripMenuItem.Enabled = false;
3677                 DMStripMenuItem.Enabled = false;
3678                 ShowProfileMenuItem.Enabled = false;
3679                 ShowUserTimelineContextMenuItem.Enabled = false;
3680                 ListManageUserContextToolStripMenuItem2.Enabled = false;
3681                 MoveToFavToolStripMenuItem.Enabled = false;
3682                 TabMenuItem.Enabled = false;
3683                 IDRuleMenuItem.Enabled = false;
3684                 SourceRuleMenuItem.Enabled = false;
3685                 ReadedStripMenuItem.Enabled = false;
3686                 UnreadStripMenuItem.Enabled = false;
3687             }
3688             else
3689             {
3690                 ShowProfileMenuItem.Enabled = true;
3691                 ListManageUserContextToolStripMenuItem2.Enabled = true;
3692                 ReplyStripMenuItem.Enabled = true;
3693                 ReplyAllStripMenuItem.Enabled = true;
3694                 DMStripMenuItem.Enabled = true;
3695                 ShowUserTimelineContextMenuItem.Enabled = true;
3696                 MoveToFavToolStripMenuItem.Enabled = true;
3697                 TabMenuItem.Enabled = true;
3698                 IDRuleMenuItem.Enabled = true;
3699                 SourceRuleMenuItem.Enabled = true;
3700                 ReadedStripMenuItem.Enabled = true;
3701                 UnreadStripMenuItem.Enabled = true;
3702             }
3703             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3704             {
3705                 FavAddToolStripMenuItem.Enabled = false;
3706                 FavRemoveToolStripMenuItem.Enabled = false;
3707                 StatusOpenMenuItem.Enabled = false;
3708                 FavorareMenuItem.Enabled = false;
3709                 ShowRelatedStatusesMenuItem.Enabled = false;
3710
3711                 ReTweetStripMenuItem.Enabled = false;
3712                 ReTweetUnofficialStripMenuItem.Enabled = false;
3713                 QuoteStripMenuItem.Enabled = false;
3714                 FavoriteRetweetContextMenu.Enabled = false;
3715                 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3716             }
3717             else
3718             {
3719                 FavAddToolStripMenuItem.Enabled = true;
3720                 FavRemoveToolStripMenuItem.Enabled = true;
3721                 StatusOpenMenuItem.Enabled = true;
3722                 FavorareMenuItem.Enabled = true;
3723                 ShowRelatedStatusesMenuItem.Enabled = true;  //PublicSearchの時問題出るかも
3724
3725                 if (_curPost.IsMe)
3726                 {
3727                     ReTweetStripMenuItem.Enabled = false;  //公式RTは無効に
3728                     ReTweetUnofficialStripMenuItem.Enabled = true;
3729                     QuoteStripMenuItem.Enabled = true;
3730                     FavoriteRetweetContextMenu.Enabled = false;  //公式RTは無効に
3731                     FavoriteRetweetUnofficialContextMenu.Enabled = true;
3732                 }
3733                 else
3734                 {
3735                     if (_curPost.IsProtect)
3736                     {
3737                         ReTweetStripMenuItem.Enabled = false;
3738                         ReTweetUnofficialStripMenuItem.Enabled = false;
3739                         QuoteStripMenuItem.Enabled = false;
3740                         FavoriteRetweetContextMenu.Enabled = false;
3741                         FavoriteRetweetUnofficialContextMenu.Enabled = false;
3742                     }
3743                     else
3744                     {
3745                         ReTweetStripMenuItem.Enabled = true;
3746                         ReTweetUnofficialStripMenuItem.Enabled = true;
3747                         QuoteStripMenuItem.Enabled = true;
3748                         FavoriteRetweetContextMenu.Enabled = true;
3749                         FavoriteRetweetUnofficialContextMenu.Enabled = true;
3750                     }
3751                 }
3752             }
3753             //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3754             //{
3755             //    RefreshMoreStripMenuItem.Enabled = true;
3756             //}
3757             //else
3758             //{
3759             //    RefreshMoreStripMenuItem.Enabled = false;
3760             //}
3761             if (!this.ExistCurrentPost
3762                 || _curPost.InReplyToStatusId == null)
3763             {
3764                 RepliedStatusOpenMenuItem.Enabled = false;
3765             }
3766             else
3767             {
3768                 RepliedStatusOpenMenuItem.Enabled = true;
3769             }
3770             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3771             {
3772                 MoveToRTHomeMenuItem.Enabled = false;
3773             }
3774             else
3775             {
3776                 MoveToRTHomeMenuItem.Enabled = true;
3777             }
3778
3779             if (this.ExistCurrentPost)
3780             {
3781                 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3782                 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3783                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3784                 else
3785                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3786             }
3787         }
3788
3789         private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3790         {
3791             MakeReplyOrDirectStatus(false, true);
3792         }
3793
3794         private void DMStripMenuItem_Click(object sender, EventArgs e)
3795         {
3796             MakeReplyOrDirectStatus(false, false);
3797         }
3798
3799         private async Task doStatusDelete()
3800         {
3801             if (this._curTab == null || this._curList == null)
3802                 return;
3803
3804             if (this._curList.SelectedIndices.Count == 0)
3805                 return;
3806
3807             var posts = this._curList.SelectedIndices.Cast<int>()
3808                 .Select(x => this.GetCurTabPost(x))
3809                 .ToArray();
3810
3811             // 選択されたツイートの中に削除可能なものが一つでもあるか
3812             if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3813                 return;
3814
3815             var ret = MessageBox.Show(this,
3816                 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3817                 Properties.Resources.DeleteStripMenuItem_ClickText2,
3818                 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3819
3820             if (ret != DialogResult.OK)
3821                 return;
3822
3823             var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3824
3825             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3826             {
3827                 Exception lastException = null;
3828                 foreach (var post in posts)
3829                 {
3830                     if (!post.CanDeleteBy(this.tw.UserId))
3831                         continue;
3832
3833                     try
3834                     {
3835                         if (post.IsDm)
3836                         {
3837                             await this.twitterApi.DirectMessagesDestroy(post.StatusId)
3838                                 .IgnoreResponse();
3839                         }
3840                         else
3841                         {
3842                             if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3843                                 // 他人に RT された自分のツイート
3844                                 await this.twitterApi.StatusesDestroy(post.RetweetedId.Value)
3845                                     .IgnoreResponse();
3846                             else
3847                                 // 自分のツイート or 自分が RT したツイート
3848                                 await this.twitterApi.StatusesDestroy(post.StatusId)
3849                                     .IgnoreResponse();
3850                         }
3851                     }
3852                     catch (WebApiException ex)
3853                     {
3854                         lastException = ex;
3855                         continue;
3856                     }
3857
3858                     this._statuses.RemovePostFromAllTabs(post.StatusId, setIsDeleted: true);
3859                 }
3860
3861                 if (lastException == null)
3862                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3863                 else
3864                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3865
3866                 this.PurgeListViewItemCache();
3867                 this._curPost = null;
3868                 this._curItemIndex = -1;
3869
3870                 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3871                 {
3872                     var listView = (DetailsListView)tabPage.Tag;
3873                     var tab = this._statuses.Tabs[tabPage.Text];
3874
3875                     using (ControlTransaction.Update(listView))
3876                     {
3877                         listView.VirtualListSize = tab.AllCount;
3878
3879                         if (tabPage == this._curTab)
3880                         {
3881                             listView.SelectedIndices.Clear();
3882
3883                             if (tab.AllCount != 0)
3884                             {
3885                                 int selectedIndex;
3886                                 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3887                                     selectedIndex = focusedIndex;
3888                                 else
3889                                     selectedIndex = tab.AllCount - 1;
3890
3891                                 listView.SelectedIndices.Add(selectedIndex);
3892                                 listView.EnsureVisible(selectedIndex);
3893                                 listView.FocusedItem = listView.Items[selectedIndex];
3894                             }
3895                         }
3896                     }
3897
3898                     if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3899                     {
3900                         if (tabPage.ImageIndex == 0)
3901                             tabPage.ImageIndex = -1; // タブアイコン
3902                     }
3903                 }
3904
3905                 if (!this._cfgCommon.TabIconDisp)
3906                     this.ListTab.Refresh();
3907             }
3908         }
3909
3910         private async void DeleteStripMenuItem_Click(object sender, EventArgs e)
3911         {
3912             await this.doStatusDelete();
3913         }
3914
3915         private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3916         {
3917             using (ControlTransaction.Update(this._curList))
3918             {
3919                 foreach (int idx in _curList.SelectedIndices)
3920                 {
3921                     var post = this._statuses.Tabs[this._curTab.Text][idx];
3922                     this._statuses.SetReadAllTab(post.StatusId, read: true);
3923                     ChangeCacheStyleRead(true, idx);
3924                 }
3925                 ColorizeList();
3926             }
3927             foreach (TabPage tb in ListTab.TabPages)
3928             {
3929                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3930                 {
3931                     if (this._cfgCommon.TabIconDisp)
3932                     {
3933                         if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3934                     }
3935                 }
3936             }
3937             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3938         }
3939
3940         private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3941         {
3942             using (ControlTransaction.Update(this._curList))
3943             {
3944                 foreach (int idx in _curList.SelectedIndices)
3945                 {
3946                     var post = this._statuses.Tabs[this._curTab.Text][idx];
3947                     this._statuses.SetReadAllTab(post.StatusId, read: false);
3948                     ChangeCacheStyleRead(false, idx);
3949                 }
3950                 ColorizeList();
3951             }
3952             foreach (TabPage tb in ListTab.TabPages)
3953             {
3954                 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3955                 {
3956                     if (this._cfgCommon.TabIconDisp)
3957                     {
3958                         if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3959                     }
3960                 }
3961             }
3962             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3963         }
3964
3965         private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
3966         {
3967             await this.DoRefresh();
3968         }
3969
3970         private async Task DoRefresh()
3971         {
3972             if (_curTab != null)
3973             {
3974                 TabModel tab;
3975                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3976                     return;
3977
3978                 switch (_statuses.Tabs[_curTab.Text].TabType)
3979                 {
3980                     case MyCommon.TabUsageType.Mentions:
3981                         await this.GetReplyAsync();
3982                         break;
3983                     case MyCommon.TabUsageType.DirectMessage:
3984                         await this.GetDirectMessagesAsync();
3985                         break;
3986                     case MyCommon.TabUsageType.Favorites:
3987                         await this.GetFavoritesAsync();
3988                         break;
3989                     //case MyCommon.TabUsageType.Profile:
3990                         //// TODO
3991                     case MyCommon.TabUsageType.PublicSearch:
3992                         var searchTab = (PublicSearchTabModel)tab;
3993                         if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
3994                         await this.GetPublicSearchAsync(searchTab);
3995                         break;
3996                     case MyCommon.TabUsageType.UserTimeline:
3997                         await this.GetUserTimelineAsync((UserTimelineTabModel)tab);
3998                         break;
3999                     case MyCommon.TabUsageType.Lists:
4000                         var listTab = (ListTimelineTabModel)tab;
4001                         if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
4002                         await this.GetListTimelineAsync(listTab);
4003                         break;
4004                     default:
4005                         await this.GetHomeTimelineAsync();
4006                         break;
4007                 }
4008             }
4009             else
4010             {
4011                 await this.GetHomeTimelineAsync();
4012             }
4013         }
4014
4015         private async Task DoRefreshMore()
4016         {
4017             //ページ指定をマイナス1に
4018             if (_curTab != null)
4019             {
4020                 TabModel tab;
4021                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4022                     return;
4023
4024                 switch (_statuses.Tabs[_curTab.Text].TabType)
4025                 {
4026                     case MyCommon.TabUsageType.Mentions:
4027                         await this.GetReplyAsync(loadMore: true);
4028                         break;
4029                     case MyCommon.TabUsageType.DirectMessage:
4030                         await this.GetDirectMessagesAsync(loadMore: true);
4031                         break;
4032                     case MyCommon.TabUsageType.Favorites:
4033                         await this.GetFavoritesAsync(loadMore: true);
4034                         break;
4035                     case MyCommon.TabUsageType.Profile:
4036                         //// TODO
4037                         break;
4038                     case MyCommon.TabUsageType.PublicSearch:
4039                         var searchTab = (PublicSearchTabModel)tab;
4040                         if (string.IsNullOrEmpty(searchTab.SearchWords)) return;
4041                         await this.GetPublicSearchAsync(searchTab, loadMore: true);
4042                         break;
4043                     case MyCommon.TabUsageType.UserTimeline:
4044                         await this.GetUserTimelineAsync((UserTimelineTabModel)tab, loadMore: true);
4045                         break;
4046                     case MyCommon.TabUsageType.Lists:
4047                         var listTab = (ListTimelineTabModel)tab;
4048                         if (listTab.ListInfo == null || listTab.ListInfo.Id == 0) return;
4049                         await this.GetListTimelineAsync(listTab, loadMore: true);
4050                         break;
4051                     default:
4052                         await this.GetHomeTimelineAsync(loadMore: true);
4053                         break;
4054                 }
4055             }
4056             else
4057             {
4058                 await this.GetHomeTimelineAsync(loadMore: true);
4059             }
4060         }
4061
4062         private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4063         {
4064             DialogResult result = DialogResult.Abort;
4065
4066             using (var settingDialog = new AppendSettingDialog())
4067             {
4068                 settingDialog.Icon = this.MainIcon;
4069                 settingDialog.Owner = this;
4070                 settingDialog.ShowInTaskbar = showTaskbarIcon;
4071                 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4072
4073                 settingDialog.tw = this.tw;
4074                 settingDialog.twitterApi = this.twitterApi;
4075
4076                 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4077
4078                 try
4079                 {
4080                     result = settingDialog.ShowDialog(this);
4081                 }
4082                 catch (Exception)
4083                 {
4084                     return DialogResult.Abort;
4085                 }
4086
4087                 if (result == DialogResult.OK)
4088                 {
4089                     lock (_syncObject)
4090                     {
4091                         settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4092                     }
4093                 }
4094             }
4095
4096             return result;
4097         }
4098
4099         private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4100         {
4101             // 設定画面表示前のユーザー情報
4102             var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4103
4104             var oldIconSz = this._cfgCommon.IconSize;
4105
4106             if (ShowSettingDialog() == DialogResult.OK)
4107             {
4108                 lock (_syncObject)
4109                 {
4110                     tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4111                     tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4112                     ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4113                     ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4114                     ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4115                     TwitterApiConnection.RestApiBase = this._cfgCommon.TwitterApiBaseUri;
4116
4117                     Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4118                     Networking.SetWebProxy(this._cfgLocal.ProxyType,
4119                         this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4120                         this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4121                     Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
4122
4123                     ImageSelector.Reset(tw, this.tw.Configuration);
4124
4125                     try
4126                     {
4127                         if (this._cfgCommon.TabIconDisp)
4128                         {
4129                             ListTab.DrawItem -= ListTab_DrawItem;
4130                             ListTab.DrawMode = TabDrawMode.Normal;
4131                             ListTab.ImageList = this.TabImage;
4132                         }
4133                         else
4134                         {
4135                             ListTab.DrawItem -= ListTab_DrawItem;
4136                             ListTab.DrawItem += ListTab_DrawItem;
4137                             ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4138                             ListTab.ImageList = null;
4139                         }
4140                     }
4141                     catch (Exception ex)
4142                     {
4143                         ex.Data["Instance"] = "ListTab(TabIconDisp)";
4144                         ex.Data["IsTerminatePermission"] = false;
4145                         throw;
4146                     }
4147
4148                     try
4149                     {
4150                         if (!this._cfgCommon.UnreadManage)
4151                         {
4152                             ReadedStripMenuItem.Enabled = false;
4153                             UnreadStripMenuItem.Enabled = false;
4154                             if (this._cfgCommon.TabIconDisp)
4155                             {
4156                                 foreach (TabPage myTab in ListTab.TabPages)
4157                                 {
4158                                     myTab.ImageIndex = -1;
4159                                 }
4160                             }
4161                         }
4162                         else
4163                         {
4164                             ReadedStripMenuItem.Enabled = true;
4165                             UnreadStripMenuItem.Enabled = true;
4166                         }
4167                     }
4168                     catch (Exception ex)
4169                     {
4170                         ex.Data["Instance"] = "ListTab(UnreadManage)";
4171                         ex.Data["IsTerminatePermission"] = false;
4172                         throw;
4173                     }
4174
4175                     // タブの表示位置の決定
4176                     SetTabAlignment();
4177
4178                     SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4179
4180                     var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4181                     imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4182                     imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4183
4184                     this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4185                     this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4186                     _fntUnread = this._cfgLocal.FontUnread;
4187                     _clUnread = this._cfgLocal.ColorUnread;
4188                     _fntReaded = this._cfgLocal.FontRead;
4189                     _clReaded = this._cfgLocal.ColorRead;
4190                     _clFav = this._cfgLocal.ColorFav;
4191                     _clOWL = this._cfgLocal.ColorOWL;
4192                     _clRetweet = this._cfgLocal.ColorRetweet;
4193                     _fntDetail = this._cfgLocal.FontDetail;
4194                     _clDetail = this._cfgLocal.ColorDetail;
4195                     _clDetailLink = this._cfgLocal.ColorDetailLink;
4196                     _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4197                     _clSelf = this._cfgLocal.ColorSelf;
4198                     _clAtSelf = this._cfgLocal.ColorAtSelf;
4199                     _clTarget = this._cfgLocal.ColorTarget;
4200                     _clAtTarget = this._cfgLocal.ColorAtTarget;
4201                     _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4202                     _clAtTo = this._cfgLocal.ColorAtTo;
4203                     _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4204                     _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4205                     _clInputFont = this._cfgLocal.ColorInputFont;
4206                     _fntInputFont = this._cfgLocal.FontInputFont;
4207                     _brsBackColorMine.Dispose();
4208                     _brsBackColorAt.Dispose();
4209                     _brsBackColorYou.Dispose();
4210                     _brsBackColorAtYou.Dispose();
4211                     _brsBackColorAtFromTarget.Dispose();
4212                     _brsBackColorAtTo.Dispose();
4213                     _brsBackColorNone.Dispose();
4214                     _brsBackColorMine = new SolidBrush(_clSelf);
4215                     _brsBackColorAt = new SolidBrush(_clAtSelf);
4216                     _brsBackColorYou = new SolidBrush(_clTarget);
4217                     _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4218                     _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4219                     _brsBackColorAtTo = new SolidBrush(_clAtTo);
4220                     _brsBackColorNone = new SolidBrush(_clListBackcolor);
4221
4222                     try
4223                     {
4224                         if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4225                         StatusText.Font = _fntInputFont;
4226                         StatusText.ForeColor = _clInputFont;
4227                     }
4228                     catch (Exception ex)
4229                     {
4230                         MessageBox.Show(ex.Message);
4231                     }
4232
4233                     try
4234                     {
4235                         InitDetailHtmlFormat();
4236                     }
4237                     catch (Exception ex)
4238                     {
4239                         ex.Data["Instance"] = "Font";
4240                         ex.Data["IsTerminatePermission"] = false;
4241                         throw;
4242                     }
4243
4244                     try
4245                     {
4246                         foreach (TabPage tb in ListTab.TabPages)
4247                         {
4248                             if (this._cfgCommon.TabIconDisp)
4249                             {
4250                                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4251                                     tb.ImageIndex = -1;
4252                                 else
4253                                     tb.ImageIndex = 0;
4254                             }
4255                         }
4256                     }
4257                     catch (Exception ex)
4258                     {
4259                         ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4260                         ex.Data["IsTerminatePermission"] = false;
4261                         throw;
4262                     }
4263
4264                     try
4265                     {
4266                         var oldIconCol = _iconCol;
4267
4268                         if (this._cfgCommon.IconSize != oldIconSz)
4269                             ApplyListViewIconSize(this._cfgCommon.IconSize);
4270
4271                         foreach (TabPage tp in ListTab.TabPages)
4272                         {
4273                             DetailsListView lst = (DetailsListView)tp.Tag;
4274
4275                             using (ControlTransaction.Update(lst))
4276                             {
4277                                 lst.GridLines = this._cfgCommon.ShowGrid;
4278                                 lst.Font = _fntReaded;
4279                                 lst.BackColor = _clListBackcolor;
4280
4281                                 if (_iconCol != oldIconCol)
4282                                     ResetColumns(lst);
4283                             }
4284                         }
4285                     }
4286                     catch (Exception ex)
4287                     {
4288                         ex.Data["Instance"] = "ListView(IconSize)";
4289                         ex.Data["IsTerminatePermission"] = false;
4290                         throw;
4291                     }
4292
4293                     SetMainWindowTitle();
4294                     SetNotifyIconText();
4295
4296                     this.PurgeListViewItemCache();
4297                     _curList?.Refresh();
4298                     ListTab.Refresh();
4299
4300                     _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4301                     if (this._cfgCommon.HotkeyEnabled)
4302                     {
4303                         ///グローバルホットキーの登録。設定で変更可能にするかも
4304                         HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4305                         if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4306                             modKey |= HookGlobalHotkey.ModKeys.Alt;
4307                         if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4308                             modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4309                         if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4310                             modKey |=  HookGlobalHotkey.ModKeys.Shift;
4311                         if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4312                             modKey |= HookGlobalHotkey.ModKeys.Win;
4313
4314                         _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4315                     }
4316
4317                     if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4318                     try
4319                     {
4320                         StatusText_TextChanged(null, null);
4321                     }
4322                     catch (Exception)
4323                     {
4324                     }
4325                 }
4326             }
4327             else
4328             {
4329                 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4330                 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4331             }
4332
4333             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4334
4335             this.TopMost = this._cfgCommon.AlwaysTop;
4336             SaveConfigsAll(false);
4337
4338             if (tw.Username != oldUser.Username)
4339                 await this.doGetFollowersMenu();
4340         }
4341
4342         /// <summary>
4343         /// タブの表示位置を設定する
4344         /// </summary>
4345         private void SetTabAlignment()
4346         {
4347             var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4348             if (ListTab.Alignment == newAlignment) return;
4349
4350             // 各タブのリスト上の選択位置などを退避
4351             var listSelections = this.SaveListViewSelection();
4352
4353             ListTab.Alignment = newAlignment;
4354
4355             foreach (TabPage tab in ListTab.TabPages)
4356             {
4357                 DetailsListView lst = (DetailsListView)tab.Tag;
4358                 TabModel tabInfo = _statuses.Tabs[tab.Text];
4359                 using (ControlTransaction.Update(lst))
4360                 {
4361                     // 選択位置などを復元
4362                     this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4363                 }
4364             }
4365         }
4366
4367         private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4368         {
4369             // アイコンサイズの再設定
4370             _iconCol = false;
4371             switch (iconSz)
4372             {
4373                 case MyCommon.IconSizes.IconNone:
4374                     _iconSz = 0;
4375                     break;
4376                 case MyCommon.IconSizes.Icon16:
4377                     _iconSz = 16;
4378                     break;
4379                 case MyCommon.IconSizes.Icon24:
4380                     _iconSz = 26;
4381                     break;
4382                 case MyCommon.IconSizes.Icon48:
4383                     _iconSz = 48;
4384                     break;
4385                 case MyCommon.IconSizes.Icon48_2:
4386                     _iconSz = 48;
4387                     _iconCol = true;
4388                     break;
4389             }
4390
4391             if (_iconSz > 0)
4392             {
4393                 // ディスプレイの DPI 設定を考慮したサイズを設定する
4394                 _listViewImageList.ImageSize = new Size(
4395                     1,
4396                     (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4397             }
4398             else
4399             {
4400                 _listViewImageList.ImageSize = new Size(1, 1);
4401             }
4402         }
4403
4404         private void ResetColumns(DetailsListView list)
4405         {
4406             using (ControlTransaction.Update(list))
4407             using (ControlTransaction.Layout(list, false))
4408             {
4409                 // カラムヘッダの再設定
4410                 list.ColumnClick -= MyList_ColumnClick;
4411                 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4412                 list.ColumnReordered -= MyList_ColumnReordered;
4413                 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4414
4415                 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4416                 list.Columns.Clear();
4417                 cols.ForEach(col => col.Dispose());
4418                 cols.Clear();
4419
4420                 InitColumns(list, true);
4421
4422                 list.ColumnClick += MyList_ColumnClick;
4423                 list.DrawColumnHeader += MyList_DrawColumnHeader;
4424                 list.ColumnReordered += MyList_ColumnReordered;
4425                 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4426             }
4427         }
4428
4429         private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4430         {
4431             if (e.Url.AbsoluteUri != "about:blank")
4432             {
4433                 await this.DispSelectedPost();
4434                 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4435             }
4436         }
4437
4438         private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4439         {
4440             if (e.Url.Scheme == "data")
4441             {
4442                 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4443             }
4444             else if (e.Url.AbsoluteUri != "about:blank")
4445             {
4446                 e.Cancel = true;
4447                 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4448                 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4449             }
4450         }
4451
4452         public void AddNewTabForSearch(string searchWord)
4453         {
4454             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4455             foreach (var tb in _statuses.GetTabsByType<PublicSearchTabModel>())
4456             {
4457                 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4458                 {
4459                     foreach (TabPage tp in ListTab.TabPages)
4460                     {
4461                         if (tb.TabName == tp.Text)
4462                         {
4463                             ListTab.SelectedTab = tp;
4464                             return;
4465                         }
4466                     }
4467                 }
4468             }
4469             //ユニークなタブ名生成
4470             string tabName = searchWord;
4471             for (int i = 0; i <= 100; i++)
4472             {
4473                 if (_statuses.ContainsTab(tabName))
4474                     tabName += "_";
4475                 else
4476                     break;
4477             }
4478             //タブ追加
4479             var tab = new PublicSearchTabModel(tabName);
4480             _statuses.AddTab(tab);
4481             AddNewTab(tab, startup: false);
4482             //追加したタブをアクティブに
4483             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4484             //検索条件の設定
4485             ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4486             cmb.Items.Add(searchWord);
4487             cmb.Text = searchWord;
4488             SaveConfigsTabs();
4489             //検索実行
4490             this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4491         }
4492
4493         private void ShowUserTimeline()
4494         {
4495             if (!this.ExistCurrentPost) return;
4496             AddNewTabForUserTimeline(_curPost.ScreenName);
4497         }
4498
4499         private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4500         {
4501             if (e.KeyCode == Keys.Escape)
4502             {
4503                 TabPage relTp = ListTab.SelectedTab;
4504                 RemoveSpecifiedTab(relTp.Text, false);
4505                 SaveConfigsTabs();
4506                 e.SuppressKeyPress = true;
4507             }
4508         }
4509
4510         public void AddNewTabForUserTimeline(string user)
4511         {
4512             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4513             foreach (var tb in _statuses.GetTabsByType<UserTimelineTabModel>())
4514             {
4515                 if (tb.ScreenName == user)
4516                 {
4517                     foreach (TabPage tp in ListTab.TabPages)
4518                     {
4519                         if (tb.TabName == tp.Text)
4520                         {
4521                             ListTab.SelectedTab = tp;
4522                             return;
4523                         }
4524                     }
4525                 }
4526             }
4527             //ユニークなタブ名生成
4528             string tabName = "user:" + user;
4529             while (_statuses.ContainsTab(tabName))
4530             {
4531                 tabName += "_";
4532             }
4533             //タブ追加
4534             var tab = new UserTimelineTabModel(tabName, user);
4535             this._statuses.AddTab(tab);
4536             this.AddNewTab(tab, startup: false);
4537             //追加したタブをアクティブに
4538             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4539             SaveConfigsTabs();
4540             //検索実行
4541             this.GetUserTimelineAsync(tab);
4542         }
4543
4544         public bool AddNewTab(TabModel tab, bool startup)
4545         {
4546             //重複チェック
4547             foreach (TabPage tb in ListTab.TabPages)
4548             {
4549                 if (tb.Text == tab.TabName) return false;
4550             }
4551
4552             //新規タブ名チェック
4553             if (tab.TabName == Properties.Resources.AddNewTabText1) return false;
4554
4555             //タブタイプ重複チェック
4556             if (!startup)
4557             {
4558                 if (tab.IsDefaultTabType || tab.TabType == MyCommon.TabUsageType.Related)
4559                 {
4560                     if (_statuses.GetTabByType(tab.TabType) != null) return false;
4561                 }
4562             }
4563
4564             var _tabPage = new TabPage();
4565             var _listCustom = new DetailsListView();
4566
4567             int cnt = ListTab.TabPages.Count;
4568
4569             ///ToDo:Create and set controls follow tabtypes
4570
4571             using (ControlTransaction.Update(_listCustom))
4572             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4573             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4574             using (ControlTransaction.Layout(this.SplitContainer1, false))
4575             using (ControlTransaction.Layout(this.ListTab, false))
4576             using (ControlTransaction.Layout(this))
4577             using (ControlTransaction.Layout(_tabPage, false))
4578             {
4579                 _tabPage.Controls.Add(_listCustom);
4580
4581                 /// UserTimeline関連
4582                 var userTab = tab as UserTimelineTabModel;
4583                 var listTab = tab as ListTimelineTabModel;
4584                 var searchTab = tab as PublicSearchTabModel;
4585
4586                 if (userTab != null || listTab != null)
4587                 {
4588                     var label = new Label();
4589                     label.Dock = DockStyle.Top;
4590                     label.Name = "labelUser";
4591                     label.TabIndex = 0;
4592
4593                     if (listTab != null)
4594                     {
4595                         label.Text = listTab.ListInfo.ToString();
4596                     }
4597                     else if (userTab != null)
4598                     {
4599                         label.Text = userTab.ScreenName + "'s Timeline";
4600                     }
4601                     label.TextAlign = ContentAlignment.MiddleLeft;
4602                     using (ComboBox tmpComboBox = new ComboBox())
4603                     {
4604                         label.Height = tmpComboBox.Height;
4605                     }
4606                     _tabPage.Controls.Add(label);
4607                 }
4608                 /// 検索関連の準備
4609                 else if (searchTab != null)
4610                 {
4611                     var pnl = new Panel();
4612
4613                     var lbl = new Label();
4614                     var cmb = new ComboBox();
4615                     var btn = new Button();
4616                     var cmbLang = new ComboBox();
4617
4618                     using (ControlTransaction.Layout(pnl, false))
4619                     {
4620                         pnl.Controls.Add(cmb);
4621                         pnl.Controls.Add(cmbLang);
4622                         pnl.Controls.Add(btn);
4623                         pnl.Controls.Add(lbl);
4624                         pnl.Name = "panelSearch";
4625                         pnl.TabIndex = 0;
4626                         pnl.Dock = DockStyle.Top;
4627                         pnl.Height = cmb.Height;
4628                         pnl.Enter += SearchControls_Enter;
4629                         pnl.Leave += SearchControls_Leave;
4630
4631                         cmb.Text = "";
4632                         cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4633                         cmb.Dock = DockStyle.Fill;
4634                         cmb.Name = "comboSearch";
4635                         cmb.DropDownStyle = ComboBoxStyle.DropDown;
4636                         cmb.ImeMode = ImeMode.NoControl;
4637                         cmb.TabStop = false;
4638                         cmb.TabIndex = 1;
4639                         cmb.AutoCompleteMode = AutoCompleteMode.None;
4640                         cmb.KeyDown += SearchComboBox_KeyDown;
4641
4642                         cmbLang.Text = "";
4643                         cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4644                         cmbLang.Dock = DockStyle.Right;
4645                         cmbLang.Width = 50;
4646                         cmbLang.Name = "comboLang";
4647                         cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4648                         cmbLang.TabStop = false;
4649                         cmbLang.TabIndex = 2;
4650                         cmbLang.Items.Add("");
4651                         cmbLang.Items.Add("ja");
4652                         cmbLang.Items.Add("en");
4653                         cmbLang.Items.Add("ar");
4654                         cmbLang.Items.Add("da");
4655                         cmbLang.Items.Add("nl");
4656                         cmbLang.Items.Add("fa");
4657                         cmbLang.Items.Add("fi");
4658                         cmbLang.Items.Add("fr");
4659                         cmbLang.Items.Add("de");
4660                         cmbLang.Items.Add("hu");
4661                         cmbLang.Items.Add("is");
4662                         cmbLang.Items.Add("it");
4663                         cmbLang.Items.Add("no");
4664                         cmbLang.Items.Add("pl");
4665                         cmbLang.Items.Add("pt");
4666                         cmbLang.Items.Add("ru");
4667                         cmbLang.Items.Add("es");
4668                         cmbLang.Items.Add("sv");
4669                         cmbLang.Items.Add("th");
4670
4671                         lbl.Text = "Search(C-S-f)";
4672                         lbl.Name = "label1";
4673                         lbl.Dock = DockStyle.Left;
4674                         lbl.Width = 90;
4675                         lbl.Height = cmb.Height;
4676                         lbl.TextAlign = ContentAlignment.MiddleLeft;
4677                         lbl.TabIndex = 0;
4678
4679                         btn.Text = "Search";
4680                         btn.Name = "buttonSearch";
4681                         btn.UseVisualStyleBackColor = true;
4682                         btn.Dock = DockStyle.Right;
4683                         btn.TabStop = false;
4684                         btn.TabIndex = 3;
4685                         btn.Click += SearchButton_Click;
4686
4687                         if (!string.IsNullOrEmpty(searchTab.SearchWords))
4688                         {
4689                             cmb.Items.Add(searchTab.SearchWords);
4690                             cmb.Text = searchTab.SearchWords;
4691                         }
4692
4693                         cmbLang.Text = searchTab.SearchLang;
4694
4695                         _tabPage.Controls.Add(pnl);
4696                     }
4697                 }
4698
4699                 _tabPage.Tag = _listCustom;
4700                 this.ListTab.Controls.Add(_tabPage);
4701
4702                 _tabPage.Location = new Point(4, 4);
4703                 _tabPage.Name = "CTab" + cnt.ToString();
4704                 _tabPage.Size = new Size(380, 260);
4705                 _tabPage.TabIndex = 2 + cnt;
4706                 _tabPage.Text = tab.TabName;
4707                 _tabPage.UseVisualStyleBackColor = true;
4708                 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4709
4710                 _listCustom.AccessibleName = Properties.Resources.AddNewTab_ListView_AccessibleName;
4711                 _listCustom.TabIndex = 1;
4712                 _listCustom.AllowColumnReorder = true;
4713                 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4714                 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4715                 _listCustom.Dock = DockStyle.Fill;
4716                 _listCustom.FullRowSelect = true;
4717                 _listCustom.HideSelection = false;
4718                 _listCustom.Location = new Point(0, 0);
4719                 _listCustom.Margin = new Padding(0);
4720                 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4721                 _listCustom.ShowItemToolTips = true;
4722                 _listCustom.Size = new Size(380, 260);
4723                 _listCustom.UseCompatibleStateImageBehavior = false;
4724                 _listCustom.View = View.Details;
4725                 _listCustom.OwnerDraw = true;
4726                 _listCustom.VirtualMode = true;
4727                 _listCustom.Font = _fntReaded;
4728                 _listCustom.BackColor = _clListBackcolor;
4729
4730                 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4731                 _listCustom.AllowDrop = true;
4732
4733                 _listCustom.SmallImageList = _listViewImageList;
4734
4735                 InitColumns(_listCustom, startup);
4736
4737                 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4738                 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4739                 _listCustom.ColumnClick += MyList_ColumnClick;
4740                 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4741                 _listCustom.DragDrop += TweenMain_DragDrop;
4742                 _listCustom.DragEnter += TweenMain_DragEnter;
4743                 _listCustom.DragOver += TweenMain_DragOver;
4744                 _listCustom.DrawItem += MyList_DrawItem;
4745                 _listCustom.MouseClick += MyList_MouseClick;
4746                 _listCustom.ColumnReordered += MyList_ColumnReordered;
4747                 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4748                 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4749                 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4750                 _listCustom.DrawSubItem += MyList_DrawSubItem;
4751                 _listCustom.HScrolled += MyList_HScrolled;
4752             }
4753
4754             return true;
4755         }
4756
4757         public bool RemoveSpecifiedTab(string TabName, bool confirm)
4758         {
4759             var tabInfo = _statuses.GetTabByName(TabName);
4760             if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4761
4762             if (confirm)
4763             {
4764                 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4765                 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4766                                  MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4767                 {
4768                     return false;
4769                 }
4770             }
4771
4772             var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4773             if (_tabPage == null) return false;
4774
4775             SetListProperty();   //他のタブに列幅等を反映
4776
4777             //オブジェクトインスタンスの削除
4778             DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4779             _tabPage.Tag = null;
4780
4781             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4782             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4783             using (ControlTransaction.Layout(this.SplitContainer1, false))
4784             using (ControlTransaction.Layout(this.ListTab, false))
4785             using (ControlTransaction.Layout(this))
4786             using (ControlTransaction.Layout(_tabPage, false))
4787             {
4788                 if (this.ListTab.SelectedTab == _tabPage)
4789                 {
4790                     this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4791                     this._beforeSelectedTab = null;
4792                 }
4793                 this.ListTab.Controls.Remove(_tabPage);
4794
4795                 // 後付けのコントロールを破棄
4796                 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4797                 {
4798                     using (Control label = _tabPage.Controls["labelUser"])
4799                     {
4800                         _tabPage.Controls.Remove(label);
4801                     }
4802                 }
4803                 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4804                 {
4805                     using (Control pnl = _tabPage.Controls["panelSearch"])
4806                     {
4807                         pnl.Enter -= SearchControls_Enter;
4808                         pnl.Leave -= SearchControls_Leave;
4809                         _tabPage.Controls.Remove(pnl);
4810
4811                         foreach (Control ctrl in pnl.Controls)
4812                         {
4813                             if (ctrl.Name == "buttonSearch")
4814                             {
4815                                 ctrl.Click -= SearchButton_Click;
4816                             }
4817                             else if (ctrl.Name == "comboSearch")
4818                             {
4819                                 ctrl.KeyDown -= SearchComboBox_KeyDown;
4820                             }
4821                             pnl.Controls.Remove(ctrl);
4822                             ctrl.Dispose();
4823                         }
4824                     }
4825                 }
4826
4827                 _tabPage.Controls.Remove(_listCustom);
4828
4829                 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4830                 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4831                 _listCustom.ColumnClick -= MyList_ColumnClick;
4832                 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4833                 _listCustom.DragDrop -= TweenMain_DragDrop;
4834                 _listCustom.DragEnter -= TweenMain_DragEnter;
4835                 _listCustom.DragOver -= TweenMain_DragOver;
4836                 _listCustom.DrawItem -= MyList_DrawItem;
4837                 _listCustom.MouseClick -= MyList_MouseClick;
4838                 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4839                 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4840                 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4841                 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4842                 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4843                 _listCustom.HScrolled -= MyList_HScrolled;
4844
4845                 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4846                 _listCustom.Columns.Clear();
4847                 cols.ForEach(col => col.Dispose());
4848                 cols.Clear();
4849
4850                 _listCustom.ContextMenuStrip = null;
4851                 _listCustom.ColumnHeaderContextMenuStrip = null;
4852                 _listCustom.Font = null;
4853
4854                 _listCustom.SmallImageList = null;
4855                 _listCustom.ListViewItemSorter = null;
4856
4857                 //キャッシュのクリア
4858                 if (_curTab.Equals(_tabPage))
4859                 {
4860                     _curTab = null;
4861                     _curItemIndex = -1;
4862                     _curList = null;
4863                     _curPost = null;
4864                 }
4865                 this.PurgeListViewItemCache();
4866             }
4867
4868             _tabPage.Dispose();
4869             _listCustom.Dispose();
4870             _statuses.RemoveTab(TabName);
4871
4872             foreach (TabPage tp in ListTab.TabPages)
4873             {
4874                 DetailsListView lst = (DetailsListView)tp.Tag;
4875                 var count = _statuses.Tabs[tp.Text].AllCount;
4876                 if (lst.VirtualListSize != count)
4877                 {
4878                     lst.VirtualListSize = count;
4879                 }
4880             }
4881
4882             return true;
4883         }
4884
4885         private void ListTab_Deselected(object sender, TabControlEventArgs e)
4886         {
4887             this.PurgeListViewItemCache();
4888             _beforeSelectedTab = e.TabPage;
4889         }
4890
4891         private void ListTab_MouseMove(object sender, MouseEventArgs e)
4892         {
4893             //タブのD&D
4894
4895             if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4896             {
4897                 string tn = "";
4898                 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4899                 if (!dragEnableRectangle.Contains(e.Location))
4900                 {
4901                     //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4902                     tn = ListTab.SelectedTab.Text;
4903                 }
4904
4905                 if (string.IsNullOrEmpty(tn)) return;
4906
4907                 foreach (TabPage tb in ListTab.TabPages)
4908                 {
4909                     if (tb.Text == tn)
4910                     {
4911                         ListTab.DoDragDrop(tb, DragDropEffects.All);
4912                         break;
4913                     }
4914                 }
4915             }
4916             else
4917             {
4918                 _tabDrag = false;
4919             }
4920
4921             Point cpos = new Point(e.X, e.Y);
4922             for (int i = 0; i < ListTab.TabPages.Count; i++)
4923             {
4924                 Rectangle rect = ListTab.GetTabRect(i);
4925                 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4926                    rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4927                 {
4928                     _rclickTabName = ListTab.TabPages[i].Text;
4929                     break;
4930                 }
4931             }
4932         }
4933
4934         private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4935         {
4936             //_curList.Refresh();
4937             SetMainWindowTitle();
4938             SetStatusLabelUrl();
4939             SetApiStatusLabel();
4940             if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4941             TabMenuControl(ListTab.SelectedTab.Text);
4942             this.PushSelectPostChain();
4943             await DispSelectedPost();
4944         }
4945
4946         private void SetListProperty()
4947         {
4948             //削除などで見つからない場合は処理せず
4949             if (_curList == null) return;
4950             if (!_isColumnChanged) return;
4951
4952             int[] dispOrder = new int[_curList.Columns.Count];
4953             for (int i = 0; i < _curList.Columns.Count; i++)
4954             {
4955                 for (int j = 0; j < _curList.Columns.Count; j++)
4956                 {
4957                     if (_curList.Columns[j].DisplayIndex == i)
4958                     {
4959                         dispOrder[i] = j;
4960                         break;
4961                     }
4962                 }
4963             }
4964
4965             //列幅、列並びを他のタブに設定
4966             foreach (TabPage tb in ListTab.TabPages)
4967             {
4968                 if (!tb.Equals(_curTab))
4969                 {
4970                     if (tb.Tag != null && tb.Controls.Count > 0)
4971                     {
4972                         DetailsListView lst = (DetailsListView)tb.Tag;
4973                         for (int i = 0; i < lst.Columns.Count; i++)
4974                         {
4975                             lst.Columns[dispOrder[i]].DisplayIndex = i;
4976                             lst.Columns[i].Width = _curList.Columns[i].Width;
4977                         }
4978                     }
4979                 }
4980             }
4981
4982             _isColumnChanged = false;
4983         }
4984
4985         private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
4986         {
4987             try
4988             {
4989                 if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal)
4990                     || PostBrowser.StatusText.StartsWith("ftp", StringComparison.Ordinal)
4991                     || PostBrowser.StatusText.StartsWith("data", StringComparison.Ordinal))
4992                 {
4993                     StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4994                 }
4995                 if (string.IsNullOrEmpty(PostBrowser.StatusText))
4996                 {
4997                     SetStatusLabelUrl();
4998                 }
4999             }
5000             catch (Exception)
5001             {
5002             }
5003         }
5004
5005         private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5006         {
5007             if (e.KeyChar == '@')
5008             {
5009                 if (!this._cfgCommon.UseAtIdSupplement) return;
5010                 //@マーク
5011                 int cnt = AtIdSupl.ItemCount;
5012                 ShowSuplDialog(StatusText, AtIdSupl);
5013                 if (cnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
5014                 e.Handled = true;
5015             }
5016             else if (e.KeyChar == '#')
5017             {
5018                 if (!this._cfgCommon.UseHashSupplement) return;
5019                 ShowSuplDialog(StatusText, HashSupl);
5020                 e.Handled = true;
5021             }
5022         }
5023
5024         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5025         {
5026             ShowSuplDialog(owner, dialog, 0, "");
5027         }
5028
5029         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5030         {
5031             ShowSuplDialog(owner, dialog, offset, "");
5032         }
5033
5034         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5035         {
5036             dialog.StartsWith = startswith;
5037             if (dialog.Visible)
5038             {
5039                 dialog.Focus();
5040             }
5041             else
5042             {
5043                 dialog.ShowDialog();
5044             }
5045             this.TopMost = this._cfgCommon.AlwaysTop;
5046             int selStart = owner.SelectionStart;
5047             string fHalf = "";
5048             string eHalf = "";
5049             if (dialog.DialogResult == DialogResult.OK)
5050             {
5051                 if (!string.IsNullOrEmpty(dialog.inputText))
5052                 {
5053                     if (selStart > 0)
5054                     {
5055                         fHalf = owner.Text.Substring(0, selStart - offset);
5056                     }
5057                     if (selStart < owner.Text.Length)
5058                     {
5059                         eHalf = owner.Text.Substring(selStart);
5060                     }
5061                     owner.Text = fHalf + dialog.inputText + eHalf;
5062                     owner.SelectionStart = selStart + dialog.inputText.Length;
5063                 }
5064             }
5065             else
5066             {
5067                 if (selStart > 0)
5068                 {
5069                     fHalf = owner.Text.Substring(0, selStart);
5070                 }
5071                 if (selStart < owner.Text.Length)
5072                 {
5073                     eHalf = owner.Text.Substring(selStart);
5074                 }
5075                 owner.Text = fHalf + eHalf;
5076                 if (selStart > 0)
5077                 {
5078                     owner.SelectionStart = selStart;
5079                 }
5080             }
5081             owner.Focus();
5082         }
5083
5084         private void StatusText_KeyUp(object sender, KeyEventArgs e)
5085         {
5086             //スペースキーで未読ジャンプ
5087             if (!e.Alt && !e.Control && !e.Shift)
5088             {
5089                 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5090                 {
5091                     bool isSpace = false;
5092                     foreach (char c in StatusText.Text.ToCharArray())
5093                     {
5094                         if (c == ' ' || c == ' ')
5095                         {
5096                             isSpace = true;
5097                         }
5098                         else
5099                         {
5100                             isSpace = false;
5101                             break;
5102                         }
5103                     }
5104                     if (isSpace)
5105                     {
5106                         e.Handled = true;
5107                         StatusText.Text = "";
5108                         JumpUnreadMenuItem_Click(null, null);
5109                     }
5110                 }
5111             }
5112             this.StatusText_TextChanged(null, null);
5113         }
5114
5115         private void StatusText_TextChanged(object sender, EventArgs e)
5116         {
5117             //文字数カウント
5118             int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
5119             lblLen.Text = pLen.ToString();
5120             if (pLen < 0)
5121             {
5122                 StatusText.ForeColor = Color.Red;
5123             }
5124             else
5125             {
5126                 StatusText.ForeColor = _clInputFont;
5127             }
5128             if (string.IsNullOrEmpty(StatusText.Text))
5129             {
5130                 this.inReplyTo = null;
5131             }
5132         }
5133
5134         /// <summary>
5135         /// ツイート投稿前のフッター付与などの前処理を行います
5136         /// </summary>
5137         private string FormatStatusText(string statusText)
5138         {
5139             statusText = statusText.Replace("\r\n", "\n");
5140
5141             if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
5142             {
5143                 // URLと全角文字の切り離し
5144                 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
5145             }
5146
5147             if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
5148             {
5149                 // 文中の全角スペースを半角スペース1個にする
5150                 statusText = statusText.Replace(" ", " ");
5151             }
5152
5153             // DM の場合はこれ以降の処理を行わない
5154             if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
5155                 return statusText;
5156
5157             bool disableFooter;
5158             if (this._cfgCommon.PostShiftEnter)
5159             {
5160                 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5161             }
5162             else
5163             {
5164                 if (this.StatusText.Multiline && !this._cfgCommon.PostCtrlEnter)
5165                     disableFooter = MyCommon.IsKeyDown(Keys.Control);
5166                 else
5167                     disableFooter = MyCommon.IsKeyDown(Keys.Shift);
5168             }
5169
5170             if (statusText.Contains("RT @"))
5171                 disableFooter = true;
5172
5173             var header = "";
5174             var footer = "";
5175
5176             var hashtag = this.HashMgr.UseHash;
5177             if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
5178             {
5179                 if (HashMgr.IsHead)
5180                     header = HashMgr.UseHash + " ";
5181                 else
5182                     footer = " " + HashMgr.UseHash;
5183             }
5184
5185             if (!disableFooter)
5186             {
5187                 if (this._cfgLocal.UseRecommendStatus)
5188                 {
5189                     // 推奨ステータスを使用する
5190                     footer += this.recommendedStatusFooter;
5191                 }
5192                 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
5193                 {
5194                     // テキストボックスに入力されている文字列を使用する
5195                     footer += " " + this._cfgLocal.StatusText.Trim();
5196                 }
5197             }
5198
5199             statusText = header + statusText + footer;
5200
5201             if (this.ToolStripMenuItemPreventSmsCommand.Checked)
5202             {
5203                 // ツイートが意図せず SMS コマンドとして解釈されることを回避 (D, DM, M のみ)
5204                 // 参照: https://support.twitter.com/articles/14020
5205
5206                 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(d|dm|m)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
5207                     && !Twitter.DMSendTextRegex.IsMatch(statusText))
5208                 {
5209                     // U+200B (ZERO WIDTH SPACE) を先頭に加えて回避
5210                     statusText = '\u200b' + statusText;
5211                 }
5212             }
5213
5214             return statusText;
5215         }
5216
5217         /// <summary>
5218         /// 投稿欄に表示する入力可能な文字数を計算します
5219         /// </summary>
5220         private int GetRestStatusCount(string statusText)
5221         {
5222             //文字数カウント
5223             var remainCount = this.tw.GetTextLengthRemain(statusText);
5224
5225             if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
5226             {
5227                 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
5228             }
5229
5230             return remainCount;
5231         }
5232
5233         private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5234         {
5235             if (sender != this._curList)
5236                 return;
5237
5238             var listCache = this._listItemCache;
5239             if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
5240             {
5241                 // If the newly requested cache is a subset of the old cache,
5242                 // no need to rebuild everything, so do nothing.
5243                 return;
5244             }
5245
5246             // Now we need to rebuild the cache.
5247             this.CreateCache(e.StartIndex, e.EndIndex);
5248         }
5249
5250         private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5251         {
5252             var listCache = this._listItemCache;
5253             if (listCache != null && listCache.TargetList == sender)
5254             {
5255                 ListViewItem item;
5256                 PostClass cacheItemPost;
5257                 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
5258                 {
5259                     e.Item = item;
5260                     return;
5261                 }
5262             }
5263
5264             // A cache miss, so create a new ListViewItem and pass it back.
5265             TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5266             try
5267             {
5268                 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5269             }
5270             catch (Exception)
5271             {
5272                 // 不正な要求に対する間に合わせの応答
5273                 string[] sitem = {"", "", "", "", "", "", "", ""};
5274                 e.Item = new ImageListViewItem(sitem);
5275             }
5276         }
5277
5278         private void CreateCache(int startIndex, int endIndex)
5279         {
5280             var tabInfo = this._statuses.Tabs[this._curTab.Text];
5281
5282             if (tabInfo.AllCount == 0)
5283                 return;
5284
5285             // キャッシュ要求(要求範囲±30を作成)
5286             startIndex = Math.Max(startIndex - 30, 0);
5287             endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
5288
5289             var cacheLength = endIndex - startIndex + 1;
5290
5291             var posts = tabInfo[startIndex, endIndex]; //配列で取得
5292             var listItems = Enumerable.Range(0, cacheLength)
5293                 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
5294                 .ToArray();
5295
5296             var listCache = new ListViewItemCache
5297             {
5298                 TargetList = this._curList,
5299                 StartIndex = startIndex,
5300                 EndIndex = endIndex,
5301                 Post = posts,
5302                 ListItem = listItems,
5303             };
5304
5305             Interlocked.Exchange(ref this._listItemCache, listCache);
5306         }
5307
5308         /// <summary>
5309         /// DetailsListView のための ListViewItem のキャッシュを消去する
5310         /// </summary>
5311         private void PurgeListViewItemCache()
5312         {
5313             Interlocked.Exchange(ref this._listItemCache, null);
5314         }
5315
5316         private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5317         {
5318             StringBuilder mk = new StringBuilder();
5319             //if (Post.IsDeleted) mk.Append("×");
5320             //if (Post.IsMark) mk.Append("♪");
5321             //if (Post.IsProtect) mk.Append("Ю");
5322             //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5323             if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5324             ImageListViewItem itm;
5325             if (Post.RetweetedId == null)
5326             {
5327                 string[] sitem= {"",
5328                                  Post.Nickname,
5329                                  Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5330                                  Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5331                                  Post.ScreenName,
5332                                  "",
5333                                  mk.ToString(),
5334                                  Post.Source};
5335                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5336             }
5337             else
5338             {
5339                 string[] sitem = {"",
5340                                   Post.Nickname,
5341                                   Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5342                                   Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5343                                   Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5344                                   "",
5345                                   mk.ToString(),
5346                                   Post.Source};
5347                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5348             }
5349             itm.StateIndex = Post.StateIndex;
5350
5351             bool read = Post.IsRead;
5352             //未読管理していなかったら既読として扱う
5353             if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5354             ChangeItemStyleRead(read, itm, Post, null);
5355             if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5356             return itm;
5357         }
5358
5359         /// <summary>
5360         /// 全てのタブの振り分けルールを反映し直します
5361         /// </summary>
5362         private void ApplyPostFilters()
5363         {
5364             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5365             {
5366                 this.PurgeListViewItemCache();
5367                 this._curPost = null;
5368                 this._curItemIndex = -1;
5369                 this._statuses.FilterAll();
5370
5371                 foreach (TabPage tabPage in this.ListTab.TabPages)
5372                 {
5373                     var tab = this._statuses.Tabs[tabPage.Text];
5374
5375                     var listview = (DetailsListView)tabPage.Tag;
5376                     using (ControlTransaction.Update(listview))
5377                     {
5378                         listview.VirtualListSize = tab.AllCount;
5379                     }
5380
5381                     if (this._cfgCommon.TabIconDisp)
5382                     {
5383                         if (tab.UnreadCount > 0)
5384                             tabPage.ImageIndex = 0;
5385                         else
5386                             tabPage.ImageIndex = -1;
5387                     }
5388                 }
5389
5390                 if (!this._cfgCommon.TabIconDisp)
5391                     this.ListTab.Refresh();
5392
5393                 SetMainWindowTitle();
5394                 SetStatusLabelUrl();
5395             }
5396         }
5397
5398         private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5399         {
5400             e.DrawDefault = true;
5401         }
5402
5403         private void MyList_HScrolled(object sender, EventArgs e)
5404         {
5405             DetailsListView listView = (DetailsListView)sender;
5406             listView.Refresh();
5407         }
5408
5409         private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5410         {
5411             if (e.State == 0) return;
5412             e.DrawDefault = false;
5413
5414             SolidBrush brs2 = null;
5415             if (!e.Item.Selected)     //e.ItemStateでうまく判定できない???
5416             {
5417                 if (e.Item.BackColor == _clSelf)
5418                     brs2 = _brsBackColorMine;
5419                 else if (e.Item.BackColor == _clAtSelf)
5420                     brs2 = _brsBackColorAt;
5421                 else if (e.Item.BackColor == _clTarget)
5422                     brs2 = _brsBackColorYou;
5423                 else if (e.Item.BackColor == _clAtTarget)
5424                     brs2 = _brsBackColorAtYou;
5425                 else if (e.Item.BackColor == _clAtFromTarget)
5426                     brs2 = _brsBackColorAtFromTarget;
5427                 else if (e.Item.BackColor == _clAtTo)
5428                     brs2 = _brsBackColorAtTo;
5429                 else
5430                     brs2 = _brsBackColorNone;
5431             }
5432             else
5433             {
5434                 //選択中の行
5435                 if (((Control)sender).Focused)
5436                     brs2 = _brsHighLight;
5437                 else
5438                     brs2 = _brsDeactiveSelection;
5439             }
5440             e.Graphics.FillRectangle(brs2, e.Bounds);
5441             e.DrawFocusRectangle();
5442             this.DrawListViewItemIcon(e);
5443         }
5444
5445         private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5446         {
5447             if (e.ItemState == 0) return;
5448
5449             if (e.ColumnIndex > 0)
5450             {
5451                 //アイコン以外の列
5452                 RectangleF rct = e.Bounds;
5453                 rct.Width = e.Header.Width;
5454                 int fontHeight = e.Item.Font.Height;
5455                 if (_iconCol)
5456                 {
5457                     rct.Y += fontHeight;
5458                     rct.Height -= fontHeight;
5459                 }
5460
5461                 int heightDiff;
5462                 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5463
5464                 //if (heightDiff > fontHeight * 0.7)
5465                 //{
5466                 //    rct.Height += fontHeight;
5467                 //    drawLineCount += 1;
5468                 //}
5469
5470                 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5471                 if (!_iconCol && drawLineCount <= 1)
5472                 {
5473                     //rct.Inflate(0, heightDiff / -2);
5474                     //rct.Height += fontHeight / 2;
5475                 }
5476                 else if (heightDiff < fontHeight * 0.7)
5477                 {
5478                     //最終行が70%以上欠けていたら、最終行は表示しない
5479                     //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5480                     rct.Height = (fontHeight * drawLineCount) - 1;
5481                 }
5482                 else
5483                 {
5484                     drawLineCount += 1;
5485                 }
5486
5487                 //if (!_iconCol && drawLineCount > 1)
5488                 //{
5489                 //    rct.Y += fontHeight * 0.2;
5490                 //    if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5491                 //}
5492
5493                 if (rct.Width > 0)
5494                 {
5495                     Color color = (!e.Item.Selected) ? e.Item.ForeColor :   //選択されていない行
5496                         (((Control)sender).Focused) ? _clHighLight :        //選択中の行
5497                         _clUnread;
5498
5499                     if (_iconCol)
5500                     {
5501                         Rectangle rctB = e.Bounds;
5502                         rctB.Width = e.Header.Width;
5503                         rctB.Height = fontHeight;
5504
5505                         using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5506                         {
5507                             TextRenderer.DrawText(e.Graphics,
5508                                                     e.Item.SubItems[2].Text,
5509                                                     e.Item.Font,
5510                                                     Rectangle.Round(rct),
5511                                                     color,
5512                                                     TextFormatFlags.WordBreak |
5513                                                     TextFormatFlags.EndEllipsis |
5514                                                     TextFormatFlags.GlyphOverhangPadding |
5515                                                     TextFormatFlags.NoPrefix);
5516                             TextRenderer.DrawText(e.Graphics,
5517                                                     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 + "]",
5518                                                     fnt,
5519                                                     rctB,
5520                                                     color,
5521                                                     TextFormatFlags.SingleLine |
5522                                                     TextFormatFlags.EndEllipsis |
5523                                                     TextFormatFlags.GlyphOverhangPadding |
5524                                                     TextFormatFlags.NoPrefix);
5525                         }
5526                     }
5527                     else if (drawLineCount == 1)
5528                     {
5529                         TextRenderer.DrawText(e.Graphics,
5530                                                 e.SubItem.Text,
5531                                                 e.Item.Font,
5532                                                 Rectangle.Round(rct),
5533                                                 color,
5534                                                 TextFormatFlags.SingleLine |
5535                                                 TextFormatFlags.EndEllipsis |
5536                                                 TextFormatFlags.GlyphOverhangPadding |
5537                                                 TextFormatFlags.NoPrefix |
5538                                                 TextFormatFlags.VerticalCenter);
5539                     }
5540                     else
5541                     {
5542                         TextRenderer.DrawText(e.Graphics,
5543                                                 e.SubItem.Text,
5544                                                 e.Item.Font,
5545                                                 Rectangle.Round(rct),
5546                                                 color,
5547                                                 TextFormatFlags.WordBreak |
5548                                                 TextFormatFlags.EndEllipsis |
5549                                                 TextFormatFlags.GlyphOverhangPadding |
5550                                                 TextFormatFlags.NoPrefix);
5551                     }
5552                     //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5553                 }
5554             }
5555         }
5556
5557         private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5558         {
5559             if (_iconSz == 0) return;
5560
5561             ImageListViewItem item = (ImageListViewItem)e.Item;
5562
5563             //e.Bounds.Leftが常に0を指すから自前で計算
5564             Rectangle itemRect = item.Bounds;
5565             var col0 = e.Item.ListView.Columns[0];
5566             itemRect.Width = col0.Width;
5567
5568             if (col0.DisplayIndex > 0)
5569             {
5570                 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5571                 {
5572                     if (clm.DisplayIndex < col0.DisplayIndex)
5573                         itemRect.X += clm.Width;
5574                 }
5575             }
5576
5577             // ディスプレイの DPI 設定を考慮したアイコンサイズ
5578             var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5579             var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5580
5581             Rectangle iconRect;
5582             var img = item.Image;
5583             if (img != null)
5584             {
5585                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5586                 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5587
5588                 if (iconRect.Width > 0)
5589                 {
5590                     e.Graphics.FillRectangle(Brushes.White, iconRect);
5591                     e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5592                     try
5593                     {
5594                         e.Graphics.DrawImage(img.Image, iconRect);
5595                     }
5596                     catch (ArgumentException)
5597                     {
5598                         item.RefreshImageAsync();
5599                     }
5600                 }
5601             }
5602             else
5603             {
5604                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5605                 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5606
5607                 item.GetImageAsync();
5608             }
5609
5610             if (item.StateIndex > -1)
5611             {
5612                 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5613                 if (stateRect.Width > 0)
5614                 {
5615                     //e.Graphics.FillRectangle(Brushes.White, stateRect);
5616                     //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5617                     e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5618                 }
5619             }
5620         }
5621
5622         protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5623         {
5624             base.ScaleControl(factor, specified);
5625
5626             ScaleChildControl(this.TabImage, factor);
5627
5628             var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5629             var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5630
5631             foreach (var listview in listviews)
5632             {
5633                 ScaleChildControl(listview, factor);
5634             }
5635         }
5636
5637         //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5638         //{
5639         //    ImageListViewItem item = (ImageListViewItem)e.Item;
5640         //    if (item.StateImageIndex > -1)
5641         //    {
5642         //        ////e.Bounds.Leftが常に0を指すから自前で計算
5643         //        //Rectangle itemRect = item.Bounds;
5644         //        //itemRect.Width = e.Item.ListView.Columns[4].Width;
5645
5646         //        //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5647         //        //{
5648         //        //    if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5649         //        //    {
5650         //        //        itemRect.X += clm.Width;
5651         //        //    }
5652         //        //}
5653
5654         //        //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5655         //        //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5656
5657         //        if (rct.Width > 0)
5658         //        {
5659         //            RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5660         //            //e.Graphics.FillRectangle(Brushes.White, rct);
5661         //            //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5662         //            e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5663         //        }
5664         //    }
5665         //}
5666
5667         private void DoTabSearch(string searchWord, bool caseSensitive, bool useRegex, SEARCHTYPE searchType)
5668         {
5669             var tab = this._statuses.Tabs[this._curTab.Text];
5670
5671             if (tab.AllCount == 0)
5672             {
5673                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5674                 return;
5675             }
5676
5677             var selectedIndex = this._curList.SelectedIndices.Count != 0 ? this._curList.SelectedIndices[0] : -1;
5678
5679             int startIndex;
5680             switch (searchType)
5681             {
5682                 case SEARCHTYPE.NextSearch: // 次を検索
5683                     if (selectedIndex != -1)
5684                         startIndex = Math.Min(selectedIndex + 1, tab.AllCount - 1);
5685                     else
5686                         startIndex = 0;
5687                     break;
5688                 case SEARCHTYPE.PrevSearch: // 前を検索
5689                     if (selectedIndex != -1)
5690                         startIndex = Math.Max(selectedIndex - 1, 0);
5691                     else
5692                         startIndex = tab.AllCount - 1;
5693                     break;
5694                 case SEARCHTYPE.DialogSearch: // ダイアログからの検索
5695                 default:
5696                     if (selectedIndex != -1)
5697                         startIndex = selectedIndex;
5698                     else
5699                         startIndex = 0;
5700                     break;
5701             }
5702
5703             Func<string, bool> stringComparer;
5704             try
5705             {
5706                 stringComparer = this.CreateSearchComparer(searchWord, useRegex, caseSensitive);
5707             }
5708             catch (ArgumentException)
5709             {
5710                 MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5711                 return;
5712             }
5713
5714             var reverse = searchType == SEARCHTYPE.PrevSearch;
5715             var foundIndex = tab.SearchPostsAll(stringComparer, startIndex, reverse)
5716                 .DefaultIfEmpty(-1).First();
5717
5718             if (foundIndex == -1)
5719             {
5720                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5721                 return;
5722             }
5723
5724             this.SelectListItem(this._curList, foundIndex);
5725             this._curList.EnsureVisible(foundIndex);
5726         }
5727
5728         private void MenuItemSubSearch_Click(object sender, EventArgs e)
5729         {
5730             // 検索メニュー
5731             this.ShowSearchDialog();
5732         }
5733
5734         private void MenuItemSearchNext_Click(object sender, EventArgs e)
5735         {
5736             var previousSearch = this.SearchDialog.ResultOptions;
5737             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5738             {
5739                 this.SearchDialog.Reset();
5740                 this.ShowSearchDialog();
5741                 return;
5742             }
5743
5744             // 次を検索
5745             this.DoTabSearch(
5746                 previousSearch.Query,
5747                 previousSearch.CaseSensitive,
5748                 previousSearch.UseRegex,
5749                 SEARCHTYPE.NextSearch);
5750         }
5751
5752         private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5753         {
5754             var previousSearch = this.SearchDialog.ResultOptions;
5755             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5756             {
5757                 this.SearchDialog.Reset();
5758                 this.ShowSearchDialog();
5759                 return;
5760             }
5761
5762             // 前を検索
5763             this.DoTabSearch(
5764                 previousSearch.Query,
5765                 previousSearch.CaseSensitive,
5766                 previousSearch.UseRegex,
5767                 SEARCHTYPE.PrevSearch);
5768         }
5769
5770         /// <summary>
5771         /// 検索ダイアログを表示し、検索を実行します
5772         /// </summary>
5773         private void ShowSearchDialog()
5774         {
5775             if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5776             {
5777                 this.TopMost = this._cfgCommon.AlwaysTop;
5778                 return;
5779             }
5780             this.TopMost = this._cfgCommon.AlwaysTop;
5781
5782             var searchOptions = this.SearchDialog.ResultOptions;
5783             if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5784             {
5785                 if (searchOptions.NewTab)
5786                 {
5787                     var tabName = Properties.Resources.SearchResults_TabName;
5788
5789                     try
5790                     {
5791                         tabName = this._statuses.MakeTabName(tabName);
5792                     }
5793                     catch (TabException ex)
5794                     {
5795                         MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5796                     }
5797
5798                     var resultTab = new LocalSearchTabModel(tabName);
5799                     this.AddNewTab(resultTab, startup: false);
5800                     this._statuses.AddTab(resultTab);
5801
5802                     var targetTab = this._statuses.Tabs[this._curTab.Text];
5803
5804                     Func<string, bool> stringComparer;
5805                     try
5806                     {
5807                         stringComparer = this.CreateSearchComparer(searchOptions.Query, searchOptions.UseRegex, searchOptions.CaseSensitive);
5808                     }
5809                     catch (ArgumentException)
5810                     {
5811                         MessageBox.Show(Properties.Resources.DoTabSearchText1, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Error);
5812                         return;
5813                     }
5814
5815                     var foundIndices = targetTab.SearchPostsAll(stringComparer).ToArray();
5816                     if (foundIndices.Length == 0)
5817                     {
5818                         MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5819                         return;
5820                     }
5821
5822                     var foundPosts = foundIndices.Select(x => targetTab[x]);
5823                     foreach (var post in foundPosts)
5824                     {
5825                         resultTab.AddPostQueue(post);
5826                     }
5827
5828                     this._statuses.DistributePosts();
5829                     this.RefreshTimeline();
5830
5831                     var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5832                         .First(x => x.Text == tabName);
5833
5834                     this.ListTab.SelectedTab = tabPage;
5835                 }
5836                 else
5837                 {
5838                     this.DoTabSearch(
5839                         searchOptions.Query,
5840                         searchOptions.CaseSensitive,
5841                         searchOptions.UseRegex,
5842                         SEARCHTYPE.DialogSearch);
5843                 }
5844             }
5845             else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5846             {
5847                 this.AddNewTabForSearch(searchOptions.Query);
5848             }
5849         }
5850
5851         /// <summary>発言検索に使用するメソッドを生成します</summary>
5852         /// <exception cref="ArgumentException">
5853         /// <paramref name="useRegex"/> が true かつ、<paramref name="query"> が不正な正規表現な場合
5854         /// </exception>
5855         private Func<string, bool> CreateSearchComparer(string query, bool useRegex, bool caseSensitive)
5856         {
5857             if (useRegex)
5858             {
5859                 var regexOption = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
5860                 var regex = new Regex(query, regexOption);
5861
5862                 return x => regex.IsMatch(x);
5863             }
5864             else
5865             {
5866                 var comparisonType = caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
5867
5868                 return x => x.IndexOf(query, comparisonType) != -1;
5869             }
5870         }
5871
5872         private void AboutMenuItem_Click(object sender, EventArgs e)
5873         {
5874             using (TweenAboutBox about = new TweenAboutBox())
5875             {
5876                 about.ShowDialog(this);
5877             }
5878             this.TopMost = this._cfgCommon.AlwaysTop;
5879         }
5880
5881         private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5882         {
5883             int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5884             int idx = -1;
5885             DetailsListView lst = null;
5886
5887             if (ImageSelector.Enabled)
5888                 return;
5889
5890             //現在タブから最終タブまで探索
5891             for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5892             {
5893                 //未読Index取得
5894                 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5895                 if (idx > -1)
5896                 {
5897                     ListTab.SelectedIndex = i;
5898                     lst = (DetailsListView)ListTab.TabPages[i].Tag;
5899                     //_curTab = ListTab.TabPages[i];
5900                     break;
5901                 }
5902             }
5903
5904             //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5905             if (idx == -1 && bgnIdx > 0)
5906             {
5907                 for (int i = 0; i < bgnIdx; i++)
5908                 {
5909                     idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5910                     if (idx > -1)
5911                     {
5912                         ListTab.SelectedIndex = i;
5913                         lst = (DetailsListView)ListTab.TabPages[i].Tag;
5914                         //_curTab = ListTab.TabPages[i];
5915                         break;
5916                     }
5917                 }
5918             }
5919
5920             //全部調べたが未読見つからず→先頭タブの最新発言へ
5921             if (idx == -1)
5922             {
5923                 ListTab.SelectedIndex = 0;
5924                 lst = (DetailsListView)ListTab.TabPages[0].Tag;
5925                 //_curTab = ListTab.TabPages[0];
5926                 if (_statuses.SortOrder == SortOrder.Ascending)
5927                     idx = lst.VirtualListSize - 1;
5928                 else
5929                     idx = 0;
5930             }
5931
5932             if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
5933             {
5934                 SelectListItem(lst, idx);
5935                 if (_statuses.SortMode == ComparerMode.Id)
5936                 {
5937                     if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
5938                        _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
5939                     {
5940                         MoveTop();
5941                     }
5942                     else
5943                     {
5944                         lst.EnsureVisible(idx);
5945                     }
5946                 }
5947                 else
5948                 {
5949                     lst.EnsureVisible(idx);
5950                 }
5951             }
5952             lst.Focus();
5953         }
5954
5955         private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
5956         {
5957             if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
5958             {
5959                 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5960                 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
5961             }
5962         }
5963
5964         private async void FavorareMenuItem_Click(object sender, EventArgs e)
5965         {
5966             if (_curList.SelectedIndices.Count > 0)
5967             {
5968                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
5969                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
5970             }
5971         }
5972
5973         private async void VerUpMenuItem_Click(object sender, EventArgs e)
5974         {
5975             await this.CheckNewVersion(false);
5976         }
5977
5978         private void RunTweenUp()
5979         {
5980             ProcessStartInfo pinfo = new ProcessStartInfo();
5981             pinfo.UseShellExecute = true;
5982             pinfo.WorkingDirectory = MyCommon.settingPath;
5983             pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
5984             pinfo.Arguments = "\"" + Application.StartupPath + "\"";
5985             try
5986             {
5987                 Process.Start(pinfo);
5988             }
5989             catch (Exception)
5990             {
5991                 MessageBox.Show("Failed to execute TweenUp3.exe.");
5992             }
5993         }
5994
5995         public class VersionInfo
5996         {
5997             public Version Version { get; set; }
5998             public Uri DownloadUri { get; set; }
5999             public string ReleaseNote { get; set; }
6000         }
6001
6002         /// <summary>
6003         /// OpenTween の最新バージョンの情報を取得します
6004         /// </summary>
6005         public async Task<VersionInfo> GetVersionInfoAsync()
6006         {
6007             var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6008                 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6009
6010             var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6011                 .ConfigureAwait(false);
6012
6013             // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6014             var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6015
6016             var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6017             var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6018
6019             msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6020
6021             return new VersionInfo
6022             {
6023                 Version = Version.Parse(msgHeader[0]),
6024                 DownloadUri = new Uri(msgHeader[1]),
6025                 ReleaseNote = msgBody,
6026             };
6027         }
6028
6029         private async Task CheckNewVersion(bool startup = false)
6030         {
6031             if (ApplicationSettings.VersionInfoUrl == null)
6032                 return; // 更新チェック無効化
6033
6034             try
6035             {
6036                 var versionInfo = await this.GetVersionInfoAsync();
6037
6038                 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6039                 {
6040                     // 更新不要
6041                     if (!startup)
6042                     {
6043                         var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6044                             MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6045                         msgtext = MyCommon.ReplaceAppName(msgtext);
6046
6047                         MessageBox.Show(msgtext,
6048                             MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6049                             MessageBoxButtons.OK, MessageBoxIcon.Information);
6050                     }
6051                     return;
6052                 }
6053
6054                 using (var dialog = new UpdateDialog())
6055                 {
6056                     dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6057                         MyCommon.GetReadableVersion(versionInfo.Version));
6058                     dialog.DetailsText = versionInfo.ReleaseNote;
6059
6060                     if (dialog.ShowDialog(this) == DialogResult.Yes)
6061                     {
6062                         await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
6063                     }
6064                 }
6065             }
6066             catch (Exception)
6067             {
6068                 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6069                 if (!startup)
6070                 {
6071                     MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6072                         MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6073                         MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6074                 }
6075             }
6076         }
6077
6078         private async Task Colorize()
6079         {
6080             _colorize = false;
6081             await this.DispSelectedPost();
6082             //件数関連の場合、タイトル即時書き換え
6083             if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6084                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6085                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6086                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6087             {
6088                 SetMainWindowTitle();
6089             }
6090             if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6091             foreach (TabPage tb in ListTab.TabPages)
6092             {
6093                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6094                 {
6095                     if (this._cfgCommon.TabIconDisp)
6096                     {
6097                         if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6098                     }
6099                 }
6100             }
6101             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6102         }
6103
6104         public string createDetailHtml(string orgdata)
6105         {
6106             if (this._cfgLocal.UseTwemoji)
6107                 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6108
6109             return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6110         }
6111
6112         private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6113         {
6114             if (sender.Equals(displayItem))
6115             {
6116                 this.ClearUserPicture();
6117
6118                 var img = displayItem.Image;
6119                 try
6120                 {
6121                     if (img != null)
6122                         img = await img.CloneAsync();
6123
6124                     UserPicture.Image = img;
6125                 }
6126                 catch (Exception)
6127                 {
6128                     UserPicture.ShowErrorImage();
6129                 }
6130             }
6131         }
6132
6133         private Task DispSelectedPost()
6134         {
6135             return this.DispSelectedPost(false);
6136         }
6137
6138         private PostClass displayPost = new PostClass();
6139
6140         /// <summary>
6141         /// サムネイル表示に使用する CancellationToken の生成元
6142         /// </summary>
6143         private CancellationTokenSource thumbnailTokenSource = null;
6144
6145         private async Task DispSelectedPost(bool forceupdate)
6146         {
6147             if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6148                 return;
6149
6150             var oldDisplayPost = this.displayPost;
6151             this.displayPost = this._curPost;
6152
6153             if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6154                 return;
6155
6156             if (displayItem != null)
6157             {
6158                 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6159                 displayItem = null;
6160             }
6161             displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6162             displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6163
6164             using (ControlTransaction.Update(this.TableLayoutPanel1))
6165             {
6166                 SourceLinkLabel.Text = this._curPost.Source;
6167                 SourceLinkLabel.Tag = this._curPost.SourceUri;
6168                 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6169
6170                 string nameText;
6171                 if (_curPost.IsDm)
6172                 {
6173                     if (_curPost.IsOwl)
6174                         nameText = "DM FROM <- ";
6175                     else
6176                         nameText = "DM TO -> ";
6177                 }
6178                 else
6179                 {
6180                     nameText = "";
6181                 }
6182                 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6183                 if (_curPost.RetweetedId != null)
6184                     nameText += " (RT:" + _curPost.RetweetedBy + ")";
6185
6186                 NameLabel.Text = nameText;
6187                 NameLabel.Tag = _curPost.ScreenName;
6188
6189                 var nameForeColor = SystemColors.ControlText;
6190                 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6191                     nameForeColor = this._clOWL;
6192                 if (_curPost.RetweetedId != null)
6193                     nameForeColor = this._clRetweet;
6194                 if (_curPost.IsFav)
6195                     nameForeColor = this._clFav;
6196                 NameLabel.ForeColor = nameForeColor;
6197
6198                 this.ClearUserPicture();
6199
6200                 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6201                 {
6202                     var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6203                     try
6204                     {
6205                         UserPicture.Image = image?.Clone();
6206                     }
6207                     catch (Exception)
6208                     {
6209                         UserPicture.ShowErrorImage();
6210                     }
6211                 }
6212
6213                 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6214             }
6215
6216             if (DumpPostClassToolStripMenuItem.Checked)
6217             {
6218                 StringBuilder sb = new StringBuilder(512);
6219
6220                 sb.Append("-----Start PostClass Dump<br>");
6221                 sb.AppendFormat("TextFromApi           : {0}<br>", _curPost.TextFromApi);
6222                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6223                 sb.AppendFormat("StatusId             : {0}<br>", _curPost.StatusId.ToString());
6224                 //sb.AppendFormat("ImageIndex     : {0}<br>", _curPost.ImageIndex.ToString());
6225                 sb.AppendFormat("ImageUrl       : {0}<br>", _curPost.ImageUrl);
6226                 sb.AppendFormat("InReplyToStatusId    : {0}<br>", _curPost.InReplyToStatusId.ToString());
6227                 sb.AppendFormat("InReplyToUser  : {0}<br>", _curPost.InReplyToUser);
6228                 sb.AppendFormat("IsDM           : {0}<br>", _curPost.IsDm.ToString());
6229                 sb.AppendFormat("IsFav          : {0}<br>", _curPost.IsFav.ToString());
6230                 sb.AppendFormat("IsMark         : {0}<br>", _curPost.IsMark.ToString());
6231                 sb.AppendFormat("IsMe           : {0}<br>", _curPost.IsMe.ToString());
6232                 sb.AppendFormat("IsOwl          : {0}<br>", _curPost.IsOwl.ToString());
6233                 sb.AppendFormat("IsProtect      : {0}<br>", _curPost.IsProtect.ToString());
6234                 sb.AppendFormat("IsRead         : {0}<br>", _curPost.IsRead.ToString());
6235                 sb.AppendFormat("IsReply        : {0}<br>", _curPost.IsReply.ToString());
6236
6237                 foreach (string nm in _curPost.ReplyToList)
6238                 {
6239                     sb.AppendFormat("ReplyToList    : {0}<br>", nm);
6240                 }
6241
6242                 sb.AppendFormat("ScreenName           : {0}<br>", _curPost.ScreenName);
6243                 sb.AppendFormat("NickName       : {0}<br>", _curPost.Nickname);
6244                 sb.AppendFormat("Text   : {0}<br>", _curPost.Text);
6245                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.Text);
6246                 sb.AppendFormat("CreatedAt          : {0}<br>", _curPost.CreatedAt.ToString());
6247                 sb.AppendFormat("Source         : {0}<br>", _curPost.Source);
6248                 sb.AppendFormat("UserId            : {0}<br>", _curPost.UserId);
6249                 sb.AppendFormat("FilterHit      : {0}<br>", _curPost.FilterHit);
6250                 sb.AppendFormat("RetweetedBy    : {0}<br>", _curPost.RetweetedBy);
6251                 sb.AppendFormat("RetweetedId    : {0}<br>", _curPost.RetweetedId);
6252
6253                 sb.AppendFormat("Media.Count    : {0}<br>", _curPost.Media.Count);
6254                 if (_curPost.Media.Count > 0)
6255                 {
6256                     for (int i = 0; i < _curPost.Media.Count; i++)
6257                     {
6258                         var info = _curPost.Media[i];
6259                         sb.AppendFormat("Media[{0}].Url         : {1}<br>", i, info.Url);
6260                         sb.AppendFormat("Media[{0}].VideoUrl    : {1}<br>", i, info.VideoUrl ?? "---");
6261                     }
6262                 }
6263                 sb.Append("-----End PostClass Dump<br>");
6264
6265                 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6266                 return;
6267             }
6268
6269             var loadTasks = new List<Task>();
6270
6271             // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6272             // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6273             if (_curPost.StatusId != oldDisplayPost.StatusId)
6274             {
6275                 using (ControlTransaction.Update(this.PostBrowser))
6276                 {
6277                     this.PostBrowser.DocumentText =
6278                         this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6279
6280                     this.PostBrowser.Document.Window.ScrollTo(0, 0);
6281                 }
6282
6283                 this.SplitContainer3.Panel2Collapsed = true;
6284
6285                 if (this._cfgCommon.PreviewEnable)
6286                 {
6287                     var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
6288                     oldTokenSource?.Cancel();
6289
6290                     var token = this.thumbnailTokenSource.Token;
6291                     loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
6292                 }
6293
6294                 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
6295             }
6296
6297             try
6298             {
6299                 await Task.WhenAll(loadTasks);
6300             }
6301             catch (OperationCanceledException) { }
6302         }
6303
6304         /// <summary>
6305         /// 発言詳細欄のツイートURLを展開する
6306         /// </summary>
6307         private async Task AppendQuoteTweetAsync(PostClass post)
6308         {
6309             var quoteStatusIds = post.QuoteStatusIds;
6310             if (quoteStatusIds.Length == 0 && post.InReplyToStatusId == null)
6311                 return;
6312
6313             // 「読み込み中」テキストを表示
6314             var loadingQuoteHtml = quoteStatusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText, isReply: false));
6315
6316             var loadingReplyHtml = string.Empty;
6317             if (post.InReplyToStatusId != null)
6318                 loadingReplyHtml = FormatQuoteTweetHtml(post.InReplyToStatusId.Value, Properties.Resources.LoadingText, isReply: true);
6319
6320             var body = post.Text + string.Concat(loadingQuoteHtml) + loadingReplyHtml;
6321
6322             using (ControlTransaction.Update(this.PostBrowser))
6323                 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6324
6325             // 引用ツイートを読み込み
6326             var loadTweetTasks = quoteStatusIds.Select(x => this.CreateQuoteTweetHtml(x, isReply: false)).ToList();
6327
6328             if (post.InReplyToStatusId != null)
6329                 loadTweetTasks.Add(this.CreateQuoteTweetHtml(post.InReplyToStatusId.Value, isReply: true));
6330
6331             var quoteHtmls = await Task.WhenAll(loadTweetTasks);
6332
6333             // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
6334             if (this._curPost != post || this._curPost.IsDeleted)
6335                 return;
6336
6337             body = post.Text + string.Concat(quoteHtmls);
6338
6339             using (ControlTransaction.Update(this.PostBrowser))
6340                 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6341         }
6342
6343         private async Task<string> CreateQuoteTweetHtml(long statusId, bool isReply)
6344         {
6345             PostClass post = this._statuses[statusId];
6346             if (post == null)
6347             {
6348                 try
6349                 {
6350                     post = await this.tw.GetStatusApi(false, statusId)
6351                         .ConfigureAwait(false);
6352                 }
6353                 catch (WebApiException ex)
6354                 {
6355                     return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode($"Err:{ex.Message}(GetStatus)"), isReply);
6356                 }
6357
6358                 post.IsRead = true;
6359                 if (!this._statuses.AddQuoteTweet(post))
6360                     return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.", isReply);
6361             }
6362
6363             return FormatQuoteTweetHtml(post, isReply);
6364         }
6365
6366         internal static string FormatQuoteTweetHtml(PostClass post, bool isReply)
6367         {
6368             var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6369                 " &mdash; " + WebUtility.HtmlEncode(post.Nickname) +
6370                 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6371                 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6372
6373             return FormatQuoteTweetHtml(post.StatusId, innerHtml, isReply);
6374         }
6375
6376         internal static string FormatQuoteTweetHtml(long statusId, string innerHtml, bool isReply)
6377         {
6378             var blockClassName = "quote-tweet";
6379
6380             if (isReply)
6381                 blockClassName += " reply";
6382
6383             return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6384                 $"<blockquote class=\"{blockClassName}\">{innerHtml}</blockquote>" +
6385                 "</a>";
6386         }
6387
6388         /// <summary>
6389         /// 指定されたHTMLからリンクを除去します
6390         /// </summary>
6391         internal static string StripLinkTagHtml(string html)
6392         {
6393             // a 要素はネストされていない前提の正規表現パターン
6394             return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6395         }
6396
6397         private async void MatomeMenuItem_Click(object sender, EventArgs e)
6398         {
6399             await this.OpenApplicationWebsite();
6400         }
6401
6402         private async Task OpenApplicationWebsite()
6403         {
6404             await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6405         }
6406
6407         private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6408         {
6409             await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6410         }
6411
6412         private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6413         {
6414             if (ListTab.SelectedTab != null)
6415             {
6416                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6417                 {
6418                     Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6419                     if (pnl.Controls["comboSearch"].Focused ||
6420                         pnl.Controls["comboLang"].Focused ||
6421                         pnl.Controls["buttonSearch"].Focused) return;
6422                 }
6423
6424                 if (e.Control || e.Shift || e.Alt)
6425                     this._anchorFlag = false;
6426
6427                 Task asyncTask;
6428                 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6429                 {
6430                     e.Handled = true;
6431                     e.SuppressKeyPress = true;
6432                 }
6433
6434                 if (asyncTask != null)
6435                     await asyncTask;
6436             }
6437         }
6438
6439         private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6440
6441         private void InitializeShortcuts()
6442         {
6443             this.shortcutCommands = new[]
6444             {
6445                 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6446                 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6447                     .FocusedOn(FocusedControl.ListTab)
6448                     .Do(() => SendKeys.Send("{DOWN}")),
6449
6450                 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6451                     .FocusedOn(FocusedControl.ListTab)
6452                     .Do(() => SendKeys.Send("{UP}")),
6453
6454                 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6455                     .FocusedOn(FocusedControl.ListTab)
6456                     .Do(() => SendKeys.Send("{PGDN}")),
6457
6458                 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6459                     .FocusedOn(FocusedControl.ListTab)
6460                     .Do(() => SendKeys.Send("{PGUP}")),
6461
6462                 ShortcutCommand.Create(Keys.F1)
6463                     .Do(() => this.OpenApplicationWebsite()),
6464
6465                 ShortcutCommand.Create(Keys.F3)
6466                     .Do(() => this.MenuItemSearchNext_Click(null, null)),
6467
6468                 ShortcutCommand.Create(Keys.F5)
6469                     .Do(() => this.DoRefresh()),
6470
6471                 ShortcutCommand.Create(Keys.F6)
6472                     .Do(() => this.GetReplyAsync()),
6473
6474                 ShortcutCommand.Create(Keys.F7)
6475                     .Do(() => this.GetDirectMessagesAsync()),
6476
6477                 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6478                     .NotFocusedOn(FocusedControl.StatusText)
6479                     .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6480
6481                 ShortcutCommand.Create(Keys.G)
6482                     .NotFocusedOn(FocusedControl.StatusText)
6483                     .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6484
6485                 ShortcutCommand.Create(Keys.Right, Keys.N)
6486                     .FocusedOn(FocusedControl.ListTab)
6487                     .Do(() => this.GoRelPost(forward: true)),
6488
6489                 ShortcutCommand.Create(Keys.Left, Keys.P)
6490                     .FocusedOn(FocusedControl.ListTab)
6491                     .Do(() => this.GoRelPost(forward: false)),
6492
6493                 ShortcutCommand.Create(Keys.OemPeriod)
6494                     .FocusedOn(FocusedControl.ListTab)
6495                     .Do(() => this.GoAnchor()),
6496
6497                 ShortcutCommand.Create(Keys.I)
6498                     .FocusedOn(FocusedControl.ListTab)
6499                     .OnlyWhen(() => this.StatusText.Enabled)
6500                     .Do(() => this.StatusText.Focus()),
6501
6502                 ShortcutCommand.Create(Keys.Enter)
6503                     .FocusedOn(FocusedControl.ListTab)
6504                     .Do(() => this.MakeReplyOrDirectStatus()),
6505
6506                 ShortcutCommand.Create(Keys.R)
6507                     .FocusedOn(FocusedControl.ListTab)
6508                     .Do(() => this.DoRefresh()),
6509
6510                 ShortcutCommand.Create(Keys.L)
6511                     .FocusedOn(FocusedControl.ListTab)
6512                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6513
6514                 ShortcutCommand.Create(Keys.H)
6515                     .FocusedOn(FocusedControl.ListTab)
6516                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6517
6518                 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6519                     .FocusedOn(FocusedControl.ListTab)
6520                     .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6521
6522                 ShortcutCommand.Create(Keys.S)
6523                     .FocusedOn(FocusedControl.ListTab)
6524                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6525
6526                 ShortcutCommand.Create(Keys.A)
6527                     .FocusedOn(FocusedControl.ListTab)
6528                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6529
6530                 // ] in_reply_to参照元へ戻る
6531                 ShortcutCommand.Create(Keys.Oem4)
6532                     .FocusedOn(FocusedControl.ListTab)
6533                     .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6534
6535                 // [ in_reply_toへジャンプ
6536                 ShortcutCommand.Create(Keys.Oem6)
6537                     .FocusedOn(FocusedControl.ListTab)
6538                     .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6539
6540                 ShortcutCommand.Create(Keys.Escape)
6541                     .FocusedOn(FocusedControl.ListTab)
6542                     .Do(() => {
6543                         this._anchorFlag = false;
6544                         if (ListTab.SelectedTab != null)
6545                         {
6546                             var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6547                             if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6548                             {
6549                                 var relTp = ListTab.SelectedTab;
6550                                 RemoveSpecifiedTab(relTp.Text, false);
6551                                 SaveConfigsTabs();
6552                             }
6553                         }
6554                     }),
6555
6556                 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6557                 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6558                     .FocusedOn(FocusedControl.ListTab)
6559                     .Do(() => this._anchorFlag = false, preventDefault: false),
6560
6561                 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6562                 ShortcutCommand.Create(Keys.Up, Keys.Down)
6563                     .FocusedOn(FocusedControl.PostBrowser)
6564                     .Do(() => { }),
6565
6566                 ShortcutCommand.Create(Keys.Control | Keys.R)
6567                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6568
6569                 ShortcutCommand.Create(Keys.Control | Keys.D)
6570                     .Do(() => this.doStatusDelete()),
6571
6572                 ShortcutCommand.Create(Keys.Control | Keys.M)
6573                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6574
6575                 ShortcutCommand.Create(Keys.Control | Keys.S)
6576                     .Do(() => this.FavoriteChange(FavAdd: true)),
6577
6578                 ShortcutCommand.Create(Keys.Control | Keys.I)
6579                     .Do(() => this.doRepliedStatusOpen()),
6580
6581                 ShortcutCommand.Create(Keys.Control | Keys.Q)
6582                     .Do(() => this.doQuoteOfficial()),
6583
6584                 ShortcutCommand.Create(Keys.Control | Keys.B)
6585                     .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6586
6587                 ShortcutCommand.Create(Keys.Control | Keys.T)
6588                     .Do(() => this.HashManageMenuItem_Click(null, null)),
6589
6590                 ShortcutCommand.Create(Keys.Control | Keys.L)
6591                     .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6592
6593                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6594                     .NotFocusedOn(FocusedControl.PostBrowser)
6595                     .Do(() => this.MultiLineMenuItem_Click(null, null)),
6596
6597                 ShortcutCommand.Create(Keys.Control | Keys.F)
6598                     .Do(() => this.MenuItemSubSearch_Click(null, null)),
6599
6600                 ShortcutCommand.Create(Keys.Control | Keys.U)
6601                     .Do(() => this.ShowUserTimeline()),
6602
6603                 ShortcutCommand.Create(Keys.Control | Keys.H)
6604                     .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6605
6606                 ShortcutCommand.Create(Keys.Control | Keys.G)
6607                     .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6608
6609                 ShortcutCommand.Create(Keys.Control | Keys.O)
6610                     .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6611
6612                 ShortcutCommand.Create(Keys.Control | Keys.E)
6613                     .Do(() => this.OpenURLMenuItem_Click(null, null)),
6614
6615                 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6616                     .FocusedOn(FocusedControl.ListTab)
6617                     .Do(() => this._colorize = true, preventDefault: false),
6618
6619                 ShortcutCommand.Create(Keys.Control | Keys.N)
6620                     .FocusedOn(FocusedControl.ListTab)
6621                     .Do(() => this.GoNextTab(forward: true)),
6622
6623                 ShortcutCommand.Create(Keys.Control | Keys.P)
6624                     .FocusedOn(FocusedControl.ListTab)
6625                     .Do(() => this.GoNextTab(forward: false)),
6626
6627                 ShortcutCommand.Create(Keys.Control | Keys.C, Keys.Control | Keys.Insert)
6628                     .FocusedOn(FocusedControl.ListTab)
6629                     .Do(() => this.CopyStot()),
6630
6631                 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6632                 ShortcutCommand.Create(Keys.Control | Keys.D1)
6633                     .FocusedOn(FocusedControl.ListTab)
6634                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6635                     .Do(() => this.ListTab.SelectedIndex = 0),
6636
6637                 ShortcutCommand.Create(Keys.Control | Keys.D2)
6638                     .FocusedOn(FocusedControl.ListTab)
6639                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6640                     .Do(() => this.ListTab.SelectedIndex = 1),
6641
6642                 ShortcutCommand.Create(Keys.Control | Keys.D3)
6643                     .FocusedOn(FocusedControl.ListTab)
6644                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6645                     .Do(() => this.ListTab.SelectedIndex = 2),
6646
6647                 ShortcutCommand.Create(Keys.Control | Keys.D4)
6648                     .FocusedOn(FocusedControl.ListTab)
6649                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6650                     .Do(() => this.ListTab.SelectedIndex = 3),
6651
6652                 ShortcutCommand.Create(Keys.Control | Keys.D5)
6653                     .FocusedOn(FocusedControl.ListTab)
6654                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6655                     .Do(() => this.ListTab.SelectedIndex = 4),
6656
6657                 ShortcutCommand.Create(Keys.Control | Keys.D6)
6658                     .FocusedOn(FocusedControl.ListTab)
6659                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6660                     .Do(() => this.ListTab.SelectedIndex = 5),
6661
6662                 ShortcutCommand.Create(Keys.Control | Keys.D7)
6663                     .FocusedOn(FocusedControl.ListTab)
6664                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6665                     .Do(() => this.ListTab.SelectedIndex = 6),
6666
6667                 ShortcutCommand.Create(Keys.Control | Keys.D8)
6668                     .FocusedOn(FocusedControl.ListTab)
6669                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6670                     .Do(() => this.ListTab.SelectedIndex = 7),
6671
6672                 ShortcutCommand.Create(Keys.Control | Keys.D9)
6673                     .FocusedOn(FocusedControl.ListTab)
6674                     .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6675
6676                 ShortcutCommand.Create(Keys.Control | Keys.A)
6677                     .FocusedOn(FocusedControl.StatusText)
6678                     .Do(() => this.StatusText.SelectAll()),
6679
6680                 ShortcutCommand.Create(Keys.Control | Keys.V)
6681                     .FocusedOn(FocusedControl.StatusText)
6682                     .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6683
6684                 ShortcutCommand.Create(Keys.Control | Keys.Up)
6685                     .FocusedOn(FocusedControl.StatusText)
6686                     .Do(() => {
6687                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6688                         {
6689                             var inReplyToStatusId = this.inReplyTo?.Item1;
6690                             var inReplyToScreenName = this.inReplyTo?.Item2;
6691                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6692                         }
6693                         _hisIdx -= 1;
6694                         if (_hisIdx < 0) _hisIdx = 0;
6695
6696                         var historyItem = this._history[this._hisIdx];
6697                         StatusText.Text = historyItem.status;
6698                         StatusText.SelectionStart = StatusText.Text.Length;
6699                         if (historyItem.inReplyToId != null)
6700                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6701                         else
6702                             this.inReplyTo = null;
6703                     }),
6704
6705                 ShortcutCommand.Create(Keys.Control | Keys.Down)
6706                     .FocusedOn(FocusedControl.StatusText)
6707                     .Do(() => {
6708                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6709                         {
6710                             var inReplyToStatusId = this.inReplyTo?.Item1;
6711                             var inReplyToScreenName = this.inReplyTo?.Item2;
6712                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6713                         }
6714                         _hisIdx += 1;
6715                         if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6716
6717                         var historyItem = this._history[this._hisIdx];
6718                         StatusText.Text = historyItem.status;
6719                         StatusText.SelectionStart = StatusText.Text.Length;
6720                         if (historyItem.inReplyToId != null)
6721                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6722                         else
6723                             this.inReplyTo = null;
6724                     }),
6725
6726                 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6727                     .FocusedOn(FocusedControl.StatusText)
6728                     .Do(() => {
6729                         if (ListTab.SelectedIndex == 0)
6730                         {
6731                             ListTab.SelectedIndex = ListTab.TabCount - 1;
6732                         }
6733                         else
6734                         {
6735                             ListTab.SelectedIndex -= 1;
6736                         }
6737                         StatusText.Focus();
6738                     }),
6739
6740                 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6741                     .FocusedOn(FocusedControl.StatusText)
6742                     .Do(() => {
6743                         if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6744                         {
6745                             ListTab.SelectedIndex = 0;
6746                         }
6747                         else
6748                         {
6749                             ListTab.SelectedIndex += 1;
6750                         }
6751                         StatusText.Focus();
6752                     }),
6753
6754                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6755                     .FocusedOn(FocusedControl.PostBrowser)
6756                     .Do(() => {
6757                         MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6758                         MultiLineMenuItem_Click(null, null);
6759                     }),
6760
6761                 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6762                     .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6763
6764                 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6765                     .Do(() => this.DoRefreshMore()),
6766
6767                 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6768                     .Do(() => this.GetReplyAsync(loadMore: true)),
6769
6770                 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6771                     .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6772
6773                 ShortcutCommand.Create(Keys.Shift | Keys.R)
6774                     .NotFocusedOn(FocusedControl.StatusText)
6775                     .Do(() => this.DoRefreshMore()),
6776
6777                 ShortcutCommand.Create(Keys.Shift | Keys.H)
6778                     .FocusedOn(FocusedControl.ListTab)
6779                     .Do(() => this.GoTopEnd(GoTop: true)),
6780
6781                 ShortcutCommand.Create(Keys.Shift | Keys.L)
6782                     .FocusedOn(FocusedControl.ListTab)
6783                     .Do(() => this.GoTopEnd(GoTop: false)),
6784
6785                 ShortcutCommand.Create(Keys.Shift | Keys.M)
6786                     .FocusedOn(FocusedControl.ListTab)
6787                     .Do(() => this.GoMiddle()),
6788
6789                 ShortcutCommand.Create(Keys.Shift | Keys.G)
6790                     .FocusedOn(FocusedControl.ListTab)
6791                     .Do(() => this.GoLast()),
6792
6793                 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6794                     .FocusedOn(FocusedControl.ListTab)
6795                     .Do(() => this.MoveMiddle()),
6796
6797                 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6798                     .FocusedOn(FocusedControl.ListTab)
6799                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6800
6801                 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6802                     .FocusedOn(FocusedControl.ListTab)
6803                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6804
6805                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6806                 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6807                     .FocusedOn(FocusedControl.ListTab)
6808                     .Do(() => this.GoFav(forward: true)),
6809
6810                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6811                 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6812                     .FocusedOn(FocusedControl.ListTab)
6813                     .Do(() => this.GoFav(forward: false)),
6814
6815                 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6816                     .FocusedOn(FocusedControl.ListTab)
6817                     .Do(() => this.GoBackSelectPostChain()),
6818
6819                 ShortcutCommand.Create(Keys.Alt | Keys.R)
6820                     .Do(() => this.doReTweetOfficial(isConfirm: true)),
6821
6822                 ShortcutCommand.Create(Keys.Alt | Keys.P)
6823                     .OnlyWhen(() => this._curPost != null)
6824                     .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6825
6826                 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6827                     .Do(() => this.ScrollDownPostBrowser(forward: false)),
6828
6829                 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6830                     .Do(() => this.ScrollDownPostBrowser(forward: true)),
6831
6832                 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6833                     .Do(() => this.PageDownPostBrowser(forward: false)),
6834
6835                 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6836                     .Do(() => this.PageDownPostBrowser(forward: true)),
6837
6838                 // 別タブの同じ書き込みへ(ALT+←/→)
6839                 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6840                     .FocusedOn(FocusedControl.ListTab)
6841                     .Do(() => this.GoSamePostToAnotherTab(left: false)),
6842
6843                 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6844                     .FocusedOn(FocusedControl.ListTab)
6845                     .Do(() => this.GoSamePostToAnotherTab(left: true)),
6846
6847                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6848                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6849
6850                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C, Keys.Control | Keys.Shift | Keys.Insert)
6851                     .Do(() => this.CopyIdUri()),
6852
6853                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6854                     .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6855                         this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6856                     .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6857
6858                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6859                     .Do(() => this.FavoriteChange(FavAdd: false)),
6860
6861                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6862                     .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6863
6864                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6865                     .Do(() => this.HashToggleMenuItem_Click(null, null)),
6866
6867                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6868                     .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6869
6870                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6871                     .Do(() => this.doMoveToRTHome()),
6872
6873                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6874                     .Do(() => this.FavorareMenuItem_Click(null, null)),
6875
6876                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6877                     .FocusedOn(FocusedControl.StatusText)
6878                     .Do(() => {
6879                         if (_curList != null && _curList.VirtualListSize != 0 &&
6880                                     _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6881                         {
6882                             var idx = _curList.SelectedIndices[0] - 1;
6883                             SelectListItem(_curList, idx);
6884                             _curList.EnsureVisible(idx);
6885                         }
6886                     }),
6887
6888                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6889                     .FocusedOn(FocusedControl.StatusText)
6890                     .Do(() => {
6891                         if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6892                                     && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6893                         {
6894                             var idx = _curList.SelectedIndices[0] + 1;
6895                             SelectListItem(_curList, idx);
6896                             _curList.EnsureVisible(idx);
6897                         }
6898                     }),
6899
6900                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6901                     .FocusedOn(FocusedControl.StatusText)
6902                     .Do(() => {
6903                         if (StatusText.SelectionStart > 0)
6904                         {
6905                             int endidx = StatusText.SelectionStart - 1;
6906                             string startstr = "";
6907                             for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6908                             {
6909                                 char c = StatusText.Text[i];
6910                                 if (Char.IsLetterOrDigit(c) || c == '_')
6911                                 {
6912                                     continue;
6913                                 }
6914                                 if (c == '@')
6915                                 {
6916                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6917                                     int cnt = AtIdSupl.ItemCount;
6918                                     ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6919                                     if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
6920                                 }
6921                                 else if (c == '#')
6922                                 {
6923                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6924                                     ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6925                                 }
6926                                 else
6927                                 {
6928                                     break;
6929                                 }
6930                             }
6931                         }
6932                     }),
6933
6934                 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
6935                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
6936                     .FocusedOn(FocusedControl.ListTab)
6937                     .Do(() => this.SetSortColumnByDisplayIndex(0)),
6938
6939                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
6940                     .FocusedOn(FocusedControl.ListTab)
6941                     .Do(() => this.SetSortColumnByDisplayIndex(1)),
6942
6943                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
6944                     .FocusedOn(FocusedControl.ListTab)
6945                     .Do(() => this.SetSortColumnByDisplayIndex(2)),
6946
6947                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
6948                     .FocusedOn(FocusedControl.ListTab)
6949                     .Do(() => this.SetSortColumnByDisplayIndex(3)),
6950
6951                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
6952                     .FocusedOn(FocusedControl.ListTab)
6953                     .Do(() => this.SetSortColumnByDisplayIndex(4)),
6954
6955                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
6956                     .FocusedOn(FocusedControl.ListTab)
6957                     .Do(() => this.SetSortColumnByDisplayIndex(5)),
6958
6959                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
6960                     .FocusedOn(FocusedControl.ListTab)
6961                     .Do(() => this.SetSortColumnByDisplayIndex(6)),
6962
6963                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
6964                     .FocusedOn(FocusedControl.ListTab)
6965                     .Do(() => this.SetSortColumnByDisplayIndex(7)),
6966
6967                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
6968                     .FocusedOn(FocusedControl.ListTab)
6969                     .Do(() => this.SetSortLastColumn()),
6970
6971                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
6972                     .Do(() => this.FavoritesRetweetOfficial()),
6973
6974                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
6975                     .Do(() => this.FavoritesRetweetUnofficial()),
6976
6977                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
6978                     .Do(() => this.OpenUserAppointUrl()),
6979
6980                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6981                     .FocusedOn(FocusedControl.PostBrowser)
6982                     .Do(() => this.doReTweetUnofficial()),
6983
6984                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
6985                     .OnlyWhen(() => this.ExistCurrentPost)
6986                     .Do(() => this.doTranslation(_curPost.TextFromApi)),
6987
6988                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
6989                     .Do(() => this.doReTweetUnofficial()),
6990
6991                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C, Keys.Alt | Keys.Shift | Keys.Insert)
6992                     .Do(() => this.CopyUserId()),
6993
6994                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
6995                     .Do(() => this.tweetThumbnail1.ScrollUp()),
6996
6997                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
6998                     .Do(() => this.tweetThumbnail1.ScrollDown()),
6999
7000                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
7001                     .FocusedOn(FocusedControl.ListTab)
7002                     .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
7003                     .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
7004             };
7005         }
7006
7007         private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
7008         {
7009             // Task を返す非同期処理があれば asyncTask に代入する
7010             asyncTask = null;
7011
7012             // ShortcutCommand に対応しているコマンドはここで処理される
7013             foreach (var command in this.shortcutCommands)
7014             {
7015                 if (command.IsMatch(keyData, focusedOn))
7016                 {
7017                     asyncTask = command.RunCommand();
7018                     return command.PreventDefault;
7019                 }
7020             }
7021
7022             return false;
7023         }
7024
7025         private void ScrollDownPostBrowser(bool forward)
7026         {
7027             var doc = PostBrowser.Document;
7028             if (doc == null) return;
7029
7030             var tags = doc.GetElementsByTagName("html");
7031             if (tags.Count > 0)
7032             {
7033                 if (forward)
7034                     tags[0].ScrollTop += this._fntDetail.Height;
7035                 else
7036                     tags[0].ScrollTop -= this._fntDetail.Height;
7037             }
7038         }
7039
7040         private void PageDownPostBrowser(bool forward)
7041         {
7042             var doc = PostBrowser.Document;
7043             if (doc == null) return;
7044
7045             var tags = doc.GetElementsByTagName("html");
7046             if (tags.Count > 0)
7047             {
7048                 if (forward)
7049                     tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7050                 else
7051                     tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7052             }
7053         }
7054
7055         private void GoNextTab(bool forward)
7056         {
7057             int idx = ListTab.SelectedIndex;
7058             if (forward)
7059             {
7060                 idx += 1;
7061                 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7062             }
7063             else
7064             {
7065                 idx -= 1;
7066                 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7067             }
7068             ListTab.SelectedIndex = idx;
7069         }
7070
7071         private void CopyStot()
7072         {
7073             string clstr = "";
7074             StringBuilder sb = new StringBuilder();
7075             bool IsProtected = false;
7076             bool isDm = false;
7077             if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7078             foreach (int idx in _curList.SelectedIndices)
7079             {
7080                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7081                 if (post.IsProtect)
7082                 {
7083                     IsProtected = true;
7084                     continue;
7085                 }
7086                 if (post.IsDeleted) continue;
7087                 if (!isDm)
7088                 {
7089                     if (post.RetweetedId != null)
7090                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7091                     else
7092                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7093                 }
7094                 else
7095                 {
7096                     sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7097                 }
7098             }
7099             if (IsProtected)
7100             {
7101                 MessageBox.Show(Properties.Resources.CopyStotText1);
7102             }
7103             if (sb.Length > 0)
7104             {
7105                 clstr = sb.ToString();
7106                 try
7107                 {
7108                     Clipboard.SetDataObject(clstr, false, 5, 100);
7109                 }
7110                 catch (Exception ex)
7111                 {
7112                     MessageBox.Show(ex.Message);
7113                 }
7114             }
7115         }
7116
7117         private void CopyIdUri()
7118         {
7119             string clstr = "";
7120             StringBuilder sb = new StringBuilder();
7121             if (this._curTab == null) return;
7122             if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7123             if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7124             foreach (int idx in _curList.SelectedIndices)
7125             {
7126                 var post = _statuses.Tabs[_curTab.Text][idx];
7127                 sb.Append(MyCommon.GetStatusUrl(post));
7128                 sb.Append(Environment.NewLine);
7129             }
7130             if (sb.Length > 0)
7131             {
7132                 clstr = sb.ToString();
7133                 try
7134                 {
7135                     Clipboard.SetDataObject(clstr, false, 5, 100);
7136                 }
7137                 catch (Exception ex)
7138                 {
7139                     MessageBox.Show(ex.Message);
7140                 }
7141             }
7142         }
7143
7144         private void GoFav(bool forward)
7145         {
7146             if (_curList.VirtualListSize == 0) return;
7147             int fIdx = 0;
7148             int toIdx = 0;
7149             int stp = 1;
7150
7151             if (forward)
7152             {
7153                 if (_curList.SelectedIndices.Count == 0)
7154                 {
7155                     fIdx = 0;
7156                 }
7157                 else
7158                 {
7159                     fIdx = _curList.SelectedIndices[0] + 1;
7160                     if (fIdx > _curList.VirtualListSize - 1) return;
7161                 }
7162                 toIdx = _curList.VirtualListSize;
7163                 stp = 1;
7164             }
7165             else
7166             {
7167                 if (_curList.SelectedIndices.Count == 0)
7168                 {
7169                     fIdx = _curList.VirtualListSize - 1;
7170                 }
7171                 else
7172                 {
7173                     fIdx = _curList.SelectedIndices[0] - 1;
7174                     if (fIdx < 0) return;
7175                 }
7176                 toIdx = -1;
7177                 stp = -1;
7178             }
7179
7180             for (int idx = fIdx; idx != toIdx; idx += stp)
7181             {
7182                 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7183                 {
7184                     SelectListItem(_curList, idx);
7185                     _curList.EnsureVisible(idx);
7186                     break;
7187                 }
7188             }
7189         }
7190
7191         private void GoSamePostToAnotherTab(bool left)
7192         {
7193             if (_curList.VirtualListSize == 0) return;
7194             int fIdx = 0;
7195             int toIdx = 0;
7196             int stp = 1;
7197             long targetId = 0;
7198
7199             if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7200             if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7201
7202             targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7203
7204             if (left)
7205             {
7206                 // 左のタブへ
7207                 if (ListTab.SelectedIndex == 0)
7208                 {
7209                     return;
7210                 }
7211                 else
7212                 {
7213                     fIdx = ListTab.SelectedIndex - 1;
7214                 }
7215                 toIdx = -1;
7216                 stp = -1;
7217             }
7218             else
7219             {
7220                 // 右のタブへ
7221                 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7222                 {
7223                     return;
7224                 }
7225                 else
7226                 {
7227                     fIdx = ListTab.SelectedIndex + 1;
7228                 }
7229                 toIdx = ListTab.TabCount;
7230                 stp = 1;
7231             }
7232
7233             bool found = false;
7234             for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7235             {
7236                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7237                 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7238                 {
7239                     if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7240                     {
7241                         ListTab.SelectedIndex = tabidx;
7242                         SelectListItem(_curList, idx);
7243                         _curList.EnsureVisible(idx);
7244                         found = true;
7245                         break;
7246                     }
7247                 }
7248                 if (found) break;
7249             }
7250         }
7251
7252         private void GoPost(bool forward)
7253         {
7254             if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7255             int fIdx = 0;
7256             int toIdx = 0;
7257             int stp = 1;
7258
7259             if (forward)
7260             {
7261                 fIdx = _curList.SelectedIndices[0] + 1;
7262                 if (fIdx > _curList.VirtualListSize - 1) return;
7263                 toIdx = _curList.VirtualListSize;
7264                 stp = 1;
7265             }
7266             else
7267             {
7268                 fIdx = _curList.SelectedIndices[0] - 1;
7269                 if (fIdx < 0) return;
7270                 toIdx = -1;
7271                 stp = -1;
7272             }
7273
7274             string name = "";
7275             if (_curPost.RetweetedId == null)
7276             {
7277                 name = _curPost.ScreenName;
7278             }
7279             else
7280             {
7281                 name = _curPost.RetweetedBy;
7282             }
7283             for (int idx = fIdx; idx != toIdx; idx += stp)
7284             {
7285                 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7286                 {
7287                     if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7288                     {
7289                         SelectListItem(_curList, idx);
7290                         _curList.EnsureVisible(idx);
7291                         break;
7292                     }
7293                 }
7294                 else
7295                 {
7296                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7297                     {
7298                         SelectListItem(_curList, idx);
7299                         _curList.EnsureVisible(idx);
7300                         break;
7301                     }
7302                 }
7303             }
7304         }
7305
7306         private void GoRelPost(bool forward)
7307         {
7308             if (_curList.SelectedIndices.Count == 0) return;
7309
7310             int fIdx = 0;
7311             int toIdx = 0;
7312             int stp = 1;
7313             if (forward)
7314             {
7315                 fIdx = _curList.SelectedIndices[0] + 1;
7316                 if (fIdx > _curList.VirtualListSize - 1) return;
7317                 toIdx = _curList.VirtualListSize;
7318                 stp = 1;
7319             }
7320             else
7321             {
7322                 fIdx = _curList.SelectedIndices[0] - 1;
7323                 if (fIdx < 0) return;
7324                 toIdx = -1;
7325                 stp = -1;
7326             }
7327
7328             if (!_anchorFlag)
7329             {
7330                 if (_curPost == null) return;
7331                 _anchorPost = _curPost;
7332                 _anchorFlag = true;
7333             }
7334             else
7335             {
7336                 if (_anchorPost == null) return;
7337             }
7338
7339             for (int idx = fIdx; idx != toIdx; idx += stp)
7340             {
7341                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7342                 if (post.ScreenName == _anchorPost.ScreenName ||
7343                     post.RetweetedBy == _anchorPost.ScreenName ||
7344                     post.ScreenName == _anchorPost.RetweetedBy ||
7345                     (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7346                     _anchorPost.ReplyToList.Contains(post.ScreenName.ToLowerInvariant()) ||
7347                     _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLowerInvariant()) ||
7348                     post.ReplyToList.Contains(_anchorPost.ScreenName.ToLowerInvariant()) ||
7349                     post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLowerInvariant()))
7350                 {
7351                     SelectListItem(_curList, idx);
7352                     _curList.EnsureVisible(idx);
7353                     break;
7354                 }
7355             }
7356         }
7357
7358         private void GoAnchor()
7359         {
7360             if (_anchorPost == null) return;
7361             int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7362             if (idx == -1) return;
7363
7364             SelectListItem(_curList, idx);
7365             _curList.EnsureVisible(idx);
7366         }
7367
7368         private void GoTopEnd(bool GoTop)
7369         {
7370             if (_curList.VirtualListSize == 0)
7371                 return;
7372
7373             ListViewItem _item;
7374             int idx;
7375
7376             if (GoTop)
7377             {
7378                 _item = _curList.GetItemAt(0, 25);
7379                 if (_item == null)
7380                     idx = 0;
7381                 else
7382                     idx = _item.Index;
7383             }
7384             else
7385             {
7386                 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7387                 if (_item == null)
7388                     idx = _curList.VirtualListSize - 1;
7389                 else
7390                     idx = _item.Index;
7391             }
7392             SelectListItem(_curList, idx);
7393         }
7394
7395         private void GoMiddle()
7396         {
7397             if (_curList.VirtualListSize == 0)
7398                 return;
7399
7400             ListViewItem _item;
7401             int idx1;
7402             int idx2;
7403             int idx3;
7404
7405             _item = _curList.GetItemAt(0, 0);
7406             if (_item == null)
7407             {
7408                 idx1 = 0;
7409             }
7410             else
7411             {
7412                 idx1 = _item.Index;
7413             }
7414
7415             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7416             if (_item == null)
7417             {
7418                 idx2 = _curList.VirtualListSize - 1;
7419             }
7420             else
7421             {
7422                 idx2 = _item.Index;
7423             }
7424             idx3 = (idx1 + idx2) / 2;
7425
7426             SelectListItem(_curList, idx3);
7427         }
7428
7429         private void GoLast()
7430         {
7431             if (_curList.VirtualListSize == 0) return;
7432
7433             if (_statuses.SortOrder == SortOrder.Ascending)
7434             {
7435                 SelectListItem(_curList, _curList.VirtualListSize - 1);
7436                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7437             }
7438             else
7439             {
7440                 SelectListItem(_curList, 0);
7441                 _curList.EnsureVisible(0);
7442             }
7443         }
7444
7445         private void MoveTop()
7446         {
7447             if (_curList.SelectedIndices.Count == 0) return;
7448             int idx = _curList.SelectedIndices[0];
7449             if (_statuses.SortOrder == SortOrder.Ascending)
7450             {
7451                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7452             }
7453             else
7454             {
7455                 _curList.EnsureVisible(0);
7456             }
7457             _curList.EnsureVisible(idx);
7458         }
7459
7460         private async Task GoInReplyToPostTree()
7461         {
7462             if (_curPost == null) return;
7463
7464             TabModel curTabClass = _statuses.Tabs[_curTab.Text];
7465
7466             if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7467             {
7468                 try
7469                 {
7470                     var post = await tw.GetStatusApi(false, _curPost.StatusId);
7471
7472                     _curPost.InReplyToStatusId = post.InReplyToStatusId;
7473                     _curPost.InReplyToUser = post.InReplyToUser;
7474                     _curPost.IsReply = post.IsReply;
7475                     this.PurgeListViewItemCache();
7476                     _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7477                 }
7478                 catch (WebApiException ex)
7479                 {
7480                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7481                 }
7482             }
7483
7484             if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7485
7486             if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7487             {
7488                 replyChains = new Stack<ReplyChain>();
7489             }
7490             replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7491
7492             int inReplyToIndex;
7493             string inReplyToTabName;
7494             long inReplyToId = _curPost.InReplyToStatusId.Value;
7495             string inReplyToUser = _curPost.InReplyToUser;
7496             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7497
7498             var inReplyToPosts = from tab in _statuses.Tabs.Values
7499                                  orderby tab != curTabClass
7500                                  from post in tab.Posts.Values
7501                                  where post.StatusId == inReplyToId
7502                                  let index = tab.IndexOf(post.StatusId)
7503                                  where index != -1
7504                                  select new {Tab = tab, Index = index};
7505
7506             var inReplyPost = inReplyToPosts.FirstOrDefault();
7507             if (inReplyPost == null)
7508             {
7509                 try
7510                 {
7511                     await Task.Run(async () =>
7512                     {
7513                         var post = await tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value)
7514                             .ConfigureAwait(false);
7515                         post.IsRead = true;
7516
7517                         _statuses.AddPost(post);
7518                         _statuses.DistributePosts();
7519                     });
7520                 }
7521                 catch (WebApiException ex)
7522                 {
7523                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
7524                     await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7525                     return;
7526                 }
7527
7528                 this.RefreshTimeline();
7529
7530                 inReplyPost = inReplyToPosts.FirstOrDefault();
7531                 if (inReplyPost == null)
7532                 {
7533                     await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7534                     return;
7535                 }
7536             }
7537             inReplyToTabName = inReplyPost.Tab.TabName;
7538             inReplyToIndex = inReplyPost.Index;
7539
7540             TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7541             DetailsListView listView = (DetailsListView)tabPage.Tag;
7542
7543             if (_curTab != tabPage)
7544             {
7545                 this.ListTab.SelectTab(tabPage);
7546             }
7547
7548             this.SelectListItem(listView, inReplyToIndex);
7549             listView.EnsureVisible(inReplyToIndex);
7550         }
7551
7552         private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7553         {
7554             if (_curPost == null) return;
7555
7556             TabModel curTabClass = _statuses.Tabs[_curTab.Text];
7557             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7558
7559             if (parallel)
7560             {
7561                 if (_curPost.InReplyToStatusId != null)
7562                 {
7563                     var posts = from t in _statuses.Tabs
7564                                 from p in t.Value.Posts
7565                                 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7566                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7567                                 where indexOf > -1
7568                                 orderby isForward ? indexOf : indexOf * -1
7569                                 orderby t.Value != curTabClass
7570                                 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7571                     try
7572                     {
7573                         var postList = posts.ToList();
7574                         for (int i = postList.Count - 1; i >= 0; i--)
7575                         {
7576                             int index = i;
7577                             if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7578                             {
7579                                 postList.RemoveAt(index);
7580                             }
7581                         }
7582                         var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7583                         if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7584                         if (post == null) post = postList.First();
7585                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7586                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7587                         SelectListItem(listView, post.Index);
7588                         listView.EnsureVisible(post.Index);
7589                     }
7590                     catch (InvalidOperationException)
7591                     {
7592                         return;
7593                     }
7594                 }
7595             }
7596             else
7597             {
7598                 if (replyChains == null || replyChains.Count < 1)
7599                 {
7600                     var posts = from t in _statuses.Tabs
7601                                 from p in t.Value.Posts
7602                                 where p.Value.InReplyToStatusId == _curPost.StatusId
7603                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7604                                 where indexOf > -1
7605                                 orderby indexOf
7606                                 orderby t.Value != curTabClass
7607                                 select new {Tab = t.Value, Index = indexOf};
7608                     try
7609                     {
7610                         var post = posts.First();
7611                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7612                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7613                         SelectListItem(listView, post.Index);
7614                         listView.EnsureVisible(post.Index);
7615                     }
7616                     catch (InvalidOperationException)
7617                     {
7618                         return;
7619                     }
7620                 }
7621                 else
7622                 {
7623                     ReplyChain chainHead = replyChains.Pop();
7624                     if (chainHead.InReplyToId == _curPost.StatusId)
7625                     {
7626                         int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7627                         if (idx == -1)
7628                         {
7629                             replyChains = null;
7630                         }
7631                         else
7632                         {
7633                             try
7634                             {
7635                                 ListTab.SelectTab(chainHead.OriginalTab);
7636                             }
7637                             catch (Exception)
7638                             {
7639                                 replyChains = null;
7640                             }
7641                             SelectListItem(_curList, idx);
7642                             _curList.EnsureVisible(idx);
7643                         }
7644                     }
7645                     else
7646                     {
7647                         replyChains = null;
7648                         this.GoBackInReplyToPostTree(parallel);
7649                     }
7650                 }
7651             }
7652         }
7653
7654         private void GoBackSelectPostChain()
7655         {
7656             if (this.selectPostChains.Count > 1)
7657             {
7658                 var idx = -1;
7659                 TabPage tp = null;
7660
7661                 do
7662                 {
7663                     try
7664                     {
7665                         this.selectPostChains.Pop();
7666                         var tabPostPair = this.selectPostChains.Peek();
7667
7668                         if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue;  //該当タブが存在しないので無視
7669
7670                         if (tabPostPair.Item2 != null)
7671                         {
7672                             idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7673                             if (idx == -1) continue;  //該当ポストが存在しないので無視
7674                         }
7675
7676                         tp = tabPostPair.Item1;
7677
7678                         this.selectPostChains.Pop();
7679                     }
7680                     catch (InvalidOperationException)
7681                     {
7682                     }
7683
7684                     break;
7685                 }
7686                 while (this.selectPostChains.Count > 1);
7687
7688                 if (tp == null)
7689                 {
7690                     //状態がおかしいので処理を中断
7691                     //履歴が残り1つであればクリアしておく
7692                     if (this.selectPostChains.Count == 1)
7693                         this.selectPostChains.Clear();
7694                     return;
7695                 }
7696
7697                 DetailsListView lst = (DetailsListView)tp.Tag;
7698                 this.ListTab.SelectedTab = tp;
7699                 if (idx > -1)
7700                 {
7701                     SelectListItem(lst, idx);
7702                     lst.EnsureVisible(idx);
7703                 }
7704                 lst.Focus();
7705             }
7706         }
7707
7708         private void PushSelectPostChain()
7709         {
7710             int count = this.selectPostChains.Count;
7711             if (count > 0)
7712             {
7713                 var p = this.selectPostChains.Peek();
7714                 if (p.Item1 == this._curTab)
7715                 {
7716                     if (p.Item2 == this._curPost) return;  //最新の履歴と同一
7717                     if (p.Item2 == null) this.selectPostChains.Pop();  //置き換えるため削除
7718                 }
7719             }
7720             if (count >= 2500) TrimPostChain();
7721             this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7722         }
7723
7724         private void TrimPostChain()
7725         {
7726             if (this.selectPostChains.Count <= 2000) return;
7727             var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7728             for (int i = 0; i < 2000; i++)
7729             {
7730                 p.Push(this.selectPostChains.Pop());
7731             }
7732             this.selectPostChains.Clear();
7733             for (int i = 0; i < 2000; i++)
7734             {
7735                 this.selectPostChains.Push(p.Pop());
7736             }
7737         }
7738
7739         private bool GoStatus(long statusId)
7740         {
7741             if (statusId == 0) return false;
7742             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7743             {
7744                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7745                 {
7746                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7747                     ListTab.SelectedIndex = tabidx;
7748                     SelectListItem(_curList, idx);
7749                     _curList.EnsureVisible(idx);
7750                     return true;
7751                 }
7752             }
7753             return false;
7754         }
7755
7756         private bool GoDirectMessage(long statusId)
7757         {
7758             if (statusId == 0) return false;
7759             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7760             {
7761                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7762                 {
7763                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7764                     ListTab.SelectedIndex = tabidx;
7765                     SelectListItem(_curList, idx);
7766                     _curList.EnsureVisible(idx);
7767                     return true;
7768                 }
7769             }
7770             return false;
7771         }
7772
7773         private void MyList_MouseClick(object sender, MouseEventArgs e)
7774         {
7775             _anchorFlag = false;
7776         }
7777
7778         private void StatusText_Enter(object sender, EventArgs e)
7779         {
7780             // フォーカスの戻り先を StatusText に設定
7781             this.Tag = StatusText;
7782             StatusText.BackColor = _clInputBackcolor;
7783         }
7784
7785         public Color InputBackColor
7786         {
7787             get { return _clInputBackcolor; }
7788             set { _clInputBackcolor = value; }
7789         }
7790
7791         private void StatusText_Leave(object sender, EventArgs e)
7792         {
7793             // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7794             if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7795             StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7796         }
7797
7798         private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7799         {
7800             Task asyncTask;
7801             if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7802             {
7803                 e.Handled = true;
7804                 e.SuppressKeyPress = true;
7805             }
7806
7807             this.StatusText_TextChanged(null, null);
7808
7809             if (asyncTask != null)
7810                 await asyncTask;
7811         }
7812
7813         private void SaveConfigsAll(bool ifModified)
7814         {
7815             if (!ifModified)
7816             {
7817                 SaveConfigsCommon();
7818                 SaveConfigsLocal();
7819                 SaveConfigsTabs();
7820                 SaveConfigsAtId();
7821             }
7822             else
7823             {
7824                 if (ModifySettingCommon) SaveConfigsCommon();
7825                 if (ModifySettingLocal) SaveConfigsLocal();
7826                 if (ModifySettingAtId) SaveConfigsAtId();
7827             }
7828         }
7829
7830         private void SaveConfigsAtId()
7831         {
7832             if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7833
7834             ModifySettingAtId = false;
7835             SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7836             cfgAtId.Save();
7837         }
7838
7839         private void SaveConfigsCommon()
7840         {
7841             if (_ignoreConfigSave) return;
7842
7843             ModifySettingCommon = false;
7844             lock (_syncObject)
7845             {
7846                 _cfgCommon.UserName = tw.Username;
7847                 _cfgCommon.UserId = tw.UserId;
7848                 _cfgCommon.Token = tw.AccessToken;
7849                 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7850
7851                 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7852                    IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7853                 {
7854                     _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7855                 }
7856
7857                 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7858                 switch (_statuses.SortMode)
7859                 {
7860                     case ComparerMode.Nickname:  //ニックネーム
7861                         _cfgCommon.SortColumn = 1;
7862                         break;
7863                     case ComparerMode.Data:  //本文
7864                         _cfgCommon.SortColumn = 2;
7865                         break;
7866                     case ComparerMode.Id:  //時刻=発言Id
7867                         _cfgCommon.SortColumn = 3;
7868                         break;
7869                     case ComparerMode.Name:  //名前
7870                         _cfgCommon.SortColumn = 4;
7871                         break;
7872                     case ComparerMode.Source:  //Source
7873                         _cfgCommon.SortColumn = 7;
7874                         break;
7875                 }
7876
7877                 _cfgCommon.HashTags = HashMgr.HashHistories;
7878                 if (HashMgr.IsPermanent)
7879                 {
7880                     _cfgCommon.HashSelected = HashMgr.UseHash;
7881                 }
7882                 else
7883                 {
7884                     _cfgCommon.HashSelected = "";
7885                 }
7886                 _cfgCommon.HashIsHead = HashMgr.IsHead;
7887                 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7888                 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7889                 if (ToolStripFocusLockMenuItem != null &&
7890                         ToolStripFocusLockMenuItem.IsDisposed == false)
7891                 {
7892                     _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7893                 }
7894                 _cfgCommon.TrackWord = tw.TrackWord;
7895                 _cfgCommon.AllAtReply = tw.AllAtReply;
7896                 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7897                 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7898
7899                 _cfgCommon.Save();
7900             }
7901         }
7902
7903         private void SaveConfigsLocal()
7904         {
7905             if (_ignoreConfigSave) return;
7906             lock (_syncObject)
7907             {
7908                 ModifySettingLocal = false;
7909                 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7910                 _cfgLocal.FormSize = _mySize;
7911                 _cfgLocal.FormLocation = _myLoc;
7912                 _cfgLocal.SplitterDistance = _mySpDis;
7913                 _cfgLocal.PreviewDistance = _mySpDis3;
7914                 _cfgLocal.StatusMultiline = StatusText.Multiline;
7915                 _cfgLocal.StatusTextHeight = _mySpDis2;
7916
7917                 _cfgLocal.FontUnread = _fntUnread;
7918                 _cfgLocal.ColorUnread = _clUnread;
7919                 _cfgLocal.FontRead = _fntReaded;
7920                 _cfgLocal.ColorRead = _clReaded;
7921                 _cfgLocal.FontDetail = _fntDetail;
7922                 _cfgLocal.ColorDetail = _clDetail;
7923                 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7924                 _cfgLocal.ColorDetailLink = _clDetailLink;
7925                 _cfgLocal.ColorFav = _clFav;
7926                 _cfgLocal.ColorOWL = _clOWL;
7927                 _cfgLocal.ColorRetweet = _clRetweet;
7928                 _cfgLocal.ColorSelf = _clSelf;
7929                 _cfgLocal.ColorAtSelf = _clAtSelf;
7930                 _cfgLocal.ColorTarget = _clTarget;
7931                 _cfgLocal.ColorAtTarget = _clAtTarget;
7932                 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
7933                 _cfgLocal.ColorAtTo = _clAtTo;
7934                 _cfgLocal.ColorListBackcolor = _clListBackcolor;
7935                 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
7936                 _cfgLocal.ColorInputFont = _clInputFont;
7937                 _cfgLocal.FontInputFont = _fntInputFont;
7938
7939                 if (_ignoreConfigSave) return;
7940                 _cfgLocal.Save();
7941             }
7942         }
7943
7944         private void SaveConfigsTabs()
7945         {
7946             var tabsSetting = new SettingTabs();
7947
7948             var tabs = this.ListTab.TabPages.Cast<TabPage>()
7949                 .Select(x => this._statuses.Tabs[x.Text])
7950                 .Concat(new[] { this._statuses.GetTabByType(MyCommon.TabUsageType.Mute) });
7951
7952             foreach (var tab in tabs)
7953             {
7954                 if (tab.TabType == MyCommon.TabUsageType.Related || tab.TabType == MyCommon.TabUsageType.SearchResults)
7955                     continue;
7956
7957                 var tabSetting = new SettingTabs.SettingTabItem
7958                 {
7959                     TabName = tab.TabName,
7960                     TabType = tab.TabType,
7961                     UnreadManage = tab.UnreadManage,
7962                     Protected = tab.Protected,
7963                     Notify = tab.Notify,
7964                     SoundFile = tab.SoundFile,
7965                 };
7966
7967                 var filterTab = tab as FilterTabModel;
7968                 if (filterTab != null)
7969                     tabSetting.FilterArray = filterTab.FilterArray;
7970
7971                 var userTab = tab as UserTimelineTabModel;
7972                 if (userTab != null)
7973                     tabSetting.User = userTab.ScreenName;
7974
7975                 var searchTab = tab as PublicSearchTabModel;
7976                 if (searchTab != null)
7977                 {
7978                     tabSetting.SearchWords = searchTab.SearchWords;
7979                     tabSetting.SearchLang = searchTab.SearchLang;
7980                 }
7981
7982                 var listTab = tab as ListTimelineTabModel;
7983                 if (listTab != null)
7984                     tabSetting.ListInfo = listTab.ListInfo;
7985
7986                 tabsSetting.Tabs.Add(tabSetting);
7987             }
7988
7989             tabsSetting.Save();
7990         }
7991
7992         private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
7993         {
7994             string inputText;
7995             var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
7996             if (ret != DialogResult.OK)
7997                 return;
7998
7999             var match = Twitter.StatusUrlRegex.Match(inputText);
8000             if (!match.Success)
8001             {
8002                 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8003                     Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8004                 return;
8005             }
8006
8007             try
8008             {
8009                 var statusId = long.Parse(match.Groups["StatusId"].Value);
8010                 await this.OpenRelatedTab(statusId);
8011             }
8012             catch (TabException ex)
8013             {
8014                 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8015             }
8016         }
8017
8018         private void SaveLogMenuItem_Click(object sender, EventArgs e)
8019         {
8020             DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8021                     Properties.Resources.SaveLogMenuItem_ClickText2,
8022                     MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8023             if (rslt == DialogResult.Cancel) return;
8024
8025             SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8026             SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8027             SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8028             SaveFileDialog1.FilterIndex = 0;
8029             SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8030             SaveFileDialog1.RestoreDirectory = true;
8031
8032             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8033             {
8034                 if (!SaveFileDialog1.ValidateNames) return;
8035                 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8036                 {
8037                     if (rslt == DialogResult.Yes)
8038                     {
8039                         //All
8040                         for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8041                         {
8042                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
8043                             string protect = "";
8044                             if (post.IsProtect) protect = "Protect";
8045                             sw.WriteLine(post.Nickname + "\t" +
8046                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8047                                      post.CreatedAt.ToString() + "\t" +
8048                                      post.ScreenName + "\t" +
8049                                      post.StatusId.ToString() + "\t" +
8050                                      post.ImageUrl + "\t" +
8051                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8052                                      protect);
8053                         }
8054                     }
8055                     else
8056                     {
8057                         foreach (int idx in _curList.SelectedIndices)
8058                         {
8059                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
8060                             string protect = "";
8061                             if (post.IsProtect) protect = "Protect";
8062                             sw.WriteLine(post.Nickname + "\t" +
8063                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8064                                      post.CreatedAt.ToString() + "\t" +
8065                                      post.ScreenName + "\t" +
8066                                      post.StatusId.ToString() + "\t" +
8067                                      post.ImageUrl + "\t" +
8068                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8069                                      protect);
8070                         }
8071                     }
8072                 }
8073             }
8074             this.TopMost = this._cfgCommon.AlwaysTop;
8075         }
8076
8077         private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8078         {
8079             Task asyncTask;
8080             bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
8081             if (KeyRes)
8082             {
8083                 e.IsInputKey = true;
8084             }
8085             else
8086             {
8087                 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8088                 {
8089                     var shortcut = (Shortcut)e.KeyData;
8090                     switch (shortcut)
8091                     {
8092                         case Shortcut.CtrlA:
8093                         case Shortcut.CtrlC:
8094                         case Shortcut.CtrlIns:
8095                             // 既定の動作を有効にする
8096                             break;
8097                         default:
8098                             // その他のショートカットキーは無効にする
8099                             e.IsInputKey = true;
8100                             break;
8101                     }
8102                 }
8103             }
8104
8105             if (asyncTask != null)
8106                 await asyncTask;
8107         }
8108         public bool TabRename(ref string tabName)
8109         {
8110             //タブ名変更
8111             string newTabText = null;
8112             using (InputTabName inputName = new InputTabName())
8113             {
8114                 inputName.TabName = tabName;
8115                 inputName.ShowDialog();
8116                 if (inputName.DialogResult == DialogResult.Cancel) return false;
8117                 newTabText = inputName.TabName;
8118             }
8119             this.TopMost = this._cfgCommon.AlwaysTop;
8120             if (!string.IsNullOrEmpty(newTabText))
8121             {
8122                 //新タブ名存在チェック
8123                 for (int i = 0; i < ListTab.TabCount; i++)
8124                 {
8125                     if (ListTab.TabPages[i].Text == newTabText)
8126                     {
8127                         string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8128                         MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8129                         return false;
8130                     }
8131                 }
8132                 //タブ名を変更
8133                 for (int i = 0; i < ListTab.TabCount; i++)
8134                 {
8135                     if (ListTab.TabPages[i].Text == tabName)
8136                     {
8137                         ListTab.TabPages[i].Text = newTabText;
8138                         break;
8139                     }
8140                 }
8141                 _statuses.RenameTab(tabName, newTabText);
8142
8143                 SaveConfigsCommon();
8144                 SaveConfigsTabs();
8145                 _rclickTabName = newTabText;
8146                 tabName = newTabText;
8147                 return true;
8148             }
8149             else
8150             {
8151                 return false;
8152             }
8153         }
8154
8155         private void ListTab_MouseClick(object sender, MouseEventArgs e)
8156         {
8157             if (e.Button == MouseButtons.Middle)
8158             {
8159                 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8160                 {
8161                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8162                     {
8163                         this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8164                         this.SaveConfigsTabs();
8165                         break;
8166                     }
8167                 }
8168             }
8169         }
8170
8171         private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8172         {
8173             string tn = ListTab.SelectedTab.Text;
8174             TabRename(ref tn);
8175         }
8176
8177         private void ListTab_MouseDown(object sender, MouseEventArgs e)
8178         {
8179             if (this._cfgCommon.TabMouseLock) return;
8180             Point cpos = new Point(e.X, e.Y);
8181             if (e.Button == MouseButtons.Left)
8182             {
8183                 for (int i = 0; i < ListTab.TabPages.Count; i++)
8184                 {
8185                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8186                     {
8187                         _tabDrag = true;
8188                         _tabMouseDownPoint = e.Location;
8189                         break;
8190                     }
8191                 }
8192             }
8193             else
8194             {
8195                 _tabDrag = false;
8196             }
8197         }
8198
8199         private void ListTab_DragEnter(object sender, DragEventArgs e)
8200         {
8201             if (e.Data.GetDataPresent(typeof(TabPage)))
8202                 e.Effect = DragDropEffects.Move;
8203             else
8204                 e.Effect = DragDropEffects.None;
8205         }
8206
8207         private void ListTab_DragDrop(object sender, DragEventArgs e)
8208         {
8209             if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8210
8211             _tabDrag = false;
8212             string tn = "";
8213             bool bef = false;
8214             Point cpos = new Point(e.X, e.Y);
8215             Point spos = ListTab.PointToClient(cpos);
8216             int i;
8217             for (i = 0; i < ListTab.TabPages.Count; i++)
8218             {
8219                 Rectangle rect = ListTab.GetTabRect(i);
8220                 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8221                     rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8222                 {
8223                     tn = ListTab.TabPages[i].Text;
8224                     if (spos.X <= (rect.Left + rect.Right) / 2)
8225                         bef = true;
8226                     else
8227                         bef = false;
8228
8229                     break;
8230                 }
8231             }
8232
8233             //タブのないところにドロップ->最後尾へ移動
8234             if (string.IsNullOrEmpty(tn))
8235             {
8236                 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8237                 bef = false;
8238                 i = ListTab.TabPages.Count - 1;
8239             }
8240
8241             TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8242             if (tp.Text == tn) return;
8243
8244             ReOrderTab(tp.Text, tn, bef);
8245         }
8246
8247         public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8248         {
8249             var baseIndex = this.GetTabPageIndex(baseTabText);
8250             if (baseIndex == -1)
8251                 return;
8252
8253             var targetIndex = this.GetTabPageIndex(targetTabText);
8254             if (targetIndex == -1)
8255                 return;
8256
8257             using (ControlTransaction.Layout(this.ListTab))
8258             {
8259                 var mTp = this.ListTab.TabPages[targetIndex];
8260                 this.ListTab.TabPages.Remove(mTp);
8261
8262                 if (targetIndex < baseIndex)
8263                     baseIndex--;
8264
8265                 if (isBeforeBaseTab)
8266                     ListTab.TabPages.Insert(baseIndex, mTp);
8267                 else
8268                     ListTab.TabPages.Insert(baseIndex + 1, mTp);
8269             }
8270
8271             SaveConfigsTabs();
8272         }
8273
8274         private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8275         {
8276             //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8277             //isReply:true=@,false=DM
8278             if (!StatusText.Enabled) return;
8279             if (_curList == null) return;
8280             if (_curTab == null) return;
8281             if (!this.ExistCurrentPost) return;
8282
8283             // 複数あてリプライはReplyではなく通常ポスト
8284             //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8285             //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8286             //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8287
8288             if (_curList.SelectedIndices.Count > 0)
8289             {
8290                 // アイテムが1件以上選択されている
8291                 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8292                 {
8293                     // 単独ユーザー宛リプライまたはDM
8294                     if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8295                     {
8296                         // ダイレクトメッセージ
8297                         StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8298                         StatusText.SelectionStart = StatusText.Text.Length;
8299                         StatusText.Focus();
8300                         this.inReplyTo = null;
8301                         return;
8302                     }
8303                     if (string.IsNullOrEmpty(StatusText.Text))
8304                     {
8305                         //空の場合
8306
8307                         // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8308                         StatusText.Text = "@" + _curPost.ScreenName + " ";
8309
8310                         var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8311                         var inReplyToScreenName = this._curPost.ScreenName;
8312                         this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8313                     }
8314                     else
8315                     {
8316                         //何か入力済の場合
8317
8318                         if (isAuto)
8319                         {
8320                             //1件選んでEnter or DoubleClick
8321                             if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8322                             {
8323                                 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
8324                                 {
8325                                     //返信先書き換え
8326                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8327                                     var inReplyToScreenName = this._curPost.ScreenName;
8328                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8329                                 }
8330                                 return;
8331                             }
8332                             if (!StatusText.Text.StartsWith("@", StringComparison.Ordinal))
8333                             {
8334                                 //文頭@以外
8335                                 if (StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8336                                 {
8337                                     // 複数リプライ
8338                                     StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8339                                     this.inReplyTo = null;
8340                                 }
8341                                 else
8342                                 {
8343                                     // 単独リプライ
8344                                     StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8345                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8346                                     var inReplyToScreenName = this._curPost.ScreenName;
8347                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8348                                 }
8349                             }
8350                             else
8351                             {
8352                                 //文頭@
8353                                 // 複数リプライ
8354                                 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8355                                 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8356                                 this.inReplyTo = null;
8357                             }
8358                         }
8359                         else
8360                         {
8361                             //1件選んでCtrl-Rの場合(返信先操作せず)
8362                             int sidx = StatusText.SelectionStart;
8363                             string id = "@" + _curPost.ScreenName + " ";
8364                             if (sidx > 0)
8365                             {
8366                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8367                                 {
8368                                     id = " " + id;
8369                                 }
8370                             }
8371                             StatusText.Text = StatusText.Text.Insert(sidx, id);
8372                             sidx += id.Length;
8373                             //if (StatusText.Text.StartsWith("@"))
8374                             //{
8375                             //    //複数リプライ
8376                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8377                             //    sidx += 5 + _curPost.ScreenName.Length;
8378                             //}
8379                             //else
8380                             //{
8381                             //    // 複数リプライ
8382                             //    StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8383                             //    sidx += 3 + _curPost.ScreenName.Length;
8384                             //}
8385                             StatusText.SelectionStart = sidx;
8386                             StatusText.Focus();
8387                             //_reply_to_id = 0;
8388                             //_reply_to_name = null;
8389                             return;
8390                         }
8391                     }
8392                 }
8393                 else
8394                 {
8395                     // 複数リプライ
8396                     if (!isAuto && !isReply) return;
8397
8398                     //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8399
8400                     if (isAuto)
8401                     {
8402                         //Enter or DoubleClick
8403
8404                         string sTxt = StatusText.Text;
8405                         if (!sTxt.StartsWith(". ", StringComparison.Ordinal))
8406                         {
8407                             sTxt = ". " + sTxt;
8408                             this.inReplyTo = null;
8409                         }
8410                         for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8411                         {
8412                             PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8413                             if (!sTxt.Contains("@" + post.ScreenName + " "))
8414                             {
8415                                 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8416                                 //sTxt = "@" + post.ScreenName + " " + sTxt;
8417                             }
8418                         }
8419                         StatusText.Text = sTxt;
8420                     }
8421                     else
8422                     {
8423                         //C-S-r or C-r
8424                         if (_curList.SelectedIndices.Count > 1)
8425                         {
8426                             //複数ポスト選択
8427
8428                             string ids = "";
8429                             int sidx = StatusText.SelectionStart;
8430                             for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8431                             {
8432                                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8433                                 if (!ids.Contains("@" + post.ScreenName + " ") &&
8434                                     !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8435                                 {
8436                                     ids += "@" + post.ScreenName + " ";
8437                                 }
8438                                 if (isAll)
8439                                 {
8440                                     foreach (string nm in post.ReplyToList)
8441                                     {
8442                                         if (!ids.Contains("@" + nm + " ") &&
8443                                             !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8444                                         {
8445                                             Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8446                                             if (m.Success)
8447                                                 ids += "@" + m.Result("${id}") + " ";
8448                                             else
8449                                                 ids += "@" + nm + " ";
8450                                         }
8451                                     }
8452                                 }
8453                             }
8454                             if (ids.Length == 0) return;
8455                             if (!StatusText.Text.StartsWith(". ", StringComparison.Ordinal))
8456                             {
8457                                 StatusText.Text = ". " + StatusText.Text;
8458                                 sidx += 2;
8459                                 this.inReplyTo = null;
8460                             }
8461                             if (sidx > 0)
8462                             {
8463                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8464                                 {
8465                                     ids = " " + ids;
8466                                 }
8467                             }
8468                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8469                             sidx += ids.Length;
8470                             //if (StatusText.Text.StartsWith("@"))
8471                             //{
8472                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8473                             //    sidx += 2 + ids.Length;
8474                             //}
8475                             //else
8476                             //{
8477                             //    StatusText.Text = StatusText.Text.Insert(sidx, ids);
8478                             //    sidx += 1 + ids.Length;
8479                             //}
8480                             StatusText.SelectionStart = sidx;
8481                             StatusText.Focus();
8482                             return;
8483                         }
8484                         else
8485                         {
8486                             //1件のみ選択のC-S-r(返信元付加する可能性あり)
8487
8488                             string ids = "";
8489                             int sidx = StatusText.SelectionStart;
8490                             PostClass post = _curPost;
8491                             if (!ids.Contains("@" + post.ScreenName + " ") &&
8492                                 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8493                             {
8494                                 ids += "@" + post.ScreenName + " ";
8495                             }
8496                             foreach (string nm in post.ReplyToList)
8497                             {
8498                                 if (!ids.Contains("@" + nm + " ") &&
8499                                     !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8500                                 {
8501                                     Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8502                                     if (m.Success)
8503                                         ids += "@" + m.Result("${id}") + " ";
8504                                     else
8505                                         ids += "@" + nm + " ";
8506                                 }
8507                             }
8508                             if (!string.IsNullOrEmpty(post.RetweetedBy))
8509                             {
8510                                 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8511                                    !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8512                                 {
8513                                     ids += "@" + post.RetweetedBy + " ";
8514                                 }
8515                             }
8516                             if (ids.Length == 0) return;
8517                             if (string.IsNullOrEmpty(StatusText.Text))
8518                             {
8519                                 //未入力の場合のみ返信先付加
8520                                 StatusText.Text = ids;
8521                                 StatusText.SelectionStart = ids.Length;
8522                                 StatusText.Focus();
8523
8524                                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8525                                 var inReplyToScreenName = this._curPost.ScreenName;
8526                                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8527                                 return;
8528                             }
8529
8530                             if (sidx > 0)
8531                             {
8532                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8533                                 {
8534                                     ids = " " + ids;
8535                                 }
8536                             }
8537                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8538                             sidx += ids.Length;
8539                             StatusText.SelectionStart = sidx;
8540                             StatusText.Focus();
8541                             return;
8542                         }
8543                     }
8544                 }
8545                 StatusText.SelectionStart = StatusText.Text.Length;
8546                 StatusText.Focus();
8547             }
8548         }
8549
8550         private void ListTab_MouseUp(object sender, MouseEventArgs e)
8551         {
8552             _tabDrag = false;
8553         }
8554
8555         private static int iconCnt = 0;
8556         private static int blinkCnt = 0;
8557         private static bool blink = false;
8558         private static bool idle = false;
8559
8560         private async Task RefreshTasktrayIcon()
8561         {
8562             if (_colorize)
8563                 await this.Colorize();
8564
8565             if (!TimerRefreshIcon.Enabled) return;
8566             //Static usCheckCnt As int = 0
8567
8568             //Static iconDlListTopItem As ListViewItem = null
8569
8570             //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8571             //    ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8572             //else
8573             //    ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8574             //
8575             //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8576
8577             iconCnt += 1;
8578             blinkCnt += 1;
8579             //usCheckCnt += 1;
8580
8581             //if (usCheckCnt > 300)    //1min
8582             //{
8583             //    usCheckCnt = 0;
8584             //    if (!this.IsReceivedUserStream)
8585             //    {
8586             //        TraceOut("ReconnectUserStream");
8587             //        tw.ReconnectUserStream();
8588             //    }
8589             //}
8590
8591             var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8592
8593             if (iconCnt >= this.NIconRefresh.Length)
8594             {
8595                 iconCnt = 0;
8596             }
8597             if (blinkCnt > 10)
8598             {
8599                 blinkCnt = 0;
8600                 //未保存の変更を保存
8601                 SaveConfigsAll(true);
8602             }
8603
8604             if (busy)
8605             {
8606                 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8607                 idle = false;
8608                 _myStatusError = false;
8609                 return;
8610             }
8611
8612             TabModel tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8613             if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8614             {
8615                 if (blinkCnt > 0) return;
8616                 blink = !blink;
8617                 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8618                 {
8619                     NotifyIcon1.Icon = ReplyIcon;
8620                 }
8621                 else
8622                 {
8623                     NotifyIcon1.Icon = ReplyIconBlink;
8624                 }
8625                 idle = false;
8626                 return;
8627             }
8628
8629             if (idle) return;
8630             idle = true;
8631             //優先度:エラー→オフライン→アイドル
8632             //エラーは更新アイコンでクリアされる
8633             if (_myStatusError)
8634             {
8635                 NotifyIcon1.Icon = NIconAtRed;
8636                 return;
8637             }
8638             if (_myStatusOnline)
8639             {
8640                 NotifyIcon1.Icon = NIconAt;
8641             }
8642             else
8643             {
8644                 NotifyIcon1.Icon = NIconAtSmoke;
8645             }
8646         }
8647
8648         private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8649         {
8650             //200ms
8651             await this.RefreshTasktrayIcon();
8652         }
8653
8654         private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8655         {
8656             //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8657             if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8658             {
8659                 if (ListTab != null && ListTab.SelectedTab != null)
8660                     _rclickTabName = ListTab.SelectedTab.Text;
8661                 else
8662                     return;
8663             }
8664
8665             if (_statuses == null) return;
8666             if (_statuses.Tabs == null) return;
8667
8668             TabModel tb = _statuses.Tabs[_rclickTabName];
8669             if (tb == null) return;
8670
8671             NotifyDispMenuItem.Checked = tb.Notify;
8672             this.NotifyTbMenuItem.Checked = tb.Notify;
8673
8674             soundfileListup = true;
8675             SoundFileComboBox.Items.Clear();
8676             this.SoundFileTbComboBox.Items.Clear();
8677             SoundFileComboBox.Items.Add("");
8678             this.SoundFileTbComboBox.Items.Add("");
8679             DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8680             if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8681             {
8682                 oDir = oDir.GetDirectories("Sounds")[0];
8683             }
8684             foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8685             {
8686                 SoundFileComboBox.Items.Add(oFile.Name);
8687                 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8688             }
8689             int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8690             if (idx == -1) idx = 0;
8691             SoundFileComboBox.SelectedIndex = idx;
8692             this.SoundFileTbComboBox.SelectedIndex = idx;
8693             soundfileListup = false;
8694             UreadManageMenuItem.Checked = tb.UnreadManage;
8695             this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8696
8697             TabMenuControl(_rclickTabName);
8698         }
8699
8700         private void TabMenuControl(string tabName)
8701         {
8702             var tabInfo = _statuses.GetTabByName(tabName);
8703
8704             this.FilterEditMenuItem.Enabled = true;
8705             this.EditRuleTbMenuItem.Enabled = true;
8706
8707             if (tabInfo.IsDefaultTabType)
8708             {
8709                 this.ProtectTabMenuItem.Enabled = false;
8710                 this.ProtectTbMenuItem.Enabled = false;
8711             }
8712             else
8713             {
8714                 this.ProtectTabMenuItem.Enabled = true;
8715                 this.ProtectTbMenuItem.Enabled = true;
8716             }
8717
8718             if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8719             {
8720                 this.ProtectTabMenuItem.Checked = true;
8721                 this.ProtectTbMenuItem.Checked = true;
8722                 this.DeleteTabMenuItem.Enabled = false;
8723                 this.DeleteTbMenuItem.Enabled = false;
8724             }
8725             else
8726             {
8727                 this.ProtectTabMenuItem.Checked = false;
8728                 this.ProtectTbMenuItem.Checked = false;
8729                 this.DeleteTabMenuItem.Enabled = true;
8730                 this.DeleteTbMenuItem.Enabled = true;
8731             }
8732         }
8733
8734         private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8735         {
8736             var checkState = ((ToolStripMenuItem)sender).Checked;
8737
8738             // チェック状態を同期
8739             this.ProtectTbMenuItem.Checked = checkState;
8740             this.ProtectTabMenuItem.Checked = checkState;
8741
8742             // ロック中はタブの削除を無効化
8743             this.DeleteTabMenuItem.Enabled = !checkState;
8744             this.DeleteTbMenuItem.Enabled = !checkState;
8745
8746             if (string.IsNullOrEmpty(_rclickTabName)) return;
8747             _statuses.Tabs[_rclickTabName].Protected = checkState;
8748
8749             SaveConfigsTabs();
8750         }
8751
8752         private void UreadManageMenuItem_Click(object sender, EventArgs e)
8753         {
8754             UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8755             this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8756
8757             if (string.IsNullOrEmpty(_rclickTabName)) return;
8758             ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8759
8760             SaveConfigsTabs();
8761         }
8762
8763         public void ChangeTabUnreadManage(string tabName, bool isManage)
8764         {
8765             var idx = this.GetTabPageIndex(tabName);
8766             if (idx == -1)
8767                 return;
8768
8769             _statuses.Tabs[tabName].UnreadManage = isManage;
8770             if (this._cfgCommon.TabIconDisp)
8771             {
8772                 if (_statuses.Tabs[tabName].UnreadCount > 0)
8773                     ListTab.TabPages[idx].ImageIndex = 0;
8774                 else
8775                     ListTab.TabPages[idx].ImageIndex = -1;
8776             }
8777
8778             if (_curTab.Text == tabName)
8779             {
8780                 this.PurgeListViewItemCache();
8781                 _curList.Refresh();
8782             }
8783
8784             SetMainWindowTitle();
8785             SetStatusLabelUrl();
8786             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8787         }
8788
8789         private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8790         {
8791             NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8792             this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8793
8794             if (string.IsNullOrEmpty(_rclickTabName)) return;
8795
8796             _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8797
8798             SaveConfigsTabs();
8799         }
8800
8801         private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8802         {
8803             if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8804
8805             _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8806
8807             SaveConfigsTabs();
8808         }
8809
8810         private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8811         {
8812             if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8813
8814             RemoveSpecifiedTab(_rclickTabName, true);
8815             SaveConfigsTabs();
8816         }
8817
8818         private void FilterEditMenuItem_Click(object sender, EventArgs e)
8819         {
8820             if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8821
8822             using (var fltDialog = new FilterDialog())
8823             {
8824                 fltDialog.Owner = this;
8825                 fltDialog.SetCurrent(_rclickTabName);
8826                 fltDialog.ShowDialog(this);
8827             }
8828             this.TopMost = this._cfgCommon.AlwaysTop;
8829
8830             this.ApplyPostFilters();
8831             SaveConfigsTabs();
8832         }
8833
8834         private void AddTabMenuItem_Click(object sender, EventArgs e)
8835         {
8836             string tabName = null;
8837             MyCommon.TabUsageType tabUsage;
8838             using (InputTabName inputName = new InputTabName())
8839             {
8840                 inputName.TabName = _statuses.MakeTabName("MyTab");
8841                 inputName.IsShowUsage = true;
8842                 inputName.ShowDialog();
8843                 if (inputName.DialogResult == DialogResult.Cancel) return;
8844                 tabName = inputName.TabName;
8845                 tabUsage = inputName.Usage;
8846             }
8847             this.TopMost = this._cfgCommon.AlwaysTop;
8848             if (!string.IsNullOrEmpty(tabName))
8849             {
8850                 //List対応
8851                 ListElement list = null;
8852                 if (tabUsage == MyCommon.TabUsageType.Lists)
8853                 {
8854                     using (ListAvailable listAvail = new ListAvailable())
8855                     {
8856                         if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8857                         if (listAvail.SelectedList == null) return;
8858                         list = listAvail.SelectedList;
8859                     }
8860                 }
8861
8862                 TabModel tab;
8863                 switch (tabUsage)
8864                 {
8865                     case MyCommon.TabUsageType.UserDefined:
8866                         tab = new FilterTabModel(tabName);
8867                         break;
8868                     case MyCommon.TabUsageType.PublicSearch:
8869                         tab = new PublicSearchTabModel(tabName);
8870                         break;
8871                     case MyCommon.TabUsageType.Lists:
8872                         tab = new ListTimelineTabModel(tabName, list);
8873                         break;
8874                     default:
8875                         return;
8876                 }
8877
8878                 if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
8879                 {
8880                     string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8881                     MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8882                 }
8883                 else
8884                 {
8885                     //成功
8886                     SaveConfigsTabs();
8887                     if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8888                     {
8889                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8890                         ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8891                     }
8892                     if (tabUsage == MyCommon.TabUsageType.Lists)
8893                     {
8894                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8895                         var listTab = (ListTimelineTabModel)this._statuses.Tabs[this._curTab.Text];
8896                         this.GetListTimelineAsync(listTab);
8897                     }
8898                 }
8899             }
8900         }
8901
8902         private void TabMenuItem_Click(object sender, EventArgs e)
8903         {
8904             using (var fltDialog = new FilterDialog())
8905             {
8906                 fltDialog.Owner = this;
8907
8908                 //選択発言を元にフィルタ追加
8909                 foreach (int idx in _curList.SelectedIndices)
8910                 {
8911                     string tabName;
8912                     //タブ選択(or追加)
8913                     if (!SelectTab(out tabName)) return;
8914
8915                     fltDialog.SetCurrent(tabName);
8916                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8917                     {
8918                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8919                     }
8920                     else
8921                     {
8922                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8923                     }
8924                     fltDialog.ShowDialog(this);
8925                     this.TopMost = this._cfgCommon.AlwaysTop;
8926                 }
8927             }
8928
8929             this.ApplyPostFilters();
8930             SaveConfigsTabs();
8931             if (this.ListTab.SelectedTab != null &&
8932                 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8933             {
8934                 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8935             }
8936         }
8937
8938         protected override bool ProcessDialogKey(Keys keyData)
8939         {
8940             //TextBox1でEnterを押してもビープ音が鳴らないようにする
8941             if ((keyData & Keys.KeyCode) == Keys.Enter)
8942             {
8943                 if (StatusText.Focused)
8944                 {
8945                     bool _NewLine = false;
8946                     bool _Post = false;
8947
8948                     if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8949                     {
8950                         if (StatusText.Multiline)
8951                         {
8952                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8953
8954                             if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8955                         }
8956                         else
8957                         {
8958                             if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8959                         }
8960
8961                     }
8962                     else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8963                     {
8964                         if (StatusText.Multiline)
8965                         {
8966                             if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8967
8968                             if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8969                         }
8970                         else
8971                         {
8972                             if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8973                         }
8974
8975                     }
8976                     else //Enter投稿時
8977                     {
8978                         if (StatusText.Multiline)
8979                         {
8980                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8981
8982                             if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
8983                                 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8984                         }
8985                         else
8986                         {
8987                             if (((keyData & Keys.Shift) == Keys.Shift) ||
8988                                 (((keyData & Keys.Control) != Keys.Control) &&
8989                                 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
8990                         }
8991                     }
8992
8993                     if (_NewLine)
8994                     {
8995                         int pos1 = StatusText.SelectionStart;
8996                         if (StatusText.SelectionLength > 0)
8997                         {
8998                             StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength);  //選択状態文字列削除
8999                         }
9000                         StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine);  //改行挿入
9001                         StatusText.SelectionStart = pos1 + Environment.NewLine.Length;    //カーソルを改行の次の文字へ移動
9002                         return true;
9003                     }
9004                     else if (_Post)
9005                     {
9006                         PostButton_Click(null, null);
9007                         return true;
9008                     }
9009                 }
9010                 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
9011                          (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
9012                          ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
9013                 {
9014                     this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9015                     return true;
9016                 }
9017             }
9018
9019             return base.ProcessDialogKey(keyData);
9020         }
9021
9022         private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9023         {
9024             MakeReplyOrDirectStatus(false, true, true);
9025         }
9026
9027         private void IDRuleMenuItem_Click(object sender, EventArgs e)
9028         {
9029             string tabName;
9030
9031             //未選択なら処理終了
9032             if (_curList.SelectedIndices.Count == 0) return;
9033
9034             //タブ選択(or追加)
9035             if (!SelectTab(out tabName)) return;
9036
9037             var tab = (FilterTabModel)this._statuses.Tabs[tabName];
9038
9039             bool mv;
9040             bool mk;
9041             if (tab.TabType != MyCommon.TabUsageType.Mute)
9042             {
9043                 this.MoveOrCopy(out mv, out mk);
9044             }
9045             else
9046             {
9047                 // ミュートタブでは常に MoveMatches を true にする
9048                 mv = true;
9049                 mk = false;
9050             }
9051
9052             List<string> ids = new List<string>();
9053             foreach (int idx in _curList.SelectedIndices)
9054             {
9055                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9056                 if (!ids.Contains(post.ScreenName))
9057                 {
9058                     PostFilterRule fc = new PostFilterRule();
9059                     ids.Add(post.ScreenName);
9060                     if (post.RetweetedId == null)
9061                     {
9062                         fc.FilterName = post.ScreenName;
9063                     }
9064                     else
9065                     {
9066                         fc.FilterName = post.RetweetedBy;
9067                     }
9068                     fc.UseNameField = true;
9069                     fc.MoveMatches = mv;
9070                     fc.MarkMatches = mk;
9071                     fc.UseRegex = false;
9072                     fc.FilterByUrl = false;
9073                     tab.AddFilter(fc);
9074                 }
9075             }
9076             if (ids.Count != 0)
9077             {
9078                 List<string> atids = new List<string>();
9079                 foreach (string id in ids)
9080                 {
9081                     atids.Add("@" + id);
9082                 }
9083                 int cnt = AtIdSupl.ItemCount;
9084                 AtIdSupl.AddRangeItem(atids.ToArray());
9085                 if (AtIdSupl.ItemCount != cnt) ModifySettingAtId = true;
9086             }
9087
9088             this.ApplyPostFilters();
9089             SaveConfigsTabs();
9090         }
9091
9092         private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9093         {
9094             if (this._curList.SelectedIndices.Count == 0)
9095                 return;
9096
9097             // タブ選択ダイアログを表示(or追加)
9098             string tabName;
9099             if (!this.SelectTab(out tabName))
9100                 return;
9101
9102             var currentTab = this._statuses.Tabs[this._curTab.Text];
9103             var filterTab = (FilterTabModel)this._statuses.Tabs[tabName];
9104
9105             bool mv;
9106             bool mk;
9107             if (filterTab.TabType != MyCommon.TabUsageType.Mute)
9108             {
9109                 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9110                 this.MoveOrCopy(out mv, out mk);
9111             }
9112             else
9113             {
9114                 // ミュートタブでは常に MoveMatches を true にする
9115                 mv = true;
9116                 mk = false;
9117             }
9118
9119             // 振り分けルールに追加するSource
9120             var sources = new HashSet<string>();
9121
9122             foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9123             {
9124                 var post = currentTab[idx];
9125                 var filterSource = post.Source;
9126
9127                 if (sources.Add(filterSource))
9128                 {
9129                     var filter = new PostFilterRule
9130                     {
9131                         FilterSource = filterSource,
9132                         MoveMatches = mv,
9133                         MarkMatches = mk,
9134                         UseRegex = false,
9135                         FilterByUrl = false,
9136                     };
9137                     filterTab.AddFilter(filter);
9138                 }
9139             }
9140
9141             this.ApplyPostFilters();
9142             this.SaveConfigsTabs();
9143         }
9144
9145         private bool SelectTab(out string tabName)
9146         {
9147             do
9148             {
9149                 tabName = null;
9150
9151                 //振り分け先タブ選択
9152                 using (var dialog = new TabsDialog(_statuses))
9153                 {
9154                     if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9155
9156                     var selectedTab = dialog.SelectedTab;
9157                     tabName = selectedTab == null ? null : selectedTab.TabName;
9158                 }
9159
9160                 ListTab.SelectedTab.Focus();
9161                 //新規タブを選択→タブ作成
9162                 if (tabName == null)
9163                 {
9164                     using (InputTabName inputName = new InputTabName())
9165                     {
9166                         inputName.TabName = _statuses.MakeTabName("MyTab");
9167                         inputName.ShowDialog();
9168                         if (inputName.DialogResult == DialogResult.Cancel) return false;
9169                         tabName = inputName.TabName;
9170                     }
9171                     this.TopMost = this._cfgCommon.AlwaysTop;
9172                     if (!string.IsNullOrEmpty(tabName))
9173                     {
9174                         var tab = new FilterTabModel(tabName);
9175                         if (!_statuses.AddTab(tab) || !AddNewTab(tab, startup: false))
9176                         {
9177                             string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9178                             MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9179                             //もう一度タブ名入力
9180                         }
9181                         else
9182                         {
9183                             return true;
9184                         }
9185                     }
9186                 }
9187                 else
9188                 {
9189                     //既存タブを選択
9190                     return true;
9191                 }
9192             }
9193             while (true);
9194         }
9195
9196         private void MoveOrCopy(out bool move, out bool mark)
9197         {
9198             {
9199                 //移動するか?
9200                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9201                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9202                     move = false;
9203                 else
9204                     move = true;
9205             }
9206             if (!move)
9207             {
9208                 //マークするか?
9209                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9210                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9211                     mark = true;
9212                 else
9213                     mark = false;
9214             }
9215             else
9216             {
9217                 mark = false;
9218             }
9219         }
9220         private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9221         {
9222             this.CopyStot();
9223         }
9224
9225         private void CopyURLMenuItem_Click(object sender, EventArgs e)
9226         {
9227             this.CopyIdUri();
9228         }
9229
9230         private void SelectAllMenuItem_Click(object sender, EventArgs e)
9231         {
9232             if (StatusText.Focused)
9233             {
9234                 // 発言欄でのCtrl+A
9235                 StatusText.SelectAll();
9236             }
9237             else
9238             {
9239                 // ListView上でのCtrl+A
9240                 NativeMethods.SelectAllItems(this._curList);
9241             }
9242         }
9243
9244         private void MoveMiddle()
9245         {
9246             ListViewItem _item;
9247             int idx1;
9248             int idx2;
9249
9250             if (_curList.SelectedIndices.Count == 0) return;
9251
9252             int idx = _curList.SelectedIndices[0];
9253
9254             _item = _curList.GetItemAt(0, 25);
9255             if (_item == null)
9256                 idx1 = 0;
9257             else
9258                 idx1 = _item.Index;
9259
9260             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9261             if (_item == null)
9262                 idx2 = _curList.VirtualListSize - 1;
9263             else
9264                 idx2 = _item.Index;
9265
9266             idx -= Math.Abs(idx1 - idx2) / 2;
9267             if (idx < 0) idx = 0;
9268
9269             _curList.EnsureVisible(_curList.VirtualListSize - 1);
9270             _curList.EnsureVisible(idx);
9271         }
9272
9273         private async void OpenURLMenuItem_Click(object sender, EventArgs e)
9274         {
9275             var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
9276                 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
9277                 .ToArray();
9278
9279             if (linkElements.Length > 0)
9280             {
9281                 UrlDialog.ClearUrl();
9282
9283                 string openUrlStr = "";
9284
9285                 if (linkElements.Length == 1)
9286                 {
9287                     // ツイートに含まれる URL が 1 つのみの場合
9288                     //   => OpenURL ダイアログを表示せずにリンクを開く
9289
9290                     string urlStr = "";
9291                     try
9292                     {
9293                         urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
9294                     }
9295                     catch (ArgumentException)
9296                     {
9297                         //変なHTML?
9298                         return;
9299                     }
9300                     catch (Exception)
9301                     {
9302                         return;
9303                     }
9304                     if (string.IsNullOrEmpty(urlStr)) return;
9305                     openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9306
9307                     // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
9308                     await this.OpenUriAsync(new Uri(openUrlStr));
9309                 }
9310                 else
9311                 {
9312                     // ツイートに含まれる URL が複数ある場合
9313                     //   => OpenURL を表示しユーザーが選択したリンクを開く
9314
9315                     foreach (var linkElm in linkElements)
9316                     {
9317                         string urlStr = "";
9318                         string linkText = "";
9319                         string href = "";
9320                         try
9321                         {
9322                             urlStr = linkElm.GetAttribute("title");
9323                             href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9324                             if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9325                             linkText = linkElm.InnerText;
9326                         }
9327                         catch (ArgumentException)
9328                         {
9329                             //変なHTML?
9330                             return;
9331                         }
9332                         catch (Exception)
9333                         {
9334                             return;
9335                         }
9336                         if (string.IsNullOrEmpty(urlStr)) continue;
9337                         UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9338                     }
9339                     try
9340                     {
9341                         if (UrlDialog.ShowDialog() == DialogResult.OK)
9342                         {
9343                             openUrlStr = UrlDialog.SelectedUrl;
9344
9345                             // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
9346                             await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
9347                         }
9348                     }
9349                     catch (Exception)
9350                     {
9351                         return;
9352                     }
9353                     this.TopMost = this._cfgCommon.AlwaysTop;
9354                 }
9355             }
9356         }
9357
9358         private void ClearTabMenuItem_Click(object sender, EventArgs e)
9359         {
9360             if (string.IsNullOrEmpty(_rclickTabName)) return;
9361             ClearTab(_rclickTabName, true);
9362         }
9363
9364         private void ClearTab(string tabName, bool showWarning)
9365         {
9366             if (showWarning)
9367             {
9368                 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9369                 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9370                 {
9371                     return;
9372                 }
9373             }
9374
9375             _statuses.ClearTabIds(tabName);
9376             if (ListTab.SelectedTab.Text == tabName)
9377             {
9378                 _anchorPost = null;
9379                 _anchorFlag = false;
9380                 this.PurgeListViewItemCache();
9381                 _curItemIndex = -1;
9382                 _curPost = null;
9383             }
9384             foreach (TabPage tb in ListTab.TabPages)
9385             {
9386                 if (tb.Text == tabName)
9387                 {
9388                     tb.ImageIndex = -1;
9389                     ((DetailsListView)tb.Tag).VirtualListSize = 0;
9390                     break;
9391                 }
9392             }
9393             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9394
9395             SetMainWindowTitle();
9396             SetStatusLabelUrl();
9397         }
9398
9399         private static long followers = 0;
9400
9401         private void SetMainWindowTitle()
9402         {
9403             //メインウインドウタイトルの書き換え
9404             StringBuilder ttl = new StringBuilder(256);
9405             int ur = 0;
9406             int al = 0;
9407             if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9408                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9409                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9410                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9411             {
9412                 foreach (var tab in _statuses.Tabs.Values)
9413                 {
9414                     ur += tab.UnreadCount;
9415                     al += tab.AllCount;
9416                 }
9417             }
9418
9419             if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9420             ttl.Append(Application.ProductName);
9421             ttl.Append("  ");
9422             switch (this._cfgCommon.DispLatestPost)
9423             {
9424                 case MyCommon.DispTitleEnum.Ver:
9425                     ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9426                     break;
9427                 case MyCommon.DispTitleEnum.Post:
9428                     if (_history != null && _history.Count > 1)
9429                         ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9430                     break;
9431                 case MyCommon.DispTitleEnum.UnreadRepCount:
9432                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9433                     break;
9434                 case MyCommon.DispTitleEnum.UnreadAllCount:
9435                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9436                     break;
9437                 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9438                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9439                     break;
9440                 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9441                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9442                     break;
9443                 case MyCommon.DispTitleEnum.OwnStatus:
9444                     if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9445                     ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9446                     break;
9447             }
9448
9449             try
9450             {
9451                 this.Text = ttl.ToString();
9452             }
9453             catch (AccessViolationException)
9454             {
9455                 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9456             }
9457         }
9458
9459         private string GetStatusLabelText()
9460         {
9461             //ステータス欄にカウント表示
9462             //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9463             if (_statuses == null) return "";
9464             TabModel tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9465             TabModel tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9466             if (tbRep == null || tbDm == null) return "";
9467             int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9468             int ur = 0;
9469             int al = 0;
9470             int tur = 0;
9471             int tal = 0;
9472             StringBuilder slbl = new StringBuilder(256);
9473             try
9474             {
9475                 foreach (var tab in _statuses.Tabs.Values)
9476                 {
9477                     ur += tab.UnreadCount;
9478                     al += tab.AllCount;
9479                     if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9480                     {
9481                         tur = tab.UnreadCount;
9482                         tal = tab.AllCount;
9483                     }
9484                 }
9485             }
9486             catch (Exception)
9487             {
9488                 return "";
9489             }
9490
9491             UnreadCounter = ur;
9492             UnreadAtCounter = urat;
9493
9494             slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9495             if (this._cfgCommon.TimelinePeriod == 0)
9496             {
9497                 slbl.Append(Properties.Resources.SetStatusLabelText2);
9498             }
9499             else
9500             {
9501                 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9502             }
9503             return slbl.ToString();
9504         }
9505
9506         private async void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9507         {
9508             try
9509             {
9510                 if (this.InvokeRequired && !this.IsDisposed)
9511                 {
9512                     await this.InvokeAsync(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e));
9513                 }
9514                 else
9515                 {
9516                     var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9517                     SetApiStatusLabel(endpointName);
9518                 }
9519             }
9520             catch (ObjectDisposedException)
9521             {
9522                 return;
9523             }
9524             catch (InvalidOperationException)
9525             {
9526                 return;
9527             }
9528         }
9529
9530         private void SetApiStatusLabel(string endpointName = null)
9531         {
9532             if (_curTab == null)
9533             {
9534                 this.toolStripApiGauge.ApiEndpoint = null;
9535             }
9536             else
9537             {
9538                 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9539
9540                 if (endpointName == null)
9541                 {
9542                     // 表示中のタブに応じて更新
9543                     switch (tabType)
9544                     {
9545                         case MyCommon.TabUsageType.Home:
9546                         case MyCommon.TabUsageType.UserDefined:
9547                             endpointName = "/statuses/home_timeline";
9548                             break;
9549
9550                         case MyCommon.TabUsageType.Mentions:
9551                             endpointName = "/statuses/mentions_timeline";
9552                             break;
9553
9554                         case MyCommon.TabUsageType.Favorites:
9555                             endpointName = "/favorites/list";
9556                             break;
9557
9558                         case MyCommon.TabUsageType.DirectMessage:
9559                             endpointName = "/direct_messages";
9560                             break;
9561
9562                         case MyCommon.TabUsageType.UserTimeline:
9563                             endpointName = "/statuses/user_timeline";
9564                             break;
9565
9566                         case MyCommon.TabUsageType.Lists:
9567                             endpointName = "/lists/statuses";
9568                             break;
9569
9570                         case MyCommon.TabUsageType.PublicSearch:
9571                             endpointName = "/search/tweets";
9572                             break;
9573
9574                         case MyCommon.TabUsageType.Related:
9575                             endpointName = "/statuses/show/:id";
9576                             break;
9577
9578                         default:
9579                             break;
9580                     }
9581
9582                     this.toolStripApiGauge.ApiEndpoint = endpointName;
9583                 }
9584                 else
9585                 {
9586                     // 表示中のタブに関連する endpoint であれば更新
9587                     var update = false;
9588
9589                     switch (endpointName)
9590                     {
9591                         case "/statuses/home_timeline":
9592                             update = tabType == MyCommon.TabUsageType.Home ||
9593                                      tabType == MyCommon.TabUsageType.UserDefined;
9594                             break;
9595
9596                         case "/statuses/mentions_timeline":
9597                             update = tabType == MyCommon.TabUsageType.Mentions;
9598                             break;
9599
9600                         case "/favorites/list":
9601                             update = tabType == MyCommon.TabUsageType.Favorites;
9602                             break;
9603
9604                         case "/direct_messages:":
9605                             update = tabType == MyCommon.TabUsageType.DirectMessage;
9606                             break;
9607
9608                         case "/statuses/user_timeline":
9609                             update = tabType == MyCommon.TabUsageType.UserTimeline;
9610                             break;
9611
9612                         case "/lists/statuses":
9613                             update = tabType == MyCommon.TabUsageType.Lists;
9614                             break;
9615
9616                         case "/search/tweets":
9617                             update = tabType == MyCommon.TabUsageType.PublicSearch;
9618                             break;
9619
9620                         case "/statuses/show/:id":
9621                             update = tabType == MyCommon.TabUsageType.Related;
9622                             break;
9623
9624                         default:
9625                             break;
9626                     }
9627
9628                     if (update)
9629                     {
9630                         this.toolStripApiGauge.ApiEndpoint = endpointName;
9631                     }
9632                 }
9633             }
9634         }
9635
9636         private void SetStatusLabelUrl()
9637         {
9638             StatusLabelUrl.Text = GetStatusLabelText();
9639         }
9640
9641         public void SetStatusLabel(string text)
9642         {
9643             StatusLabel.Text = text;
9644         }
9645
9646         private static StringBuilder ur = new StringBuilder(64);
9647
9648         private void SetNotifyIconText()
9649         {
9650             // タスクトレイアイコンのツールチップテキスト書き換え
9651             // Tween [未読/@]
9652             ur.Remove(0, ur.Length);
9653             if (this._cfgCommon.DispUsername)
9654             {
9655                 ur.Append(tw.Username);
9656                 ur.Append(" - ");
9657             }
9658             ur.Append(Application.ProductName);
9659 #if DEBUG
9660             ur.Append("(Debug Build)");
9661 #endif
9662             if (UnreadCounter != -1 && UnreadAtCounter != -1)
9663             {
9664                 ur.Append(" [");
9665                 ur.Append(UnreadCounter);
9666                 ur.Append("/@");
9667                 ur.Append(UnreadAtCounter);
9668                 ur.Append("]");
9669             }
9670             NotifyIcon1.Text = ur.ToString();
9671         }
9672
9673         internal void CheckReplyTo(string StatusText)
9674         {
9675             MatchCollection m;
9676             //ハッシュタグの保存
9677             m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9678             string hstr = "";
9679             foreach (Match hm in m)
9680             {
9681                 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9682                 {
9683                     hstr += "#" + hm.Result("$3") + " ";
9684                     HashSupl.AddItem("#" + hm.Result("$3"));
9685                 }
9686             }
9687             if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9688             {
9689                 hstr += HashMgr.UseHash;
9690             }
9691             if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9692
9693             // 本当にリプライ先指定すべきかどうかの判定
9694             m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9695
9696             if (this._cfgCommon.UseAtIdSupplement)
9697             {
9698                 int bCnt = AtIdSupl.ItemCount;
9699                 foreach (Match mid in m)
9700                 {
9701                     AtIdSupl.AddItem(mid.Result("${id}"));
9702                 }
9703                 if (bCnt != AtIdSupl.ItemCount) ModifySettingAtId = true;
9704             }
9705
9706             // リプライ先ステータスIDの指定がない場合は指定しない
9707             if (this.inReplyTo == null)
9708                 return;
9709
9710             // 通常Reply
9711             // 次の条件を満たす場合に in_reply_to_status_id 指定
9712             // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9713             // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9714             // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9715
9716             if (m != null)
9717             {
9718                 var inReplyToScreenName = this.inReplyTo.Item2;
9719                 if (StatusText.StartsWith("@", StringComparison.Ordinal))
9720                 {
9721                     if (StatusText.StartsWith("@" + inReplyToScreenName, StringComparison.Ordinal)) return;
9722                 }
9723                 else
9724                 {
9725                     foreach (Match mid in m)
9726                     {
9727                         if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9728                     }
9729                 }
9730             }
9731
9732             this.inReplyTo = null;
9733         }
9734
9735         private void TweenMain_Resize(object sender, EventArgs e)
9736         {
9737             if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9738             {
9739                 this.Visible = false;
9740             }
9741             if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9742             {
9743                 // 現在の DPI と設定保存時の DPI との比を取得する
9744                 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9745
9746                 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9747                 //_mySize = this.ClientSize;                     //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9748                 this.DesktopLocation = _cfgLocal.FormLocation;
9749                 //_myLoc = this.DesktopLocation;                        //位置保持(最小化・最大化されたまま終了した場合の対応用)
9750
9751                 // Splitterの位置設定
9752                 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9753                 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9754                     splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9755                 {
9756                     this.SplitContainer1.SplitterDistance = splitterDistance;
9757                 }
9758
9759                 //発言欄複数行
9760                 StatusText.Multiline = _cfgLocal.StatusMultiline;
9761                 if (StatusText.Multiline)
9762                 {
9763                     var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9764                     int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9765                     if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9766                     {
9767                         SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9768                     }
9769                     StatusText.Height = statusTextHeight;
9770                 }
9771                 else
9772                 {
9773                     if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9774                     {
9775                         SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9776                     }
9777                 }
9778
9779                 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9780                 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9781                 {
9782                     this.SplitContainer3.SplitterDistance = previewDistance;
9783                 }
9784
9785                 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9786                 this.SplitContainer3.Panel2Collapsed = true;
9787
9788                 _initialLayout = false;
9789             }
9790             if (this.WindowState != FormWindowState.Minimized)
9791             {
9792                 _formWindowState = this.WindowState;
9793             }
9794         }
9795
9796         private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9797         {
9798             PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9799             this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9800             if (PlaySoundMenuItem.Checked)
9801             {
9802                 this._cfgCommon.PlaySound = true;
9803             }
9804             else
9805             {
9806                 this._cfgCommon.PlaySound = false;
9807             }
9808             ModifySettingCommon = true;
9809         }
9810
9811         private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9812         {
9813             if (this._initialLayout)
9814                 return;
9815
9816             int splitterDistance;
9817             switch (this.WindowState)
9818             {
9819                 case FormWindowState.Normal:
9820                     splitterDistance = this.SplitContainer1.SplitterDistance;
9821                     break;
9822                 case FormWindowState.Maximized:
9823                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9824                     var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9825                     splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9826                     splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9827                     break;
9828                 default:
9829                     return;
9830             }
9831
9832             this._mySpDis = splitterDistance;
9833             this.ModifySettingLocal = true;
9834         }
9835
9836         private async Task doRepliedStatusOpen()
9837         {
9838             if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9839             {
9840                 if (MyCommon.IsKeyDown(Keys.Shift))
9841                 {
9842                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9843                     return;
9844                 }
9845                 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9846                 {
9847                     PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9848                     MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9849                 }
9850                 else
9851                 {
9852                     foreach (TabModel tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9853                     {
9854                         if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9855                         PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9856                         MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9857                         return;
9858                     }
9859                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9860                 }
9861             }
9862         }
9863
9864         private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9865         {
9866             await this.doRepliedStatusOpen();
9867         }
9868
9869         /// <summary>
9870         /// UserPicture.Image に設定されている画像を破棄します。
9871         /// </summary>
9872         private void ClearUserPicture()
9873         {
9874             if (this.UserPicture.Image != null)
9875             {
9876                 var oldImage = this.UserPicture.Image;
9877                 this.UserPicture.Image = null;
9878                 oldImage.Dispose();
9879             }
9880         }
9881
9882         private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9883         {
9884             //発言詳細のアイコン右クリック時のメニュー制御
9885             if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9886             {
9887                 string name = _curPost.ImageUrl;
9888                 if (name != null && name.Length > 0)
9889                 {
9890                     int idx = name.LastIndexOf('/');
9891                     if (idx != -1)
9892                     {
9893                         name = Path.GetFileName(name.Substring(idx));
9894                         if (name.Contains("_normal.") || name.EndsWith("_normal", StringComparison.Ordinal))
9895                         {
9896                             name = name.Replace("_normal", "");
9897                             this.IconNameToolStripMenuItem.Text = name;
9898                             this.IconNameToolStripMenuItem.Enabled = true;
9899                         }
9900                         else
9901                         {
9902                             this.IconNameToolStripMenuItem.Enabled = false;
9903                             this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9904                         }
9905                     }
9906                     else
9907                     {
9908                         this.IconNameToolStripMenuItem.Enabled = false;
9909                         this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9910                     }
9911
9912                     this.ReloadIconToolStripMenuItem.Enabled = true;
9913
9914                     if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9915                     {
9916                         this.SaveIconPictureToolStripMenuItem.Enabled = true;
9917                     }
9918                     else
9919                     {
9920                         this.SaveIconPictureToolStripMenuItem.Enabled = false;
9921                     }
9922                 }
9923                 else
9924                 {
9925                     this.IconNameToolStripMenuItem.Enabled = false;
9926                     this.ReloadIconToolStripMenuItem.Enabled = false;
9927                     this.SaveIconPictureToolStripMenuItem.Enabled = false;
9928                     this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9929                 }
9930             }
9931             else
9932             {
9933                 this.IconNameToolStripMenuItem.Enabled = false;
9934                 this.ReloadIconToolStripMenuItem.Enabled = false;
9935                 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9936                 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9937             }
9938             if (NameLabel.Tag != null)
9939             {
9940                 string id = (string)NameLabel.Tag;
9941                 if (id == tw.Username)
9942                 {
9943                     FollowToolStripMenuItem.Enabled = false;
9944                     UnFollowToolStripMenuItem.Enabled = false;
9945                     ShowFriendShipToolStripMenuItem.Enabled = false;
9946                     ShowUserStatusToolStripMenuItem.Enabled = true;
9947                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9948                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9949                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9950                 }
9951                 else
9952                 {
9953                     FollowToolStripMenuItem.Enabled = true;
9954                     UnFollowToolStripMenuItem.Enabled = true;
9955                     ShowFriendShipToolStripMenuItem.Enabled = true;
9956                     ShowUserStatusToolStripMenuItem.Enabled = true;
9957                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9958                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9959                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9960                 }
9961             }
9962             else
9963             {
9964                 FollowToolStripMenuItem.Enabled = false;
9965                 UnFollowToolStripMenuItem.Enabled = false;
9966                 ShowFriendShipToolStripMenuItem.Enabled = false;
9967                 ShowUserStatusToolStripMenuItem.Enabled = false;
9968                 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9969                 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9970                 ListManageUserContextToolStripMenuItem3.Enabled = false;
9971             }
9972         }
9973
9974         private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9975         {
9976             if (_curPost == null) return;
9977             string name = _curPost.ImageUrl;
9978             await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
9979         }
9980
9981         private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
9982         {
9983             if (this._curPost == null) return;
9984
9985             await this.UserPicture.SetImageFromTask(async () =>
9986             {
9987                 var imageUrl = this._curPost.ImageUrl;
9988
9989                 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
9990                     .ConfigureAwait(false);
9991
9992                 return await image.CloneAsync()
9993                     .ConfigureAwait(false);
9994             });
9995         }
9996
9997         private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
9998         {
9999             if (_curPost == null) return;
10000             string name = _curPost.ImageUrl;
10001             name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
10002
10003             this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
10004
10005             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10006             {
10007                 // STUB
10008             }
10009         }
10010
10011         private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10012         {
10013             if (_curPost == null) return;
10014             string name = _curPost.ImageUrl;
10015
10016             this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
10017
10018             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10019             {
10020                 try
10021                 {
10022                     using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10023                     {
10024                         using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10025                         {
10026                             using (Graphics g = Graphics.FromImage(bmp2))
10027                             {
10028                                 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10029                                 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10030                             }
10031                             bmp2.Save(this.SaveFileDialog1.FileName);
10032                         }
10033                     }
10034                 }
10035                 catch (Exception)
10036                 {
10037                     //処理中にキャッシュアウトする可能性あり
10038                 }
10039             }
10040         }
10041
10042         private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10043         {
10044             var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10045             if (multiline != this.StatusText.Multiline)
10046             {
10047                 this.StatusText.Multiline = multiline;
10048                 MultiLineMenuItem.Checked = multiline;
10049                 ModifySettingLocal = true;
10050             }
10051         }
10052
10053         private void StatusText_MultilineChanged(object sender, EventArgs e)
10054         {
10055             if (this.StatusText.Multiline)
10056                 this.StatusText.ScrollBars = ScrollBars.Vertical;
10057             else
10058                 this.StatusText.ScrollBars = ScrollBars.None;
10059
10060             ModifySettingLocal = true;
10061         }
10062
10063         private void MultiLineMenuItem_Click(object sender, EventArgs e)
10064         {
10065             //発言欄複数行
10066             StatusText.Multiline = MultiLineMenuItem.Checked;
10067             _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10068             if (MultiLineMenuItem.Checked)
10069             {
10070                 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10071                     SplitContainer2.SplitterDistance = 0;
10072                 else
10073                     SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10074             }
10075             else
10076             {
10077                 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10078             }
10079             ModifySettingLocal = true;
10080         }
10081
10082         private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10083         {
10084             //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10085             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10086
10087             //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10088             //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10089             //Appendix A.  Collected ABNF for URI
10090             //http://www.ietf.org/rfc/rfc3986.txt
10091
10092             string result = "";
10093
10094             const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10095
10096             if (StatusText.SelectionLength > 0)
10097             {
10098                 string tmp = StatusText.SelectedText;
10099                 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10100                 if (tmp.StartsWith("http"))
10101                 {
10102                     // 文字列が選択されている場合はその文字列について処理
10103
10104                     //nico.ms使用、nicovideoにマッチしたら変換
10105                     if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10106                     {
10107                         result = nicoms.Shorten(tmp);
10108                     }
10109                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10110                     {
10111                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10112                         try
10113                         {
10114                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10115                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10116                             result = resultUri.AbsoluteUri;
10117                         }
10118                         catch (WebApiException e)
10119                         {
10120                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10121                             return false;
10122                         }
10123                         catch (UriFormatException e)
10124                         {
10125                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10126                             return false;
10127                         }
10128                     }
10129                     else
10130                     {
10131                         return true;
10132                     }
10133
10134                     if (!string.IsNullOrEmpty(result))
10135                     {
10136                         urlUndo undotmp = new urlUndo();
10137
10138                         StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10139                         StatusText.SelectedText = result;
10140
10141                         //undoバッファにセット
10142                         undotmp.Before = tmp;
10143                         undotmp.After = result;
10144
10145                         if (urlUndoBuffer == null)
10146                         {
10147                             urlUndoBuffer = new List<urlUndo>();
10148                             UrlUndoToolStripMenuItem.Enabled = true;
10149                         }
10150
10151                         urlUndoBuffer.Add(undotmp);
10152                     }
10153                 }
10154             }
10155             else
10156             {
10157                 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10158                                    @"(?<url>(?<protocol>https?://)" +
10159                                    @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10160                                    @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10161                                    @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10162                 // 正規表現にマッチしたURL文字列をtinyurl化
10163                 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10164                 {
10165                     if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10166                     string tmp = mt.Result("${url}");
10167                     if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10168                     urlUndo undotmp = new urlUndo();
10169
10170                     //選んだURLを選択(?)
10171                     StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10172
10173                     //nico.ms使用、nicovideoにマッチしたら変換
10174                     if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10175                     {
10176                         result = nicoms.Shorten(tmp);
10177                     }
10178                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10179                     {
10180                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10181                         try
10182                         {
10183                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10184                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10185                             result = resultUri.AbsoluteUri;
10186                         }
10187                         catch (HttpRequestException e)
10188                         {
10189                             // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10190                             // のように長いので「:」が含まれていればそれ以降のみを抽出する
10191                             var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10192
10193                             this.StatusLabel.Text = Converter_Type + ":" + message;
10194                             continue;
10195                         }
10196                         catch (WebApiException e)
10197                         {
10198                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10199                             continue;
10200                         }
10201                         catch (UriFormatException e)
10202                         {
10203                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10204                             continue;
10205                         }
10206                     }
10207                     else
10208                     {
10209                         continue;
10210                     }
10211
10212                     if (!string.IsNullOrEmpty(result))
10213                     {
10214                         StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10215                         StatusText.SelectedText = result;
10216                         //undoバッファにセット
10217                         undotmp.Before = mt.Result("${url}");
10218                         undotmp.After = result;
10219
10220                         if (urlUndoBuffer == null)
10221                         {
10222                             urlUndoBuffer = new List<urlUndo>();
10223                             UrlUndoToolStripMenuItem.Enabled = true;
10224                         }
10225
10226                         urlUndoBuffer.Add(undotmp);
10227                     }
10228                 }
10229             }
10230
10231             return true;
10232         }
10233
10234         private void doUrlUndo()
10235         {
10236             if (urlUndoBuffer != null)
10237             {
10238                 string tmp = StatusText.Text;
10239                 foreach (urlUndo data in urlUndoBuffer)
10240                 {
10241                     tmp = tmp.Replace(data.After, data.Before);
10242                 }
10243                 StatusText.Text = tmp;
10244                 urlUndoBuffer = null;
10245                 UrlUndoToolStripMenuItem.Enabled = false;
10246                 StatusText.SelectionStart = 0;
10247                 StatusText.SelectionLength = 0;
10248             }
10249         }
10250
10251         private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10252         {
10253             await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10254         }
10255
10256         private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10257         {
10258             await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10259         }
10260
10261         private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10262         {
10263             await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10264         }
10265
10266         private async void UxnuMenuItem_Click(object sender, EventArgs e)
10267         {
10268             await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10269         }
10270
10271         private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10272         {
10273             if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10274             {
10275                 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10276                 Random rnd = new Random();
10277                 // 前回使用した短縮URLサービス以外を選択する
10278                 do
10279                 {
10280                     svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10281                 }
10282                 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10283                 await UrlConvertAsync(svc);
10284             }
10285         }
10286
10287         private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10288         {
10289             doUrlUndo();
10290         }
10291
10292         private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10293         {
10294             this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10295             this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10296             _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10297             ModifySettingCommon = true;
10298         }
10299
10300         private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10301         {
10302             ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10303             this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10304             _cfgCommon.ListLock = ListLockMenuItem.Checked;
10305             ModifySettingCommon = true;
10306         }
10307
10308         private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10309         {
10310             // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10311             MenuStrip1.Tag = new Object();
10312             MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10313         }
10314
10315         private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10316         {
10317             if (this.Tag != null) // 設定された戻り先へ遷移
10318             {
10319                 if (this.Tag == this.ListTab.SelectedTab)
10320                     ((Control)this.ListTab.SelectedTab.Tag).Select();
10321                 else
10322                     ((Control)this.Tag).Select();
10323             }
10324             else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10325             {
10326                 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10327                 {
10328                     this.Tag = ListTab.SelectedTab.Tag;
10329                     ((Control)this.Tag).Select();
10330                 }
10331             }
10332             // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10333             MenuStrip1.Tag = null;
10334         }
10335
10336         private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10337         {
10338             DetailsListView lst = (DetailsListView)sender;
10339             if (_cfgLocal == null) return;
10340
10341             if (_iconCol)
10342             {
10343                 _cfgLocal.Width1 = lst.Columns[0].Width;
10344                 _cfgLocal.Width3 = lst.Columns[1].Width;
10345             }
10346             else
10347             {
10348                 int[] darr = new int[lst.Columns.Count];
10349                 for (int i = 0; i < lst.Columns.Count; i++)
10350                 {
10351                     darr[lst.Columns[i].DisplayIndex] = i;
10352                 }
10353                 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10354
10355                 for (int i = 0; i < lst.Columns.Count; i++)
10356                 {
10357                     switch (darr[i])
10358                     {
10359                         case 0:
10360                             _cfgLocal.DisplayIndex1 = i;
10361                             break;
10362                         case 1:
10363                             _cfgLocal.DisplayIndex2 = i;
10364                             break;
10365                         case 2:
10366                             _cfgLocal.DisplayIndex3 = i;
10367                             break;
10368                         case 3:
10369                             _cfgLocal.DisplayIndex4 = i;
10370                             break;
10371                         case 4:
10372                             _cfgLocal.DisplayIndex5 = i;
10373                             break;
10374                         case 5:
10375                             _cfgLocal.DisplayIndex6 = i;
10376                             break;
10377                         case 6:
10378                             _cfgLocal.DisplayIndex7 = i;
10379                             break;
10380                         case 7:
10381                             _cfgLocal.DisplayIndex8 = i;
10382                             break;
10383                     }
10384                 }
10385                 _cfgLocal.Width1 = lst.Columns[0].Width;
10386                 _cfgLocal.Width2 = lst.Columns[1].Width;
10387                 _cfgLocal.Width3 = lst.Columns[2].Width;
10388                 _cfgLocal.Width4 = lst.Columns[3].Width;
10389                 _cfgLocal.Width5 = lst.Columns[4].Width;
10390                 _cfgLocal.Width6 = lst.Columns[5].Width;
10391                 _cfgLocal.Width7 = lst.Columns[6].Width;
10392                 _cfgLocal.Width8 = lst.Columns[7].Width;
10393             }
10394             ModifySettingLocal = true;
10395             _isColumnChanged = true;
10396         }
10397
10398         private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10399         {
10400             DetailsListView lst = (DetailsListView)sender;
10401             if (_cfgLocal == null) return;
10402             if (_iconCol)
10403             {
10404                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10405                 {
10406                     _cfgLocal.Width1 = lst.Columns[0].Width;
10407                     ModifySettingLocal = true;
10408                     _isColumnChanged = true;
10409                 }
10410                 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10411                 {
10412                     _cfgLocal.Width3 = lst.Columns[1].Width;
10413                     ModifySettingLocal = true;
10414                     _isColumnChanged = true;
10415                 }
10416             }
10417             else
10418             {
10419                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10420                 {
10421                     _cfgLocal.Width1 = lst.Columns[0].Width;
10422                     ModifySettingLocal = true;
10423                     _isColumnChanged = true;
10424                 }
10425                 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10426                 {
10427                     _cfgLocal.Width2 = lst.Columns[1].Width;
10428                     ModifySettingLocal = true;
10429                     _isColumnChanged = true;
10430                 }
10431                 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10432                 {
10433                     _cfgLocal.Width3 = lst.Columns[2].Width;
10434                     ModifySettingLocal = true;
10435                     _isColumnChanged = true;
10436                 }
10437                 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10438                 {
10439                     _cfgLocal.Width4 = lst.Columns[3].Width;
10440                     ModifySettingLocal = true;
10441                     _isColumnChanged = true;
10442                 }
10443                 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10444                 {
10445                     _cfgLocal.Width5 = lst.Columns[4].Width;
10446                     ModifySettingLocal = true;
10447                     _isColumnChanged = true;
10448                 }
10449                 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10450                 {
10451                     _cfgLocal.Width6 = lst.Columns[5].Width;
10452                     ModifySettingLocal = true;
10453                     _isColumnChanged = true;
10454                 }
10455                 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10456                 {
10457                     _cfgLocal.Width7 = lst.Columns[6].Width;
10458                     ModifySettingLocal = true;
10459                     _isColumnChanged = true;
10460                 }
10461                 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10462                 {
10463                     _cfgLocal.Width8 = lst.Columns[7].Width;
10464                     ModifySettingLocal = true;
10465                     _isColumnChanged = true;
10466                 }
10467             }
10468             // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10469             //if (changed)
10470             //{
10471             //    SaveConfigsLocal();
10472             //}
10473         }
10474
10475         private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10476         {
10477             //発言詳細で「選択文字列をコピー」
10478             string _selText = this.PostBrowser.GetSelectedText();
10479             try
10480             {
10481                 Clipboard.SetDataObject(_selText, false, 5, 100);
10482             }
10483             catch (Exception ex)
10484             {
10485                 MessageBox.Show(ex.Message);
10486             }
10487         }
10488
10489         private async Task doSearchToolStrip(string url)
10490         {
10491             //発言詳細で「選択文字列で検索」(選択文字列取得)
10492             string _selText = this.PostBrowser.GetSelectedText();
10493
10494             if (_selText != null)
10495             {
10496                 if (url == Properties.Resources.SearchItem4Url)
10497                 {
10498                     //公式検索
10499                     AddNewTabForSearch(_selText);
10500                     return;
10501                 }
10502
10503                 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10504                 await this.OpenUriInBrowserAsync(tmp);
10505             }
10506         }
10507
10508         private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10509         {
10510             //発言詳細ですべて選択
10511             PostBrowser.Document.ExecCommand("SelectAll", false, null);
10512         }
10513
10514         private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10515         {
10516             await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10517         }
10518
10519         private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10520         {
10521             await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10522         }
10523
10524         private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10525         {
10526             await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10527         }
10528
10529         private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10530         {
10531             try
10532             {
10533                 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
10534                 {
10535                     if (link.GetAttribute("href") == this._postBrowserStatusText)
10536                     {
10537                         var linkStr = link.GetAttribute("title");
10538                         if (string.IsNullOrEmpty(linkStr))
10539                             linkStr = link.GetAttribute("href");
10540
10541                         Clipboard.SetDataObject(linkStr, false, 5, 100);
10542                         return;
10543                     }
10544                 }
10545
10546                 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10547             }
10548             catch (Exception ex)
10549             {
10550                 MessageBox.Show(ex.Message);
10551             }
10552         }
10553
10554         private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10555         {
10556             // URLコピーの項目の表示/非表示
10557             if (PostBrowser.StatusText.StartsWith("http", StringComparison.Ordinal))
10558             {
10559                 this._postBrowserStatusText = PostBrowser.StatusText;
10560                 string name = GetUserId();
10561                 UrlCopyContextMenuItem.Enabled = true;
10562                 if (name != null)
10563                 {
10564                     FollowContextMenuItem.Enabled = true;
10565                     RemoveContextMenuItem.Enabled = true;
10566                     FriendshipContextMenuItem.Enabled = true;
10567                     ShowUserStatusContextMenuItem.Enabled = true;
10568                     SearchPostsDetailToolStripMenuItem.Enabled = true;
10569                     IdFilterAddMenuItem.Enabled = true;
10570                     ListManageUserContextToolStripMenuItem.Enabled = true;
10571                     SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10572                 }
10573                 else
10574                 {
10575                     FollowContextMenuItem.Enabled = false;
10576                     RemoveContextMenuItem.Enabled = false;
10577                     FriendshipContextMenuItem.Enabled = false;
10578                     ShowUserStatusContextMenuItem.Enabled = false;
10579                     SearchPostsDetailToolStripMenuItem.Enabled = false;
10580                     IdFilterAddMenuItem.Enabled = false;
10581                     ListManageUserContextToolStripMenuItem.Enabled = false;
10582                     SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10583                 }
10584
10585                 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10586                     UseHashtagMenuItem.Enabled = true;
10587                 else
10588                     UseHashtagMenuItem.Enabled = false;
10589             }
10590             else
10591             {
10592                 this._postBrowserStatusText = "";
10593                 UrlCopyContextMenuItem.Enabled = false;
10594                 FollowContextMenuItem.Enabled = false;
10595                 RemoveContextMenuItem.Enabled = false;
10596                 FriendshipContextMenuItem.Enabled = false;
10597                 ShowUserStatusContextMenuItem.Enabled = false;
10598                 SearchPostsDetailToolStripMenuItem.Enabled = false;
10599                 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10600                 UseHashtagMenuItem.Enabled = false;
10601                 IdFilterAddMenuItem.Enabled = false;
10602                 ListManageUserContextToolStripMenuItem.Enabled = false;
10603             }
10604             // 文字列選択されていないときは選択文字列関係の項目を非表示に
10605             string _selText = this.PostBrowser.GetSelectedText();
10606             if (_selText == null)
10607             {
10608                 SelectionSearchContextMenuItem.Enabled = false;
10609                 SelectionCopyContextMenuItem.Enabled = false;
10610                 SelectionTranslationToolStripMenuItem.Enabled = false;
10611             }
10612             else
10613             {
10614                 SelectionSearchContextMenuItem.Enabled = true;
10615                 SelectionCopyContextMenuItem.Enabled = true;
10616                 SelectionTranslationToolStripMenuItem.Enabled = true;
10617             }
10618             //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10619             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10620             bool fAllFlag = false;
10621             foreach (Match mu in ma)
10622             {
10623                 if (mu.Result("${ScreenName}").ToLowerInvariant() != tw.Username.ToLowerInvariant())
10624                 {
10625                     fAllFlag = true;
10626                     break;
10627                 }
10628             }
10629             this.FriendshipAllMenuItem.Enabled = fAllFlag;
10630
10631             if (_curPost == null)
10632                 TranslationToolStripMenuItem.Enabled = false;
10633             else
10634                 TranslationToolStripMenuItem.Enabled = true;
10635
10636             e.Cancel = false;
10637         }
10638
10639         private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10640         {
10641             //発言詳細の選択文字列で現在のタブを検索
10642             string _selText = this.PostBrowser.GetSelectedText();
10643
10644             if (_selText != null)
10645             {
10646                 var searchOptions = new SearchWordDialog.SearchOptions(
10647                     SearchWordDialog.SearchType.Timeline,
10648                     _selText,
10649                     newTab: false,
10650                     caseSensitive: false,
10651                     useRegex: false);
10652
10653                 this.SearchDialog.ResultOptions = searchOptions;
10654
10655                 this.DoTabSearch(
10656                     searchOptions.Query,
10657                     searchOptions.CaseSensitive,
10658                     searchOptions.UseRegex,
10659                     SEARCHTYPE.NextSearch);
10660             }
10661         }
10662
10663         private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10664         {
10665             if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10666             ModifySettingLocal = true;
10667         }
10668
10669         private void TweenMain_DragDrop(object sender, DragEventArgs e)
10670         {
10671             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10672             {
10673                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10674                 {
10675                     SelectMedia_DragDrop(e);
10676                 }
10677             }
10678             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10679             {
10680                 var url = GetUrlFromDataObject(e.Data);
10681
10682                 string appendText;
10683                 if (url.Item2 == null)
10684                     appendText = url.Item1;
10685                 else
10686                     appendText = url.Item2 + " " + url.Item1;
10687
10688                 if (this.StatusText.TextLength == 0)
10689                     this.StatusText.Text = appendText;
10690                 else
10691                     this.StatusText.Text += " " + appendText;
10692             }
10693             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10694             {
10695                 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10696                 if (text != null)
10697                     this.StatusText.Text += text;
10698             }
10699             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10700             {
10701                 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10702                 if (data != null) StatusText.Text += data;
10703             }
10704         }
10705
10706         /// <summary>
10707         /// IDataObject から URL とタイトルの対を取得します
10708         /// </summary>
10709         /// <remarks>
10710         /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10711         /// </remarks>
10712         /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10713         /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10714         internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10715         {
10716             if (data.GetDataPresent("text/x-moz-url"))
10717             {
10718                 // Firefox, Google Chrome で利用可能
10719                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10720
10721                 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10722                 {
10723                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10724                     if (lines.Length < 2)
10725                         throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10726
10727                     return new Tuple<string, string>(lines[0], lines[1]);
10728                 }
10729             }
10730             else if (data.GetDataPresent("IESiteModeToUrl"))
10731             {
10732                 // Internet Exproler 用
10733                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10734
10735                 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10736                 {
10737                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10738                     if (lines.Length < 2)
10739                         throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10740
10741                     return new Tuple<string, string>(lines[0], lines[1]);
10742                 }
10743             }
10744             else if (data.GetDataPresent("UniformResourceLocatorW"))
10745             {
10746                 // それ以外のブラウザ向け
10747
10748                 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10749                 {
10750                     var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10751                     return new Tuple<string, string>(url, null);
10752                 }
10753             }
10754
10755             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10756         }
10757
10758         private void TweenMain_DragEnter(object sender, DragEventArgs e)
10759         {
10760             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10761             {
10762                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10763                 {
10764                     SelectMedia_DragEnter(e);
10765                     return;
10766                 }
10767             }
10768             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10769             {
10770                 e.Effect = DragDropEffects.Copy;
10771                 return;
10772             }
10773             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10774             {
10775                 e.Effect = DragDropEffects.Copy;
10776                 return;
10777             }
10778             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10779             {
10780                 e.Effect = DragDropEffects.Copy;
10781                 return;
10782             }
10783
10784             e.Effect = DragDropEffects.None;
10785         }
10786
10787         private void TweenMain_DragOver(object sender, DragEventArgs e)
10788         {
10789         }
10790
10791         public bool IsNetworkAvailable()
10792         {
10793             bool nw = true;
10794             nw = MyCommon.IsNetworkAvailable();
10795             _myStatusOnline = nw;
10796             return nw;
10797         }
10798
10799         public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10800         {
10801             var uriStr = uri.AbsoluteUri;
10802
10803             // OpenTween 内部で使用する URL
10804             if (uri.Authority == "opentween")
10805             {
10806                 await this.OpenInternalUriAsync(uri);
10807                 return;
10808             }
10809
10810             // ハッシュタグを含む Twitter 検索
10811             if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10812             {
10813                 // ハッシュタグの場合は、タブで開く
10814                 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10815                 var pos = unescapedQuery.IndexOf('#');
10816                 if (pos == -1) return;
10817
10818                 var hash = unescapedQuery.Substring(pos);
10819                 this.HashSupl.AddItem(hash);
10820                 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10821                 this.AddNewTabForSearch(hash);
10822                 return;
10823             }
10824
10825             // ユーザープロフィールURL
10826             // フラグが立っている場合は設定と逆の動作をする
10827             if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10828                 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10829             {
10830                 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10831                 if (userUriMatch.Success)
10832                 {
10833                     var screenName = userUriMatch.Groups["ScreenName"].Value;
10834                     if (this.IsTwitterId(screenName))
10835                     {
10836                         this.AddNewTabForUserTimeline(screenName);
10837                         return;
10838                     }
10839                 }
10840             }
10841
10842             // どのパターンにも該当しないURL
10843             await this.OpenUriInBrowserAsync(uriStr);
10844         }
10845
10846         /// <summary>
10847         /// OpenTween 内部の機能を呼び出すための URL を開きます
10848         /// </summary>
10849         private async Task OpenInternalUriAsync(Uri uri)
10850         {
10851             // ツイートを開く (//opentween/status/:status_id)
10852             var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10853             if (match.Success)
10854             {
10855                 var statusId = long.Parse(match.Groups[1].Value);
10856                 await this.OpenRelatedTab(statusId);
10857                 return;
10858             }
10859         }
10860
10861         public Task OpenUriInBrowserAsync(string UriString)
10862         {
10863             return Task.Run(() =>
10864             {
10865                 string myPath = UriString;
10866
10867                 try
10868                 {
10869                     var configBrowserPath = this._cfgLocal.BrowserPath;
10870                     if (!string.IsNullOrEmpty(configBrowserPath))
10871                     {
10872                         if (configBrowserPath.StartsWith("\"", StringComparison.Ordinal) && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal) > -1)
10873                         {
10874                             int sep = configBrowserPath.IndexOf("\"", 2, StringComparison.Ordinal);
10875                             string browserPath = configBrowserPath.Substring(1, sep - 1);
10876                             string arg = "";
10877                             if (sep < configBrowserPath.Length - 1)
10878                             {
10879                                 arg = configBrowserPath.Substring(sep + 1);
10880                             }
10881                             myPath = arg + " " + myPath;
10882                             System.Diagnostics.Process.Start(browserPath, myPath);
10883                         }
10884                         else
10885                         {
10886                             System.Diagnostics.Process.Start(configBrowserPath, myPath);
10887                         }
10888                     }
10889                     else
10890                     {
10891                         System.Diagnostics.Process.Start(myPath);
10892                     }
10893                 }
10894                 catch (Exception)
10895                 {
10896                     //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10897                 }
10898             });
10899         }
10900
10901         private void ListTabSelect(TabPage _tab)
10902         {
10903             SetListProperty();
10904
10905             this.PurgeListViewItemCache();
10906
10907             _curTab = _tab;
10908             _curList = (DetailsListView)_tab.Tag;
10909             if (_curList.SelectedIndices.Count > 0)
10910             {
10911                 _curItemIndex = _curList.SelectedIndices[0];
10912                 _curPost = GetCurTabPost(_curItemIndex);
10913             }
10914             else
10915             {
10916                 _curItemIndex = -1;
10917                 _curPost = null;
10918             }
10919
10920             _anchorPost = null;
10921             _anchorFlag = false;
10922
10923             if (_iconCol)
10924             {
10925                 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10926             }
10927             else
10928             {
10929                 for (int i = 0; i < _curList.Columns.Count; i++)
10930                 {
10931                     ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10932                 }
10933             }
10934         }
10935
10936         private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10937         {
10938             ListTabSelect(e.TabPage);
10939         }
10940
10941         private void SelectListItem(DetailsListView LView, int Index)
10942         {
10943             //単一
10944             Rectangle bnd = new Rectangle();
10945             bool flg = false;
10946             var item = LView.FocusedItem;
10947             if (item != null)
10948             {
10949                 bnd = item.Bounds;
10950                 flg = true;
10951             }
10952
10953             do
10954             {
10955                 LView.SelectedIndices.Clear();
10956             }
10957             while (LView.SelectedIndices.Count > 0);
10958             item = LView.Items[Index];
10959             item.Selected = true;
10960             item.Focused = true;
10961
10962             if (flg) LView.Invalidate(bnd);
10963         }
10964
10965         private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10966         {
10967             //複数
10968             Rectangle bnd = new Rectangle();
10969             bool flg = false;
10970             var item = LView.FocusedItem;
10971             if (item != null)
10972             {
10973                 bnd = item.Bounds;
10974                 flg = true;
10975             }
10976
10977             if (Index != null)
10978             {
10979                 do
10980                 {
10981                     LView.SelectedIndices.Clear();
10982                 }
10983                 while (LView.SelectedIndices.Count > 0);
10984                 LView.SelectItems(Index);
10985             }
10986             if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
10987             {
10988                 LView.SelectionMark = selectionMarkIndex;
10989             }
10990             if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
10991             {
10992                 LView.Items[focusedIndex].Focused = true;
10993             }
10994             else if (Index != null && Index.Length != 0)
10995             {
10996                 LView.Items[Index.Last()].Focused = true;
10997             }
10998
10999             if (flg) LView.Invalidate(bnd);
11000         }
11001
11002         private void StartUserStream()
11003         {
11004             tw.NewPostFromStream += tw_NewPostFromStream;
11005             tw.UserStreamStarted += tw_UserStreamStarted;
11006             tw.UserStreamStopped += tw_UserStreamStopped;
11007             tw.PostDeleted += tw_PostDeleted;
11008             tw.UserStreamEventReceived += tw_UserStreamEventArrived;
11009
11010             this.RefreshUserStreamsMenu();
11011
11012             if (this._cfgCommon.UserstreamStartup)
11013                 tw.StartUserStream();
11014         }
11015
11016         private async void TweenMain_Shown(object sender, EventArgs e)
11017         {
11018             try
11019             {
11020                 using (ControlTransaction.Update(this.PostBrowser))
11021                 {
11022                     PostBrowser.Url = new Uri("about:blank");
11023                     PostBrowser.DocumentText = "";       //発言詳細部初期化
11024                 }
11025             }
11026             catch (Exception)
11027             {
11028             }
11029
11030             NotifyIcon1.Visible = true;
11031
11032             if (this.IsNetworkAvailable())
11033             {
11034                 StartUserStream();
11035
11036                 var loadTasks = new List<Task>
11037                 {
11038                     this.RefreshMuteUserIdsAsync(),
11039                     this.RefreshBlockIdsAsync(),
11040                     this.RefreshNoRetweetIdsAsync(),
11041                     this.RefreshTwitterConfigurationAsync(),
11042                     this.GetHomeTimelineAsync(),
11043                     this.GetReplyAsync(),
11044                     this.GetDirectMessagesAsync(),
11045                     this.GetPublicSearchAllAsync(),
11046                     this.GetUserTimelineAllAsync(),
11047                     this.GetListTimelineAllAsync(),
11048                 };
11049
11050                 if (this._cfgCommon.StartupFollowers)
11051                     loadTasks.Add(this.RefreshFollowerIdsAsync());
11052
11053                 if (this._cfgCommon.GetFav)
11054                     loadTasks.Add(this.GetFavoritesAsync());
11055
11056                 var allTasks = Task.WhenAll(loadTasks);
11057
11058                 var i = 0;
11059                 while (true)
11060                 {
11061                     var timeout = Task.Delay(5000);
11062                     if (await Task.WhenAny(allTasks, timeout) != timeout)
11063                         break;
11064
11065                     i += 1;
11066                     if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11067
11068                     if (MyCommon._endingFlag)
11069                         return;
11070                 }
11071
11072                 if (MyCommon._endingFlag) return;
11073
11074                 if (ApplicationSettings.VersionInfoUrl != null)
11075                 {
11076                     //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11077                     if (this._cfgCommon.StartupVersion)
11078                         await this.CheckNewVersion(true);
11079                 }
11080                 else
11081                 {
11082                     // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11083                     this.VerUpMenuItem.Enabled = false;
11084                     this.VerUpMenuItem.Available = false;
11085                     this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11086                 }
11087
11088                 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11089                 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11090                 {
11091                     MessageBox.Show(Properties.Resources.ReAuthorizeText);
11092                     SettingStripMenuItem_Click(null, null);
11093                 }
11094
11095                 // 取得失敗の場合は再試行する
11096                 var reloadTasks = new List<Task>();
11097
11098                 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11099                     reloadTasks.Add(this.RefreshFollowerIdsAsync());
11100
11101                 if (!tw.GetNoRetweetSuccess)
11102                     reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11103
11104                 if (this.tw.Configuration.PhotoSizeLimit == 0)
11105                     reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11106
11107                 await Task.WhenAll(reloadTasks);
11108             }
11109
11110             _initial = false;
11111
11112             TimerTimeline.Enabled = true;
11113         }
11114
11115         private async Task doGetFollowersMenu()
11116         {
11117             await this.RefreshFollowerIdsAsync();
11118             await this.DispSelectedPost(true);
11119         }
11120
11121         private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11122         {
11123             await this.doGetFollowersMenu();
11124         }
11125
11126         private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
11127         {
11128             doReTweetUnofficial();
11129         }
11130
11131         private async Task doReTweetOfficial(bool isConfirm)
11132         {
11133             //公式RT
11134             if (this.ExistCurrentPost)
11135             {
11136                 if (_curPost.IsProtect)
11137                 {
11138                     MessageBox.Show("Protected.");
11139                     _DoFavRetweetFlags = false;
11140                     return;
11141                 }
11142                 if (_curList.SelectedIndices.Count > 15)
11143                 {
11144                     MessageBox.Show(Properties.Resources.RetweetLimitText);
11145                     _DoFavRetweetFlags = false;
11146                     return;
11147                 }
11148                 else if (_curList.SelectedIndices.Count > 1)
11149                 {
11150                     string QuestionText = Properties.Resources.RetweetQuestion2;
11151                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11152                     switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11153                     {
11154                         case DialogResult.Cancel:
11155                         case DialogResult.No:
11156                             _DoFavRetweetFlags = false;
11157                             return;
11158                     }
11159                 }
11160                 else
11161                 {
11162                     if (_curPost.IsDm || _curPost.IsMe)
11163                     {
11164                         _DoFavRetweetFlags = false;
11165                         return;
11166                     }
11167                     if (!this._cfgCommon.RetweetNoConfirm)
11168                     {
11169                         string Questiontext = Properties.Resources.RetweetQuestion1;
11170                         if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11171                         if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11172                         {
11173                             _DoFavRetweetFlags = false;
11174                             return;
11175                         }
11176                     }
11177                 }
11178
11179                 var statusIds = new List<long>();
11180                 foreach (int idx in _curList.SelectedIndices)
11181                 {
11182                     PostClass post = GetCurTabPost(idx);
11183                     if (!post.IsMe && !post.IsProtect && !post.IsDm)
11184                         statusIds.Add(post.StatusId);
11185                 }
11186
11187                 await this.RetweetAsync(statusIds);
11188             }
11189         }
11190
11191         private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11192         {
11193             await this.doReTweetOfficial(true);
11194         }
11195
11196         private async Task FavoritesRetweetOfficial()
11197         {
11198             if (!this.ExistCurrentPost) return;
11199             _DoFavRetweetFlags = true;
11200             var retweetTask = this.doReTweetOfficial(true);
11201             if (_DoFavRetweetFlags)
11202             {
11203                 _DoFavRetweetFlags = false;
11204                 var favoriteTask = this.FavoriteChange(true, false);
11205
11206                 await Task.WhenAll(retweetTask, favoriteTask);
11207             }
11208             else
11209             {
11210                 await retweetTask;
11211             }
11212         }
11213
11214         private async Task FavoritesRetweetUnofficial()
11215         {
11216             if (this.ExistCurrentPost && !_curPost.IsDm)
11217             {
11218                 _DoFavRetweetFlags = true;
11219                 var favoriteTask = this.FavoriteChange(true);
11220                 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11221                 {
11222                     _DoFavRetweetFlags = false;
11223                     doReTweetUnofficial();
11224                 }
11225
11226                 await favoriteTask;
11227             }
11228         }
11229
11230         /// <summary>
11231         /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11232         /// </summary>
11233         /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11234         /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11235         /// <returns>復元されたツイート本文</returns>
11236         internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11237         {
11238             // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11239
11240             // 通常の URL
11241             statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11242             // メンション
11243             statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11244             // ハッシュタグ
11245             statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11246
11247             // <br> 除去
11248             if (multiline)
11249                 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11250             else
11251                 statusHtml = statusHtml.Replace("<br>", " ");
11252
11253             // &nbsp; は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11254             // 現状では半角スペースの代用として &nbsp; を使用しているため U+0020 に置換します
11255             statusHtml = statusHtml.Replace("&nbsp;", " ");
11256
11257             return WebUtility.HtmlDecode(statusHtml);
11258         }
11259
11260         private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11261         {
11262             if (_curPost != null)
11263                 await this.DispSelectedPost(true);
11264         }
11265
11266         private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11267         {
11268             if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11269                 DebugModeToolStripMenuItem.Visible = true;
11270             else
11271                 DebugModeToolStripMenuItem.Visible = false;
11272         }
11273
11274         private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11275         {
11276             this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11277         }
11278
11279         private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11280         {
11281             ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11282         }
11283
11284         private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11285         {
11286             if (TraceOutToolStripMenuItem.Checked)
11287                 MyCommon.TraceFlag = true;
11288             else
11289                 MyCommon.TraceFlag = false;
11290         }
11291
11292         private void TweenMain_Deactivate(object sender, EventArgs e)
11293         {
11294             //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11295             this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11296         }
11297
11298         private void TabRenameMenuItem_Click(object sender, EventArgs e)
11299         {
11300             if (string.IsNullOrEmpty(_rclickTabName)) return;
11301             TabRename(ref _rclickTabName);
11302         }
11303
11304         private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11305         {
11306             await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11307         }
11308
11309         private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11310         {
11311             await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11312         }
11313
11314         private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11315         {
11316             TwitterApiStatus apiStatus;
11317
11318             using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
11319             {
11320                 var cancellationToken = dialog.EnableCancellation();
11321
11322                 try
11323                 {
11324                     var task = this.tw.GetInfoApi();
11325                     apiStatus = await dialog.WaitForAsync(this, task);
11326                 }
11327                 catch (WebApiException)
11328                 {
11329                     apiStatus = null;
11330                 }
11331
11332                 if (cancellationToken.IsCancellationRequested)
11333                     return;
11334
11335                 if (apiStatus == null)
11336                 {
11337                     MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11338                     return;
11339                 }
11340             }
11341
11342             using (var apiDlg = new ApiInfoDialog())
11343             {
11344                 apiDlg.ShowDialog(this);
11345             }
11346         }
11347
11348         private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
11349         {
11350             var id = _curPost?.ScreenName ?? "";
11351
11352             await this.FollowCommand(id);
11353         }
11354
11355         private async Task FollowCommand(string id)
11356         {
11357             using (var inputName = new InputTabName())
11358             {
11359                 inputName.FormTitle = "Follow";
11360                 inputName.FormDescription = Properties.Resources.FRMessage1;
11361                 inputName.TabName = id;
11362
11363                 if (inputName.ShowDialog(this) != DialogResult.OK)
11364                     return;
11365                 if (string.IsNullOrWhiteSpace(inputName.TabName))
11366                     return;
11367
11368                 id = inputName.TabName.Trim();
11369             }
11370
11371             using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11372             {
11373                 try
11374                 {
11375                     var task = this.twitterApi.FriendshipsCreate(id);
11376                     await dialog.WaitForAsync(this, task);
11377                 }
11378                 catch (WebApiException ex)
11379                 {
11380                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11381                     return;
11382                 }
11383             }
11384
11385             MessageBox.Show(Properties.Resources.FRMessage3);
11386         }
11387
11388         private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11389         {
11390             var id = _curPost?.ScreenName ?? "";
11391
11392             await this.RemoveCommand(id, false);
11393         }
11394
11395         private async Task RemoveCommand(string id, bool skipInput)
11396         {
11397             if (!skipInput)
11398             {
11399                 using (var inputName = new InputTabName())
11400                 {
11401                     inputName.FormTitle = "Unfollow";
11402                     inputName.FormDescription = Properties.Resources.FRMessage1;
11403                     inputName.TabName = id;
11404
11405                     if (inputName.ShowDialog(this) != DialogResult.OK)
11406                         return;
11407                     if (string.IsNullOrWhiteSpace(inputName.TabName))
11408                         return;
11409
11410                     id = inputName.TabName.Trim();
11411                 }
11412             }
11413
11414             using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11415             {
11416                 try
11417                 {
11418                     var task = this.twitterApi.FriendshipsDestroy(id);
11419                     await dialog.WaitForAsync(this, task);
11420                 }
11421                 catch (WebApiException ex)
11422                 {
11423                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11424                     return;
11425                 }
11426             }
11427
11428             MessageBox.Show(Properties.Resources.FRMessage3);
11429         }
11430
11431         private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11432         {
11433             var id = _curPost?.ScreenName ?? "";
11434
11435             await this.ShowFriendship(id);
11436         }
11437
11438         private async Task ShowFriendship(string id)
11439         {
11440             using (var inputName = new InputTabName())
11441             {
11442                 inputName.FormTitle = "Show Friendships";
11443                 inputName.FormDescription = Properties.Resources.FRMessage1;
11444                 inputName.TabName = id;
11445
11446                 if (inputName.ShowDialog(this) != DialogResult.OK)
11447                     return;
11448                 if (string.IsNullOrWhiteSpace(inputName.TabName))
11449                     return;
11450
11451                 id = inputName.TabName.Trim();
11452             }
11453
11454             bool isFollowing, isFollowed;
11455
11456             using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11457             {
11458                 var cancellationToken = dialog.EnableCancellation();
11459
11460                 try
11461                 {
11462                     var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11463                     var friendship = await dialog.WaitForAsync(this, task);
11464
11465                     isFollowing = friendship.Relationship.Source.Following;
11466                     isFollowed = friendship.Relationship.Source.FollowedBy;
11467                 }
11468                 catch (WebApiException ex)
11469                 {
11470                     if (!cancellationToken.IsCancellationRequested)
11471                         MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11472                     return;
11473                 }
11474
11475                 if (cancellationToken.IsCancellationRequested)
11476                     return;
11477             }
11478
11479             string result = "";
11480             if (isFollowing)
11481             {
11482                 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11483             }
11484             else
11485             {
11486                 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11487             }
11488             if (isFollowed)
11489             {
11490                 result += Properties.Resources.GetFriendshipInfo3;
11491             }
11492             else
11493             {
11494                 result += Properties.Resources.GetFriendshipInfo4;
11495             }
11496             result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11497             MessageBox.Show(result);
11498         }
11499
11500         private async Task ShowFriendship(string[] ids)
11501         {
11502             foreach (string id in ids)
11503             {
11504                 bool isFollowing, isFollowed;
11505
11506                 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11507                 {
11508                     var cancellationToken = dialog.EnableCancellation();
11509
11510                     try
11511                     {
11512                         var task = this.twitterApi.FriendshipsShow(this.twitterApi.CurrentScreenName, id);
11513                         var friendship = await dialog.WaitForAsync(this, task);
11514
11515                         isFollowing = friendship.Relationship.Source.Following;
11516                         isFollowed = friendship.Relationship.Source.FollowedBy;
11517                     }
11518                     catch (WebApiException ex)
11519                     {
11520                         if (!cancellationToken.IsCancellationRequested)
11521                             MessageBox.Show($"Err:{ex.Message}(FriendshipsShow)");
11522                         return;
11523                     }
11524
11525                     if (cancellationToken.IsCancellationRequested)
11526                         return;
11527                 }
11528
11529                 string result = "";
11530                 string ff = "";
11531
11532                 ff = "  ";
11533                 if (isFollowing)
11534                 {
11535                     ff += Properties.Resources.GetFriendshipInfo1;
11536                 }
11537                 else
11538                 {
11539                     ff += Properties.Resources.GetFriendshipInfo2;
11540                 }
11541
11542                 ff += System.Environment.NewLine + "  ";
11543                 if (isFollowed)
11544                 {
11545                     ff += Properties.Resources.GetFriendshipInfo3;
11546                 }
11547                 else
11548                 {
11549                     ff += Properties.Resources.GetFriendshipInfo4;
11550                 }
11551                 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11552                 if (isFollowing)
11553                 {
11554                     if (MessageBox.Show(
11555                         Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11556                         MessageBoxButtons.YesNo,
11557                         MessageBoxIcon.Question,
11558                         MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11559                     {
11560                         await this.RemoveCommand(id, true);
11561                     }
11562                 }
11563                 else
11564                 {
11565                     MessageBox.Show(result);
11566                 }
11567             }
11568         }
11569
11570         private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11571         {
11572             await this.doShowUserStatus(tw.Username, false);
11573             //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11574             //{
11575             //    doShowUserStatus(tw.Username, false);
11576             //}
11577             //else
11578             //{
11579             //    MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11580             //    return;
11581             //}
11582         }
11583
11584         // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11585         // URLから切り出した文字列を渡す
11586
11587         public bool IsTwitterId(string name)
11588         {
11589             if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11590                 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11591             else
11592                 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLowerInvariant());
11593         }
11594
11595         private string GetUserId()
11596         {
11597             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11598             if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11599                 return m.Result("${ScreenName}");
11600             else
11601                 return null;
11602         }
11603
11604         private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11605         {
11606             string name = GetUserId();
11607             if (name != null)
11608                 await this.FollowCommand(name);
11609         }
11610
11611         private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11612         {
11613             string name = GetUserId();
11614             if (name != null)
11615                 await this.RemoveCommand(name, false);
11616         }
11617
11618         private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11619         {
11620             string name = GetUserId();
11621             if (name != null)
11622                 await this.ShowFriendship(name);
11623         }
11624
11625         private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11626         {
11627             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11628             List<string> ids = new List<string>();
11629             foreach (Match mu in ma)
11630             {
11631                 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11632                 {
11633                     ids.Add(mu.Result("${ScreenName}"));
11634                 }
11635             }
11636
11637             await this.ShowFriendship(ids.ToArray());
11638         }
11639
11640         private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11641         {
11642             string name = GetUserId();
11643             if (name != null)
11644                 await this.ShowUserStatus(name);
11645         }
11646
11647         private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11648         {
11649             string name = GetUserId();
11650             if (name != null) AddNewTabForUserTimeline(name);
11651         }
11652
11653         private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11654         {
11655             string name = GetUserId();
11656             if (name != null) AddNewTabForSearch("@" + name);
11657         }
11658
11659         private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11660         {
11661             ModifySettingCommon = true;
11662         }
11663
11664         private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11665         {
11666             ModifySettingCommon = true;
11667         }
11668
11669         private void doQuoteOfficial()
11670         {
11671             if (this.ExistCurrentPost)
11672             {
11673                 if (_curPost.IsDm ||
11674                     !StatusText.Enabled) return;
11675
11676                 if (_curPost.IsProtect)
11677                 {
11678                     MessageBox.Show("Protected.");
11679                     return;
11680                 }
11681
11682                 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11683
11684                 this.inReplyTo = null;
11685
11686                 StatusText.SelectionStart = 0;
11687                 StatusText.Focus();
11688             }
11689         }
11690
11691         private void doReTweetUnofficial()
11692         {
11693             //RT @id:内容
11694             if (this.ExistCurrentPost)
11695             {
11696                 if (_curPost.IsDm || !StatusText.Enabled)
11697                     return;
11698
11699                 if (_curPost.IsProtect)
11700                 {
11701                     MessageBox.Show("Protected.");
11702                     return;
11703                 }
11704                 string rtdata = _curPost.Text;
11705                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11706
11707                 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11708
11709                 // 投稿時に in_reply_to_status_id を付加する
11710                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11711                 var inReplyToScreenName = this._curPost.ScreenName;
11712                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11713
11714                 StatusText.SelectionStart = 0;
11715                 StatusText.Focus();
11716             }
11717         }
11718
11719         private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11720         {
11721             doQuoteOfficial();
11722         }
11723
11724         private void SearchButton_Click(object sender, EventArgs e)
11725         {
11726             //公式検索
11727             Control pnl = ((Control)sender).Parent;
11728             if (pnl == null) return;
11729             string tbName = pnl.Parent.Text;
11730             var tb = (PublicSearchTabModel)_statuses.Tabs[tbName];
11731             ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11732             ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11733             cmb.Text = cmb.Text.Trim();
11734             // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11735             bool Quote = false;
11736             StringBuilder buf = new StringBuilder();
11737             char[] c = cmb.Text.ToCharArray();
11738             for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11739             {
11740                 if (cnt > cmb.Text.Length - 4)
11741                 {
11742                     buf.Append(cmb.Text.Substring(cnt));
11743                     break;
11744                 }
11745                 if (c[cnt] == '"')
11746                 {
11747                     Quote = !Quote;
11748                 }
11749                 else
11750                 {
11751                     if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11752                     {
11753                         buf.Append(" OR ");
11754                         cnt += 3;
11755                         continue;
11756                     }
11757                 }
11758                 buf.Append(c[cnt]);
11759             }
11760             cmb.Text = buf.ToString();
11761
11762             var listView = (DetailsListView)pnl.Parent.Tag;
11763
11764             var queryChanged = tb.SearchWords != cmb.Text || tb.SearchLang != cmbLang.Text;
11765
11766             tb.SearchWords = cmb.Text;
11767             tb.SearchLang = cmbLang.Text;
11768             if (string.IsNullOrEmpty(cmb.Text))
11769             {
11770                 listView.Focus();
11771                 SaveConfigsTabs();
11772                 return;
11773             }
11774             if (queryChanged)
11775             {
11776                 int idx = cmb.Items.IndexOf(tb.SearchWords);
11777                 if (idx > -1) cmb.Items.RemoveAt(idx);
11778                 cmb.Items.Insert(0, tb.SearchWords);
11779                 cmb.Text = tb.SearchWords;
11780                 cmb.SelectAll();
11781                 this.PurgeListViewItemCache();
11782                 listView.VirtualListSize = 0;
11783                 _statuses.ClearTabIds(tbName);
11784                 SaveConfigsTabs();   //検索条件の保存
11785             }
11786
11787             this.GetPublicSearchAsync(tb);
11788             listView.Focus();
11789         }
11790
11791         private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11792         {
11793             //もっと前を取得
11794             await this.DoRefreshMore();
11795         }
11796
11797         /// <summary>
11798         /// 指定されたタブのListTabにおける位置を返します
11799         /// </summary>
11800         /// <remarks>
11801         /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11802         /// </remarks>
11803         public int GetTabPageIndex(string tabName)
11804         {
11805             var index = 0;
11806             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11807             {
11808                 if (tabPage.Text == tabName)
11809                     return index;
11810
11811                 index++;
11812             }
11813
11814             return -1;
11815         }
11816
11817         private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11818         {
11819             if (_statuses.RemovedTab.Count == 0)
11820             {
11821                 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11822                 return;
11823             }
11824             else
11825             {
11826                 DetailsListView listView = null;
11827
11828                 TabModel tb = _statuses.RemovedTab.Pop();
11829                 if (tb.TabType == MyCommon.TabUsageType.Related)
11830                 {
11831                     var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11832                     if (relatedTab != null)
11833                     {
11834                         // 関連発言なら既存のタブを置き換える
11835                         tb.TabName = relatedTab.TabName;
11836                         this.ClearTab(tb.TabName, false);
11837                         _statuses.Tabs[tb.TabName] = tb;
11838
11839                         for (int i = 0; i < ListTab.TabPages.Count; i++)
11840                         {
11841                             var tabPage = ListTab.TabPages[i];
11842                             if (tb.TabName == tabPage.Text)
11843                             {
11844                                 listView = (DetailsListView)tabPage.Tag;
11845                                 ListTab.SelectedIndex = i;
11846                                 break;
11847                             }
11848                         }
11849                     }
11850                     else
11851                     {
11852                         const string TabName = "Related Tweets";
11853                         string renamed = TabName;
11854                         for (int i = 2; i <= 100; i++)
11855                         {
11856                             if (!_statuses.ContainsTab(renamed)) break;
11857                             renamed = TabName + i.ToString();
11858                         }
11859                         tb.TabName = renamed;
11860
11861                         _statuses.AddTab(tb);
11862                         AddNewTab(tb, startup: false);
11863
11864                         var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11865                         listView = (DetailsListView)tabPage.Tag;
11866                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11867                     }
11868                 }
11869                 else
11870                 {
11871                     string renamed = tb.TabName;
11872                     for (int i = 1; i < int.MaxValue; i++)
11873                     {
11874                         if (!_statuses.ContainsTab(renamed)) break;
11875                         renamed = tb.TabName + "(" + i.ToString() + ")";
11876                     }
11877                     tb.TabName = renamed;
11878
11879                     _statuses.AddTab(tb);
11880                     AddNewTab(tb, startup: false);
11881
11882                     var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11883                     listView = (DetailsListView)tabPage.Tag;
11884                     ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11885                 }
11886                 SaveConfigsTabs();
11887
11888                 if (listView != null)
11889                 {
11890                     using (ControlTransaction.Update(listView))
11891                     {
11892                         listView.VirtualListSize = tb.AllCount;
11893                     }
11894                 }
11895             }
11896         }
11897
11898         private async Task doMoveToRTHome()
11899         {
11900             if (_curList.SelectedIndices.Count > 0)
11901             {
11902                 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11903                 if (post.RetweetedId != null)
11904                 {
11905                     await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11906                 }
11907             }
11908         }
11909
11910         private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11911         {
11912             await this.doMoveToRTHome();
11913         }
11914
11915         private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11916         {
11917             string name = GetUserId();
11918             if (name != null)
11919             {
11920                 string tabName;
11921
11922                 //未選択なら処理終了
11923                 if (_curList.SelectedIndices.Count == 0) return;
11924
11925                 //タブ選択(or追加)
11926                 if (!SelectTab(out tabName)) return;
11927
11928                 var tab = (FilterTabModel)this._statuses.Tabs[tabName];
11929
11930                 bool mv;
11931                 bool mk;
11932                 if (tab.TabType != MyCommon.TabUsageType.Mute)
11933                 {
11934                     this.MoveOrCopy(out mv, out mk);
11935                 }
11936                 else
11937                 {
11938                     // ミュートタブでは常に MoveMatches を true にする
11939                     mv = true;
11940                     mk = false;
11941                 }
11942
11943                 PostFilterRule fc = new PostFilterRule();
11944                 fc.FilterName = name;
11945                 fc.UseNameField = true;
11946                 fc.MoveMatches = mv;
11947                 fc.MarkMatches = mk;
11948                 fc.UseRegex = false;
11949                 fc.FilterByUrl = false;
11950                 tab.AddFilter(fc);
11951
11952                 this.ApplyPostFilters();
11953                 SaveConfigsTabs();
11954             }
11955         }
11956
11957         private async void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11958         {
11959             string user;
11960
11961             ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11962
11963             if (menuItem.Owner == this.ContextMenuPostBrowser)
11964             {
11965                 user = GetUserId();
11966                 if (user == null) return;
11967             }
11968             else if (this._curPost != null)
11969             {
11970                 user = this._curPost.ScreenName;
11971             }
11972             else
11973             {
11974                 return;
11975             }
11976
11977             if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11978             {
11979                 try
11980                 {
11981                     using (var dialog = new WaitingDialog(Properties.Resources.ListsGetting))
11982                     {
11983                         var cancellationToken = dialog.EnableCancellation();
11984
11985                         var task = this.tw.GetListsApi();
11986                         await dialog.WaitForAsync(this, task);
11987
11988                         cancellationToken.ThrowIfCancellationRequested();
11989                     }
11990                 }
11991                 catch (OperationCanceledException) { return; }
11992                 catch (WebApiException ex)
11993                 {
11994                     MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
11995                     return;
11996                 }
11997             }
11998
11999             using (MyLists listSelectForm = new MyLists(user, this.tw))
12000             {
12001                 listSelectForm.ShowDialog(this);
12002             }
12003         }
12004
12005         private void SearchControls_Enter(object sender, EventArgs e)
12006         {
12007             Control pnl = (Control)sender;
12008             foreach (Control ctl in pnl.Controls)
12009             {
12010                 ctl.TabStop = true;
12011             }
12012         }
12013
12014         private void SearchControls_Leave(object sender, EventArgs e)
12015         {
12016             Control pnl = (Control)sender;
12017             foreach (Control ctl in pnl.Controls)
12018             {
12019                 ctl.TabStop = false;
12020             }
12021         }
12022
12023         private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12024         {
12025             if (ListTab.SelectedTab != null)
12026             {
12027                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12028                 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12029             }
12030         }
12031
12032         private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12033         {
12034             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12035             if (m.Success)
12036             {
12037                 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12038                 HashStripSplitButton.Text = HashMgr.UseHash;
12039                 HashToggleMenuItem.Checked = true;
12040                 HashToggleToolStripMenuItem.Checked = true;
12041                 //使用ハッシュタグとして設定
12042                 ModifySettingCommon = true;
12043             }
12044         }
12045
12046         private void StatusLabel_DoubleClick(object sender, EventArgs e)
12047         {
12048             MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12049         }
12050
12051         private void HashManageMenuItem_Click(object sender, EventArgs e)
12052         {
12053             DialogResult rslt = DialogResult.Cancel;
12054             try
12055             {
12056                 rslt = HashMgr.ShowDialog();
12057             }
12058             catch (Exception)
12059             {
12060                 return;
12061             }
12062             this.TopMost = this._cfgCommon.AlwaysTop;
12063             if (rslt == DialogResult.Cancel) return;
12064             if (!string.IsNullOrEmpty(HashMgr.UseHash))
12065             {
12066                 HashStripSplitButton.Text = HashMgr.UseHash;
12067                 HashToggleMenuItem.Checked = true;
12068                 HashToggleToolStripMenuItem.Checked = true;
12069             }
12070             else
12071             {
12072                 HashStripSplitButton.Text = "#[-]";
12073                 HashToggleMenuItem.Checked = false;
12074                 HashToggleToolStripMenuItem.Checked = false;
12075             }
12076             //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12077             //{
12078             //    int sidx = StatusText.SelectionStart;
12079             //    string hash = HashMgr.UseHash + " ";
12080             //    if (sidx > 0)
12081             //    {
12082             //        if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12083             //            hash = " " + hash;
12084             //    }
12085             //    StatusText.Text = StatusText.Text.Insert(sidx, hash);
12086             //    sidx += hash.Length;
12087             //    StatusText.SelectionStart = sidx;
12088             //    StatusText.Focus();
12089             //}
12090             ModifySettingCommon = true;
12091             this.StatusText_TextChanged(null, null);
12092         }
12093
12094         private void HashToggleMenuItem_Click(object sender, EventArgs e)
12095         {
12096             HashMgr.ToggleHash();
12097             if (!string.IsNullOrEmpty(HashMgr.UseHash))
12098             {
12099                 HashStripSplitButton.Text = HashMgr.UseHash;
12100                 HashToggleMenuItem.Checked = true;
12101                 HashToggleToolStripMenuItem.Checked = true;
12102             }
12103             else
12104             {
12105                 HashStripSplitButton.Text = "#[-]";
12106                 HashToggleMenuItem.Checked = false;
12107                 HashToggleToolStripMenuItem.Checked = false;
12108             }
12109             ModifySettingCommon = true;
12110             this.StatusText_TextChanged(null, null);
12111         }
12112
12113         private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12114         {
12115             HashToggleMenuItem_Click(null, null);
12116         }
12117
12118         private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12119         {
12120             if (ListTab.SelectedTab == null) return;
12121             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12122             if (!this.ExistCurrentPost)
12123             {
12124                 this.ReplyOpMenuItem.Enabled = false;
12125                 this.ReplyAllOpMenuItem.Enabled = false;
12126                 this.DmOpMenuItem.Enabled = false;
12127                 this.ShowProfMenuItem.Enabled = false;
12128                 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12129                 this.ListManageMenuItem.Enabled = false;
12130                 this.OpenFavOpMenuItem.Enabled = false;
12131                 this.CreateTabRuleOpMenuItem.Enabled = false;
12132                 this.CreateIdRuleOpMenuItem.Enabled = false;
12133                 this.CreateSourceRuleOpMenuItem.Enabled = false;
12134                 this.ReadOpMenuItem.Enabled = false;
12135                 this.UnreadOpMenuItem.Enabled = false;
12136             }
12137             else
12138             {
12139                 this.ReplyOpMenuItem.Enabled = true;
12140                 this.ReplyAllOpMenuItem.Enabled = true;
12141                 this.DmOpMenuItem.Enabled = true;
12142                 this.ShowProfMenuItem.Enabled = true;
12143                 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12144                 this.ListManageMenuItem.Enabled = true;
12145                 this.OpenFavOpMenuItem.Enabled = true;
12146                 this.CreateTabRuleOpMenuItem.Enabled = true;
12147                 this.CreateIdRuleOpMenuItem.Enabled = true;
12148                 this.CreateSourceRuleOpMenuItem.Enabled = true;
12149                 this.ReadOpMenuItem.Enabled = true;
12150                 this.UnreadOpMenuItem.Enabled = true;
12151             }
12152
12153             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12154             {
12155                 this.FavOpMenuItem.Enabled = false;
12156                 this.UnFavOpMenuItem.Enabled = false;
12157                 this.OpenStatusOpMenuItem.Enabled = false;
12158                 this.OpenFavotterOpMenuItem.Enabled = false;
12159                 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12160                 this.RtOpMenuItem.Enabled = false;
12161                 this.RtUnOpMenuItem.Enabled = false;
12162                 this.QtOpMenuItem.Enabled = false;
12163                 this.FavoriteRetweetMenuItem.Enabled = false;
12164                 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12165             }
12166             else
12167             {
12168                 this.FavOpMenuItem.Enabled = true;
12169                 this.UnFavOpMenuItem.Enabled = true;
12170                 this.OpenStatusOpMenuItem.Enabled = true;
12171                 this.OpenFavotterOpMenuItem.Enabled = true;
12172                 this.ShowRelatedStatusesMenuItem2.Enabled = true;  //PublicSearchの時問題出るかも
12173
12174                 if (_curPost.IsMe)
12175                 {
12176                     this.RtOpMenuItem.Enabled = false;  //公式RTは無効に
12177                     this.RtUnOpMenuItem.Enabled = true;
12178                     this.QtOpMenuItem.Enabled = true;
12179                     this.FavoriteRetweetMenuItem.Enabled = false;  //公式RTは無効に
12180                     this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12181                 }
12182                 else
12183                 {
12184                     if (_curPost.IsProtect)
12185                     {
12186                         this.RtOpMenuItem.Enabled = false;
12187                         this.RtUnOpMenuItem.Enabled = false;
12188                         this.QtOpMenuItem.Enabled = false;
12189                         this.FavoriteRetweetMenuItem.Enabled = false;
12190                         this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12191                     }
12192                     else
12193                     {
12194                         this.RtOpMenuItem.Enabled = true;
12195                         this.RtUnOpMenuItem.Enabled = true;
12196                         this.QtOpMenuItem.Enabled = true;
12197                         this.FavoriteRetweetMenuItem.Enabled = true;
12198                         this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12199                     }
12200                 }
12201             }
12202
12203             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12204             {
12205                 this.RefreshPrevOpMenuItem.Enabled = true;
12206             }
12207             else
12208             {
12209                 this.RefreshPrevOpMenuItem.Enabled = false;
12210             }
12211             if (!this.ExistCurrentPost
12212                 || _curPost.InReplyToStatusId == null)
12213             {
12214                 OpenRepSourceOpMenuItem.Enabled = false;
12215             }
12216             else
12217             {
12218                 OpenRepSourceOpMenuItem.Enabled = true;
12219             }
12220             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12221             {
12222                 OpenRterHomeMenuItem.Enabled = false;
12223             }
12224             else
12225             {
12226                 OpenRterHomeMenuItem.Enabled = true;
12227             }
12228
12229             if (this.ExistCurrentPost)
12230             {
12231                 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12232             }
12233         }
12234
12235         private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12236         {
12237             ContextMenuTabProperty_Opening(sender, null);
12238         }
12239
12240         public Twitter TwitterInstance
12241         {
12242             get { return tw; }
12243         }
12244
12245         private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12246         {
12247             if (this._initialLayout)
12248                 return;
12249
12250             int splitterDistance;
12251             switch (this.WindowState)
12252             {
12253                 case FormWindowState.Normal:
12254                     splitterDistance = this.SplitContainer3.SplitterDistance;
12255                     break;
12256                 case FormWindowState.Maximized:
12257                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
12258                     var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
12259                     splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
12260                     splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
12261                     break;
12262                 default:
12263                     return;
12264             }
12265
12266             this._mySpDis3 = splitterDistance;
12267             this.ModifySettingLocal = true;
12268         }
12269
12270         private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12271         {
12272             if (_statuses.RemovedTab.Count == 0)
12273             {
12274                 UndoRemoveTabMenuItem.Enabled = false;
12275             }
12276             else
12277             {
12278                 UndoRemoveTabMenuItem.Enabled = true;
12279             }
12280             if (ListTab.SelectedTab != null)
12281             {
12282                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12283                     PublicSearchQueryMenuItem.Enabled = true;
12284                 else
12285                     PublicSearchQueryMenuItem.Enabled = false;
12286             }
12287             else
12288             {
12289                 PublicSearchQueryMenuItem.Enabled = false;
12290             }
12291             if (!this.ExistCurrentPost)
12292             {
12293                 this.CopySTOTMenuItem.Enabled = false;
12294                 this.CopyURLMenuItem.Enabled = false;
12295                 this.CopyUserIdStripMenuItem.Enabled = false;
12296             }
12297             else
12298             {
12299                 this.CopySTOTMenuItem.Enabled = true;
12300                 this.CopyURLMenuItem.Enabled = true;
12301                 this.CopyUserIdStripMenuItem.Enabled = true;
12302                 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12303                 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12304             }
12305         }
12306
12307         private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12308         {
12309             SetNotifyIconText();
12310         }
12311
12312         private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12313         {
12314             var id = _curPost?.ScreenName ?? "";
12315
12316             await this.ShowUserStatus(id);
12317         }
12318
12319         private async Task doShowUserStatus(string id, bool ShowInputDialog)
12320         {
12321             TwitterUser user = null;
12322
12323             if (ShowInputDialog)
12324             {
12325                 using (var inputName = new InputTabName())
12326                 {
12327                     inputName.FormTitle = "Show UserStatus";
12328                     inputName.FormDescription = Properties.Resources.FRMessage1;
12329                     inputName.TabName = id;
12330
12331                     if (inputName.ShowDialog(this) != DialogResult.OK)
12332                         return;
12333                     if (string.IsNullOrWhiteSpace(inputName.TabName))
12334                         return;
12335
12336                     id = inputName.TabName.Trim();
12337                 }
12338             }
12339
12340             using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
12341             {
12342                 var cancellationToken = dialog.EnableCancellation();
12343
12344                 try
12345                 {
12346                     var task = this.twitterApi.UsersShow(id);
12347                     user = await dialog.WaitForAsync(this, task);
12348                 }
12349                 catch (WebApiException ex)
12350                 {
12351                     if (!cancellationToken.IsCancellationRequested)
12352                         MessageBox.Show($"Err:{ex.Message}(UsersShow)");
12353                     return;
12354                 }
12355
12356                 if (cancellationToken.IsCancellationRequested)
12357                     return;
12358             }
12359
12360             await this.doShowUserStatus(user);
12361         }
12362
12363         private async Task doShowUserStatus(TwitterUser user)
12364         {
12365             using (var userDialog = new UserInfoDialog(this, this.twitterApi))
12366             {
12367                 var showUserTask = userDialog.ShowUserAsync(user);
12368                 userDialog.ShowDialog(this);
12369
12370                 this.Activate();
12371                 this.BringToFront();
12372
12373                 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12374                 await showUserTask;
12375             }
12376         }
12377
12378         private Task ShowUserStatus(string id, bool ShowInputDialog)
12379         {
12380             return this.doShowUserStatus(id, ShowInputDialog);
12381         }
12382
12383         private Task ShowUserStatus(string id)
12384         {
12385             return this.doShowUserStatus(id, true);
12386         }
12387
12388         private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12389         {
12390             if (NameLabel.Tag != null)
12391             {
12392                 string id = (string)NameLabel.Tag;
12393                 if (id != tw.Username)
12394                 {
12395                     await this.FollowCommand(id);
12396                 }
12397             }
12398         }
12399
12400         private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12401         {
12402             if (NameLabel.Tag != null)
12403             {
12404                 string id = (string)NameLabel.Tag;
12405                 if (id != tw.Username)
12406                 {
12407                     await this.RemoveCommand(id, false);
12408                 }
12409             }
12410         }
12411
12412         private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12413         {
12414             if (NameLabel.Tag != null)
12415             {
12416                 string id = (string)NameLabel.Tag;
12417                 if (id != tw.Username)
12418                 {
12419                     await this.ShowFriendship(id);
12420                 }
12421             }
12422         }
12423
12424         private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12425         {
12426             if (NameLabel.Tag != null)
12427             {
12428                 string id = (string)NameLabel.Tag;
12429                 await this.ShowUserStatus(id, false);
12430             }
12431         }
12432
12433         private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12434         {
12435             if (NameLabel.Tag != null)
12436             {
12437                 string id = (string)NameLabel.Tag;
12438                 AddNewTabForUserTimeline(id);
12439             }
12440         }
12441
12442         private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12443         {
12444             if (NameLabel.Tag != null)
12445             {
12446                 string id = (string)NameLabel.Tag;
12447                 AddNewTabForSearch("@" + id);
12448             }
12449         }
12450
12451         private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12452         {
12453             if (_curPost != null)
12454             {
12455                 await this.ShowUserStatus(_curPost.ScreenName, false);
12456             }
12457         }
12458
12459         private async void RtCountMenuItem_Click(object sender, EventArgs e)
12460         {
12461             if (!this.ExistCurrentPost)
12462                 return;
12463
12464             var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12465             TwitterStatus status;
12466
12467             using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12468             {
12469                 var cancellationToken = dialog.EnableCancellation();
12470
12471                 try
12472                 {
12473                     var task = this.twitterApi.StatusesShow(statusId);
12474                     status = await dialog.WaitForAsync(this, task);
12475                 }
12476                 catch (WebApiException ex)
12477                 {
12478                     if (!cancellationToken.IsCancellationRequested)
12479                         MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + "Err:" + ex.Message);
12480                     return;
12481                 }
12482
12483                 if (cancellationToken.IsCancellationRequested)
12484                     return;
12485             }
12486
12487             MessageBox.Show(status.RetweetCount + Properties.Resources.RtCountText1);
12488         }
12489
12490         private HookGlobalHotkey _hookGlobalHotkey;
12491         public TweenMain()
12492         {
12493             _hookGlobalHotkey = new HookGlobalHotkey(this);
12494
12495             // この呼び出しは、Windows フォーム デザイナで必要です。
12496             InitializeComponent();
12497
12498             // InitializeComponent() 呼び出しの後で初期化を追加します。
12499
12500             if (!this.DesignMode)
12501             {
12502                 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12503                 this.StatusText.Dock = DockStyle.Fill;
12504             }
12505
12506             this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12507             this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12508             this.gh.NotifyClicked += GrowlHelper_Callback;
12509
12510             // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12511             this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12512
12513             this.ImageSelector.Visible = false;
12514             this.ImageSelector.Enabled = false;
12515             this.ImageSelector.FilePickDialog = OpenFileDialog1;
12516
12517             this.ReplaceAppName();
12518             this.InitializeShortcuts();
12519         }
12520
12521         private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12522         {
12523             if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12524             {
12525                 //アイコン化
12526                 this.Visible = false;
12527             }
12528             else if (Form.ActiveForm == null)
12529             {
12530                 this.Visible = true;
12531                 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12532                 this.Activate();
12533                 this.BringToFront();
12534                 this.StatusText.Focus();
12535             }
12536         }
12537
12538         private void UserPicture_MouseEnter(object sender, EventArgs e)
12539         {
12540             this.UserPicture.Cursor = Cursors.Hand;
12541         }
12542
12543         private void UserPicture_MouseLeave(object sender, EventArgs e)
12544         {
12545             this.UserPicture.Cursor = Cursors.Default;
12546         }
12547
12548         private async void UserPicture_DoubleClick(object sender, EventArgs e)
12549         {
12550             if (NameLabel.Tag != null)
12551             {
12552                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12553             }
12554         }
12555
12556         private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12557         {
12558             this.MultiLineMenuItem.PerformClick();
12559         }
12560
12561         public PostClass CurPost
12562         {
12563             get { return _curPost; }
12564         }
12565
12566 #region "画像投稿"
12567         private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12568         {
12569             if (ImageSelector.Visible)
12570                 ImageSelector.EndSelection();
12571             else
12572                 ImageSelector.BeginSelection();
12573         }
12574
12575         private void SelectMedia_DragEnter(DragEventArgs e)
12576         {
12577             if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12578             {
12579                 e.Effect = DragDropEffects.Copy;
12580                 return;
12581             }
12582             e.Effect = DragDropEffects.None;
12583         }
12584
12585         private void SelectMedia_DragDrop(DragEventArgs e)
12586         {
12587             this.Activate();
12588             this.BringToFront();
12589             ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12590             StatusText.Focus();
12591         }
12592
12593         private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12594         {
12595             TimelinePanel.Visible = false;
12596             TimelinePanel.Enabled = false;
12597         }
12598
12599         private void ImageSelector_EndSelecting(object sender, EventArgs e)
12600         {
12601             TimelinePanel.Visible = true;
12602             TimelinePanel.Enabled = true;
12603             ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12604         }
12605
12606         private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12607         {
12608             this.AllowDrop = false;
12609         }
12610
12611         private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12612         {
12613             this.AllowDrop = true;
12614         }
12615
12616         private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12617         {
12618             if (ImageSelector.Visible)
12619             {
12620                 ModifySettingCommon = true;
12621                 SaveConfigsAll(true);
12622
12623                 if (ImageSelector.ServiceName.Equals("Twitter"))
12624                     this.StatusText_TextChanged(null, null);
12625             }
12626         }
12627
12628         private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12629         {
12630             this.StatusText_TextChanged(null, null);
12631         }
12632
12633         /// <summary>
12634         /// StatusTextでCtrl+Vが押下された時の処理
12635         /// </summary>
12636         private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12637         {
12638             if (Clipboard.ContainsText())
12639             {
12640                 // clipboardにテキストがある場合は貼り付け処理
12641                 this.StatusText.Paste(Clipboard.GetText());
12642             }
12643             else if (Clipboard.ContainsImage())
12644             {
12645                 // 画像があるので投稿処理を行う
12646                 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12647                                    Properties.Resources.PostPictureWarn4,
12648                                    MessageBoxButtons.OKCancel,
12649                                    MessageBoxIcon.Question,
12650                                    MessageBoxDefaultButton.Button2)
12651                                == DialogResult.OK)
12652                 {
12653                     // clipboardから画像を取得
12654                     using (var image = Clipboard.GetImage())
12655                     {
12656                         this.ImageSelector.BeginSelection(image);
12657                     }
12658                 }
12659             }
12660         }
12661 #endregion
12662
12663         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12664         {
12665             using (ListManage form = new ListManage(tw))
12666             {
12667                 form.ShowDialog(this);
12668             }
12669         }
12670
12671         public bool ModifySettingCommon { get; set; }
12672         public bool ModifySettingLocal { get; set; }
12673         public bool ModifySettingAtId { get; set; }
12674
12675         private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12676         {
12677             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12678             if (sourceUri != null && e.Button == MouseButtons.Left)
12679             {
12680                 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12681             }
12682         }
12683
12684         private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12685         {
12686             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12687             if (sourceUri != null)
12688             {
12689                 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12690             }
12691         }
12692
12693         private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12694         {
12695             SetStatusLabelUrl();
12696         }
12697
12698         private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12699         {
12700             if (this.ExistCurrentPost && !_curPost.IsDm)
12701                 RtCountMenuItem.Enabled = true;
12702             else
12703                 RtCountMenuItem.Enabled = false;
12704
12705             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12706             //    TinyUrlConvertToolStripMenuItem.Enabled = false;
12707             //else
12708             //    TinyUrlConvertToolStripMenuItem.Enabled = true;
12709         }
12710
12711         private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12712         {
12713             CopyUserId();
12714         }
12715
12716         private void CopyUserId()
12717         {
12718             if (_curPost == null) return;
12719             string clstr = _curPost.ScreenName;
12720             try
12721             {
12722                 Clipboard.SetDataObject(clstr, false, 5, 100);
12723             }
12724             catch (Exception ex)
12725             {
12726                 MessageBox.Show(ex.Message);
12727             }
12728         }
12729
12730         private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12731         {
12732             if (this.ExistCurrentPost && !_curPost.IsDm)
12733             {
12734                 try
12735                 {
12736                     await this.OpenRelatedTab(this._curPost);
12737                 }
12738                 catch (TabException ex)
12739                 {
12740                     MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12741                 }
12742             }
12743         }
12744
12745         /// <summary>
12746         /// 指定されたツイートに対する関連発言タブを開きます
12747         /// </summary>
12748         /// <param name="statusId">表示するツイートのID</param>
12749         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12750         private async Task OpenRelatedTab(long statusId)
12751         {
12752             var post = this._statuses[statusId];
12753             if (post == null)
12754             {
12755                 try
12756                 {
12757                     post = await this.tw.GetStatusApi(false, statusId);
12758                 }
12759                 catch (WebApiException ex)
12760                 {
12761                     this.StatusLabel.Text = $"Err:{ex.Message}(GetStatus)";
12762                     return;
12763                 }
12764             }
12765
12766             await this.OpenRelatedTab(post);
12767         }
12768
12769         /// <summary>
12770         /// 指定されたツイートに対する関連発言タブを開きます
12771         /// </summary>
12772         /// <param name="post">表示する対象となるツイート</param>
12773         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12774         private async Task OpenRelatedTab(PostClass post)
12775         {
12776             var tabRelated = this._statuses.GetTabByType<RelatedPostsTabModel>();
12777             if (tabRelated != null)
12778             {
12779                 this.RemoveSpecifiedTab(tabRelated.TabName, confirm: false);
12780             }
12781
12782             var tabName = this._statuses.MakeTabName("Related Tweets");
12783
12784             tabRelated = new RelatedPostsTabModel(tabName, post);
12785             tabRelated.UnreadManage = false;
12786             tabRelated.Notify = false;
12787
12788             this._statuses.AddTab(tabRelated);
12789             this.AddNewTab(tabRelated, startup: false);
12790
12791             for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12792             {
12793                 var tabPage = this.ListTab.TabPages[i];
12794                 if (tabName == tabPage.Text)
12795                 {
12796                     this.ListTab.SelectedIndex = i;
12797                     break;
12798                 }
12799             }
12800
12801             await this.GetRelatedTweetsAsync(tabRelated);
12802         }
12803
12804         private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12805         {
12806             StringBuilder buf = new StringBuilder();
12807             //buf.AppendFormat("キャッシュメモリ容量         : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12808             //buf.AppendFormat("物理メモリ使用割合           : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12809             buf.AppendFormat("キャッシュエントリ保持数     : {0}" + Environment.NewLine, IconCache.CacheCount);
12810             buf.AppendFormat("キャッシュエントリ破棄数     : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12811             MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12812         }
12813
12814         private void tw_UserIdChanged()
12815         {
12816             this.ModifySettingCommon = true;
12817         }
12818
12819 #region "Userstream"
12820         private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12821         {
12822             try
12823             {
12824                 if (InvokeRequired && !IsDisposed)
12825                 {
12826                     Invoke((Action) (async () =>
12827                            {
12828                                this._statuses.RemovePostFromAllTabs(e.StatusId, setIsDeleted: true);
12829                                if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12830                                {
12831                                    this.PurgeListViewItemCache();
12832                                    ((DetailsListView)_curTab.Tag).Update();
12833                                    if (_curPost != null && _curPost.StatusId == e.StatusId)
12834                                        await this.DispSelectedPost(true);
12835                                }
12836                            }));
12837                     return;
12838                 }
12839             }
12840             catch (ObjectDisposedException)
12841             {
12842                 return;
12843             }
12844             catch (InvalidOperationException)
12845             {
12846                 return;
12847             }
12848         }
12849
12850         private int userStreamsRefreshing = 0;
12851
12852         private async void tw_NewPostFromStream(object sender, EventArgs e)
12853         {
12854             if (this._cfgCommon.ReadOldPosts)
12855             {
12856                 _statuses.SetReadHomeTab(); //新着時未読クリア
12857             }
12858
12859             int rsltAddCount = _statuses.DistributePosts();
12860
12861             this.UpdateTimelineSpeed(rsltAddCount);
12862
12863             if (this._cfgCommon.UserstreamPeriod > 0) return;
12864
12865             // userStreamsRefreshing が 0 (インクリメント後は1) であれば RefreshTimeline を実行
12866             if (Interlocked.Increment(ref this.userStreamsRefreshing) == 1)
12867             {
12868                 try
12869                 {
12870                     await this.InvokeAsync(() => this.RefreshTimeline())
12871                         .ConfigureAwait(false);
12872                 }
12873                 finally
12874                 {
12875                     Interlocked.Exchange(ref this.userStreamsRefreshing, 0);
12876                 }
12877             }
12878         }
12879
12880         private void tw_UserStreamStarted(object sender, EventArgs e)
12881         {
12882             try
12883             {
12884                 if (InvokeRequired && !IsDisposed)
12885                 {
12886                     Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12887                     return;
12888                 }
12889             }
12890             catch (ObjectDisposedException)
12891             {
12892                 return;
12893             }
12894             catch (InvalidOperationException)
12895             {
12896                 return;
12897             }
12898
12899             this.RefreshUserStreamsMenu();
12900             this.MenuItemUserStream.Enabled = true;
12901
12902             StatusLabel.Text = "UserStream Started.";
12903         }
12904
12905         private void tw_UserStreamStopped(object sender, EventArgs e)
12906         {
12907             try
12908             {
12909                 if (InvokeRequired && !IsDisposed)
12910                 {
12911                     Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12912                     return;
12913                 }
12914             }
12915             catch (ObjectDisposedException)
12916             {
12917                 return;
12918             }
12919             catch (InvalidOperationException)
12920             {
12921                 return;
12922             }
12923
12924             this.RefreshUserStreamsMenu();
12925             this.MenuItemUserStream.Enabled = true;
12926
12927             StatusLabel.Text = "UserStream Stopped.";
12928         }
12929
12930         private void RefreshUserStreamsMenu()
12931         {
12932             if (this.tw.UserStreamActive)
12933             {
12934                 this.MenuItemUserStream.Text = "&UserStream ▶";
12935                 this.StopToolStripMenuItem.Text = "&Stop";
12936             }
12937             else
12938             {
12939                 this.MenuItemUserStream.Text = "&UserStream ■";
12940                 this.StopToolStripMenuItem.Text = "&Start";
12941             }
12942         }
12943
12944         private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12945         {
12946             try
12947             {
12948                 if (InvokeRequired && !IsDisposed)
12949                 {
12950                     Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
12951                     return;
12952                 }
12953             }
12954             catch (ObjectDisposedException)
12955             {
12956                 return;
12957             }
12958             catch (InvalidOperationException)
12959             {
12960                 return;
12961             }
12962             var ev = e.EventData;
12963             StatusLabel.Text = "Event: " + ev.Event;
12964             //if (ev.Event == "favorite")
12965             //{
12966             //    NotifyFavorite(ev);
12967             //}
12968             NotifyEvent(ev);
12969             if (ev.Event == "favorite" || ev.Event == "unfavorite")
12970             {
12971                 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
12972                 {
12973                     this.PurgeListViewItemCache();
12974                     ((DetailsListView)_curTab.Tag).Update();
12975                 }
12976                 if (ev.Event == "unfavorite" && ev.Username.ToLowerInvariant().Equals(tw.Username.ToLowerInvariant()))
12977                 {
12978                     var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
12979                     favTab.EnqueueRemovePost(ev.Id, setIsDeleted: false);
12980                 }
12981             }
12982         }
12983
12984         private void NotifyEvent(Twitter.FormattedEvent ev)
12985         {
12986             //新着通知 
12987             if (BalloonRequired(ev))
12988             {
12989                 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
12990                 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
12991                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
12992                 StringBuilder title = new StringBuilder();
12993                 if (this._cfgCommon.DispUsername)
12994                 {
12995                     title.Append(tw.Username);
12996                     title.Append(" - ");
12997                 }
12998                 else
12999                 {
13000                     //title.Clear();
13001                 }
13002                 title.Append(Application.ProductName);
13003                 title.Append(" [");
13004                 title.Append(ev.Event.ToUpper(CultureInfo.CurrentCulture));
13005                 title.Append("] by ");
13006                 if (!string.IsNullOrEmpty(ev.Username))
13007                 {
13008                     title.Append(ev.Username.ToString());
13009                 }
13010                 else
13011                 {
13012                     //title.Append("");
13013                 }
13014                 string text;
13015                 if (!string.IsNullOrEmpty(ev.Target))
13016                 {
13017                     //NotifyIcon1.BalloonTipText = ev.Target;
13018                     text = ev.Target;
13019                 }
13020                 else
13021                 {
13022                     //NotifyIcon1.BalloonTipText = " ";
13023                     text = " ";
13024                 }
13025                 //NotifyIcon1.ShowBalloonTip(500);
13026                 if (this._cfgCommon.IsUseNotifyGrowl)
13027                 {
13028                     gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13029                               ev.Id.ToString(), title.ToString(), text);
13030                 }
13031                 else
13032                 {
13033                     NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13034                     NotifyIcon1.BalloonTipTitle = title.ToString();
13035                     NotifyIcon1.BalloonTipText = text;
13036                     NotifyIcon1.ShowBalloonTip(500);
13037                 }
13038             }
13039
13040             //サウンド再生
13041             string snd = this._cfgCommon.EventSoundFile;
13042             if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13043             {
13044                 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13045                 {
13046                     try
13047                     {
13048                         string dir = Application.StartupPath;
13049                         if (Directory.Exists(Path.Combine(dir, "Sounds")))
13050                         {
13051                             dir = Path.Combine(dir, "Sounds");
13052                         }
13053                         using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13054                         {
13055                             player.Play();
13056                         }
13057                     }
13058                     catch (Exception)
13059                     {
13060                     }
13061                 }
13062             }
13063         }
13064
13065         private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13066         {
13067             MenuItemUserStream.Enabled = false;
13068             if (StopRefreshAllMenuItem.Checked)
13069             {
13070                 StopRefreshAllMenuItem.Checked = false;
13071                 return;
13072             }
13073             if (this.tw.UserStreamActive)
13074             {
13075                 tw.StopUserStream();
13076             }
13077             else
13078             {
13079                 tw.StartUserStream();
13080             }
13081         }
13082
13083         private static string inputTrack = "";
13084
13085         private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13086         {
13087             if (TrackToolStripMenuItem.Checked)
13088             {
13089                 using (InputTabName inputForm = new InputTabName())
13090                 {
13091                     inputForm.TabName = inputTrack;
13092                     inputForm.FormTitle = "Input track word";
13093                     inputForm.FormDescription = "Track word";
13094                     if (inputForm.ShowDialog() != DialogResult.OK)
13095                     {
13096                         TrackToolStripMenuItem.Checked = false;
13097                         return;
13098                     }
13099                     inputTrack = inputForm.TabName.Trim();
13100                 }
13101                 if (!inputTrack.Equals(tw.TrackWord))
13102                 {
13103                     tw.TrackWord = inputTrack;
13104                     this.ModifySettingCommon = true;
13105                     TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13106                     tw.ReconnectUserStream();
13107                 }
13108             }
13109             else
13110             {
13111                 tw.TrackWord = "";
13112                 tw.ReconnectUserStream();
13113             }
13114             this.ModifySettingCommon = true;
13115         }
13116
13117         private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13118         {
13119             tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13120             this.ModifySettingCommon = true;
13121             tw.ReconnectUserStream();
13122         }
13123
13124         private void EventViewerMenuItem_Click(object sender, EventArgs e)
13125         {
13126             if (evtDialog == null || evtDialog.IsDisposed)
13127             {
13128                 evtDialog = null;
13129                 evtDialog = new EventViewerDialog();
13130                 evtDialog.Owner = this;
13131                 //親の中央に表示
13132                 Point pos = evtDialog.Location;
13133                 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13134                 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13135                 evtDialog.Location = pos;
13136             }
13137             evtDialog.EventSource = tw.StoredEvent;
13138             if (!evtDialog.Visible)
13139             {
13140                 evtDialog.Show(this);
13141             }
13142             else
13143             {
13144                 evtDialog.Activate();
13145             }
13146             this.TopMost = this._cfgCommon.AlwaysTop;
13147         }
13148 #endregion
13149
13150         private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13151         {
13152             MyCommon._endingFlag = true;
13153             try
13154             {
13155                 this.Close();
13156                 Application.Restart();
13157             }
13158             catch (Exception)
13159             {
13160                 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13161             }
13162         }
13163
13164         private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13165         {
13166             if (!string.IsNullOrEmpty(tw.Username))
13167                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13168         }
13169
13170         private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13171         {
13172             await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
13173         }
13174
13175         private async Task doTranslation(string str)
13176         {
13177             if (string.IsNullOrEmpty(str))
13178                 return;
13179
13180             var bing = new Bing();
13181             try
13182             {
13183                 var translatedText = await bing.TranslateAsync(str,
13184                     langFrom: null,
13185                     langTo: this._cfgCommon.TranslateLanguage);
13186
13187                 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13188             }
13189             catch (HttpRequestException e)
13190             {
13191                 this.StatusLabel.Text = "Err:" + e.Message;
13192             }
13193             catch (OperationCanceledException)
13194             {
13195                 this.StatusLabel.Text = "Err:Timeout";
13196             }
13197         }
13198
13199         private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13200         {
13201             if (!this.ExistCurrentPost)
13202                 return;
13203
13204             await this.doTranslation(this._curPost.TextFromApi);
13205         }
13206
13207         private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13208         {
13209             var text = this.PostBrowser.GetSelectedText();
13210             await this.doTranslation(text);
13211         }
13212
13213         private bool ExistCurrentPost
13214         {
13215             get
13216             {
13217                 if (_curPost == null) return false;
13218                 if (_curPost.IsDeleted) return false;
13219                 return true;
13220             }
13221         }
13222
13223         private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13224         {
13225             ShowUserTimeline();
13226         }
13227
13228         private string GetUserIdFromCurPostOrInput(string caption)
13229         {
13230             var id = _curPost?.ScreenName ?? "";
13231
13232             using (InputTabName inputName = new InputTabName())
13233             {
13234                 inputName.FormTitle = caption;
13235                 inputName.FormDescription = Properties.Resources.FRMessage1;
13236                 inputName.TabName = id;
13237                 if (inputName.ShowDialog() == DialogResult.OK &&
13238                     !string.IsNullOrEmpty(inputName.TabName.Trim()))
13239                 {
13240                     id = inputName.TabName.Trim();
13241                 }
13242                 else
13243                 {
13244                     id = "";
13245                 }
13246             }
13247             return id;
13248         }
13249
13250         private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13251         {
13252             string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13253             if (!string.IsNullOrEmpty(id))
13254             {
13255                 AddNewTabForUserTimeline(id);
13256             }
13257         }
13258
13259         private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13260         {
13261             string id = GetUserIdFromCurPostOrInput("Show Favstar");
13262             if (!string.IsNullOrEmpty(id))
13263             {
13264                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13265             }
13266         }
13267
13268         private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13269         {
13270             if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13271         }
13272
13273         private void TimelineRefreshEnableChange(bool isEnable)
13274         {
13275             if (isEnable)
13276             {
13277                 tw.StartUserStream();
13278             }
13279             else
13280             {
13281                 tw.StopUserStream();
13282             }
13283             TimerTimeline.Enabled = isEnable;
13284         }
13285
13286         private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13287         {
13288             TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13289         }
13290
13291         private async Task OpenUserAppointUrl()
13292         {
13293             if (this._cfgCommon.UserAppointUrl != null)
13294             {
13295                 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13296                 {
13297                     if (_curPost != null)
13298                     {
13299                         string xUrl = this._cfgCommon.UserAppointUrl;
13300                         xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13301
13302                         var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
13303                         xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
13304
13305                         await this.OpenUriInBrowserAsync(xUrl);
13306                     }
13307                 }
13308                 else
13309                 {
13310                     await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
13311                 }
13312             }
13313         }
13314
13315         private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13316         {
13317             await this.OpenUserAppointUrl();
13318         }
13319
13320         private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13321         {
13322             string selText = SourceLinkLabel.Text;
13323             try
13324             {
13325                 Clipboard.SetDataObject(selText, false, 5, 100);
13326             }
13327             catch (Exception ex)
13328             {
13329                 MessageBox.Show(ex.Message);
13330             }
13331         }
13332
13333         private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13334         {
13335             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
13336             try
13337             {
13338                 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
13339             }
13340             catch (Exception ex)
13341             {
13342                 MessageBox.Show(ex.Message);
13343             }
13344         }
13345
13346         private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13347         {
13348             if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13349             {
13350                 SourceCopyMenuItem.Enabled = false;
13351                 SourceUrlCopyMenuItem.Enabled = false;
13352             }
13353             else
13354             {
13355                 SourceCopyMenuItem.Enabled = true;
13356                 SourceUrlCopyMenuItem.Enabled = true;
13357             }
13358         }
13359
13360         private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13361         {
13362             if (Form.ActiveForm == null)
13363             {
13364                 this.BeginInvoke((Action) (() =>
13365                 {
13366                     this.Visible = true;
13367                     if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13368                     this.Activate();
13369                     this.BringToFront();
13370                     if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13371                     {
13372                         if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13373                     }
13374                     else
13375                     {
13376                         if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13377                     }
13378                 }));
13379             }
13380         }
13381
13382         private void ReplaceAppName()
13383         {
13384             MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13385             AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13386         }
13387
13388         private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13389         {
13390             this.SplitContainer3.Panel2Collapsed = false;
13391         }
13392
13393         private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13394         {
13395             await this.OpenThumbnailPicture(e.Thumbnail);
13396         }
13397
13398         private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13399         {
13400             await this.OpenUriInBrowserAsync(e.ImageUrl);
13401         }
13402
13403         private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13404         {
13405             var url = thumbnail.FullSizeImageUrl ?? thumbnail.MediaPageUrl;
13406
13407             await this.OpenUriInBrowserAsync(url);
13408         }
13409
13410         private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13411         {
13412             await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13413         }
13414
13415         private void PostButton_KeyDown(object sender, KeyEventArgs e)
13416         {
13417             if (e.KeyCode == Keys.Space)
13418             {
13419                 this.JumpUnreadMenuItem_Click(null, null);
13420
13421                 e.SuppressKeyPress = true;
13422             }
13423         }
13424
13425         private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13426         {
13427             this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13428             this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13429             this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13430             this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13431             this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13432
13433             this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13434         }
13435
13436         private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13437         {
13438             ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13439         }
13440
13441         private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13442         {
13443             ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13444         }
13445
13446         private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13447         {
13448             ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13449         }
13450
13451         private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13452         {
13453             ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13454         }
13455
13456         private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13457         {
13458             ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13459         }
13460
13461         private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13462         {
13463             if (this._cfgCommon.IconSize == iconSize) return;
13464
13465             var oldIconCol = _iconCol;
13466
13467             this._cfgCommon.IconSize = iconSize;
13468             ApplyListViewIconSize(iconSize);
13469
13470             if (_iconCol != oldIconCol)
13471             {
13472                 foreach (TabPage tp in ListTab.TabPages)
13473                 {
13474                     ResetColumns((DetailsListView)tp.Tag);
13475                 }
13476             }
13477
13478             _curList?.Refresh();
13479
13480             ModifySettingCommon = true;
13481         }
13482
13483         private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13484         {
13485             var state = this.LockListSortOrderToolStripMenuItem.Checked;
13486             if (this._cfgCommon.SortOrderLock == state) return;
13487
13488             this._cfgCommon.SortOrderLock = state;
13489
13490             ModifySettingCommon = true;
13491         }
13492     }
13493 }