OSDN Git Service

c7056b3fd7935c51b6d0735b8e5b796585d1edc4
[opentween/open-tween.git] / OpenTween / Tween.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 //           (c) 2008-2011 Moz (@syo68k)
4 //           (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 //           (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 //           (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 //           (c) 2011      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
8 // All rights reserved.
9 // 
10 // This file is part of OpenTween.
11 // 
12 // This program is free software; you can redistribute it and/or modify it
13 // under the terms of the GNU General public License as published by the Free
14 // Software Foundation; either version 3 of the License, or (at your option)
15 // any later version.
16 // 
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
20 // for more details. 
21 // 
22 // You should have received a copy of the GNU General public License along
23 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
24 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
25 // Boston, MA 02110-1301, USA.
26
27 //コンパイル後コマンド
28 //"c:\Program Files\Microsoft.NET\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
29 //"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" /f /a:"$(TargetPath)"
30
31 using System;
32 using System.Collections.Generic;
33 using System.ComponentModel;
34 using System.Diagnostics;
35 using System.Drawing;
36 using System.IO;
37 using System.Linq;
38 using System.Media;
39 using System.Net;
40 using System.Net.Http;
41 using System.Reflection;
42 using System.Text;
43 using System.Text.RegularExpressions;
44 using System.Threading;
45 using System.Threading.Tasks;
46 using System.Windows.Forms;
47 using OpenTween.Api;
48 using OpenTween.Connection;
49 using OpenTween.OpenTweenCustomControl;
50 using OpenTween.Thumbnail;
51
52 namespace OpenTween
53 {
54     public partial class TweenMain : OTBaseForm
55     {
56         //各種設定
57         private Size _mySize;           //画面サイズ
58         private Point _myLoc;           //画面位置
59         private int _mySpDis;           //区切り位置
60         private int _mySpDis2;          //発言欄区切り位置
61         private int _mySpDis3;          //プレビュー区切り位置
62         private int _iconSz;            //アイコンサイズ(現在は16、24、48の3種類。将来直接数字指定可能とする 注:24x24の場合に26と指定しているのはMSゴシック系フォントのための仕様)
63         private bool _iconCol;          //1列表示の時true(48サイズのとき)
64
65         //雑多なフラグ類
66         private bool _initial;         //true:起動時処理中
67         private bool _initialLayout = true;
68         private bool _ignoreConfigSave;         //true:起動時処理中
69         private bool _tabDrag;           //タブドラッグ中フラグ(DoDragDropを実行するかの判定用)
70         private TabPage _beforeSelectedTab; //タブが削除されたときに前回選択されていたときのタブを選択する為に保持
71         private Point _tabMouseDownPoint;
72         private string _rclickTabName;      //右クリックしたタブの名前(Tabコントロール機能不足対応)
73         private readonly object _syncObject = new object();    //ロック用
74
75         private const string detailHtmlFormatHeaderMono = 
76             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
77             + "<style type=\"text/css\"><!-- "
78             + "body, p, pre {margin: 0;} "
79             + "pre {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
80             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
81             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
82             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
83             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
84             + "--></style>"
85             + "</head><body><pre>";
86         private const string detailHtmlFormatFooterMono = "</pre></body></html>";
87         private const string detailHtmlFormatHeaderColor = 
88             "<html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\">"
89             + "<style type=\"text/css\"><!-- "
90             + "body, p, pre {margin: 0;} "
91             + "body {font-family: \"%FONT_FAMILY%\", sans-serif; font-size: %FONT_SIZE%pt; background-color:rgb(%BG_COLOR%); margin: 0; word-wrap: break-word; color:rgb(%FONT_COLOR%);} "
92             + "a:link, a:visited, a:active, a:hover {color:rgb(%LINK_COLOR%); } "
93             + "img.emoji {width: 1em; height: 1em; margin: 0 .05em 0 .1em; vertical-align: -0.1em; border: none;} "
94             + ".quote-tweet {border: 1px solid #ccc; margin: 1em; padding: 0.5em;} "
95             + ".quote-tweet-link {color: inherit !important; text-decoration: none;}"
96             + "--></style>"
97             + "</head><body><p>";
98         private const string detailHtmlFormatFooterColor = "</p></body></html>";
99         private string detailHtmlFormatHeader;
100         private string detailHtmlFormatFooter;
101
102         private bool _myStatusError = false;
103         private bool _myStatusOnline = false;
104         private bool soundfileListup = false;
105         private FormWindowState _formWindowState = FormWindowState.Normal; // フォームの状態保存用 通知領域からアイコンをクリックして復帰した際に使用する
106
107         //設定ファイル関連
108         //private SettingToConfig _cfg; //旧
109         private SettingLocal _cfgLocal;
110         private SettingCommon _cfgCommon;
111         private bool _modifySettingLocal = false;
112         private bool _modifySettingCommon = false;
113         private bool _modifySettingAtId = false;
114
115         //twitter解析部
116         private Twitter tw = new Twitter();
117
118         //Growl呼び出し部
119         private GrowlHelper gh = new GrowlHelper(Application.ProductName);
120
121         //サブ画面インスタンス
122         private SearchWordDialog SearchDialog = new SearchWordDialog();     //検索画面インスタンス
123         private OpenURL UrlDialog = new OpenURL();
124         public AtIdSupplement AtIdSupl;     //@id補助
125         public AtIdSupplement HashSupl;    //Hashtag補助
126         public HashtagManage HashMgr;
127         private EventViewerDialog evtDialog;
128
129         //表示フォント、色、アイコン
130         private Font _fntUnread;            //未読用フォント
131         private Color _clUnread;            //未読用文字色
132         private Font _fntReaded;            //既読用フォント
133         private Color _clReaded;            //既読用文字色
134         private Color _clFav;               //Fav用文字色
135         private Color _clOWL;               //片思い用文字色
136         private Color _clRetweet;               //Retweet用文字色
137         private Color _clHighLight = Color.FromKnownColor(KnownColor.HighlightText);         //選択中の行用文字色
138         private Font _fntDetail;            //発言詳細部用フォント
139         private Color _clDetail;              //発言詳細部用色
140         private Color _clDetailLink;          //発言詳細部用リンク文字色
141         private Color _clDetailBackcolor;     //発言詳細部用背景色
142         private Color _clSelf;              //自分の発言用背景色
143         private Color _clAtSelf;            //自分宛返信用背景色
144         private Color _clTarget;            //選択発言者の他の発言用背景色
145         private Color _clAtTarget;          //選択発言中の返信先用背景色
146         private Color _clAtFromTarget;      //選択発言者への返信発言用背景色
147         private Color _clAtTo;              //選択発言の唯一@先
148         private Color _clListBackcolor;       //リスト部通常発言背景色
149         private Color _clInputBackcolor;      //入力欄背景色
150         private Color _clInputFont;           //入力欄文字色
151         private Font _fntInputFont;           //入力欄フォント
152         private ImageCache IconCache;        //アイコン画像リスト
153         private Icon NIconAt;               //At.ico             タスクトレイアイコン:通常時
154         private Icon NIconAtRed;            //AtRed.ico          タスクトレイアイコン:通信エラー時
155         private Icon NIconAtSmoke;          //AtSmoke.ico        タスクトレイアイコン:オフライン時
156         private Icon[] NIconRefresh = new Icon[4];       //Refresh.ico        タスクトレイアイコン:更新中(アニメーション用に4種類を保持するリスト)
157         private Icon TabIcon;               //Tab.ico            未読のあるタブ用アイコン
158         private Icon MainIcon;              //Main.ico           画面左上のアイコン
159         private Icon ReplyIcon;               //5g
160         private Icon ReplyIconBlink;          //6g
161
162         private ImageList _listViewImageList = new ImageList();    //ListViewItemの高さ変更用
163
164         private PostClass _anchorPost;
165         private bool _anchorFlag;        //true:関連発言移動中(関連移動以外のオペレーションをするとfalseへ。trueだとリスト背景色をアンカー発言選択中として描画)
166
167         private List<PostingStatus> _history = new List<PostingStatus>();   //発言履歴
168         private int _hisIdx;                  //発言履歴カレントインデックス
169
170         //発言投稿時のAPI引数(発言編集時に設定。手書きreplyでは設定されない)
171         private Tuple<long, string> inReplyTo = null; // リプライ先のステータスID・スクリーン名
172
173         //時速表示用
174         private List<DateTime> _postTimestamps = new List<DateTime>();
175         private List<DateTime> _favTimestamps = new List<DateTime>();
176         private Dictionary<DateTime, int> _tlTimestamps = new Dictionary<DateTime, int>();
177         private int _tlCount;
178
179         // 以下DrawItem関連
180         private SolidBrush _brsHighLight = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
181         private SolidBrush _brsBackColorMine;
182         private SolidBrush _brsBackColorAt;
183         private SolidBrush _brsBackColorYou;
184         private SolidBrush _brsBackColorAtYou;
185         private SolidBrush _brsBackColorAtFromTarget;
186         private SolidBrush _brsBackColorAtTo;
187         private SolidBrush _brsBackColorNone;
188         private SolidBrush _brsDeactiveSelection = new SolidBrush(Color.FromKnownColor(KnownColor.ButtonFace)); //Listにフォーカスないときの選択行の背景色
189         private StringFormat sfTab = new StringFormat();
190
191         //////////////////////////////////////////////////////////////////////////////////////////////////////////
192         private TabInformations _statuses;
193
194         /// <summary>
195         /// 現在表示している発言一覧の <see cref="ListView"/> に対するキャッシュ
196         /// </summary>
197         /// <remarks>
198         /// キャッシュクリアのために null が代入されることがあるため、
199         /// 使用する場合には <see cref="_listItemCache"/> に対して直接メソッド等を呼び出さずに
200         /// 一旦ローカル変数に代入してから参照すること。
201         /// </remarks>
202         private ListViewItemCache _listItemCache = null;
203
204         internal class ListViewItemCache
205         {
206             /// <summary>アイテムをキャッシュする対象の <see cref="ListView"/></summary>
207             public ListView TargetList { get; set; }
208
209             /// <summary>キャッシュする範囲の開始インデックス</summary>
210             public int StartIndex { get; set; }
211
212             /// <summary>キャッシュする範囲の終了インデックス</summary>
213             public int EndIndex { get; set; }
214
215             /// <summary>キャッシュされた <see cref="ListViewItem"/> インスタンス</summary>
216             public ListViewItem[] ListItem { get; set; }
217
218             /// <summary>キャッシュされた範囲に対応する <see cref="PostClass"/> インスタンス</summary>
219             public PostClass[] Post { get; set; }
220
221             /// <summary>キャッシュされたアイテムの件数</summary>
222             public int Count
223                 => this.EndIndex - this.StartIndex + 1;
224
225             /// <summary>指定されたインデックスがキャッシュの範囲内であるか判定します</summary>
226             /// <returns><paramref name="index"/> がキャッシュの範囲内であれば true、それ以外は false</returns>
227             public bool Contains(int index)
228                 => index >= this.StartIndex && index <= this.EndIndex;
229
230             /// <summary>指定されたインデックスの範囲が全てキャッシュの範囲内であるか判定します</summary>
231             /// <returns><paramref name="rangeStart"/> から <paramref name="rangeEnd"/> の範囲が全てキャッシュの範囲内であれば true、それ以外は false</returns>
232             public bool IsSupersetOf(int rangeStart, int rangeEnd)
233                 => rangeStart >= this.StartIndex && rangeEnd <= this.EndIndex;
234
235             /// <summary>指定されたインデックスの <see cref="ListViewItem"/> と <see cref="PostClass"/> をキャッシュから取得することを試みます</summary>
236             /// <returns>取得に成功すれば true、それ以外は false</returns>
237             public bool TryGetValue(int index, out ListViewItem item, out PostClass post)
238             {
239                 if (this.Contains(index))
240                 {
241                     item = this.ListItem[index - this.StartIndex];
242                     post = this.Post[index - this.StartIndex];
243                     return true;
244                 }
245                 else
246                 {
247                     item = null;
248                     post = null;
249                     return false;
250                 }
251             }
252         }
253
254         private TabPage _curTab;
255         private int _curItemIndex;
256         private DetailsListView _curList;
257         private PostClass _curPost;
258         private bool _isColumnChanged = false;
259
260         private const int MAX_WORKER_THREADS = 20;
261         private SemaphoreSlim workerSemaphore = new SemaphoreSlim(MAX_WORKER_THREADS);
262         private CancellationTokenSource workerCts = new CancellationTokenSource();
263
264         private int UnreadCounter = -1;
265         private int UnreadAtCounter = -1;
266
267         private string[] ColumnOrgText = new string[9];
268         private string[] ColumnText = new string[9];
269
270         private bool _DoFavRetweetFlags = false;
271         private bool osResumed = false;
272
273         //////////////////////////////////////////////////////////////////////////////////////////////////////////
274         private string _postBrowserStatusText = "";
275
276         private bool _colorize = false;
277
278         private System.Timers.Timer TimerTimeline = new System.Timers.Timer();
279
280         private ImageListViewItem displayItem;
281
282         private string recommendedStatusFooter;
283
284         //URL短縮のUndo用
285         private struct urlUndo
286         {
287             public string Before;
288             public string After;
289         }
290
291         private List<urlUndo> urlUndoBuffer = null;
292
293         private struct ReplyChain
294         {
295             public long OriginalId;
296             public long InReplyToId;
297             public TabPage OriginalTab;
298
299             public ReplyChain(long originalId, long inReplyToId, TabPage originalTab)
300             {
301                 this.OriginalId = originalId;
302                 this.InReplyToId = inReplyToId;
303                 this.OriginalTab = originalTab;
304             }
305         }
306
307         private Stack<ReplyChain> replyChains; //[, ]でのリプライ移動の履歴
308         private Stack<Tuple<TabPage, PostClass>> selectPostChains = new Stack<Tuple<TabPage, PostClass>>(); //ポスト選択履歴
309
310         //検索処理タイプ
311         private enum SEARCHTYPE
312         {
313             DialogSearch,
314             NextSearch,
315             PrevSearch,
316         }
317
318         private class PostingStatus
319         {
320             public string status = "";
321             public long? inReplyToId = null;
322             public string inReplyToName = null;
323             public string imageService = "";      //画像投稿サービス名
324             public IMediaItem[] mediaItems = null;
325             public PostingStatus()
326             {
327             }
328             public PostingStatus(string status, long? replyToId, string replyToName)
329             {
330                 this.status = status;
331                 this.inReplyToId = replyToId;
332                 this.inReplyToName = replyToName;
333             }
334         }
335
336         private void TweenMain_Activated(object sender, EventArgs e)
337         {
338             //画面がアクティブになったら、発言欄の背景色戻す
339             if (StatusText.Focused)
340             {
341                 this.StatusText_Enter(this.StatusText, System.EventArgs.Empty);
342             }
343         }
344
345         private bool disposed = false;
346
347         /// <summary>
348         /// 使用中のリソースをすべてクリーンアップします。
349         /// </summary>
350         /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
351         protected override void Dispose(bool disposing)
352         {
353             base.Dispose(disposing);
354
355             if (this.disposed)
356                 return;
357
358             if (disposing)
359             {
360                 this.components?.Dispose();
361
362                 //後始末
363                 SearchDialog.Dispose();
364                 UrlDialog.Dispose();
365                 NIconAt?.Dispose();
366                 NIconAtRed?.Dispose();
367                 NIconAtSmoke?.Dispose();
368                 foreach (var iconRefresh in this.NIconRefresh)
369                 {
370                     iconRefresh?.Dispose();
371                 }
372                 TabIcon?.Dispose();
373                 MainIcon?.Dispose();
374                 ReplyIcon?.Dispose();
375                 ReplyIconBlink?.Dispose();
376                 _listViewImageList.Dispose();
377                 _brsHighLight.Dispose();
378                 _brsBackColorMine?.Dispose();
379                 _brsBackColorAt?.Dispose();
380                 _brsBackColorYou?.Dispose();
381                 _brsBackColorAtYou?.Dispose();
382                 _brsBackColorAtFromTarget?.Dispose();
383                 _brsBackColorAtTo?.Dispose();
384                 _brsBackColorNone?.Dispose();
385                 _brsDeactiveSelection?.Dispose();
386                 //sf.Dispose();
387                 sfTab.Dispose();
388
389                 this.workerCts.Cancel();
390
391                 if (IconCache != null)
392                 {
393                     this.IconCache.CancelAsync();
394                     this.IconCache.Dispose();
395                 }
396
397                 this.thumbnailTokenSource?.Dispose();
398
399                 this.tw.Dispose();
400                 this._hookGlobalHotkey.Dispose();
401             }
402
403             // 終了時にRemoveHandlerしておかないとメモリリークする
404             // http://msdn.microsoft.com/ja-jp/library/microsoft.win32.systemevents.powermodechanged.aspx
405             Microsoft.Win32.SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
406
407             this.disposed = true;
408         }
409
410         private void LoadIcons()
411         {
412             // Icons フォルダ以下のアイコンを読み込み(着せ替えアイコン対応)
413             var iconsDir = Path.Combine(Application.StartupPath, "Icons");
414
415             // ウィンドウ左上のアイコン
416             var iconMain = this.LoadIcon(Path.Combine(iconsDir, "MIcon.ico"));
417
418             // タブ見出し未読表示アイコン
419             var iconTab = this.LoadIcon(Path.Combine(iconsDir, "Tab.ico"));
420
421             // タスクトレイ: 通常時アイコン
422             var iconAt = this.LoadIcon(Path.Combine(iconsDir, "At.ico"));
423
424             // タスクトレイ: エラー時アイコン
425             var iconAtRed = this.LoadIcon(Path.Combine(iconsDir, "AtRed.ico"));
426
427             // タスクトレイ: オフライン時アイコン
428             var iconAtSmoke = this.LoadIcon(Path.Combine(iconsDir, "AtSmoke.ico"));
429
430             // タスクトレイ: Reply通知アイコン (最大2枚でアニメーション可能)
431             var iconReply = this.LoadIcon(Path.Combine(iconsDir, "Reply.ico"));
432             var iconReplyBlink = this.LoadIcon(Path.Combine(iconsDir, "ReplyBlink.ico"));
433
434             // タスクトレイ: 更新中アイコン (最大4枚でアニメーション可能)
435             var iconRefresh1 = this.LoadIcon(Path.Combine(iconsDir, "Refresh.ico"));
436             var iconRefresh2 = this.LoadIcon(Path.Combine(iconsDir, "Refresh2.ico"));
437             var iconRefresh3 = this.LoadIcon(Path.Combine(iconsDir, "Refresh3.ico"));
438             var iconRefresh4 = this.LoadIcon(Path.Combine(iconsDir, "Refresh4.ico"));
439
440             // 読み込んだアイコンを設定 (不足するアイコンはデフォルトのものを設定)
441
442             this.MainIcon = iconMain ?? Properties.Resources.MIcon;
443             this.TabIcon = iconTab ?? Properties.Resources.TabIcon;
444             this.NIconAt = iconAt ?? iconMain ?? Properties.Resources.At;
445             this.NIconAtRed = iconAtRed ?? Properties.Resources.AtRed;
446             this.NIconAtSmoke = iconAtSmoke ?? Properties.Resources.AtSmoke;
447
448             if (iconReply != null && iconReplyBlink != null)
449             {
450                 this.ReplyIcon = iconReply;
451                 this.ReplyIconBlink = iconReplyBlink;
452             }
453             else
454             {
455                 this.ReplyIcon = iconReply ?? iconReplyBlink ?? Properties.Resources.Reply;
456                 this.ReplyIconBlink = this.NIconAt;
457             }
458
459             if (iconRefresh1 == null)
460             {
461                 this.NIconRefresh = new[] {
462                     Properties.Resources.Refresh, Properties.Resources.Refresh2,
463                     Properties.Resources.Refresh3, Properties.Resources.Refresh4,
464                 };
465             }
466             else if (iconRefresh2 == null)
467             {
468                 this.NIconRefresh = new[] { iconRefresh1 };
469             }
470             else if (iconRefresh3 == null)
471             {
472                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2 };
473             }
474             else if (iconRefresh4 == null)
475             {
476                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3 };
477             }
478             else // iconRefresh1 から iconRefresh4 まで全て揃っている
479             {
480                 this.NIconRefresh = new[] { iconRefresh1, iconRefresh2, iconRefresh3, iconRefresh4 };
481             }
482         }
483
484         private Icon LoadIcon(string filePath)
485         {
486             if (!File.Exists(filePath))
487                 return null;
488
489             try
490             {
491                 return new Icon(filePath);
492             }
493             catch (Exception)
494             {
495                 return null;
496             }
497         }
498
499         private void InitColumns(ListView list, bool startup)
500         {
501             this.InitColumnText();
502
503             ColumnHeader[] columns;
504             if (this._iconCol)
505             {
506                 columns = new[]
507                 {
508                     new ColumnHeader { Text = this.ColumnText[0], Width = 48 }, // アイコン
509                     new ColumnHeader { Text = this.ColumnText[2], Width = 300 },  // 本文
510                 };
511
512                 if (startup)
513                 {
514                     var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
515
516                     columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
517                     columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
518                     columns[0].DisplayIndex = 0;
519                     columns[1].DisplayIndex = 1;
520                 }
521                 else
522                 {
523                     var idx = 0;
524                     foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
525                     {
526                         columns[idx].Width = curListColumn.Width;
527                         columns[idx].DisplayIndex = curListColumn.DisplayIndex;
528                         idx++;
529                     }
530                 }
531             }
532             else
533             {
534                 columns = new[]
535                 {
536                     new ColumnHeader { Text = this.ColumnText[0], Width = 48 }, // アイコン
537                     new ColumnHeader { Text = this.ColumnText[1], Width = 80 }, // ニックネーム
538                     new ColumnHeader { Text = this.ColumnText[2], Width = 300 }, // 本文
539                     new ColumnHeader { Text = this.ColumnText[3], Width = 50 }, // 日付
540                     new ColumnHeader { Text = this.ColumnText[4], Width = 50 }, // ユーザID
541                     new ColumnHeader { Text = this.ColumnText[5], Width = 16 }, // 未読
542                     new ColumnHeader { Text = this.ColumnText[6], Width = 16 }, // マーク&プロテクト
543                     new ColumnHeader { Text = this.ColumnText[7], Width = 50 }, // ソース
544                 };
545
546                 if (startup)
547                 {
548                     var widthScaleFactor = this.CurrentAutoScaleDimensions.Width / this._cfgLocal.ScaleDimension.Width;
549
550                     columns[0].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width1);
551                     columns[1].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width2);
552                     columns[2].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width3);
553                     columns[3].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width4);
554                     columns[4].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width5);
555                     columns[5].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width6);
556                     columns[6].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width7);
557                     columns[7].Width = ScaleBy(widthScaleFactor, _cfgLocal.Width8);
558
559                     var displayIndex = new[] {
560                         this._cfgLocal.DisplayIndex1, this._cfgLocal.DisplayIndex2,
561                         this._cfgLocal.DisplayIndex3, this._cfgLocal.DisplayIndex4,
562                         this._cfgLocal.DisplayIndex5, this._cfgLocal.DisplayIndex6,
563                         this._cfgLocal.DisplayIndex7, this._cfgLocal.DisplayIndex8
564                     };
565
566                     foreach (var i in Enumerable.Range(0, displayIndex.Length))
567                     {
568                         columns[i].DisplayIndex = displayIndex[i];
569                     }
570                 }
571                 else
572                 {
573                     var idx = 0;
574                     foreach (var curListColumn in this._curList.Columns.Cast<ColumnHeader>())
575                     {
576                         columns[idx].Width = curListColumn.Width;
577                         columns[idx].DisplayIndex = curListColumn.DisplayIndex;
578                         idx++;
579                     }
580                 }
581             }
582
583             list.Columns.AddRange(columns);
584         }
585
586         private void InitColumnText()
587         {
588             ColumnText[0] = "";
589             ColumnText[1] = Properties.Resources.AddNewTabText2;
590             ColumnText[2] = Properties.Resources.AddNewTabText3;
591             ColumnText[3] = Properties.Resources.AddNewTabText4_2;
592             ColumnText[4] = Properties.Resources.AddNewTabText5;
593             ColumnText[5] = "";
594             ColumnText[6] = "";
595             ColumnText[7] = "Source";
596
597             ColumnOrgText[0] = "";
598             ColumnOrgText[1] = Properties.Resources.AddNewTabText2;
599             ColumnOrgText[2] = Properties.Resources.AddNewTabText3;
600             ColumnOrgText[3] = Properties.Resources.AddNewTabText4_2;
601             ColumnOrgText[4] = Properties.Resources.AddNewTabText5;
602             ColumnOrgText[5] = "";
603             ColumnOrgText[6] = "";
604             ColumnOrgText[7] = "Source";
605
606             int c = 0;
607             switch (_statuses.SortMode)
608             {
609                 case ComparerMode.Nickname:  //ニックネーム
610                     c = 1;
611                     break;
612                 case ComparerMode.Data:  //本文
613                     c = 2;
614                     break;
615                 case ComparerMode.Id:  //時刻=発言Id
616                     c = 3;
617                     break;
618                 case ComparerMode.Name:  //名前
619                     c = 4;
620                     break;
621                 case ComparerMode.Source:  //Source
622                     c = 7;
623                     break;
624             }
625
626             if (_iconCol)
627             {
628                 if (_statuses.SortOrder == SortOrder.Descending)
629                 {
630                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
631                     ColumnText[2] = ColumnOrgText[2] + "▾";
632                 }
633                 else
634                 {
635                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
636                     ColumnText[2] = ColumnOrgText[2] + "▴";
637                 }
638             }
639             else
640             {
641                 if (_statuses.SortOrder == SortOrder.Descending)
642                 {
643                     // U+25BE BLACK DOWN-POINTING SMALL TRIANGLE
644                     ColumnText[c] = ColumnOrgText[c] + "▾";
645                 }
646                 else
647                 {
648                     // U+25B4 BLACK UP-POINTING SMALL TRIANGLE
649                     ColumnText[c] = ColumnOrgText[c] + "▴";
650                 }
651             }
652         }
653
654         private void InitializeTraceFrag()
655         {
656 #if DEBUG
657             TraceOutToolStripMenuItem.Checked = true;
658             MyCommon.TraceFlag = true;
659 #endif
660             if (!MyCommon.FileVersion.EndsWith("0"))
661             {
662                 TraceOutToolStripMenuItem.Checked = true;
663                 MyCommon.TraceFlag = true;
664             }
665         }
666
667         private void TweenMain_Load(object sender, EventArgs e)
668         {
669             _ignoreConfigSave = true;
670             this.Visible = false;
671
672             if (MyApplication.StartupOptions.ContainsKey("d"))
673                 MyCommon.TraceFlag = true;
674
675             InitializeTraceFrag();
676
677             //Win32Api.SetProxy(HttpConnection.ProxyType.Specified, "127.0.0.1", 8080, "user", "pass")
678
679             new InternetSecurityManager(PostBrowser);
680             this.PostBrowser.AllowWebBrowserDrop = false;  // COMException を回避するため、ActiveX の初期化が終わってから設定する
681
682             MyCommon.TwitterApiInfo.AccessLimitUpdated += TwitterApiStatus_AccessLimitUpdated;
683             Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
684
685             Regex.CacheSize = 100;
686
687             //発言保持クラス
688             _statuses = TabInformations.GetInstance();
689
690             //アイコン設定
691             LoadIcons();
692             this.Icon = MainIcon;              //メインフォーム(TweenMain)
693             NotifyIcon1.Icon = NIconAt;      //タスクトレイ
694             TabImage.Images.Add(TabIcon);    //タブ見出し
695
696             //<<<<<<<<<設定関連>>>>>>>>>
697             ////設定読み出し
698             LoadConfig();
699
700             // 現在の DPI と設定保存時の DPI との比を取得する
701             var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
702
703             // UIフォント設定
704             var fontUIGlobal = this._cfgLocal.FontUIGlobal;
705             if (fontUIGlobal != null)
706             {
707                 OTBaseForm.GlobalFont = fontUIGlobal;
708                 this.Font = fontUIGlobal;
709             }
710
711             //不正値チェック
712             if (!MyApplication.StartupOptions.ContainsKey("nolimit"))
713             {
714                 if (this._cfgCommon.TimelinePeriod < 15 && this._cfgCommon.TimelinePeriod > 0)
715                     this._cfgCommon.TimelinePeriod = 15;
716
717                 if (this._cfgCommon.ReplyPeriod < 15 && this._cfgCommon.ReplyPeriod > 0)
718                     this._cfgCommon.ReplyPeriod = 15;
719
720                 if (this._cfgCommon.DMPeriod < 15 && this._cfgCommon.DMPeriod > 0)
721                     this._cfgCommon.DMPeriod = 15;
722
723                 if (this._cfgCommon.PubSearchPeriod < 30 && this._cfgCommon.PubSearchPeriod > 0)
724                     this._cfgCommon.PubSearchPeriod = 30;
725
726                 if (this._cfgCommon.UserTimelinePeriod < 15 && this._cfgCommon.UserTimelinePeriod > 0)
727                     this._cfgCommon.UserTimelinePeriod = 15;
728
729                 if (this._cfgCommon.ListsPeriod < 15 && this._cfgCommon.ListsPeriod > 0)
730                     this._cfgCommon.ListsPeriod = 15;
731             }
732
733             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Timeline, this._cfgCommon.CountApi))
734                 this._cfgCommon.CountApi = 60;
735             if (!Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Reply, this._cfgCommon.CountApiReply))
736                 this._cfgCommon.CountApiReply = 40;
737
738             if (this._cfgCommon.MoreCountApi != 0 && !Twitter.VerifyMoreApiResultCount(this._cfgCommon.MoreCountApi))
739                 this._cfgCommon.MoreCountApi = 200;
740             if (this._cfgCommon.FirstCountApi != 0 && !Twitter.VerifyFirstApiResultCount(this._cfgCommon.FirstCountApi))
741                 this._cfgCommon.FirstCountApi = 100;
742
743             if (this._cfgCommon.FavoritesCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.Favorites, this._cfgCommon.FavoritesCountApi))
744                 this._cfgCommon.FavoritesCountApi = 40;
745             if (this._cfgCommon.ListCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.List, this._cfgCommon.ListCountApi))
746                 this._cfgCommon.ListCountApi = 100;
747             if (this._cfgCommon.SearchCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.PublicSearch, this._cfgCommon.SearchCountApi))
748                 this._cfgCommon.SearchCountApi = 100;
749             if (this._cfgCommon.UserTimelineCountApi != 0 && !Twitter.VerifyApiResultCount(MyCommon.WORKERTYPE.UserTimeline, this._cfgCommon.UserTimelineCountApi))
750                 this._cfgCommon.UserTimelineCountApi = 20;
751
752             //廃止サービスが選択されていた場合ux.nuへ読み替え
753             if (this._cfgCommon.AutoShortUrlFirst < 0)
754                 this._cfgCommon.AutoShortUrlFirst = MyCommon.UrlConverter.Uxnu;
755
756             HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
757
758             //認証関連
759             if (string.IsNullOrEmpty(this._cfgCommon.Token)) this._cfgCommon.UserName = "";
760             tw.Initialize(this._cfgCommon.Token, this._cfgCommon.TokenSecret, this._cfgCommon.UserName, this._cfgCommon.UserId);
761
762             _initial = true;
763
764             Networking.Initialize();
765
766             bool saveRequired = false;
767             bool firstRun = false;
768
769             //ユーザー名、パスワードが未設定なら設定画面を表示(初回起動時など)
770             if (string.IsNullOrEmpty(tw.Username))
771             {
772                 saveRequired = true;
773                 firstRun = true;
774
775                 //設定せずにキャンセルされたか、設定されたが依然ユーザー名が未設定ならプログラム終了
776                 if (ShowSettingDialog(showTaskbarIcon: true) != DialogResult.OK ||
777                     string.IsNullOrEmpty(tw.Username))
778                 {
779                     Application.Exit();  //強制終了
780                     return;
781                 }
782             }
783
784             //Twitter用通信クラス初期化
785             Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
786             Networking.SetWebProxy(this._cfgLocal.ProxyType,
787                 this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
788                 this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
789             Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
790
791             HttpTwitter.TwitterUrl = this._cfgCommon.TwitterUrl;
792             tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
793             tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
794             tw.TrackWord = this._cfgCommon.TrackWord;
795             TrackToolStripMenuItem.Checked = !String.IsNullOrEmpty(tw.TrackWord);
796             tw.AllAtReply = this._cfgCommon.AllAtReply;
797             AllrepliesToolStripMenuItem.Checked = tw.AllAtReply;
798             ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
799             ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
800             ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
801
802             // アクセストークンが有効であるか確認する
803             // ここが Twitter API への最初のアクセスになるようにすること
804             try
805             {
806                 this.tw.VerifyCredentials();
807             }
808             catch (WebApiException ex)
809             {
810                 MessageBox.Show(this, string.Format(Properties.Resources.StartupAuthError_Text, ex.Message),
811                     Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
812             }
813
814             //サムネイル関連の初期化
815             //プロキシ設定等の通信まわりの初期化が済んでから処理する
816             ThumbnailGenerator.InitializeGenerator();
817
818             var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
819             imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
820             imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
821
822             Thumbnail.Services.TonTwitterCom.InitializeOAuthToken = x =>
823                 x.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret,
824                     this.tw.AccessToken, this.tw.AccessTokenSecret, "", "");
825
826             //画像投稿サービス
827             ImageSelector.Initialize(tw, this.tw.Configuration, _cfgCommon.UseImageServiceName, _cfgCommon.UseImageService);
828
829             //ハッシュタグ/@id関連
830             AtIdSupl = new AtIdSupplement(SettingAtIdList.Load().AtIdList, "@");
831             HashSupl = new AtIdSupplement(_cfgCommon.HashTags, "#");
832             HashMgr = new HashtagManage(HashSupl,
833                                     _cfgCommon.HashTags.ToArray(),
834                                     _cfgCommon.HashSelected,
835                                     _cfgCommon.HashIsPermanent,
836                                     _cfgCommon.HashIsHead,
837                                     _cfgCommon.HashIsNotAddToAtReply);
838             if (!string.IsNullOrEmpty(HashMgr.UseHash) && HashMgr.IsPermanent) HashStripSplitButton.Text = HashMgr.UseHash;
839
840             //アイコンリスト作成
841             this.IconCache = new ImageCache();
842
843             //フォント&文字色&背景色保持
844             _fntUnread = this._cfgLocal.FontUnread;
845             _clUnread = this._cfgLocal.ColorUnread;
846             _fntReaded = this._cfgLocal.FontRead;
847             _clReaded = this._cfgLocal.ColorRead;
848             _clFav = this._cfgLocal.ColorFav;
849             _clOWL = this._cfgLocal.ColorOWL;
850             _clRetweet = this._cfgLocal.ColorRetweet;
851             _fntDetail = this._cfgLocal.FontDetail;
852             _clDetail = this._cfgLocal.ColorDetail;
853             _clDetailLink = this._cfgLocal.ColorDetailLink;
854             _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
855             _clSelf = this._cfgLocal.ColorSelf;
856             _clAtSelf = this._cfgLocal.ColorAtSelf;
857             _clTarget = this._cfgLocal.ColorTarget;
858             _clAtTarget = this._cfgLocal.ColorAtTarget;
859             _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
860             _clAtTo = this._cfgLocal.ColorAtTo;
861             _clListBackcolor = this._cfgLocal.ColorListBackcolor;
862             _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
863             _clInputFont = this._cfgLocal.ColorInputFont;
864             _fntInputFont = this._cfgLocal.FontInputFont;
865
866             _brsBackColorMine = new SolidBrush(_clSelf);
867             _brsBackColorAt = new SolidBrush(_clAtSelf);
868             _brsBackColorYou = new SolidBrush(_clTarget);
869             _brsBackColorAtYou = new SolidBrush(_clAtTarget);
870             _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
871             _brsBackColorAtTo = new SolidBrush(_clAtTo);
872             //_brsBackColorNone = new SolidBrush(Color.FromKnownColor(KnownColor.Window));
873             _brsBackColorNone = new SolidBrush(_clListBackcolor);
874
875             // StringFormatオブジェクトへの事前設定
876             //sf.Alignment = StringAlignment.Near;             // Textを近くへ配置(左から右の場合は左寄せ)
877             //sf.LineAlignment = StringAlignment.Near;         // Textを近くへ配置(上寄せ)
878             //sf.FormatFlags = StringFormatFlags.LineLimit;    // 
879             sfTab.Alignment = StringAlignment.Center;
880             sfTab.LineAlignment = StringAlignment.Center;
881
882             InitDetailHtmlFormat();
883
884             //Regex statregex = new Regex("^0*");
885             this.recommendedStatusFooter = " [TWNv" + Regex.Replace(MyCommon.FileVersion.Replace(".", ""), "^0*", "") + "]";
886
887             _history.Add(new PostingStatus());
888             _hisIdx = 0;
889             this.inReplyTo = null;
890
891             //各種ダイアログ設定
892             SearchDialog.Owner = this;
893             UrlDialog.Owner = this;
894
895             //新着バルーン通知のチェック状態設定
896             NewPostPopMenuItem.Checked = _cfgCommon.NewAllPop;
897             this.NotifyFileMenuItem.Checked = NewPostPopMenuItem.Checked;
898
899             //新着取得時のリストスクロールをするか。trueならスクロールしない
900             ListLockMenuItem.Checked = _cfgCommon.ListLock;
901             this.LockListFileMenuItem.Checked = _cfgCommon.ListLock;
902             //サウンド再生(タブ別設定より優先)
903             this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
904             this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
905
906             this.IdeographicSpaceToSpaceToolStripMenuItem.Checked = _cfgCommon.WideSpaceConvert;
907             this.ToolStripFocusLockMenuItem.Checked = _cfgCommon.FocusLockToStatusText;
908
909             //ウィンドウ設定
910             this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
911             _mySize = this.ClientSize; // サイズ保持(最小化・最大化されたまま終了した場合の対応用)
912             _myLoc = _cfgLocal.FormLocation;
913             //タイトルバー領域
914             if (this.WindowState != FormWindowState.Minimized)
915             {
916                 this.DesktopLocation = _cfgLocal.FormLocation;
917                 Rectangle tbarRect = new Rectangle(this.Location, new Size(_mySize.Width, SystemInformation.CaptionHeight));
918                 bool outOfScreen = true;
919                 if (Screen.AllScreens.Length == 1)    //ハングするとの報告
920                 {
921                     foreach (Screen scr in Screen.AllScreens)
922                     {
923                         if (!Rectangle.Intersect(tbarRect, scr.Bounds).IsEmpty)
924                         {
925                             outOfScreen = false;
926                             break;
927                         }
928                     }
929                     if (outOfScreen)
930                     {
931                         this.DesktopLocation = new Point(0, 0);
932                         _myLoc = this.DesktopLocation;
933                     }
934                 }
935             }
936             this.TopMost = this._cfgCommon.AlwaysTop;
937             _mySpDis = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
938             _mySpDis2 = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
939             if (_cfgLocal.PreviewDistance == -1)
940             {
941                 _mySpDis3 = _mySize.Width - ScaleBy(this.CurrentScaleFactor.Width, 150);
942                 if (_mySpDis3 < 1) _mySpDis3 = ScaleBy(this.CurrentScaleFactor.Width, 50);
943                 _cfgLocal.PreviewDistance = _mySpDis3;
944             }
945             else
946             {
947                 _mySpDis3 = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
948             }
949             MultiLineMenuItem.Checked = _cfgLocal.StatusMultiline;
950             //this.Tween_ClientSizeChanged(this, null);
951             this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
952             this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
953             //入力欄
954             StatusText.Font = _fntInputFont;
955             StatusText.ForeColor = _clInputFont;
956
957             // SplitContainer2.Panel2MinSize を一行表示の入力欄の高さに合わせる (MS UI Gothic 12pt (96dpi) の場合は 19px)
958             this.StatusText.Multiline = false; // _cfgLocal.StatusMultiline の設定は後で反映される
959             this.SplitContainer2.Panel2MinSize = this.StatusText.Height;
960
961             // NameLabel のフォントを OTBaseForm.GlobalFont に変更
962             this.NameLabel.Font = this.ReplaceToGlobalFont(this.NameLabel.Font);
963
964             // 必要であれば、発言一覧と発言詳細部・入力欄の上下を入れ替える
965             SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
966
967             //全新着通知のチェック状態により、Reply&DMの新着通知有効無効切り替え(タブ別設定にするため削除予定)
968             if (this._cfgCommon.UnreadManage == false)
969             {
970                 ReadedStripMenuItem.Enabled = false;
971                 UnreadStripMenuItem.Enabled = false;
972             }
973
974             //発言詳細部の初期化
975             NameLabel.Text = "";
976             DateTimeLabel.Text = "";
977             SourceLinkLabel.Text = "";
978
979             //リンク先URL表示部の初期化(画面左下)
980             StatusLabelUrl.Text = "";
981             //状態表示部の初期化(画面右下)
982             StatusLabel.Text = "";
983             StatusLabel.AutoToolTip = false;
984             StatusLabel.ToolTipText = "";
985             //文字カウンタ初期化
986             lblLen.Text = this.GetRestStatusCount(this.FormatStatusText("")).ToString();
987
988             this.JumpReadOpMenuItem.ShortcutKeyDisplayString = "Space";
989             CopySTOTMenuItem.ShortcutKeyDisplayString = "Ctrl+C";
990             CopyURLMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+C";
991             CopyUserIdStripMenuItem.ShortcutKeyDisplayString = "Shift+Alt+C";
992
993             ////////////////////////////////////////////////////////////////////////////////
994             var sortOrder = (SortOrder)_cfgCommon.SortOrder;
995             var mode = ComparerMode.Id;
996             switch (_cfgCommon.SortColumn)
997             {
998                 case 0:    //0:アイコン,5:未読マーク,6:プロテクト・フィルターマーク
999                 case 5:
1000                 case 6:
1001                     //ソートしない
1002                     mode = ComparerMode.Id;  //Idソートに読み替え
1003                     break;
1004                 case 1:  //ニックネーム
1005                     mode = ComparerMode.Nickname;
1006                     break;
1007                 case 2:  //本文
1008                     mode = ComparerMode.Data;
1009                     break;
1010                 case 3:  //時刻=発言Id
1011                     mode = ComparerMode.Id;
1012                     break;
1013                 case 4:  //名前
1014                     mode = ComparerMode.Name;
1015                     break;
1016                 case 7:  //Source
1017                     mode = ComparerMode.Source;
1018                     break;
1019             }
1020             _statuses.SetSortMode(mode, sortOrder);
1021             ////////////////////////////////////////////////////////////////////////////////
1022
1023             ApplyListViewIconSize(this._cfgCommon.IconSize);
1024
1025             //<<<<<<<<タブ関連>>>>>>>
1026             // タブの位置を調整する
1027             SetTabAlignment();
1028
1029             //デフォルトタブの存在チェック、ない場合には追加
1030             if (_statuses.GetTabByType(MyCommon.TabUsageType.Home) == null)
1031             {
1032                 TabClass tab;
1033                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.RECENT, out tab))
1034                 {
1035                     _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1036                 }
1037                 else
1038                 {
1039                     tab.TabType = MyCommon.TabUsageType.Home;
1040                 }
1041             }
1042             if (_statuses.GetTabByType(MyCommon.TabUsageType.Mentions) == null)
1043             {
1044                 TabClass tab;
1045                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.REPLY, out tab))
1046                 {
1047                     _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1048                 }
1049                 else
1050                 {
1051                     tab.TabType = MyCommon.TabUsageType.Mentions;
1052                 }
1053             }
1054             if (_statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage) == null)
1055             {
1056                 TabClass tab;
1057                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.DM, out tab))
1058                 {
1059                     _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1060                 }
1061                 else
1062                 {
1063                     tab.TabType = MyCommon.TabUsageType.DirectMessage;
1064                 }
1065             }
1066             if (_statuses.GetTabByType(MyCommon.TabUsageType.Favorites) == null)
1067             {
1068                 TabClass tab;
1069                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.FAV, out tab))
1070                 {
1071                     _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1072                 }
1073                 else
1074                 {
1075                     tab.TabType = MyCommon.TabUsageType.Favorites;
1076                 }
1077             }
1078             if (_statuses.GetTabByType(MyCommon.TabUsageType.Mute) == null)
1079             {
1080                 TabClass tab;
1081                 if (!_statuses.Tabs.TryGetValue(MyCommon.DEFAULTTAB.MUTE, out tab))
1082                 {
1083                     _statuses.AddTab(MyCommon.DEFAULTTAB.MUTE, MyCommon.TabUsageType.Mute, null);
1084                 }
1085                 else
1086                 {
1087                     tab.TabType = MyCommon.TabUsageType.Mute;
1088                 }
1089             }
1090
1091             foreach (var tab in _statuses.Tabs.Values)
1092             {
1093                 // ミュートタブは表示しない
1094                 if (tab.TabType == MyCommon.TabUsageType.Mute)
1095                     continue;
1096
1097                 if (tab.TabType == MyCommon.TabUsageType.Undefined)
1098                 {
1099                     tab.TabType = MyCommon.TabUsageType.UserDefined;
1100                 }
1101                 if (!AddNewTab(tab.TabName, true, tab.TabType, tab.ListInfo))
1102                     throw new TabException(Properties.Resources.TweenMain_LoadText1);
1103             }
1104
1105             _curTab = ListTab.SelectedTab;
1106             _curItemIndex = -1;
1107             _curList = (DetailsListView)_curTab.Tag;
1108
1109             if (this._cfgCommon.TabIconDisp)
1110             {
1111                 ListTab.DrawMode = TabDrawMode.Normal;
1112             }
1113             else
1114             {
1115                 ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
1116                 ListTab.DrawItem += ListTab_DrawItem;
1117                 ListTab.ImageList = null;
1118             }
1119
1120             if (this._cfgCommon.HotkeyEnabled)
1121             {
1122                 //////グローバルホットキーの登録
1123                 HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
1124                 if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
1125                     modKey |= HookGlobalHotkey.ModKeys.Alt;
1126                 if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
1127                     modKey |= HookGlobalHotkey.ModKeys.Ctrl;
1128                 if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
1129                     modKey |= HookGlobalHotkey.ModKeys.Shift;
1130                 if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
1131                     modKey |= HookGlobalHotkey.ModKeys.Win;
1132
1133                 _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
1134             }
1135
1136             if (this._cfgCommon.IsUseNotifyGrowl)
1137                 gh.RegisterGrowl();
1138
1139             StatusLabel.Text = Properties.Resources.Form1_LoadText1;       //画面右下の状態表示を変更
1140
1141             SetMainWindowTitle();
1142             SetNotifyIconText();
1143
1144             if (!this._cfgCommon.MinimizeToTray || this.WindowState != FormWindowState.Minimized)
1145             {
1146                 this.Visible = true;
1147             }
1148
1149             //タイマー設定
1150             TimerTimeline.AutoReset = true;
1151             TimerTimeline.SynchronizingObject = this;
1152             //Recent取得間隔
1153             TimerTimeline.Interval = 1000;
1154             TimerTimeline.Enabled = true;
1155             //更新中アイコンアニメーション間隔
1156             TimerRefreshIcon.Interval = 200;
1157             TimerRefreshIcon.Enabled = true;
1158
1159             _ignoreConfigSave = false;
1160             this.TweenMain_Resize(null, null);
1161             if (saveRequired) SaveConfigsAll(false);
1162
1163             foreach (var ua in this._cfgCommon.UserAccounts)
1164             {
1165                 if (ua.UserId == 0 && ua.Username.ToLower() == tw.Username.ToLower())
1166                 {
1167                     ua.UserId = tw.UserId;
1168                     break;
1169                 }
1170             }
1171
1172             if (firstRun)
1173             {
1174                 // 初回起動時だけ右下のメニューを目立たせる
1175                 HashStripSplitButton.ShowDropDown();
1176             }
1177         }
1178
1179         private void InitDetailHtmlFormat()
1180         {
1181             if (this._cfgCommon.IsMonospace)
1182             {
1183                 detailHtmlFormatHeader = detailHtmlFormatHeaderMono;
1184                 detailHtmlFormatFooter = detailHtmlFormatFooterMono;
1185             }
1186             else
1187             {
1188                 detailHtmlFormatHeader = detailHtmlFormatHeaderColor;
1189                 detailHtmlFormatFooter = detailHtmlFormatFooterColor;
1190             }
1191
1192             detailHtmlFormatHeader = detailHtmlFormatHeader
1193                     .Replace("%FONT_FAMILY%", _fntDetail.Name)
1194                     .Replace("%FONT_SIZE%", _fntDetail.Size.ToString())
1195                     .Replace("%FONT_COLOR%", _clDetail.R.ToString() + "," + _clDetail.G.ToString() + "," + _clDetail.B.ToString())
1196                     .Replace("%LINK_COLOR%", _clDetailLink.R.ToString() + "," + _clDetailLink.G.ToString() + "," + _clDetailLink.B.ToString())
1197                     .Replace("%BG_COLOR%", _clDetailBackcolor.R.ToString() + "," + _clDetailBackcolor.G.ToString() + "," + _clDetailBackcolor.B.ToString());
1198         }
1199
1200         private void ListTab_DrawItem(object sender, DrawItemEventArgs e)
1201         {
1202             string txt;
1203             try
1204             {
1205                 txt = ListTab.TabPages[e.Index].Text;
1206             }
1207             catch (Exception)
1208             {
1209                 return;
1210             }
1211
1212             e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, e.Bounds);
1213             if (e.State == DrawItemState.Selected)
1214             {
1215                 e.DrawFocusRectangle();
1216             }
1217             Brush fore;
1218             try
1219             {
1220                 if (_statuses.Tabs[txt].UnreadCount > 0)
1221                     fore = Brushes.Red;
1222                 else
1223                     fore = System.Drawing.SystemBrushes.ControlText;
1224             }
1225             catch (Exception)
1226             {
1227                 fore = System.Drawing.SystemBrushes.ControlText;
1228             }
1229             e.Graphics.DrawString(txt, e.Font, fore, e.Bounds, sfTab);
1230         }
1231
1232         private void LoadConfig()
1233         {
1234             _cfgCommon = SettingCommon.Load();
1235             SettingCommon.Instance = this._cfgCommon;
1236             if (_cfgCommon.UserAccounts == null || _cfgCommon.UserAccounts.Count == 0)
1237             {
1238                 _cfgCommon.UserAccounts = new List<UserAccount>();
1239                 if (!string.IsNullOrEmpty(_cfgCommon.UserName))
1240                 {
1241                     UserAccount account = new UserAccount();
1242                     account.Username = _cfgCommon.UserName;
1243                     account.UserId = _cfgCommon.UserId;
1244                     account.Token = _cfgCommon.Token;
1245                     account.TokenSecret = _cfgCommon.TokenSecret;
1246
1247                     _cfgCommon.UserAccounts.Add(account);
1248                 }
1249             }
1250
1251             _cfgLocal = SettingLocal.Load();
1252
1253             // v1.2.4 以前の設定には ScaleDimension の項目がないため、現在の DPI と同じとして扱う
1254             if (_cfgLocal.ScaleDimension.IsEmpty)
1255                 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
1256
1257             List<TabClass> tabs = SettingTabs.Load().Tabs;
1258             foreach (TabClass tb in tabs)
1259             {
1260                 try
1261                 {
1262                     tb.FilterModified = false;
1263                     _statuses.Tabs.Add(tb.TabName, tb);
1264                 }
1265                 catch (Exception)
1266                 {
1267                     tb.TabName = _statuses.MakeTabName("MyTab");
1268                     _statuses.Tabs.Add(tb.TabName, tb);
1269                 }
1270             }
1271             if (_statuses.Tabs.Count == 0)
1272             {
1273                 _statuses.AddTab(MyCommon.DEFAULTTAB.RECENT, MyCommon.TabUsageType.Home, null);
1274                 _statuses.AddTab(MyCommon.DEFAULTTAB.REPLY, MyCommon.TabUsageType.Mentions, null);
1275                 _statuses.AddTab(MyCommon.DEFAULTTAB.DM, MyCommon.TabUsageType.DirectMessage, null);
1276                 _statuses.AddTab(MyCommon.DEFAULTTAB.FAV, MyCommon.TabUsageType.Favorites, null);
1277             }
1278         }
1279
1280         private void TimerInterval_Changed(object sender, IntervalChangedEventArgs e) //Handles SettingDialog.IntervalChanged
1281         {
1282             if (!TimerTimeline.Enabled) return;
1283             ResetTimers = e;
1284         }
1285
1286         private IntervalChangedEventArgs ResetTimers = IntervalChangedEventArgs.ResetAll;
1287
1288         private static int homeCounter = 0;
1289         private static int mentionCounter = 0;
1290         private static int dmCounter = 0;
1291         private static int pubSearchCounter = 0;
1292         private static int userTimelineCounter = 0;
1293         private static int listsCounter = 0;
1294         private static int usCounter = 0;
1295         private static int ResumeWait = 0;
1296         private static int refreshFollowers = 0;
1297
1298         private async void TimerTimeline_Elapsed(object sender, EventArgs e)
1299         {
1300             if (homeCounter > 0) Interlocked.Decrement(ref homeCounter);
1301             if (mentionCounter > 0) Interlocked.Decrement(ref mentionCounter);
1302             if (dmCounter > 0) Interlocked.Decrement(ref dmCounter);
1303             if (pubSearchCounter > 0) Interlocked.Decrement(ref pubSearchCounter);
1304             if (userTimelineCounter > 0) Interlocked.Decrement(ref userTimelineCounter);
1305             if (listsCounter > 0) Interlocked.Decrement(ref listsCounter);
1306             if (usCounter > 0) Interlocked.Decrement(ref usCounter);
1307             Interlocked.Increment(ref refreshFollowers);
1308
1309             var refreshTasks = new List<Task>();
1310
1311             ////タイマー初期化
1312             if (ResetTimers.Timeline || homeCounter <= 0 && this._cfgCommon.TimelinePeriod > 0)
1313             {
1314                 Interlocked.Exchange(ref homeCounter, this._cfgCommon.TimelinePeriod);
1315                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Timeline)
1316                     refreshTasks.Add(this.GetHomeTimelineAsync());
1317                 ResetTimers.Timeline = false;
1318             }
1319             if (ResetTimers.Reply || mentionCounter <= 0 && this._cfgCommon.ReplyPeriod > 0)
1320             {
1321                 Interlocked.Exchange(ref mentionCounter, this._cfgCommon.ReplyPeriod);
1322                 if (!tw.IsUserstreamDataReceived && !ResetTimers.Reply)
1323                     refreshTasks.Add(this.GetReplyAsync());
1324                 ResetTimers.Reply = false;
1325             }
1326             if (ResetTimers.DirectMessage || dmCounter <= 0 && this._cfgCommon.DMPeriod > 0)
1327             {
1328                 Interlocked.Exchange(ref dmCounter, this._cfgCommon.DMPeriod);
1329                 if (!tw.IsUserstreamDataReceived && !ResetTimers.DirectMessage)
1330                     refreshTasks.Add(this.GetDirectMessagesAsync());
1331                 ResetTimers.DirectMessage = false;
1332             }
1333             if (ResetTimers.PublicSearch || pubSearchCounter <= 0 && this._cfgCommon.PubSearchPeriod > 0)
1334             {
1335                 Interlocked.Exchange(ref pubSearchCounter, this._cfgCommon.PubSearchPeriod);
1336                 if (!ResetTimers.PublicSearch)
1337                     refreshTasks.Add(this.GetPublicSearchAllAsync());
1338                 ResetTimers.PublicSearch = false;
1339             }
1340             if (ResetTimers.UserTimeline || userTimelineCounter <= 0 && this._cfgCommon.UserTimelinePeriod > 0)
1341             {
1342                 Interlocked.Exchange(ref userTimelineCounter, this._cfgCommon.UserTimelinePeriod);
1343                 if (!ResetTimers.UserTimeline)
1344                     refreshTasks.Add(this.GetUserTimelineAllAsync());
1345                 ResetTimers.UserTimeline = false;
1346             }
1347             if (ResetTimers.Lists || listsCounter <= 0 && this._cfgCommon.ListsPeriod > 0)
1348             {
1349                 Interlocked.Exchange(ref listsCounter, this._cfgCommon.ListsPeriod);
1350                 if (!ResetTimers.Lists)
1351                     refreshTasks.Add(this.GetListTimelineAllAsync());
1352                 ResetTimers.Lists = false;
1353             }
1354             if (ResetTimers.UserStream || usCounter <= 0 && this._cfgCommon.UserstreamPeriod > 0)
1355             {
1356                 Interlocked.Exchange(ref usCounter, this._cfgCommon.UserstreamPeriod);
1357                 if (this._isActiveUserstream)
1358                 {
1359                     refreshTasks.Add(this.RefreshTasktrayIcon(true));
1360                     this.RefreshTimeline();
1361                 }
1362                 ResetTimers.UserStream = false;
1363             }
1364             if (refreshFollowers > 6 * 3600)
1365             {
1366                 Interlocked.Exchange(ref refreshFollowers, 0);
1367                 refreshTasks.AddRange(new[]
1368                 {
1369                     this.doGetFollowersMenu(),
1370                     this.RefreshNoRetweetIdsAsync(),
1371                     this.RefreshTwitterConfigurationAsync(),
1372                 });
1373             }
1374             if (osResumed)
1375             {
1376                 Interlocked.Increment(ref ResumeWait);
1377                 if (ResumeWait > 30)
1378                 {
1379                     osResumed = false;
1380                     Interlocked.Exchange(ref ResumeWait, 0);
1381                     refreshTasks.AddRange(new[]
1382                     {
1383                         this.GetHomeTimelineAsync(),
1384                         this.GetReplyAsync(),
1385                         this.GetDirectMessagesAsync(),
1386                         this.GetPublicSearchAllAsync(),
1387                         this.GetUserTimelineAllAsync(),
1388                         this.GetListTimelineAllAsync(),
1389                         this.doGetFollowersMenu(),
1390                         this.RefreshTwitterConfigurationAsync(),
1391                     });
1392                 }
1393             }
1394
1395             await Task.WhenAll(refreshTasks);
1396         }
1397
1398         private void RefreshTimeline()
1399         {
1400             // 現在表示中のタブのスクロール位置を退避
1401             var curListScroll = this.SaveListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text]);
1402
1403             // 各タブのリスト上の選択位置などを退避
1404             var listSelections = this.SaveListViewSelection();
1405
1406             //更新確定
1407             PostClass[] notifyPosts;
1408             string soundFile;
1409             int addCount;
1410             bool newMentionOrDm;
1411             bool isDelete;
1412             addCount = _statuses.SubmitUpdate(out soundFile, out notifyPosts, out newMentionOrDm, out isDelete);
1413
1414             if (MyCommon._endingFlag) return;
1415
1416             //リストに反映&選択状態復元
1417             try
1418             {
1419                 foreach (TabPage tab in ListTab.TabPages)
1420                 {
1421                     DetailsListView lst = (DetailsListView)tab.Tag;
1422                     TabClass tabInfo = _statuses.Tabs[tab.Text];
1423                     using (ControlTransaction.Update(lst))
1424                     {
1425                         if (isDelete || lst.VirtualListSize != tabInfo.AllCount)
1426                         {
1427                             if (lst.Equals(_curList))
1428                             {
1429                                 this.PurgeListViewItemCache();
1430                             }
1431                             try
1432                             {
1433                                 lst.VirtualListSize = tabInfo.AllCount; //リスト件数更新
1434                             }
1435                             catch (Exception)
1436                             {
1437                                 //アイコン描画不具合あり?
1438                             }
1439
1440                             // 選択位置などを復元
1441                             this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
1442                         }
1443                     }
1444                     if (tabInfo.UnreadCount > 0)
1445                         if (this._cfgCommon.TabIconDisp)
1446                             if (tab.ImageIndex == -1) tab.ImageIndex = 0; //タブアイコン
1447                 }
1448                 if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
1449             }
1450             catch (Exception)
1451             {
1452                 //ex.Data["Msg"] = "Ref1, UseAPI=" + SettingDialog.UseAPI.ToString();
1453                 //throw;
1454             }
1455
1456             // スクロール位置を復元
1457             this.RestoreListViewScroll(this._curList, this._statuses.Tabs[this._curTab.Text], curListScroll);
1458
1459             //新着通知
1460             NotifyNewPosts(notifyPosts, soundFile, addCount, newMentionOrDm);
1461
1462             SetMainWindowTitle();
1463             if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
1464
1465             HashSupl.AddRangeItem(tw.GetHashList());
1466
1467         }
1468
1469         internal struct ListViewScroll
1470         {
1471             public ScrollLockMode ScrollLockMode { get; set; }
1472             public long? TopItemStatusId { get; set; }
1473         }
1474
1475         internal enum ScrollLockMode
1476         {
1477             /// <summary>固定しない</summary>
1478             None,
1479
1480             /// <summary>最上部に固定する</summary>
1481             FixedToTop,
1482
1483             /// <summary>最下部に固定する</summary>
1484             FixedToBottom,
1485
1486             /// <summary><see cref="ListViewScroll.TopItemStatusId"/> の位置に固定する</summary>
1487             FixedToItem,
1488         }
1489
1490         /// <summary>
1491         /// <see cref="ListView"/> のスクロール位置に関する情報を <see cref="ListViewScroll"/> として返します
1492         /// </summary>
1493         private ListViewScroll SaveListViewScroll(DetailsListView listView, TabClass tab)
1494         {
1495             var listScroll = new ListViewScroll
1496             {
1497                 ScrollLockMode = this.GetScrollLockMode(listView),
1498             };
1499
1500             if (listScroll.ScrollLockMode == ScrollLockMode.FixedToItem)
1501             {
1502                 var topItem = listView.TopItem;
1503                 if (topItem != null)
1504                     listScroll.TopItemStatusId = tab.GetId(topItem.Index);
1505             }
1506
1507             return listScroll;
1508         }
1509
1510         private ScrollLockMode GetScrollLockMode(DetailsListView listView)
1511         {
1512             if (this._statuses.SortMode == ComparerMode.Id)
1513             {
1514                 if (this._statuses.SortOrder == SortOrder.Ascending)
1515                 {
1516                     // Id昇順
1517                     if (this.ListLockMenuItem.Checked)
1518                         return ScrollLockMode.None;
1519
1520                     // 最下行が表示されていたら、最下行へ強制スクロール。最下行が表示されていなかったら制御しない
1521
1522                     // 一番下に表示されているアイテム
1523                     var bottomItem = listView.GetItemAt(0, listView.ClientSize.Height - 1);
1524                     if (bottomItem == null || bottomItem.Index == listView.VirtualListSize - 1)
1525                         return ScrollLockMode.FixedToBottom;
1526                     else
1527                         return ScrollLockMode.None;
1528                 }
1529                 else
1530                 {
1531                     // Id降順
1532                     if (this.ListLockMenuItem.Checked)
1533                         return ScrollLockMode.FixedToItem;
1534
1535                     // 最上行が表示されていたら、制御しない。最上行が表示されていなかったら、現在表示位置へ強制スクロール
1536                     var topItem = listView.TopItem;
1537                     if (topItem == null || topItem.Index == 0)
1538                         return ScrollLockMode.FixedToTop;
1539                     else
1540                         return ScrollLockMode.FixedToItem;
1541                 }
1542             }
1543             else
1544             {
1545                 return ScrollLockMode.FixedToItem;
1546             }
1547         }
1548
1549         internal struct ListViewSelection
1550         {
1551             public long[] SelectedStatusIds { get; set; }
1552             public long? SelectionMarkStatusId { get; set; }
1553             public long? FocusedStatusId { get; set; }
1554         }
1555
1556         /// <summary>
1557         /// <see cref="ListView"/> の選択状態を <see cref="ListViewSelection"/> として返します
1558         /// </summary>
1559         private IReadOnlyDictionary<string, ListViewSelection> SaveListViewSelection()
1560         {
1561             var listsDict = new Dictionary<string, ListViewSelection>();
1562
1563             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
1564             {
1565                 var listView = (DetailsListView)tabPage.Tag;
1566                 var tab = _statuses.Tabs[tabPage.Text];
1567
1568                 ListViewSelection listStatus;
1569                 if (listView.VirtualListSize != 0)
1570                 {
1571                     listStatus = new ListViewSelection
1572                     {
1573                         SelectedStatusIds = this.GetSelectedStatusIds(listView, tab),
1574                         FocusedStatusId = this.GetFocusedStatusId(listView, tab),
1575                         SelectionMarkStatusId = this.GetSelectionMarkStatusId(listView, tab),
1576                     };
1577                 }
1578                 else
1579                 {
1580                     listStatus = new ListViewSelection
1581                     {
1582                         SelectedStatusIds = new long[0],
1583                         SelectionMarkStatusId = null,
1584                         FocusedStatusId = null,
1585                     };
1586                 }
1587
1588                 listsDict[tab.TabName] = listStatus;
1589             }
1590
1591             return listsDict;
1592         }
1593
1594         private long[] GetSelectedStatusIds(DetailsListView listView, TabClass tab)
1595         {
1596             var selectedIndices = listView.SelectedIndices;
1597             if (selectedIndices.Count > 0 && selectedIndices.Count < 61)
1598                 return tab.GetId(selectedIndices);
1599             else
1600                 return null;
1601         }
1602
1603         private long? GetFocusedStatusId(DetailsListView listView, TabClass tab)
1604         {
1605             var focusedItem = listView.FocusedItem;
1606
1607             return focusedItem != null ? tab.GetId(focusedItem.Index) : (long?)null;
1608         }
1609
1610         private long? GetSelectionMarkStatusId(DetailsListView listView, TabClass tab)
1611         {
1612             var selectionMarkIndex = listView.SelectionMark;
1613
1614             return selectionMarkIndex != -1 ? tab.GetId(selectionMarkIndex) : (long?)null;
1615         }
1616
1617         /// <summary>
1618         /// <see cref="SaveListViewScroll"/> によって保存されたスクロール位置を復元します
1619         /// </summary>
1620         private void RestoreListViewScroll(DetailsListView listView, TabClass tab, ListViewScroll listScroll)
1621         {
1622             if (listView.VirtualListSize == 0)
1623                 return;
1624
1625             switch (listScroll.ScrollLockMode)
1626             {
1627                 case ScrollLockMode.FixedToTop:
1628                     listView.EnsureVisible(0);
1629                     break;
1630                 case ScrollLockMode.FixedToBottom:
1631                     listView.EnsureVisible(listView.VirtualListSize - 1);
1632                     break;
1633                 case ScrollLockMode.FixedToItem:
1634                     var topIndex = listScroll.TopItemStatusId != null ? tab.IndexOf(listScroll.TopItemStatusId.Value) : -1;
1635                     if (topIndex != -1)
1636                         listView.TopItem = listView.Items[topIndex];
1637                     break;
1638                 case ScrollLockMode.None:
1639                 default:
1640                     break;
1641             }
1642         }
1643
1644         /// <summary>
1645         /// <see cref="SaveListViewStatus"/> によって保存された選択状態を復元します
1646         /// </summary>
1647         private void RestoreListViewSelection(DetailsListView listView, TabClass tab, ListViewSelection listSelection)
1648         {
1649             // status_id から ListView 上のインデックスに変換
1650             int[] selectedIndices = null;
1651             if (listSelection.SelectedStatusIds != null)
1652                 selectedIndices = tab.IndexOf(listSelection.SelectedStatusIds).Where(x => x != -1).ToArray();
1653
1654             var focusedIndex = -1;
1655             if (listSelection.FocusedStatusId != null)
1656                 focusedIndex = tab.IndexOf(listSelection.FocusedStatusId.Value);
1657
1658             var selectionMarkIndex = -1;
1659             if (listSelection.SelectionMarkStatusId != null)
1660                 selectionMarkIndex = tab.IndexOf(listSelection.SelectionMarkStatusId.Value);
1661
1662             this.SelectListItem(listView, selectedIndices, focusedIndex, selectionMarkIndex);
1663         }
1664
1665         private bool BalloonRequired()
1666         {
1667             Twitter.FormattedEvent ev = new Twitter.FormattedEvent();
1668             ev.Eventtype = MyCommon.EVENTTYPE.None;
1669
1670             return BalloonRequired(ev);
1671         }
1672
1673         private bool IsEventNotifyAsEventType(MyCommon.EVENTTYPE type)
1674         {
1675             if (type == MyCommon.EVENTTYPE.None)
1676                 return true;
1677
1678             if (!this._cfgCommon.EventNotifyEnabled)
1679                 return false;
1680
1681             return this._cfgCommon.EventNotifyFlag.HasFlag(type);
1682         }
1683
1684         private bool IsMyEventNotityAsEventType(Twitter.FormattedEvent ev)
1685         {
1686             if (!ev.IsMe)
1687                 return true;
1688
1689             return this._cfgCommon.IsMyEventNotifyFlag.HasFlag(ev.Eventtype);
1690         }
1691
1692         private bool BalloonRequired(Twitter.FormattedEvent ev)
1693         {
1694             if (this._initial)
1695                 return false;
1696
1697             if (NativeMethods.IsScreenSaverRunning())
1698                 return false;
1699
1700             // 「新着通知」が無効
1701             if (!this.NewPostPopMenuItem.Checked)
1702             {
1703                 // 「新着通知が無効でもイベントを通知する」にも該当しない
1704                 if (!this._cfgCommon.ForceEventNotify || ev.Eventtype == MyCommon.EVENTTYPE.None)
1705                     return false;
1706             }
1707
1708             // 「画面最小化・アイコン時のみバルーンを表示する」が有効
1709             if (this._cfgCommon.LimitBalloon)
1710             {
1711                 if (this.WindowState != FormWindowState.Minimized && this.Visible && Form.ActiveForm != null)
1712                     return false;
1713             }
1714
1715             return this.IsEventNotifyAsEventType(ev.Eventtype) && this.IsMyEventNotityAsEventType(ev);
1716         }
1717
1718         private void NotifyNewPosts(PostClass[] notifyPosts, string soundFile, int addCount, bool newMentions)
1719         {
1720             if (this._cfgCommon.ReadOwnPost)
1721             {
1722                 if (notifyPosts != null && notifyPosts.Length > 0 && notifyPosts.All(x => x.UserId == tw.UserId))
1723                     return;
1724             }
1725
1726             //新着通知
1727             if (BalloonRequired())
1728             {
1729                 if (notifyPosts != null && notifyPosts.Length > 0)
1730                 {
1731                     //Growlは一個ずつばらして通知。ただし、3ポスト以上あるときはまとめる
1732                     if (this._cfgCommon.IsUseNotifyGrowl)
1733                     {
1734                         StringBuilder sb = new StringBuilder();
1735                         bool reply = false;
1736                         bool dm = false;
1737
1738                         foreach (PostClass post in notifyPosts)
1739                         {
1740                             if (!(notifyPosts.Length > 3))
1741                             {
1742                                 sb.Clear();
1743                                 reply = false;
1744                                 dm = false;
1745                             }
1746                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1747                             if (post.IsDm) dm = true;
1748                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1749                             switch (this._cfgCommon.NameBalloon)
1750                             {
1751                                 case MyCommon.NameBalloonEnum.UserID:
1752                                     sb.Append(post.ScreenName).Append(" : ");
1753                                     break;
1754                                 case MyCommon.NameBalloonEnum.NickName:
1755                                     sb.Append(post.Nickname).Append(" : ");
1756                                     break;
1757                             }
1758                             sb.Append(post.TextFromApi);
1759                             if (notifyPosts.Length > 3)
1760                             {
1761                                 if (notifyPosts.Last() != post) continue;
1762                             }
1763
1764                             StringBuilder title = new StringBuilder();
1765                             GrowlHelper.NotifyType nt;
1766                             if (this._cfgCommon.DispUsername)
1767                             {
1768                                 title.Append(tw.Username);
1769                                 title.Append(" - ");
1770                             }
1771                             else
1772                             {
1773                                 //title.Clear();
1774                             }
1775                             if (dm)
1776                             {
1777                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1778                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1779                                 title.Append(Application.ProductName);
1780                                 title.Append(" [DM] ");
1781                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1782                                 nt = GrowlHelper.NotifyType.DirectMessage;
1783                             }
1784                             else if (reply)
1785                             {
1786                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1787                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1788                                 title.Append(Application.ProductName);
1789                                 title.Append(" [Reply!] ");
1790                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1791                                 nt = GrowlHelper.NotifyType.Reply;
1792                             }
1793                             else
1794                             {
1795                                 //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1796                                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1797                                 title.Append(Application.ProductName);
1798                                 title.Append(" ");
1799                                 title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1800                                 nt = GrowlHelper.NotifyType.Notify;
1801                             }
1802                             string bText = sb.ToString();
1803                             if (string.IsNullOrEmpty(bText)) return;
1804
1805                             var image = this.IconCache.TryGetFromCache(post.ImageUrl);
1806                             gh.Notify(nt, post.StatusId.ToString(), title.ToString(), bText, image == null ? null : image.Image, post.ImageUrl);
1807                         }
1808                     }
1809                     else
1810                     {
1811                         StringBuilder sb = new StringBuilder();
1812                         bool reply = false;
1813                         bool dm = false;
1814                         foreach (PostClass post in notifyPosts)
1815                         {
1816                             if (post.IsReply && !post.IsExcludeReply) reply = true;
1817                             if (post.IsDm) dm = true;
1818                             if (sb.Length > 0) sb.Append(System.Environment.NewLine);
1819                             switch (this._cfgCommon.NameBalloon)
1820                             {
1821                                 case MyCommon.NameBalloonEnum.UserID:
1822                                     sb.Append(post.ScreenName).Append(" : ");
1823                                     break;
1824                                 case MyCommon.NameBalloonEnum.NickName:
1825                                     sb.Append(post.Nickname).Append(" : ");
1826                                     break;
1827                             }
1828                             sb.Append(post.TextFromApi);
1829
1830                         }
1831                         //if (SettingDialog.DispUsername) { NotifyIcon1.BalloonTipTitle = tw.Username + " - "; } else { NotifyIcon1.BalloonTipTitle = ""; }
1832                         StringBuilder title = new StringBuilder();
1833                         ToolTipIcon ntIcon;
1834                         if (this._cfgCommon.DispUsername)
1835                         {
1836                             title.Append(tw.Username);
1837                             title.Append(" - ");
1838                         }
1839                         else
1840                         {
1841                             //title.Clear();
1842                         }
1843                         if (dm)
1844                         {
1845                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1846                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [DM] " + Properties.Resources.RefreshDirectMessageText1 + " " + addCount.ToString() + Properties.Resources.RefreshDirectMessageText2;
1847                             ntIcon = ToolTipIcon.Warning;
1848                             title.Append(Application.ProductName);
1849                             title.Append(" [DM] ");
1850                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1851                         }
1852                         else if (reply)
1853                         {
1854                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
1855                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [Reply!] " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1856                             ntIcon = ToolTipIcon.Warning;
1857                             title.Append(Application.ProductName);
1858                             title.Append(" [Reply!] ");
1859                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1860                         }
1861                         else
1862                         {
1863                             //NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
1864                             //NotifyIcon1.BalloonTipTitle += Application.ProductName + " " + Properties.Resources.RefreshTimelineText1 + " " + addCount.ToString() + Properties.Resources.RefreshTimelineText2;
1865                             ntIcon = ToolTipIcon.Info;
1866                             title.Append(Application.ProductName);
1867                             title.Append(" ");
1868                             title.AppendFormat(Properties.Resources.RefreshTimeline_NotifyText, addCount);
1869                         }
1870                         string bText = sb.ToString();
1871                         if (string.IsNullOrEmpty(bText)) return;
1872                         //NotifyIcon1.BalloonTipText = sb.ToString();
1873                         //NotifyIcon1.ShowBalloonTip(500);
1874                         NotifyIcon1.BalloonTipTitle = title.ToString();
1875                         NotifyIcon1.BalloonTipText = bText;
1876                         NotifyIcon1.BalloonTipIcon = ntIcon;
1877                         NotifyIcon1.ShowBalloonTip(500);
1878                     }
1879                 }
1880             }
1881
1882             //サウンド再生
1883             if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(soundFile))
1884             {
1885                 try
1886                 {
1887                     string dir = Application.StartupPath;
1888                     if (Directory.Exists(Path.Combine(dir, "Sounds")))
1889                     {
1890                         dir = Path.Combine(dir, "Sounds");
1891                     }
1892                     using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, soundFile)))
1893                     {
1894                         player.Play();
1895                     }
1896                 }
1897                 catch (Exception)
1898                 {
1899                 }
1900             }
1901
1902             //mentions新着時に画面ブリンク
1903             if (!_initial && this._cfgCommon.BlinkNewMentions && newMentions && Form.ActiveForm == null)
1904             {
1905                 NativeMethods.FlashMyWindow(this.Handle, NativeMethods.FlashSpecification.FlashTray, 3);
1906             }
1907         }
1908
1909         private void MyList_SelectedIndexChanged(object sender, EventArgs e)
1910         {
1911             if (_curList == null || !_curList.Equals(sender) || _curList.SelectedIndices.Count != 1) return;
1912
1913             _curItemIndex = _curList.SelectedIndices[0];
1914             if (_curItemIndex > _curList.VirtualListSize - 1) return;
1915
1916             try
1917             {
1918                 _curPost = GetCurTabPost(_curItemIndex);
1919             }
1920             catch (ArgumentException)
1921             {
1922                 return;
1923             }
1924
1925             this.PushSelectPostChain();
1926
1927             this._statuses.SetReadAllTab(_curPost.StatusId, read: true);
1928             //キャッシュの書き換え
1929             ChangeCacheStyleRead(true, _curItemIndex);   //既読へ(フォント、文字色)
1930
1931             ColorizeList();
1932             _colorize = true;
1933         }
1934
1935         private void ChangeCacheStyleRead(bool Read, int Index)
1936         {
1937             var tabInfo = _statuses.Tabs[_curTab.Text];
1938             //Read:true=既読 false=未読
1939             //未読管理していなかったら既読として扱う
1940             if (!tabInfo.UnreadManage ||
1941                !this._cfgCommon.UnreadManage) Read = true;
1942
1943             var listCache = this._listItemCache;
1944             if (listCache == null)
1945                 return;
1946
1947             // キャッシュに含まれていないアイテムは対象外
1948             ListViewItem itm;
1949             PostClass post;
1950             if (!listCache.TryGetValue(Index, out itm, out post))
1951                 return;
1952
1953             ChangeItemStyleRead(Read, itm, post, ((DetailsListView)_curTab.Tag));
1954         }
1955
1956         private void ChangeItemStyleRead(bool Read, ListViewItem Item, PostClass Post, DetailsListView DList)
1957         {
1958             Font fnt;
1959             //フォント
1960             if (Read)
1961             {
1962                 fnt = _fntReaded;
1963                 Item.SubItems[5].Text = "";
1964             }
1965             else
1966             {
1967                 fnt = _fntUnread;
1968                 Item.SubItems[5].Text = "★";
1969             }
1970             //文字色
1971             Color cl;
1972             if (Post.IsFav)
1973                 cl = _clFav;
1974             else if (Post.RetweetedId != null)
1975                 cl = _clRetweet;
1976             else if (Post.IsOwl && (Post.IsDm || this._cfgCommon.OneWayLove))
1977                 cl = _clOWL;
1978             else if (Read || !this._cfgCommon.UseUnreadStyle)
1979                 cl = _clReaded;
1980             else
1981                 cl = _clUnread;
1982
1983             if (DList == null || Item.Index == -1)
1984             {
1985                 Item.ForeColor = cl;
1986                 if (this._cfgCommon.UseUnreadStyle)
1987                     Item.Font = fnt;
1988             }
1989             else
1990             {
1991                 DList.Update();
1992                 if (this._cfgCommon.UseUnreadStyle)
1993                     DList.ChangeItemFontAndColor(Item.Index, cl, fnt);
1994                 else
1995                     DList.ChangeItemForeColor(Item.Index, cl);
1996                 //if (_itemCache != null) DList.RedrawItems(_itemCacheIndex, _itemCacheIndex + _itemCache.Length - 1, false);
1997             }
1998         }
1999
2000         private void ColorizeList()
2001         {
2002             //Index:更新対象のListviewItem.Index。Colorを返す。
2003             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2004             PostClass _post;
2005             if (_anchorFlag)
2006                 _post = _anchorPost;
2007             else
2008                 _post = _curPost;
2009
2010             if (_post == null) return;
2011
2012             var listCache = this._listItemCache;
2013             if (listCache == null)
2014                 return;
2015
2016             var index = listCache.StartIndex;
2017             foreach (var cachedPost in listCache.Post)
2018             {
2019                 var backColor = this.JudgeColor(_post, cachedPost);
2020                 this._curList.ChangeItemBackColor(index++, backColor);
2021             }
2022         }
2023
2024         private void ColorizeList(ListViewItem Item, int Index)
2025         {
2026             //Index:更新対象のListviewItem.Index。Colorを返す。
2027             //-1は全キャッシュ。Colorは返さない(ダミーを戻す)
2028             PostClass _post;
2029             if (_anchorFlag)
2030                 _post = _anchorPost;
2031             else
2032                 _post = _curPost;
2033
2034             PostClass tPost = GetCurTabPost(Index);
2035
2036             if (_post == null) return;
2037
2038             if (Item.Index == -1)
2039                 Item.BackColor = JudgeColor(_post, tPost);
2040             else
2041                 _curList.ChangeItemBackColor(Item.Index, JudgeColor(_post, tPost));
2042         }
2043
2044         private Color JudgeColor(PostClass BasePost, PostClass TargetPost)
2045         {
2046             Color cl;
2047             if (TargetPost.StatusId == BasePost.InReplyToStatusId)
2048                 //@先
2049                 cl = _clAtTo;
2050             else if (TargetPost.IsMe)
2051                 //自分=発言者
2052                 cl = _clSelf;
2053             else if (TargetPost.IsReply)
2054                 //自分宛返信
2055                 cl = _clAtSelf;
2056             else if (BasePost.ReplyToList.Contains(TargetPost.ScreenName.ToLower()))
2057                 //返信先
2058                 cl = _clAtFromTarget;
2059             else if (TargetPost.ReplyToList.Contains(BasePost.ScreenName.ToLower()))
2060                 //その人への返信
2061                 cl = _clAtTarget;
2062             else if (TargetPost.ScreenName.Equals(BasePost.ScreenName, StringComparison.OrdinalIgnoreCase))
2063                 //発言者
2064                 cl = _clTarget;
2065             else
2066                 //その他
2067                 cl = _clListBackcolor;
2068
2069             return cl;
2070         }
2071
2072         private async void PostButton_Click(object sender, EventArgs e)
2073         {
2074             if (StatusText.Text.Trim().Length == 0)
2075             {
2076                 if (!ImageSelector.Enabled)
2077                 {
2078                     await this.DoRefresh();
2079                     return;
2080                 }
2081             }
2082
2083             if (this.ExistCurrentPost && StatusText.Text.Trim() == string.Format("RT @{0}: {1}", _curPost.ScreenName, _curPost.TextFromApi))
2084             {
2085                 DialogResult rtResult = MessageBox.Show(string.Format(Properties.Resources.PostButton_Click1, Environment.NewLine),
2086                                                                "Retweet",
2087                                                                MessageBoxButtons.YesNoCancel,
2088                                                                MessageBoxIcon.Question);
2089                 switch (rtResult)
2090                 {
2091                     case DialogResult.Yes:
2092                         StatusText.Text = "";
2093                         await this.doReTweetOfficial(false);
2094                         return;
2095                     case DialogResult.Cancel:
2096                         return;
2097                 }
2098             }
2099
2100             var inReplyToStatusId = this.inReplyTo?.Item1;
2101             var inReplyToScreenName = this.inReplyTo?.Item2;
2102             _history[_history.Count - 1] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
2103
2104             if (this._cfgCommon.Nicoms)
2105             {
2106                 StatusText.SelectionStart = StatusText.Text.Length;
2107                 await UrlConvertAsync(MyCommon.UrlConverter.Nicoms);
2108             }
2109             //if (SettingDialog.UrlConvertAuto)
2110             //{
2111             //    StatusText.SelectionStart = StatusText.Text.Length;
2112             //    UrlConvertAutoToolStripMenuItem_Click(null, null);
2113             //}
2114             //else if (SettingDialog.Nicoms)
2115             //{
2116             //    StatusText.SelectionStart = StatusText.Text.Length;
2117             //    UrlConvert(UrlConverter.Nicoms);
2118             //}
2119             StatusText.SelectionStart = StatusText.Text.Length;
2120             CheckReplyTo(StatusText.Text);
2121
2122             var statusText = this.FormatStatusText(this.StatusText.Text);
2123
2124             if (this.GetRestStatusCount(statusText) < 0)
2125             {
2126                 // 文字数制限を超えているが強制的に投稿するか
2127                 var ret = MessageBox.Show(Properties.Resources.PostLengthOverMessage1, Properties.Resources.PostLengthOverMessage2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
2128                 if (ret != DialogResult.OK)
2129                     return;
2130             }
2131
2132             var status = new PostingStatus();
2133             status.status = statusText;
2134
2135             status.inReplyToId = this.inReplyTo?.Item1;
2136             status.inReplyToName = this.inReplyTo?.Item2;
2137             if (ImageSelector.Visible)
2138             {
2139                 //画像投稿
2140                 if (!ImageSelector.TryGetSelectedMedia(out status.imageService, out status.mediaItems))
2141                     return;
2142             }
2143
2144             this.inReplyTo = null;
2145             StatusText.Text = "";
2146             _history.Add(new PostingStatus());
2147             _hisIdx = _history.Count - 1;
2148             if (!ToolStripFocusLockMenuItem.Checked)
2149                 ((Control)ListTab.SelectedTab.Tag).Focus();
2150             urlUndoBuffer = null;
2151             UrlUndoToolStripMenuItem.Enabled = false;  //Undoをできないように設定
2152
2153             //Google検索(試験実装)
2154             if (StatusText.Text.StartsWith("Google:", StringComparison.OrdinalIgnoreCase) && StatusText.Text.Trim().Length > 7)
2155             {
2156                 string tmp = string.Format(Properties.Resources.SearchItem2Url, Uri.EscapeDataString(StatusText.Text.Substring(7)));
2157                 await this.OpenUriInBrowserAsync(tmp);
2158             }
2159
2160             await this.PostMessageAsync(status);
2161         }
2162
2163         private void EndToolStripMenuItem_Click(object sender, EventArgs e)
2164         {
2165             MyCommon._endingFlag = true;
2166             this.Close();
2167         }
2168
2169         private void TweenMain_FormClosing(object sender, FormClosingEventArgs e)
2170         {
2171             if (!this._cfgCommon.CloseToExit && e.CloseReason == CloseReason.UserClosing && MyCommon._endingFlag == false)
2172             {
2173                 //_endingFlag=false:フォームの×ボタン
2174                 e.Cancel = true;
2175                 this.Visible = false;
2176             }
2177             else
2178             {
2179                 _hookGlobalHotkey.UnregisterAllOriginalHotkey();
2180                 _ignoreConfigSave = true;
2181                 MyCommon._endingFlag = true;
2182                 TimerTimeline.Enabled = false;
2183                 TimerRefreshIcon.Enabled = false;
2184             }
2185         }
2186
2187         private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
2188         {
2189             this.Visible = true;
2190             if (this.WindowState == FormWindowState.Minimized)
2191             {
2192                 this.WindowState = FormWindowState.Normal;
2193             }
2194             this.Activate();
2195             this.BringToFront();
2196         }
2197
2198         private static int errorCount = 0;
2199
2200         private static bool CheckAccountValid()
2201         {
2202             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2203             {
2204                 errorCount += 1;
2205                 if (errorCount > 5)
2206                 {
2207                     errorCount = 0;
2208                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2209                     return true;
2210                 }
2211                 return false;
2212             }
2213             errorCount = 0;
2214             return true;
2215         }
2216
2217         private Task GetHomeTimelineAsync()
2218         {
2219             return this.GetHomeTimelineAsync(loadMore: false);
2220         }
2221
2222         private async Task GetHomeTimelineAsync(bool loadMore)
2223         {
2224             await this.workerSemaphore.WaitAsync();
2225
2226             try
2227             {
2228                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2229
2230                 await this.GetHomeTimelineAsyncInternal(progress, this.workerCts.Token, loadMore);
2231             }
2232             catch (WebApiException ex)
2233             {
2234                 this._myStatusError = true;
2235                 this.StatusLabel.Text = ex.Message;
2236             }
2237             finally
2238             {
2239                 this.workerSemaphore.Release();
2240             }
2241         }
2242
2243         private async Task GetHomeTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2244         {
2245             if (ct.IsCancellationRequested)
2246                 return;
2247
2248             if (!CheckAccountValid())
2249                 throw new WebApiException("Auth error. Check your account");
2250
2251             bool read;
2252             if (!this._cfgCommon.UnreadManage)
2253                 read = true;
2254             else
2255                 read = this._initial && this._cfgCommon.Read;
2256
2257             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText5, loadMore ? -1 : 1));
2258
2259             await Task.Run(() =>
2260             {
2261                 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Timeline, loadMore, this._initial);
2262
2263                 // 新着時未読クリア
2264                 if (this._cfgCommon.ReadOldPosts)
2265                     this._statuses.SetReadHomeTab();
2266
2267                 var addCount = this._statuses.DistributePosts();
2268
2269                 if (!this._initial)
2270                 {
2271                     lock (this._syncObject)
2272                     {
2273                         var tm = DateTime.Now;
2274                         if (this._tlTimestamps.ContainsKey(tm))
2275                             this._tlTimestamps[tm] += addCount;
2276                         else
2277                             this._tlTimestamps[tm] = addCount;
2278
2279                         var removeKeys = new List<DateTime>();
2280                         var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2281
2282                         this._tlCount = 0;
2283                         foreach (var pair in this._tlTimestamps)
2284                         {
2285                             if (pair.Key < oneHour)
2286                                 removeKeys.Add(pair.Key);
2287                             else
2288                                 this._tlCount += pair.Value;
2289                         }
2290
2291                         foreach (var key in removeKeys)
2292                             this._tlTimestamps.Remove(key);
2293                     }
2294                 }
2295             });
2296
2297             if (ct.IsCancellationRequested)
2298                 return;
2299
2300             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText1);
2301
2302             this.RefreshTimeline();
2303         }
2304
2305         private Task GetReplyAsync()
2306         {
2307             return this.GetReplyAsync(loadMore: false);
2308         }
2309
2310         private async Task GetReplyAsync(bool loadMore)
2311         {
2312             await this.workerSemaphore.WaitAsync();
2313
2314             try
2315             {
2316                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2317
2318                 await this.GetReplyAsyncInternal(progress, this.workerCts.Token, loadMore);
2319             }
2320             catch (WebApiException ex)
2321             {
2322                 this._myStatusError = true;
2323                 this.StatusLabel.Text = ex.Message;
2324             }
2325             finally
2326             {
2327                 this.workerSemaphore.Release();
2328             }
2329         }
2330
2331         private async Task GetReplyAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2332         {
2333             if (ct.IsCancellationRequested)
2334                 return;
2335
2336             if (!CheckAccountValid())
2337                 throw new WebApiException("Auth error. Check your account");
2338
2339             bool read;
2340             if (!this._cfgCommon.UnreadManage)
2341                 read = true;
2342             else
2343                 read = this._initial && this._cfgCommon.Read;
2344
2345             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText4, loadMore ? -1 : 1));
2346
2347             await Task.Run(() =>
2348             {
2349                 this.tw.GetTimelineApi(read, MyCommon.WORKERTYPE.Reply, loadMore, this._initial);
2350
2351                 this._statuses.DistributePosts();
2352             });
2353
2354             if (ct.IsCancellationRequested)
2355                 return;
2356
2357             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText9);
2358
2359             this.RefreshTimeline();
2360         }
2361
2362         private Task GetDirectMessagesAsync()
2363         {
2364             return this.GetDirectMessagesAsync(loadMore: false);
2365         }
2366
2367         private async Task GetDirectMessagesAsync(bool loadMore)
2368         {
2369             await this.workerSemaphore.WaitAsync();
2370
2371             try
2372             {
2373                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2374
2375                 await this.GetDirectMessagesAsyncInternal(progress, this.workerCts.Token, loadMore);
2376             }
2377             catch (WebApiException ex)
2378             {
2379                 this._myStatusError = true;
2380                 this.StatusLabel.Text = ex.Message;
2381             }
2382             finally
2383             {
2384                 this.workerSemaphore.Release();
2385             }
2386         }
2387
2388         private async Task GetDirectMessagesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2389         {
2390             if (ct.IsCancellationRequested)
2391                 return;
2392
2393             if (!CheckAccountValid())
2394                 throw new WebApiException("Auth error. Check your account");
2395
2396             bool read;
2397             if (!this._cfgCommon.UnreadManage)
2398                 read = true;
2399             else
2400                 read = this._initial && this._cfgCommon.Read;
2401
2402             p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText8, loadMore ? -1 : 1));
2403
2404             await Task.Run(() =>
2405             {
2406                 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeRcv, loadMore);
2407                 this.tw.GetDirectMessageApi(read, MyCommon.WORKERTYPE.DirectMessegeSnt, loadMore);
2408
2409                 this._statuses.DistributePosts();
2410             });
2411
2412             if (ct.IsCancellationRequested)
2413                 return;
2414
2415             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText11);
2416
2417             this.RefreshTimeline();
2418         }
2419
2420         private Task GetFavoritesAsync()
2421         {
2422             return this.GetFavoritesAsync(loadMore: false);
2423         }
2424
2425         private async Task GetFavoritesAsync(bool loadMore)
2426         {
2427             await this.workerSemaphore.WaitAsync();
2428
2429             try
2430             {
2431                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2432
2433                 await this.GetFavoritesAsyncInternal(progress, this.workerCts.Token, loadMore);
2434             }
2435             catch (WebApiException ex)
2436             {
2437                 this._myStatusError = true;
2438                 this.StatusLabel.Text = ex.Message;
2439             }
2440             finally
2441             {
2442                 this.workerSemaphore.Release();
2443             }
2444         }
2445
2446         private async Task GetFavoritesAsyncInternal(IProgress<string> p, CancellationToken ct, bool loadMore)
2447         {
2448             if (ct.IsCancellationRequested)
2449                 return;
2450
2451             if (!CheckAccountValid())
2452                 throw new WebApiException("Auth error. Check your account");
2453
2454             bool read;
2455             if (!this._cfgCommon.UnreadManage)
2456                 read = true;
2457             else
2458                 read = this._initial && this._cfgCommon.Read;
2459
2460             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText19);
2461
2462             await Task.Run(() =>
2463             {
2464                 this.tw.GetFavoritesApi(read, loadMore);
2465
2466                 this._statuses.DistributePosts();
2467             });
2468
2469             if (ct.IsCancellationRequested)
2470                 return;
2471
2472             p.Report(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText20);
2473
2474             this.RefreshTimeline();
2475         }
2476
2477         private Task GetPublicSearchAllAsync()
2478         {
2479             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch);
2480
2481             return this.GetPublicSearchAsync(tabs, loadMore: false);
2482         }
2483
2484         private Task GetPublicSearchAsync(TabClass tab)
2485         {
2486             return this.GetPublicSearchAsync(tab, loadMore: false);
2487         }
2488
2489         private Task GetPublicSearchAsync(TabClass tab, bool loadMore)
2490         {
2491             return this.GetPublicSearchAsync(new[] { tab }, loadMore);
2492         }
2493
2494         private async Task GetPublicSearchAsync(IEnumerable<TabClass> tabs, bool loadMore)
2495         {
2496             await this.workerSemaphore.WaitAsync();
2497
2498             try
2499             {
2500                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2501
2502                 await this.GetPublicSearchAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2503             }
2504             catch (WebApiException ex)
2505             {
2506                 this._myStatusError = true;
2507                 this.StatusLabel.Text = ex.Message;
2508             }
2509             finally
2510             {
2511                 this.workerSemaphore.Release();
2512             }
2513         }
2514
2515         private async Task GetPublicSearchAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2516         {
2517             if (ct.IsCancellationRequested)
2518                 return;
2519
2520             if (!CheckAccountValid())
2521                 throw new WebApiException("Auth error. Check your account");
2522
2523             bool read;
2524             if (!this._cfgCommon.UnreadManage)
2525                 read = true;
2526             else
2527                 read = this._initial && this._cfgCommon.Read;
2528
2529             p.Report("Search refreshing...");
2530
2531             await Task.Run(() =>
2532             {
2533                 WebApiException lastException = null;
2534
2535                 foreach (var tab in tabs)
2536                 {
2537                     try
2538                     {
2539                         if (string.IsNullOrEmpty(tab.SearchWords))
2540                             continue;
2541
2542                         this.tw.GetSearch(read, tab, false);
2543
2544                         if (loadMore)
2545                             this.tw.GetSearch(read, tab, true);
2546                     }
2547                     catch (WebApiException ex)
2548                     {
2549                         lastException = ex;
2550                     }
2551                 }
2552
2553                 this._statuses.DistributePosts();
2554
2555                 if (lastException != null)
2556                     throw new WebApiException(lastException.Message, lastException);
2557             });
2558
2559             if (ct.IsCancellationRequested)
2560                 return;
2561
2562             p.Report("Search refreshed");
2563
2564             this.RefreshTimeline();
2565         }
2566
2567         private Task GetUserTimelineAllAsync()
2568         {
2569             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline);
2570
2571             return this.GetUserTimelineAsync(tabs, loadMore: false);
2572         }
2573
2574         private Task GetUserTimelineAsync(TabClass tab)
2575         {
2576             return this.GetUserTimelineAsync(tab, loadMore: false);
2577         }
2578
2579         private Task GetUserTimelineAsync(TabClass tab, bool loadMore)
2580         {
2581             return this.GetUserTimelineAsync(new[] { tab }, loadMore);
2582         }
2583
2584         private async Task GetUserTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2585         {
2586             await this.workerSemaphore.WaitAsync();
2587
2588             try
2589             {
2590                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2591
2592                 await this.GetUserTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2593             }
2594             catch (WebApiException ex)
2595             {
2596                 this._myStatusError = true;
2597                 this.StatusLabel.Text = ex.Message;
2598             }
2599             finally
2600             {
2601                 this.workerSemaphore.Release();
2602             }
2603         }
2604
2605         private async Task GetUserTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2606         {
2607             if (ct.IsCancellationRequested)
2608                 return;
2609
2610             if (!CheckAccountValid())
2611                 throw new WebApiException("Auth error. Check your account");
2612
2613             bool read;
2614             if (!this._cfgCommon.UnreadManage)
2615                 read = true;
2616             else
2617                 read = this._initial && this._cfgCommon.Read;
2618
2619             p.Report("UserTimeline refreshing...");
2620
2621             await Task.Run(() =>
2622             {
2623                 WebApiException lastException = null;
2624
2625                 foreach (var tab in tabs)
2626                 {
2627                     try
2628                     {
2629                         if (string.IsNullOrEmpty(tab.User))
2630                             continue;
2631
2632                         this.tw.GetUserTimelineApi(read, tab.User, tab, loadMore);
2633                     }
2634                     catch (WebApiException ex)
2635                     {
2636                         lastException = ex;
2637                     }
2638                 }
2639
2640                 this._statuses.DistributePosts();
2641
2642                 if (lastException != null)
2643                     throw new WebApiException(lastException.Message, lastException);
2644             });
2645
2646             if (ct.IsCancellationRequested)
2647                 return;
2648
2649             p.Report("UserTimeline refreshed");
2650
2651             this.RefreshTimeline();
2652         }
2653
2654         private Task GetListTimelineAllAsync()
2655         {
2656             var tabs = this._statuses.GetTabsByType(MyCommon.TabUsageType.Lists);
2657
2658             return this.GetListTimelineAsync(tabs, loadMore: false);
2659         }
2660
2661         private Task GetListTimelineAsync(TabClass tab)
2662         {
2663             return this.GetListTimelineAsync(tab, loadMore: false);
2664         }
2665
2666         private Task GetListTimelineAsync(TabClass tab, bool loadMore)
2667         {
2668             return this.GetListTimelineAsync(new[] { tab }, loadMore);
2669         }
2670
2671         private async Task GetListTimelineAsync(IEnumerable<TabClass> tabs, bool loadMore)
2672         {
2673             await this.workerSemaphore.WaitAsync();
2674
2675             try
2676             {
2677                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2678
2679                 await this.GetListTimelineAsyncInternal(progress, this.workerCts.Token, tabs, loadMore);
2680             }
2681             catch (WebApiException ex)
2682             {
2683                 this._myStatusError = true;
2684                 this.StatusLabel.Text = ex.Message;
2685             }
2686             finally
2687             {
2688                 this.workerSemaphore.Release();
2689             }
2690         }
2691
2692         private async Task GetListTimelineAsyncInternal(IProgress<string> p, CancellationToken ct, IEnumerable<TabClass> tabs, bool loadMore)
2693         {
2694             if (ct.IsCancellationRequested)
2695                 return;
2696
2697             if (!CheckAccountValid())
2698                 throw new WebApiException("Auth error. Check your account");
2699
2700             bool read;
2701             if (!this._cfgCommon.UnreadManage)
2702                 read = true;
2703             else
2704                 read = this._initial && this._cfgCommon.Read;
2705
2706             p.Report("List refreshing...");
2707
2708             await Task.Run(() =>
2709             {
2710                 WebApiException lastException = null;
2711
2712                 foreach (var tab in tabs)
2713                 {
2714                     try
2715                     {
2716                         if (tab.ListInfo == null || tab.ListInfo.Id == 0)
2717                             continue;
2718
2719                         this.tw.GetListStatus(read, tab, loadMore, this._initial);
2720                     }
2721                     catch (WebApiException ex)
2722                     {
2723                         lastException = ex;
2724                     }
2725                 }
2726
2727                 this._statuses.DistributePosts();
2728
2729                 if (lastException != null)
2730                     throw new WebApiException(lastException.Message, lastException);
2731             });
2732
2733             if (ct.IsCancellationRequested)
2734                 return;
2735
2736             p.Report("List refreshed");
2737
2738             this.RefreshTimeline();
2739         }
2740
2741         private async Task GetRelatedTweetsAsync(TabClass tab)
2742         {
2743             await this.workerSemaphore.WaitAsync();
2744
2745             try
2746             {
2747                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2748
2749                 await this.GetRelatedTweetsAsyncInternal(progress, this.workerCts.Token, tab);
2750             }
2751             catch (WebApiException ex)
2752             {
2753                 this._myStatusError = true;
2754                 this.StatusLabel.Text = ex.Message;
2755             }
2756             finally
2757             {
2758                 this.workerSemaphore.Release();
2759             }
2760         }
2761
2762         private async Task GetRelatedTweetsAsyncInternal(IProgress<string> p, CancellationToken ct, TabClass tab)
2763         {
2764             if (ct.IsCancellationRequested)
2765                 return;
2766
2767             if (!CheckAccountValid())
2768                 throw new WebApiException("Auth error. Check your account");
2769
2770             bool read;
2771             if (!this._cfgCommon.UnreadManage)
2772                 read = true;
2773             else
2774                 read = this._initial && this._cfgCommon.Read;
2775
2776             p.Report("Related refreshing...");
2777
2778             await Task.Run(() =>
2779             {
2780                 this.tw.GetRelatedResult(read, tab);
2781
2782                 this._statuses.DistributePosts();
2783             });
2784
2785             if (ct.IsCancellationRequested)
2786                 return;
2787
2788             p.Report("Related refreshed");
2789
2790             this.RefreshTimeline();
2791
2792             var tabPage = this.ListTab.TabPages.Cast<TabPage>()
2793                 .FirstOrDefault(x => x.Text == tab.TabName);
2794
2795             if (tabPage != null)
2796             {
2797                 // TODO: 非同期更新中にタブが閉じられている場合を厳密に考慮したい
2798
2799                 var listView = (DetailsListView)tabPage.Tag;
2800                 var index = tab.IndexOf(tab.RelationTargetPost.RetweetedId ?? tab.RelationTargetPost.StatusId);
2801
2802                 if (index != -1 && index < listView.Items.Count)
2803                 {
2804                     listView.SelectedIndices.Add(index);
2805                     listView.Items[index].Focused = true;
2806                 }
2807             }
2808         }
2809
2810         private async Task FavAddAsync(IReadOnlyList<long> statusIds, TabClass tab)
2811         {
2812             await this.workerSemaphore.WaitAsync();
2813
2814             try
2815             {
2816                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2817
2818                 await this.FavAddAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2819             }
2820             catch (WebApiException ex)
2821             {
2822                 this._myStatusError = true;
2823                 this.StatusLabel.Text = ex.Message;
2824             }
2825             finally
2826             {
2827                 this.workerSemaphore.Release();
2828             }
2829         }
2830
2831         private async Task FavAddAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2832         {
2833             if (ct.IsCancellationRequested)
2834                 return;
2835
2836             if (!CheckAccountValid())
2837                 throw new WebApiException("Auth error. Check your account");
2838
2839             var successIds = new List<long>();
2840
2841             await Task.Run(() =>
2842             {
2843                 //スレッド処理はしない
2844                 var allCount = 0;
2845                 var failedCount = 0;
2846
2847                 foreach (var statusId in statusIds)
2848                 {
2849                     allCount++;
2850
2851                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText15, allCount, statusIds.Count, failedCount));
2852
2853                     var post = tab.Posts[statusId];
2854
2855                     if (post.IsFav)
2856                         continue;
2857
2858                     try
2859                     {
2860                         this.tw.PostFavAdd(post.RetweetedId ?? post.StatusId);
2861                     }
2862                     catch (WebApiException)
2863                     {
2864                         failedCount++;
2865                         continue;
2866                     }
2867
2868                     successIds.Add(statusId);
2869                     post.IsFav = true; // リスト再描画必要
2870
2871                     this._favTimestamps.Add(DateTime.Now);
2872
2873                     // TLでも取得済みならfav反映
2874                     if (this._statuses.ContainsKey(statusId))
2875                     {
2876                         var postTl = this._statuses[statusId];
2877                         postTl.IsFav = true;
2878
2879                         var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
2880                         favTab.AddPostImmediately(statusId, postTl.IsRead);
2881                     }
2882
2883                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
2884                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
2885                     {
2886                         if (tb.Contains(statusId))
2887                             tb.Posts[statusId].IsFav = true;
2888                     }
2889                 }
2890
2891                 // 時速表示用
2892                 var oneHour = DateTime.Now - TimeSpan.FromHours(1);
2893                 foreach (var i in MyCommon.CountDown(this._favTimestamps.Count - 1, 0))
2894                 {
2895                     if (this._favTimestamps[i] < oneHour)
2896                         this._favTimestamps.RemoveAt(i);
2897                 }
2898
2899                 this._statuses.DistributePosts();
2900             });
2901
2902             if (ct.IsCancellationRequested)
2903                 return;
2904
2905             this.RefreshTimeline();
2906
2907             if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
2908             {
2909                 using (ControlTransaction.Update(this._curList))
2910                 {
2911                     foreach (var statusId in successIds)
2912                     {
2913                         var idx = tab.IndexOf(statusId);
2914                         if (idx == -1)
2915                             continue;
2916
2917                         var post = tab.Posts[statusId];
2918                         this.ChangeCacheStyleRead(post.IsRead, idx);
2919                     }
2920                 }
2921
2922                 if (successIds.Contains(this._curPost.StatusId))
2923                     await this.DispSelectedPost(true); // 選択アイテム再表示
2924             }
2925         }
2926
2927         private async Task FavRemoveAsync(IReadOnlyList<long> statusIds, TabClass tab)
2928         {
2929             await this.workerSemaphore.WaitAsync();
2930
2931             try
2932             {
2933                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
2934
2935                 await this.FavRemoveAsyncInternal(progress, this.workerCts.Token, statusIds, tab);
2936             }
2937             catch (WebApiException ex)
2938             {
2939                 this._myStatusError = true;
2940                 this.StatusLabel.Text = ex.Message;
2941             }
2942             finally
2943             {
2944                 this.workerSemaphore.Release();
2945             }
2946         }
2947
2948         private async Task FavRemoveAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds, TabClass tab)
2949         {
2950             if (ct.IsCancellationRequested)
2951                 return;
2952
2953             if (!CheckAccountValid())
2954                 throw new WebApiException("Auth error. Check your account");
2955
2956             var successIds = new List<long>();
2957
2958             await Task.Run(() =>
2959             {
2960                 //スレッド処理はしない
2961                 var allCount = 0;
2962                 var failedCount = 0;
2963                 foreach (var statusId in statusIds)
2964                 {
2965                     allCount++;
2966
2967                     var post = tab.Posts[statusId];
2968
2969                     p.Report(string.Format(Properties.Resources.GetTimelineWorker_RunWorkerCompletedText17, allCount, statusIds.Count, failedCount));
2970
2971                     if (!post.IsFav)
2972                         continue;
2973
2974                     try
2975                     {
2976                         this.tw.PostFavRemove(post.RetweetedId ?? post.StatusId);
2977                     }
2978                     catch (WebApiException)
2979                     {
2980                         failedCount++;
2981                         continue;
2982                     }
2983
2984                     successIds.Add(statusId);
2985                     post.IsFav = false; // リスト再描画必要
2986
2987                     if (this._statuses.ContainsKey(statusId))
2988                     {
2989                         this._statuses[statusId].IsFav = false;
2990                     }
2991
2992                     // 検索,リスト,UserTimeline,Relatedの各タブに反映
2993                     foreach (var tb in this._statuses.GetTabsInnerStorageType())
2994                     {
2995                         if (tb.Contains(statusId))
2996                             tb.Posts[statusId].IsFav = false;
2997                     }
2998                 }
2999             });
3000
3001             if (ct.IsCancellationRequested)
3002                 return;
3003
3004             this.RemovePostFromFavTab(successIds.ToArray());
3005
3006             this.RefreshTimeline();
3007
3008             if (this._curList != null && this._curTab != null && this._curTab.Text == tab.TabName)
3009             {
3010                 if (tab.TabType == MyCommon.TabUsageType.Favorites)
3011                 {
3012                     // 色変えは不要
3013                 }
3014                 else
3015                 {
3016                     using (ControlTransaction.Update(this._curList))
3017                     {
3018                         foreach (var statusId in successIds)
3019                         {
3020                             var idx = tab.IndexOf(statusId);
3021                             if (idx == -1)
3022                                 continue;
3023
3024                             var post = tab.Posts[statusId];
3025                             this.ChangeCacheStyleRead(post.IsRead, idx);
3026                         }
3027                     }
3028
3029                     if (successIds.Contains(this._curPost.StatusId))
3030                         await this.DispSelectedPost(true); // 選択アイテム再表示
3031                 }
3032             }
3033         }
3034
3035         private async Task PostMessageAsync(PostingStatus status)
3036         {
3037             await this.workerSemaphore.WaitAsync();
3038
3039             try
3040             {
3041                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3042
3043                 await this.PostMessageAsyncInternal(progress, this.workerCts.Token, status);
3044             }
3045             catch (WebApiException ex)
3046             {
3047                 this._myStatusError = true;
3048                 this.StatusLabel.Text = ex.Message;
3049             }
3050             finally
3051             {
3052                 this.workerSemaphore.Release();
3053             }
3054         }
3055
3056         private async Task PostMessageAsyncInternal(IProgress<string> p, CancellationToken ct, PostingStatus status)
3057         {
3058             if (ct.IsCancellationRequested)
3059                 return;
3060
3061             if (!CheckAccountValid())
3062                 throw new WebApiException("Auth error. Check your account");
3063
3064             p.Report("Posting...");
3065
3066             var errMsg = "";
3067
3068             try
3069             {
3070                 await Task.Run(async () =>
3071                 {
3072                     if (status.mediaItems == null || status.mediaItems.Length == 0)
3073                     {
3074                         this.tw.PostStatus(status.status, status.inReplyToId);
3075                     }
3076                     else
3077                     {
3078                         var service = ImageSelector.GetService(status.imageService);
3079                         await service.PostStatusAsync(status.status, status.inReplyToId, status.mediaItems)
3080                             .ConfigureAwait(false);
3081                     }
3082                 });
3083
3084                 p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3085             }
3086             catch (WebApiException ex)
3087             {
3088                 // 処理は中断せずエラーの表示のみ行う
3089                 errMsg = ex.Message;
3090                 p.Report(errMsg);
3091                 this._myStatusError = true;
3092             }
3093             finally
3094             {
3095                 // 使い終わった MediaItem は破棄する
3096                 if (status.mediaItems != null)
3097                 {
3098                     foreach (var disposableItem in status.mediaItems.OfType<IDisposable>())
3099                     {
3100                         disposableItem.Dispose();
3101                     }
3102                 }
3103             }
3104
3105             if (ct.IsCancellationRequested)
3106                 return;
3107
3108             if (!string.IsNullOrEmpty(errMsg) &&
3109                 !errMsg.StartsWith("OK:", StringComparison.Ordinal) &&
3110                 !errMsg.StartsWith("Warn:", StringComparison.Ordinal))
3111             {
3112                 var ret = MessageBox.Show(
3113                     string.Format(
3114                         "{0}   --->   [ " + errMsg + " ]" + Environment.NewLine +
3115                         "\"" + status.status + "\"" + Environment.NewLine +
3116                         "{1}",
3117                         Properties.Resources.StatusUpdateFailed1,
3118                         Properties.Resources.StatusUpdateFailed2),
3119                     "Failed to update status",
3120                     MessageBoxButtons.RetryCancel,
3121                     MessageBoxIcon.Question);
3122
3123                 if (ret == DialogResult.Retry)
3124                 {
3125                     await this.PostMessageAsync(status);
3126                 }
3127                 else
3128                 {
3129                     // 連投モードのときだけEnterイベントが起きないので強制的に背景色を戻す
3130                     if (this.ToolStripFocusLockMenuItem.Checked)
3131                         this.StatusText_Enter(this.StatusText, EventArgs.Empty);
3132                 }
3133                 return;
3134             }
3135
3136             this._postTimestamps.Add(DateTime.Now);
3137
3138             var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3139             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3140             {
3141                 if (this._postTimestamps[i] < oneHour)
3142                     this._postTimestamps.RemoveAt(i);
3143             }
3144
3145             if (!this.HashMgr.IsPermanent && !string.IsNullOrEmpty(this.HashMgr.UseHash))
3146             {
3147                 this.HashMgr.ClearHashtag();
3148                 this.HashStripSplitButton.Text = "#[-]";
3149                 this.HashToggleMenuItem.Checked = false;
3150                 this.HashToggleToolStripMenuItem.Checked = false;
3151             }
3152
3153             this.SetMainWindowTitle();
3154
3155             if (this._cfgCommon.PostAndGet)
3156             {
3157                 if (this._isActiveUserstream)
3158                     this.RefreshTimeline();
3159                 else
3160                     await this.GetHomeTimelineAsync();
3161             }
3162         }
3163
3164         private async Task RetweetAsync(IReadOnlyList<long> statusIds)
3165         {
3166             await this.workerSemaphore.WaitAsync();
3167
3168             try
3169             {
3170                 var progress = new Progress<string>(x => this.StatusLabel.Text = x);
3171
3172                 await this.RetweetAsyncInternal(progress, this.workerCts.Token, statusIds);
3173             }
3174             catch (WebApiException ex)
3175             {
3176                 this._myStatusError = true;
3177                 this.StatusLabel.Text = ex.Message;
3178             }
3179             finally
3180             {
3181                 this.workerSemaphore.Release();
3182             }
3183         }
3184
3185         private async Task RetweetAsyncInternal(IProgress<string> p, CancellationToken ct, IReadOnlyList<long> statusIds)
3186         {
3187             if (ct.IsCancellationRequested)
3188                 return;
3189
3190             if (!CheckAccountValid())
3191                 throw new WebApiException("Auth error. Check your account");
3192
3193             bool read;
3194             if (!this._cfgCommon.UnreadManage)
3195                 read = true;
3196             else
3197                 read = this._initial && this._cfgCommon.Read;
3198
3199             p.Report("Posting...");
3200
3201             await Task.Run(() =>
3202             {
3203                 foreach (var statusId in statusIds)
3204                 {
3205                     this.tw.PostRetweet(statusId, read);
3206                 }
3207             });
3208
3209             if (ct.IsCancellationRequested)
3210                 return;
3211
3212             p.Report(Properties.Resources.PostWorker_RunWorkerCompletedText4);
3213
3214             this._postTimestamps.Add(DateTime.Now);
3215
3216             var oneHour = DateTime.Now - TimeSpan.FromHours(1);
3217             foreach (var i in MyCommon.CountDown(this._postTimestamps.Count - 1, 0))
3218             {
3219                 if (this._postTimestamps[i] < oneHour)
3220                     this._postTimestamps.RemoveAt(i);
3221             }
3222
3223             if (this._cfgCommon.PostAndGet && !this._isActiveUserstream)
3224                 await this.GetHomeTimelineAsync();
3225         }
3226
3227         private async Task RefreshFollowerIdsAsync()
3228         {
3229             await this.workerSemaphore.WaitAsync();
3230             try
3231             {
3232                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText1;
3233
3234                 await Task.Run(() => tw.RefreshFollowerIds());
3235
3236                 this.StatusLabel.Text = Properties.Resources.UpdateFollowersMenuItem1_ClickText3;
3237
3238                 this.RefreshTimeline();
3239                 this.PurgeListViewItemCache();
3240                 this._curList?.Refresh();
3241             }
3242             catch (WebApiException ex)
3243             {
3244                 this.StatusLabel.Text = ex.Message;
3245             }
3246             finally
3247             {
3248                 this.workerSemaphore.Release();
3249             }
3250         }
3251
3252         private async Task RefreshNoRetweetIdsAsync()
3253         {
3254             await this.workerSemaphore.WaitAsync();
3255             try
3256             {
3257                 await Task.Run(() => tw.RefreshNoRetweetIds());
3258
3259                 this.StatusLabel.Text = "NoRetweetIds refreshed";
3260             }
3261             catch (WebApiException ex)
3262             {
3263                 this.StatusLabel.Text = ex.Message;
3264             }
3265             finally
3266             {
3267                 this.workerSemaphore.Release();
3268             }
3269         }
3270
3271         private async Task RefreshBlockIdsAsync()
3272         {
3273             await this.workerSemaphore.WaitAsync();
3274             try
3275             {
3276                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText1;
3277
3278                 await Task.Run(() => tw.RefreshBlockIds());
3279
3280                 this.StatusLabel.Text = Properties.Resources.UpdateBlockUserText3;
3281             }
3282             catch (WebApiException ex)
3283             {
3284                 this.StatusLabel.Text = ex.Message;
3285             }
3286             finally
3287             {
3288                 this.workerSemaphore.Release();
3289             }
3290         }
3291
3292         private async Task RefreshTwitterConfigurationAsync()
3293         {
3294             await this.workerSemaphore.WaitAsync();
3295             try
3296             {
3297                 await Task.Run(() => tw.RefreshConfiguration());
3298
3299                 if (this.tw.Configuration.PhotoSizeLimit != 0)
3300                 {
3301                     foreach (var service in this.ImageSelector.GetServices())
3302                     {
3303                         service.UpdateTwitterConfiguration(this.tw.Configuration);
3304                     }
3305                 }
3306
3307                 this.PurgeListViewItemCache();
3308
3309                 this._curList?.Refresh();
3310             }
3311             catch (WebApiException ex)
3312             {
3313                 this.StatusLabel.Text = ex.Message;
3314             }
3315             finally
3316             {
3317                 this.workerSemaphore.Release();
3318             }
3319         }
3320
3321         private async Task RefreshMuteUserIdsAsync()
3322         {
3323             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Start;
3324
3325             try
3326             {
3327                 await tw.RefreshMuteUserIdsAsync();
3328             }
3329             catch (WebApiException ex)
3330             {
3331                 this.StatusLabel.Text = string.Format(Properties.Resources.UpdateMuteUserIds_Error, ex.Message);
3332                 return;
3333             }
3334
3335             this.StatusLabel.Text = Properties.Resources.UpdateMuteUserIds_Finish;
3336         }
3337
3338         private void RemovePostFromFavTab(Int64[] ids)
3339         {
3340             var favTab = this._statuses.GetTabByType(MyCommon.TabUsageType.Favorites);
3341             string favTabName = favTab.TabName;
3342             int fidx = 0;
3343             if (_curTab.Text.Equals(favTabName))
3344             {
3345                 fidx = _curList.FocusedItem?.Index ?? _curList.TopItem?.Index ?? 0;
3346             }
3347
3348             foreach (long i in ids)
3349             {
3350                 try
3351                 {
3352                     _statuses.RemoveFavPost(i);
3353                 }
3354                 catch (Exception)
3355                 {
3356                     continue;
3357                 }
3358             }
3359             if (_curTab != null && _curTab.Text.Equals(favTabName))
3360             {
3361                 this.PurgeListViewItemCache();
3362                 _curPost = null;
3363                 //_curItemIndex = -1;
3364             }
3365             foreach (TabPage tp in ListTab.TabPages)
3366             {
3367                 if (tp.Text == favTabName)
3368                 {
3369                     ((DetailsListView)tp.Tag).VirtualListSize = favTab.AllCount;
3370                     break;
3371                 }
3372             }
3373             if (_curTab.Text.Equals(favTabName))
3374             {
3375                 do
3376                 {
3377                     _curList.SelectedIndices.Clear();
3378                 }
3379                 while (_curList.SelectedIndices.Count > 0);
3380
3381                 if (favTab.AllCount > 0)
3382                 {
3383                     if (favTab.AllCount - 1 > fidx && fidx > -1)
3384                     {
3385                         _curList.SelectedIndices.Add(fidx);
3386                     }
3387                     else
3388                     {
3389                         _curList.SelectedIndices.Add(favTab.AllCount - 1);
3390                     }
3391                     if (_curList.SelectedIndices.Count > 0)
3392                     {
3393                         _curList.EnsureVisible(_curList.SelectedIndices[0]);
3394                         _curList.FocusedItem = _curList.Items[_curList.SelectedIndices[0]];
3395                     }
3396                 }
3397             }
3398         }
3399
3400         private void NotifyIcon1_MouseClick(object sender, MouseEventArgs e)
3401         {
3402             if (e.Button == MouseButtons.Left)
3403             {
3404                 this.Visible = true;
3405                 if (this.WindowState == FormWindowState.Minimized)
3406                 {
3407                     this.WindowState = _formWindowState;
3408                 }
3409                 this.Activate();
3410                 this.BringToFront();
3411             }
3412         }
3413
3414         private async void MyList_MouseDoubleClick(object sender, MouseEventArgs e)
3415         {
3416             switch (this._cfgCommon.ListDoubleClickAction)
3417             {
3418                 case 0:
3419                     MakeReplyOrDirectStatus();
3420                     break;
3421                 case 1:
3422                     await this.FavoriteChange(true);
3423                     break;
3424                 case 2:
3425                     if (_curPost != null)
3426                         await this.ShowUserStatus(_curPost.ScreenName, false);
3427                     break;
3428                 case 3:
3429                     ShowUserTimeline();
3430                     break;
3431                 case 4:
3432                     ShowRelatedStatusesMenuItem_Click(null, null);
3433                     break;
3434                 case 5:
3435                     MoveToHomeToolStripMenuItem_Click(null, null);
3436                     break;
3437                 case 6:
3438                     StatusOpenMenuItem_Click(null, null);
3439                     break;
3440                 case 7:
3441                     //動作なし
3442                     break;
3443             }
3444         }
3445
3446         private async void FavAddToolStripMenuItem_Click(object sender, EventArgs e)
3447         {
3448             await this.FavoriteChange(true);
3449         }
3450
3451         private async void FavRemoveToolStripMenuItem_Click(object sender, EventArgs e)
3452         {
3453             await this.FavoriteChange(false);
3454         }
3455
3456
3457         private async void FavoriteRetweetMenuItem_Click(object sender, EventArgs e)
3458         {
3459             await this.FavoritesRetweetOfficial();
3460         }
3461
3462         private async void FavoriteRetweetUnofficialMenuItem_Click(object sender, EventArgs e)
3463         {
3464             await this.FavoritesRetweetUnofficial();
3465         }
3466
3467         private async Task FavoriteChange(bool FavAdd , bool multiFavoriteChangeDialogEnable = true)
3468         {
3469             TabClass tab;
3470             if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
3471                 return;
3472
3473             //trueでFavAdd,falseでFavRemove
3474             if (tab.TabType == MyCommon.TabUsageType.DirectMessage || _curList.SelectedIndices.Count == 0
3475                 || !this.ExistCurrentPost) return;
3476
3477             // 誤ふぁぼ・故意によるふぁぼ爆対策 (変更しないこと)
3478             // https://support.twitter.com/articles/76915#favoriting
3479             const int MultiSelectFavLimit = 1;
3480
3481             //複数fav確認msg
3482             if (_curList.SelectedIndices.Count > MultiSelectFavLimit && FavAdd)
3483             {
3484                 MessageBox.Show(string.Format(Properties.Resources.FavoriteLimitCountText, MultiSelectFavLimit));
3485                 _DoFavRetweetFlags = false;
3486                 return;
3487             }
3488             else if (multiFavoriteChangeDialogEnable && _curList.SelectedIndices.Count > 1)
3489             {
3490                 if (FavAdd)
3491                 {
3492                     string QuestionText = Properties.Resources.FavAddToolStripMenuItem_ClickText1;
3493                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText3;
3494                     if (MessageBox.Show(QuestionText, Properties.Resources.FavAddToolStripMenuItem_ClickText2,
3495                                        MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3496                     {
3497                         _DoFavRetweetFlags = false;
3498                         return;
3499                     }
3500                 }
3501                 else
3502                 {
3503                     if (MessageBox.Show(Properties.Resources.FavRemoveToolStripMenuItem_ClickText1, Properties.Resources.FavRemoveToolStripMenuItem_ClickText2,
3504                                     MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
3505                     {
3506                         return;
3507                     }
3508                 }
3509             }
3510
3511             var statusIds = new List<long>();
3512             foreach (int idx in _curList.SelectedIndices)
3513             {
3514                 PostClass post = GetCurTabPost(idx);
3515                 if (FavAdd)
3516                 {
3517                     if (!post.IsFav)
3518                         statusIds.Add(post.StatusId);
3519                 }
3520                 else
3521                 {
3522                     if (post.IsFav)
3523                         statusIds.Add(post.StatusId);
3524                 }
3525             }
3526             if (statusIds.Count == 0)
3527             {
3528                 if (FavAdd)
3529                     StatusLabel.Text = Properties.Resources.FavAddToolStripMenuItem_ClickText4;
3530                 else
3531                     StatusLabel.Text = Properties.Resources.FavRemoveToolStripMenuItem_ClickText4;
3532
3533                 return;
3534             }
3535
3536             if (FavAdd)
3537                 await this.FavAddAsync(statusIds, tab);
3538             else
3539                 await this.FavRemoveAsync(statusIds, tab);
3540         }
3541
3542         private PostClass GetCurTabPost(int Index)
3543         {
3544             var listCache = this._listItemCache;
3545             if (listCache != null)
3546             {
3547                 ListViewItem item;
3548                 PostClass post;
3549                 if (listCache.TryGetValue(Index, out item, out post))
3550                     return post;
3551             }
3552
3553             return _statuses.Tabs[_curTab.Text][Index];
3554         }
3555
3556         private async void MoveToHomeToolStripMenuItem_Click(object sender, EventArgs e)
3557         {
3558             if (_curList.SelectedIndices.Count > 0)
3559                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName);
3560             else if (_curList.SelectedIndices.Count == 0)
3561                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl);
3562         }
3563
3564         private async void MoveToFavToolStripMenuItem_Click(object sender, EventArgs e)
3565         {
3566             if (_curList.SelectedIndices.Count > 0)
3567                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + "#!/" + GetCurTabPost(_curList.SelectedIndices[0]).ScreenName + "/favorites");
3568         }
3569
3570         private void TweenMain_ClientSizeChanged(object sender, EventArgs e)
3571         {
3572             if ((!_initialLayout) && this.Visible)
3573             {
3574                 if (this.WindowState == FormWindowState.Normal)
3575                 {
3576                     _mySize = this.ClientSize;
3577                     _mySpDis = this.SplitContainer1.SplitterDistance;
3578                     _mySpDis3 = this.SplitContainer3.SplitterDistance;
3579                     if (StatusText.Multiline) _mySpDis2 = this.StatusText.Height;
3580                     _modifySettingLocal = true;
3581                 }
3582             }
3583         }
3584
3585         private void MyList_ColumnClick(object sender, ColumnClickEventArgs e)
3586         {
3587             var comparerMode = this.GetComparerModeByColumnIndex(e.Column);
3588             if (comparerMode == null)
3589                 return;
3590
3591             this.SetSortColumn(comparerMode.Value);
3592         }
3593
3594         /// <summary>
3595         /// 列インデックスからソートを行う ComparerMode を求める
3596         /// </summary>
3597         /// <param name="columnIndex">ソートを行うカラムのインデックス (表示上の順序とは異なる)</param>
3598         /// <returns>ソートを行う ComparerMode。null であればソートを行わない</returns>
3599         private ComparerMode? GetComparerModeByColumnIndex(int columnIndex)
3600         {
3601             if (this._iconCol)
3602                 return ComparerMode.Id;
3603
3604             switch (columnIndex)
3605             {
3606                 case 1: // ニックネーム
3607                     return ComparerMode.Nickname;
3608                 case 2: // 本文
3609                     return ComparerMode.Data;
3610                 case 3: // 時刻=発言Id
3611                     return ComparerMode.Id;
3612                 case 4: // 名前
3613                     return ComparerMode.Name;
3614                 case 7: // Source
3615                     return ComparerMode.Source;
3616                 default:
3617                     // 0:アイコン, 5:未読マーク, 6:プロテクト・フィルターマーク
3618                     return null;
3619             }
3620         }
3621
3622         /// <summary>
3623         /// 発言一覧の指定した位置の列でソートする
3624         /// </summary>
3625         /// <param name="columnIndex">ソートする列の位置 (表示上の順序で指定)</param>
3626         private void SetSortColumnByDisplayIndex(int columnIndex)
3627         {
3628             // 表示上の列の位置から ColumnHeader を求める
3629             var col = this._curList.Columns.Cast<ColumnHeader>()
3630                 .Where(x => x.DisplayIndex == columnIndex)
3631                 .FirstOrDefault();
3632
3633             if (col == null)
3634                 return;
3635
3636             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3637             if (comparerMode == null)
3638                 return;
3639
3640             this.SetSortColumn(comparerMode.Value);
3641         }
3642
3643         /// <summary>
3644         /// 発言一覧の最後列の項目でソートする
3645         /// </summary>
3646         private void SetSortLastColumn()
3647         {
3648             // 表示上の最後列にある ColumnHeader を求める
3649             var col = this._curList.Columns.Cast<ColumnHeader>()
3650                 .OrderByDescending(x => x.DisplayIndex)
3651                 .First();
3652
3653             var comparerMode = this.GetComparerModeByColumnIndex(col.Index);
3654             if (comparerMode == null)
3655                 return;
3656
3657             this.SetSortColumn(comparerMode.Value);
3658         }
3659
3660         /// <summary>
3661         /// 発言一覧を指定された ComparerMode に基づいてソートする
3662         /// </summary>
3663         private void SetSortColumn(ComparerMode sortColumn)
3664         {
3665             if (this._cfgCommon.SortOrderLock)
3666                 return;
3667
3668             this._statuses.ToggleSortOrder(sortColumn);
3669             this.InitColumnText();
3670
3671             var list = this._curList;
3672             if (_iconCol)
3673             {
3674                 list.Columns[0].Text = this.ColumnText[0];
3675                 list.Columns[1].Text = this.ColumnText[2];
3676             }
3677             else
3678             {
3679                 for (var i = 0; i <= 7; i++)
3680                 {
3681                     list.Columns[i].Text = this.ColumnText[i];
3682                 }
3683             }
3684
3685             this.PurgeListViewItemCache();
3686
3687             var tab = this._statuses.Tabs[this._curTab.Text];
3688             if (tab.AllCount > 0 && this._curPost != null)
3689             {
3690                 var idx = tab.IndexOf(this._curPost.StatusId);
3691                 if (idx > -1)
3692                 {
3693                     this.SelectListItem(list, idx);
3694                     list.EnsureVisible(idx);
3695                 }
3696             }
3697             list.Refresh();
3698
3699             this._modifySettingCommon = true;
3700         }
3701
3702         private void TweenMain_LocationChanged(object sender, EventArgs e)
3703         {
3704             if (this.WindowState == FormWindowState.Normal && !_initialLayout)
3705             {
3706                 _myLoc = this.DesktopLocation;
3707                 _modifySettingLocal = true;
3708             }
3709         }
3710
3711         private void ContextMenuOperate_Opening(object sender, CancelEventArgs e)
3712         {
3713             if (ListTab.SelectedTab == null) return;
3714             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
3715             if (!this.ExistCurrentPost)
3716             {
3717                 ReplyStripMenuItem.Enabled = false;
3718                 ReplyAllStripMenuItem.Enabled = false;
3719                 DMStripMenuItem.Enabled = false;
3720                 ShowProfileMenuItem.Enabled = false;
3721                 ShowUserTimelineContextMenuItem.Enabled = false;
3722                 ListManageUserContextToolStripMenuItem2.Enabled = false;
3723                 MoveToFavToolStripMenuItem.Enabled = false;
3724                 TabMenuItem.Enabled = false;
3725                 IDRuleMenuItem.Enabled = false;
3726                 SourceRuleMenuItem.Enabled = false;
3727                 ReadedStripMenuItem.Enabled = false;
3728                 UnreadStripMenuItem.Enabled = false;
3729             }
3730             else
3731             {
3732                 ShowProfileMenuItem.Enabled = true;
3733                 ListManageUserContextToolStripMenuItem2.Enabled = true;
3734                 ReplyStripMenuItem.Enabled = true;
3735                 ReplyAllStripMenuItem.Enabled = true;
3736                 DMStripMenuItem.Enabled = true;
3737                 ShowUserTimelineContextMenuItem.Enabled = true;
3738                 MoveToFavToolStripMenuItem.Enabled = true;
3739                 TabMenuItem.Enabled = true;
3740                 IDRuleMenuItem.Enabled = true;
3741                 SourceRuleMenuItem.Enabled = true;
3742                 ReadedStripMenuItem.Enabled = true;
3743                 UnreadStripMenuItem.Enabled = true;
3744             }
3745             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
3746             {
3747                 FavAddToolStripMenuItem.Enabled = false;
3748                 FavRemoveToolStripMenuItem.Enabled = false;
3749                 StatusOpenMenuItem.Enabled = false;
3750                 FavorareMenuItem.Enabled = false;
3751                 ShowRelatedStatusesMenuItem.Enabled = false;
3752
3753                 ReTweetStripMenuItem.Enabled = false;
3754                 ReTweetUnofficialStripMenuItem.Enabled = false;
3755                 QuoteStripMenuItem.Enabled = false;
3756                 FavoriteRetweetContextMenu.Enabled = false;
3757                 FavoriteRetweetUnofficialContextMenu.Enabled = false;
3758             }
3759             else
3760             {
3761                 FavAddToolStripMenuItem.Enabled = true;
3762                 FavRemoveToolStripMenuItem.Enabled = true;
3763                 StatusOpenMenuItem.Enabled = true;
3764                 FavorareMenuItem.Enabled = true;
3765                 ShowRelatedStatusesMenuItem.Enabled = true;  //PublicSearchの時問題出るかも
3766
3767                 if (_curPost.IsMe)
3768                 {
3769                     ReTweetStripMenuItem.Enabled = false;  //公式RTは無効に
3770                     ReTweetUnofficialStripMenuItem.Enabled = true;
3771                     QuoteStripMenuItem.Enabled = true;
3772                     FavoriteRetweetContextMenu.Enabled = false;  //公式RTは無効に
3773                     FavoriteRetweetUnofficialContextMenu.Enabled = true;
3774                 }
3775                 else
3776                 {
3777                     if (_curPost.IsProtect)
3778                     {
3779                         ReTweetStripMenuItem.Enabled = false;
3780                         ReTweetUnofficialStripMenuItem.Enabled = false;
3781                         QuoteStripMenuItem.Enabled = false;
3782                         FavoriteRetweetContextMenu.Enabled = false;
3783                         FavoriteRetweetUnofficialContextMenu.Enabled = false;
3784                     }
3785                     else
3786                     {
3787                         ReTweetStripMenuItem.Enabled = true;
3788                         ReTweetUnofficialStripMenuItem.Enabled = true;
3789                         QuoteStripMenuItem.Enabled = true;
3790                         FavoriteRetweetContextMenu.Enabled = true;
3791                         FavoriteRetweetUnofficialContextMenu.Enabled = true;
3792                     }
3793                 }
3794             }
3795             //if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
3796             //{
3797             //    RefreshMoreStripMenuItem.Enabled = true;
3798             //}
3799             //else
3800             //{
3801             //    RefreshMoreStripMenuItem.Enabled = false;
3802             //}
3803             if (!this.ExistCurrentPost
3804                 || _curPost.InReplyToStatusId == null)
3805             {
3806                 RepliedStatusOpenMenuItem.Enabled = false;
3807             }
3808             else
3809             {
3810                 RepliedStatusOpenMenuItem.Enabled = true;
3811             }
3812             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
3813             {
3814                 MoveToRTHomeMenuItem.Enabled = false;
3815             }
3816             else
3817             {
3818                 MoveToRTHomeMenuItem.Enabled = true;
3819             }
3820
3821             if (this.ExistCurrentPost)
3822             {
3823                 this.DeleteStripMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
3824                 if (this._curPost.RetweetedByUserId == this.tw.UserId)
3825                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText2;
3826                 else
3827                     this.DeleteStripMenuItem.Text = Properties.Resources.DeleteMenuText1;
3828             }
3829         }
3830
3831         private void ReplyStripMenuItem_Click(object sender, EventArgs e)
3832         {
3833             MakeReplyOrDirectStatus(false, true);
3834         }
3835
3836         private void DMStripMenuItem_Click(object sender, EventArgs e)
3837         {
3838             MakeReplyOrDirectStatus(false, false);
3839         }
3840
3841         private void doStatusDelete()
3842         {
3843             if (this._curTab == null || this._curList == null)
3844                 return;
3845
3846             if (this._curList.SelectedIndices.Count == 0)
3847                 return;
3848
3849             var posts = this._curList.SelectedIndices.Cast<int>()
3850                 .Select(x => this.GetCurTabPost(x))
3851                 .ToArray();
3852
3853             // 選択されたツイートの中に削除可能なものが一つでもあるか
3854             if (!posts.Any(x => x.CanDeleteBy(this.tw.UserId)))
3855                 return;
3856
3857             var ret = MessageBox.Show(this,
3858                 string.Format(Properties.Resources.DeleteStripMenuItem_ClickText1, Environment.NewLine),
3859                 Properties.Resources.DeleteStripMenuItem_ClickText2,
3860                 MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
3861
3862             if (ret != DialogResult.OK)
3863                 return;
3864
3865             var focusedIndex = this._curList.FocusedItem?.Index ?? this._curList.TopItem?.Index ?? 0;
3866
3867             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
3868             {
3869                 Exception lastException = null;
3870                 foreach (var post in posts)
3871                 {
3872                     if (!post.CanDeleteBy(this.tw.UserId))
3873                         continue;
3874
3875                     try
3876                     {
3877                         if (post.IsDm)
3878                         {
3879                             this.tw.RemoveDirectMessage(post.StatusId, post);
3880                         }
3881                         else
3882                         {
3883                             if (post.RetweetedId != null && post.UserId == this.tw.UserId)
3884                                 // 他人に RT された自分のツイート
3885                                 this.tw.RemoveStatus(post.RetweetedId.Value);
3886                             else
3887                                 // 自分のツイート or 自分が RT したツイート
3888                                 this.tw.RemoveStatus(post.StatusId);
3889                         }
3890                     }
3891                     catch (WebApiException ex)
3892                     {
3893                         lastException = ex;
3894                         continue;
3895                     }
3896
3897                     this._statuses.RemovePost(post.StatusId);
3898                 }
3899
3900                 if (lastException == null)
3901                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText4; // 成功
3902                 else
3903                     this.StatusLabel.Text = Properties.Resources.DeleteStripMenuItem_ClickText3; // 失敗
3904
3905                 this.PurgeListViewItemCache();
3906                 this._curPost = null;
3907                 this._curItemIndex = -1;
3908
3909                 foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
3910                 {
3911                     var listView = (DetailsListView)tabPage.Tag;
3912                     var tab = this._statuses.Tabs[tabPage.Text];
3913
3914                     using (ControlTransaction.Update(listView))
3915                     {
3916                         listView.VirtualListSize = tab.AllCount;
3917
3918                         if (tabPage == this._curTab)
3919                         {
3920                             listView.SelectedIndices.Clear();
3921
3922                             if (tab.AllCount != 0)
3923                             {
3924                                 int selectedIndex;
3925                                 if (tab.AllCount - 1 > focusedIndex && focusedIndex > -1)
3926                                     selectedIndex = focusedIndex;
3927                                 else
3928                                     selectedIndex = tab.AllCount - 1;
3929
3930                                 listView.SelectedIndices.Add(selectedIndex);
3931                                 listView.EnsureVisible(selectedIndex);
3932                                 listView.FocusedItem = listView.Items[selectedIndex];
3933                             }
3934                         }
3935                     }
3936
3937                     if (this._cfgCommon.TabIconDisp && tab.UnreadCount == 0)
3938                     {
3939                         if (tabPage.ImageIndex == 0)
3940                             tabPage.ImageIndex = -1; // タブアイコン
3941                     }
3942                 }
3943
3944                 if (!this._cfgCommon.TabIconDisp)
3945                     this.ListTab.Refresh();
3946             }
3947         }
3948
3949         private void DeleteStripMenuItem_Click(object sender, EventArgs e)
3950         {
3951             doStatusDelete();
3952         }
3953
3954         private void ReadedStripMenuItem_Click(object sender, EventArgs e)
3955         {
3956             using (ControlTransaction.Update(this._curList))
3957             {
3958                 foreach (int idx in _curList.SelectedIndices)
3959                 {
3960                     var post = this._statuses.Tabs[this._curTab.Text][idx];
3961                     this._statuses.SetReadAllTab(post.StatusId, read: true);
3962                     ChangeCacheStyleRead(true, idx);
3963                 }
3964                 ColorizeList();
3965             }
3966             foreach (TabPage tb in ListTab.TabPages)
3967             {
3968                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
3969                 {
3970                     if (this._cfgCommon.TabIconDisp)
3971                     {
3972                         if (tb.ImageIndex == 0) tb.ImageIndex = -1; //タブアイコン
3973                     }
3974                 }
3975             }
3976             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
3977         }
3978
3979         private void UnreadStripMenuItem_Click(object sender, EventArgs e)
3980         {
3981             using (ControlTransaction.Update(this._curList))
3982             {
3983                 foreach (int idx in _curList.SelectedIndices)
3984                 {
3985                     var post = this._statuses.Tabs[this._curTab.Text][idx];
3986                     this._statuses.SetReadAllTab(post.StatusId, read: false);
3987                     ChangeCacheStyleRead(false, idx);
3988                 }
3989                 ColorizeList();
3990             }
3991             foreach (TabPage tb in ListTab.TabPages)
3992             {
3993                 if (_statuses.Tabs[tb.Text].UnreadCount > 0)
3994                 {
3995                     if (this._cfgCommon.TabIconDisp)
3996                     {
3997                         if (tb.ImageIndex == -1) tb.ImageIndex = 0; //タブアイコン
3998                     }
3999                 }
4000             }
4001             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
4002         }
4003
4004         private async void RefreshStripMenuItem_Click(object sender, EventArgs e)
4005         {
4006             await this.DoRefresh();
4007         }
4008
4009         private async Task DoRefresh()
4010         {
4011             if (_curTab != null)
4012             {
4013                 TabClass tab;
4014                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4015                     return;
4016
4017                 switch (_statuses.Tabs[_curTab.Text].TabType)
4018                 {
4019                     case MyCommon.TabUsageType.Mentions:
4020                         await this.GetReplyAsync();
4021                         break;
4022                     case MyCommon.TabUsageType.DirectMessage:
4023                         await this.GetDirectMessagesAsync();
4024                         break;
4025                     case MyCommon.TabUsageType.Favorites:
4026                         await this.GetFavoritesAsync();
4027                         break;
4028                     //case MyCommon.TabUsageType.Profile:
4029                         //// TODO
4030                     case MyCommon.TabUsageType.PublicSearch:
4031                         //// TODO
4032                         if (string.IsNullOrEmpty(tab.SearchWords)) return;
4033                         await this.GetPublicSearchAsync(tab);
4034                         break;
4035                     case MyCommon.TabUsageType.UserTimeline:
4036                         await this.GetUserTimelineAsync(tab);
4037                         break;
4038                     case MyCommon.TabUsageType.Lists:
4039                         //// TODO
4040                         if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4041                         await this.GetListTimelineAsync(tab);
4042                         break;
4043                     default:
4044                         await this.GetHomeTimelineAsync();
4045                         break;
4046                 }
4047             }
4048             else
4049             {
4050                 await this.GetHomeTimelineAsync();
4051             }
4052         }
4053
4054         private async Task DoRefreshMore()
4055         {
4056             //ページ指定をマイナス1に
4057             if (_curTab != null)
4058             {
4059                 TabClass tab;
4060                 if (!this._statuses.Tabs.TryGetValue(this._curTab.Text, out tab))
4061                     return;
4062
4063                 switch (_statuses.Tabs[_curTab.Text].TabType)
4064                 {
4065                     case MyCommon.TabUsageType.Mentions:
4066                         await this.GetReplyAsync(loadMore: true);
4067                         break;
4068                     case MyCommon.TabUsageType.DirectMessage:
4069                         await this.GetDirectMessagesAsync(loadMore: true);
4070                         break;
4071                     case MyCommon.TabUsageType.Favorites:
4072                         await this.GetFavoritesAsync(loadMore: true);
4073                         break;
4074                     case MyCommon.TabUsageType.Profile:
4075                         //// TODO
4076                         break;
4077                     case MyCommon.TabUsageType.PublicSearch:
4078                         // TODO
4079                         if (string.IsNullOrEmpty(tab.SearchWords)) return;
4080                         await this.GetPublicSearchAsync(tab, loadMore: true);
4081                         break;
4082                     case MyCommon.TabUsageType.UserTimeline:
4083                         await this.GetUserTimelineAsync(tab, loadMore: true);
4084                         break;
4085                     case MyCommon.TabUsageType.Lists:
4086                         //// TODO
4087                         if (tab.ListInfo == null || tab.ListInfo.Id == 0) return;
4088                         await this.GetListTimelineAsync(tab, loadMore: true);
4089                         break;
4090                     default:
4091                         await this.GetHomeTimelineAsync(loadMore: true);
4092                         break;
4093                 }
4094             }
4095             else
4096             {
4097                 await this.GetHomeTimelineAsync(loadMore: true);
4098             }
4099         }
4100
4101         private DialogResult ShowSettingDialog(bool showTaskbarIcon = false)
4102         {
4103             DialogResult result = DialogResult.Abort;
4104
4105             using (var settingDialog = new AppendSettingDialog())
4106             {
4107                 settingDialog.Icon = this.MainIcon;
4108                 settingDialog.Owner = this;
4109                 settingDialog.ShowInTaskbar = showTaskbarIcon;
4110                 settingDialog.IntervalChanged += this.TimerInterval_Changed;
4111
4112                 settingDialog.tw = this.tw;
4113                 settingDialog.LoadConfig(this._cfgCommon, this._cfgLocal);
4114
4115                 try
4116                 {
4117                     result = settingDialog.ShowDialog(this);
4118                 }
4119                 catch (Exception)
4120                 {
4121                     return DialogResult.Abort;
4122                 }
4123
4124                 if (result == DialogResult.OK)
4125                 {
4126                     lock (_syncObject)
4127                     {
4128                         settingDialog.SaveConfig(this._cfgCommon, this._cfgLocal);
4129                     }
4130                 }
4131             }
4132
4133             return result;
4134         }
4135
4136         private async void SettingStripMenuItem_Click(object sender, EventArgs e)
4137         {
4138             // 設定画面表示前のユーザー情報
4139             var oldUser = new { tw.AccessToken, tw.AccessTokenSecret, tw.Username, tw.UserId };
4140
4141             var oldIconSz = this._cfgCommon.IconSize;
4142
4143             if (ShowSettingDialog() == DialogResult.OK)
4144             {
4145                 lock (_syncObject)
4146                 {
4147                     tw.RestrictFavCheck = this._cfgCommon.RestrictFavCheck;
4148                     tw.ReadOwnPost = this._cfgCommon.ReadOwnPost;
4149                     ShortUrl.Instance.DisableExpanding = !this._cfgCommon.TinyUrlResolve;
4150                     ShortUrl.Instance.BitlyId = this._cfgCommon.BilyUser;
4151                     ShortUrl.Instance.BitlyKey = this._cfgCommon.BitlyPwd;
4152                     HttpTwitter.TwitterUrl = _cfgCommon.TwitterUrl;
4153
4154                     Networking.DefaultTimeout = TimeSpan.FromSeconds(this._cfgCommon.DefaultTimeOut);
4155                     Networking.SetWebProxy(this._cfgLocal.ProxyType,
4156                         this._cfgLocal.ProxyAddress, this._cfgLocal.ProxyPort,
4157                         this._cfgLocal.ProxyUser, this._cfgLocal.ProxyPassword);
4158                     Networking.ForceIPv4 = this._cfgCommon.ForceIPv4;
4159
4160                     ImageSelector.Reset(tw, this.tw.Configuration);
4161
4162                     try
4163                     {
4164                         if (this._cfgCommon.TabIconDisp)
4165                         {
4166                             ListTab.DrawItem -= ListTab_DrawItem;
4167                             ListTab.DrawMode = TabDrawMode.Normal;
4168                             ListTab.ImageList = this.TabImage;
4169                         }
4170                         else
4171                         {
4172                             ListTab.DrawItem -= ListTab_DrawItem;
4173                             ListTab.DrawItem += ListTab_DrawItem;
4174                             ListTab.DrawMode = TabDrawMode.OwnerDrawFixed;
4175                             ListTab.ImageList = null;
4176                         }
4177                     }
4178                     catch (Exception ex)
4179                     {
4180                         ex.Data["Instance"] = "ListTab(TabIconDisp)";
4181                         ex.Data["IsTerminatePermission"] = false;
4182                         throw;
4183                     }
4184
4185                     try
4186                     {
4187                         if (!this._cfgCommon.UnreadManage)
4188                         {
4189                             ReadedStripMenuItem.Enabled = false;
4190                             UnreadStripMenuItem.Enabled = false;
4191                             if (this._cfgCommon.TabIconDisp)
4192                             {
4193                                 foreach (TabPage myTab in ListTab.TabPages)
4194                                 {
4195                                     myTab.ImageIndex = -1;
4196                                 }
4197                             }
4198                         }
4199                         else
4200                         {
4201                             ReadedStripMenuItem.Enabled = true;
4202                             UnreadStripMenuItem.Enabled = true;
4203                         }
4204                     }
4205                     catch (Exception ex)
4206                     {
4207                         ex.Data["Instance"] = "ListTab(UnreadManage)";
4208                         ex.Data["IsTerminatePermission"] = false;
4209                         throw;
4210                     }
4211
4212                     // タブの表示位置の決定
4213                     SetTabAlignment();
4214
4215                     SplitContainer1.IsPanelInverted = !this._cfgCommon.StatusAreaAtBottom;
4216
4217                     var imgazyobizinet = ThumbnailGenerator.ImgAzyobuziNetInstance;
4218                     imgazyobizinet.Enabled = this._cfgCommon.EnableImgAzyobuziNet;
4219                     imgazyobizinet.DisabledInDM = this._cfgCommon.ImgAzyobuziNetDisabledInDM;
4220
4221                     this.PlaySoundMenuItem.Checked = this._cfgCommon.PlaySound;
4222                     this.PlaySoundFileMenuItem.Checked = this._cfgCommon.PlaySound;
4223                     _fntUnread = this._cfgLocal.FontUnread;
4224                     _clUnread = this._cfgLocal.ColorUnread;
4225                     _fntReaded = this._cfgLocal.FontRead;
4226                     _clReaded = this._cfgLocal.ColorRead;
4227                     _clFav = this._cfgLocal.ColorFav;
4228                     _clOWL = this._cfgLocal.ColorOWL;
4229                     _clRetweet = this._cfgLocal.ColorRetweet;
4230                     _fntDetail = this._cfgLocal.FontDetail;
4231                     _clDetail = this._cfgLocal.ColorDetail;
4232                     _clDetailLink = this._cfgLocal.ColorDetailLink;
4233                     _clDetailBackcolor = this._cfgLocal.ColorDetailBackcolor;
4234                     _clSelf = this._cfgLocal.ColorSelf;
4235                     _clAtSelf = this._cfgLocal.ColorAtSelf;
4236                     _clTarget = this._cfgLocal.ColorTarget;
4237                     _clAtTarget = this._cfgLocal.ColorAtTarget;
4238                     _clAtFromTarget = this._cfgLocal.ColorAtFromTarget;
4239                     _clAtTo = this._cfgLocal.ColorAtTo;
4240                     _clListBackcolor = this._cfgLocal.ColorListBackcolor;
4241                     _clInputBackcolor = this._cfgLocal.ColorInputBackcolor;
4242                     _clInputFont = this._cfgLocal.ColorInputFont;
4243                     _fntInputFont = this._cfgLocal.FontInputFont;
4244                     _brsBackColorMine.Dispose();
4245                     _brsBackColorAt.Dispose();
4246                     _brsBackColorYou.Dispose();
4247                     _brsBackColorAtYou.Dispose();
4248                     _brsBackColorAtFromTarget.Dispose();
4249                     _brsBackColorAtTo.Dispose();
4250                     _brsBackColorNone.Dispose();
4251                     _brsBackColorMine = new SolidBrush(_clSelf);
4252                     _brsBackColorAt = new SolidBrush(_clAtSelf);
4253                     _brsBackColorYou = new SolidBrush(_clTarget);
4254                     _brsBackColorAtYou = new SolidBrush(_clAtTarget);
4255                     _brsBackColorAtFromTarget = new SolidBrush(_clAtFromTarget);
4256                     _brsBackColorAtTo = new SolidBrush(_clAtTo);
4257                     _brsBackColorNone = new SolidBrush(_clListBackcolor);
4258
4259                     try
4260                     {
4261                         if (StatusText.Focused) StatusText.BackColor = _clInputBackcolor;
4262                         StatusText.Font = _fntInputFont;
4263                         StatusText.ForeColor = _clInputFont;
4264                     }
4265                     catch (Exception ex)
4266                     {
4267                         MessageBox.Show(ex.Message);
4268                     }
4269
4270                     try
4271                     {
4272                         InitDetailHtmlFormat();
4273                     }
4274                     catch (Exception ex)
4275                     {
4276                         ex.Data["Instance"] = "Font";
4277                         ex.Data["IsTerminatePermission"] = false;
4278                         throw;
4279                     }
4280
4281                     try
4282                     {
4283                         foreach (TabPage tb in ListTab.TabPages)
4284                         {
4285                             if (this._cfgCommon.TabIconDisp)
4286                             {
4287                                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
4288                                     tb.ImageIndex = -1;
4289                                 else
4290                                     tb.ImageIndex = 0;
4291                             }
4292                         }
4293                     }
4294                     catch (Exception ex)
4295                     {
4296                         ex.Data["Instance"] = "ListTab(TabIconDisp no2)";
4297                         ex.Data["IsTerminatePermission"] = false;
4298                         throw;
4299                     }
4300
4301                     try
4302                     {
4303                         var oldIconCol = _iconCol;
4304
4305                         if (this._cfgCommon.IconSize != oldIconSz)
4306                             ApplyListViewIconSize(this._cfgCommon.IconSize);
4307
4308                         foreach (TabPage tp in ListTab.TabPages)
4309                         {
4310                             DetailsListView lst = (DetailsListView)tp.Tag;
4311
4312                             using (ControlTransaction.Update(lst))
4313                             {
4314                                 lst.GridLines = this._cfgCommon.ShowGrid;
4315                                 lst.Font = _fntReaded;
4316                                 lst.BackColor = _clListBackcolor;
4317
4318                                 if (_iconCol != oldIconCol)
4319                                     ResetColumns(lst);
4320                             }
4321                         }
4322                     }
4323                     catch (Exception ex)
4324                     {
4325                         ex.Data["Instance"] = "ListView(IconSize)";
4326                         ex.Data["IsTerminatePermission"] = false;
4327                         throw;
4328                     }
4329
4330                     SetMainWindowTitle();
4331                     SetNotifyIconText();
4332
4333                     this.PurgeListViewItemCache();
4334                     _curList?.Refresh();
4335                     ListTab.Refresh();
4336
4337                     _hookGlobalHotkey.UnregisterAllOriginalHotkey();
4338                     if (this._cfgCommon.HotkeyEnabled)
4339                     {
4340                         ///グローバルホットキーの登録。設定で変更可能にするかも
4341                         HookGlobalHotkey.ModKeys modKey = HookGlobalHotkey.ModKeys.None;
4342                         if ((this._cfgCommon.HotkeyModifier & Keys.Alt) == Keys.Alt)
4343                             modKey |= HookGlobalHotkey.ModKeys.Alt;
4344                         if ((this._cfgCommon.HotkeyModifier & Keys.Control) == Keys.Control)
4345                             modKey |= HookGlobalHotkey.ModKeys.Ctrl;
4346                         if ((this._cfgCommon.HotkeyModifier & Keys.Shift) == Keys.Shift)
4347                             modKey |=  HookGlobalHotkey.ModKeys.Shift;
4348                         if ((this._cfgCommon.HotkeyModifier & Keys.LWin) == Keys.LWin)
4349                             modKey |= HookGlobalHotkey.ModKeys.Win;
4350
4351                         _hookGlobalHotkey.RegisterOriginalHotkey(this._cfgCommon.HotkeyKey, this._cfgCommon.HotkeyValue, modKey);
4352                     }
4353
4354                     if (this._cfgCommon.IsUseNotifyGrowl) gh.RegisterGrowl();
4355                     try
4356                     {
4357                         StatusText_TextChanged(null, null);
4358                     }
4359                     catch (Exception)
4360                     {
4361                     }
4362                 }
4363             }
4364             else
4365             {
4366                 // キャンセル時は Twitter クラスの認証情報を画面表示前の状態に戻す
4367                 this.tw.Initialize(oldUser.AccessToken, oldUser.AccessTokenSecret, oldUser.Username, oldUser.UserId);
4368             }
4369
4370             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
4371
4372             this.TopMost = this._cfgCommon.AlwaysTop;
4373             SaveConfigsAll(false);
4374
4375             if (tw.Username != oldUser.Username)
4376                 await this.doGetFollowersMenu();
4377         }
4378
4379         /// <summary>
4380         /// タブの表示位置を設定する
4381         /// </summary>
4382         private void SetTabAlignment()
4383         {
4384             var newAlignment = this._cfgCommon.ViewTabBottom ? TabAlignment.Bottom : TabAlignment.Top;
4385             if (ListTab.Alignment == newAlignment) return;
4386
4387             // 各タブのリスト上の選択位置などを退避
4388             var listSelections = this.SaveListViewSelection();
4389
4390             ListTab.Alignment = newAlignment;
4391
4392             foreach (TabPage tab in ListTab.TabPages)
4393             {
4394                 DetailsListView lst = (DetailsListView)tab.Tag;
4395                 TabClass tabInfo = _statuses.Tabs[tab.Text];
4396                 using (ControlTransaction.Update(lst))
4397                 {
4398                     // 選択位置などを復元
4399                     this.RestoreListViewSelection(lst, tabInfo, listSelections[tabInfo.TabName]);
4400                 }
4401             }
4402         }
4403
4404         private void ApplyListViewIconSize(MyCommon.IconSizes iconSz)
4405         {
4406             // アイコンサイズの再設定
4407             _iconCol = false;
4408             switch (iconSz)
4409             {
4410                 case MyCommon.IconSizes.IconNone:
4411                     _iconSz = 0;
4412                     break;
4413                 case MyCommon.IconSizes.Icon16:
4414                     _iconSz = 16;
4415                     break;
4416                 case MyCommon.IconSizes.Icon24:
4417                     _iconSz = 26;
4418                     break;
4419                 case MyCommon.IconSizes.Icon48:
4420                     _iconSz = 48;
4421                     break;
4422                 case MyCommon.IconSizes.Icon48_2:
4423                     _iconSz = 48;
4424                     _iconCol = true;
4425                     break;
4426             }
4427
4428             if (_iconSz > 0)
4429             {
4430                 // ディスプレイの DPI 設定を考慮したサイズを設定する
4431                 _listViewImageList.ImageSize = new Size(
4432                     1,
4433                     (int)Math.Ceiling(this._iconSz * this.CurrentScaleFactor.Height));
4434             }
4435             else
4436             {
4437                 _listViewImageList.ImageSize = new Size(1, 1);
4438             }
4439         }
4440
4441         private void ResetColumns(DetailsListView list)
4442         {
4443             using (ControlTransaction.Update(list))
4444             using (ControlTransaction.Layout(list, false))
4445             {
4446                 // カラムヘッダの再設定
4447                 list.ColumnClick -= MyList_ColumnClick;
4448                 list.DrawColumnHeader -= MyList_DrawColumnHeader;
4449                 list.ColumnReordered -= MyList_ColumnReordered;
4450                 list.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4451
4452                 var cols = list.Columns.Cast<ColumnHeader>().ToList();
4453                 list.Columns.Clear();
4454                 cols.ForEach(col => col.Dispose());
4455                 cols.Clear();
4456
4457                 InitColumns(list, true);
4458
4459                 list.ColumnClick += MyList_ColumnClick;
4460                 list.DrawColumnHeader += MyList_DrawColumnHeader;
4461                 list.ColumnReordered += MyList_ColumnReordered;
4462                 list.ColumnWidthChanged += MyList_ColumnWidthChanged;
4463             }
4464         }
4465
4466         private async void PostBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
4467         {
4468             if (e.Url.AbsoluteUri != "about:blank")
4469             {
4470                 await this.DispSelectedPost();
4471                 await this.OpenUriInBrowserAsync(e.Url.OriginalString);
4472             }
4473         }
4474
4475         private async void PostBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
4476         {
4477             if (e.Url.Scheme == "data")
4478             {
4479                 StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
4480             }
4481             else if (e.Url.AbsoluteUri != "about:blank")
4482             {
4483                 e.Cancel = true;
4484                 // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
4485                 await this.OpenUriAsync( e.Url, MyCommon.IsKeyDown( Keys.Control ) );
4486             }
4487         }
4488
4489         public void AddNewTabForSearch(string searchWord)
4490         {
4491             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4492             foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.PublicSearch))
4493             {
4494                 if (tb.SearchWords == searchWord && string.IsNullOrEmpty(tb.SearchLang))
4495                 {
4496                     foreach (TabPage tp in ListTab.TabPages)
4497                     {
4498                         if (tb.TabName == tp.Text)
4499                         {
4500                             ListTab.SelectedTab = tp;
4501                             return;
4502                         }
4503                     }
4504                 }
4505             }
4506             //ユニークなタブ名生成
4507             string tabName = searchWord;
4508             for (int i = 0; i <= 100; i++)
4509             {
4510                 if (_statuses.ContainsTab(tabName))
4511                     tabName += "_";
4512                 else
4513                     break;
4514             }
4515             //タブ追加
4516             _statuses.AddTab(tabName, MyCommon.TabUsageType.PublicSearch, null);
4517             AddNewTab(tabName, false, MyCommon.TabUsageType.PublicSearch);
4518             //追加したタブをアクティブに
4519             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4520             //検索条件の設定
4521             ComboBox cmb = (ComboBox)ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"];
4522             cmb.Items.Add(searchWord);
4523             cmb.Text = searchWord;
4524             SaveConfigsTabs();
4525             //検索実行
4526             this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
4527         }
4528
4529         private void ShowUserTimeline()
4530         {
4531             if (!this.ExistCurrentPost) return;
4532             AddNewTabForUserTimeline(_curPost.ScreenName);
4533         }
4534
4535         private void SearchComboBox_KeyDown(object sender, KeyEventArgs e)
4536         {
4537             if (e.KeyCode == Keys.Escape)
4538             {
4539                 TabPage relTp = ListTab.SelectedTab;
4540                 RemoveSpecifiedTab(relTp.Text, false);
4541                 SaveConfigsTabs();
4542                 e.SuppressKeyPress = true;
4543             }
4544         }
4545
4546         public void AddNewTabForUserTimeline(string user)
4547         {
4548             //同一検索条件のタブが既に存在すれば、そのタブアクティブにして終了
4549             foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.UserTimeline))
4550             {
4551                 if (tb.User == user)
4552                 {
4553                     foreach (TabPage tp in ListTab.TabPages)
4554                     {
4555                         if (tb.TabName == tp.Text)
4556                         {
4557                             ListTab.SelectedTab = tp;
4558                             return;
4559                         }
4560                     }
4561                 }
4562             }
4563             //ユニークなタブ名生成
4564             string tabName = "user:" + user;
4565             while (_statuses.ContainsTab(tabName))
4566             {
4567                 tabName += "_";
4568             }
4569             //タブ追加
4570             _statuses.AddTab(tabName, MyCommon.TabUsageType.UserTimeline, null);
4571             var tab = this._statuses.Tabs[tabName];
4572             tab.User = user;
4573             AddNewTab(tabName, false, MyCommon.TabUsageType.UserTimeline);
4574             //追加したタブをアクティブに
4575             ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
4576             SaveConfigsTabs();
4577             //検索実行
4578             this.GetUserTimelineAsync(tab);
4579         }
4580
4581         public bool AddNewTab(string tabName, bool startup, MyCommon.TabUsageType tabType, ListElement listInfo = null)
4582         {
4583             //重複チェック
4584             foreach (TabPage tb in ListTab.TabPages)
4585             {
4586                 if (tb.Text == tabName) return false;
4587             }
4588
4589             //新規タブ名チェック
4590             if (tabName == Properties.Resources.AddNewTabText1) return false;
4591
4592             //タブタイプ重複チェック
4593             if (!startup)
4594             {
4595                 if (tabType == MyCommon.TabUsageType.DirectMessage ||
4596                    tabType == MyCommon.TabUsageType.Favorites ||
4597                    tabType == MyCommon.TabUsageType.Home ||
4598                    tabType == MyCommon.TabUsageType.Mentions ||
4599                    tabType == MyCommon.TabUsageType.Related)
4600                 {
4601                     if (_statuses.GetTabByType(tabType) != null) return false;
4602                 }
4603             }
4604
4605             var _tabPage = new TabPage();
4606             var _listCustom = new DetailsListView();
4607
4608             int cnt = ListTab.TabPages.Count;
4609
4610             ///ToDo:Create and set controls follow tabtypes
4611
4612             using (ControlTransaction.Update(_listCustom))
4613             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4614             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4615             using (ControlTransaction.Layout(this.SplitContainer1, false))
4616             using (ControlTransaction.Layout(this.ListTab, false))
4617             using (ControlTransaction.Layout(this))
4618             using (ControlTransaction.Layout(_tabPage, false))
4619             {
4620                 _tabPage.Controls.Add(_listCustom);
4621
4622                 /// UserTimeline関連
4623                 if (tabType == MyCommon.TabUsageType.UserTimeline || tabType == MyCommon.TabUsageType.Lists)
4624                 {
4625                     var label = new Label();
4626                     label.Dock = DockStyle.Top;
4627                     label.Name = "labelUser";
4628                     if (tabType == MyCommon.TabUsageType.Lists)
4629                     {
4630                         label.Text = listInfo.ToString();
4631                     }
4632                     else
4633                     {
4634                         label.Text = _statuses.Tabs[tabName].User + "'s Timeline";
4635                     }
4636                     label.TextAlign = ContentAlignment.MiddleLeft;
4637                     using (ComboBox tmpComboBox = new ComboBox())
4638                     {
4639                         label.Height = tmpComboBox.Height;
4640                     }
4641                     _tabPage.Controls.Add(label);
4642                 }
4643                 /// 検索関連の準備
4644                 else if (tabType == MyCommon.TabUsageType.PublicSearch)
4645                 {
4646                     var pnl = new Panel();
4647
4648                     var lbl = new Label();
4649                     var cmb = new ComboBox();
4650                     var btn = new Button();
4651                     var cmbLang = new ComboBox();
4652
4653                     using (ControlTransaction.Layout(pnl, false))
4654                     {
4655                         pnl.Controls.Add(cmb);
4656                         pnl.Controls.Add(cmbLang);
4657                         pnl.Controls.Add(btn);
4658                         pnl.Controls.Add(lbl);
4659                         pnl.Name = "panelSearch";
4660                         pnl.Dock = DockStyle.Top;
4661                         pnl.Height = cmb.Height;
4662                         pnl.Enter += SearchControls_Enter;
4663                         pnl.Leave += SearchControls_Leave;
4664
4665                         cmb.Text = "";
4666                         cmb.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4667                         cmb.Dock = DockStyle.Fill;
4668                         cmb.Name = "comboSearch";
4669                         cmb.DropDownStyle = ComboBoxStyle.DropDown;
4670                         cmb.ImeMode = ImeMode.NoControl;
4671                         cmb.TabStop = false;
4672                         cmb.AutoCompleteMode = AutoCompleteMode.None;
4673                         cmb.KeyDown += SearchComboBox_KeyDown;
4674
4675                         cmbLang.Text = "";
4676                         cmbLang.Anchor = AnchorStyles.Left | AnchorStyles.Right;
4677                         cmbLang.Dock = DockStyle.Right;
4678                         cmbLang.Width = 50;
4679                         cmbLang.Name = "comboLang";
4680                         cmbLang.DropDownStyle = ComboBoxStyle.DropDownList;
4681                         cmbLang.TabStop = false;
4682                         cmbLang.Items.Add("");
4683                         cmbLang.Items.Add("ja");
4684                         cmbLang.Items.Add("en");
4685                         cmbLang.Items.Add("ar");
4686                         cmbLang.Items.Add("da");
4687                         cmbLang.Items.Add("nl");
4688                         cmbLang.Items.Add("fa");
4689                         cmbLang.Items.Add("fi");
4690                         cmbLang.Items.Add("fr");
4691                         cmbLang.Items.Add("de");
4692                         cmbLang.Items.Add("hu");
4693                         cmbLang.Items.Add("is");
4694                         cmbLang.Items.Add("it");
4695                         cmbLang.Items.Add("no");
4696                         cmbLang.Items.Add("pl");
4697                         cmbLang.Items.Add("pt");
4698                         cmbLang.Items.Add("ru");
4699                         cmbLang.Items.Add("es");
4700                         cmbLang.Items.Add("sv");
4701                         cmbLang.Items.Add("th");
4702
4703                         lbl.Text = "Search(C-S-f)";
4704                         lbl.Name = "label1";
4705                         lbl.Dock = DockStyle.Left;
4706                         lbl.Width = 90;
4707                         lbl.Height = cmb.Height;
4708                         lbl.TextAlign = ContentAlignment.MiddleLeft;
4709
4710                         btn.Text = "Search";
4711                         btn.Name = "buttonSearch";
4712                         btn.UseVisualStyleBackColor = true;
4713                         btn.Dock = DockStyle.Right;
4714                         btn.TabStop = false;
4715                         btn.Click += SearchButton_Click;
4716
4717                         TabClass tab;
4718                         if (_statuses.Tabs.TryGetValue(tabName, out tab))
4719                         {
4720                             if (!string.IsNullOrEmpty(tab.SearchWords))
4721                             {
4722                                 cmb.Items.Add(tab.SearchWords);
4723                                 cmb.Text = tab.SearchWords;
4724                             }
4725
4726                             cmbLang.Text = tab.SearchLang;
4727                         }
4728
4729                         _tabPage.Controls.Add(pnl);
4730                     }
4731                 }
4732
4733                 _tabPage.Tag = _listCustom;
4734                 this.ListTab.Controls.Add(_tabPage);
4735
4736                 _tabPage.Location = new Point(4, 4);
4737                 _tabPage.Name = "CTab" + cnt.ToString();
4738                 _tabPage.Size = new Size(380, 260);
4739                 _tabPage.TabIndex = 2 + cnt;
4740                 _tabPage.Text = tabName;
4741                 _tabPage.UseVisualStyleBackColor = true;
4742                 _tabPage.AccessibleRole = AccessibleRole.PageTab;
4743
4744                 _listCustom.AllowColumnReorder = true;
4745                 _listCustom.ContextMenuStrip = this.ContextMenuOperate;
4746                 _listCustom.ColumnHeaderContextMenuStrip = this.ContextMenuColumnHeader;
4747                 _listCustom.Dock = DockStyle.Fill;
4748                 _listCustom.FullRowSelect = true;
4749                 _listCustom.HideSelection = false;
4750                 _listCustom.Location = new Point(0, 0);
4751                 _listCustom.Margin = new Padding(0);
4752                 _listCustom.Name = "CList" + Environment.TickCount.ToString();
4753                 _listCustom.ShowItemToolTips = true;
4754                 _listCustom.Size = new Size(380, 260);
4755                 _listCustom.UseCompatibleStateImageBehavior = false;
4756                 _listCustom.View = View.Details;
4757                 _listCustom.OwnerDraw = true;
4758                 _listCustom.VirtualMode = true;
4759                 _listCustom.Font = _fntReaded;
4760                 _listCustom.BackColor = _clListBackcolor;
4761
4762                 _listCustom.GridLines = this._cfgCommon.ShowGrid;
4763                 _listCustom.AllowDrop = true;
4764
4765                 _listCustom.SmallImageList = _listViewImageList;
4766
4767                 InitColumns(_listCustom, startup);
4768
4769                 _listCustom.SelectedIndexChanged += MyList_SelectedIndexChanged;
4770                 _listCustom.MouseDoubleClick += MyList_MouseDoubleClick;
4771                 _listCustom.ColumnClick += MyList_ColumnClick;
4772                 _listCustom.DrawColumnHeader += MyList_DrawColumnHeader;
4773                 _listCustom.DragDrop += TweenMain_DragDrop;
4774                 _listCustom.DragEnter += TweenMain_DragEnter;
4775                 _listCustom.DragOver += TweenMain_DragOver;
4776                 _listCustom.DrawItem += MyList_DrawItem;
4777                 _listCustom.MouseClick += MyList_MouseClick;
4778                 _listCustom.ColumnReordered += MyList_ColumnReordered;
4779                 _listCustom.ColumnWidthChanged += MyList_ColumnWidthChanged;
4780                 _listCustom.CacheVirtualItems += MyList_CacheVirtualItems;
4781                 _listCustom.RetrieveVirtualItem += MyList_RetrieveVirtualItem;
4782                 _listCustom.DrawSubItem += MyList_DrawSubItem;
4783                 _listCustom.HScrolled += MyList_HScrolled;
4784             }
4785
4786             return true;
4787         }
4788
4789         public bool RemoveSpecifiedTab(string TabName, bool confirm)
4790         {
4791             var tabInfo = _statuses.GetTabByName(TabName);
4792             if (tabInfo.IsDefaultTabType || tabInfo.Protected) return false;
4793
4794             if (confirm)
4795             {
4796                 string tmp = string.Format(Properties.Resources.RemoveSpecifiedTabText1, Environment.NewLine);
4797                 if (MessageBox.Show(tmp, TabName + " " + Properties.Resources.RemoveSpecifiedTabText2,
4798                                  MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
4799                 {
4800                     return false;
4801                 }
4802             }
4803
4804             var _tabPage = ListTab.TabPages.Cast<TabPage>().FirstOrDefault(tp => tp.Text == TabName);
4805             if (_tabPage == null) return false;
4806
4807             SetListProperty();   //他のタブに列幅等を反映
4808
4809             //オブジェクトインスタンスの削除
4810             DetailsListView _listCustom = (DetailsListView)_tabPage.Tag;
4811             _tabPage.Tag = null;
4812
4813             using (ControlTransaction.Layout(this.SplitContainer1.Panel1, false))
4814             using (ControlTransaction.Layout(this.SplitContainer1.Panel2, false))
4815             using (ControlTransaction.Layout(this.SplitContainer1, false))
4816             using (ControlTransaction.Layout(this.ListTab, false))
4817             using (ControlTransaction.Layout(this))
4818             using (ControlTransaction.Layout(_tabPage, false))
4819             {
4820                 if (this.ListTab.SelectedTab == _tabPage)
4821                 {
4822                     this.ListTab.SelectTab((this._beforeSelectedTab != null && this.ListTab.TabPages.Contains(this._beforeSelectedTab)) ? this._beforeSelectedTab : this.ListTab.TabPages[0]);
4823                     this._beforeSelectedTab = null;
4824                 }
4825                 this.ListTab.Controls.Remove(_tabPage);
4826
4827                 // 後付けのコントロールを破棄
4828                 if (tabInfo.TabType == MyCommon.TabUsageType.UserTimeline || tabInfo.TabType == MyCommon.TabUsageType.Lists)
4829                 {
4830                     using (Control label = _tabPage.Controls["labelUser"])
4831                     {
4832                         _tabPage.Controls.Remove(label);
4833                     }
4834                 }
4835                 else if (tabInfo.TabType == MyCommon.TabUsageType.PublicSearch)
4836                 {
4837                     using (Control pnl = _tabPage.Controls["panelSearch"])
4838                     {
4839                         pnl.Enter -= SearchControls_Enter;
4840                         pnl.Leave -= SearchControls_Leave;
4841                         _tabPage.Controls.Remove(pnl);
4842
4843                         foreach (Control ctrl in pnl.Controls)
4844                         {
4845                             if (ctrl.Name == "buttonSearch")
4846                             {
4847                                 ctrl.Click -= SearchButton_Click;
4848                             }
4849                             else if (ctrl.Name == "comboSearch")
4850                             {
4851                                 ctrl.KeyDown -= SearchComboBox_KeyDown;
4852                             }
4853                             pnl.Controls.Remove(ctrl);
4854                             ctrl.Dispose();
4855                         }
4856                     }
4857                 }
4858
4859                 _tabPage.Controls.Remove(_listCustom);
4860
4861                 _listCustom.SelectedIndexChanged -= MyList_SelectedIndexChanged;
4862                 _listCustom.MouseDoubleClick -= MyList_MouseDoubleClick;
4863                 _listCustom.ColumnClick -= MyList_ColumnClick;
4864                 _listCustom.DrawColumnHeader -= MyList_DrawColumnHeader;
4865                 _listCustom.DragDrop -= TweenMain_DragDrop;
4866                 _listCustom.DragEnter -= TweenMain_DragEnter;
4867                 _listCustom.DragOver -= TweenMain_DragOver;
4868                 _listCustom.DrawItem -= MyList_DrawItem;
4869                 _listCustom.MouseClick -= MyList_MouseClick;
4870                 _listCustom.ColumnReordered -= MyList_ColumnReordered;
4871                 _listCustom.ColumnWidthChanged -= MyList_ColumnWidthChanged;
4872                 _listCustom.CacheVirtualItems -= MyList_CacheVirtualItems;
4873                 _listCustom.RetrieveVirtualItem -= MyList_RetrieveVirtualItem;
4874                 _listCustom.DrawSubItem -= MyList_DrawSubItem;
4875                 _listCustom.HScrolled -= MyList_HScrolled;
4876
4877                 var cols = _listCustom.Columns.Cast<ColumnHeader>().ToList<ColumnHeader>();
4878                 _listCustom.Columns.Clear();
4879                 cols.ForEach(col => col.Dispose());
4880                 cols.Clear();
4881
4882                 _listCustom.ContextMenuStrip = null;
4883                 _listCustom.ColumnHeaderContextMenuStrip = null;
4884                 _listCustom.Font = null;
4885
4886                 _listCustom.SmallImageList = null;
4887                 _listCustom.ListViewItemSorter = null;
4888
4889                 //キャッシュのクリア
4890                 if (_curTab.Equals(_tabPage))
4891                 {
4892                     _curTab = null;
4893                     _curItemIndex = -1;
4894                     _curList = null;
4895                     _curPost = null;
4896                 }
4897                 this.PurgeListViewItemCache();
4898             }
4899
4900             _tabPage.Dispose();
4901             _listCustom.Dispose();
4902             _statuses.RemoveTab(TabName);
4903
4904             foreach (TabPage tp in ListTab.TabPages)
4905             {
4906                 DetailsListView lst = (DetailsListView)tp.Tag;
4907                 var count = _statuses.Tabs[tp.Text].AllCount;
4908                 if (lst.VirtualListSize != count)
4909                 {
4910                     lst.VirtualListSize = count;
4911                 }
4912             }
4913
4914             return true;
4915         }
4916
4917         private void ListTab_Deselected(object sender, TabControlEventArgs e)
4918         {
4919             this.PurgeListViewItemCache();
4920             _beforeSelectedTab = e.TabPage;
4921         }
4922
4923         private void ListTab_MouseMove(object sender, MouseEventArgs e)
4924         {
4925             //タブのD&D
4926
4927             if (!this._cfgCommon.TabMouseLock && e.Button == MouseButtons.Left && _tabDrag)
4928             {
4929                 string tn = "";
4930                 Rectangle dragEnableRectangle = new Rectangle((int)(_tabMouseDownPoint.X - (SystemInformation.DragSize.Width / 2)), (int)(_tabMouseDownPoint.Y - (SystemInformation.DragSize.Height / 2)), SystemInformation.DragSize.Width, SystemInformation.DragSize.Height);
4931                 if (!dragEnableRectangle.Contains(e.Location))
4932                 {
4933                     //タブが多段の場合にはMouseDownの前の段階で選択されたタブの段が変わっているので、このタイミングでカーソルの位置からタブを判定出来ない。
4934                     tn = ListTab.SelectedTab.Text;
4935                 }
4936
4937                 if (string.IsNullOrEmpty(tn)) return;
4938
4939                 foreach (TabPage tb in ListTab.TabPages)
4940                 {
4941                     if (tb.Text == tn)
4942                     {
4943                         ListTab.DoDragDrop(tb, DragDropEffects.All);
4944                         break;
4945                     }
4946                 }
4947             }
4948             else
4949             {
4950                 _tabDrag = false;
4951             }
4952
4953             Point cpos = new Point(e.X, e.Y);
4954             for (int i = 0; i < ListTab.TabPages.Count; i++)
4955             {
4956                 Rectangle rect = ListTab.GetTabRect(i);
4957                 if (rect.Left <= cpos.X & cpos.X <= rect.Right &
4958                    rect.Top <= cpos.Y & cpos.Y <= rect.Bottom)
4959                 {
4960                     _rclickTabName = ListTab.TabPages[i].Text;
4961                     break;
4962                 }
4963             }
4964         }
4965
4966         private async void ListTab_SelectedIndexChanged(object sender, EventArgs e)
4967         {
4968             //_curList.Refresh();
4969             SetMainWindowTitle();
4970             SetStatusLabelUrl();
4971             SetApiStatusLabel();
4972             if (ListTab.Focused || ((Control)ListTab.SelectedTab.Tag).Focused) this.Tag = ListTab.Tag;
4973             TabMenuControl(ListTab.SelectedTab.Text);
4974             this.PushSelectPostChain();
4975             await DispSelectedPost();
4976         }
4977
4978         private void SetListProperty()
4979         {
4980             //削除などで見つからない場合は処理せず
4981             if (_curList == null) return;
4982             if (!_isColumnChanged) return;
4983
4984             int[] dispOrder = new int[_curList.Columns.Count];
4985             for (int i = 0; i < _curList.Columns.Count; i++)
4986             {
4987                 for (int j = 0; j < _curList.Columns.Count; j++)
4988                 {
4989                     if (_curList.Columns[j].DisplayIndex == i)
4990                     {
4991                         dispOrder[i] = j;
4992                         break;
4993                     }
4994                 }
4995             }
4996
4997             //列幅、列並びを他のタブに設定
4998             foreach (TabPage tb in ListTab.TabPages)
4999             {
5000                 if (!tb.Equals(_curTab))
5001                 {
5002                     if (tb.Tag != null && tb.Controls.Count > 0)
5003                     {
5004                         DetailsListView lst = (DetailsListView)tb.Tag;
5005                         for (int i = 0; i < lst.Columns.Count; i++)
5006                         {
5007                             lst.Columns[dispOrder[i]].DisplayIndex = i;
5008                             lst.Columns[i].Width = _curList.Columns[i].Width;
5009                         }
5010                     }
5011                 }
5012             }
5013
5014             _isColumnChanged = false;
5015         }
5016
5017         private void PostBrowser_StatusTextChanged(object sender, EventArgs e)
5018         {
5019             try
5020             {
5021                 if (PostBrowser.StatusText.StartsWith("http") || PostBrowser.StatusText.StartsWith("ftp")
5022                         || PostBrowser.StatusText.StartsWith("data"))
5023                 {
5024                     StatusLabelUrl.Text = PostBrowser.StatusText.Replace("&", "&&");
5025                 }
5026                 if (string.IsNullOrEmpty(PostBrowser.StatusText))
5027                 {
5028                     SetStatusLabelUrl();
5029                 }
5030             }
5031             catch (Exception)
5032             {
5033             }
5034         }
5035
5036         private void StatusText_KeyPress(object sender, KeyPressEventArgs e)
5037         {
5038             if (e.KeyChar == '@')
5039             {
5040                 if (!this._cfgCommon.UseAtIdSupplement) return;
5041                 //@マーク
5042                 int cnt = AtIdSupl.ItemCount;
5043                 ShowSuplDialog(StatusText, AtIdSupl);
5044                 if (cnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
5045                 e.Handled = true;
5046             }
5047             else if (e.KeyChar == '#')
5048             {
5049                 if (!this._cfgCommon.UseHashSupplement) return;
5050                 ShowSuplDialog(StatusText, HashSupl);
5051                 e.Handled = true;
5052             }
5053         }
5054
5055         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog)
5056         {
5057             ShowSuplDialog(owner, dialog, 0, "");
5058         }
5059
5060         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset)
5061         {
5062             ShowSuplDialog(owner, dialog, offset, "");
5063         }
5064
5065         public void ShowSuplDialog(TextBox owner, AtIdSupplement dialog, int offset, string startswith)
5066         {
5067             dialog.StartsWith = startswith;
5068             if (dialog.Visible)
5069             {
5070                 dialog.Focus();
5071             }
5072             else
5073             {
5074                 dialog.ShowDialog();
5075             }
5076             this.TopMost = this._cfgCommon.AlwaysTop;
5077             int selStart = owner.SelectionStart;
5078             string fHalf = "";
5079             string eHalf = "";
5080             if (dialog.DialogResult == DialogResult.OK)
5081             {
5082                 if (!string.IsNullOrEmpty(dialog.inputText))
5083                 {
5084                     if (selStart > 0)
5085                     {
5086                         fHalf = owner.Text.Substring(0, selStart - offset);
5087                     }
5088                     if (selStart < owner.Text.Length)
5089                     {
5090                         eHalf = owner.Text.Substring(selStart);
5091                     }
5092                     owner.Text = fHalf + dialog.inputText + eHalf;
5093                     owner.SelectionStart = selStart + dialog.inputText.Length;
5094                 }
5095             }
5096             else
5097             {
5098                 if (selStart > 0)
5099                 {
5100                     fHalf = owner.Text.Substring(0, selStart);
5101                 }
5102                 if (selStart < owner.Text.Length)
5103                 {
5104                     eHalf = owner.Text.Substring(selStart);
5105                 }
5106                 owner.Text = fHalf + eHalf;
5107                 if (selStart > 0)
5108                 {
5109                     owner.SelectionStart = selStart;
5110                 }
5111             }
5112             owner.Focus();
5113         }
5114
5115         private void StatusText_KeyUp(object sender, KeyEventArgs e)
5116         {
5117             //スペースキーで未読ジャンプ
5118             if (!e.Alt && !e.Control && !e.Shift)
5119             {
5120                 if (e.KeyCode == Keys.Space || e.KeyCode == Keys.ProcessKey)
5121                 {
5122                     bool isSpace = false;
5123                     foreach (char c in StatusText.Text.ToCharArray())
5124                     {
5125                         if (c == ' ' || c == ' ')
5126                         {
5127                             isSpace = true;
5128                         }
5129                         else
5130                         {
5131                             isSpace = false;
5132                             break;
5133                         }
5134                     }
5135                     if (isSpace)
5136                     {
5137                         e.Handled = true;
5138                         StatusText.Text = "";
5139                         JumpUnreadMenuItem_Click(null, null);
5140                     }
5141                 }
5142             }
5143             this.StatusText_TextChanged(null, null);
5144         }
5145
5146         private void StatusText_TextChanged(object sender, EventArgs e)
5147         {
5148             //文字数カウント
5149             int pLen = this.GetRestStatusCount(this.FormatStatusText(this.StatusText.Text));
5150             lblLen.Text = pLen.ToString();
5151             if (pLen < 0)
5152             {
5153                 StatusText.ForeColor = Color.Red;
5154             }
5155             else
5156             {
5157                 StatusText.ForeColor = _clInputFont;
5158             }
5159             if (string.IsNullOrEmpty(StatusText.Text))
5160             {
5161                 this.inReplyTo = null;
5162             }
5163         }
5164
5165         /// <summary>
5166         /// ツイート投稿前のフッター付与などの前処理を行います
5167         /// </summary>
5168         private string FormatStatusText(string statusText)
5169         {
5170             statusText = statusText.Replace("\r\n", "\n");
5171
5172             if (this.ToolStripMenuItemUrlMultibyteSplit.Checked)
5173             {
5174                 // URLと全角文字の切り離し
5175                 statusText = Regex.Replace(statusText, @"https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#^]+", "$& ");
5176             }
5177
5178             if (this.IdeographicSpaceToSpaceToolStripMenuItem.Checked)
5179             {
5180                 // 文中の全角スペースを半角スペース1個にする
5181                 statusText = statusText.Replace(" ", " ");
5182             }
5183
5184             // DM の場合はこれ以降の処理を行わない
5185             if (statusText.StartsWith("D ", StringComparison.OrdinalIgnoreCase))
5186                 return statusText;
5187
5188             bool disableFooter;
5189             if (this._cfgCommon.PostShiftEnter)
5190             {
5191                 disableFooter = MyCommon.IsKeyDown(Keys.Control);
5192             }
5193             else
5194             {
5195                 if (this.StatusText.Multiline)
5196                     disableFooter = MyCommon.IsKeyDown(Keys.Control);
5197                 else
5198                     disableFooter = MyCommon.IsKeyDown(Keys.Shift);
5199             }
5200
5201             if (statusText.Contains("RT @"))
5202                 disableFooter = true;
5203
5204             var header = "";
5205             var footer = "";
5206
5207             var hashtag = this.HashMgr.UseHash;
5208             if (!string.IsNullOrEmpty(hashtag) && !(this.HashMgr.IsNotAddToAtReply && this.inReplyTo != null))
5209             {
5210                 if (HashMgr.IsHead)
5211                     header = HashMgr.UseHash + " ";
5212                 else
5213                     footer = " " + HashMgr.UseHash;
5214             }
5215
5216             if (!disableFooter)
5217             {
5218                 if (this._cfgLocal.UseRecommendStatus)
5219                 {
5220                     // 推奨ステータスを使用する
5221                     footer += this.recommendedStatusFooter;
5222                 }
5223                 else if (!string.IsNullOrEmpty(this._cfgLocal.StatusText))
5224                 {
5225                     // テキストボックスに入力されている文字列を使用する
5226                     footer += " " + this._cfgLocal.StatusText.Trim();
5227                 }
5228             }
5229
5230             statusText = header + statusText + footer;
5231
5232             if (this.ToolStripMenuItemApiCommandEvasion.Checked)
5233             {
5234                 // APIコマンド回避
5235                 if (Regex.IsMatch(statusText, @"^[+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]*(get|g|fav|follow|f|on|off|stop|quit|leave|l|whois|w|nudge|n|stats|invite|track|untrack|tracks|tracking|\*)([+\-\[\]\s\\.,*/(){}^~|='&%$#""<>?]+|$)", RegexOptions.IgnoreCase)
5236                    && !statusText.EndsWith(" .", StringComparison.Ordinal))
5237                     statusText += " .";
5238             }
5239
5240             return statusText;
5241         }
5242
5243         /// <summary>
5244         /// 投稿欄に表示する入力可能な文字数を計算します
5245         /// </summary>
5246         private int GetRestStatusCount(string statusText)
5247         {
5248             //文字数カウント
5249             var remainCount = this.tw.GetTextLengthRemain(statusText);
5250
5251             if (this.ImageSelector.Visible && !string.IsNullOrEmpty(this.ImageSelector.ServiceName))
5252             {
5253                 remainCount -= this.tw.Configuration.CharactersReservedPerMedia;
5254             }
5255
5256             return remainCount;
5257         }
5258
5259         private void MyList_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
5260         {
5261             if (sender != this._curList)
5262                 return;
5263
5264             var listCache = this._listItemCache;
5265             if (listCache != null && listCache.IsSupersetOf(e.StartIndex, e.EndIndex))
5266             {
5267                 // If the newly requested cache is a subset of the old cache,
5268                 // no need to rebuild everything, so do nothing.
5269                 return;
5270             }
5271
5272             // Now we need to rebuild the cache.
5273             this.CreateCache(e.StartIndex, e.EndIndex);
5274         }
5275
5276         private void MyList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
5277         {
5278             var listCache = this._listItemCache;
5279             if (listCache != null && listCache.TargetList == sender)
5280             {
5281                 ListViewItem item;
5282                 PostClass cacheItemPost;
5283                 if (listCache.TryGetValue(e.ItemIndex, out item, out cacheItemPost))
5284                 {
5285                     e.Item = item;
5286                     return;
5287                 }
5288             }
5289
5290             // A cache miss, so create a new ListViewItem and pass it back.
5291             TabPage tb = (TabPage)((DetailsListView)sender).Parent;
5292             try
5293             {
5294                 e.Item = this.CreateItem(tb, _statuses.Tabs[tb.Text][e.ItemIndex], e.ItemIndex);
5295             }
5296             catch (Exception)
5297             {
5298                 // 不正な要求に対する間に合わせの応答
5299                 string[] sitem = {"", "", "", "", "", "", "", ""};
5300                 e.Item = new ImageListViewItem(sitem);
5301             }
5302         }
5303
5304         private void CreateCache(int startIndex, int endIndex)
5305         {
5306             var tabInfo = this._statuses.Tabs[this._curTab.Text];
5307
5308             // キャッシュ要求(要求範囲±30を作成)
5309             startIndex = Math.Max(startIndex - 30, 0);
5310             endIndex = Math.Min(endIndex + 30, tabInfo.AllCount - 1);
5311
5312             var cacheLength = endIndex - startIndex + 1;
5313
5314             var posts = tabInfo[startIndex, endIndex]; //配列で取得
5315             var listItems = Enumerable.Range(0, cacheLength)
5316                 .Select(x => this.CreateItem(this._curTab, posts[x], startIndex + x))
5317                 .ToArray();
5318
5319             var listCache = new ListViewItemCache
5320             {
5321                 TargetList = this._curList,
5322                 StartIndex = startIndex,
5323                 EndIndex = endIndex,
5324                 Post = posts,
5325                 ListItem = listItems,
5326             };
5327
5328             Interlocked.Exchange(ref this._listItemCache, listCache);
5329         }
5330
5331         /// <summary>
5332         /// DetailsListView のための ListViewItem のキャッシュを消去する
5333         /// </summary>
5334         private void PurgeListViewItemCache()
5335         {
5336             Interlocked.Exchange(ref this._listItemCache, null);
5337         }
5338
5339         private ListViewItem CreateItem(TabPage Tab, PostClass Post, int Index)
5340         {
5341             StringBuilder mk = new StringBuilder();
5342             //if (Post.IsDeleted) mk.Append("×");
5343             //if (Post.IsMark) mk.Append("♪");
5344             //if (Post.IsProtect) mk.Append("Ю");
5345             //if (Post.InReplyToStatusId != null) mk.Append("⇒");
5346             if (Post.FavoritedCount > 0) mk.Append("+" + Post.FavoritedCount.ToString());
5347             ImageListViewItem itm;
5348             if (Post.RetweetedId == null)
5349             {
5350                 string[] sitem= {"",
5351                                  Post.Nickname,
5352                                  Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5353                                  Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5354                                  Post.ScreenName,
5355                                  "",
5356                                  mk.ToString(),
5357                                  Post.Source};
5358                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5359             }
5360             else
5361             {
5362                 string[] sitem = {"",
5363                                   Post.Nickname,
5364                                   Post.IsDeleted ? "(DELETED)" : Post.TextSingleLine,
5365                                   Post.CreatedAt.ToString(this._cfgCommon.DateTimeFormat),
5366                                   Post.ScreenName + Environment.NewLine + "(RT:" + Post.RetweetedBy + ")",
5367                                   "",
5368                                   mk.ToString(),
5369                                   Post.Source};
5370                 itm = new ImageListViewItem(sitem, this.IconCache, Post.ImageUrl);
5371             }
5372             itm.StateIndex = Post.StateIndex;
5373
5374             bool read = Post.IsRead;
5375             //未読管理していなかったら既読として扱う
5376             if (!_statuses.Tabs[Tab.Text].UnreadManage || !this._cfgCommon.UnreadManage) read = true;
5377             ChangeItemStyleRead(read, itm, Post, null);
5378             if (Tab.Equals(_curTab)) ColorizeList(itm, Index);
5379             return itm;
5380         }
5381
5382         /// <summary>
5383         /// 全てのタブの振り分けルールを反映し直します
5384         /// </summary>
5385         private void ApplyPostFilters()
5386         {
5387             using (ControlTransaction.Cursor(this, Cursors.WaitCursor))
5388             {
5389                 this.PurgeListViewItemCache();
5390                 this._curPost = null;
5391                 this._curItemIndex = -1;
5392                 this._statuses.FilterAll();
5393
5394                 foreach (TabPage tabPage in this.ListTab.TabPages)
5395                 {
5396                     var tab = this._statuses.Tabs[tabPage.Text];
5397
5398                     var listview = (DetailsListView)tabPage.Tag;
5399                     using (ControlTransaction.Update(listview))
5400                     {
5401                         listview.VirtualListSize = tab.AllCount;
5402                     }
5403
5404                     if (this._cfgCommon.TabIconDisp)
5405                     {
5406                         if (tab.UnreadCount > 0)
5407                             tabPage.ImageIndex = 0;
5408                         else
5409                             tabPage.ImageIndex = -1;
5410                     }
5411                 }
5412
5413                 if (!this._cfgCommon.TabIconDisp)
5414                     this.ListTab.Refresh();
5415
5416                 SetMainWindowTitle();
5417                 SetStatusLabelUrl();
5418             }
5419         }
5420
5421         private void MyList_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
5422         {
5423             e.DrawDefault = true;
5424         }
5425
5426         private void MyList_HScrolled(object sender, EventArgs e)
5427         {
5428             DetailsListView listView = (DetailsListView)sender;
5429             listView.Refresh();
5430         }
5431
5432         private void MyList_DrawItem(object sender, DrawListViewItemEventArgs e)
5433         {
5434             if (e.State == 0) return;
5435             e.DrawDefault = false;
5436
5437             SolidBrush brs2 = null;
5438             if (!e.Item.Selected)     //e.ItemStateでうまく判定できない???
5439             {
5440                 if (e.Item.BackColor == _clSelf)
5441                     brs2 = _brsBackColorMine;
5442                 else if (e.Item.BackColor == _clAtSelf)
5443                     brs2 = _brsBackColorAt;
5444                 else if (e.Item.BackColor == _clTarget)
5445                     brs2 = _brsBackColorYou;
5446                 else if (e.Item.BackColor == _clAtTarget)
5447                     brs2 = _brsBackColorAtYou;
5448                 else if (e.Item.BackColor == _clAtFromTarget)
5449                     brs2 = _brsBackColorAtFromTarget;
5450                 else if (e.Item.BackColor == _clAtTo)
5451                     brs2 = _brsBackColorAtTo;
5452                 else
5453                     brs2 = _brsBackColorNone;
5454             }
5455             else
5456             {
5457                 //選択中の行
5458                 if (((Control)sender).Focused)
5459                     brs2 = _brsHighLight;
5460                 else
5461                     brs2 = _brsDeactiveSelection;
5462             }
5463             e.Graphics.FillRectangle(brs2, e.Bounds);
5464             e.DrawFocusRectangle();
5465             this.DrawListViewItemIcon(e);
5466         }
5467
5468         private void MyList_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
5469         {
5470             if (e.ItemState == 0) return;
5471
5472             if (e.ColumnIndex > 0)
5473             {
5474                 //アイコン以外の列
5475                 RectangleF rct = e.Bounds;
5476                 rct.Width = e.Header.Width;
5477                 int fontHeight = e.Item.Font.Height;
5478                 if (_iconCol)
5479                 {
5480                     rct.Y += fontHeight;
5481                     rct.Height -= fontHeight;
5482                 }
5483
5484                 int heightDiff;
5485                 int drawLineCount = Math.Max(1, Math.DivRem((int)rct.Height, fontHeight, out heightDiff));
5486
5487                 //if (heightDiff > fontHeight * 0.7)
5488                 //{
5489                 //    rct.Height += fontHeight;
5490                 //    drawLineCount += 1;
5491                 //}
5492
5493                 //フォントの高さの半分を足してるのは保険。無くてもいいかも。
5494                 if (!_iconCol && drawLineCount <= 1)
5495                 {
5496                     //rct.Inflate(0, heightDiff / -2);
5497                     //rct.Height += fontHeight / 2;
5498                 }
5499                 else if (heightDiff < fontHeight * 0.7)
5500                 {
5501                     //最終行が70%以上欠けていたら、最終行は表示しない
5502                     //rct.Height = (float)((fontHeight * drawLineCount) + (fontHeight / 2));
5503                     rct.Height = (fontHeight * drawLineCount) - 1;
5504                 }
5505                 else
5506                 {
5507                     drawLineCount += 1;
5508                 }
5509
5510                 //if (!_iconCol && drawLineCount > 1)
5511                 //{
5512                 //    rct.Y += fontHeight * 0.2;
5513                 //    if (heightDiff >= fontHeight * 0.8) rct.Height -= fontHeight * 0.2;
5514                 //}
5515
5516                 if (rct.Width > 0)
5517                 {
5518                     Color color = (!e.Item.Selected) ? e.Item.ForeColor :   //選択されていない行
5519                         (((Control)sender).Focused) ? _clHighLight :        //選択中の行
5520                         _clUnread;
5521
5522                     if (_iconCol)
5523                     {
5524                         Rectangle rctB = e.Bounds;
5525                         rctB.Width = e.Header.Width;
5526                         rctB.Height = fontHeight;
5527
5528                         using (Font fnt = new Font(e.Item.Font, FontStyle.Bold))
5529                         {
5530                             TextRenderer.DrawText(e.Graphics,
5531                                                     e.Item.SubItems[2].Text,
5532                                                     e.Item.Font,
5533                                                     Rectangle.Round(rct),
5534                                                     color,
5535                                                     TextFormatFlags.WordBreak |
5536                                                     TextFormatFlags.EndEllipsis |
5537                                                     TextFormatFlags.GlyphOverhangPadding |
5538                                                     TextFormatFlags.NoPrefix);
5539                             TextRenderer.DrawText(e.Graphics,
5540                                                     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 + "]",
5541                                                     fnt,
5542                                                     rctB,
5543                                                     color,
5544                                                     TextFormatFlags.SingleLine |
5545                                                     TextFormatFlags.EndEllipsis |
5546                                                     TextFormatFlags.GlyphOverhangPadding |
5547                                                     TextFormatFlags.NoPrefix);
5548                         }
5549                     }
5550                     else if (drawLineCount == 1)
5551                     {
5552                         TextRenderer.DrawText(e.Graphics,
5553                                                 e.SubItem.Text,
5554                                                 e.Item.Font,
5555                                                 Rectangle.Round(rct),
5556                                                 color,
5557                                                 TextFormatFlags.SingleLine |
5558                                                 TextFormatFlags.EndEllipsis |
5559                                                 TextFormatFlags.GlyphOverhangPadding |
5560                                                 TextFormatFlags.NoPrefix |
5561                                                 TextFormatFlags.VerticalCenter);
5562                     }
5563                     else
5564                     {
5565                         TextRenderer.DrawText(e.Graphics,
5566                                                 e.SubItem.Text,
5567                                                 e.Item.Font,
5568                                                 Rectangle.Round(rct),
5569                                                 color,
5570                                                 TextFormatFlags.WordBreak |
5571                                                 TextFormatFlags.EndEllipsis |
5572                                                 TextFormatFlags.GlyphOverhangPadding |
5573                                                 TextFormatFlags.NoPrefix);
5574                     }
5575                     //if (e.ColumnIndex == 6) this.DrawListViewItemStateIcon(e, rct);
5576                 }
5577             }
5578         }
5579
5580         private void DrawListViewItemIcon(DrawListViewItemEventArgs e)
5581         {
5582             if (_iconSz == 0) return;
5583
5584             ImageListViewItem item = (ImageListViewItem)e.Item;
5585
5586             //e.Bounds.Leftが常に0を指すから自前で計算
5587             Rectangle itemRect = item.Bounds;
5588             var col0 = e.Item.ListView.Columns[0];
5589             itemRect.Width = col0.Width;
5590
5591             if (col0.DisplayIndex > 0)
5592             {
5593                 foreach (ColumnHeader clm in e.Item.ListView.Columns)
5594                 {
5595                     if (clm.DisplayIndex < col0.DisplayIndex)
5596                         itemRect.X += clm.Width;
5597                 }
5598             }
5599
5600             // ディスプレイの DPI 設定を考慮したアイコンサイズ
5601             var realIconSize = new SizeF(this._iconSz * this.CurrentScaleFactor.Width, this._iconSz * this.CurrentScaleFactor.Height).ToSize();
5602             var realStateSize = new SizeF(16 * this.CurrentScaleFactor.Width, 16 * this.CurrentScaleFactor.Height).ToSize();
5603
5604             Rectangle iconRect;
5605             var img = item.Image;
5606             if (img != null)
5607             {
5608                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, realIconSize), itemRect);
5609                 iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5610
5611                 if (iconRect.Width > 0)
5612                 {
5613                     e.Graphics.FillRectangle(Brushes.White, iconRect);
5614                     e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
5615                     try
5616                     {
5617                         e.Graphics.DrawImage(img.Image, iconRect);
5618                     }
5619                     catch (ArgumentException)
5620                     {
5621                         item.RefreshImageAsync();
5622                     }
5623                 }
5624             }
5625             else
5626             {
5627                 iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(1, 1)), itemRect);
5628                 //iconRect.Offset(0, Math.Max(0, (itemRect.Height - realIconSize.Height) / 2));
5629
5630                 item.GetImageAsync();
5631             }
5632
5633             if (item.StateIndex > -1)
5634             {
5635                 Rectangle stateRect = Rectangle.Intersect(new Rectangle(new Point(iconRect.X + realIconSize.Width + 2, iconRect.Y), realStateSize), itemRect);
5636                 if (stateRect.Width > 0)
5637                 {
5638                     //e.Graphics.FillRectangle(Brushes.White, stateRect);
5639                     //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5640                     e.Graphics.DrawImage(this.PostStateImageList.Images[item.StateIndex], stateRect);
5641                 }
5642             }
5643         }
5644
5645         protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
5646         {
5647             base.ScaleControl(factor, specified);
5648
5649             ScaleChildControl(this.TabImage, factor);
5650
5651             var tabpages = this.ListTab.TabPages.Cast<TabPage>();
5652             var listviews = tabpages.Select(x => x.Tag).Cast<ListView>();
5653
5654             foreach (var listview in listviews)
5655             {
5656                 ScaleChildControl(listview, factor);
5657             }
5658         }
5659
5660         //private void DrawListViewItemStateIcon(DrawListViewSubItemEventArgs e, RectangleF rct)
5661         //{
5662         //    ImageListViewItem item = (ImageListViewItem)e.Item;
5663         //    if (item.StateImageIndex > -1)
5664         //    {
5665         //        ////e.Bounds.Leftが常に0を指すから自前で計算
5666         //        //Rectangle itemRect = item.Bounds;
5667         //        //itemRect.Width = e.Item.ListView.Columns[4].Width;
5668
5669         //        //foreach (ColumnHeader clm in e.Item.ListView.Columns)
5670         //        //{
5671         //        //    if (clm.DisplayIndex < e.Item.ListView.Columns[4].DisplayIndex)
5672         //        //    {
5673         //        //        itemRect.X += clm.Width;
5674         //        //    }
5675         //        //}
5676
5677         //        //Rectangle iconRect = Rectangle.Intersect(new Rectangle(e.Item.GetBounds(ItemBoundsPortion.Icon).Location, new Size(_iconSz, _iconSz)), itemRect);
5678         //        //iconRect.Offset(0, Math.Max(0, (itemRect.Height - _iconSz) / 2));
5679
5680         //        if (rct.Width > 0)
5681         //        {
5682         //            RectangleF stateRect = RectangleF.Intersect(rct, new RectangleF(rct.Location, new Size(18, 16)));
5683         //            //e.Graphics.FillRectangle(Brushes.White, rct);
5684         //            //e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.High;
5685         //            e.Graphics.DrawImage(this.PostStateImageList.Images(item.StateImageIndex), stateRect);
5686         //        }
5687         //    }
5688         //}
5689
5690         private void DoTabSearch(string _word,
5691                                  bool CaseSensitive,
5692                                  bool UseRegex,
5693                                  SEARCHTYPE SType)
5694         {
5695             int cidx = 0;
5696             bool fnd = false;
5697             int toIdx;
5698             int stp = 1;
5699
5700             if (_curList.VirtualListSize == 0)
5701             {
5702                 MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5703             }
5704
5705             if (_curList.SelectedIndices.Count > 0)
5706             {
5707                 cidx = _curList.SelectedIndices[0];
5708             }
5709             toIdx = _curList.VirtualListSize;
5710
5711             switch (SType)
5712             {
5713                 case SEARCHTYPE.DialogSearch:    //ダイアログからの検索
5714                     if (_curList.SelectedIndices.Count > 0)
5715                         cidx = _curList.SelectedIndices[0];
5716                     else
5717                         cidx = 0;
5718                     break;
5719                 case SEARCHTYPE.NextSearch:      //次を検索
5720                     if (_curList.SelectedIndices.Count > 0)
5721                     {
5722                         cidx = _curList.SelectedIndices[0] + 1;
5723                         if (cidx > toIdx) cidx = toIdx;
5724                     }
5725                     else
5726                     {
5727                         cidx = 0;
5728                     }
5729                     break;
5730                 case SEARCHTYPE.PrevSearch:      //前を検索
5731                     if (_curList.SelectedIndices.Count > 0)
5732                     {
5733                         cidx = _curList.SelectedIndices[0] - 1;
5734                         if (cidx < 0) cidx = 0;
5735                     }
5736                     else
5737                     {
5738                         cidx = toIdx;
5739                     }
5740                     toIdx = -1;
5741                     stp = -1;
5742                     break;
5743             }
5744
5745             RegexOptions regOpt = RegexOptions.None;
5746             StringComparison fndOpt = StringComparison.Ordinal;
5747             if (!CaseSensitive)
5748             {
5749                 regOpt = RegexOptions.IgnoreCase;
5750                 fndOpt = StringComparison.OrdinalIgnoreCase;
5751             }
5752             try
5753             {
5754     RETRY:
5755                 if (UseRegex)
5756                 {
5757                     // 正規表現検索
5758                     Regex _search;
5759                     try
5760                     {
5761                         _search = new Regex(_word, regOpt);
5762                         for (int idx = cidx; idx != toIdx; idx += stp)
5763                         {
5764                             PostClass post;
5765                             try
5766                             {
5767                                 post = _statuses.Tabs[_curTab.Text][idx];
5768                             }
5769                             catch (Exception)
5770                             {
5771                                 continue;
5772                             }
5773                             if (_search.IsMatch(post.Nickname)
5774                                 || _search.IsMatch(post.TextFromApi)
5775                                 || _search.IsMatch(post.ScreenName))
5776                             {
5777                                 SelectListItem(_curList, idx);
5778                                 _curList.EnsureVisible(idx);
5779                                 return;
5780                             }
5781                         }
5782                     }
5783                     catch (ArgumentException)
5784                     {
5785                         MessageBox.Show(Properties.Resources.DoTabSearchText1, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
5786                         return;
5787                     }
5788                 }
5789                 else
5790                 {
5791                     // 通常検索
5792                     for (int idx = cidx; idx != toIdx; idx += stp)
5793                     {
5794                         PostClass post;
5795                         try
5796                         {
5797                             post = _statuses.Tabs[_curTab.Text][idx];
5798                         }
5799                         catch (Exception)
5800                         {
5801                             continue;
5802                         }
5803                         if (post.Nickname.IndexOf(_word, fndOpt) > -1
5804                             || post.TextFromApi.IndexOf(_word, fndOpt) > -1
5805                             || post.ScreenName.IndexOf(_word, fndOpt) > -1)
5806                         {
5807                             SelectListItem(_curList, idx);
5808                             _curList.EnsureVisible(idx);
5809                             return;
5810                         }
5811                     }
5812                 }
5813
5814                 if (!fnd)
5815                 {
5816                     switch (SType)
5817                     {
5818                         case SEARCHTYPE.DialogSearch:
5819                         case SEARCHTYPE.NextSearch:
5820                             toIdx = cidx;
5821                             cidx = 0;
5822                             break;
5823                         case SEARCHTYPE.PrevSearch:
5824                             toIdx = cidx;
5825                             cidx = _curList.VirtualListSize - 1;
5826                             break;
5827                     }
5828                     fnd = true;
5829                     goto RETRY;
5830                 }
5831             }
5832             catch (ArgumentOutOfRangeException)
5833             {
5834             }
5835             MessageBox.Show(Properties.Resources.DoTabSearchText2, Properties.Resources.DoTabSearchText3, MessageBoxButtons.OK, MessageBoxIcon.Information);
5836         }
5837
5838         private void MenuItemSubSearch_Click(object sender, EventArgs e)
5839         {
5840             // 検索メニュー
5841             this.ShowSearchDialog();
5842         }
5843
5844         private void MenuItemSearchNext_Click(object sender, EventArgs e)
5845         {
5846             var previousSearch = this.SearchDialog.ResultOptions;
5847             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5848             {
5849                 this.SearchDialog.Reset();
5850                 this.ShowSearchDialog();
5851                 return;
5852             }
5853
5854             // 次を検索
5855             this.DoTabSearch(
5856                 previousSearch.Query,
5857                 previousSearch.CaseSensitive,
5858                 previousSearch.UseRegex,
5859                 SEARCHTYPE.NextSearch);
5860         }
5861
5862         private void MenuItemSearchPrev_Click(object sender, EventArgs e)
5863         {
5864             var previousSearch = this.SearchDialog.ResultOptions;
5865             if (previousSearch == null || previousSearch.Type != SearchWordDialog.SearchType.Timeline)
5866             {
5867                 this.SearchDialog.Reset();
5868                 this.ShowSearchDialog();
5869                 return;
5870             }
5871
5872             // 前を検索
5873             this.DoTabSearch(
5874                 previousSearch.Query,
5875                 previousSearch.CaseSensitive,
5876                 previousSearch.UseRegex,
5877                 SEARCHTYPE.PrevSearch);
5878         }
5879
5880         /// <summary>
5881         /// 検索ダイアログを表示し、検索を実行します
5882         /// </summary>
5883         private void ShowSearchDialog()
5884         {
5885             if (this.SearchDialog.ShowDialog(this) != DialogResult.OK)
5886             {
5887                 this.TopMost = this._cfgCommon.AlwaysTop;
5888                 return;
5889             }
5890             this.TopMost = this._cfgCommon.AlwaysTop;
5891
5892             var searchOptions = this.SearchDialog.ResultOptions;
5893             if (searchOptions.Type == SearchWordDialog.SearchType.Timeline)
5894             {
5895                 if (searchOptions.NewTab)
5896                 {
5897                     var tabName = Properties.Resources.SearchResults_TabName;
5898
5899                     try
5900                     {
5901                         tabName = this._statuses.MakeTabName(tabName);
5902                     }
5903                     catch (TabException ex)
5904                     {
5905                         MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
5906                     }
5907
5908                     this.AddNewTab(tabName, false, MyCommon.TabUsageType.SearchResults);
5909                     this._statuses.AddTab(tabName, MyCommon.TabUsageType.SearchResults, null);
5910
5911                     var filter = new PostFilterRule
5912                     {
5913                         FilterBody = new[] { searchOptions.Query },
5914                         UseRegex = searchOptions.UseRegex,
5915                         CaseSensitive = searchOptions.CaseSensitive,
5916                     };
5917
5918                     var targetTab = this._statuses.Tabs[this._curTab.Text];
5919                     var posts = targetTab.Posts.Values
5920                         .Where(x => filter.ExecFilter(x) == MyCommon.HITRESULT.CopyAndMark)
5921                         .Where(x => targetTab.Contains(x.StatusId));
5922
5923                     var resultTab = this._statuses.Tabs[tabName];
5924                     foreach (var post in posts)
5925                     {
5926                         resultTab.AddPostToInnerStorage(post);
5927                     }
5928
5929                     this._statuses.DistributePosts();
5930                     this.RefreshTimeline();
5931
5932                     var tabPage = this.ListTab.TabPages.Cast<TabPage>()
5933                         .First(x => x.Text == tabName);
5934
5935                     this.ListTab.SelectedTab = tabPage;
5936                 }
5937                 else
5938                 {
5939                     this.DoTabSearch(
5940                         searchOptions.Query,
5941                         searchOptions.CaseSensitive,
5942                         searchOptions.UseRegex,
5943                         SEARCHTYPE.DialogSearch);
5944                 }
5945             }
5946             else if (searchOptions.Type == SearchWordDialog.SearchType.Public)
5947             {
5948                 this.AddNewTabForSearch(searchOptions.Query);
5949             }
5950         }
5951
5952         private void AboutMenuItem_Click(object sender, EventArgs e)
5953         {
5954             using (TweenAboutBox about = new TweenAboutBox())
5955             {
5956                 about.ShowDialog(this);
5957             }
5958             this.TopMost = this._cfgCommon.AlwaysTop;
5959         }
5960
5961         private void JumpUnreadMenuItem_Click(object sender, EventArgs e)
5962         {
5963             int bgnIdx = ListTab.TabPages.IndexOf(_curTab);
5964             int idx = -1;
5965             DetailsListView lst = null;
5966
5967             if (ImageSelector.Enabled)
5968                 return;
5969
5970             //現在タブから最終タブまで探索
5971             for (int i = bgnIdx; i < ListTab.TabPages.Count; i++)
5972             {
5973                 //未読Index取得
5974                 idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5975                 if (idx > -1)
5976                 {
5977                     ListTab.SelectedIndex = i;
5978                     lst = (DetailsListView)ListTab.TabPages[i].Tag;
5979                     //_curTab = ListTab.TabPages[i];
5980                     break;
5981                 }
5982             }
5983
5984             //未読みつからず&現在タブが先頭ではなかったら、先頭タブから現在タブの手前まで探索
5985             if (idx == -1 && bgnIdx > 0)
5986             {
5987                 for (int i = 0; i < bgnIdx; i++)
5988                 {
5989                     idx = _statuses.Tabs[ListTab.TabPages[i].Text].NextUnreadIndex;
5990                     if (idx > -1)
5991                     {
5992                         ListTab.SelectedIndex = i;
5993                         lst = (DetailsListView)ListTab.TabPages[i].Tag;
5994                         //_curTab = ListTab.TabPages[i];
5995                         break;
5996                     }
5997                 }
5998             }
5999
6000             //全部調べたが未読見つからず→先頭タブの最新発言へ
6001             if (idx == -1)
6002             {
6003                 ListTab.SelectedIndex = 0;
6004                 lst = (DetailsListView)ListTab.TabPages[0].Tag;
6005                 //_curTab = ListTab.TabPages[0];
6006                 if (_statuses.SortOrder == SortOrder.Ascending)
6007                     idx = lst.VirtualListSize - 1;
6008                 else
6009                     idx = 0;
6010             }
6011
6012             if (lst.VirtualListSize > 0 && idx > -1 && lst.VirtualListSize > idx)
6013             {
6014                 SelectListItem(lst, idx);
6015                 if (_statuses.SortMode == ComparerMode.Id)
6016                 {
6017                     if (_statuses.SortOrder == SortOrder.Ascending && lst.Items[idx].Position.Y > lst.ClientSize.Height - _iconSz - 10 ||
6018                        _statuses.SortOrder == SortOrder.Descending && lst.Items[idx].Position.Y < _iconSz + 10)
6019                     {
6020                         MoveTop();
6021                     }
6022                     else
6023                     {
6024                         lst.EnsureVisible(idx);
6025                     }
6026                 }
6027                 else
6028                 {
6029                     lst.EnsureVisible(idx);
6030                 }
6031             }
6032             lst.Focus();
6033         }
6034
6035         private async void StatusOpenMenuItem_Click(object sender, EventArgs e)
6036         {
6037             if (_curList.SelectedIndices.Count > 0 && _statuses.Tabs[_curTab.Text].TabType != MyCommon.TabUsageType.DirectMessage)
6038             {
6039                 var post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6040                 await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(post));
6041             }
6042         }
6043
6044         private async void FavorareMenuItem_Click(object sender, EventArgs e)
6045         {
6046             if (_curList.SelectedIndices.Count > 0)
6047             {
6048                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[0]];
6049                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + post.ScreenName + "/recent");
6050             }
6051         }
6052
6053         private async void VerUpMenuItem_Click(object sender, EventArgs e)
6054         {
6055             await this.CheckNewVersion(false);
6056         }
6057
6058         private void RunTweenUp()
6059         {
6060             ProcessStartInfo pinfo = new ProcessStartInfo();
6061             pinfo.UseShellExecute = true;
6062             pinfo.WorkingDirectory = MyCommon.settingPath;
6063             pinfo.FileName = Path.Combine(MyCommon.settingPath, "TweenUp3.exe");
6064             pinfo.Arguments = "\"" + Application.StartupPath + "\"";
6065             try
6066             {
6067                 Process.Start(pinfo);
6068             }
6069             catch (Exception)
6070             {
6071                 MessageBox.Show("Failed to execute TweenUp3.exe.");
6072             }
6073         }
6074
6075         public class VersionInfo
6076         {
6077             public Version Version { get; set; }
6078             public Uri DownloadUri { get; set; }
6079             public string ReleaseNote { get; set; }
6080         }
6081
6082         /// <summary>
6083         /// OpenTween の最新バージョンの情報を取得します
6084         /// </summary>
6085         public async Task<VersionInfo> GetVersionInfoAsync()
6086         {
6087             var versionInfoUrl = new Uri(ApplicationSettings.VersionInfoUrl + "?" +
6088                 DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount);
6089
6090             var responseText = await Networking.Http.GetStringAsync(versionInfoUrl)
6091                 .ConfigureAwait(false);
6092
6093             // 改行2つで前後パートを分割(前半がバージョン番号など、後半が詳細テキスト)
6094             var msgPart = responseText.Split(new[] { "\n\n", "\r\n\r\n" }, 2, StringSplitOptions.None);
6095
6096             var msgHeader = msgPart[0].Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
6097             var msgBody = msgPart.Length == 2 ? msgPart[1] : "";
6098
6099             msgBody = Regex.Replace(msgBody, "(?<!\r)\n", "\r\n"); // LF -> CRLF
6100
6101             return new VersionInfo
6102             {
6103                 Version = Version.Parse(msgHeader[0]),
6104                 DownloadUri = new Uri(msgHeader[1]),
6105                 ReleaseNote = msgBody,
6106             };
6107         }
6108
6109         private async Task CheckNewVersion(bool startup = false)
6110         {
6111             if (ApplicationSettings.VersionInfoUrl == null)
6112                 return; // 更新チェック無効化
6113
6114             try
6115             {
6116                 var versionInfo = await this.GetVersionInfoAsync();
6117
6118                 if (versionInfo.Version <= Version.Parse(MyCommon.FileVersion))
6119                 {
6120                     // 更新不要
6121                     if (!startup)
6122                     {
6123                         var msgtext = string.Format(Properties.Resources.CheckNewVersionText7,
6124                             MyCommon.GetReadableVersion(), MyCommon.GetReadableVersion(versionInfo.Version));
6125                         msgtext = MyCommon.ReplaceAppName(msgtext);
6126
6127                         MessageBox.Show(msgtext,
6128                             MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6129                             MessageBoxButtons.OK, MessageBoxIcon.Information);
6130                     }
6131                     return;
6132                 }
6133
6134                 using (var dialog = new UpdateDialog())
6135                 {
6136                     dialog.SummaryText = string.Format(Properties.Resources.CheckNewVersionText3,
6137                         MyCommon.GetReadableVersion(versionInfo.Version));
6138                     dialog.DetailsText = versionInfo.ReleaseNote;
6139
6140                     if (dialog.ShowDialog(this) == DialogResult.Yes)
6141                     {
6142                         await this.OpenUriInBrowserAsync(versionInfo.DownloadUri.OriginalString);
6143                     }
6144                 }
6145             }
6146             catch (Exception)
6147             {
6148                 this.StatusLabel.Text = Properties.Resources.CheckNewVersionText9;
6149                 if (!startup)
6150                 {
6151                     MessageBox.Show(Properties.Resources.CheckNewVersionText10,
6152                         MyCommon.ReplaceAppName(Properties.Resources.CheckNewVersionText2),
6153                         MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
6154                 }
6155             }
6156         }
6157
6158         private async Task Colorize()
6159         {
6160             _colorize = false;
6161             await this.DispSelectedPost();
6162             //件数関連の場合、タイトル即時書き換え
6163             if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
6164                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
6165                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
6166                this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
6167             {
6168                 SetMainWindowTitle();
6169             }
6170             if (!StatusLabelUrl.Text.StartsWith("http")) SetStatusLabelUrl();
6171             foreach (TabPage tb in ListTab.TabPages)
6172             {
6173                 if (_statuses.Tabs[tb.Text].UnreadCount == 0)
6174                 {
6175                     if (this._cfgCommon.TabIconDisp)
6176                     {
6177                         if (tb.ImageIndex == 0) tb.ImageIndex = -1;
6178                     }
6179                 }
6180             }
6181             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
6182         }
6183
6184         public string createDetailHtml(string orgdata)
6185         {
6186             if (this._cfgLocal.UseTwemoji)
6187                 orgdata = EmojiFormatter.ReplaceEmojiToImg(orgdata);
6188
6189             return detailHtmlFormatHeader + orgdata + detailHtmlFormatFooter;
6190         }
6191
6192         private async void DisplayItemImage_Downloaded(object sender, EventArgs e)
6193         {
6194             if (sender.Equals(displayItem))
6195             {
6196                 this.ClearUserPicture();
6197
6198                 var img = displayItem.Image;
6199                 try
6200                 {
6201                     if (img != null)
6202                         img = await img.CloneAsync();
6203
6204                     UserPicture.Image = img;
6205                 }
6206                 catch (Exception)
6207                 {
6208                     UserPicture.ShowErrorImage();
6209                 }
6210             }
6211         }
6212
6213         private Task DispSelectedPost()
6214         {
6215             return this.DispSelectedPost(false);
6216         }
6217
6218         private PostClass displayPost = new PostClass();
6219
6220         /// <summary>
6221         /// サムネイル表示に使用する CancellationToken の生成元
6222         /// </summary>
6223         private CancellationTokenSource thumbnailTokenSource = null;
6224
6225         private async Task DispSelectedPost(bool forceupdate)
6226         {
6227             if (_curList.SelectedIndices.Count == 0 || _curPost == null)
6228                 return;
6229
6230             var oldDisplayPost = this.displayPost;
6231             this.displayPost = this._curPost;
6232
6233             if (!forceupdate && this._curPost.Equals(oldDisplayPost))
6234                 return;
6235
6236             if (displayItem != null)
6237             {
6238                 displayItem.ImageDownloaded -= this.DisplayItemImage_Downloaded;
6239                 displayItem = null;
6240             }
6241             displayItem = (ImageListViewItem)_curList.Items[_curList.SelectedIndices[0]];
6242             displayItem.ImageDownloaded += this.DisplayItemImage_Downloaded;
6243
6244             using (ControlTransaction.Update(this.TableLayoutPanel1))
6245             {
6246                 SourceLinkLabel.Text = this._curPost.Source;
6247                 SourceLinkLabel.Tag = this._curPost.SourceUri;
6248                 SourceLinkLabel.TabStop = false; // Text を更新すると勝手に true にされる
6249
6250                 string nameText;
6251                 if (_curPost.IsDm)
6252                 {
6253                     if (_curPost.IsOwl)
6254                         nameText = "DM FROM <- ";
6255                     else
6256                         nameText = "DM TO -> ";
6257                 }
6258                 else
6259                 {
6260                     nameText = "";
6261                 }
6262                 nameText += _curPost.ScreenName + "/" + _curPost.Nickname;
6263                 if (_curPost.RetweetedId != null)
6264                     nameText += " (RT:" + _curPost.RetweetedBy + ")";
6265
6266                 NameLabel.Text = nameText;
6267                 NameLabel.Tag = _curPost.ScreenName;
6268
6269                 var nameForeColor = SystemColors.ControlText;
6270                 if (_curPost.IsOwl && (this._cfgCommon.OneWayLove || _curPost.IsDm))
6271                     nameForeColor = this._clOWL;
6272                 if (_curPost.RetweetedId != null)
6273                     nameForeColor = this._clRetweet;
6274                 if (_curPost.IsFav)
6275                     nameForeColor = this._clFav;
6276                 NameLabel.ForeColor = nameForeColor;
6277
6278                 this.ClearUserPicture();
6279
6280                 if (!string.IsNullOrEmpty(_curPost.ImageUrl))
6281                 {
6282                     var image = IconCache.TryGetFromCache(_curPost.ImageUrl);
6283                     try
6284                     {
6285                         UserPicture.Image = image?.Clone();
6286                     }
6287                     catch (Exception)
6288                     {
6289                         UserPicture.ShowErrorImage();
6290                     }
6291                 }
6292
6293                 DateTimeLabel.Text = _curPost.CreatedAt.ToString();
6294             }
6295
6296             if (DumpPostClassToolStripMenuItem.Checked)
6297             {
6298                 StringBuilder sb = new StringBuilder(512);
6299
6300                 sb.Append("-----Start PostClass Dump<br>");
6301                 sb.AppendFormat("TextFromApi           : {0}<br>", _curPost.TextFromApi);
6302                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.TextFromApi);
6303                 sb.AppendFormat("StatusId             : {0}<br>", _curPost.StatusId.ToString());
6304                 //sb.AppendFormat("ImageIndex     : {0}<br>", _curPost.ImageIndex.ToString());
6305                 sb.AppendFormat("ImageUrl       : {0}<br>", _curPost.ImageUrl);
6306                 sb.AppendFormat("InReplyToStatusId    : {0}<br>", _curPost.InReplyToStatusId.ToString());
6307                 sb.AppendFormat("InReplyToUser  : {0}<br>", _curPost.InReplyToUser);
6308                 sb.AppendFormat("IsDM           : {0}<br>", _curPost.IsDm.ToString());
6309                 sb.AppendFormat("IsFav          : {0}<br>", _curPost.IsFav.ToString());
6310                 sb.AppendFormat("IsMark         : {0}<br>", _curPost.IsMark.ToString());
6311                 sb.AppendFormat("IsMe           : {0}<br>", _curPost.IsMe.ToString());
6312                 sb.AppendFormat("IsOwl          : {0}<br>", _curPost.IsOwl.ToString());
6313                 sb.AppendFormat("IsProtect      : {0}<br>", _curPost.IsProtect.ToString());
6314                 sb.AppendFormat("IsRead         : {0}<br>", _curPost.IsRead.ToString());
6315                 sb.AppendFormat("IsReply        : {0}<br>", _curPost.IsReply.ToString());
6316
6317                 foreach (string nm in _curPost.ReplyToList)
6318                 {
6319                     sb.AppendFormat("ReplyToList    : {0}<br>", nm);
6320                 }
6321
6322                 sb.AppendFormat("ScreenName           : {0}<br>", _curPost.ScreenName);
6323                 sb.AppendFormat("NickName       : {0}<br>", _curPost.Nickname);
6324                 sb.AppendFormat("Text   : {0}<br>", _curPost.Text);
6325                 sb.AppendFormat("(PlainText)    : <xmp>{0}</xmp><br>", _curPost.Text);
6326                 sb.AppendFormat("CreatedAt          : {0}<br>", _curPost.CreatedAt.ToString());
6327                 sb.AppendFormat("Source         : {0}<br>", _curPost.Source);
6328                 sb.AppendFormat("UserId            : {0}<br>", _curPost.UserId);
6329                 sb.AppendFormat("FilterHit      : {0}<br>", _curPost.FilterHit);
6330                 sb.AppendFormat("RetweetedBy    : {0}<br>", _curPost.RetweetedBy);
6331                 sb.AppendFormat("RetweetedId    : {0}<br>", _curPost.RetweetedId);
6332
6333                 sb.AppendFormat("Media.Count    : {0}<br>", _curPost.Media.Count);
6334                 if (_curPost.Media.Count > 0)
6335                 {
6336                     for (int i = 0; i < _curPost.Media.Count; i++)
6337                     {
6338                         var info = _curPost.Media[i];
6339                         sb.AppendFormat("Media[{0}].Url         : {1}<br>", i, info.Url);
6340                         sb.AppendFormat("Media[{0}].VideoUrl    : {1}<br>", i, info.VideoUrl ?? "---");
6341                     }
6342                 }
6343                 sb.Append("-----End PostClass Dump<br>");
6344
6345                 PostBrowser.DocumentText = detailHtmlFormatHeader + sb.ToString() + detailHtmlFormatFooter;
6346                 return;
6347             }
6348
6349             var loadTasks = new List<Task>();
6350
6351             // 同じIDのツイートであれば WebBrowser とサムネイルの更新を行わない
6352             // (同一ツイートの RT は文面が同じであるため同様に更新しない)
6353             if (_curPost.StatusId != oldDisplayPost.StatusId)
6354             {
6355                 using (ControlTransaction.Update(this.PostBrowser))
6356                 {
6357                     this.PostBrowser.DocumentText =
6358                         this.createDetailHtml(_curPost.IsDeleted ? "(DELETED)" : _curPost.Text);
6359
6360                     this.PostBrowser.Document.Window.ScrollTo(0, 0);
6361                 }
6362
6363                 this.SplitContainer3.Panel2Collapsed = true;
6364
6365                 if (this._cfgCommon.PreviewEnable)
6366                 {
6367                     var oldTokenSource = Interlocked.Exchange(ref this.thumbnailTokenSource, new CancellationTokenSource());
6368                     oldTokenSource?.Cancel();
6369
6370                     var token = this.thumbnailTokenSource.Token;
6371                     loadTasks.Add(this.tweetThumbnail1.ShowThumbnailAsync(_curPost, token));
6372                 }
6373
6374                 loadTasks.Add(this.AppendQuoteTweetAsync(this._curPost));
6375             }
6376
6377             try
6378             {
6379                 await Task.WhenAll(loadTasks);
6380             }
6381             catch (OperationCanceledException) { }
6382         }
6383
6384         /// <summary>
6385         /// 発言詳細欄のツイートURLを展開する
6386         /// </summary>
6387         private async Task AppendQuoteTweetAsync(PostClass post)
6388         {
6389             var statusIds = post.QuoteStatusIds;
6390             if (statusIds.Length == 0)
6391                 return;
6392
6393             // 「読み込み中」テキストを表示
6394             var loadingQuoteHtml = statusIds.Select(x => FormatQuoteTweetHtml(x, Properties.Resources.LoadingText));
6395             var body = post.Text + string.Concat(loadingQuoteHtml);
6396
6397             using (ControlTransaction.Update(this.PostBrowser))
6398                 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6399
6400             // 引用ツイートを読み込み
6401             var quoteHtmls = await Task.WhenAll(statusIds.Select(x => this.CreateQuoteTweetHtml(x)));
6402
6403             // 非同期処理中に表示中のツイートが変わっていたらキャンセルされたものと扱う
6404             if (this._curPost != post || this._curPost.IsDeleted)
6405                 return;
6406
6407             body = post.Text + string.Concat(quoteHtmls);
6408
6409             using (ControlTransaction.Update(this.PostBrowser))
6410                 this.PostBrowser.DocumentText = this.createDetailHtml(body);
6411         }
6412
6413         private async Task<string> CreateQuoteTweetHtml(long statusId)
6414         {
6415             PostClass post = this._statuses[statusId];
6416             if (post == null)
6417             {
6418                 try
6419                 {
6420                     post = await Task.Run(() => this.tw.GetStatusApi(false, statusId))
6421                         .ConfigureAwait(false);
6422                 }
6423                 catch (WebApiException ex)
6424                 {
6425                     return FormatQuoteTweetHtml(statusId, WebUtility.HtmlEncode(ex.Message));
6426                 }
6427
6428                 post.IsRead = true;
6429                 if (!this._statuses.AddQuoteTweet(post))
6430                     return FormatQuoteTweetHtml(statusId, "This Tweet is unavailable.");
6431             }
6432
6433             return FormatQuoteTweetHtml(post);
6434         }
6435
6436         internal static string FormatQuoteTweetHtml(PostClass post)
6437         {
6438             var innerHtml = "<p>" + StripLinkTagHtml(post.Text) + "</p>" +
6439                 " &mdash; " + WebUtility.HtmlEncode(post.Nickname) +
6440                 " (@" + WebUtility.HtmlEncode(post.ScreenName) + ") " +
6441                 WebUtility.HtmlEncode(post.CreatedAt.ToString());
6442
6443             return FormatQuoteTweetHtml(post.StatusId, innerHtml);
6444         }
6445
6446         internal static string FormatQuoteTweetHtml(long statusId, string innerHtml)
6447         {
6448             return "<a class=\"quote-tweet-link\" href=\"//opentween/status/" + statusId + "\">" +
6449                 "<blockquote class=\"quote-tweet\">" + innerHtml + "</blockquote>" +
6450                 "</a>";
6451         }
6452
6453         /// <summary>
6454         /// 指定されたHTMLからリンクを除去します
6455         /// </summary>
6456         internal static string StripLinkTagHtml(string html)
6457         {
6458             // a 要素はネストされていない前提の正規表現パターン
6459             return Regex.Replace(html, @"<a[^>]*>(.*?)</a>", "$1");
6460         }
6461
6462         private async void MatomeMenuItem_Click(object sender, EventArgs e)
6463         {
6464             await this.OpenApplicationWebsite();
6465         }
6466
6467         private async Task OpenApplicationWebsite()
6468         {
6469             await this.OpenUriInBrowserAsync(ApplicationSettings.WebsiteUrl);
6470         }
6471
6472         private async void ShortcutKeyListMenuItem_Click(object sender, EventArgs e)
6473         {
6474             await this.OpenUriInBrowserAsync(ApplicationSettings.ShortcutKeyUrl);
6475         }
6476
6477         private async void ListTab_KeyDown(object sender, KeyEventArgs e)
6478         {
6479             if (ListTab.SelectedTab != null)
6480             {
6481                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6482                 {
6483                     Control pnl = ListTab.SelectedTab.Controls["panelSearch"];
6484                     if (pnl.Controls["comboSearch"].Focused ||
6485                         pnl.Controls["comboLang"].Focused ||
6486                         pnl.Controls["buttonSearch"].Focused) return;
6487                 }
6488
6489                 if (e.Control || e.Shift || e.Alt)
6490                     this._anchorFlag = false;
6491
6492                 Task asyncTask;
6493                 if (CommonKeyDown(e.KeyData, FocusedControl.ListTab, out asyncTask))
6494                 {
6495                     e.Handled = true;
6496                     e.SuppressKeyPress = true;
6497                 }
6498
6499                 if (asyncTask != null)
6500                     await asyncTask;
6501             }
6502         }
6503
6504         private ShortcutCommand[] shortcutCommands = new ShortcutCommand[0];
6505
6506         private void InitializeShortcuts()
6507         {
6508             this.shortcutCommands = new[]
6509             {
6510                 // リストのカーソル移動関係(上下キー、PageUp/Downに該当)
6511                 ShortcutCommand.Create(Keys.J, Keys.Control | Keys.J, Keys.Shift | Keys.J, Keys.Control | Keys.Shift | Keys.J)
6512                     .FocusedOn(FocusedControl.ListTab)
6513                     .Do(() => SendKeys.Send("{DOWN}")),
6514
6515                 ShortcutCommand.Create(Keys.K, Keys.Control | Keys.K, Keys.Shift | Keys.K, Keys.Control | Keys.Shift | Keys.K)
6516                     .FocusedOn(FocusedControl.ListTab)
6517                     .Do(() => SendKeys.Send("{UP}")),
6518
6519                 ShortcutCommand.Create(Keys.F, Keys.Shift | Keys.F)
6520                     .FocusedOn(FocusedControl.ListTab)
6521                     .Do(() => SendKeys.Send("{PGDN}")),
6522
6523                 ShortcutCommand.Create(Keys.B, Keys.Shift | Keys.B)
6524                     .FocusedOn(FocusedControl.ListTab)
6525                     .Do(() => SendKeys.Send("{PGUP}")),
6526
6527                 ShortcutCommand.Create(Keys.F1)
6528                     .Do(() => this.OpenApplicationWebsite()),
6529
6530                 ShortcutCommand.Create(Keys.F3)
6531                     .Do(() => this.MenuItemSearchNext_Click(null, null)),
6532
6533                 ShortcutCommand.Create(Keys.F5)
6534                     .Do(() => this.DoRefresh()),
6535
6536                 ShortcutCommand.Create(Keys.F6)
6537                     .Do(() => this.GetReplyAsync()),
6538
6539                 ShortcutCommand.Create(Keys.F7)
6540                     .Do(() => this.GetDirectMessagesAsync()),
6541
6542                 ShortcutCommand.Create(Keys.Space, Keys.ProcessKey)
6543                     .NotFocusedOn(FocusedControl.StatusText)
6544                     .Do(() => { this._anchorFlag = false; this.JumpUnreadMenuItem_Click(null, null); }),
6545
6546                 ShortcutCommand.Create(Keys.G)
6547                     .NotFocusedOn(FocusedControl.StatusText)
6548                     .Do(() => { this._anchorFlag = false; this.ShowRelatedStatusesMenuItem_Click(null, null); }),
6549
6550                 ShortcutCommand.Create(Keys.Right, Keys.N)
6551                     .FocusedOn(FocusedControl.ListTab)
6552                     .Do(() => this.GoRelPost(forward: true)),
6553
6554                 ShortcutCommand.Create(Keys.Left, Keys.P)
6555                     .FocusedOn(FocusedControl.ListTab)
6556                     .Do(() => this.GoRelPost(forward: false)),
6557
6558                 ShortcutCommand.Create(Keys.OemPeriod)
6559                     .FocusedOn(FocusedControl.ListTab)
6560                     .Do(() => this.GoAnchor()),
6561
6562                 ShortcutCommand.Create(Keys.I)
6563                     .FocusedOn(FocusedControl.ListTab)
6564                     .OnlyWhen(() => this.StatusText.Enabled)
6565                     .Do(() => this.StatusText.Focus()),
6566
6567                 ShortcutCommand.Create(Keys.Enter)
6568                     .FocusedOn(FocusedControl.ListTab)
6569                     .Do(() => this.MakeReplyOrDirectStatus()),
6570
6571                 ShortcutCommand.Create(Keys.R)
6572                     .FocusedOn(FocusedControl.ListTab)
6573                     .Do(() => this.DoRefresh()),
6574
6575                 ShortcutCommand.Create(Keys.L)
6576                     .FocusedOn(FocusedControl.ListTab)
6577                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: true); }),
6578
6579                 ShortcutCommand.Create(Keys.H)
6580                     .FocusedOn(FocusedControl.ListTab)
6581                     .Do(() => { this._anchorFlag = false; this.GoPost(forward: false); }),
6582
6583                 ShortcutCommand.Create(Keys.Z, Keys.Oemcomma)
6584                     .FocusedOn(FocusedControl.ListTab)
6585                     .Do(() => { this._anchorFlag = false; this.MoveTop(); }),
6586
6587                 ShortcutCommand.Create(Keys.S)
6588                     .FocusedOn(FocusedControl.ListTab)
6589                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: true); }),
6590
6591                 ShortcutCommand.Create(Keys.A)
6592                     .FocusedOn(FocusedControl.ListTab)
6593                     .Do(() => { this._anchorFlag = false; this.GoNextTab(forward: false); }),
6594
6595                 // ] in_reply_to参照元へ戻る
6596                 ShortcutCommand.Create(Keys.Oem4)
6597                     .FocusedOn(FocusedControl.ListTab)
6598                     .Do(() => { this._anchorFlag = false; return this.GoInReplyToPostTree(); }),
6599
6600                 // [ in_reply_toへジャンプ
6601                 ShortcutCommand.Create(Keys.Oem6)
6602                     .FocusedOn(FocusedControl.ListTab)
6603                     .Do(() => { this._anchorFlag = false; this.GoBackInReplyToPostTree(); }),
6604
6605                 ShortcutCommand.Create(Keys.Escape)
6606                     .FocusedOn(FocusedControl.ListTab)
6607                     .Do(() => {
6608                         this._anchorFlag = false;
6609                         if (ListTab.SelectedTab != null)
6610                         {
6611                             var tabtype = _statuses.Tabs[ListTab.SelectedTab.Text].TabType;
6612                             if (tabtype == MyCommon.TabUsageType.Related || tabtype == MyCommon.TabUsageType.UserTimeline || tabtype == MyCommon.TabUsageType.PublicSearch || tabtype == MyCommon.TabUsageType.SearchResults)
6613                             {
6614                                 var relTp = ListTab.SelectedTab;
6615                                 RemoveSpecifiedTab(relTp.Text, false);
6616                                 SaveConfigsTabs();
6617                             }
6618                         }
6619                     }),
6620
6621                 // 上下キー, PageUp/Downキー, Home/Endキー は既定の動作を残しつつアンカー初期化
6622                 ShortcutCommand.Create(Keys.Up, Keys.Down, Keys.PageUp, Keys.PageDown, Keys.Home, Keys.End)
6623                     .FocusedOn(FocusedControl.ListTab)
6624                     .Do(() => this._anchorFlag = false, preventDefault: false),
6625
6626                 // PreviewKeyDownEventArgs.IsInputKey を true にしてスクロールを発生させる
6627                 ShortcutCommand.Create(Keys.Up, Keys.Down)
6628                     .FocusedOn(FocusedControl.PostBrowser)
6629                     .Do(() => { }),
6630
6631                 ShortcutCommand.Create(Keys.Control | Keys.R)
6632                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true)),
6633
6634                 ShortcutCommand.Create(Keys.Control | Keys.D)
6635                     .Do(() => this.doStatusDelete()),
6636
6637                 ShortcutCommand.Create(Keys.Control | Keys.M)
6638                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: false)),
6639
6640                 ShortcutCommand.Create(Keys.Control | Keys.S)
6641                     .Do(() => this.FavoriteChange(FavAdd: true)),
6642
6643                 ShortcutCommand.Create(Keys.Control | Keys.I)
6644                     .Do(() => this.doRepliedStatusOpen()),
6645
6646                 ShortcutCommand.Create(Keys.Control | Keys.Q)
6647                     .Do(() => this.doQuoteOfficial()),
6648
6649                 ShortcutCommand.Create(Keys.Control | Keys.B)
6650                     .Do(() => this.ReadedStripMenuItem_Click(null, null)),
6651
6652                 ShortcutCommand.Create(Keys.Control | Keys.T)
6653                     .Do(() => this.HashManageMenuItem_Click(null, null)),
6654
6655                 ShortcutCommand.Create(Keys.Control | Keys.L)
6656                     .Do(() => this.UrlConvertAutoToolStripMenuItem_Click(null, null)),
6657
6658                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6659                     .NotFocusedOn(FocusedControl.PostBrowser)
6660                     .Do(() => this.MultiLineMenuItem_Click(null, null)),
6661
6662                 ShortcutCommand.Create(Keys.Control | Keys.F)
6663                     .Do(() => this.MenuItemSubSearch_Click(null, null)),
6664
6665                 ShortcutCommand.Create(Keys.Control | Keys.U)
6666                     .Do(() => this.ShowUserTimeline()),
6667
6668                 ShortcutCommand.Create(Keys.Control | Keys.H)
6669                     .Do(() => this.MoveToHomeToolStripMenuItem_Click(null, null)),
6670
6671                 ShortcutCommand.Create(Keys.Control | Keys.G)
6672                     .Do(() => this.MoveToFavToolStripMenuItem_Click(null, null)),
6673
6674                 ShortcutCommand.Create(Keys.Control | Keys.O)
6675                     .Do(() => this.StatusOpenMenuItem_Click(null, null)),
6676
6677                 ShortcutCommand.Create(Keys.Control | Keys.E)
6678                     .Do(() => this.OpenURLMenuItem_Click(null, null)),
6679
6680                 ShortcutCommand.Create(Keys.Control | Keys.Home, Keys.Control | Keys.End)
6681                     .FocusedOn(FocusedControl.ListTab)
6682                     .Do(() => this._colorize = true, preventDefault: false),
6683
6684                 ShortcutCommand.Create(Keys.Control | Keys.N)
6685                     .FocusedOn(FocusedControl.ListTab)
6686                     .Do(() => this.GoNextTab(forward: true)),
6687
6688                 ShortcutCommand.Create(Keys.Control | Keys.P)
6689                     .FocusedOn(FocusedControl.ListTab)
6690                     .Do(() => this.GoNextTab(forward: false)),
6691
6692                 ShortcutCommand.Create(Keys.Control | Keys.C)
6693                     .FocusedOn(FocusedControl.ListTab)
6694                     .Do(() => this.CopyStot()),
6695
6696                 ShortcutCommand.Create(Keys.Control | Keys.C)
6697                     .FocusedOn(FocusedControl.ListTab)
6698                     .Do(() => this.CopyStot()),
6699
6700                 // タブダイレクト選択(Ctrl+1~8,Ctrl+9)
6701                 ShortcutCommand.Create(Keys.Control | Keys.D1)
6702                     .FocusedOn(FocusedControl.ListTab)
6703                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 1)
6704                     .Do(() => this.ListTab.SelectedIndex = 0),
6705
6706                 ShortcutCommand.Create(Keys.Control | Keys.D2)
6707                     .FocusedOn(FocusedControl.ListTab)
6708                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 2)
6709                     .Do(() => this.ListTab.SelectedIndex = 1),
6710
6711                 ShortcutCommand.Create(Keys.Control | Keys.D3)
6712                     .FocusedOn(FocusedControl.ListTab)
6713                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 3)
6714                     .Do(() => this.ListTab.SelectedIndex = 2),
6715
6716                 ShortcutCommand.Create(Keys.Control | Keys.D4)
6717                     .FocusedOn(FocusedControl.ListTab)
6718                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 4)
6719                     .Do(() => this.ListTab.SelectedIndex = 3),
6720
6721                 ShortcutCommand.Create(Keys.Control | Keys.D5)
6722                     .FocusedOn(FocusedControl.ListTab)
6723                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 5)
6724                     .Do(() => this.ListTab.SelectedIndex = 4),
6725
6726                 ShortcutCommand.Create(Keys.Control | Keys.D6)
6727                     .FocusedOn(FocusedControl.ListTab)
6728                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 6)
6729                     .Do(() => this.ListTab.SelectedIndex = 5),
6730
6731                 ShortcutCommand.Create(Keys.Control | Keys.D7)
6732                     .FocusedOn(FocusedControl.ListTab)
6733                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 7)
6734                     .Do(() => this.ListTab.SelectedIndex = 6),
6735
6736                 ShortcutCommand.Create(Keys.Control | Keys.D8)
6737                     .FocusedOn(FocusedControl.ListTab)
6738                     .OnlyWhen(() => this.ListTab.TabPages.Count >= 8)
6739                     .Do(() => this.ListTab.SelectedIndex = 7),
6740
6741                 ShortcutCommand.Create(Keys.Control | Keys.D9)
6742                     .FocusedOn(FocusedControl.ListTab)
6743                     .Do(() => this.ListTab.SelectedIndex = this.ListTab.TabPages.Count - 1),
6744
6745                 ShortcutCommand.Create(Keys.Control | Keys.A)
6746                     .FocusedOn(FocusedControl.StatusText)
6747                     .Do(() => this.StatusText.SelectAll()),
6748
6749                 ShortcutCommand.Create(Keys.Control | Keys.V)
6750                     .FocusedOn(FocusedControl.StatusText)
6751                     .Do(() => this.ProcClipboardFromStatusTextWhenCtrlPlusV()),
6752
6753                 ShortcutCommand.Create(Keys.Control | Keys.Up)
6754                     .FocusedOn(FocusedControl.StatusText)
6755                     .Do(() => {
6756                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6757                         {
6758                             var inReplyToStatusId = this.inReplyTo?.Item1;
6759                             var inReplyToScreenName = this.inReplyTo?.Item2;
6760                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6761                         }
6762                         _hisIdx -= 1;
6763                         if (_hisIdx < 0) _hisIdx = 0;
6764
6765                         var historyItem = this._history[this._hisIdx];
6766                         StatusText.Text = historyItem.status;
6767                         StatusText.SelectionStart = StatusText.Text.Length;
6768                         if (historyItem.inReplyToId != null)
6769                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6770                         else
6771                             this.inReplyTo = null;
6772                     }),
6773
6774                 ShortcutCommand.Create(Keys.Control | Keys.Down)
6775                     .FocusedOn(FocusedControl.StatusText)
6776                     .Do(() => {
6777                         if (!string.IsNullOrWhiteSpace(StatusText.Text))
6778                         {
6779                             var inReplyToStatusId = this.inReplyTo?.Item1;
6780                             var inReplyToScreenName = this.inReplyTo?.Item2;
6781                             _history[_hisIdx] = new PostingStatus(StatusText.Text, inReplyToStatusId, inReplyToScreenName);
6782                         }
6783                         _hisIdx += 1;
6784                         if (_hisIdx > _history.Count - 1) _hisIdx = _history.Count - 1;
6785
6786                         var historyItem = this._history[this._hisIdx];
6787                         StatusText.Text = historyItem.status;
6788                         StatusText.SelectionStart = StatusText.Text.Length;
6789                         if (historyItem.inReplyToId != null)
6790                             this.inReplyTo = Tuple.Create(historyItem.inReplyToId.Value, historyItem.inReplyToName);
6791                         else
6792                             this.inReplyTo = null;
6793                     }),
6794
6795                 ShortcutCommand.Create(Keys.Control | Keys.PageUp, Keys.Control | Keys.P)
6796                     .FocusedOn(FocusedControl.StatusText)
6797                     .Do(() => {
6798                         if (ListTab.SelectedIndex == 0)
6799                         {
6800                             ListTab.SelectedIndex = ListTab.TabCount - 1;
6801                         }
6802                         else
6803                         {
6804                             ListTab.SelectedIndex -= 1;
6805                         }
6806                         StatusText.Focus();
6807                     }),
6808
6809                 ShortcutCommand.Create(Keys.Control | Keys.PageDown, Keys.Control | Keys.N)
6810                     .FocusedOn(FocusedControl.StatusText)
6811                     .Do(() => {
6812                         if (ListTab.SelectedIndex == ListTab.TabCount - 1)
6813                         {
6814                             ListTab.SelectedIndex = 0;
6815                         }
6816                         else
6817                         {
6818                             ListTab.SelectedIndex += 1;
6819                         }
6820                         StatusText.Focus();
6821                     }),
6822
6823                 ShortcutCommand.Create(Keys.Control | Keys.Y)
6824                     .FocusedOn(FocusedControl.PostBrowser)
6825                     .Do(() => {
6826                         MultiLineMenuItem.Checked = !MultiLineMenuItem.Checked;
6827                         MultiLineMenuItem_Click(null, null);
6828                     }),
6829
6830                 ShortcutCommand.Create(Keys.Shift | Keys.F3)
6831                     .Do(() => this.MenuItemSearchPrev_Click(null, null)),
6832
6833                 ShortcutCommand.Create(Keys.Shift | Keys.F5)
6834                     .Do(() => this.DoRefreshMore()),
6835
6836                 ShortcutCommand.Create(Keys.Shift | Keys.F6)
6837                     .Do(() => this.GetReplyAsync(loadMore: true)),
6838
6839                 ShortcutCommand.Create(Keys.Shift | Keys.F7)
6840                     .Do(() => this.GetDirectMessagesAsync(loadMore: true)),
6841
6842                 ShortcutCommand.Create(Keys.Shift | Keys.R)
6843                     .NotFocusedOn(FocusedControl.StatusText)
6844                     .Do(() => this.DoRefreshMore()),
6845
6846                 ShortcutCommand.Create(Keys.Shift | Keys.H)
6847                     .FocusedOn(FocusedControl.ListTab)
6848                     .Do(() => this.GoTopEnd(GoTop: true)),
6849
6850                 ShortcutCommand.Create(Keys.Shift | Keys.L)
6851                     .FocusedOn(FocusedControl.ListTab)
6852                     .Do(() => this.GoTopEnd(GoTop: false)),
6853
6854                 ShortcutCommand.Create(Keys.Shift | Keys.M)
6855                     .FocusedOn(FocusedControl.ListTab)
6856                     .Do(() => this.GoMiddle()),
6857
6858                 ShortcutCommand.Create(Keys.Shift | Keys.G)
6859                     .FocusedOn(FocusedControl.ListTab)
6860                     .Do(() => this.GoLast()),
6861
6862                 ShortcutCommand.Create(Keys.Shift | Keys.Z)
6863                     .FocusedOn(FocusedControl.ListTab)
6864                     .Do(() => this.MoveMiddle()),
6865
6866                 ShortcutCommand.Create(Keys.Shift | Keys.Oem4)
6867                     .FocusedOn(FocusedControl.ListTab)
6868                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: false)),
6869
6870                 ShortcutCommand.Create(Keys.Shift | Keys.Oem6)
6871                     .FocusedOn(FocusedControl.ListTab)
6872                     .Do(() => this.GoBackInReplyToPostTree(parallel: true, isForward: true)),
6873
6874                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6875                 ShortcutCommand.Create(Keys.Shift | Keys.Right, Keys.Shift | Keys.N)
6876                     .FocusedOn(FocusedControl.ListTab)
6877                     .Do(() => this.GoFav(forward: true)),
6878
6879                 // お気に入り前後ジャンプ(SHIFT+N←/P→)
6880                 ShortcutCommand.Create(Keys.Shift | Keys.Left, Keys.Shift | Keys.P)
6881                     .FocusedOn(FocusedControl.ListTab)
6882                     .Do(() => this.GoFav(forward: false)),
6883
6884                 ShortcutCommand.Create(Keys.Shift | Keys.Space)
6885                     .FocusedOn(FocusedControl.ListTab)
6886                     .Do(() => this.GoBackSelectPostChain()),
6887
6888                 ShortcutCommand.Create(Keys.Alt | Keys.R)
6889                     .Do(() => this.doReTweetOfficial(isConfirm: true)),
6890
6891                 ShortcutCommand.Create(Keys.Alt | Keys.P)
6892                     .OnlyWhen(() => this._curPost != null)
6893                     .Do(() => this.doShowUserStatus(_curPost.ScreenName, ShowInputDialog: false)),
6894
6895                 ShortcutCommand.Create(Keys.Alt | Keys.Up)
6896                     .Do(() => this.ScrollDownPostBrowser(forward: false)),
6897
6898                 ShortcutCommand.Create(Keys.Alt | Keys.Down)
6899                     .Do(() => this.ScrollDownPostBrowser(forward: true)),
6900
6901                 ShortcutCommand.Create(Keys.Alt | Keys.PageUp)
6902                     .Do(() => this.PageDownPostBrowser(forward: false)),
6903
6904                 ShortcutCommand.Create(Keys.Alt | Keys.PageDown)
6905                     .Do(() => this.PageDownPostBrowser(forward: true)),
6906
6907                 // 別タブの同じ書き込みへ(ALT+←/→)
6908                 ShortcutCommand.Create(Keys.Alt | Keys.Right)
6909                     .FocusedOn(FocusedControl.ListTab)
6910                     .Do(() => this.GoSamePostToAnotherTab(left: false)),
6911
6912                 ShortcutCommand.Create(Keys.Alt | Keys.Left)
6913                     .FocusedOn(FocusedControl.ListTab)
6914                     .Do(() => this.GoSamePostToAnotherTab(left: true)),
6915
6916                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.R)
6917                     .Do(() => this.MakeReplyOrDirectStatus(isAuto: false, isReply: true, isAll: true)),
6918
6919                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.C)
6920                     .Do(() => this.CopyIdUri()),
6921
6922                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.F)
6923                     .OnlyWhen(() => this.ListTab.SelectedTab != null &&
6924                         this._statuses.Tabs[this.ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
6925                     .Do(() => this.ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus()),
6926
6927                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.S)
6928                     .Do(() => this.FavoriteChange(FavAdd: false)),
6929
6930                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.B)
6931                     .Do(() => this.UnreadStripMenuItem_Click(null, null)),
6932
6933                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.T)
6934                     .Do(() => this.HashToggleMenuItem_Click(null, null)),
6935
6936                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.P)
6937                     .Do(() => this.ImageSelectMenuItem_Click(null, null)),
6938
6939                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.H)
6940                     .Do(() => this.doMoveToRTHome()),
6941
6942                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.O)
6943                     .Do(() => this.FavorareMenuItem_Click(null, null)),
6944
6945                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Up)
6946                     .FocusedOn(FocusedControl.StatusText)
6947                     .Do(() => {
6948                         if (_curList != null && _curList.VirtualListSize != 0 &&
6949                                     _curList.SelectedIndices.Count > 0 && _curList.SelectedIndices[0] > 0)
6950                         {
6951                             var idx = _curList.SelectedIndices[0] - 1;
6952                             SelectListItem(_curList, idx);
6953                             _curList.EnsureVisible(idx);
6954                         }
6955                     }),
6956
6957                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Down)
6958                     .FocusedOn(FocusedControl.StatusText)
6959                     .Do(() => {
6960                         if (_curList != null && _curList.VirtualListSize != 0 && _curList.SelectedIndices.Count > 0
6961                                     && _curList.SelectedIndices[0] < _curList.VirtualListSize - 1)
6962                         {
6963                             var idx = _curList.SelectedIndices[0] + 1;
6964                             SelectListItem(_curList, idx);
6965                             _curList.EnsureVisible(idx);
6966                         }
6967                     }),
6968
6969                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.Space)
6970                     .FocusedOn(FocusedControl.StatusText)
6971                     .Do(() => {
6972                         if (StatusText.SelectionStart > 0)
6973                         {
6974                             int endidx = StatusText.SelectionStart - 1;
6975                             string startstr = "";
6976                             for (int i = StatusText.SelectionStart - 1; i >= 0; i--)
6977                             {
6978                                 char c = StatusText.Text[i];
6979                                 if (Char.IsLetterOrDigit(c) || c == '_')
6980                                 {
6981                                     continue;
6982                                 }
6983                                 if (c == '@')
6984                                 {
6985                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6986                                     int cnt = AtIdSupl.ItemCount;
6987                                     ShowSuplDialog(StatusText, AtIdSupl, startstr.Length + 1, startstr);
6988                                     if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
6989                                 }
6990                                 else if (c == '#')
6991                                 {
6992                                     startstr = StatusText.Text.Substring(i + 1, endidx - i);
6993                                     ShowSuplDialog(StatusText, HashSupl, startstr.Length + 1, startstr);
6994                                 }
6995                                 else
6996                                 {
6997                                     break;
6998                                 }
6999                             }
7000                         }
7001                     }),
7002
7003                 // ソートダイレクト選択(Ctrl+Shift+1~8,Ctrl+Shift+9)
7004                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D1)
7005                     .FocusedOn(FocusedControl.ListTab)
7006                     .Do(() => this.SetSortColumnByDisplayIndex(0)),
7007
7008                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D2)
7009                     .FocusedOn(FocusedControl.ListTab)
7010                     .Do(() => this.SetSortColumnByDisplayIndex(1)),
7011
7012                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D3)
7013                     .FocusedOn(FocusedControl.ListTab)
7014                     .Do(() => this.SetSortColumnByDisplayIndex(2)),
7015
7016                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D4)
7017                     .FocusedOn(FocusedControl.ListTab)
7018                     .Do(() => this.SetSortColumnByDisplayIndex(3)),
7019
7020                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D5)
7021                     .FocusedOn(FocusedControl.ListTab)
7022                     .Do(() => this.SetSortColumnByDisplayIndex(4)),
7023
7024                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D6)
7025                     .FocusedOn(FocusedControl.ListTab)
7026                     .Do(() => this.SetSortColumnByDisplayIndex(5)),
7027
7028                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D7)
7029                     .FocusedOn(FocusedControl.ListTab)
7030                     .Do(() => this.SetSortColumnByDisplayIndex(6)),
7031
7032                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D8)
7033                     .FocusedOn(FocusedControl.ListTab)
7034                     .Do(() => this.SetSortColumnByDisplayIndex(7)),
7035
7036                 ShortcutCommand.Create(Keys.Control | Keys.Shift | Keys.D9)
7037                     .FocusedOn(FocusedControl.ListTab)
7038                     .Do(() => this.SetSortLastColumn()),
7039
7040                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.S)
7041                     .Do(() => this.FavoritesRetweetOfficial()),
7042
7043                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.R)
7044                     .Do(() => this.FavoritesRetweetUnofficial()),
7045
7046                 ShortcutCommand.Create(Keys.Control | Keys.Alt | Keys.H)
7047                     .Do(() => this.OpenUserAppointUrl()),
7048
7049                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7050                     .FocusedOn(FocusedControl.PostBrowser)
7051                     .Do(() => this.doReTweetUnofficial()),
7052
7053                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C)
7054                     .FocusedOn(FocusedControl.PostBrowser)
7055                     .Do(() => this.CopyUserId()),
7056
7057                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.T)
7058                     .OnlyWhen(() => this.ExistCurrentPost)
7059                     .Do(() => this.doTranslation(_curPost.TextFromApi)),
7060
7061                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.R)
7062                     .Do(() => this.doReTweetUnofficial()),
7063
7064                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.C)
7065                     .Do(() => this.CopyUserId()),
7066
7067                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Up)
7068                     .Do(() => this.tweetThumbnail1.ScrollUp()),
7069
7070                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Down)
7071                     .Do(() => this.tweetThumbnail1.ScrollDown()),
7072
7073                 ShortcutCommand.Create(Keys.Alt | Keys.Shift | Keys.Enter)
7074                     .FocusedOn(FocusedControl.ListTab)
7075                     .OnlyWhen(() => !this.SplitContainer3.Panel2Collapsed)
7076                     .Do(() => this.OpenThumbnailPicture(this.tweetThumbnail1.Thumbnail)),
7077             };
7078         }
7079
7080         private bool CommonKeyDown(Keys keyData, FocusedControl focusedOn, out Task asyncTask)
7081         {
7082             // Task を返す非同期処理があれば asyncTask に代入する
7083             asyncTask = null;
7084
7085             // ShortcutCommand に対応しているコマンドはここで処理される
7086             foreach (var command in this.shortcutCommands)
7087             {
7088                 if (command.IsMatch(keyData, focusedOn))
7089                 {
7090                     asyncTask = command.RunCommand();
7091                     return command.PreventDefault;
7092                 }
7093             }
7094
7095             return false;
7096         }
7097
7098         private void ScrollDownPostBrowser(bool forward)
7099         {
7100             var doc = PostBrowser.Document;
7101             if (doc == null) return;
7102
7103             var tags = doc.GetElementsByTagName("html");
7104             if (tags.Count > 0)
7105             {
7106                 if (forward)
7107                     tags[0].ScrollTop += this._fntDetail.Height;
7108                 else
7109                     tags[0].ScrollTop -= this._fntDetail.Height;
7110             }
7111         }
7112
7113         private void PageDownPostBrowser(bool forward)
7114         {
7115             var doc = PostBrowser.Document;
7116             if (doc == null) return;
7117
7118             var tags = doc.GetElementsByTagName("html");
7119             if (tags.Count > 0)
7120             {
7121                 if (forward)
7122                     tags[0].ScrollTop += PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7123                 else
7124                     tags[0].ScrollTop -= PostBrowser.ClientRectangle.Height - this._fntDetail.Height;
7125             }
7126         }
7127
7128         private void GoNextTab(bool forward)
7129         {
7130             int idx = ListTab.SelectedIndex;
7131             if (forward)
7132             {
7133                 idx += 1;
7134                 if (idx > ListTab.TabPages.Count - 1) idx = 0;
7135             }
7136             else
7137             {
7138                 idx -= 1;
7139                 if (idx < 0) idx = ListTab.TabPages.Count - 1;
7140             }
7141             ListTab.SelectedIndex = idx;
7142         }
7143
7144         private void CopyStot()
7145         {
7146             string clstr = "";
7147             StringBuilder sb = new StringBuilder();
7148             bool IsProtected = false;
7149             bool isDm = false;
7150             if (this._curTab != null && this._statuses.GetTabByName(this._curTab.Text) != null) isDm = this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage;
7151             foreach (int idx in _curList.SelectedIndices)
7152             {
7153                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7154                 if (post.IsProtect)
7155                 {
7156                     IsProtected = true;
7157                     continue;
7158                 }
7159                 if (post.IsDeleted) continue;
7160                 if (!isDm)
7161                 {
7162                     if (post.RetweetedId != null)
7163                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.RetweetedId, Environment.NewLine);
7164                     else
7165                         sb.AppendFormat("{0}:{1} [https://twitter.com/{0}/status/{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7166                 }
7167                 else
7168                 {
7169                     sb.AppendFormat("{0}:{1} [{2}]{3}", post.ScreenName, post.TextSingleLine, post.StatusId, Environment.NewLine);
7170                 }
7171             }
7172             if (IsProtected)
7173             {
7174                 MessageBox.Show(Properties.Resources.CopyStotText1);
7175             }
7176             if (sb.Length > 0)
7177             {
7178                 clstr = sb.ToString();
7179                 try
7180                 {
7181                     Clipboard.SetDataObject(clstr, false, 5, 100);
7182                 }
7183                 catch (Exception ex)
7184                 {
7185                     MessageBox.Show(ex.Message);
7186                 }
7187             }
7188         }
7189
7190         private void CopyIdUri()
7191         {
7192             string clstr = "";
7193             StringBuilder sb = new StringBuilder();
7194             if (this._curTab == null) return;
7195             if (this._statuses.GetTabByName(this._curTab.Text) == null) return;
7196             if (this._statuses.GetTabByName(this._curTab.Text).TabType == MyCommon.TabUsageType.DirectMessage) return;
7197             foreach (int idx in _curList.SelectedIndices)
7198             {
7199                 var post = _statuses.Tabs[_curTab.Text][idx];
7200                 sb.Append(MyCommon.GetStatusUrl(post));
7201                 sb.Append(Environment.NewLine);
7202             }
7203             if (sb.Length > 0)
7204             {
7205                 clstr = sb.ToString();
7206                 try
7207                 {
7208                     Clipboard.SetDataObject(clstr, false, 5, 100);
7209                 }
7210                 catch (Exception ex)
7211                 {
7212                     MessageBox.Show(ex.Message);
7213                 }
7214             }
7215         }
7216
7217         private void GoFav(bool forward)
7218         {
7219             if (_curList.VirtualListSize == 0) return;
7220             int fIdx = 0;
7221             int toIdx = 0;
7222             int stp = 1;
7223
7224             if (forward)
7225             {
7226                 if (_curList.SelectedIndices.Count == 0)
7227                 {
7228                     fIdx = 0;
7229                 }
7230                 else
7231                 {
7232                     fIdx = _curList.SelectedIndices[0] + 1;
7233                     if (fIdx > _curList.VirtualListSize - 1) return;
7234                 }
7235                 toIdx = _curList.VirtualListSize;
7236                 stp = 1;
7237             }
7238             else
7239             {
7240                 if (_curList.SelectedIndices.Count == 0)
7241                 {
7242                     fIdx = _curList.VirtualListSize - 1;
7243                 }
7244                 else
7245                 {
7246                     fIdx = _curList.SelectedIndices[0] - 1;
7247                     if (fIdx < 0) return;
7248                 }
7249                 toIdx = -1;
7250                 stp = -1;
7251             }
7252
7253             for (int idx = fIdx; idx != toIdx; idx += stp)
7254             {
7255                 if (_statuses.Tabs[_curTab.Text][idx].IsFav)
7256                 {
7257                     SelectListItem(_curList, idx);
7258                     _curList.EnsureVisible(idx);
7259                     break;
7260                 }
7261             }
7262         }
7263
7264         private void GoSamePostToAnotherTab(bool left)
7265         {
7266             if (_curList.VirtualListSize == 0) return;
7267             int fIdx = 0;
7268             int toIdx = 0;
7269             int stp = 1;
7270             long targetId = 0;
7271
7272             if (_statuses.Tabs[_curTab.Text].TabType == MyCommon.TabUsageType.DirectMessage) return; // Directタブは対象外(見つかるはずがない)
7273             if (_curList.SelectedIndices.Count == 0) return; //未選択も処理しない
7274
7275             targetId = GetCurTabPost(_curList.SelectedIndices[0]).StatusId;
7276
7277             if (left)
7278             {
7279                 // 左のタブへ
7280                 if (ListTab.SelectedIndex == 0)
7281                 {
7282                     return;
7283                 }
7284                 else
7285                 {
7286                     fIdx = ListTab.SelectedIndex - 1;
7287                 }
7288                 toIdx = -1;
7289                 stp = -1;
7290             }
7291             else
7292             {
7293                 // 右のタブへ
7294                 if (ListTab.SelectedIndex == ListTab.TabCount - 1)
7295                 {
7296                     return;
7297                 }
7298                 else
7299                 {
7300                     fIdx = ListTab.SelectedIndex + 1;
7301                 }
7302                 toIdx = ListTab.TabCount;
7303                 stp = 1;
7304             }
7305
7306             bool found = false;
7307             for (int tabidx = fIdx; tabidx != toIdx; tabidx += stp)
7308             {
7309                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage) continue; // Directタブは対象外
7310                 for (int idx = 0; idx < ((DetailsListView)ListTab.TabPages[tabidx].Tag).VirtualListSize; idx++)
7311                 {
7312                     if (_statuses.Tabs[ListTab.TabPages[tabidx].Text][idx].StatusId == targetId)
7313                     {
7314                         ListTab.SelectedIndex = tabidx;
7315                         SelectListItem(_curList, idx);
7316                         _curList.EnsureVisible(idx);
7317                         found = true;
7318                         break;
7319                     }
7320                 }
7321                 if (found) break;
7322             }
7323         }
7324
7325         private void GoPost(bool forward)
7326         {
7327             if (_curList.SelectedIndices.Count == 0 || _curPost == null) return;
7328             int fIdx = 0;
7329             int toIdx = 0;
7330             int stp = 1;
7331
7332             if (forward)
7333             {
7334                 fIdx = _curList.SelectedIndices[0] + 1;
7335                 if (fIdx > _curList.VirtualListSize - 1) return;
7336                 toIdx = _curList.VirtualListSize;
7337                 stp = 1;
7338             }
7339             else
7340             {
7341                 fIdx = _curList.SelectedIndices[0] - 1;
7342                 if (fIdx < 0) return;
7343                 toIdx = -1;
7344                 stp = -1;
7345             }
7346
7347             string name = "";
7348             if (_curPost.RetweetedId == null)
7349             {
7350                 name = _curPost.ScreenName;
7351             }
7352             else
7353             {
7354                 name = _curPost.RetweetedBy;
7355             }
7356             for (int idx = fIdx; idx != toIdx; idx += stp)
7357             {
7358                 if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
7359                 {
7360                     if (_statuses.Tabs[_curTab.Text][idx].ScreenName == name)
7361                     {
7362                         SelectListItem(_curList, idx);
7363                         _curList.EnsureVisible(idx);
7364                         break;
7365                     }
7366                 }
7367                 else
7368                 {
7369                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedBy == name)
7370                     {
7371                         SelectListItem(_curList, idx);
7372                         _curList.EnsureVisible(idx);
7373                         break;
7374                     }
7375                 }
7376             }
7377         }
7378
7379         private void GoRelPost(bool forward)
7380         {
7381             if (_curList.SelectedIndices.Count == 0) return;
7382
7383             int fIdx = 0;
7384             int toIdx = 0;
7385             int stp = 1;
7386             if (forward)
7387             {
7388                 fIdx = _curList.SelectedIndices[0] + 1;
7389                 if (fIdx > _curList.VirtualListSize - 1) return;
7390                 toIdx = _curList.VirtualListSize;
7391                 stp = 1;
7392             }
7393             else
7394             {
7395                 fIdx = _curList.SelectedIndices[0] - 1;
7396                 if (fIdx < 0) return;
7397                 toIdx = -1;
7398                 stp = -1;
7399             }
7400
7401             if (!_anchorFlag)
7402             {
7403                 if (_curPost == null) return;
7404                 _anchorPost = _curPost;
7405                 _anchorFlag = true;
7406             }
7407             else
7408             {
7409                 if (_anchorPost == null) return;
7410             }
7411
7412             for (int idx = fIdx; idx != toIdx; idx += stp)
7413             {
7414                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
7415                 if (post.ScreenName == _anchorPost.ScreenName ||
7416                     post.RetweetedBy == _anchorPost.ScreenName ||
7417                     post.ScreenName == _anchorPost.RetweetedBy ||
7418                     (!string.IsNullOrEmpty(post.RetweetedBy) && post.RetweetedBy == _anchorPost.RetweetedBy) ||
7419                     _anchorPost.ReplyToList.Contains(post.ScreenName.ToLower()) ||
7420                     _anchorPost.ReplyToList.Contains(post.RetweetedBy.ToLower()) ||
7421                     post.ReplyToList.Contains(_anchorPost.ScreenName.ToLower()) ||
7422                     post.ReplyToList.Contains(_anchorPost.RetweetedBy.ToLower()))
7423                 {
7424                     SelectListItem(_curList, idx);
7425                     _curList.EnsureVisible(idx);
7426                     break;
7427                 }
7428             }
7429         }
7430
7431         private void GoAnchor()
7432         {
7433             if (_anchorPost == null) return;
7434             int idx = _statuses.Tabs[_curTab.Text].IndexOf(_anchorPost.StatusId);
7435             if (idx == -1) return;
7436
7437             SelectListItem(_curList, idx);
7438             _curList.EnsureVisible(idx);
7439         }
7440
7441         private void GoTopEnd(bool GoTop)
7442         {
7443             if (_curList.VirtualListSize == 0)
7444                 return;
7445
7446             ListViewItem _item;
7447             int idx;
7448
7449             if (GoTop)
7450             {
7451                 _item = _curList.GetItemAt(0, 25);
7452                 if (_item == null)
7453                     idx = 0;
7454                 else
7455                     idx = _item.Index;
7456             }
7457             else
7458             {
7459                 _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7460                 if (_item == null)
7461                     idx = _curList.VirtualListSize - 1;
7462                 else
7463                     idx = _item.Index;
7464             }
7465             SelectListItem(_curList, idx);
7466         }
7467
7468         private void GoMiddle()
7469         {
7470             if (_curList.VirtualListSize == 0)
7471                 return;
7472
7473             ListViewItem _item;
7474             int idx1;
7475             int idx2;
7476             int idx3;
7477
7478             _item = _curList.GetItemAt(0, 0);
7479             if (_item == null)
7480             {
7481                 idx1 = 0;
7482             }
7483             else
7484             {
7485                 idx1 = _item.Index;
7486             }
7487
7488             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
7489             if (_item == null)
7490             {
7491                 idx2 = _curList.VirtualListSize - 1;
7492             }
7493             else
7494             {
7495                 idx2 = _item.Index;
7496             }
7497             idx3 = (idx1 + idx2) / 2;
7498
7499             SelectListItem(_curList, idx3);
7500         }
7501
7502         private void GoLast()
7503         {
7504             if (_curList.VirtualListSize == 0) return;
7505
7506             if (_statuses.SortOrder == SortOrder.Ascending)
7507             {
7508                 SelectListItem(_curList, _curList.VirtualListSize - 1);
7509                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7510             }
7511             else
7512             {
7513                 SelectListItem(_curList, 0);
7514                 _curList.EnsureVisible(0);
7515             }
7516         }
7517
7518         private void MoveTop()
7519         {
7520             if (_curList.SelectedIndices.Count == 0) return;
7521             int idx = _curList.SelectedIndices[0];
7522             if (_statuses.SortOrder == SortOrder.Ascending)
7523             {
7524                 _curList.EnsureVisible(_curList.VirtualListSize - 1);
7525             }
7526             else
7527             {
7528                 _curList.EnsureVisible(0);
7529             }
7530             _curList.EnsureVisible(idx);
7531         }
7532
7533         private async Task GoInReplyToPostTree()
7534         {
7535             if (_curPost == null) return;
7536
7537             TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7538
7539             if (curTabClass.TabType == MyCommon.TabUsageType.PublicSearch && _curPost.InReplyToStatusId == null && _curPost.TextFromApi.Contains("@"))
7540             {
7541                 try
7542                 {
7543                     var post = tw.GetStatusApi(false, _curPost.StatusId);
7544
7545                     _curPost.InReplyToStatusId = post.InReplyToStatusId;
7546                     _curPost.InReplyToUser = post.InReplyToUser;
7547                     _curPost.IsReply = post.IsReply;
7548                     this.PurgeListViewItemCache();
7549                     _curList.RedrawItems(_curItemIndex, _curItemIndex, false);
7550                 }
7551                 catch (WebApiException ex)
7552                 {
7553                     this.StatusLabel.Text = ex.Message;
7554                 }
7555             }
7556
7557             if (!(this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)) return;
7558
7559             if (replyChains == null || (replyChains.Count > 0 && replyChains.Peek().InReplyToId != _curPost.StatusId))
7560             {
7561                 replyChains = new Stack<ReplyChain>();
7562             }
7563             replyChains.Push(new ReplyChain(_curPost.StatusId, _curPost.InReplyToStatusId.Value, _curTab));
7564
7565             int inReplyToIndex;
7566             string inReplyToTabName;
7567             long inReplyToId = _curPost.InReplyToStatusId.Value;
7568             string inReplyToUser = _curPost.InReplyToUser;
7569             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7570
7571             var inReplyToPosts = from tab in _statuses.Tabs.Values
7572                                  orderby tab != curTabClass
7573                                  from post in tab.Posts.Values
7574                                  where post.StatusId == inReplyToId
7575                                  let index = tab.IndexOf(post.StatusId)
7576                                  where index != -1
7577                                  select new {Tab = tab, Index = index};
7578
7579             var inReplyPost = inReplyToPosts.FirstOrDefault();
7580             if (inReplyPost == null)
7581             {
7582                 try
7583                 {
7584                     await Task.Run(() =>
7585                     {
7586                         var post = tw.GetStatusApi(false, _curPost.InReplyToStatusId.Value);
7587                         post.IsRead = true;
7588
7589                         _statuses.AddPost(post);
7590                         _statuses.DistributePosts();
7591                     });
7592                 }
7593                 catch (WebApiException ex)
7594                 {
7595                     this.StatusLabel.Text = ex.Message;
7596                     await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7597                     return;
7598                 }
7599
7600                 this.RefreshTimeline();
7601
7602                 inReplyPost = inReplyToPosts.FirstOrDefault();
7603                 if (inReplyPost == null)
7604                 {
7605                     await this.OpenUriInBrowserAsync("https://twitter.com/" + inReplyToUser + "/statuses/" + inReplyToId.ToString());
7606                     return;
7607                 }
7608             }
7609             inReplyToTabName = inReplyPost.Tab.TabName;
7610             inReplyToIndex = inReplyPost.Index;
7611
7612             TabPage tabPage = this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == inReplyToTabName; });
7613             DetailsListView listView = (DetailsListView)tabPage.Tag;
7614
7615             if (_curTab != tabPage)
7616             {
7617                 this.ListTab.SelectTab(tabPage);
7618             }
7619
7620             this.SelectListItem(listView, inReplyToIndex);
7621             listView.EnsureVisible(inReplyToIndex);
7622         }
7623
7624         private void GoBackInReplyToPostTree(bool parallel = false, bool isForward = true)
7625         {
7626             if (_curPost == null) return;
7627
7628             TabClass curTabClass = _statuses.Tabs[_curTab.Text];
7629             //Dictionary<long, PostClass> curTabPosts = curTabClass.Posts;
7630
7631             if (parallel)
7632             {
7633                 if (_curPost.InReplyToStatusId != null)
7634                 {
7635                     var posts = from t in _statuses.Tabs
7636                                 from p in t.Value.Posts
7637                                 where p.Value.StatusId != _curPost.StatusId && p.Value.InReplyToStatusId == _curPost.InReplyToStatusId
7638                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7639                                 where indexOf > -1
7640                                 orderby isForward ? indexOf : indexOf * -1
7641                                 orderby t.Value != curTabClass
7642                                 select new {Tab = t.Value, Post = p.Value, Index = indexOf};
7643                     try
7644                     {
7645                         var postList = posts.ToList();
7646                         for (int i = postList.Count - 1; i >= 0; i--)
7647                         {
7648                             int index = i;
7649                             if (postList.FindIndex((pst) => { return pst.Post.StatusId == postList[index].Post.StatusId; }) != index)
7650                             {
7651                                 postList.RemoveAt(index);
7652                             }
7653                         }
7654                         var post = postList.FirstOrDefault((pst) => { return pst.Tab == curTabClass && isForward ? pst.Index > _curItemIndex : pst.Index < _curItemIndex; });
7655                         if (post == null) post = postList.FirstOrDefault((pst) => { return pst.Tab != curTabClass; });
7656                         if (post == null) post = postList.First();
7657                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7658                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7659                         SelectListItem(listView, post.Index);
7660                         listView.EnsureVisible(post.Index);
7661                     }
7662                     catch (InvalidOperationException)
7663                     {
7664                         return;
7665                     }
7666                 }
7667             }
7668             else
7669             {
7670                 if (replyChains == null || replyChains.Count < 1)
7671                 {
7672                     var posts = from t in _statuses.Tabs
7673                                 from p in t.Value.Posts
7674                                 where p.Value.InReplyToStatusId == _curPost.StatusId
7675                                 let indexOf = t.Value.IndexOf(p.Value.StatusId)
7676                                 where indexOf > -1
7677                                 orderby indexOf
7678                                 orderby t.Value != curTabClass
7679                                 select new {Tab = t.Value, Index = indexOf};
7680                     try
7681                     {
7682                         var post = posts.First();
7683                         this.ListTab.SelectTab(this.ListTab.TabPages.Cast<TabPage>().First((tp) => { return tp.Text == post.Tab.TabName; }));
7684                         DetailsListView listView = (DetailsListView)this.ListTab.SelectedTab.Tag;
7685                         SelectListItem(listView, post.Index);
7686                         listView.EnsureVisible(post.Index);
7687                     }
7688                     catch (InvalidOperationException)
7689                     {
7690                         return;
7691                     }
7692                 }
7693                 else
7694                 {
7695                     ReplyChain chainHead = replyChains.Pop();
7696                     if (chainHead.InReplyToId == _curPost.StatusId)
7697                     {
7698                         int idx = _statuses.Tabs[chainHead.OriginalTab.Text].IndexOf(chainHead.OriginalId);
7699                         if (idx == -1)
7700                         {
7701                             replyChains = null;
7702                         }
7703                         else
7704                         {
7705                             try
7706                             {
7707                                 ListTab.SelectTab(chainHead.OriginalTab);
7708                             }
7709                             catch (Exception)
7710                             {
7711                                 replyChains = null;
7712                             }
7713                             SelectListItem(_curList, idx);
7714                             _curList.EnsureVisible(idx);
7715                         }
7716                     }
7717                     else
7718                     {
7719                         replyChains = null;
7720                         this.GoBackInReplyToPostTree(parallel);
7721                     }
7722                 }
7723             }
7724         }
7725
7726         private void GoBackSelectPostChain()
7727         {
7728             if (this.selectPostChains.Count > 1)
7729             {
7730                 var idx = -1;
7731                 TabPage tp = null;
7732
7733                 do
7734                 {
7735                     try
7736                     {
7737                         this.selectPostChains.Pop();
7738                         var tabPostPair = this.selectPostChains.Peek();
7739
7740                         if (!this.ListTab.TabPages.Contains(tabPostPair.Item1)) continue;  //該当タブが存在しないので無視
7741
7742                         if (tabPostPair.Item2 != null)
7743                         {
7744                             idx = this._statuses.Tabs[tabPostPair.Item1.Text].IndexOf(tabPostPair.Item2.StatusId);
7745                             if (idx == -1) continue;  //該当ポストが存在しないので無視
7746                         }
7747
7748                         tp = tabPostPair.Item1;
7749
7750                         this.selectPostChains.Pop();
7751                     }
7752                     catch (InvalidOperationException)
7753                     {
7754                     }
7755
7756                     break;
7757                 }
7758                 while (this.selectPostChains.Count > 1);
7759
7760                 if (tp == null)
7761                 {
7762                     //状態がおかしいので処理を中断
7763                     //履歴が残り1つであればクリアしておく
7764                     if (this.selectPostChains.Count == 1)
7765                         this.selectPostChains.Clear();
7766                     return;
7767                 }
7768
7769                 DetailsListView lst = (DetailsListView)tp.Tag;
7770                 this.ListTab.SelectedTab = tp;
7771                 if (idx > -1)
7772                 {
7773                     SelectListItem(lst, idx);
7774                     lst.EnsureVisible(idx);
7775                 }
7776                 lst.Focus();
7777             }
7778         }
7779
7780         private void PushSelectPostChain()
7781         {
7782             int count = this.selectPostChains.Count;
7783             if (count > 0)
7784             {
7785                 var p = this.selectPostChains.Peek();
7786                 if (p.Item1 == this._curTab)
7787                 {
7788                     if (p.Item2 == this._curPost) return;  //最新の履歴と同一
7789                     if (p.Item2 == null) this.selectPostChains.Pop();  //置き換えるため削除
7790                 }
7791             }
7792             if (count >= 2500) TrimPostChain();
7793             this.selectPostChains.Push(Tuple.Create(this._curTab, this._curPost));
7794         }
7795
7796         private void TrimPostChain()
7797         {
7798             if (this.selectPostChains.Count <= 2000) return;
7799             var p = new Stack<Tuple<TabPage, PostClass>>(2000);
7800             for (int i = 0; i < 2000; i++)
7801             {
7802                 p.Push(this.selectPostChains.Pop());
7803             }
7804             this.selectPostChains.Clear();
7805             for (int i = 0; i < 2000; i++)
7806             {
7807                 this.selectPostChains.Push(p.Pop());
7808             }
7809         }
7810
7811         private bool GoStatus(long statusId)
7812         {
7813             if (statusId == 0) return false;
7814             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7815             {
7816                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType != MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7817                 {
7818                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7819                     ListTab.SelectedIndex = tabidx;
7820                     SelectListItem(_curList, idx);
7821                     _curList.EnsureVisible(idx);
7822                     return true;
7823                 }
7824             }
7825             return false;
7826         }
7827
7828         private bool GoDirectMessage(long statusId)
7829         {
7830             if (statusId == 0) return false;
7831             for (int tabidx = 0; tabidx < ListTab.TabCount; tabidx++)
7832             {
7833                 if (_statuses.Tabs[ListTab.TabPages[tabidx].Text].TabType == MyCommon.TabUsageType.DirectMessage && _statuses.Tabs[ListTab.TabPages[tabidx].Text].Contains(statusId))
7834                 {
7835                     int idx = _statuses.Tabs[ListTab.TabPages[tabidx].Text].IndexOf(statusId);
7836                     ListTab.SelectedIndex = tabidx;
7837                     SelectListItem(_curList, idx);
7838                     _curList.EnsureVisible(idx);
7839                     return true;
7840                 }
7841             }
7842             return false;
7843         }
7844
7845         private void MyList_MouseClick(object sender, MouseEventArgs e)
7846         {
7847             _anchorFlag = false;
7848         }
7849
7850         private void StatusText_Enter(object sender, EventArgs e)
7851         {
7852             // フォーカスの戻り先を StatusText に設定
7853             this.Tag = StatusText;
7854             StatusText.BackColor = _clInputBackcolor;
7855         }
7856
7857         public Color InputBackColor
7858         {
7859             get { return _clInputBackcolor; }
7860             set { _clInputBackcolor = value; }
7861         }
7862
7863         private void StatusText_Leave(object sender, EventArgs e)
7864         {
7865             // フォーカスがメニューに遷移しないならばフォーカスはタブに移ることを期待
7866             if (ListTab.SelectedTab != null && MenuStrip1.Tag == null) this.Tag = ListTab.SelectedTab.Tag;
7867             StatusText.BackColor = Color.FromKnownColor(KnownColor.Window);
7868         }
7869
7870         private async void StatusText_KeyDown(object sender, KeyEventArgs e)
7871         {
7872             Task asyncTask;
7873             if (CommonKeyDown(e.KeyData, FocusedControl.StatusText, out asyncTask))
7874             {
7875                 e.Handled = true;
7876                 e.SuppressKeyPress = true;
7877             }
7878
7879             this.StatusText_TextChanged(null, null);
7880
7881             if (asyncTask != null)
7882                 await asyncTask;
7883         }
7884
7885         private void SaveConfigsAll(bool ifModified)
7886         {
7887             if (!ifModified)
7888             {
7889                 SaveConfigsCommon();
7890                 SaveConfigsLocal();
7891                 SaveConfigsTabs();
7892                 SaveConfigsAtId();
7893             }
7894             else
7895             {
7896                 if (_modifySettingCommon) SaveConfigsCommon();
7897                 if (_modifySettingLocal) SaveConfigsLocal();
7898                 if (_modifySettingAtId) SaveConfigsAtId();
7899             }
7900         }
7901
7902         private void SaveConfigsAtId()
7903         {
7904             if (_ignoreConfigSave || !this._cfgCommon.UseAtIdSupplement && AtIdSupl == null) return;
7905
7906             _modifySettingAtId = false;
7907             SettingAtIdList cfgAtId = new SettingAtIdList(AtIdSupl.GetItemList());
7908             cfgAtId.Save();
7909         }
7910
7911         private void SaveConfigsCommon()
7912         {
7913             if (_ignoreConfigSave) return;
7914
7915             _modifySettingCommon = false;
7916             lock (_syncObject)
7917             {
7918                 _cfgCommon.UserName = tw.Username;
7919                 _cfgCommon.UserId = tw.UserId;
7920                 _cfgCommon.Password = tw.Password;
7921                 _cfgCommon.Token = tw.AccessToken;
7922                 _cfgCommon.TokenSecret = tw.AccessTokenSecret;
7923
7924                 if (IdeographicSpaceToSpaceToolStripMenuItem != null &&
7925                    IdeographicSpaceToSpaceToolStripMenuItem.IsDisposed == false)
7926                 {
7927                     _cfgCommon.WideSpaceConvert = this.IdeographicSpaceToSpaceToolStripMenuItem.Checked;
7928                 }
7929
7930                 _cfgCommon.SortOrder = (int)_statuses.SortOrder;
7931                 switch (_statuses.SortMode)
7932                 {
7933                     case ComparerMode.Nickname:  //ニックネーム
7934                         _cfgCommon.SortColumn = 1;
7935                         break;
7936                     case ComparerMode.Data:  //本文
7937                         _cfgCommon.SortColumn = 2;
7938                         break;
7939                     case ComparerMode.Id:  //時刻=発言Id
7940                         _cfgCommon.SortColumn = 3;
7941                         break;
7942                     case ComparerMode.Name:  //名前
7943                         _cfgCommon.SortColumn = 4;
7944                         break;
7945                     case ComparerMode.Source:  //Source
7946                         _cfgCommon.SortColumn = 7;
7947                         break;
7948                 }
7949
7950                 _cfgCommon.HashTags = HashMgr.HashHistories;
7951                 if (HashMgr.IsPermanent)
7952                 {
7953                     _cfgCommon.HashSelected = HashMgr.UseHash;
7954                 }
7955                 else
7956                 {
7957                     _cfgCommon.HashSelected = "";
7958                 }
7959                 _cfgCommon.HashIsHead = HashMgr.IsHead;
7960                 _cfgCommon.HashIsPermanent = HashMgr.IsPermanent;
7961                 _cfgCommon.HashIsNotAddToAtReply = HashMgr.IsNotAddToAtReply;
7962                 if (ToolStripFocusLockMenuItem != null &&
7963                         ToolStripFocusLockMenuItem.IsDisposed == false)
7964                 {
7965                     _cfgCommon.FocusLockToStatusText = this.ToolStripFocusLockMenuItem.Checked;
7966                 }
7967                 _cfgCommon.TrackWord = tw.TrackWord;
7968                 _cfgCommon.AllAtReply = tw.AllAtReply;
7969                 _cfgCommon.UseImageService = ImageSelector.ServiceIndex;
7970                 _cfgCommon.UseImageServiceName = ImageSelector.ServiceName;
7971
7972                 _cfgCommon.Save();
7973             }
7974         }
7975
7976         private void SaveConfigsLocal()
7977         {
7978             if (_ignoreConfigSave) return;
7979             lock (_syncObject)
7980             {
7981                 _modifySettingLocal = false;
7982                 _cfgLocal.ScaleDimension = this.CurrentAutoScaleDimensions;
7983                 _cfgLocal.FormSize = _mySize;
7984                 _cfgLocal.FormLocation = _myLoc;
7985                 _cfgLocal.SplitterDistance = _mySpDis;
7986                 _cfgLocal.PreviewDistance = _mySpDis3;
7987                 _cfgLocal.StatusMultiline = StatusText.Multiline;
7988                 _cfgLocal.StatusTextHeight = _mySpDis2;
7989
7990                 _cfgLocal.FontUnread = _fntUnread;
7991                 _cfgLocal.ColorUnread = _clUnread;
7992                 _cfgLocal.FontRead = _fntReaded;
7993                 _cfgLocal.ColorRead = _clReaded;
7994                 _cfgLocal.FontDetail = _fntDetail;
7995                 _cfgLocal.ColorDetail = _clDetail;
7996                 _cfgLocal.ColorDetailBackcolor = _clDetailBackcolor;
7997                 _cfgLocal.ColorDetailLink = _clDetailLink;
7998                 _cfgLocal.ColorFav = _clFav;
7999                 _cfgLocal.ColorOWL = _clOWL;
8000                 _cfgLocal.ColorRetweet = _clRetweet;
8001                 _cfgLocal.ColorSelf = _clSelf;
8002                 _cfgLocal.ColorAtSelf = _clAtSelf;
8003                 _cfgLocal.ColorTarget = _clTarget;
8004                 _cfgLocal.ColorAtTarget = _clAtTarget;
8005                 _cfgLocal.ColorAtFromTarget = _clAtFromTarget;
8006                 _cfgLocal.ColorAtTo = _clAtTo;
8007                 _cfgLocal.ColorListBackcolor = _clListBackcolor;
8008                 _cfgLocal.ColorInputBackcolor = _clInputBackcolor;
8009                 _cfgLocal.ColorInputFont = _clInputFont;
8010                 _cfgLocal.FontInputFont = _fntInputFont;
8011
8012                 if (_ignoreConfigSave) return;
8013                 _cfgLocal.Save();
8014             }
8015         }
8016
8017         private void SaveConfigsTabs()
8018         {
8019             SettingTabs tabSetting = new SettingTabs();
8020             for (int i = 0; i < ListTab.TabPages.Count; i++)
8021             {
8022                 var tab = _statuses.Tabs[ListTab.TabPages[i].Text];
8023                 if (tab.TabType != MyCommon.TabUsageType.Related && tab.TabType != MyCommon.TabUsageType.SearchResults)
8024                     tabSetting.Tabs.Add(tab);
8025             }
8026             tabSetting.Tabs.Add(this._statuses.GetTabByType(MyCommon.TabUsageType.Mute));
8027             tabSetting.Save();
8028         }
8029
8030         private async void OpenURLFileMenuItem_Click(object sender, EventArgs e)
8031         {
8032             string inputText;
8033             var ret = InputDialog.Show(this, Properties.Resources.OpenURL_InputText, Properties.Resources.OpenURL_Caption, out inputText);
8034             if (ret != DialogResult.OK)
8035                 return;
8036
8037             var match = Twitter.StatusUrlRegex.Match(inputText);
8038             if (!match.Success)
8039             {
8040                 MessageBox.Show(this, Properties.Resources.OpenURL_InvalidFormat,
8041                     Properties.Resources.OpenURL_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
8042                 return;
8043             }
8044
8045             try
8046             {
8047                 var statusId = long.Parse(match.Groups["StatusId"].Value);
8048                 await this.OpenRelatedTab(statusId);
8049             }
8050             catch (TabException ex)
8051             {
8052                 MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
8053             }
8054         }
8055
8056         private void SaveLogMenuItem_Click(object sender, EventArgs e)
8057         {
8058             DialogResult rslt = MessageBox.Show(string.Format(Properties.Resources.SaveLogMenuItem_ClickText1, Environment.NewLine),
8059                     Properties.Resources.SaveLogMenuItem_ClickText2,
8060                     MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
8061             if (rslt == DialogResult.Cancel) return;
8062
8063             SaveFileDialog1.FileName = MyCommon.GetAssemblyName() + "Posts" + DateTime.Now.ToString("yyMMdd-HHmmss") + ".tsv";
8064             SaveFileDialog1.InitialDirectory = Application.ExecutablePath;
8065             SaveFileDialog1.Filter = Properties.Resources.SaveLogMenuItem_ClickText3;
8066             SaveFileDialog1.FilterIndex = 0;
8067             SaveFileDialog1.Title = Properties.Resources.SaveLogMenuItem_ClickText4;
8068             SaveFileDialog1.RestoreDirectory = true;
8069
8070             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
8071             {
8072                 if (!SaveFileDialog1.ValidateNames) return;
8073                 using (StreamWriter sw = new StreamWriter(SaveFileDialog1.FileName, false, Encoding.UTF8))
8074                 {
8075                     if (rslt == DialogResult.Yes)
8076                     {
8077                         //All
8078                         for (int idx = 0; idx < _curList.VirtualListSize; idx++)
8079                         {
8080                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
8081                             string protect = "";
8082                             if (post.IsProtect) protect = "Protect";
8083                             sw.WriteLine(post.Nickname + "\t" +
8084                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8085                                      post.CreatedAt.ToString() + "\t" +
8086                                      post.ScreenName + "\t" +
8087                                      post.StatusId.ToString() + "\t" +
8088                                      post.ImageUrl + "\t" +
8089                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8090                                      protect);
8091                         }
8092                     }
8093                     else
8094                     {
8095                         foreach (int idx in _curList.SelectedIndices)
8096                         {
8097                             PostClass post = _statuses.Tabs[_curTab.Text][idx];
8098                             string protect = "";
8099                             if (post.IsProtect) protect = "Protect";
8100                             sw.WriteLine(post.Nickname + "\t" +
8101                                      "\"" + post.TextFromApi.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8102                                      post.CreatedAt.ToString() + "\t" +
8103                                      post.ScreenName + "\t" +
8104                                      post.StatusId.ToString() + "\t" +
8105                                      post.ImageUrl + "\t" +
8106                                      "\"" + post.Text.Replace("\n", "").Replace("\"", "\"\"") + "\"" + "\t" +
8107                                      protect);
8108                         }
8109                     }
8110                 }
8111             }
8112             this.TopMost = this._cfgCommon.AlwaysTop;
8113         }
8114
8115         private async void PostBrowser_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
8116         {
8117             Task asyncTask;
8118             bool KeyRes = CommonKeyDown(e.KeyData, FocusedControl.PostBrowser, out asyncTask);
8119             if (KeyRes)
8120             {
8121                 e.IsInputKey = true;
8122             }
8123             else
8124             {
8125                 if (Enum.IsDefined(typeof(Shortcut), (Shortcut)e.KeyData))
8126                 {
8127                     var shortcut = (Shortcut)e.KeyData;
8128                     switch (shortcut)
8129                     {
8130                         case Shortcut.CtrlA:
8131                         case Shortcut.CtrlC:
8132                         case Shortcut.CtrlIns:
8133                             // 既定の動作を有効にする
8134                             break;
8135                         default:
8136                             // その他のショートカットキーは無効にする
8137                             e.IsInputKey = true;
8138                             break;
8139                     }
8140                 }
8141             }
8142
8143             if (asyncTask != null)
8144                 await asyncTask;
8145         }
8146         public bool TabRename(ref string tabName)
8147         {
8148             //タブ名変更
8149             string newTabText = null;
8150             using (InputTabName inputName = new InputTabName())
8151             {
8152                 inputName.TabName = tabName;
8153                 inputName.ShowDialog();
8154                 if (inputName.DialogResult == DialogResult.Cancel) return false;
8155                 newTabText = inputName.TabName;
8156             }
8157             this.TopMost = this._cfgCommon.AlwaysTop;
8158             if (!string.IsNullOrEmpty(newTabText))
8159             {
8160                 //新タブ名存在チェック
8161                 for (int i = 0; i < ListTab.TabCount; i++)
8162                 {
8163                     if (ListTab.TabPages[i].Text == newTabText)
8164                     {
8165                         string tmp = string.Format(Properties.Resources.Tabs_DoubleClickText1, newTabText);
8166                         MessageBox.Show(tmp, Properties.Resources.Tabs_DoubleClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8167                         return false;
8168                     }
8169                 }
8170                 //タブ名を変更
8171                 for (int i = 0; i < ListTab.TabCount; i++)
8172                 {
8173                     if (ListTab.TabPages[i].Text == tabName)
8174                     {
8175                         ListTab.TabPages[i].Text = newTabText;
8176                         break;
8177                     }
8178                 }
8179                 _statuses.RenameTab(tabName, newTabText);
8180
8181                 SaveConfigsCommon();
8182                 SaveConfigsTabs();
8183                 _rclickTabName = newTabText;
8184                 tabName = newTabText;
8185                 return true;
8186             }
8187             else
8188             {
8189                 return false;
8190             }
8191         }
8192
8193         private void ListTab_MouseClick(object sender, MouseEventArgs e)
8194         {
8195             if (e.Button == MouseButtons.Middle)
8196             {
8197                 for (int i = 0; i < this.ListTab.TabPages.Count; i++)
8198                 {
8199                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8200                     {
8201                         this.RemoveSpecifiedTab(this.ListTab.TabPages[i].Text, true);
8202                         this.SaveConfigsTabs();
8203                         break;
8204                     }
8205                 }
8206             }
8207         }
8208
8209         private void ListTab_DoubleClick(object sender, MouseEventArgs e)
8210         {
8211             string tn = ListTab.SelectedTab.Text;
8212             TabRename(ref tn);
8213         }
8214
8215         private void ListTab_MouseDown(object sender, MouseEventArgs e)
8216         {
8217             if (this._cfgCommon.TabMouseLock) return;
8218             Point cpos = new Point(e.X, e.Y);
8219             if (e.Button == MouseButtons.Left)
8220             {
8221                 for (int i = 0; i < ListTab.TabPages.Count; i++)
8222                 {
8223                     if (this.ListTab.GetTabRect(i).Contains(e.Location))
8224                     {
8225                         _tabDrag = true;
8226                         _tabMouseDownPoint = e.Location;
8227                         break;
8228                     }
8229                 }
8230             }
8231             else
8232             {
8233                 _tabDrag = false;
8234             }
8235         }
8236
8237         private void ListTab_DragEnter(object sender, DragEventArgs e)
8238         {
8239             if (e.Data.GetDataPresent(typeof(TabPage)))
8240                 e.Effect = DragDropEffects.Move;
8241             else
8242                 e.Effect = DragDropEffects.None;
8243         }
8244
8245         private void ListTab_DragDrop(object sender, DragEventArgs e)
8246         {
8247             if (!e.Data.GetDataPresent(typeof(TabPage))) return;
8248
8249             _tabDrag = false;
8250             string tn = "";
8251             bool bef = false;
8252             Point cpos = new Point(e.X, e.Y);
8253             Point spos = ListTab.PointToClient(cpos);
8254             int i;
8255             for (i = 0; i < ListTab.TabPages.Count; i++)
8256             {
8257                 Rectangle rect = ListTab.GetTabRect(i);
8258                 if (rect.Left <= spos.X && spos.X <= rect.Right &&
8259                     rect.Top <= spos.Y && spos.Y <= rect.Bottom)
8260                 {
8261                     tn = ListTab.TabPages[i].Text;
8262                     if (spos.X <= (rect.Left + rect.Right) / 2)
8263                         bef = true;
8264                     else
8265                         bef = false;
8266
8267                     break;
8268                 }
8269             }
8270
8271             //タブのないところにドロップ->最後尾へ移動
8272             if (string.IsNullOrEmpty(tn))
8273             {
8274                 tn = ListTab.TabPages[ListTab.TabPages.Count - 1].Text;
8275                 bef = false;
8276                 i = ListTab.TabPages.Count - 1;
8277             }
8278
8279             TabPage tp = (TabPage)e.Data.GetData(typeof(TabPage));
8280             if (tp.Text == tn) return;
8281
8282             ReOrderTab(tp.Text, tn, bef);
8283         }
8284
8285         public void ReOrderTab(string targetTabText, string baseTabText, bool isBeforeBaseTab)
8286         {
8287             var baseIndex = this.GetTabPageIndex(baseTabText);
8288             if (baseIndex == -1)
8289                 return;
8290
8291             var targetIndex = this.GetTabPageIndex(targetTabText);
8292             if (targetIndex == -1)
8293                 return;
8294
8295             using (ControlTransaction.Layout(this.ListTab))
8296             {
8297                 var mTp = this.ListTab.TabPages[targetIndex];
8298                 this.ListTab.TabPages.Remove(mTp);
8299
8300                 if (targetIndex < baseIndex)
8301                     baseIndex--;
8302
8303                 if (isBeforeBaseTab)
8304                     ListTab.TabPages.Insert(baseIndex, mTp);
8305                 else
8306                     ListTab.TabPages.Insert(baseIndex + 1, mTp);
8307             }
8308
8309             SaveConfigsTabs();
8310         }
8311
8312         private void MakeReplyOrDirectStatus(bool isAuto = true, bool isReply = true, bool isAll = false)
8313         {
8314             //isAuto:true=先頭に挿入、false=カーソル位置に挿入
8315             //isReply:true=@,false=DM
8316             if (!StatusText.Enabled) return;
8317             if (_curList == null) return;
8318             if (_curTab == null) return;
8319             if (!this.ExistCurrentPost) return;
8320
8321             // 複数あてリプライはReplyではなく通常ポスト
8322             //↑仕様変更で全部リプライ扱いでOK(先頭ドット付加しない)
8323             //090403暫定でドットを付加しないようにだけ修正。単独と複数の処理は統合できると思われる。
8324             //090513 all @ replies 廃止の仕様変更によりドット付加に戻し(syo68k)
8325
8326             if (_curList.SelectedIndices.Count > 0)
8327             {
8328                 // アイテムが1件以上選択されている
8329                 if (_curList.SelectedIndices.Count == 1 && !isAll && this.ExistCurrentPost)
8330                 {
8331                     // 単独ユーザー宛リプライまたはDM
8332                     if ((_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage && isAuto) || (!isAuto && !isReply))
8333                     {
8334                         // ダイレクトメッセージ
8335                         StatusText.Text = "D " + _curPost.ScreenName + " " + StatusText.Text;
8336                         StatusText.SelectionStart = StatusText.Text.Length;
8337                         StatusText.Focus();
8338                         this.inReplyTo = null;
8339                         return;
8340                     }
8341                     if (string.IsNullOrEmpty(StatusText.Text))
8342                     {
8343                         //空の場合
8344
8345                         // ステータステキストが入力されていない場合先頭に@ユーザー名を追加する
8346                         StatusText.Text = "@" + _curPost.ScreenName + " ";
8347
8348                         var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8349                         var inReplyToScreenName = this._curPost.ScreenName;
8350                         this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8351                     }
8352                     else
8353                     {
8354                         //何か入力済の場合
8355
8356                         if (isAuto)
8357                         {
8358                             //1件選んでEnter or DoubleClick
8359                             if (StatusText.Text.Contains("@" + _curPost.ScreenName + " "))
8360                             {
8361                                 if (this.inReplyTo?.Item2 == _curPost.ScreenName)
8362                                 {
8363                                     //返信先書き換え
8364                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8365                                     var inReplyToScreenName = this._curPost.ScreenName;
8366                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8367                                 }
8368                                 return;
8369                             }
8370                             if (!StatusText.Text.StartsWith("@"))
8371                             {
8372                                 //文頭@以外
8373                                 if (StatusText.Text.StartsWith(". "))
8374                                 {
8375                                     // 複数リプライ
8376                                     StatusText.Text = StatusText.Text.Insert(2, "@" + _curPost.ScreenName + " ");
8377                                     this.inReplyTo = null;
8378                                 }
8379                                 else
8380                                 {
8381                                     // 単独リプライ
8382                                     StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8383                                     var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8384                                     var inReplyToScreenName = this._curPost.ScreenName;
8385                                     this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8386                                 }
8387                             }
8388                             else
8389                             {
8390                                 //文頭@
8391                                 // 複数リプライ
8392                                 StatusText.Text = ". @" + _curPost.ScreenName + " " + StatusText.Text;
8393                                 //StatusText.Text = "@" + _curPost.ScreenName + " " + StatusText.Text;
8394                                 this.inReplyTo = null;
8395                             }
8396                         }
8397                         else
8398                         {
8399                             //1件選んでCtrl-Rの場合(返信先操作せず)
8400                             int sidx = StatusText.SelectionStart;
8401                             string id = "@" + _curPost.ScreenName + " ";
8402                             if (sidx > 0)
8403                             {
8404                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8405                                 {
8406                                     id = " " + id;
8407                                 }
8408                             }
8409                             StatusText.Text = StatusText.Text.Insert(sidx, id);
8410                             sidx += id.Length;
8411                             //if (StatusText.Text.StartsWith("@"))
8412                             //{
8413                             //    //複数リプライ
8414                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8415                             //    sidx += 5 + _curPost.ScreenName.Length;
8416                             //}
8417                             //else
8418                             //{
8419                             //    // 複数リプライ
8420                             //    StatusText.Text = StatusText.Text.Insert(sidx, " @" + _curPost.ScreenName + " ");
8421                             //    sidx += 3 + _curPost.ScreenName.Length;
8422                             //}
8423                             StatusText.SelectionStart = sidx;
8424                             StatusText.Focus();
8425                             //_reply_to_id = 0;
8426                             //_reply_to_name = null;
8427                             return;
8428                         }
8429                     }
8430                 }
8431                 else
8432                 {
8433                     // 複数リプライ
8434                     if (!isAuto && !isReply) return;
8435
8436                     //C-S-rか、複数の宛先を選択中にEnter/DoubleClick/C-r/C-S-r
8437
8438                     if (isAuto)
8439                     {
8440                         //Enter or DoubleClick
8441
8442                         string sTxt = StatusText.Text;
8443                         if (!sTxt.StartsWith(". "))
8444                         {
8445                             sTxt = ". " + sTxt;
8446                             this.inReplyTo = null;
8447                         }
8448                         for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8449                         {
8450                             PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8451                             if (!sTxt.Contains("@" + post.ScreenName + " "))
8452                             {
8453                                 sTxt = sTxt.Insert(2, "@" + post.ScreenName + " ");
8454                                 //sTxt = "@" + post.ScreenName + " " + sTxt;
8455                             }
8456                         }
8457                         StatusText.Text = sTxt;
8458                     }
8459                     else
8460                     {
8461                         //C-S-r or C-r
8462                         if (_curList.SelectedIndices.Count > 1)
8463                         {
8464                             //複数ポスト選択
8465
8466                             string ids = "";
8467                             int sidx = StatusText.SelectionStart;
8468                             for (int cnt = 0; cnt < _curList.SelectedIndices.Count; cnt++)
8469                             {
8470                                 PostClass post = _statuses.Tabs[_curTab.Text][_curList.SelectedIndices[cnt]];
8471                                 if (!ids.Contains("@" + post.ScreenName + " ") &&
8472                                     !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8473                                 {
8474                                     ids += "@" + post.ScreenName + " ";
8475                                 }
8476                                 if (isAll)
8477                                 {
8478                                     foreach (string nm in post.ReplyToList)
8479                                     {
8480                                         if (!ids.Contains("@" + nm + " ") &&
8481                                             !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8482                                         {
8483                                             Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8484                                             if (m.Success)
8485                                                 ids += "@" + m.Result("${id}") + " ";
8486                                             else
8487                                                 ids += "@" + nm + " ";
8488                                         }
8489                                     }
8490                                 }
8491                             }
8492                             if (ids.Length == 0) return;
8493                             if (!StatusText.Text.StartsWith(". "))
8494                             {
8495                                 StatusText.Text = ". " + StatusText.Text;
8496                                 sidx += 2;
8497                                 this.inReplyTo = null;
8498                             }
8499                             if (sidx > 0)
8500                             {
8501                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8502                                 {
8503                                     ids = " " + ids;
8504                                 }
8505                             }
8506                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8507                             sidx += ids.Length;
8508                             //if (StatusText.Text.StartsWith("@"))
8509                             //{
8510                             //    StatusText.Text = ". " + StatusText.Text.Insert(sidx, ids);
8511                             //    sidx += 2 + ids.Length;
8512                             //}
8513                             //else
8514                             //{
8515                             //    StatusText.Text = StatusText.Text.Insert(sidx, ids);
8516                             //    sidx += 1 + ids.Length;
8517                             //}
8518                             StatusText.SelectionStart = sidx;
8519                             StatusText.Focus();
8520                             return;
8521                         }
8522                         else
8523                         {
8524                             //1件のみ選択のC-S-r(返信元付加する可能性あり)
8525
8526                             string ids = "";
8527                             int sidx = StatusText.SelectionStart;
8528                             PostClass post = _curPost;
8529                             if (!ids.Contains("@" + post.ScreenName + " ") &&
8530                                 !post.ScreenName.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8531                             {
8532                                 ids += "@" + post.ScreenName + " ";
8533                             }
8534                             foreach (string nm in post.ReplyToList)
8535                             {
8536                                 if (!ids.Contains("@" + nm + " ") &&
8537                                     !nm.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8538                                 {
8539                                     Match m = Regex.Match(post.TextFromApi, "[@@](?<id>" + nm + ")([^a-zA-Z0-9]|$)", RegexOptions.IgnoreCase);
8540                                     if (m.Success)
8541                                         ids += "@" + m.Result("${id}") + " ";
8542                                     else
8543                                         ids += "@" + nm + " ";
8544                                 }
8545                             }
8546                             if (!string.IsNullOrEmpty(post.RetweetedBy))
8547                             {
8548                                 if (!ids.Contains("@" + post.RetweetedBy + " ") &&
8549                                    !post.RetweetedBy.Equals(tw.Username, StringComparison.CurrentCultureIgnoreCase))
8550                                 {
8551                                     ids += "@" + post.RetweetedBy + " ";
8552                                 }
8553                             }
8554                             if (ids.Length == 0) return;
8555                             if (string.IsNullOrEmpty(StatusText.Text))
8556                             {
8557                                 //未入力の場合のみ返信先付加
8558                                 StatusText.Text = ids;
8559                                 StatusText.SelectionStart = ids.Length;
8560                                 StatusText.Focus();
8561
8562                                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
8563                                 var inReplyToScreenName = this._curPost.ScreenName;
8564                                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
8565                                 return;
8566                             }
8567
8568                             if (sidx > 0)
8569                             {
8570                                 if (StatusText.Text.Substring(sidx - 1, 1) != " ")
8571                                 {
8572                                     ids = " " + ids;
8573                                 }
8574                             }
8575                             StatusText.Text = StatusText.Text.Insert(sidx, ids);
8576                             sidx += ids.Length;
8577                             StatusText.SelectionStart = sidx;
8578                             StatusText.Focus();
8579                             return;
8580                         }
8581                     }
8582                 }
8583                 StatusText.SelectionStart = StatusText.Text.Length;
8584                 StatusText.Focus();
8585             }
8586         }
8587
8588         private void ListTab_MouseUp(object sender, MouseEventArgs e)
8589         {
8590             _tabDrag = false;
8591         }
8592
8593         private static int iconCnt = 0;
8594         private static int blinkCnt = 0;
8595         private static bool blink = false;
8596         private static bool idle = false;
8597
8598         private async Task RefreshTasktrayIcon(bool forceRefresh)
8599         {
8600             if (_colorize)
8601                 await this.Colorize();
8602
8603             if (!TimerRefreshIcon.Enabled) return;
8604             //Static usCheckCnt As int = 0
8605
8606             //Static iconDlListTopItem As ListViewItem = null
8607
8608             if (forceRefresh) idle = false;
8609
8610             //if (((ListView)ListTab.SelectedTab.Tag).TopItem == iconDlListTopItem)
8611             //    ((ImageDictionary)this.TIconDic).PauseGetImage = false;
8612             //else
8613             //    ((ImageDictionary)this.TIconDic).PauseGetImage = true;
8614             //
8615             //iconDlListTopItem = ((ListView)ListTab.SelectedTab.Tag).TopItem;
8616
8617             iconCnt += 1;
8618             blinkCnt += 1;
8619             //usCheckCnt += 1;
8620
8621             //if (usCheckCnt > 300)    //1min
8622             //{
8623             //    usCheckCnt = 0;
8624             //    if (!this.IsReceivedUserStream)
8625             //    {
8626             //        TraceOut("ReconnectUserStream");
8627             //        tw.ReconnectUserStream();
8628             //    }
8629             //}
8630
8631             var busy = this.workerSemaphore.CurrentCount != MAX_WORKER_THREADS;
8632
8633             if (iconCnt >= this.NIconRefresh.Length)
8634             {
8635                 iconCnt = 0;
8636             }
8637             if (blinkCnt > 10)
8638             {
8639                 blinkCnt = 0;
8640                 //未保存の変更を保存
8641                 SaveConfigsAll(true);
8642             }
8643
8644             if (busy)
8645             {
8646                 NotifyIcon1.Icon = NIconRefresh[iconCnt];
8647                 idle = false;
8648                 _myStatusError = false;
8649                 return;
8650             }
8651
8652             TabClass tb = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
8653             if (this._cfgCommon.ReplyIconState != MyCommon.REPLY_ICONSTATE.None && tb != null && tb.UnreadCount > 0)
8654             {
8655                 if (blinkCnt > 0) return;
8656                 blink = !blink;
8657                 if (blink || this._cfgCommon.ReplyIconState == MyCommon.REPLY_ICONSTATE.StaticIcon)
8658                 {
8659                     NotifyIcon1.Icon = ReplyIcon;
8660                 }
8661                 else
8662                 {
8663                     NotifyIcon1.Icon = ReplyIconBlink;
8664                 }
8665                 idle = false;
8666                 return;
8667             }
8668
8669             if (idle) return;
8670             idle = true;
8671             //優先度:エラー→オフライン→アイドル
8672             //エラーは更新アイコンでクリアされる
8673             if (_myStatusError)
8674             {
8675                 NotifyIcon1.Icon = NIconAtRed;
8676                 return;
8677             }
8678             if (_myStatusOnline)
8679             {
8680                 NotifyIcon1.Icon = NIconAt;
8681             }
8682             else
8683             {
8684                 NotifyIcon1.Icon = NIconAtSmoke;
8685             }
8686         }
8687
8688         private async void TimerRefreshIcon_Tick(object sender, EventArgs e)
8689         {
8690             //200ms
8691             await this.RefreshTasktrayIcon(false);
8692         }
8693
8694         private void ContextMenuTabProperty_Opening(object sender, CancelEventArgs e)
8695         {
8696             //右クリックの場合はタブ名が設定済。アプリケーションキーの場合は現在のタブを対象とする
8697             if (string.IsNullOrEmpty(_rclickTabName) || sender != ContextMenuTabProperty)
8698             {
8699                 if (ListTab != null && ListTab.SelectedTab != null)
8700                     _rclickTabName = ListTab.SelectedTab.Text;
8701                 else
8702                     return;
8703             }
8704
8705             if (_statuses == null) return;
8706             if (_statuses.Tabs == null) return;
8707
8708             TabClass tb = _statuses.Tabs[_rclickTabName];
8709             if (tb == null) return;
8710
8711             NotifyDispMenuItem.Checked = tb.Notify;
8712             this.NotifyTbMenuItem.Checked = tb.Notify;
8713
8714             soundfileListup = true;
8715             SoundFileComboBox.Items.Clear();
8716             this.SoundFileTbComboBox.Items.Clear();
8717             SoundFileComboBox.Items.Add("");
8718             this.SoundFileTbComboBox.Items.Add("");
8719             DirectoryInfo oDir = new DirectoryInfo(Application.StartupPath + Path.DirectorySeparatorChar);
8720             if (Directory.Exists(Path.Combine(Application.StartupPath, "Sounds")))
8721             {
8722                 oDir = oDir.GetDirectories("Sounds")[0];
8723             }
8724             foreach (FileInfo oFile in oDir.GetFiles("*.wav"))
8725             {
8726                 SoundFileComboBox.Items.Add(oFile.Name);
8727                 this.SoundFileTbComboBox.Items.Add(oFile.Name);
8728             }
8729             int idx = SoundFileComboBox.Items.IndexOf(tb.SoundFile);
8730             if (idx == -1) idx = 0;
8731             SoundFileComboBox.SelectedIndex = idx;
8732             this.SoundFileTbComboBox.SelectedIndex = idx;
8733             soundfileListup = false;
8734             UreadManageMenuItem.Checked = tb.UnreadManage;
8735             this.UnreadMngTbMenuItem.Checked = tb.UnreadManage;
8736
8737             TabMenuControl(_rclickTabName);
8738         }
8739
8740         private void TabMenuControl(string tabName)
8741         {
8742             var tabInfo = _statuses.GetTabByName(tabName);
8743
8744             this.FilterEditMenuItem.Enabled = true;
8745             this.EditRuleTbMenuItem.Enabled = true;
8746
8747             if (tabInfo.IsDefaultTabType)
8748             {
8749                 this.ProtectTabMenuItem.Enabled = false;
8750                 this.ProtectTbMenuItem.Enabled = false;
8751             }
8752             else
8753             {
8754                 this.ProtectTabMenuItem.Enabled = true;
8755                 this.ProtectTbMenuItem.Enabled = true;
8756             }
8757
8758             if (tabInfo.IsDefaultTabType || tabInfo.Protected)
8759             {
8760                 this.ProtectTabMenuItem.Checked = true;
8761                 this.ProtectTbMenuItem.Checked = true;
8762                 this.DeleteTabMenuItem.Enabled = false;
8763                 this.DeleteTbMenuItem.Enabled = false;
8764             }
8765             else
8766             {
8767                 this.ProtectTabMenuItem.Checked = false;
8768                 this.ProtectTbMenuItem.Checked = false;
8769                 this.DeleteTabMenuItem.Enabled = true;
8770                 this.DeleteTbMenuItem.Enabled = true;
8771             }
8772         }
8773
8774         private void ProtectTabMenuItem_Click(object sender, EventArgs e)
8775         {
8776             var checkState = ((ToolStripMenuItem)sender).Checked;
8777
8778             // チェック状態を同期
8779             this.ProtectTbMenuItem.Checked = checkState;
8780             this.ProtectTabMenuItem.Checked = checkState;
8781
8782             // ロック中はタブの削除を無効化
8783             this.DeleteTabMenuItem.Enabled = !checkState;
8784             this.DeleteTbMenuItem.Enabled = !checkState;
8785
8786             if (string.IsNullOrEmpty(_rclickTabName)) return;
8787             _statuses.Tabs[_rclickTabName].Protected = checkState;
8788
8789             SaveConfigsTabs();
8790         }
8791
8792         private void UreadManageMenuItem_Click(object sender, EventArgs e)
8793         {
8794             UreadManageMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8795             this.UnreadMngTbMenuItem.Checked = UreadManageMenuItem.Checked;
8796
8797             if (string.IsNullOrEmpty(_rclickTabName)) return;
8798             ChangeTabUnreadManage(_rclickTabName, UreadManageMenuItem.Checked);
8799
8800             SaveConfigsTabs();
8801         }
8802
8803         public void ChangeTabUnreadManage(string tabName, bool isManage)
8804         {
8805             var idx = this.GetTabPageIndex(tabName);
8806             if (idx == -1)
8807                 return;
8808
8809             _statuses.Tabs[tabName].UnreadManage = isManage;
8810             if (this._cfgCommon.TabIconDisp)
8811             {
8812                 if (_statuses.Tabs[tabName].UnreadCount > 0)
8813                     ListTab.TabPages[idx].ImageIndex = 0;
8814                 else
8815                     ListTab.TabPages[idx].ImageIndex = -1;
8816             }
8817
8818             if (_curTab.Text == tabName)
8819             {
8820                 this.PurgeListViewItemCache();
8821                 _curList.Refresh();
8822             }
8823
8824             SetMainWindowTitle();
8825             SetStatusLabelUrl();
8826             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
8827         }
8828
8829         private void NotifyDispMenuItem_Click(object sender, EventArgs e)
8830         {
8831             NotifyDispMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
8832             this.NotifyTbMenuItem.Checked = NotifyDispMenuItem.Checked;
8833
8834             if (string.IsNullOrEmpty(_rclickTabName)) return;
8835
8836             _statuses.Tabs[_rclickTabName].Notify = NotifyDispMenuItem.Checked;
8837
8838             SaveConfigsTabs();
8839         }
8840
8841         private void SoundFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
8842         {
8843             if (soundfileListup || string.IsNullOrEmpty(_rclickTabName)) return;
8844
8845             _statuses.Tabs[_rclickTabName].SoundFile = (string)((ToolStripComboBox)sender).SelectedItem;
8846
8847             SaveConfigsTabs();
8848         }
8849
8850         private void DeleteTabMenuItem_Click(object sender, EventArgs e)
8851         {
8852             if (string.IsNullOrEmpty(_rclickTabName) || sender == this.DeleteTbMenuItem) _rclickTabName = ListTab.SelectedTab.Text;
8853
8854             RemoveSpecifiedTab(_rclickTabName, true);
8855             SaveConfigsTabs();
8856         }
8857
8858         private void FilterEditMenuItem_Click(object sender, EventArgs e)
8859         {
8860             if (string.IsNullOrEmpty(_rclickTabName)) _rclickTabName = _statuses.GetTabByType(MyCommon.TabUsageType.Home).TabName;
8861
8862             using (var fltDialog = new FilterDialog())
8863             {
8864                 fltDialog.Owner = this;
8865                 fltDialog.SetCurrent(_rclickTabName);
8866                 fltDialog.ShowDialog(this);
8867             }
8868             this.TopMost = this._cfgCommon.AlwaysTop;
8869
8870             this.ApplyPostFilters();
8871             SaveConfigsTabs();
8872         }
8873
8874         private void AddTabMenuItem_Click(object sender, EventArgs e)
8875         {
8876             string tabName = null;
8877             MyCommon.TabUsageType tabUsage;
8878             using (InputTabName inputName = new InputTabName())
8879             {
8880                 inputName.TabName = _statuses.MakeTabName("MyTab");
8881                 inputName.IsShowUsage = true;
8882                 inputName.ShowDialog();
8883                 if (inputName.DialogResult == DialogResult.Cancel) return;
8884                 tabName = inputName.TabName;
8885                 tabUsage = inputName.Usage;
8886             }
8887             this.TopMost = this._cfgCommon.AlwaysTop;
8888             if (!string.IsNullOrEmpty(tabName))
8889             {
8890                 //List対応
8891                 ListElement list = null;
8892                 if (tabUsage == MyCommon.TabUsageType.Lists)
8893                 {
8894                     using (ListAvailable listAvail = new ListAvailable())
8895                     {
8896                         if (listAvail.ShowDialog(this) == DialogResult.Cancel) return;
8897                         if (listAvail.SelectedList == null) return;
8898                         list = listAvail.SelectedList;
8899                     }
8900                 }
8901                 if (!_statuses.AddTab(tabName, tabUsage, list) || !AddNewTab(tabName, false, tabUsage, list))
8902                 {
8903                     string tmp = string.Format(Properties.Resources.AddTabMenuItem_ClickText1, tabName);
8904                     MessageBox.Show(tmp, Properties.Resources.AddTabMenuItem_ClickText2, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
8905                 }
8906                 else
8907                 {
8908                     //成功
8909                     SaveConfigsTabs();
8910                     if (tabUsage == MyCommon.TabUsageType.PublicSearch)
8911                     {
8912                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8913                         ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
8914                     }
8915                     if (tabUsage == MyCommon.TabUsageType.Lists)
8916                     {
8917                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
8918                         var tab = this._statuses.Tabs[this._curTab.Text];
8919                         this.GetListTimelineAsync(tab);
8920                     }
8921                 }
8922             }
8923         }
8924
8925         private void TabMenuItem_Click(object sender, EventArgs e)
8926         {
8927             using (var fltDialog = new FilterDialog())
8928             {
8929                 fltDialog.Owner = this;
8930
8931                 //選択発言を元にフィルタ追加
8932                 foreach (int idx in _curList.SelectedIndices)
8933                 {
8934                     string tabName;
8935                     //タブ選択(or追加)
8936                     if (!SelectTab(out tabName)) return;
8937
8938                     fltDialog.SetCurrent(tabName);
8939                     if (_statuses.Tabs[_curTab.Text][idx].RetweetedId == null)
8940                     {
8941                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].ScreenName, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8942                     }
8943                     else
8944                     {
8945                         fltDialog.AddNewFilter(_statuses.Tabs[_curTab.Text][idx].RetweetedBy, _statuses.Tabs[_curTab.Text][idx].TextFromApi);
8946                     }
8947                     fltDialog.ShowDialog(this);
8948                     this.TopMost = this._cfgCommon.AlwaysTop;
8949                 }
8950             }
8951
8952             this.ApplyPostFilters();
8953             SaveConfigsTabs();
8954             if (this.ListTab.SelectedTab != null &&
8955                 ((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices.Count > 0)
8956             {
8957                 _curPost = _statuses.Tabs[this.ListTab.SelectedTab.Text][((DetailsListView)this.ListTab.SelectedTab.Tag).SelectedIndices[0]];
8958             }
8959         }
8960
8961         protected override bool ProcessDialogKey(Keys keyData)
8962         {
8963             //TextBox1でEnterを押してもビープ音が鳴らないようにする
8964             if ((keyData & Keys.KeyCode) == Keys.Enter)
8965             {
8966                 if (StatusText.Focused)
8967                 {
8968                     bool _NewLine = false;
8969                     bool _Post = false;
8970
8971                     if (this._cfgCommon.PostCtrlEnter) //Ctrl+Enter投稿時
8972                     {
8973                         if (StatusText.Multiline)
8974                         {
8975                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
8976
8977                             if ((keyData & Keys.Control) == Keys.Control) _Post = true;
8978                         }
8979                         else
8980                         {
8981                             if (((keyData & Keys.Control) == Keys.Control)) _Post = true;
8982                         }
8983
8984                     }
8985                     else if (this._cfgCommon.PostShiftEnter) //SHift+Enter投稿時
8986                     {
8987                         if (StatusText.Multiline)
8988                         {
8989                             if ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) != Keys.Shift) _NewLine = true;
8990
8991                             if ((keyData & Keys.Shift) == Keys.Shift) _Post = true;
8992                         }
8993                         else
8994                         {
8995                             if (((keyData & Keys.Shift) == Keys.Shift)) _Post = true;
8996                         }
8997
8998                     }
8999                     else //Enter投稿時
9000                     {
9001                         if (StatusText.Multiline)
9002                         {
9003                             if ((keyData & Keys.Shift) == Keys.Shift && (keyData & Keys.Control) != Keys.Control) _NewLine = true;
9004
9005                             if (((keyData & Keys.Control) != Keys.Control && (keyData & Keys.Shift) != Keys.Shift) ||
9006                                 ((keyData & Keys.Control) == Keys.Control && (keyData & Keys.Shift) == Keys.Shift)) _Post = true;
9007                         }
9008                         else
9009                         {
9010                             if (((keyData & Keys.Shift) == Keys.Shift) ||
9011                                 (((keyData & Keys.Control) != Keys.Control) &&
9012                                 ((keyData & Keys.Shift) != Keys.Shift))) _Post = true;
9013                         }
9014                     }
9015
9016                     if (_NewLine)
9017                     {
9018                         int pos1 = StatusText.SelectionStart;
9019                         if (StatusText.SelectionLength > 0)
9020                         {
9021                             StatusText.Text = StatusText.Text.Remove(pos1, StatusText.SelectionLength);  //選択状態文字列削除
9022                         }
9023                         StatusText.Text = StatusText.Text.Insert(pos1, Environment.NewLine);  //改行挿入
9024                         StatusText.SelectionStart = pos1 + Environment.NewLine.Length;    //カーソルを改行の次の文字へ移動
9025                         return true;
9026                     }
9027                     else if (_Post)
9028                     {
9029                         PostButton_Click(null, null);
9030                         return true;
9031                     }
9032                 }
9033                 else if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch &&
9034                          (ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focused ||
9035                          ListTab.SelectedTab.Controls["panelSearch"].Controls["comboLang"].Focused))
9036                 {
9037                     this.SearchButton_Click(ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"], null);
9038                     return true;
9039                 }
9040             }
9041
9042             return base.ProcessDialogKey(keyData);
9043         }
9044
9045         private void ReplyAllStripMenuItem_Click(object sender, EventArgs e)
9046         {
9047             MakeReplyOrDirectStatus(false, true, true);
9048         }
9049
9050         private void IDRuleMenuItem_Click(object sender, EventArgs e)
9051         {
9052             string tabName;
9053
9054             //未選択なら処理終了
9055             if (_curList.SelectedIndices.Count == 0) return;
9056
9057             //タブ選択(or追加)
9058             if (!SelectTab(out tabName)) return;
9059
9060             var tab = this._statuses.Tabs[tabName];
9061
9062             bool mv;
9063             bool mk;
9064             if (tab.TabType != MyCommon.TabUsageType.Mute)
9065             {
9066                 this.MoveOrCopy(out mv, out mk);
9067             }
9068             else
9069             {
9070                 // ミュートタブでは常に MoveMatches を true にする
9071                 mv = true;
9072                 mk = false;
9073             }
9074
9075             List<string> ids = new List<string>();
9076             foreach (int idx in _curList.SelectedIndices)
9077             {
9078                 PostClass post = _statuses.Tabs[_curTab.Text][idx];
9079                 if (!ids.Contains(post.ScreenName))
9080                 {
9081                     PostFilterRule fc = new PostFilterRule();
9082                     ids.Add(post.ScreenName);
9083                     if (post.RetweetedId == null)
9084                     {
9085                         fc.FilterName = post.ScreenName;
9086                     }
9087                     else
9088                     {
9089                         fc.FilterName = post.RetweetedBy;
9090                     }
9091                     fc.UseNameField = true;
9092                     fc.MoveMatches = mv;
9093                     fc.MarkMatches = mk;
9094                     fc.UseRegex = false;
9095                     fc.FilterByUrl = false;
9096                     tab.AddFilter(fc);
9097                 }
9098             }
9099             if (ids.Count != 0)
9100             {
9101                 List<string> atids = new List<string>();
9102                 foreach (string id in ids)
9103                 {
9104                     atids.Add("@" + id);
9105                 }
9106                 int cnt = AtIdSupl.ItemCount;
9107                 AtIdSupl.AddRangeItem(atids.ToArray());
9108                 if (AtIdSupl.ItemCount != cnt) _modifySettingAtId = true;
9109             }
9110
9111             this.ApplyPostFilters();
9112             SaveConfigsTabs();
9113         }
9114
9115         private void SourceRuleMenuItem_Click(object sender, EventArgs e)
9116         {
9117             if (this._curList.SelectedIndices.Count == 0)
9118                 return;
9119
9120             // タブ選択ダイアログを表示(or追加)
9121             string tabName;
9122             if (!this.SelectTab(out tabName))
9123                 return;
9124
9125             var currentTab = this._statuses.Tabs[this._curTab.Text];
9126             var filterTab = this._statuses.Tabs[tabName];
9127
9128             bool mv;
9129             bool mk;
9130             if (filterTab.TabType != MyCommon.TabUsageType.Mute)
9131             {
9132                 // フィルタ動作選択ダイアログを表示(移動/コピー, マーク有無)
9133                 this.MoveOrCopy(out mv, out mk);
9134             }
9135             else
9136             {
9137                 // ミュートタブでは常に MoveMatches を true にする
9138                 mv = true;
9139                 mk = false;
9140             }
9141
9142             // 振り分けルールに追加するSource
9143             var sources = new HashSet<string>();
9144
9145             foreach (var idx in this._curList.SelectedIndices.Cast<int>())
9146             {
9147                 var post = currentTab[idx];
9148                 var filterSource = post.Source;
9149
9150                 if (sources.Add(filterSource))
9151                 {
9152                     var filter = new PostFilterRule
9153                     {
9154                         FilterSource = filterSource,
9155                         MoveMatches = mv,
9156                         MarkMatches = mk,
9157                         UseRegex = false,
9158                         FilterByUrl = false,
9159                     };
9160                     filterTab.AddFilter(filter);
9161                 }
9162             }
9163
9164             this.ApplyPostFilters();
9165             this.SaveConfigsTabs();
9166         }
9167
9168         private bool SelectTab(out string tabName)
9169         {
9170             do
9171             {
9172                 tabName = null;
9173
9174                 //振り分け先タブ選択
9175                 using (var dialog = new TabsDialog(_statuses))
9176                 {
9177                     if (dialog.ShowDialog(this) == DialogResult.Cancel) return false;
9178
9179                     var selectedTab = dialog.SelectedTab;
9180                     tabName = selectedTab == null ? null : selectedTab.TabName;
9181                 }
9182
9183                 ListTab.SelectedTab.Focus();
9184                 //新規タブを選択→タブ作成
9185                 if (tabName == null)
9186                 {
9187                     using (InputTabName inputName = new InputTabName())
9188                     {
9189                         inputName.TabName = _statuses.MakeTabName("MyTab");
9190                         inputName.ShowDialog();
9191                         if (inputName.DialogResult == DialogResult.Cancel) return false;
9192                         tabName = inputName.TabName;
9193                     }
9194                     this.TopMost = this._cfgCommon.AlwaysTop;
9195                     if (!string.IsNullOrEmpty(tabName))
9196                     {
9197                         if (!_statuses.AddTab(tabName, MyCommon.TabUsageType.UserDefined, null) || !AddNewTab(tabName, false, MyCommon.TabUsageType.UserDefined))
9198                         {
9199                             string tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText2, tabName);
9200                             MessageBox.Show(tmp, Properties.Resources.IDRuleMenuItem_ClickText3, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
9201                             //もう一度タブ名入力
9202                         }
9203                         else
9204                         {
9205                             return true;
9206                         }
9207                     }
9208                 }
9209                 else
9210                 {
9211                     //既存タブを選択
9212                     return true;
9213                 }
9214             }
9215             while (true);
9216         }
9217
9218         private void MoveOrCopy(out bool move, out bool mark)
9219         {
9220             {
9221                 //移動するか?
9222                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText4, Environment.NewLine);
9223                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText5, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9224                     move = false;
9225                 else
9226                     move = true;
9227             }
9228             if (!move)
9229             {
9230                 //マークするか?
9231                 string _tmp = string.Format(Properties.Resources.IDRuleMenuItem_ClickText6, Environment.NewLine);
9232                 if (MessageBox.Show(_tmp, Properties.Resources.IDRuleMenuItem_ClickText7, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
9233                     mark = true;
9234                 else
9235                     mark = false;
9236             }
9237             else
9238             {
9239                 mark = false;
9240             }
9241         }
9242         private void CopySTOTMenuItem_Click(object sender, EventArgs e)
9243         {
9244             this.CopyStot();
9245         }
9246
9247         private void CopyURLMenuItem_Click(object sender, EventArgs e)
9248         {
9249             this.CopyIdUri();
9250         }
9251
9252         private void SelectAllMenuItem_Click(object sender, EventArgs e)
9253         {
9254             if (StatusText.Focused)
9255             {
9256                 // 発言欄でのCtrl+A
9257                 StatusText.SelectAll();
9258             }
9259             else
9260             {
9261                 // ListView上でのCtrl+A
9262                 NativeMethods.SelectAllItems(this._curList);
9263             }
9264         }
9265
9266         private void MoveMiddle()
9267         {
9268             ListViewItem _item;
9269             int idx1;
9270             int idx2;
9271
9272             if (_curList.SelectedIndices.Count == 0) return;
9273
9274             int idx = _curList.SelectedIndices[0];
9275
9276             _item = _curList.GetItemAt(0, 25);
9277             if (_item == null)
9278                 idx1 = 0;
9279             else
9280                 idx1 = _item.Index;
9281
9282             _item = _curList.GetItemAt(0, _curList.ClientSize.Height - 1);
9283             if (_item == null)
9284                 idx2 = _curList.VirtualListSize - 1;
9285             else
9286                 idx2 = _item.Index;
9287
9288             idx -= Math.Abs(idx1 - idx2) / 2;
9289             if (idx < 0) idx = 0;
9290
9291             _curList.EnsureVisible(_curList.VirtualListSize - 1);
9292             _curList.EnsureVisible(idx);
9293         }
9294
9295         private async void OpenURLMenuItem_Click(object sender, EventArgs e)
9296         {
9297             var linkElements = this.PostBrowser.Document.Links.Cast<HtmlElement>()
9298                 .Where(x => x.GetAttribute("className") != "tweet-quote-link") // 引用ツイートで追加されたリンクを除く
9299                 .ToArray();
9300
9301             if (linkElements.Length > 0)
9302             {
9303                 UrlDialog.ClearUrl();
9304
9305                 string openUrlStr = "";
9306
9307                 if (linkElements.Length == 1)
9308                 {
9309                     // ツイートに含まれる URL が 1 つのみの場合
9310                     //   => OpenURL ダイアログを表示せずにリンクを開く
9311
9312                     string urlStr = "";
9313                     try
9314                     {
9315                         urlStr = MyCommon.IDNEncode(linkElements[0].GetAttribute("href"));
9316                     }
9317                     catch (ArgumentException)
9318                     {
9319                         //変なHTML?
9320                         return;
9321                     }
9322                     catch (Exception)
9323                     {
9324                         return;
9325                     }
9326                     if (string.IsNullOrEmpty(urlStr)) return;
9327                     openUrlStr = MyCommon.urlEncodeMultibyteChar(urlStr);
9328
9329                     // Ctrl+E で呼ばれた場合を考慮し isReverseSettings の判定を行わない
9330                     await this.OpenUriAsync(new Uri(openUrlStr));
9331                 }
9332                 else
9333                 {
9334                     // ツイートに含まれる URL が複数ある場合
9335                     //   => OpenURL を表示しユーザーが選択したリンクを開く
9336
9337                     foreach (var linkElm in linkElements)
9338                     {
9339                         string urlStr = "";
9340                         string linkText = "";
9341                         string href = "";
9342                         try
9343                         {
9344                             urlStr = linkElm.GetAttribute("title");
9345                             href = MyCommon.IDNEncode(linkElm.GetAttribute("href"));
9346                             if (string.IsNullOrEmpty(urlStr)) urlStr = href;
9347                             linkText = linkElm.InnerText;
9348                         }
9349                         catch (ArgumentException)
9350                         {
9351                             //変なHTML?
9352                             return;
9353                         }
9354                         catch (Exception)
9355                         {
9356                             return;
9357                         }
9358                         if (string.IsNullOrEmpty(urlStr)) continue;
9359                         UrlDialog.AddUrl(new OpenUrlItem(linkText, MyCommon.urlEncodeMultibyteChar(urlStr), href));
9360                     }
9361                     try
9362                     {
9363                         if (UrlDialog.ShowDialog() == DialogResult.OK)
9364                         {
9365                             openUrlStr = UrlDialog.SelectedUrl;
9366
9367                             // Ctrlを押しながらリンクを開いた場合は、設定と逆の動作をするフラグを true としておく
9368                             await this.OpenUriAsync(new Uri(openUrlStr), MyCommon.IsKeyDown(Keys.Control));
9369                         }
9370                     }
9371                     catch (Exception)
9372                     {
9373                         return;
9374                     }
9375                     this.TopMost = this._cfgCommon.AlwaysTop;
9376                 }
9377             }
9378         }
9379
9380         private void ClearTabMenuItem_Click(object sender, EventArgs e)
9381         {
9382             if (string.IsNullOrEmpty(_rclickTabName)) return;
9383             ClearTab(_rclickTabName, true);
9384         }
9385
9386         private void ClearTab(string tabName, bool showWarning)
9387         {
9388             if (showWarning)
9389             {
9390                 string tmp = string.Format(Properties.Resources.ClearTabMenuItem_ClickText1, Environment.NewLine);
9391                 if (MessageBox.Show(tmp, tabName + " " + Properties.Resources.ClearTabMenuItem_ClickText2, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
9392                 {
9393                     return;
9394                 }
9395             }
9396
9397             _statuses.ClearTabIds(tabName);
9398             if (ListTab.SelectedTab.Text == tabName)
9399             {
9400                 _anchorPost = null;
9401                 _anchorFlag = false;
9402                 this.PurgeListViewItemCache();
9403                 _curItemIndex = -1;
9404                 _curPost = null;
9405             }
9406             foreach (TabPage tb in ListTab.TabPages)
9407             {
9408                 if (tb.Text == tabName)
9409                 {
9410                     tb.ImageIndex = -1;
9411                     ((DetailsListView)tb.Tag).VirtualListSize = 0;
9412                     break;
9413                 }
9414             }
9415             if (!this._cfgCommon.TabIconDisp) ListTab.Refresh();
9416
9417             SetMainWindowTitle();
9418             SetStatusLabelUrl();
9419         }
9420
9421         private static long followers = 0;
9422
9423         private void SetMainWindowTitle()
9424         {
9425             //メインウインドウタイトルの書き換え
9426             StringBuilder ttl = new StringBuilder(256);
9427             int ur = 0;
9428             int al = 0;
9429             if (this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.None &&
9430                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Post &&
9431                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.Ver &&
9432                 this._cfgCommon.DispLatestPost != MyCommon.DispTitleEnum.OwnStatus)
9433             {
9434                 foreach (var tab in _statuses.Tabs.Values)
9435                 {
9436                     ur += tab.UnreadCount;
9437                     al += tab.AllCount;
9438                 }
9439             }
9440
9441             if (this._cfgCommon.DispUsername) ttl.Append(tw.Username).Append(" - ");
9442             ttl.Append(Application.ProductName);
9443             ttl.Append("  ");
9444             switch (this._cfgCommon.DispLatestPost)
9445             {
9446                 case MyCommon.DispTitleEnum.Ver:
9447                     ttl.Append("Ver:").Append(MyCommon.GetReadableVersion());
9448                     break;
9449                 case MyCommon.DispTitleEnum.Post:
9450                     if (_history != null && _history.Count > 1)
9451                         ttl.Append(_history[_history.Count - 2].status.Replace("\r\n", " "));
9452                     break;
9453                 case MyCommon.DispTitleEnum.UnreadRepCount:
9454                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText1, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9455                     break;
9456                 case MyCommon.DispTitleEnum.UnreadAllCount:
9457                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText2, ur);
9458                     break;
9459                 case MyCommon.DispTitleEnum.UnreadAllRepCount:
9460                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText3, ur, _statuses.GetTabByType(MyCommon.TabUsageType.Mentions).UnreadCount + _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage).UnreadCount);
9461                     break;
9462                 case MyCommon.DispTitleEnum.UnreadCountAllCount:
9463                     ttl.AppendFormat(Properties.Resources.SetMainWindowTitleText4, ur, al);
9464                     break;
9465                 case MyCommon.DispTitleEnum.OwnStatus:
9466                     if (followers == 0 && tw.FollowersCount > 0) followers = tw.FollowersCount;
9467                     ttl.AppendFormat(Properties.Resources.OwnStatusTitle, tw.StatusesCount, tw.FriendsCount, tw.FollowersCount, tw.FollowersCount - followers);
9468                     break;
9469             }
9470
9471             try
9472             {
9473                 this.Text = ttl.ToString();
9474             }
9475             catch (AccessViolationException)
9476             {
9477                 //原因不明。ポスト内容に依存か?たまーに発生するが再現せず。
9478             }
9479         }
9480
9481         private string GetStatusLabelText()
9482         {
9483             //ステータス欄にカウント表示
9484             //タブ未読数/タブ発言数 全未読数/総発言数 (未読@+未読DM数)
9485             if (_statuses == null) return "";
9486             TabClass tbRep = _statuses.GetTabByType(MyCommon.TabUsageType.Mentions);
9487             TabClass tbDm = _statuses.GetTabByType(MyCommon.TabUsageType.DirectMessage);
9488             if (tbRep == null || tbDm == null) return "";
9489             int urat = tbRep.UnreadCount + tbDm.UnreadCount;
9490             int ur = 0;
9491             int al = 0;
9492             int tur = 0;
9493             int tal = 0;
9494             StringBuilder slbl = new StringBuilder(256);
9495             try
9496             {
9497                 foreach (var tab in _statuses.Tabs.Values)
9498                 {
9499                     ur += tab.UnreadCount;
9500                     al += tab.AllCount;
9501                     if (_curTab != null && tab.TabName.Equals(_curTab.Text))
9502                     {
9503                         tur = tab.UnreadCount;
9504                         tal = tab.AllCount;
9505                     }
9506                 }
9507             }
9508             catch (Exception)
9509             {
9510                 return "";
9511             }
9512
9513             UnreadCounter = ur;
9514             UnreadAtCounter = urat;
9515
9516             slbl.AppendFormat(Properties.Resources.SetStatusLabelText1, tur, tal, ur, al, urat, _postTimestamps.Count, _favTimestamps.Count, _tlCount);
9517             if (this._cfgCommon.TimelinePeriod == 0)
9518             {
9519                 slbl.Append(Properties.Resources.SetStatusLabelText2);
9520             }
9521             else
9522             {
9523                 slbl.Append(this._cfgCommon.TimelinePeriod + Properties.Resources.SetStatusLabelText3);
9524             }
9525             return slbl.ToString();
9526         }
9527
9528         private void TwitterApiStatus_AccessLimitUpdated(object sender, EventArgs e)
9529         {
9530             try
9531             {
9532                 if (this.InvokeRequired && !this.IsDisposed)
9533                 {
9534                     this.Invoke((MethodInvoker)(() => this.TwitterApiStatus_AccessLimitUpdated(sender, e)));
9535                 }
9536                 else
9537                 {
9538                     var endpointName = (e as TwitterApiStatus.AccessLimitUpdatedEventArgs).EndpointName;
9539                     SetApiStatusLabel(endpointName);
9540                 }
9541             }
9542             catch (ObjectDisposedException)
9543             {
9544                 return;
9545             }
9546             catch (InvalidOperationException)
9547             {
9548                 return;
9549             }
9550         }
9551
9552         private void SetApiStatusLabel(string endpointName = null)
9553         {
9554             if (_curTab == null)
9555             {
9556                 this.toolStripApiGauge.ApiEndpoint = null;
9557             }
9558             else
9559             {
9560                 var tabType = _statuses.Tabs[_curTab.Text].TabType;
9561
9562                 if (endpointName == null)
9563                 {
9564                     // 表示中のタブに応じて更新
9565                     switch (tabType)
9566                     {
9567                         case MyCommon.TabUsageType.Home:
9568                         case MyCommon.TabUsageType.UserDefined:
9569                             endpointName = "/statuses/home_timeline";
9570                             break;
9571
9572                         case MyCommon.TabUsageType.Mentions:
9573                             endpointName = "/statuses/mentions_timeline";
9574                             break;
9575
9576                         case MyCommon.TabUsageType.Favorites:
9577                             endpointName = "/favorites/list";
9578                             break;
9579
9580                         case MyCommon.TabUsageType.DirectMessage:
9581                             endpointName = "/direct_messages";
9582                             break;
9583
9584                         case MyCommon.TabUsageType.UserTimeline:
9585                             endpointName = "/statuses/user_timeline";
9586                             break;
9587
9588                         case MyCommon.TabUsageType.Lists:
9589                             endpointName = "/lists/statuses";
9590                             break;
9591
9592                         case MyCommon.TabUsageType.PublicSearch:
9593                             endpointName = "/search/tweets";
9594                             break;
9595
9596                         case MyCommon.TabUsageType.Related:
9597                             endpointName = "/statuses/show/:id";
9598                             break;
9599
9600                         default:
9601                             break;
9602                     }
9603
9604                     this.toolStripApiGauge.ApiEndpoint = endpointName;
9605                 }
9606                 else
9607                 {
9608                     // 表示中のタブに関連する endpoint であれば更新
9609                     var update = false;
9610
9611                     switch (endpointName)
9612                     {
9613                         case "/statuses/home_timeline":
9614                             update = tabType == MyCommon.TabUsageType.Home ||
9615                                      tabType == MyCommon.TabUsageType.UserDefined;
9616                             break;
9617
9618                         case "/statuses/mentions_timeline":
9619                             update = tabType == MyCommon.TabUsageType.Mentions;
9620                             break;
9621
9622                         case "/favorites/list":
9623                             update = tabType == MyCommon.TabUsageType.Favorites;
9624                             break;
9625
9626                         case "/direct_messages:":
9627                             update = tabType == MyCommon.TabUsageType.DirectMessage;
9628                             break;
9629
9630                         case "/statuses/user_timeline":
9631                             update = tabType == MyCommon.TabUsageType.UserTimeline;
9632                             break;
9633
9634                         case "/lists/statuses":
9635                             update = tabType == MyCommon.TabUsageType.Lists;
9636                             break;
9637
9638                         case "/search/tweets":
9639                             update = tabType == MyCommon.TabUsageType.PublicSearch;
9640                             break;
9641
9642                         case "/statuses/show/:id":
9643                             update = tabType == MyCommon.TabUsageType.Related;
9644                             break;
9645
9646                         default:
9647                             break;
9648                     }
9649
9650                     if (update)
9651                     {
9652                         this.toolStripApiGauge.ApiEndpoint = endpointName;
9653                     }
9654                 }
9655             }
9656         }
9657
9658         private void SetStatusLabelUrl()
9659         {
9660             StatusLabelUrl.Text = GetStatusLabelText();
9661         }
9662
9663         public void SetStatusLabel(string text)
9664         {
9665             StatusLabel.Text = text;
9666         }
9667
9668         private static StringBuilder ur = new StringBuilder(64);
9669
9670         private void SetNotifyIconText()
9671         {
9672             // タスクトレイアイコンのツールチップテキスト書き換え
9673             // Tween [未読/@]
9674             ur.Remove(0, ur.Length);
9675             if (this._cfgCommon.DispUsername)
9676             {
9677                 ur.Append(tw.Username);
9678                 ur.Append(" - ");
9679             }
9680             ur.Append(Application.ProductName);
9681 #if DEBUG
9682             ur.Append("(Debug Build)");
9683 #endif
9684             if (UnreadCounter != -1 && UnreadAtCounter != -1)
9685             {
9686                 ur.Append(" [");
9687                 ur.Append(UnreadCounter);
9688                 ur.Append("/@");
9689                 ur.Append(UnreadAtCounter);
9690                 ur.Append("]");
9691             }
9692             NotifyIcon1.Text = ur.ToString();
9693         }
9694
9695         internal void CheckReplyTo(string StatusText)
9696         {
9697             MatchCollection m;
9698             //ハッシュタグの保存
9699             m = Regex.Matches(StatusText, Twitter.HASHTAG, RegexOptions.IgnoreCase);
9700             string hstr = "";
9701             foreach (Match hm in m)
9702             {
9703                 if (!hstr.Contains("#" + hm.Result("$3") + " "))
9704                 {
9705                     hstr += "#" + hm.Result("$3") + " ";
9706                     HashSupl.AddItem("#" + hm.Result("$3"));
9707                 }
9708             }
9709             if (!string.IsNullOrEmpty(HashMgr.UseHash) && !hstr.Contains(HashMgr.UseHash + " "))
9710             {
9711                 hstr += HashMgr.UseHash;
9712             }
9713             if (!string.IsNullOrEmpty(hstr)) HashMgr.AddHashToHistory(hstr.Trim(), false);
9714
9715             // 本当にリプライ先指定すべきかどうかの判定
9716             m = Regex.Matches(StatusText, "(^|[ -/:-@[-^`{-~])(?<id>@[a-zA-Z0-9_]+)");
9717
9718             if (this._cfgCommon.UseAtIdSupplement)
9719             {
9720                 int bCnt = AtIdSupl.ItemCount;
9721                 foreach (Match mid in m)
9722                 {
9723                     AtIdSupl.AddItem(mid.Result("${id}"));
9724                 }
9725                 if (bCnt != AtIdSupl.ItemCount) _modifySettingAtId = true;
9726             }
9727
9728             // リプライ先ステータスIDの指定がない場合は指定しない
9729             if (this.inReplyTo == null)
9730                 return;
9731
9732             // 通常Reply
9733             // 次の条件を満たす場合に in_reply_to_status_id 指定
9734             // 1. Twitterによりリンクと判定される @idが文中に1つ含まれる (2009/5/28 リンク化される@IDのみカウントするように修正)
9735             // 2. リプライ先ステータスIDが設定されている(リストをダブルクリックで返信している)
9736             // 3. 文中に含まれた@idがリプライ先のポスト者のIDと一致する
9737
9738             if (m != null)
9739             {
9740                 var inReplyToScreenName = this.inReplyTo.Item2;
9741                 if (StatusText.StartsWith("@"))
9742                 {
9743                     if (StatusText.StartsWith("@" + inReplyToScreenName)) return;
9744                 }
9745                 else
9746                 {
9747                     foreach (Match mid in m)
9748                     {
9749                         if (StatusText.Contains("RT " + mid.Result("${id}") + ":") && mid.Result("${id}") == "@" + inReplyToScreenName) return;
9750                     }
9751                 }
9752             }
9753
9754             this.inReplyTo = null;
9755         }
9756
9757         private void TweenMain_Resize(object sender, EventArgs e)
9758         {
9759             if (!_initialLayout && this._cfgCommon.MinimizeToTray && WindowState == FormWindowState.Minimized)
9760             {
9761                 this.Visible = false;
9762             }
9763             if (_initialLayout && _cfgLocal != null && this.WindowState == FormWindowState.Normal && this.Visible)
9764             {
9765                 // 現在の DPI と設定保存時の DPI との比を取得する
9766                 var configScaleFactor = this._cfgLocal.GetConfigScaleFactor(this.CurrentAutoScaleDimensions);
9767
9768                 this.ClientSize = ScaleBy(configScaleFactor, _cfgLocal.FormSize);
9769                 //_mySize = this.ClientSize;                     //サイズ保持(最小化・最大化されたまま終了した場合の対応用)
9770                 this.DesktopLocation = _cfgLocal.FormLocation;
9771                 //_myLoc = this.DesktopLocation;                        //位置保持(最小化・最大化されたまま終了した場合の対応用)
9772
9773                 // Splitterの位置設定
9774                 var splitterDistance = ScaleBy(configScaleFactor.Height, _cfgLocal.SplitterDistance);
9775                 if (splitterDistance > this.SplitContainer1.Panel1MinSize &&
9776                     splitterDistance < this.SplitContainer1.Height - this.SplitContainer1.Panel2MinSize - this.SplitContainer1.SplitterWidth)
9777                 {
9778                     this.SplitContainer1.SplitterDistance = splitterDistance;
9779                 }
9780
9781                 //発言欄複数行
9782                 StatusText.Multiline = _cfgLocal.StatusMultiline;
9783                 if (StatusText.Multiline)
9784                 {
9785                     var statusTextHeight = ScaleBy(configScaleFactor.Height, _cfgLocal.StatusTextHeight);
9786                     int dis = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9787                     if (dis > SplitContainer2.Panel1MinSize && dis < SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth)
9788                     {
9789                         SplitContainer2.SplitterDistance = SplitContainer2.Height - statusTextHeight - SplitContainer2.SplitterWidth;
9790                     }
9791                     StatusText.Height = statusTextHeight;
9792                 }
9793                 else
9794                 {
9795                     if (SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth > 0)
9796                     {
9797                         SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
9798                     }
9799                 }
9800
9801                 var previewDistance = ScaleBy(configScaleFactor.Width, _cfgLocal.PreviewDistance);
9802                 if (previewDistance > this.SplitContainer3.Panel1MinSize && previewDistance < this.SplitContainer3.Width - this.SplitContainer3.Panel2MinSize - this.SplitContainer3.SplitterWidth)
9803                 {
9804                     this.SplitContainer3.SplitterDistance = previewDistance;
9805                 }
9806
9807                 // Panel2Collapsed は SplitterDistance の設定を終えるまで true にしない
9808                 this.SplitContainer3.Panel2Collapsed = true;
9809
9810                 _initialLayout = false;
9811             }
9812             if (this.WindowState != FormWindowState.Minimized)
9813             {
9814                 _formWindowState = this.WindowState;
9815             }
9816         }
9817
9818         private void PlaySoundMenuItem_CheckedChanged(object sender, EventArgs e)
9819         {
9820             PlaySoundMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
9821             this.PlaySoundFileMenuItem.Checked = PlaySoundMenuItem.Checked;
9822             if (PlaySoundMenuItem.Checked)
9823             {
9824                 this._cfgCommon.PlaySound = true;
9825             }
9826             else
9827             {
9828                 this._cfgCommon.PlaySound = false;
9829             }
9830             _modifySettingCommon = true;
9831         }
9832
9833         private void SplitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
9834         {
9835             if (this._initialLayout)
9836                 return;
9837
9838             int splitterDistance;
9839             switch (this.WindowState)
9840             {
9841                 case FormWindowState.Normal:
9842                     splitterDistance = this.SplitContainer1.SplitterDistance;
9843                     break;
9844                 case FormWindowState.Maximized:
9845                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
9846                     var normalContainerHeight = this._mySize.Height - this.ToolStripContainer1.TopToolStripPanel.Height - this.ToolStripContainer1.BottomToolStripPanel.Height;
9847                     splitterDistance = this.SplitContainer1.SplitterDistance - (this.SplitContainer1.Height - normalContainerHeight);
9848                     splitterDistance = Math.Min(splitterDistance, normalContainerHeight - this.SplitContainer1.SplitterWidth - this.SplitContainer1.Panel2MinSize);
9849                     break;
9850                 default:
9851                     return;
9852             }
9853
9854             this._mySpDis = splitterDistance;
9855             this._modifySettingLocal = true;
9856         }
9857
9858         private async Task doRepliedStatusOpen()
9859         {
9860             if (this.ExistCurrentPost && _curPost.InReplyToUser != null && _curPost.InReplyToStatusId != null)
9861             {
9862                 if (MyCommon.IsKeyDown(Keys.Shift))
9863                 {
9864                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9865                     return;
9866                 }
9867                 if (_statuses.ContainsKey(_curPost.InReplyToStatusId.Value))
9868                 {
9869                     PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9870                     MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9871                 }
9872                 else
9873                 {
9874                     foreach (TabClass tb in _statuses.GetTabsByType(MyCommon.TabUsageType.Lists | MyCommon.TabUsageType.PublicSearch))
9875                     {
9876                         if (tb == null || !tb.Contains(_curPost.InReplyToStatusId.Value)) break;
9877                         PostClass repPost = _statuses[_curPost.InReplyToStatusId.Value];
9878                         MessageBox.Show(repPost.ScreenName + " / " + repPost.Nickname + "   (" + repPost.CreatedAt.ToString() + ")" + Environment.NewLine + repPost.TextFromApi);
9879                         return;
9880                     }
9881                     await this.OpenUriInBrowserAsync(MyCommon.GetStatusUrl(_curPost.InReplyToUser, _curPost.InReplyToStatusId.Value));
9882                 }
9883             }
9884         }
9885
9886         private async void RepliedStatusOpenMenuItem_Click(object sender, EventArgs e)
9887         {
9888             await this.doRepliedStatusOpen();
9889         }
9890
9891         /// <summary>
9892         /// UserPicture.Image に設定されている画像を破棄します。
9893         /// </summary>
9894         private void ClearUserPicture()
9895         {
9896             if (this.UserPicture.Image != null)
9897             {
9898                 var oldImage = this.UserPicture.Image;
9899                 this.UserPicture.Image = null;
9900                 oldImage.Dispose();
9901             }
9902         }
9903
9904         private void ContextMenuUserPicture_Opening(object sender, CancelEventArgs e)
9905         {
9906             //発言詳細のアイコン右クリック時のメニュー制御
9907             if (_curList.SelectedIndices.Count > 0 && _curPost != null)
9908             {
9909                 string name = _curPost.ImageUrl;
9910                 if (name != null && name.Length > 0)
9911                 {
9912                     int idx = name.LastIndexOf('/');
9913                     if (idx != -1)
9914                     {
9915                         name = Path.GetFileName(name.Substring(idx));
9916                         if (name.Contains("_normal.") || name.EndsWith("_normal"))
9917                         {
9918                             name = name.Replace("_normal", "");
9919                             this.IconNameToolStripMenuItem.Text = name;
9920                             this.IconNameToolStripMenuItem.Enabled = true;
9921                         }
9922                         else
9923                         {
9924                             this.IconNameToolStripMenuItem.Enabled = false;
9925                             this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9926                         }
9927                     }
9928                     else
9929                     {
9930                         this.IconNameToolStripMenuItem.Enabled = false;
9931                         this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9932                     }
9933
9934                     this.ReloadIconToolStripMenuItem.Enabled = true;
9935
9936                     if (this.IconCache.TryGetFromCache(_curPost.ImageUrl) != null)
9937                     {
9938                         this.SaveIconPictureToolStripMenuItem.Enabled = true;
9939                     }
9940                     else
9941                     {
9942                         this.SaveIconPictureToolStripMenuItem.Enabled = false;
9943                     }
9944                 }
9945                 else
9946                 {
9947                     this.IconNameToolStripMenuItem.Enabled = false;
9948                     this.ReloadIconToolStripMenuItem.Enabled = false;
9949                     this.SaveIconPictureToolStripMenuItem.Enabled = false;
9950                     this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText1;
9951                 }
9952             }
9953             else
9954             {
9955                 this.IconNameToolStripMenuItem.Enabled = false;
9956                 this.ReloadIconToolStripMenuItem.Enabled = false;
9957                 this.SaveIconPictureToolStripMenuItem.Enabled = false;
9958                 this.IconNameToolStripMenuItem.Text = Properties.Resources.ContextMenuStrip3_OpeningText2;
9959             }
9960             if (NameLabel.Tag != null)
9961             {
9962                 string id = (string)NameLabel.Tag;
9963                 if (id == tw.Username)
9964                 {
9965                     FollowToolStripMenuItem.Enabled = false;
9966                     UnFollowToolStripMenuItem.Enabled = false;
9967                     ShowFriendShipToolStripMenuItem.Enabled = false;
9968                     ShowUserStatusToolStripMenuItem.Enabled = true;
9969                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9970                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9971                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9972                 }
9973                 else
9974                 {
9975                     FollowToolStripMenuItem.Enabled = true;
9976                     UnFollowToolStripMenuItem.Enabled = true;
9977                     ShowFriendShipToolStripMenuItem.Enabled = true;
9978                     ShowUserStatusToolStripMenuItem.Enabled = true;
9979                     SearchPostsDetailNameToolStripMenuItem.Enabled = true;
9980                     SearchAtPostsDetailNameToolStripMenuItem.Enabled = true;
9981                     ListManageUserContextToolStripMenuItem3.Enabled = true;
9982                 }
9983             }
9984             else
9985             {
9986                 FollowToolStripMenuItem.Enabled = false;
9987                 UnFollowToolStripMenuItem.Enabled = false;
9988                 ShowFriendShipToolStripMenuItem.Enabled = false;
9989                 ShowUserStatusToolStripMenuItem.Enabled = false;
9990                 SearchPostsDetailNameToolStripMenuItem.Enabled = false;
9991                 SearchAtPostsDetailNameToolStripMenuItem.Enabled = false;
9992                 ListManageUserContextToolStripMenuItem3.Enabled = false;
9993             }
9994         }
9995
9996         private async void IconNameToolStripMenuItem_Click(object sender, EventArgs e)
9997         {
9998             if (_curPost == null) return;
9999             string name = _curPost.ImageUrl;
10000             await this.OpenUriInBrowserAsync(name.Remove(name.LastIndexOf("_normal"), 7)); // "_normal".Length
10001         }
10002
10003         private async void ReloadIconToolStripMenuItem_Click(object sender, EventArgs e)
10004         {
10005             if (this._curPost == null) return;
10006
10007             await this.UserPicture.SetImageFromTask(async () =>
10008             {
10009                 var imageUrl = this._curPost.ImageUrl;
10010
10011                 var image = await this.IconCache.DownloadImageAsync(imageUrl, force: true)
10012                     .ConfigureAwait(false);
10013
10014                 return await image.CloneAsync()
10015                     .ConfigureAwait(false);
10016             });
10017         }
10018
10019         private void SaveOriginalSizeIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10020         {
10021             if (_curPost == null) return;
10022             string name = _curPost.ImageUrl;
10023             name = Path.GetFileNameWithoutExtension(name.Substring(name.LastIndexOf('/')));
10024
10025             this.SaveFileDialog1.FileName = name.Substring(0, name.Length - 8); // "_normal".Length + 1
10026
10027             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10028             {
10029                 // STUB
10030             }
10031         }
10032
10033         private void SaveIconPictureToolStripMenuItem_Click(object sender, EventArgs e)
10034         {
10035             if (_curPost == null) return;
10036             string name = _curPost.ImageUrl;
10037
10038             this.SaveFileDialog1.FileName = name.Substring(name.LastIndexOf('/') + 1);
10039
10040             if (this.SaveFileDialog1.ShowDialog() == DialogResult.OK)
10041             {
10042                 try
10043                 {
10044                     using (Image orgBmp = new Bitmap(IconCache.TryGetFromCache(name).Image))
10045                     {
10046                         using (Bitmap bmp2 = new Bitmap(orgBmp.Size.Width, orgBmp.Size.Height))
10047                         {
10048                             using (Graphics g = Graphics.FromImage(bmp2))
10049                             {
10050                                 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
10051                                 g.DrawImage(orgBmp, 0, 0, orgBmp.Size.Width, orgBmp.Size.Height);
10052                             }
10053                             bmp2.Save(this.SaveFileDialog1.FileName);
10054                         }
10055                     }
10056                 }
10057                 catch (Exception)
10058                 {
10059                     //処理中にキャッシュアウトする可能性あり
10060                 }
10061             }
10062         }
10063
10064         private void SplitContainer2_Panel2_Resize(object sender, EventArgs e)
10065         {
10066             var multiline = this.SplitContainer2.Panel2.Height > this.SplitContainer2.Panel2MinSize + 2;
10067             if (multiline != this.StatusText.Multiline)
10068             {
10069                 this.StatusText.Multiline = multiline;
10070                 MultiLineMenuItem.Checked = multiline;
10071                 _modifySettingLocal = true;
10072             }
10073         }
10074
10075         private void StatusText_MultilineChanged(object sender, EventArgs e)
10076         {
10077             if (this.StatusText.Multiline)
10078                 this.StatusText.ScrollBars = ScrollBars.Vertical;
10079             else
10080                 this.StatusText.ScrollBars = ScrollBars.None;
10081
10082             _modifySettingLocal = true;
10083         }
10084
10085         private void MultiLineMenuItem_Click(object sender, EventArgs e)
10086         {
10087             //発言欄複数行
10088             StatusText.Multiline = MultiLineMenuItem.Checked;
10089             _cfgLocal.StatusMultiline = MultiLineMenuItem.Checked;
10090             if (MultiLineMenuItem.Checked)
10091             {
10092                 if (SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth < 0)
10093                     SplitContainer2.SplitterDistance = 0;
10094                 else
10095                     SplitContainer2.SplitterDistance = SplitContainer2.Height - _mySpDis2 - SplitContainer2.SplitterWidth;
10096             }
10097             else
10098             {
10099                 SplitContainer2.SplitterDistance = SplitContainer2.Height - SplitContainer2.Panel2MinSize - SplitContainer2.SplitterWidth;
10100             }
10101             _modifySettingLocal = true;
10102         }
10103
10104         private async Task<bool> UrlConvertAsync(MyCommon.UrlConverter Converter_Type)
10105         {
10106             //t.coで投稿時自動短縮する場合は、外部サービスでの短縮禁止
10107             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco) return;
10108
10109             //Converter_Type=Nicomsの場合は、nicovideoのみ短縮する
10110             //参考資料 RFC3986 Uniform Resource Identifier (URI): Generic Syntax
10111             //Appendix A.  Collected ABNF for URI
10112             //http://www.ietf.org/rfc/rfc3986.txt
10113
10114             string result = "";
10115
10116             const string nico = @"^https?://[a-z]+\.(nicovideo|niconicommons|nicolive)\.jp/[a-z]+/[a-z0-9]+$";
10117
10118             if (StatusText.SelectionLength > 0)
10119             {
10120                 string tmp = StatusText.SelectedText;
10121                 // httpから始まらない場合、ExcludeStringで指定された文字列で始まる場合は対象としない
10122                 if (tmp.StartsWith("http"))
10123                 {
10124                     // 文字列が選択されている場合はその文字列について処理
10125
10126                     //nico.ms使用、nicovideoにマッチしたら変換
10127                     if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10128                     {
10129                         result = nicoms.Shorten(tmp);
10130                     }
10131                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10132                     {
10133                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10134                         try
10135                         {
10136                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10137                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10138                             result = resultUri.AbsoluteUri;
10139                         }
10140                         catch (WebApiException e)
10141                         {
10142                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10143                             return false;
10144                         }
10145                         catch (UriFormatException e)
10146                         {
10147                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10148                             return false;
10149                         }
10150                     }
10151                     else
10152                     {
10153                         return true;
10154                     }
10155
10156                     if (!string.IsNullOrEmpty(result))
10157                     {
10158                         urlUndo undotmp = new urlUndo();
10159
10160                         StatusText.Select(StatusText.Text.IndexOf(tmp, StringComparison.Ordinal), tmp.Length);
10161                         StatusText.SelectedText = result;
10162
10163                         //undoバッファにセット
10164                         undotmp.Before = tmp;
10165                         undotmp.After = result;
10166
10167                         if (urlUndoBuffer == null)
10168                         {
10169                             urlUndoBuffer = new List<urlUndo>();
10170                             UrlUndoToolStripMenuItem.Enabled = true;
10171                         }
10172
10173                         urlUndoBuffer.Add(undotmp);
10174                     }
10175                 }
10176             }
10177             else
10178             {
10179                 const string url = @"(?<before>(?:[^\""':!=]|^|\:))" +
10180                                    @"(?<url>(?<protocol>https?://)" +
10181                                    @"(?<domain>(?:[\.-]|[^\p{P}\s])+\.[a-z]{2,}(?::[0-9]+)?)" +
10182                                    @"(?<path>/[a-z0-9!*//();:&=+$/%#\-_.,~@]*[a-z0-9)=#/]?)?" +
10183                                    @"(?<query>\?[a-z0-9!*//();:&=+$/%#\-_.,~@?]*[a-z0-9_&=#/])?)";
10184                 // 正規表現にマッチしたURL文字列をtinyurl化
10185                 foreach (Match mt in Regex.Matches(StatusText.Text, url, RegexOptions.IgnoreCase))
10186                 {
10187                     if (StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal) == -1) continue;
10188                     string tmp = mt.Result("${url}");
10189                     if (tmp.StartsWith("w", StringComparison.OrdinalIgnoreCase)) tmp = "http://" + tmp;
10190                     urlUndo undotmp = new urlUndo();
10191
10192                     //選んだURLを選択(?)
10193                     StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10194
10195                     //nico.ms使用、nicovideoにマッチしたら変換
10196                     if (this._cfgCommon.Nicoms && Regex.IsMatch(tmp, nico))
10197                     {
10198                         result = nicoms.Shorten(tmp);
10199                     }
10200                     else if (Converter_Type != MyCommon.UrlConverter.Nicoms)
10201                     {
10202                         //短縮URL変換 日本語を含むかもしれないのでURLエンコードする
10203                         try
10204                         {
10205                             var srcUri = new Uri(MyCommon.urlEncodeMultibyteChar(tmp));
10206                             var resultUri = await ShortUrl.Instance.ShortenUrlAsync(Converter_Type, srcUri);
10207                             result = resultUri.AbsoluteUri;
10208                         }
10209                         catch (HttpRequestException e)
10210                         {
10211                             // 例外のメッセージが「Response status code does not indicate success: 500 (Internal Server Error).」
10212                             // のように長いので「:」が含まれていればそれ以降のみを抽出する
10213                             var message = e.Message.Split(new[] { ':' }, count: 2).Last();
10214
10215                             this.StatusLabel.Text = Converter_Type + ":" + message;
10216                             continue;
10217                         }
10218                         catch (WebApiException e)
10219                         {
10220                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10221                             continue;
10222                         }
10223                         catch (UriFormatException e)
10224                         {
10225                             this.StatusLabel.Text = Converter_Type + ":" + e.Message;
10226                             continue;
10227                         }
10228                     }
10229                     else
10230                     {
10231                         continue;
10232                     }
10233
10234                     if (!string.IsNullOrEmpty(result))
10235                     {
10236                         StatusText.Select(StatusText.Text.IndexOf(mt.Result("${url}"), StringComparison.Ordinal), mt.Result("${url}").Length);
10237                         StatusText.SelectedText = result;
10238                         //undoバッファにセット
10239                         undotmp.Before = mt.Result("${url}");
10240                         undotmp.After = result;
10241
10242                         if (urlUndoBuffer == null)
10243                         {
10244                             urlUndoBuffer = new List<urlUndo>();
10245                             UrlUndoToolStripMenuItem.Enabled = true;
10246                         }
10247
10248                         urlUndoBuffer.Add(undotmp);
10249                     }
10250                 }
10251             }
10252
10253             return true;
10254         }
10255
10256         private void doUrlUndo()
10257         {
10258             if (urlUndoBuffer != null)
10259             {
10260                 string tmp = StatusText.Text;
10261                 foreach (urlUndo data in urlUndoBuffer)
10262                 {
10263                     tmp = tmp.Replace(data.After, data.Before);
10264                 }
10265                 StatusText.Text = tmp;
10266                 urlUndoBuffer = null;
10267                 UrlUndoToolStripMenuItem.Enabled = false;
10268                 StatusText.SelectionStart = 0;
10269                 StatusText.SelectionLength = 0;
10270             }
10271         }
10272
10273         private async void TinyURLToolStripMenuItem_Click(object sender, EventArgs e)
10274         {
10275             await UrlConvertAsync(MyCommon.UrlConverter.TinyUrl);
10276         }
10277
10278         private async void IsgdToolStripMenuItem_Click(object sender, EventArgs e)
10279         {
10280             await UrlConvertAsync(MyCommon.UrlConverter.Isgd);
10281         }
10282
10283         private async void TwurlnlToolStripMenuItem_Click(object sender, EventArgs e)
10284         {
10285             await UrlConvertAsync(MyCommon.UrlConverter.Twurl);
10286         }
10287
10288         private async void UxnuMenuItem_Click(object sender, EventArgs e)
10289         {
10290             await UrlConvertAsync(MyCommon.UrlConverter.Uxnu);
10291         }
10292
10293         private async void UrlConvertAutoToolStripMenuItem_Click(object sender, EventArgs e)
10294         {
10295             if (!await UrlConvertAsync(this._cfgCommon.AutoShortUrlFirst))
10296             {
10297                 MyCommon.UrlConverter svc = this._cfgCommon.AutoShortUrlFirst;
10298                 Random rnd = new Random();
10299                 // 前回使用した短縮URLサービス以外を選択する
10300                 do
10301                 {
10302                     svc = (MyCommon.UrlConverter)rnd.Next(System.Enum.GetNames(typeof(MyCommon.UrlConverter)).Length);
10303                 }
10304                 while (svc == this._cfgCommon.AutoShortUrlFirst || svc == MyCommon.UrlConverter.Nicoms || svc == MyCommon.UrlConverter.Unu);
10305                 await UrlConvertAsync(svc);
10306             }
10307         }
10308
10309         private void UrlUndoToolStripMenuItem_Click(object sender, EventArgs e)
10310         {
10311             doUrlUndo();
10312         }
10313
10314         private void NewPostPopMenuItem_CheckStateChanged(object sender, EventArgs e)
10315         {
10316             this.NotifyFileMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10317             this.NewPostPopMenuItem.Checked = this.NotifyFileMenuItem.Checked;
10318             _cfgCommon.NewAllPop = NewPostPopMenuItem.Checked;
10319             _modifySettingCommon = true;
10320         }
10321
10322         private void ListLockMenuItem_CheckStateChanged(object sender, EventArgs e)
10323         {
10324             ListLockMenuItem.Checked = ((ToolStripMenuItem)sender).Checked;
10325             this.LockListFileMenuItem.Checked = ListLockMenuItem.Checked;
10326             _cfgCommon.ListLock = ListLockMenuItem.Checked;
10327             _modifySettingCommon = true;
10328         }
10329
10330         private void MenuStrip1_MenuActivate(object sender, EventArgs e)
10331         {
10332             // フォーカスがメニューに移る (MenuStrip1.Tag フラグを立てる)
10333             MenuStrip1.Tag = new Object();
10334             MenuStrip1.Select(); // StatusText がフォーカスを持っている場合 Leave が発生
10335         }
10336
10337         private void MenuStrip1_MenuDeactivate(object sender, EventArgs e)
10338         {
10339             if (this.Tag != null) // 設定された戻り先へ遷移
10340             {
10341                 if (this.Tag == this.ListTab.SelectedTab)
10342                     ((Control)this.ListTab.SelectedTab.Tag).Select();
10343                 else
10344                     ((Control)this.Tag).Select();
10345             }
10346             else // 戻り先が指定されていない (初期状態) 場合はタブに遷移
10347             {
10348                 if (ListTab.SelectedIndex > -1 && ListTab.SelectedTab.HasChildren)
10349                 {
10350                     this.Tag = ListTab.SelectedTab.Tag;
10351                     ((Control)this.Tag).Select();
10352                 }
10353             }
10354             // フォーカスがメニューに遷移したかどうかを表すフラグを降ろす
10355             MenuStrip1.Tag = null;
10356         }
10357
10358         private void MyList_ColumnReordered(object sender, ColumnReorderedEventArgs e)
10359         {
10360             DetailsListView lst = (DetailsListView)sender;
10361             if (_cfgLocal == null) return;
10362
10363             if (_iconCol)
10364             {
10365                 _cfgLocal.Width1 = lst.Columns[0].Width;
10366                 _cfgLocal.Width3 = lst.Columns[1].Width;
10367             }
10368             else
10369             {
10370                 int[] darr = new int[lst.Columns.Count];
10371                 for (int i = 0; i < lst.Columns.Count; i++)
10372                 {
10373                     darr[lst.Columns[i].DisplayIndex] = i;
10374                 }
10375                 MyCommon.MoveArrayItem(darr, e.OldDisplayIndex, e.NewDisplayIndex);
10376
10377                 for (int i = 0; i < lst.Columns.Count; i++)
10378                 {
10379                     switch (darr[i])
10380                     {
10381                         case 0:
10382                             _cfgLocal.DisplayIndex1 = i;
10383                             break;
10384                         case 1:
10385                             _cfgLocal.DisplayIndex2 = i;
10386                             break;
10387                         case 2:
10388                             _cfgLocal.DisplayIndex3 = i;
10389                             break;
10390                         case 3:
10391                             _cfgLocal.DisplayIndex4 = i;
10392                             break;
10393                         case 4:
10394                             _cfgLocal.DisplayIndex5 = i;
10395                             break;
10396                         case 5:
10397                             _cfgLocal.DisplayIndex6 = i;
10398                             break;
10399                         case 6:
10400                             _cfgLocal.DisplayIndex7 = i;
10401                             break;
10402                         case 7:
10403                             _cfgLocal.DisplayIndex8 = i;
10404                             break;
10405                     }
10406                 }
10407                 _cfgLocal.Width1 = lst.Columns[0].Width;
10408                 _cfgLocal.Width2 = lst.Columns[1].Width;
10409                 _cfgLocal.Width3 = lst.Columns[2].Width;
10410                 _cfgLocal.Width4 = lst.Columns[3].Width;
10411                 _cfgLocal.Width5 = lst.Columns[4].Width;
10412                 _cfgLocal.Width6 = lst.Columns[5].Width;
10413                 _cfgLocal.Width7 = lst.Columns[6].Width;
10414                 _cfgLocal.Width8 = lst.Columns[7].Width;
10415             }
10416             _modifySettingLocal = true;
10417             _isColumnChanged = true;
10418         }
10419
10420         private void MyList_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
10421         {
10422             DetailsListView lst = (DetailsListView)sender;
10423             if (_cfgLocal == null) return;
10424             if (_iconCol)
10425             {
10426                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10427                 {
10428                     _cfgLocal.Width1 = lst.Columns[0].Width;
10429                     _modifySettingLocal = true;
10430                     _isColumnChanged = true;
10431                 }
10432                 if (_cfgLocal.Width3 != lst.Columns[1].Width)
10433                 {
10434                     _cfgLocal.Width3 = lst.Columns[1].Width;
10435                     _modifySettingLocal = true;
10436                     _isColumnChanged = true;
10437                 }
10438             }
10439             else
10440             {
10441                 if (_cfgLocal.Width1 != lst.Columns[0].Width)
10442                 {
10443                     _cfgLocal.Width1 = lst.Columns[0].Width;
10444                     _modifySettingLocal = true;
10445                     _isColumnChanged = true;
10446                 }
10447                 if (_cfgLocal.Width2 != lst.Columns[1].Width)
10448                 {
10449                     _cfgLocal.Width2 = lst.Columns[1].Width;
10450                     _modifySettingLocal = true;
10451                     _isColumnChanged = true;
10452                 }
10453                 if (_cfgLocal.Width3 != lst.Columns[2].Width)
10454                 {
10455                     _cfgLocal.Width3 = lst.Columns[2].Width;
10456                     _modifySettingLocal = true;
10457                     _isColumnChanged = true;
10458                 }
10459                 if (_cfgLocal.Width4 != lst.Columns[3].Width)
10460                 {
10461                     _cfgLocal.Width4 = lst.Columns[3].Width;
10462                     _modifySettingLocal = true;
10463                     _isColumnChanged = true;
10464                 }
10465                 if (_cfgLocal.Width5 != lst.Columns[4].Width)
10466                 {
10467                     _cfgLocal.Width5 = lst.Columns[4].Width;
10468                     _modifySettingLocal = true;
10469                     _isColumnChanged = true;
10470                 }
10471                 if (_cfgLocal.Width6 != lst.Columns[5].Width)
10472                 {
10473                     _cfgLocal.Width6 = lst.Columns[5].Width;
10474                     _modifySettingLocal = true;
10475                     _isColumnChanged = true;
10476                 }
10477                 if (_cfgLocal.Width7 != lst.Columns[6].Width)
10478                 {
10479                     _cfgLocal.Width7 = lst.Columns[6].Width;
10480                     _modifySettingLocal = true;
10481                     _isColumnChanged = true;
10482                 }
10483                 if (_cfgLocal.Width8 != lst.Columns[7].Width)
10484                 {
10485                     _cfgLocal.Width8 = lst.Columns[7].Width;
10486                     _modifySettingLocal = true;
10487                     _isColumnChanged = true;
10488                 }
10489             }
10490             // 非表示の時にColumnChangedが呼ばれた場合はForm初期化処理中なので保存しない
10491             //if (changed)
10492             //{
10493             //    SaveConfigsLocal();
10494             //}
10495         }
10496
10497         private void SelectionCopyContextMenuItem_Click(object sender, EventArgs e)
10498         {
10499             //発言詳細で「選択文字列をコピー」
10500             string _selText = this.PostBrowser.GetSelectedText();
10501             try
10502             {
10503                 Clipboard.SetDataObject(_selText, false, 5, 100);
10504             }
10505             catch (Exception ex)
10506             {
10507                 MessageBox.Show(ex.Message);
10508             }
10509         }
10510
10511         private async Task doSearchToolStrip(string url)
10512         {
10513             //発言詳細で「選択文字列で検索」(選択文字列取得)
10514             string _selText = this.PostBrowser.GetSelectedText();
10515
10516             if (_selText != null)
10517             {
10518                 if (url == Properties.Resources.SearchItem4Url)
10519                 {
10520                     //公式検索
10521                     AddNewTabForSearch(_selText);
10522                     return;
10523                 }
10524
10525                 string tmp = string.Format(url, Uri.EscapeDataString(_selText));
10526                 await this.OpenUriInBrowserAsync(tmp);
10527             }
10528         }
10529
10530         private void SelectionAllContextMenuItem_Click(object sender, EventArgs e)
10531         {
10532             //発言詳細ですべて選択
10533             PostBrowser.Document.ExecCommand("SelectAll", false, null);
10534         }
10535
10536         private async void SearchWikipediaContextMenuItem_Click(object sender, EventArgs e)
10537         {
10538             await this.doSearchToolStrip(Properties.Resources.SearchItem1Url);
10539         }
10540
10541         private async void SearchGoogleContextMenuItem_Click(object sender, EventArgs e)
10542         {
10543             await this.doSearchToolStrip(Properties.Resources.SearchItem2Url);
10544         }
10545
10546         private async void SearchPublicSearchContextMenuItem_Click(object sender, EventArgs e)
10547         {
10548             await this.doSearchToolStrip(Properties.Resources.SearchItem4Url);
10549         }
10550
10551         private void UrlCopyContextMenuItem_Click(object sender, EventArgs e)
10552         {
10553             try
10554             {
10555                 foreach (var link in this.PostBrowser.Document.Links.Cast<HtmlElement>())
10556                 {
10557                     if (link.GetAttribute("href") == this._postBrowserStatusText)
10558                     {
10559                         Clipboard.SetDataObject(link.GetAttribute("title"), false, 5, 100);
10560                         return;
10561                     }
10562                 }
10563
10564                 Clipboard.SetDataObject(this._postBrowserStatusText, false, 5, 100);
10565             }
10566             catch (Exception ex)
10567             {
10568                 MessageBox.Show(ex.Message);
10569             }
10570         }
10571
10572         private void ContextMenuPostBrowser_Opening(object ender, CancelEventArgs e)
10573         {
10574             // URLコピーの項目の表示/非表示
10575             if (PostBrowser.StatusText.StartsWith("http"))
10576             {
10577                 this._postBrowserStatusText = PostBrowser.StatusText;
10578                 string name = GetUserId();
10579                 UrlCopyContextMenuItem.Enabled = true;
10580                 if (name != null)
10581                 {
10582                     FollowContextMenuItem.Enabled = true;
10583                     RemoveContextMenuItem.Enabled = true;
10584                     FriendshipContextMenuItem.Enabled = true;
10585                     ShowUserStatusContextMenuItem.Enabled = true;
10586                     SearchPostsDetailToolStripMenuItem.Enabled = true;
10587                     IdFilterAddMenuItem.Enabled = true;
10588                     ListManageUserContextToolStripMenuItem.Enabled = true;
10589                     SearchAtPostsDetailToolStripMenuItem.Enabled = true;
10590                 }
10591                 else
10592                 {
10593                     FollowContextMenuItem.Enabled = false;
10594                     RemoveContextMenuItem.Enabled = false;
10595                     FriendshipContextMenuItem.Enabled = false;
10596                     ShowUserStatusContextMenuItem.Enabled = false;
10597                     SearchPostsDetailToolStripMenuItem.Enabled = false;
10598                     IdFilterAddMenuItem.Enabled = false;
10599                     ListManageUserContextToolStripMenuItem.Enabled = false;
10600                     SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10601                 }
10602
10603                 if (Regex.IsMatch(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23"))
10604                     UseHashtagMenuItem.Enabled = true;
10605                 else
10606                     UseHashtagMenuItem.Enabled = false;
10607             }
10608             else
10609             {
10610                 this._postBrowserStatusText = "";
10611                 UrlCopyContextMenuItem.Enabled = false;
10612                 FollowContextMenuItem.Enabled = false;
10613                 RemoveContextMenuItem.Enabled = false;
10614                 FriendshipContextMenuItem.Enabled = false;
10615                 ShowUserStatusContextMenuItem.Enabled = false;
10616                 SearchPostsDetailToolStripMenuItem.Enabled = false;
10617                 SearchAtPostsDetailToolStripMenuItem.Enabled = false;
10618                 UseHashtagMenuItem.Enabled = false;
10619                 IdFilterAddMenuItem.Enabled = false;
10620                 ListManageUserContextToolStripMenuItem.Enabled = false;
10621             }
10622             // 文字列選択されていないときは選択文字列関係の項目を非表示に
10623             string _selText = this.PostBrowser.GetSelectedText();
10624             if (_selText == null)
10625             {
10626                 SelectionSearchContextMenuItem.Enabled = false;
10627                 SelectionCopyContextMenuItem.Enabled = false;
10628                 SelectionTranslationToolStripMenuItem.Enabled = false;
10629             }
10630             else
10631             {
10632                 SelectionSearchContextMenuItem.Enabled = true;
10633                 SelectionCopyContextMenuItem.Enabled = true;
10634                 SelectionTranslationToolStripMenuItem.Enabled = true;
10635             }
10636             //発言内に自分以外のユーザーが含まれてればフォロー状態全表示を有効に
10637             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
10638             bool fAllFlag = false;
10639             foreach (Match mu in ma)
10640             {
10641                 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
10642                 {
10643                     fAllFlag = true;
10644                     break;
10645                 }
10646             }
10647             this.FriendshipAllMenuItem.Enabled = fAllFlag;
10648
10649             if (_curPost == null)
10650                 TranslationToolStripMenuItem.Enabled = false;
10651             else
10652                 TranslationToolStripMenuItem.Enabled = true;
10653
10654             e.Cancel = false;
10655         }
10656
10657         private void CurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
10658         {
10659             //発言詳細の選択文字列で現在のタブを検索
10660             string _selText = this.PostBrowser.GetSelectedText();
10661
10662             if (_selText != null)
10663             {
10664                 var searchOptions = new SearchWordDialog.SearchOptions(
10665                     SearchWordDialog.SearchType.Timeline,
10666                     _selText,
10667                     newTab: false,
10668                     caseSensitive: false,
10669                     useRegex: false);
10670
10671                 this.SearchDialog.ResultOptions = searchOptions;
10672
10673                 this.DoTabSearch(
10674                     searchOptions.Query,
10675                     searchOptions.CaseSensitive,
10676                     searchOptions.UseRegex,
10677                     SEARCHTYPE.NextSearch);
10678             }
10679         }
10680
10681         private void SplitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
10682         {
10683             if (StatusText.Multiline) _mySpDis2 = StatusText.Height;
10684             _modifySettingLocal = true;
10685         }
10686
10687         private void TweenMain_DragDrop(object sender, DragEventArgs e)
10688         {
10689             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10690             {
10691                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10692                 {
10693                     SelectMedia_DragDrop(e);
10694                 }
10695             }
10696             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10697             {
10698                 var url = GetUrlFromDataObject(e.Data);
10699
10700                 string appendText;
10701                 if (url.Item2 == null)
10702                     appendText = url.Item1;
10703                 else
10704                     appendText = url.Item2 + " " + url.Item1;
10705
10706                 if (this.StatusText.TextLength == 0)
10707                     this.StatusText.Text = appendText;
10708                 else
10709                     this.StatusText.Text += " " + appendText;
10710             }
10711             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10712             {
10713                 var text = (string)e.Data.GetData(DataFormats.UnicodeText);
10714                 if (text != null)
10715                     this.StatusText.Text += text;
10716             }
10717             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10718             {
10719                 string data = (string)e.Data.GetData(DataFormats.StringFormat, true);
10720                 if (data != null) StatusText.Text += data;
10721             }
10722         }
10723
10724         /// <summary>
10725         /// IDataObject から URL とタイトルの対を取得します
10726         /// </summary>
10727         /// <remarks>
10728         /// タイトルのみ取得できなかった場合は Value2 が null のタプルを返すことがあります。
10729         /// </remarks>
10730         /// <exception cref="ArgumentException">不正なフォーマットが入力された場合</exception>
10731         /// <exception cref="NotSupportedException">サポートされていないデータが入力された場合</exception>
10732         internal static Tuple<string, string> GetUrlFromDataObject(IDataObject data)
10733         {
10734             if (data.GetDataPresent("text/x-moz-url"))
10735             {
10736                 // Firefox, Google Chrome で利用可能
10737                 // 参照: https://developer.mozilla.org/ja/docs/DragDrop/Recommended_Drag_Types
10738
10739                 using (var stream = (MemoryStream)data.GetData("text/x-moz-url"))
10740                 {
10741                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\n');
10742                     if (lines.Length < 2)
10743                         throw new ArgumentException("不正な text/x-moz-url フォーマットです", nameof(data));
10744
10745                     return new Tuple<string, string>(lines[0], lines[1]);
10746                 }
10747             }
10748             else if (data.GetDataPresent("IESiteModeToUrl"))
10749             {
10750                 // Internet Exproler 用
10751                 // 保護モードが有効なデフォルトの IE では DragDrop イベントが発火しないため使えない
10752
10753                 using (var stream = (MemoryStream)data.GetData("IESiteModeToUrl"))
10754                 {
10755                     var lines = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0').Split('\0');
10756                     if (lines.Length < 2)
10757                         throw new ArgumentException("不正な IESiteModeToUrl フォーマットです", nameof(data));
10758
10759                     return new Tuple<string, string>(lines[0], lines[1]);
10760                 }
10761             }
10762             else if (data.GetDataPresent("UniformResourceLocatorW"))
10763             {
10764                 // それ以外のブラウザ向け
10765
10766                 using (var stream = (MemoryStream)data.GetData("UniformResourceLocatorW"))
10767                 {
10768                     var url = Encoding.Unicode.GetString(stream.ToArray()).TrimEnd('\0');
10769                     return new Tuple<string, string>(url, null);
10770                 }
10771             }
10772
10773             throw new NotSupportedException("サポートされていないデータ形式です: " + data.GetFormats()[0]);
10774         }
10775
10776         private void TweenMain_DragEnter(object sender, DragEventArgs e)
10777         {
10778             if (e.Data.GetDataPresent(DataFormats.FileDrop))
10779             {
10780                 if (!e.Data.GetDataPresent(DataFormats.Html, false))  // WebBrowserコントロールからの絵文字画像Drag&Dropは弾く
10781                 {
10782                     SelectMedia_DragEnter(e);
10783                     return;
10784                 }
10785             }
10786             else if (e.Data.GetDataPresent("UniformResourceLocatorW"))
10787             {
10788                 e.Effect = DragDropEffects.Copy;
10789                 return;
10790             }
10791             else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
10792             {
10793                 e.Effect = DragDropEffects.Copy;
10794                 return;
10795             }
10796             else if (e.Data.GetDataPresent(DataFormats.StringFormat))
10797             {
10798                 e.Effect = DragDropEffects.Copy;
10799                 return;
10800             }
10801
10802             e.Effect = DragDropEffects.None;
10803         }
10804
10805         private void TweenMain_DragOver(object sender, DragEventArgs e)
10806         {
10807         }
10808
10809         public bool IsNetworkAvailable()
10810         {
10811             bool nw = true;
10812             nw = MyCommon.IsNetworkAvailable();
10813             _myStatusOnline = nw;
10814             return nw;
10815         }
10816
10817         public async Task OpenUriAsync(Uri uri, bool isReverseSettings = false)
10818         {
10819             var uriStr = uri.AbsoluteUri;
10820
10821             // OpenTween 内部で使用する URL
10822             if (uri.Authority == "opentween")
10823             {
10824                 await this.OpenInternalUriAsync(uri);
10825                 return;
10826             }
10827
10828             // ハッシュタグを含む Twitter 検索
10829             if (uri.Host == "twitter.com" && uri.AbsolutePath == "/search" && uri.Query.Contains("q=%23"))
10830             {
10831                 // ハッシュタグの場合は、タブで開く
10832                 var unescapedQuery = Uri.UnescapeDataString(uri.Query);
10833                 var pos = unescapedQuery.IndexOf('#');
10834                 if (pos == -1) return;
10835
10836                 var hash = unescapedQuery.Substring(pos);
10837                 this.HashSupl.AddItem(hash);
10838                 this.HashMgr.AddHashToHistory(hash.Trim(), false);
10839                 this.AddNewTabForSearch(hash);
10840                 return;
10841             }
10842
10843             // ユーザープロフィールURL
10844             // フラグが立っている場合は設定と逆の動作をする
10845             if( this._cfgCommon.OpenUserTimeline && !isReverseSettings ||
10846                 !this._cfgCommon.OpenUserTimeline && isReverseSettings )
10847             {
10848                 var userUriMatch = Regex.Match(uriStr, "^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)$");
10849                 if (userUriMatch.Success)
10850                 {
10851                     var screenName = userUriMatch.Groups["ScreenName"].Value;
10852                     if (this.IsTwitterId(screenName))
10853                     {
10854                         this.AddNewTabForUserTimeline(screenName);
10855                         return;
10856                     }
10857                 }
10858             }
10859
10860             // どのパターンにも該当しないURL
10861             await this.OpenUriInBrowserAsync(uriStr);
10862         }
10863
10864         /// <summary>
10865         /// OpenTween 内部の機能を呼び出すための URL を開きます
10866         /// </summary>
10867         private async Task OpenInternalUriAsync(Uri uri)
10868         {
10869             // ツイートを開く (//opentween/status/:status_id)
10870             var match = Regex.Match(uri.AbsolutePath, @"^/status/(\d+)$");
10871             if (match.Success)
10872             {
10873                 var statusId = long.Parse(match.Groups[1].Value);
10874                 await this.OpenRelatedTab(statusId);
10875                 return;
10876             }
10877         }
10878
10879         public Task OpenUriInBrowserAsync(string UriString)
10880         {
10881             return Task.Run(() =>
10882             {
10883                 string myPath = UriString;
10884
10885                 try
10886                 {
10887                     var configBrowserPath = this._cfgLocal.BrowserPath;
10888                     if (!string.IsNullOrEmpty(configBrowserPath))
10889                     {
10890                         if (configBrowserPath.StartsWith("\"") && configBrowserPath.Length > 2 && configBrowserPath.IndexOf("\"", 2) > -1)
10891                         {
10892                             int sep = configBrowserPath.IndexOf("\"", 2);
10893                             string browserPath = configBrowserPath.Substring(1, sep - 1);
10894                             string arg = "";
10895                             if (sep < configBrowserPath.Length - 1)
10896                             {
10897                                 arg = configBrowserPath.Substring(sep + 1);
10898                             }
10899                             myPath = arg + " " + myPath;
10900                             System.Diagnostics.Process.Start(browserPath, myPath);
10901                         }
10902                         else
10903                         {
10904                             System.Diagnostics.Process.Start(configBrowserPath, myPath);
10905                         }
10906                     }
10907                     else
10908                     {
10909                         System.Diagnostics.Process.Start(myPath);
10910                     }
10911                 }
10912                 catch (Exception)
10913                 {
10914                     //MessageBox.Show("ブラウザの起動に失敗、またはタイムアウトしました。" + ex.ToString());
10915                 }
10916             });
10917         }
10918
10919         private void ListTabSelect(TabPage _tab)
10920         {
10921             SetListProperty();
10922
10923             this.PurgeListViewItemCache();
10924
10925             _curTab = _tab;
10926             _curList = (DetailsListView)_tab.Tag;
10927             if (_curList.SelectedIndices.Count > 0)
10928             {
10929                 _curItemIndex = _curList.SelectedIndices[0];
10930                 _curPost = GetCurTabPost(_curItemIndex);
10931             }
10932             else
10933             {
10934                 _curItemIndex = -1;
10935                 _curPost = null;
10936             }
10937
10938             _anchorPost = null;
10939             _anchorFlag = false;
10940
10941             if (_iconCol)
10942             {
10943                 ((DetailsListView)_tab.Tag).Columns[1].Text = ColumnText[2];
10944             }
10945             else
10946             {
10947                 for (int i = 0; i < _curList.Columns.Count; i++)
10948                 {
10949                     ((DetailsListView)_tab.Tag).Columns[i].Text = ColumnText[i];
10950                 }
10951             }
10952         }
10953
10954         private void ListTab_Selecting(object sender, TabControlCancelEventArgs e)
10955         {
10956             ListTabSelect(e.TabPage);
10957         }
10958
10959         private void SelectListItem(DetailsListView LView, int Index)
10960         {
10961             //単一
10962             Rectangle bnd = new Rectangle();
10963             bool flg = false;
10964             var item = LView.FocusedItem;
10965             if (item != null)
10966             {
10967                 bnd = item.Bounds;
10968                 flg = true;
10969             }
10970
10971             do
10972             {
10973                 LView.SelectedIndices.Clear();
10974             }
10975             while (LView.SelectedIndices.Count > 0);
10976             item = LView.Items[Index];
10977             item.Selected = true;
10978             item.Focused = true;
10979
10980             if (flg) LView.Invalidate(bnd);
10981         }
10982
10983         private void SelectListItem(DetailsListView LView , int[] Index, int focusedIndex, int selectionMarkIndex)
10984         {
10985             //複数
10986             Rectangle bnd = new Rectangle();
10987             bool flg = false;
10988             var item = LView.FocusedItem;
10989             if (item != null)
10990             {
10991                 bnd = item.Bounds;
10992                 flg = true;
10993             }
10994
10995             if (Index != null)
10996             {
10997                 do
10998                 {
10999                     LView.SelectedIndices.Clear();
11000                 }
11001                 while (LView.SelectedIndices.Count > 0);
11002                 LView.SelectItems(Index);
11003             }
11004             if (selectionMarkIndex > -1 && LView.VirtualListSize > selectionMarkIndex)
11005             {
11006                 LView.SelectionMark = selectionMarkIndex;
11007             }
11008             if (focusedIndex > -1 && LView.VirtualListSize > focusedIndex)
11009             {
11010                 LView.Items[focusedIndex].Focused = true;
11011             }
11012             else if (Index != null && Index.Length != 0)
11013             {
11014                 LView.Items[Index.Last()].Focused = true;
11015             }
11016
11017             if (flg) LView.Invalidate(bnd);
11018         }
11019
11020         private void StartUserStream()
11021         {
11022             tw.NewPostFromStream += tw_NewPostFromStream;
11023             tw.UserStreamStarted += tw_UserStreamStarted;
11024             tw.UserStreamStopped += tw_UserStreamStopped;
11025             tw.PostDeleted += tw_PostDeleted;
11026             tw.UserStreamEventReceived += tw_UserStreamEventArrived;
11027
11028             MenuItemUserStream.Text = "&UserStream ■";
11029             MenuItemUserStream.Enabled = true;
11030             StopToolStripMenuItem.Text = "&Start";
11031             StopToolStripMenuItem.Enabled = true;
11032             if (this._cfgCommon.UserstreamStartup) tw.StartUserStream();
11033         }
11034
11035         private async void TweenMain_Shown(object sender, EventArgs e)
11036         {
11037             try
11038             {
11039                 using (ControlTransaction.Update(this.PostBrowser))
11040                 {
11041                     PostBrowser.Url = new Uri("about:blank");
11042                     PostBrowser.DocumentText = "";       //発言詳細部初期化
11043                 }
11044             }
11045             catch (Exception)
11046             {
11047             }
11048
11049             NotifyIcon1.Visible = true;
11050
11051             if (this.IsNetworkAvailable())
11052             {
11053                 StartUserStream();
11054
11055                 var loadTasks = new List<Task>
11056                 {
11057                     this.RefreshMuteUserIdsAsync(),
11058                     this.RefreshBlockIdsAsync(),
11059                     this.RefreshNoRetweetIdsAsync(),
11060                     this.RefreshTwitterConfigurationAsync(),
11061                     this.GetHomeTimelineAsync(),
11062                     this.GetReplyAsync(),
11063                     this.GetDirectMessagesAsync(),
11064                     this.GetPublicSearchAllAsync(),
11065                     this.GetUserTimelineAllAsync(),
11066                     this.GetListTimelineAllAsync(),
11067                 };
11068
11069                 if (this._cfgCommon.StartupFollowers)
11070                     loadTasks.Add(this.RefreshFollowerIdsAsync());
11071
11072                 if (this._cfgCommon.GetFav)
11073                     loadTasks.Add(this.GetFavoritesAsync());
11074
11075                 var allTasks = Task.WhenAll(loadTasks);
11076
11077                 var i = 0;
11078                 while (true)
11079                 {
11080                     var timeout = Task.Delay(5000);
11081                     if (await Task.WhenAny(allTasks, timeout) != timeout)
11082                         break;
11083
11084                     i += 1;
11085                     if (i > 24) break; // 120秒間初期処理が終了しなかったら強制的に打ち切る
11086
11087                     if (MyCommon._endingFlag)
11088                         return;
11089                 }
11090
11091                 if (MyCommon._endingFlag) return;
11092
11093                 if (ApplicationSettings.VersionInfoUrl != null)
11094                 {
11095                     //バージョンチェック(引数:起動時チェックの場合はtrue・・・チェック結果のメッセージを表示しない)
11096                     if (this._cfgCommon.StartupVersion)
11097                         await this.CheckNewVersion(true);
11098                 }
11099                 else
11100                 {
11101                     // ApplicationSetting.cs の設定により更新チェックが無効化されている場合
11102                     this.VerUpMenuItem.Enabled = false;
11103                     this.VerUpMenuItem.Available = false;
11104                     this.ToolStripSeparator16.Available = false; // VerUpMenuItem の一つ上にあるセパレータ
11105                 }
11106
11107                 // 権限チェック read/write権限(xAuthで取得したトークン)の場合は再認証を促す
11108                 if (MyCommon.TwitterApiInfo.AccessLevel == TwitterApiAccessLevel.ReadWrite)
11109                 {
11110                     MessageBox.Show(Properties.Resources.ReAuthorizeText);
11111                     SettingStripMenuItem_Click(null, null);
11112                 }
11113
11114                 // 取得失敗の場合は再試行する
11115                 var reloadTasks = new List<Task>();
11116
11117                 if (!tw.GetFollowersSuccess && this._cfgCommon.StartupFollowers)
11118                     reloadTasks.Add(this.RefreshFollowerIdsAsync());
11119
11120                 if (!tw.GetNoRetweetSuccess)
11121                     reloadTasks.Add(this.RefreshNoRetweetIdsAsync());
11122
11123                 if (this.tw.Configuration.PhotoSizeLimit == 0)
11124                     reloadTasks.Add(this.RefreshTwitterConfigurationAsync());
11125
11126                 await Task.WhenAll(reloadTasks);
11127             }
11128
11129             _initial = false;
11130
11131             TimerTimeline.Enabled = true;
11132         }
11133
11134         private async Task doGetFollowersMenu()
11135         {
11136             await this.RefreshFollowerIdsAsync();
11137             await this.DispSelectedPost(true);
11138         }
11139
11140         private async void GetFollowersAllToolStripMenuItem_Click(object sender, EventArgs e)
11141         {
11142             await this.doGetFollowersMenu();
11143         }
11144
11145         private void ReTweetUnofficialStripMenuItem_Click(object sender, EventArgs e)
11146         {
11147             doReTweetUnofficial();
11148         }
11149
11150         private async Task doReTweetOfficial(bool isConfirm)
11151         {
11152             //公式RT
11153             if (this.ExistCurrentPost)
11154             {
11155                 if (_curPost.IsProtect)
11156                 {
11157                     MessageBox.Show("Protected.");
11158                     _DoFavRetweetFlags = false;
11159                     return;
11160                 }
11161                 if (_curList.SelectedIndices.Count > 15)
11162                 {
11163                     MessageBox.Show(Properties.Resources.RetweetLimitText);
11164                     _DoFavRetweetFlags = false;
11165                     return;
11166                 }
11167                 else if (_curList.SelectedIndices.Count > 1)
11168                 {
11169                     string QuestionText = Properties.Resources.RetweetQuestion2;
11170                     if (_DoFavRetweetFlags) QuestionText = Properties.Resources.FavoriteRetweetQuestionText1;
11171                     switch (MessageBox.Show(QuestionText, "Retweet", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
11172                     {
11173                         case DialogResult.Cancel:
11174                         case DialogResult.No:
11175                             _DoFavRetweetFlags = false;
11176                             return;
11177                     }
11178                 }
11179                 else
11180                 {
11181                     if (_curPost.IsDm || _curPost.IsMe)
11182                     {
11183                         _DoFavRetweetFlags = false;
11184                         return;
11185                     }
11186                     if (!this._cfgCommon.RetweetNoConfirm)
11187                     {
11188                         string Questiontext = Properties.Resources.RetweetQuestion1;
11189                         if (_DoFavRetweetFlags) Questiontext = Properties.Resources.FavoritesRetweetQuestionText2;
11190                         if (isConfirm && MessageBox.Show(Questiontext, "Retweet", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
11191                         {
11192                             _DoFavRetweetFlags = false;
11193                             return;
11194                         }
11195                     }
11196                 }
11197
11198                 var statusIds = new List<long>();
11199                 foreach (int idx in _curList.SelectedIndices)
11200                 {
11201                     PostClass post = GetCurTabPost(idx);
11202                     if (!post.IsMe && !post.IsProtect && !post.IsDm)
11203                         statusIds.Add(post.StatusId);
11204                 }
11205
11206                 await this.RetweetAsync(statusIds);
11207             }
11208         }
11209
11210         private async void ReTweetStripMenuItem_Click(object sender, EventArgs e)
11211         {
11212             await this.doReTweetOfficial(true);
11213         }
11214
11215         private async Task FavoritesRetweetOfficial()
11216         {
11217             if (!this.ExistCurrentPost) return;
11218             _DoFavRetweetFlags = true;
11219             var retweetTask = this.doReTweetOfficial(true);
11220             if (_DoFavRetweetFlags)
11221             {
11222                 _DoFavRetweetFlags = false;
11223                 var favoriteTask = this.FavoriteChange(true, false);
11224
11225                 await Task.WhenAll(retweetTask, favoriteTask);
11226             }
11227             else
11228             {
11229                 await retweetTask;
11230             }
11231         }
11232
11233         private async Task FavoritesRetweetUnofficial()
11234         {
11235             if (this.ExistCurrentPost && !_curPost.IsDm)
11236             {
11237                 _DoFavRetweetFlags = true;
11238                 var favoriteTask = this.FavoriteChange(true);
11239                 if (!_curPost.IsProtect && _DoFavRetweetFlags)
11240                 {
11241                     _DoFavRetweetFlags = false;
11242                     doReTweetUnofficial();
11243                 }
11244
11245                 await favoriteTask;
11246             }
11247         }
11248
11249         /// <summary>
11250         /// TweetFormatterクラスによって整形された状態のHTMLを、非公式RT用に元のツイートに復元します
11251         /// </summary>
11252         /// <param name="statusHtml">TweetFormatterによって整形された状態のHTML</param>
11253         /// <param name="multiline">trueであればBRタグを改行に、falseであればスペースに変換します</param>
11254         /// <returns>復元されたツイート本文</returns>
11255         internal static string CreateRetweetUnofficial(string statusHtml, bool multiline)
11256         {
11257             // TweetFormatterクラスによって整形された状態のHTMLを元のツイートに復元します
11258
11259             // 通常の URL
11260             statusHtml = Regex.Replace(statusHtml, "<a href=\"(?<href>.+?)\" title=\"(?<title>.+?)\">(?<text>.+?)</a>", "${title}");
11261             // メンション
11262             statusHtml = Regex.Replace(statusHtml, "<a class=\"mention\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11263             // ハッシュタグ
11264             statusHtml = Regex.Replace(statusHtml, "<a class=\"hashtag\" href=\"(?<href>.+?)\">(?<text>.+?)</a>", "${text}");
11265
11266             // <br> 除去
11267             if (multiline)
11268                 statusHtml = statusHtml.Replace("<br>", Environment.NewLine);
11269             else
11270                 statusHtml = statusHtml.Replace("<br>", " ");
11271
11272             // &nbsp; は本来であれば U+00A0 (NON-BREAK SPACE) に置換すべきですが、
11273             // 現状では半角スペースの代用として &nbsp; を使用しているため U+0020 に置換します
11274             statusHtml = statusHtml.Replace("&nbsp;", " ");
11275
11276             return WebUtility.HtmlDecode(statusHtml);
11277         }
11278
11279         private async void DumpPostClassToolStripMenuItem_Click(object sender, EventArgs e)
11280         {
11281             if (_curPost != null)
11282                 await this.DispSelectedPost(true);
11283         }
11284
11285         private void MenuItemHelp_DropDownOpening(object sender, EventArgs e)
11286         {
11287             if (MyCommon.DebugBuild || MyCommon.IsKeyDown(Keys.CapsLock, Keys.Control, Keys.Shift))
11288                 DebugModeToolStripMenuItem.Visible = true;
11289             else
11290                 DebugModeToolStripMenuItem.Visible = false;
11291         }
11292
11293         private void ToolStripMenuItemUrlAutoShorten_CheckedChanged(object sender, EventArgs e)
11294         {
11295             this._cfgCommon.UrlConvertAuto = ToolStripMenuItemUrlAutoShorten.Checked;
11296         }
11297
11298         private void ContextMenuPostMode_Opening(object sender, CancelEventArgs e)
11299         {
11300             ToolStripMenuItemUrlAutoShorten.Checked = this._cfgCommon.UrlConvertAuto;
11301         }
11302
11303         private void TraceOutToolStripMenuItem_Click(object sender, EventArgs e)
11304         {
11305             if (TraceOutToolStripMenuItem.Checked)
11306                 MyCommon.TraceFlag = true;
11307             else
11308                 MyCommon.TraceFlag = false;
11309         }
11310
11311         private void TweenMain_Deactivate(object sender, EventArgs e)
11312         {
11313             //画面が非アクティブになったら、発言欄の背景色をデフォルトへ
11314             this.StatusText_Leave(StatusText, System.EventArgs.Empty);
11315         }
11316
11317         private void TabRenameMenuItem_Click(object sender, EventArgs e)
11318         {
11319             if (string.IsNullOrEmpty(_rclickTabName)) return;
11320             TabRename(ref _rclickTabName);
11321         }
11322
11323         private async void BitlyToolStripMenuItem_Click(object sender, EventArgs e)
11324         {
11325             await UrlConvertAsync(MyCommon.UrlConverter.Bitly);
11326         }
11327
11328         private async void JmpToolStripMenuItem_Click(object sender, EventArgs e)
11329         {
11330             await UrlConvertAsync(MyCommon.UrlConverter.Jmp);
11331         }
11332
11333         private async void ApiUsageInfoMenuItem_Click(object sender, EventArgs e)
11334         {
11335             TwitterApiStatus apiStatus;
11336
11337             using (var dialog = new WaitingDialog(Properties.Resources.ApiInfo6))
11338             {
11339                 var cancellationToken = dialog.EnableCancellation();
11340
11341                 try
11342                 {
11343                     var task = Task.Run(() => this.tw.GetInfoApi());
11344                     apiStatus = await dialog.WaitForAsync(this, task);
11345                 }
11346                 catch (WebApiException)
11347                 {
11348                     apiStatus = null;
11349                 }
11350
11351                 if (cancellationToken.IsCancellationRequested)
11352                     return;
11353
11354                 if (apiStatus == null)
11355                 {
11356                     MessageBox.Show(Properties.Resources.ApiInfo5, Properties.Resources.ApiInfo4, MessageBoxButtons.OK, MessageBoxIcon.Information);
11357                     return;
11358                 }
11359             }
11360
11361             using (var apiDlg = new ApiInfoDialog())
11362             {
11363                 apiDlg.ShowDialog(this);
11364             }
11365         }
11366
11367         private async void FollowCommandMenuItem_Click(object sender, EventArgs e)
11368         {
11369             var id = _curPost?.ScreenName ?? "";
11370
11371             await this.FollowCommand(id);
11372         }
11373
11374         private async Task FollowCommand(string id)
11375         {
11376             using (var inputName = new InputTabName())
11377             {
11378                 inputName.FormTitle = "Follow";
11379                 inputName.FormDescription = Properties.Resources.FRMessage1;
11380                 inputName.TabName = id;
11381
11382                 if (inputName.ShowDialog(this) != DialogResult.OK)
11383                     return;
11384                 if (string.IsNullOrWhiteSpace(inputName.TabName))
11385                     return;
11386
11387                 id = inputName.TabName.Trim();
11388             }
11389
11390             using (var dialog = new WaitingDialog(Properties.Resources.FollowCommandText1))
11391             {
11392                 try
11393                 {
11394                     var task = Task.Run(() => this.tw.PostFollowCommand(id));
11395                     await dialog.WaitForAsync(this, task);
11396                 }
11397                 catch (WebApiException ex)
11398                 {
11399                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11400                     return;
11401                 }
11402             }
11403
11404             MessageBox.Show(Properties.Resources.FRMessage3);
11405         }
11406
11407         private async void RemoveCommandMenuItem_Click(object sender, EventArgs e)
11408         {
11409             var id = _curPost?.ScreenName ?? "";
11410
11411             await this.RemoveCommand(id, false);
11412         }
11413
11414         private async Task RemoveCommand(string id, bool skipInput)
11415         {
11416             if (!skipInput)
11417             {
11418                 using (var inputName = new InputTabName())
11419                 {
11420                     inputName.FormTitle = "Unfollow";
11421                     inputName.FormDescription = Properties.Resources.FRMessage1;
11422                     inputName.TabName = id;
11423
11424                     if (inputName.ShowDialog(this) != DialogResult.OK)
11425                         return;
11426                     if (string.IsNullOrWhiteSpace(inputName.TabName))
11427                         return;
11428
11429                     id = inputName.TabName.Trim();
11430                 }
11431             }
11432
11433             using (var dialog = new WaitingDialog(Properties.Resources.RemoveCommandText1))
11434             {
11435                 try
11436                 {
11437                     var task = Task.Run(() => this.tw.PostRemoveCommand(id));
11438                     await dialog.WaitForAsync(this, task);
11439                 }
11440                 catch (WebApiException ex)
11441                 {
11442                     MessageBox.Show(Properties.Resources.FRMessage2 + ex.Message);
11443                     return;
11444                 }
11445             }
11446
11447             MessageBox.Show(Properties.Resources.FRMessage3);
11448         }
11449
11450         private async void FriendshipMenuItem_Click(object sender, EventArgs e)
11451         {
11452             var id = _curPost?.ScreenName ?? "";
11453
11454             await this.ShowFriendship(id);
11455         }
11456
11457         private async Task ShowFriendship(string id)
11458         {
11459             using (var inputName = new InputTabName())
11460             {
11461                 inputName.FormTitle = "Show Friendships";
11462                 inputName.FormDescription = Properties.Resources.FRMessage1;
11463                 inputName.TabName = id;
11464
11465                 if (inputName.ShowDialog(this) != DialogResult.OK)
11466                     return;
11467                 if (string.IsNullOrWhiteSpace(inputName.TabName))
11468                     return;
11469
11470                 id = inputName.TabName.Trim();
11471             }
11472
11473             bool isFollowing, isFollowed;
11474
11475             using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11476             {
11477                 var cancellationToken = dialog.EnableCancellation();
11478
11479                 try
11480                 {
11481                     var task = Task.Run(() => this.tw.GetFriendshipInfo(id));
11482                     var friendship = await dialog.WaitForAsync(this, task);
11483
11484                     isFollowing = friendship.Relationship.Source.Following;
11485                     isFollowed = friendship.Relationship.Source.FollowedBy;
11486                 }
11487                 catch (WebApiException ex)
11488                 {
11489                     if (!cancellationToken.IsCancellationRequested)
11490                         MessageBox.Show(ex.Message);
11491                     return;
11492                 }
11493
11494                 if (cancellationToken.IsCancellationRequested)
11495                     return;
11496             }
11497
11498             string result = "";
11499             if (isFollowing)
11500             {
11501                 result = Properties.Resources.GetFriendshipInfo1 + System.Environment.NewLine;
11502             }
11503             else
11504             {
11505                 result = Properties.Resources.GetFriendshipInfo2 + System.Environment.NewLine;
11506             }
11507             if (isFollowed)
11508             {
11509                 result += Properties.Resources.GetFriendshipInfo3;
11510             }
11511             else
11512             {
11513                 result += Properties.Resources.GetFriendshipInfo4;
11514             }
11515             result = id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + result;
11516             MessageBox.Show(result);
11517         }
11518
11519         private async Task ShowFriendship(string[] ids)
11520         {
11521             foreach (string id in ids)
11522             {
11523                 bool isFollowing, isFollowed;
11524
11525                 using (var dialog = new WaitingDialog(Properties.Resources.ShowFriendshipText1))
11526                 {
11527                     var cancellationToken = dialog.EnableCancellation();
11528
11529                     try
11530                     {
11531                         var task = Task.Run(() => this.tw.GetFriendshipInfo(id));
11532                         var friendship = await dialog.WaitForAsync(this, task);
11533
11534                         isFollowing = friendship.Relationship.Source.Following;
11535                         isFollowed = friendship.Relationship.Source.FollowedBy;
11536                     }
11537                     catch (WebApiException ex)
11538                     {
11539                         if (!cancellationToken.IsCancellationRequested)
11540                             MessageBox.Show(ex.Message);
11541                         return;
11542                     }
11543
11544                     if (cancellationToken.IsCancellationRequested)
11545                         return;
11546                 }
11547
11548                 string result = "";
11549                 string ff = "";
11550
11551                 ff = "  ";
11552                 if (isFollowing)
11553                 {
11554                     ff += Properties.Resources.GetFriendshipInfo1;
11555                 }
11556                 else
11557                 {
11558                     ff += Properties.Resources.GetFriendshipInfo2;
11559                 }
11560
11561                 ff += System.Environment.NewLine + "  ";
11562                 if (isFollowed)
11563                 {
11564                     ff += Properties.Resources.GetFriendshipInfo3;
11565                 }
11566                 else
11567                 {
11568                     ff += Properties.Resources.GetFriendshipInfo4;
11569                 }
11570                 result += id + Properties.Resources.GetFriendshipInfo5 + System.Environment.NewLine + ff;
11571                 if (isFollowing)
11572                 {
11573                     if (MessageBox.Show(
11574                         Properties.Resources.GetFriendshipInfo7 + System.Environment.NewLine + result, Properties.Resources.GetFriendshipInfo8,
11575                         MessageBoxButtons.YesNo,
11576                         MessageBoxIcon.Question,
11577                         MessageBoxDefaultButton.Button2) == DialogResult.Yes)
11578                     {
11579                         await this.RemoveCommand(id, true);
11580                     }
11581                 }
11582                 else
11583                 {
11584                     MessageBox.Show(result);
11585                 }
11586             }
11587         }
11588
11589         private async void OwnStatusMenuItem_Click(object sender, EventArgs e)
11590         {
11591             await this.doShowUserStatus(tw.Username, false);
11592             //if (!string.IsNullOrEmpty(tw.UserInfoXml))
11593             //{
11594             //    doShowUserStatus(tw.Username, false);
11595             //}
11596             //else
11597             //{
11598             //    MessageBox.Show(Properties.Resources.ShowYourProfileText1, "Your status", MessageBoxButtons.OK, MessageBoxIcon.Information);
11599             //    return;
11600             //}
11601         }
11602
11603         // TwitterIDでない固定文字列を調べる(文字列検証のみ 実際に取得はしない)
11604         // URLから切り出した文字列を渡す
11605
11606         public bool IsTwitterId(string name)
11607         {
11608             if (this.tw.Configuration.NonUsernamePaths == null || this.tw.Configuration.NonUsernamePaths.Length == 0)
11609                 return !Regex.Match(name, @"^(about|jobs|tos|privacy|who_to_follow|download|messages)$", RegexOptions.IgnoreCase).Success;
11610             else
11611                 return !this.tw.Configuration.NonUsernamePaths.Contains(name.ToLower());
11612         }
11613
11614         private string GetUserId()
11615         {
11616             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?$");
11617             if (m.Success && IsTwitterId(m.Result("${ScreenName}")))
11618                 return m.Result("${ScreenName}");
11619             else
11620                 return null;
11621         }
11622
11623         private async void FollowContextMenuItem_Click(object sender, EventArgs e)
11624         {
11625             string name = GetUserId();
11626             if (name != null)
11627                 await this.FollowCommand(name);
11628         }
11629
11630         private async void RemoveContextMenuItem_Click(object sender, EventArgs e)
11631         {
11632             string name = GetUserId();
11633             if (name != null)
11634                 await this.RemoveCommand(name, false);
11635         }
11636
11637         private async void FriendshipContextMenuItem_Click(object sender, EventArgs e)
11638         {
11639             string name = GetUserId();
11640             if (name != null)
11641                 await this.ShowFriendship(name);
11642         }
11643
11644         private async void FriendshipAllMenuItem_Click(object sender, EventArgs e)
11645         {
11646             MatchCollection ma = Regex.Matches(this.PostBrowser.DocumentText, @"href=""https?://twitter.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)(/status(es)?/[0-9]+)?""");
11647             List<string> ids = new List<string>();
11648             foreach (Match mu in ma)
11649             {
11650                 if (mu.Result("${ScreenName}").ToLower() != tw.Username.ToLower())
11651                 {
11652                     ids.Add(mu.Result("${ScreenName}"));
11653                 }
11654             }
11655
11656             await this.ShowFriendship(ids.ToArray());
11657         }
11658
11659         private async void ShowUserStatusContextMenuItem_Click(object sender, EventArgs e)
11660         {
11661             string name = GetUserId();
11662             if (name != null)
11663                 await this.ShowUserStatus(name);
11664         }
11665
11666         private void SearchPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11667         {
11668             string name = GetUserId();
11669             if (name != null) AddNewTabForUserTimeline(name);
11670         }
11671
11672         private void SearchAtPostsDetailToolStripMenuItem_Click(object sender, EventArgs e)
11673         {
11674             string name = GetUserId();
11675             if (name != null) AddNewTabForSearch("@" + name);
11676         }
11677
11678         private void IdeographicSpaceToSpaceToolStripMenuItem_Click(object sender, EventArgs e)
11679         {
11680             _modifySettingCommon = true;
11681         }
11682
11683         private void ToolStripFocusLockMenuItem_CheckedChanged(object sender, EventArgs e)
11684         {
11685             _modifySettingCommon = true;
11686         }
11687
11688         private void doQuoteOfficial()
11689         {
11690             if (this.ExistCurrentPost)
11691             {
11692                 if (_curPost.IsDm ||
11693                     !StatusText.Enabled) return;
11694
11695                 if (_curPost.IsProtect)
11696                 {
11697                     MessageBox.Show("Protected.");
11698                     return;
11699                 }
11700
11701                 StatusText.Text = " " + MyCommon.GetStatusUrl(_curPost);
11702
11703                 this.inReplyTo = null;
11704
11705                 StatusText.SelectionStart = 0;
11706                 StatusText.Focus();
11707             }
11708         }
11709
11710         private void doReTweetUnofficial()
11711         {
11712             //RT @id:内容
11713             if (this.ExistCurrentPost)
11714             {
11715                 if (_curPost.IsDm || !StatusText.Enabled)
11716                     return;
11717
11718                 if (_curPost.IsProtect)
11719                 {
11720                     MessageBox.Show("Protected.");
11721                     return;
11722                 }
11723                 string rtdata = _curPost.Text;
11724                 rtdata = CreateRetweetUnofficial(rtdata, this.StatusText.Multiline);
11725
11726                 StatusText.Text = " RT @" + _curPost.ScreenName + ": " + rtdata;
11727
11728                 // 投稿時に in_reply_to_status_id を付加する
11729                 var inReplyToStatusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
11730                 var inReplyToScreenName = this._curPost.ScreenName;
11731                 this.inReplyTo = Tuple.Create(inReplyToStatusId, inReplyToScreenName);
11732
11733                 StatusText.SelectionStart = 0;
11734                 StatusText.Focus();
11735             }
11736         }
11737
11738         private void QuoteStripMenuItem_Click(object sender, EventArgs e) // Handles QuoteStripMenuItem.Click, QtOpMenuItem.Click
11739         {
11740             doQuoteOfficial();
11741         }
11742
11743         private void SearchButton_Click(object sender, EventArgs e)
11744         {
11745             //公式検索
11746             Control pnl = ((Control)sender).Parent;
11747             if (pnl == null) return;
11748             string tbName = pnl.Parent.Text;
11749             TabClass tb = _statuses.Tabs[tbName];
11750             ComboBox cmb = (ComboBox)pnl.Controls["comboSearch"];
11751             ComboBox cmbLang = (ComboBox)pnl.Controls["comboLang"];
11752             cmb.Text = cmb.Text.Trim();
11753             // 検索式演算子 OR についてのみ大文字しか認識しないので強制的に大文字とする
11754             bool Quote = false;
11755             StringBuilder buf = new StringBuilder();
11756             char[] c = cmb.Text.ToCharArray();
11757             for (int cnt = 0; cnt < cmb.Text.Length; cnt++)
11758             {
11759                 if (cnt > cmb.Text.Length - 4)
11760                 {
11761                     buf.Append(cmb.Text.Substring(cnt));
11762                     break;
11763                 }
11764                 if (c[cnt] == '"')
11765                 {
11766                     Quote = !Quote;
11767                 }
11768                 else
11769                 {
11770                     if (!Quote && cmb.Text.Substring(cnt, 4).Equals(" or ", StringComparison.OrdinalIgnoreCase))
11771                     {
11772                         buf.Append(" OR ");
11773                         cnt += 3;
11774                         continue;
11775                     }
11776                 }
11777                 buf.Append(c[cnt]);
11778             }
11779             cmb.Text = buf.ToString();
11780
11781             var listView = (DetailsListView)pnl.Parent.Tag;
11782
11783             tb.SearchWords = cmb.Text;
11784             tb.SearchLang = cmbLang.Text;
11785             if (string.IsNullOrEmpty(cmb.Text))
11786             {
11787                 listView.Focus();
11788                 SaveConfigsTabs();
11789                 return;
11790             }
11791             if (tb.IsSearchQueryChanged)
11792             {
11793                 int idx = cmb.Items.IndexOf(tb.SearchWords);
11794                 if (idx > -1) cmb.Items.RemoveAt(idx);
11795                 cmb.Items.Insert(0, tb.SearchWords);
11796                 cmb.Text = tb.SearchWords;
11797                 cmb.SelectAll();
11798                 this.PurgeListViewItemCache();
11799                 listView.VirtualListSize = 0;
11800                 _statuses.ClearTabIds(tbName);
11801                 SaveConfigsTabs();   //検索条件の保存
11802             }
11803
11804             this.GetPublicSearchAsync(tb);
11805             listView.Focus();
11806         }
11807
11808         private async void RefreshMoreStripMenuItem_Click(object sender, EventArgs e)
11809         {
11810             //もっと前を取得
11811             await this.DoRefreshMore();
11812         }
11813
11814         /// <summary>
11815         /// 指定されたタブのListTabにおける位置を返します
11816         /// </summary>
11817         /// <remarks>
11818         /// 非表示のタブについて -1 が返ることを常に考慮して下さい
11819         /// </remarks>
11820         public int GetTabPageIndex(string tabName)
11821         {
11822             var index = 0;
11823             foreach (var tabPage in this.ListTab.TabPages.Cast<TabPage>())
11824             {
11825                 if (tabPage.Text == tabName)
11826                     return index;
11827
11828                 index++;
11829             }
11830
11831             return -1;
11832         }
11833
11834         private void UndoRemoveTabMenuItem_Click(object sender, EventArgs e)
11835         {
11836             if (_statuses.RemovedTab.Count == 0)
11837             {
11838                 MessageBox.Show("There isn't removed tab.", "Undo", MessageBoxButtons.OK, MessageBoxIcon.Information);
11839                 return;
11840             }
11841             else
11842             {
11843                 DetailsListView listView = null;
11844
11845                 TabClass tb = _statuses.RemovedTab.Pop();
11846                 if (tb.TabType == MyCommon.TabUsageType.Related)
11847                 {
11848                     var relatedTab = _statuses.GetTabByType(MyCommon.TabUsageType.Related);
11849                     if (relatedTab != null)
11850                     {
11851                         // 関連発言なら既存のタブを置き換える
11852                         tb.TabName = relatedTab.TabName;
11853                         this.ClearTab(tb.TabName, false);
11854                         _statuses.Tabs[tb.TabName] = tb;
11855
11856                         for (int i = 0; i < ListTab.TabPages.Count; i++)
11857                         {
11858                             var tabPage = ListTab.TabPages[i];
11859                             if (tb.TabName == tabPage.Text)
11860                             {
11861                                 listView = (DetailsListView)tabPage.Tag;
11862                                 ListTab.SelectedIndex = i;
11863                                 break;
11864                             }
11865                         }
11866                     }
11867                     else
11868                     {
11869                         const string TabName = "Related Tweets";
11870                         string renamed = TabName;
11871                         for (int i = 2; i <= 100; i++)
11872                         {
11873                             if (!_statuses.ContainsTab(renamed)) break;
11874                             renamed = TabName + i.ToString();
11875                         }
11876                         tb.TabName = renamed;
11877                         AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11878                         _statuses.Tabs.Add(renamed, tb);  // 後に
11879
11880                         var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11881                         listView = (DetailsListView)tabPage.Tag;
11882                         ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11883                     }
11884                 }
11885                 else
11886                 {
11887                     string renamed = tb.TabName;
11888                     for (int i = 1; i < int.MaxValue; i++)
11889                     {
11890                         if (!_statuses.ContainsTab(renamed)) break;
11891                         renamed = tb.TabName + "(" + i.ToString() + ")";
11892                     }
11893                     tb.TabName = renamed;
11894                     _statuses.Tabs.Add(renamed, tb);  // 先に
11895                     AddNewTab(renamed, false, tb.TabType, tb.ListInfo);
11896
11897                     var tabPage = ListTab.TabPages[ListTab.TabPages.Count - 1];
11898                     listView = (DetailsListView)tabPage.Tag;
11899                     ListTab.SelectedIndex = ListTab.TabPages.Count - 1;
11900                 }
11901                 SaveConfigsTabs();
11902
11903                 if (listView != null)
11904                 {
11905                     using (ControlTransaction.Update(listView))
11906                     {
11907                         listView.VirtualListSize = tb.AllCount;
11908                     }
11909                 }
11910             }
11911         }
11912
11913         private async Task doMoveToRTHome()
11914         {
11915             if (_curList.SelectedIndices.Count > 0)
11916             {
11917                 PostClass post = GetCurTabPost(_curList.SelectedIndices[0]);
11918                 if (post.RetweetedId != null)
11919                 {
11920                     await this.OpenUriInBrowserAsync("https://twitter.com/" + GetCurTabPost(_curList.SelectedIndices[0]).RetweetedBy);
11921                 }
11922             }
11923         }
11924
11925         private async void MoveToRTHomeMenuItem_Click(object sender, EventArgs e)
11926         {
11927             await this.doMoveToRTHome();
11928         }
11929
11930         private void IdFilterAddMenuItem_Click(object sender, EventArgs e)
11931         {
11932             string name = GetUserId();
11933             if (name != null)
11934             {
11935                 string tabName;
11936
11937                 //未選択なら処理終了
11938                 if (_curList.SelectedIndices.Count == 0) return;
11939
11940                 //タブ選択(or追加)
11941                 if (!SelectTab(out tabName)) return;
11942
11943                 var tab = this._statuses.Tabs[tabName];
11944
11945                 bool mv;
11946                 bool mk;
11947                 if (tab.TabType != MyCommon.TabUsageType.Mute)
11948                 {
11949                     this.MoveOrCopy(out mv, out mk);
11950                 }
11951                 else
11952                 {
11953                     // ミュートタブでは常に MoveMatches を true にする
11954                     mv = true;
11955                     mk = false;
11956                 }
11957
11958                 PostFilterRule fc = new PostFilterRule();
11959                 fc.FilterName = name;
11960                 fc.UseNameField = true;
11961                 fc.MoveMatches = mv;
11962                 fc.MarkMatches = mk;
11963                 fc.UseRegex = false;
11964                 fc.FilterByUrl = false;
11965                 tab.AddFilter(fc);
11966
11967                 this.ApplyPostFilters();
11968                 SaveConfigsTabs();
11969             }
11970         }
11971
11972         private void ListManageUserContextToolStripMenuItem_Click(object sender, EventArgs e)
11973         {
11974             string user;
11975
11976             ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
11977
11978             if (menuItem.Owner == this.ContextMenuPostBrowser)
11979             {
11980                 user = GetUserId();
11981                 if (user == null) return;
11982             }
11983             else if (this._curPost != null)
11984             {
11985                 user = this._curPost.ScreenName;
11986             }
11987             else
11988             {
11989                 return;
11990             }
11991
11992             if (TabInformations.GetInstance().SubscribableLists.Count == 0)
11993             {
11994                 try
11995                 {
11996                     this.tw.GetListsApi();
11997                 }
11998                 catch (WebApiException ex)
11999                 {
12000                     MessageBox.Show("Failed to get lists. (" + ex.Message + ")");
12001                     return;
12002                 }
12003             }
12004
12005             using (MyLists listSelectForm = new MyLists(user, this.tw))
12006             {
12007                 listSelectForm.ShowDialog(this);
12008             }
12009         }
12010
12011         private void SearchControls_Enter(object sender, EventArgs e)
12012         {
12013             Control pnl = (Control)sender;
12014             foreach (Control ctl in pnl.Controls)
12015             {
12016                 ctl.TabStop = true;
12017             }
12018         }
12019
12020         private void SearchControls_Leave(object sender, EventArgs e)
12021         {
12022             Control pnl = (Control)sender;
12023             foreach (Control ctl in pnl.Controls)
12024             {
12025                 ctl.TabStop = false;
12026             }
12027         }
12028
12029         private void PublicSearchQueryMenuItem_Click(object sender, EventArgs e)
12030         {
12031             if (ListTab.SelectedTab != null)
12032             {
12033                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.PublicSearch) return;
12034                 ListTab.SelectedTab.Controls["panelSearch"].Controls["comboSearch"].Focus();
12035             }
12036         }
12037
12038         private void UseHashtagMenuItem_Click(object sender, EventArgs e)
12039         {
12040             Match m = Regex.Match(this._postBrowserStatusText, @"^https?://twitter.com/search\?q=%23(?<hash>.+)$");
12041             if (m.Success)
12042             {
12043                 HashMgr.SetPermanentHash("#" + Uri.UnescapeDataString(m.Result("${hash}")));
12044                 HashStripSplitButton.Text = HashMgr.UseHash;
12045                 HashToggleMenuItem.Checked = true;
12046                 HashToggleToolStripMenuItem.Checked = true;
12047                 //使用ハッシュタグとして設定
12048                 _modifySettingCommon = true;
12049             }
12050         }
12051
12052         private void StatusLabel_DoubleClick(object sender, EventArgs e)
12053         {
12054             MessageBox.Show(StatusLabel.TextHistory, "Logs", MessageBoxButtons.OK, MessageBoxIcon.None);
12055         }
12056
12057         private void HashManageMenuItem_Click(object sender, EventArgs e)
12058         {
12059             DialogResult rslt = DialogResult.Cancel;
12060             try
12061             {
12062                 rslt = HashMgr.ShowDialog();
12063             }
12064             catch (Exception)
12065             {
12066                 return;
12067             }
12068             this.TopMost = this._cfgCommon.AlwaysTop;
12069             if (rslt == DialogResult.Cancel) return;
12070             if (!string.IsNullOrEmpty(HashMgr.UseHash))
12071             {
12072                 HashStripSplitButton.Text = HashMgr.UseHash;
12073                 HashToggleMenuItem.Checked = true;
12074                 HashToggleToolStripMenuItem.Checked = true;
12075             }
12076             else
12077             {
12078                 HashStripSplitButton.Text = "#[-]";
12079                 HashToggleMenuItem.Checked = false;
12080                 HashToggleToolStripMenuItem.Checked = false;
12081             }
12082             //if (HashMgr.IsInsert && HashMgr.UseHash != "")
12083             //{
12084             //    int sidx = StatusText.SelectionStart;
12085             //    string hash = HashMgr.UseHash + " ";
12086             //    if (sidx > 0)
12087             //    {
12088             //        if (StatusText.Text.Substring(sidx - 1, 1) != " ")
12089             //            hash = " " + hash;
12090             //    }
12091             //    StatusText.Text = StatusText.Text.Insert(sidx, hash);
12092             //    sidx += hash.Length;
12093             //    StatusText.SelectionStart = sidx;
12094             //    StatusText.Focus();
12095             //}
12096             _modifySettingCommon = true;
12097             this.StatusText_TextChanged(null, null);
12098         }
12099
12100         private void HashToggleMenuItem_Click(object sender, EventArgs e)
12101         {
12102             HashMgr.ToggleHash();
12103             if (!string.IsNullOrEmpty(HashMgr.UseHash))
12104             {
12105                 HashStripSplitButton.Text = HashMgr.UseHash;
12106                 HashToggleMenuItem.Checked = true;
12107                 HashToggleToolStripMenuItem.Checked = true;
12108             }
12109             else
12110             {
12111                 HashStripSplitButton.Text = "#[-]";
12112                 HashToggleMenuItem.Checked = false;
12113                 HashToggleToolStripMenuItem.Checked = false;
12114             }
12115             _modifySettingCommon = true;
12116             this.StatusText_TextChanged(null, null);
12117         }
12118
12119         private void HashStripSplitButton_ButtonClick(object sender, EventArgs e)
12120         {
12121             HashToggleMenuItem_Click(null, null);
12122         }
12123
12124         private void MenuItemOperate_DropDownOpening(object sender, EventArgs e)
12125         {
12126             if (ListTab.SelectedTab == null) return;
12127             if (_statuses == null || _statuses.Tabs == null || !_statuses.Tabs.ContainsKey(ListTab.SelectedTab.Text)) return;
12128             if (!this.ExistCurrentPost)
12129             {
12130                 this.ReplyOpMenuItem.Enabled = false;
12131                 this.ReplyAllOpMenuItem.Enabled = false;
12132                 this.DmOpMenuItem.Enabled = false;
12133                 this.ShowProfMenuItem.Enabled = false;
12134                 this.ShowUserTimelineToolStripMenuItem.Enabled = false;
12135                 this.ListManageMenuItem.Enabled = false;
12136                 this.OpenFavOpMenuItem.Enabled = false;
12137                 this.CreateTabRuleOpMenuItem.Enabled = false;
12138                 this.CreateIdRuleOpMenuItem.Enabled = false;
12139                 this.CreateSourceRuleOpMenuItem.Enabled = false;
12140                 this.ReadOpMenuItem.Enabled = false;
12141                 this.UnreadOpMenuItem.Enabled = false;
12142             }
12143             else
12144             {
12145                 this.ReplyOpMenuItem.Enabled = true;
12146                 this.ReplyAllOpMenuItem.Enabled = true;
12147                 this.DmOpMenuItem.Enabled = true;
12148                 this.ShowProfMenuItem.Enabled = true;
12149                 this.ShowUserTimelineToolStripMenuItem.Enabled = true;
12150                 this.ListManageMenuItem.Enabled = true;
12151                 this.OpenFavOpMenuItem.Enabled = true;
12152                 this.CreateTabRuleOpMenuItem.Enabled = true;
12153                 this.CreateIdRuleOpMenuItem.Enabled = true;
12154                 this.CreateSourceRuleOpMenuItem.Enabled = true;
12155                 this.ReadOpMenuItem.Enabled = true;
12156                 this.UnreadOpMenuItem.Enabled = true;
12157             }
12158
12159             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.DirectMessage || !this.ExistCurrentPost || _curPost.IsDm)
12160             {
12161                 this.FavOpMenuItem.Enabled = false;
12162                 this.UnFavOpMenuItem.Enabled = false;
12163                 this.OpenStatusOpMenuItem.Enabled = false;
12164                 this.OpenFavotterOpMenuItem.Enabled = false;
12165                 this.ShowRelatedStatusesMenuItem2.Enabled = false;
12166                 this.RtOpMenuItem.Enabled = false;
12167                 this.RtUnOpMenuItem.Enabled = false;
12168                 this.QtOpMenuItem.Enabled = false;
12169                 this.FavoriteRetweetMenuItem.Enabled = false;
12170                 this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12171             }
12172             else
12173             {
12174                 this.FavOpMenuItem.Enabled = true;
12175                 this.UnFavOpMenuItem.Enabled = true;
12176                 this.OpenStatusOpMenuItem.Enabled = true;
12177                 this.OpenFavotterOpMenuItem.Enabled = true;
12178                 this.ShowRelatedStatusesMenuItem2.Enabled = true;  //PublicSearchの時問題出るかも
12179
12180                 if (_curPost.IsMe)
12181                 {
12182                     this.RtOpMenuItem.Enabled = false;  //公式RTは無効に
12183                     this.RtUnOpMenuItem.Enabled = true;
12184                     this.QtOpMenuItem.Enabled = true;
12185                     this.FavoriteRetweetMenuItem.Enabled = false;  //公式RTは無効に
12186                     this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12187                 }
12188                 else
12189                 {
12190                     if (_curPost.IsProtect)
12191                     {
12192                         this.RtOpMenuItem.Enabled = false;
12193                         this.RtUnOpMenuItem.Enabled = false;
12194                         this.QtOpMenuItem.Enabled = false;
12195                         this.FavoriteRetweetMenuItem.Enabled = false;
12196                         this.FavoriteRetweetUnofficialMenuItem.Enabled = false;
12197                     }
12198                     else
12199                     {
12200                         this.RtOpMenuItem.Enabled = true;
12201                         this.RtUnOpMenuItem.Enabled = true;
12202                         this.QtOpMenuItem.Enabled = true;
12203                         this.FavoriteRetweetMenuItem.Enabled = true;
12204                         this.FavoriteRetweetUnofficialMenuItem.Enabled = true;
12205                     }
12206                 }
12207             }
12208
12209             if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType != MyCommon.TabUsageType.Favorites)
12210             {
12211                 this.RefreshPrevOpMenuItem.Enabled = true;
12212             }
12213             else
12214             {
12215                 this.RefreshPrevOpMenuItem.Enabled = false;
12216             }
12217             if (!this.ExistCurrentPost
12218                 || _curPost.InReplyToStatusId == null)
12219             {
12220                 OpenRepSourceOpMenuItem.Enabled = false;
12221             }
12222             else
12223             {
12224                 OpenRepSourceOpMenuItem.Enabled = true;
12225             }
12226             if (!this.ExistCurrentPost || string.IsNullOrEmpty(_curPost.RetweetedBy))
12227             {
12228                 OpenRterHomeMenuItem.Enabled = false;
12229             }
12230             else
12231             {
12232                 OpenRterHomeMenuItem.Enabled = true;
12233             }
12234
12235             if (this.ExistCurrentPost)
12236             {
12237                 this.DelOpMenuItem.Enabled = this._curPost.CanDeleteBy(this.tw.UserId);
12238             }
12239         }
12240
12241         private void MenuItemTab_DropDownOpening(object sender, EventArgs e)
12242         {
12243             ContextMenuTabProperty_Opening(sender, null);
12244         }
12245
12246         public Twitter TwitterInstance
12247         {
12248             get { return tw; }
12249         }
12250
12251         private void SplitContainer3_SplitterMoved(object sender, SplitterEventArgs e)
12252         {
12253             if (this._initialLayout)
12254                 return;
12255
12256             int splitterDistance;
12257             switch (this.WindowState)
12258             {
12259                 case FormWindowState.Normal:
12260                     splitterDistance = this.SplitContainer3.SplitterDistance;
12261                     break;
12262                 case FormWindowState.Maximized:
12263                     // 最大化時は、通常時のウィンドウサイズに換算した SplitterDistance を算出する
12264                     var normalContainerWidth = this._mySize.Width - SystemInformation.Border3DSize.Width * 2;
12265                     splitterDistance = this.SplitContainer3.SplitterDistance - (this.SplitContainer3.Width - normalContainerWidth);
12266                     splitterDistance = Math.Min(splitterDistance, normalContainerWidth - this.SplitContainer3.SplitterWidth - this.SplitContainer3.Panel2MinSize);
12267                     break;
12268                 default:
12269                     return;
12270             }
12271
12272             this._mySpDis3 = splitterDistance;
12273             this._modifySettingLocal = true;
12274         }
12275
12276         private void MenuItemEdit_DropDownOpening(object sender, EventArgs e)
12277         {
12278             if (_statuses.RemovedTab.Count == 0)
12279             {
12280                 UndoRemoveTabMenuItem.Enabled = false;
12281             }
12282             else
12283             {
12284                 UndoRemoveTabMenuItem.Enabled = true;
12285             }
12286             if (ListTab.SelectedTab != null)
12287             {
12288                 if (_statuses.Tabs[ListTab.SelectedTab.Text].TabType == MyCommon.TabUsageType.PublicSearch)
12289                     PublicSearchQueryMenuItem.Enabled = true;
12290                 else
12291                     PublicSearchQueryMenuItem.Enabled = false;
12292             }
12293             else
12294             {
12295                 PublicSearchQueryMenuItem.Enabled = false;
12296             }
12297             if (!this.ExistCurrentPost)
12298             {
12299                 this.CopySTOTMenuItem.Enabled = false;
12300                 this.CopyURLMenuItem.Enabled = false;
12301                 this.CopyUserIdStripMenuItem.Enabled = false;
12302             }
12303             else
12304             {
12305                 this.CopySTOTMenuItem.Enabled = true;
12306                 this.CopyURLMenuItem.Enabled = true;
12307                 this.CopyUserIdStripMenuItem.Enabled = true;
12308                 if (_curPost.IsDm) this.CopyURLMenuItem.Enabled = false;
12309                 if (_curPost.IsProtect) this.CopySTOTMenuItem.Enabled = false;
12310             }
12311         }
12312
12313         private void NotifyIcon1_MouseMove(object sender, MouseEventArgs e)
12314         {
12315             SetNotifyIconText();
12316         }
12317
12318         private async void UserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12319         {
12320             var id = _curPost?.ScreenName ?? "";
12321
12322             await this.ShowUserStatus(id);
12323         }
12324
12325         private async Task doShowUserStatus(string id, bool ShowInputDialog)
12326         {
12327             TwitterUser user = null;
12328
12329             if (ShowInputDialog)
12330             {
12331                 using (var inputName = new InputTabName())
12332                 {
12333                     inputName.FormTitle = "Show UserStatus";
12334                     inputName.FormDescription = Properties.Resources.FRMessage1;
12335                     inputName.TabName = id;
12336
12337                     if (inputName.ShowDialog(this) != DialogResult.OK)
12338                         return;
12339                     if (string.IsNullOrWhiteSpace(inputName.TabName))
12340                         return;
12341
12342                     id = inputName.TabName.Trim();
12343                 }
12344             }
12345
12346             using (var dialog = new WaitingDialog(Properties.Resources.doShowUserStatusText1))
12347             {
12348                 var cancellationToken = dialog.EnableCancellation();
12349
12350                 try
12351                 {
12352                     var task = Task.Run(() => this.tw.GetUserInfo(id));
12353                     user = await dialog.WaitForAsync(this, task);
12354                 }
12355                 catch (WebApiException ex)
12356                 {
12357                     if (!cancellationToken.IsCancellationRequested)
12358                         MessageBox.Show(ex.Message);
12359                     return;
12360                 }
12361
12362                 if (cancellationToken.IsCancellationRequested)
12363                     return;
12364             }
12365
12366             await this.doShowUserStatus(user);
12367         }
12368
12369         private async Task doShowUserStatus(TwitterUser user)
12370         {
12371             using (var userDialog = new UserInfoDialog(this, this.tw))
12372             {
12373                 var showUserTask = userDialog.ShowUserAsync(user);
12374                 userDialog.ShowDialog(this);
12375
12376                 this.Activate();
12377                 this.BringToFront();
12378
12379                 // ユーザー情報の表示が完了するまで userDialog を破棄しない
12380                 await showUserTask;
12381             }
12382         }
12383
12384         private Task ShowUserStatus(string id, bool ShowInputDialog)
12385         {
12386             return this.doShowUserStatus(id, ShowInputDialog);
12387         }
12388
12389         private Task ShowUserStatus(string id)
12390         {
12391             return this.doShowUserStatus(id, true);
12392         }
12393
12394         private async void FollowToolStripMenuItem_Click(object sender, EventArgs e)
12395         {
12396             if (NameLabel.Tag != null)
12397             {
12398                 string id = (string)NameLabel.Tag;
12399                 if (id != tw.Username)
12400                 {
12401                     await this.FollowCommand(id);
12402                 }
12403             }
12404         }
12405
12406         private async void UnFollowToolStripMenuItem_Click(object sender, EventArgs e)
12407         {
12408             if (NameLabel.Tag != null)
12409             {
12410                 string id = (string)NameLabel.Tag;
12411                 if (id != tw.Username)
12412                 {
12413                     await this.RemoveCommand(id, false);
12414                 }
12415             }
12416         }
12417
12418         private async void ShowFriendShipToolStripMenuItem_Click(object sender, EventArgs e)
12419         {
12420             if (NameLabel.Tag != null)
12421             {
12422                 string id = (string)NameLabel.Tag;
12423                 if (id != tw.Username)
12424                 {
12425                     await this.ShowFriendship(id);
12426                 }
12427             }
12428         }
12429
12430         private async void ShowUserStatusToolStripMenuItem_Click(object sender, EventArgs e)
12431         {
12432             if (NameLabel.Tag != null)
12433             {
12434                 string id = (string)NameLabel.Tag;
12435                 await this.ShowUserStatus(id, false);
12436             }
12437         }
12438
12439         private void SearchPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12440         {
12441             if (NameLabel.Tag != null)
12442             {
12443                 string id = (string)NameLabel.Tag;
12444                 AddNewTabForUserTimeline(id);
12445             }
12446         }
12447
12448         private void SearchAtPostsDetailNameToolStripMenuItem_Click(object sender, EventArgs e)
12449         {
12450             if (NameLabel.Tag != null)
12451             {
12452                 string id = (string)NameLabel.Tag;
12453                 AddNewTabForSearch("@" + id);
12454             }
12455         }
12456
12457         private async void ShowProfileMenuItem_Click(object sender, EventArgs e)
12458         {
12459             if (_curPost != null)
12460             {
12461                 await this.ShowUserStatus(_curPost.ScreenName, false);
12462             }
12463         }
12464
12465         private async void RtCountMenuItem_Click(object sender, EventArgs e)
12466         {
12467             if (!this.ExistCurrentPost)
12468                 return;
12469
12470             var statusId = this._curPost.RetweetedId ?? this._curPost.StatusId;
12471             int retweetCount = 0;
12472
12473             using (var dialog = new WaitingDialog(Properties.Resources.RtCountMenuItem_ClickText1))
12474             {
12475                 var cancellationToken = dialog.EnableCancellation();
12476
12477                 try
12478                 {
12479                     var task = Task.Run(() => this.tw.GetStatus_Retweeted_Count(statusId));
12480                     retweetCount = await dialog.WaitForAsync(this, task);
12481                 }
12482                 catch (WebApiException ex)
12483                 {
12484                     if (!cancellationToken.IsCancellationRequested)
12485                         MessageBox.Show(Properties.Resources.RtCountText2 + Environment.NewLine + ex.Message);
12486                     return;
12487                 }
12488
12489                 if (cancellationToken.IsCancellationRequested)
12490                     return;
12491             }
12492
12493             MessageBox.Show(retweetCount + Properties.Resources.RtCountText1);
12494         }
12495
12496         private HookGlobalHotkey _hookGlobalHotkey;
12497         public TweenMain()
12498         {
12499             _hookGlobalHotkey = new HookGlobalHotkey(this);
12500
12501             // この呼び出しは、Windows フォーム デザイナで必要です。
12502             InitializeComponent();
12503
12504             // InitializeComponent() 呼び出しの後で初期化を追加します。
12505
12506             if (!this.DesignMode)
12507             {
12508                 // デザイナでの編集時にレイアウトが縦方向に数pxずれる問題の対策
12509                 this.StatusText.Dock = DockStyle.Fill;
12510             }
12511
12512             this.TimerTimeline.Elapsed += this.TimerTimeline_Elapsed;
12513             this._hookGlobalHotkey.HotkeyPressed += _hookGlobalHotkey_HotkeyPressed;
12514             this.gh.NotifyClicked += GrowlHelper_Callback;
12515
12516             // メイリオフォント指定時にタブの最小幅が広くなる問題の対策
12517             this.ListTab.HandleCreated += (s, e) => NativeMethods.SetMinTabWidth((TabControl)s, 40);
12518
12519             this.ImageSelector.Visible = false;
12520             this.ImageSelector.Enabled = false;
12521             this.ImageSelector.FilePickDialog = OpenFileDialog1;
12522
12523             this.ReplaceAppName();
12524             this.InitializeShortcuts();
12525         }
12526
12527         private void _hookGlobalHotkey_HotkeyPressed(object sender, KeyEventArgs e)
12528         {
12529             if ((this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized) && this.Visible && Form.ActiveForm == this)
12530             {
12531                 //アイコン化
12532                 this.Visible = false;
12533             }
12534             else if (Form.ActiveForm == null)
12535             {
12536                 this.Visible = true;
12537                 if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
12538                 this.Activate();
12539                 this.BringToFront();
12540                 this.StatusText.Focus();
12541             }
12542         }
12543
12544         private void UserPicture_MouseEnter(object sender, EventArgs e)
12545         {
12546             this.UserPicture.Cursor = Cursors.Hand;
12547         }
12548
12549         private void UserPicture_MouseLeave(object sender, EventArgs e)
12550         {
12551             this.UserPicture.Cursor = Cursors.Default;
12552         }
12553
12554         private async void UserPicture_DoubleClick(object sender, EventArgs e)
12555         {
12556             if (NameLabel.Tag != null)
12557             {
12558                 await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + NameLabel.Tag.ToString());
12559             }
12560         }
12561
12562         private void SplitContainer2_MouseDoubleClick(object sender, MouseEventArgs e)
12563         {
12564             this.MultiLineMenuItem.PerformClick();
12565         }
12566
12567         public PostClass CurPost
12568         {
12569             get { return _curPost; }
12570         }
12571
12572 #region "画像投稿"
12573         private void ImageSelectMenuItem_Click(object sender, EventArgs e)
12574         {
12575             if (ImageSelector.Visible)
12576                 ImageSelector.EndSelection();
12577             else
12578                 ImageSelector.BeginSelection();
12579         }
12580
12581         private void SelectMedia_DragEnter(DragEventArgs e)
12582         {
12583             if (ImageSelector.HasUploadableService(((string[])e.Data.GetData(DataFormats.FileDrop, false))[0], true))
12584             {
12585                 e.Effect = DragDropEffects.Copy;
12586                 return;
12587             }
12588             e.Effect = DragDropEffects.None;
12589         }
12590
12591         private void SelectMedia_DragDrop(DragEventArgs e)
12592         {
12593             this.Activate();
12594             this.BringToFront();
12595             ImageSelector.BeginSelection((string[])e.Data.GetData(DataFormats.FileDrop, false));
12596             StatusText.Focus();
12597         }
12598
12599         private void ImageSelector_BeginSelecting(object sender, EventArgs e)
12600         {
12601             TimelinePanel.Visible = false;
12602             TimelinePanel.Enabled = false;
12603         }
12604
12605         private void ImageSelector_EndSelecting(object sender, EventArgs e)
12606         {
12607             TimelinePanel.Visible = true;
12608             TimelinePanel.Enabled = true;
12609             ((DetailsListView)ListTab.SelectedTab.Tag).Focus();
12610         }
12611
12612         private void ImageSelector_FilePickDialogOpening(object sender, EventArgs e)
12613         {
12614             this.AllowDrop = false;
12615         }
12616
12617         private void ImageSelector_FilePickDialogClosed(object sender, EventArgs e)
12618         {
12619             this.AllowDrop = true;
12620         }
12621
12622         private void ImageSelector_SelectedServiceChanged(object sender, EventArgs e)
12623         {
12624             if (ImageSelector.Visible)
12625             {
12626                 _modifySettingCommon = true;
12627                 SaveConfigsAll(true);
12628
12629                 if (ImageSelector.ServiceName.Equals("Twitter"))
12630                     this.StatusText_TextChanged(null, null);
12631             }
12632         }
12633
12634         private void ImageSelector_VisibleChanged(object sender, EventArgs e)
12635         {
12636             this.StatusText_TextChanged(null, null);
12637         }
12638
12639         /// <summary>
12640         /// StatusTextでCtrl+Vが押下された時の処理
12641         /// </summary>
12642         private void ProcClipboardFromStatusTextWhenCtrlPlusV()
12643         {
12644             if (Clipboard.ContainsText())
12645             {
12646                 // clipboardにテキストがある場合は貼り付け処理
12647                 this.StatusText.Paste(Clipboard.GetText());
12648             }
12649             else if (Clipboard.ContainsImage())
12650             {
12651                 // 画像があるので投稿処理を行う
12652                 if (MessageBox.Show(Properties.Resources.PostPictureConfirm3,
12653                                    Properties.Resources.PostPictureWarn4,
12654                                    MessageBoxButtons.OKCancel,
12655                                    MessageBoxIcon.Question,
12656                                    MessageBoxDefaultButton.Button2)
12657                                == DialogResult.OK)
12658                 {
12659                     // clipboardから画像を取得
12660                     using (var image = Clipboard.GetImage())
12661                     {
12662                         this.ImageSelector.BeginSelection(image);
12663                     }
12664                 }
12665             }
12666         }
12667 #endregion
12668
12669         private void ListManageToolStripMenuItem_Click(object sender, EventArgs e)
12670         {
12671             using (ListManage form = new ListManage(tw))
12672             {
12673                 form.ShowDialog(this);
12674             }
12675         }
12676
12677         public bool ModifySettingCommon
12678         {
12679             set { _modifySettingCommon = value; }
12680         }
12681
12682         public bool ModifySettingLocal
12683         {
12684             set { _modifySettingLocal = value; }
12685         }
12686
12687         public bool ModifySettingAtId
12688         {
12689             set { _modifySettingAtId = value; }
12690         }
12691
12692         private async void SourceLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
12693         {
12694             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12695             if (sourceUri != null && e.Button == MouseButtons.Left)
12696             {
12697                 await this.OpenUriInBrowserAsync(sourceUri.AbsoluteUri);
12698             }
12699         }
12700
12701         private void SourceLinkLabel_MouseEnter(object sender, EventArgs e)
12702         {
12703             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
12704             if (sourceUri != null)
12705             {
12706                 StatusLabelUrl.Text = MyCommon.ConvertToReadableUrl(sourceUri.AbsoluteUri);
12707             }
12708         }
12709
12710         private void SourceLinkLabel_MouseLeave(object sender, EventArgs e)
12711         {
12712             SetStatusLabelUrl();
12713         }
12714
12715         private void MenuItemCommand_DropDownOpening(object sender, EventArgs e)
12716         {
12717             if (this.ExistCurrentPost && !_curPost.IsDm)
12718                 RtCountMenuItem.Enabled = true;
12719             else
12720                 RtCountMenuItem.Enabled = false;
12721
12722             //if (SettingDialog.UrlConvertAuto && SettingDialog.ShortenTco)
12723             //    TinyUrlConvertToolStripMenuItem.Enabled = false;
12724             //else
12725             //    TinyUrlConvertToolStripMenuItem.Enabled = true;
12726         }
12727
12728         private void CopyUserIdStripMenuItem_Click(object sender, EventArgs e)
12729         {
12730             CopyUserId();
12731         }
12732
12733         private void CopyUserId()
12734         {
12735             if (_curPost == null) return;
12736             string clstr = _curPost.ScreenName;
12737             try
12738             {
12739                 Clipboard.SetDataObject(clstr, false, 5, 100);
12740             }
12741             catch (Exception ex)
12742             {
12743                 MessageBox.Show(ex.Message);
12744             }
12745         }
12746
12747         private async void ShowRelatedStatusesMenuItem_Click(object sender, EventArgs e)
12748         {
12749             if (this.ExistCurrentPost && !_curPost.IsDm)
12750             {
12751                 try
12752                 {
12753                     await this.OpenRelatedTab(this._curPost);
12754                 }
12755                 catch (TabException ex)
12756                 {
12757                     MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
12758                 }
12759             }
12760         }
12761
12762         /// <summary>
12763         /// 指定されたツイートに対する関連発言タブを開きます
12764         /// </summary>
12765         /// <param name="statusId">表示するツイートのID</param>
12766         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12767         private async Task OpenRelatedTab(long statusId)
12768         {
12769             var post = this._statuses[statusId];
12770             if (post == null)
12771             {
12772                 try
12773                 {
12774                     post = await Task.Run(() => this.tw.GetStatusApi(false, statusId));
12775                 }
12776                 catch (WebApiException ex)
12777                 {
12778                     this.StatusLabel.Text = ex.Message;
12779                     return;
12780                 }
12781             }
12782
12783             await this.OpenRelatedTab(post);
12784         }
12785
12786         /// <summary>
12787         /// 指定されたツイートに対する関連発言タブを開きます
12788         /// </summary>
12789         /// <param name="post">表示する対象となるツイート</param>
12790         /// <exception cref="TabException">名前の重複が多すぎてタブを作成できない場合</exception>
12791         private async Task OpenRelatedTab(PostClass post)
12792         {
12793             var tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12794             string tabName;
12795
12796             if (tabRelated == null)
12797             {
12798                 tabName = this._statuses.MakeTabName("Related Tweets");
12799
12800                 this.AddNewTab(tabName, false, MyCommon.TabUsageType.Related);
12801                 this._statuses.AddTab(tabName, MyCommon.TabUsageType.Related, null);
12802
12803                 tabRelated = this._statuses.GetTabByType(MyCommon.TabUsageType.Related);
12804                 tabRelated.UnreadManage = false;
12805                 tabRelated.Notify = false;
12806             }
12807             else
12808             {
12809                 tabName = tabRelated.TabName;
12810             }
12811
12812             tabRelated.RelationTargetPost = post;
12813             this.ClearTab(tabName, false);
12814
12815             for (int i = 0; i < this.ListTab.TabPages.Count; i++)
12816             {
12817                 var tabPage = this.ListTab.TabPages[i];
12818                 if (tabName == tabPage.Text)
12819                 {
12820                     this.ListTab.SelectedIndex = i;
12821                     break;
12822                 }
12823             }
12824
12825             await this.GetRelatedTweetsAsync(tabRelated);
12826         }
12827
12828         private void CacheInfoMenuItem_Click(object sender, EventArgs e)
12829         {
12830             StringBuilder buf = new StringBuilder();
12831             //buf.AppendFormat("キャッシュメモリ容量         : {0}bytes({1}MB)" + Environment.NewLine, IconCache.CacheMemoryLimit, ((ImageDictionary)IconCache).CacheMemoryLimit / 1048576);
12832             //buf.AppendFormat("物理メモリ使用割合           : {0}%" + Environment.NewLine, IconCache.PhysicalMemoryLimit);
12833             buf.AppendFormat("キャッシュエントリ保持数     : {0}" + Environment.NewLine, IconCache.CacheCount);
12834             buf.AppendFormat("キャッシュエントリ破棄数     : {0}" + Environment.NewLine, IconCache.CacheRemoveCount);
12835             MessageBox.Show(buf.ToString(), "アイコンキャッシュ使用状況");
12836         }
12837
12838         private void tw_UserIdChanged()
12839         {
12840             this._modifySettingCommon = true;
12841         }
12842
12843 #region "Userstream"
12844         private bool _isActiveUserstream = false;
12845
12846         private void tw_PostDeleted(object sender, PostDeletedEventArgs e)
12847         {
12848             try
12849             {
12850                 if (InvokeRequired && !IsDisposed)
12851                 {
12852                     Invoke((Action) (async () =>
12853                            {
12854                                _statuses.RemovePostReserve(e.StatusId);
12855                                if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(e.StatusId))
12856                                {
12857                                    this.PurgeListViewItemCache();
12858                                    ((DetailsListView)_curTab.Tag).Update();
12859                                    if (_curPost != null && _curPost.StatusId == e.StatusId)
12860                                        await this.DispSelectedPost(true);
12861                                }
12862                            }));
12863                     return;
12864                 }
12865             }
12866             catch (ObjectDisposedException)
12867             {
12868                 return;
12869             }
12870             catch (InvalidOperationException)
12871             {
12872                 return;
12873             }
12874         }
12875
12876         private void tw_NewPostFromStream(object sender, EventArgs e)
12877         {
12878             if (this._cfgCommon.ReadOldPosts)
12879             {
12880                 _statuses.SetReadHomeTab(); //新着時未読クリア
12881             }
12882
12883             int rsltAddCount = _statuses.DistributePosts();
12884             lock (_syncObject)
12885             {
12886                 DateTime tm = DateTime.Now;
12887                 if (_tlTimestamps.ContainsKey(tm))
12888                 {
12889                     _tlTimestamps[tm] += rsltAddCount;
12890                 }
12891                 else
12892                 {
12893                     _tlTimestamps.Add(tm, rsltAddCount);
12894                 }
12895                 DateTime oneHour = DateTime.Now.Subtract(new TimeSpan(1, 0, 0));
12896                 List<DateTime> keys = new List<DateTime>();
12897                 _tlCount = 0;
12898                 foreach (DateTime key in _tlTimestamps.Keys)
12899                 {
12900                     if (key.CompareTo(oneHour) < 0)
12901                         keys.Add(key);
12902                     else
12903                         _tlCount += _tlTimestamps[key];
12904                 }
12905                 foreach (DateTime key in keys)
12906                 {
12907                     _tlTimestamps.Remove(key);
12908                 }
12909                 keys.Clear();
12910
12911                 //Static DateTime before = Now;
12912                 //if (before.Subtract(Now).Seconds > -5) return;
12913                 //before = Now;
12914             }
12915
12916             if (this._cfgCommon.UserstreamPeriod > 0) return;
12917
12918             try
12919             {
12920                 if (InvokeRequired && !IsDisposed)
12921                 {
12922                     Invoke((Action)(async () =>
12923                     {
12924                         await this.RefreshTasktrayIcon(true);
12925                         this.RefreshTimeline();
12926                     }));
12927                     return;
12928                 }
12929             }
12930             catch (ObjectDisposedException)
12931             {
12932                 return;
12933             }
12934             catch (InvalidOperationException)
12935             {
12936                 return;
12937             }
12938         }
12939
12940         private void tw_UserStreamStarted(object sender, EventArgs e)
12941         {
12942             this._isActiveUserstream = true;
12943             try
12944             {
12945                 if (InvokeRequired && !IsDisposed)
12946                 {
12947                     Invoke((Action)(() => this.tw_UserStreamStarted(sender, e)));
12948                     return;
12949                 }
12950             }
12951             catch (ObjectDisposedException)
12952             {
12953                 return;
12954             }
12955             catch (InvalidOperationException)
12956             {
12957                 return;
12958             }
12959
12960             MenuItemUserStream.Text = "&UserStream ▶";
12961             MenuItemUserStream.Enabled = true;
12962             StopToolStripMenuItem.Text = "&Stop";
12963             StopToolStripMenuItem.Enabled = true;
12964
12965             StatusLabel.Text = "UserStream Started.";
12966         }
12967
12968         private void tw_UserStreamStopped(object sender, EventArgs e)
12969         {
12970             this._isActiveUserstream = false;
12971             try
12972             {
12973                 if (InvokeRequired && !IsDisposed)
12974                 {
12975                     Invoke((Action)(() => this.tw_UserStreamStopped(sender, e)));
12976                     return;
12977                 }
12978             }
12979             catch (ObjectDisposedException)
12980             {
12981                 return;
12982             }
12983             catch (InvalidOperationException)
12984             {
12985                 return;
12986             }
12987
12988             MenuItemUserStream.Text = "&UserStream ■";
12989             MenuItemUserStream.Enabled = true;
12990             StopToolStripMenuItem.Text = "&Start";
12991             StopToolStripMenuItem.Enabled = true;
12992
12993             StatusLabel.Text = "UserStream Stopped.";
12994         }
12995
12996         private void tw_UserStreamEventArrived(object sender, UserStreamEventReceivedEventArgs e)
12997         {
12998             try
12999             {
13000                 if (InvokeRequired && !IsDisposed)
13001                 {
13002                     Invoke((Action)(() => this.tw_UserStreamEventArrived(sender, e)));
13003                     return;
13004                 }
13005             }
13006             catch (ObjectDisposedException)
13007             {
13008                 return;
13009             }
13010             catch (InvalidOperationException)
13011             {
13012                 return;
13013             }
13014             var ev = e.EventData;
13015             StatusLabel.Text = "Event: " + ev.Event;
13016             //if (ev.Event == "favorite")
13017             //{
13018             //    NotifyFavorite(ev);
13019             //}
13020             NotifyEvent(ev);
13021             if (ev.Event == "favorite" || ev.Event == "unfavorite")
13022             {
13023                 if (_curTab != null && _statuses.Tabs[_curTab.Text].Contains(ev.Id))
13024                 {
13025                     this.PurgeListViewItemCache();
13026                     ((DetailsListView)_curTab.Tag).Update();
13027                 }
13028                 if (ev.Event == "unfavorite" && ev.Username.ToLower().Equals(tw.Username.ToLower()))
13029                 {
13030                     RemovePostFromFavTab(new long[] {ev.Id});
13031                 }
13032             }
13033         }
13034
13035         private void NotifyEvent(Twitter.FormattedEvent ev)
13036         {
13037             //新着通知 
13038             if (BalloonRequired(ev))
13039             {
13040                 NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13041                 //if (SettingDialog.DispUsername) NotifyIcon1.BalloonTipTitle = tw.Username + " - "; else NotifyIcon1.BalloonTipTitle = "";
13042                 //NotifyIcon1.BalloonTipTitle += Application.ProductName + " [" + ev.Event.ToUpper() + "] by " + ((string)(!string.IsNullOrEmpty(ev.Username) ? ev.Username : ""), string);
13043                 StringBuilder title = new StringBuilder();
13044                 if (this._cfgCommon.DispUsername)
13045                 {
13046                     title.Append(tw.Username);
13047                     title.Append(" - ");
13048                 }
13049                 else
13050                 {
13051                     //title.Clear();
13052                 }
13053                 title.Append(Application.ProductName);
13054                 title.Append(" [");
13055                 title.Append(ev.Event.ToUpper());
13056                 title.Append("] by ");
13057                 if (!string.IsNullOrEmpty(ev.Username))
13058                 {
13059                     title.Append(ev.Username.ToString());
13060                 }
13061                 else
13062                 {
13063                     //title.Append("");
13064                 }
13065                 string text;
13066                 if (!string.IsNullOrEmpty(ev.Target))
13067                 {
13068                     //NotifyIcon1.BalloonTipText = ev.Target;
13069                     text = ev.Target;
13070                 }
13071                 else
13072                 {
13073                     //NotifyIcon1.BalloonTipText = " ";
13074                     text = " ";
13075                 }
13076                 //NotifyIcon1.ShowBalloonTip(500);
13077                 if (this._cfgCommon.IsUseNotifyGrowl)
13078                 {
13079                     gh.Notify(GrowlHelper.NotifyType.UserStreamEvent,
13080                               ev.Id.ToString(), title.ToString(), text);
13081                 }
13082                 else
13083                 {
13084                     NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
13085                     NotifyIcon1.BalloonTipTitle = title.ToString();
13086                     NotifyIcon1.BalloonTipText = text;
13087                     NotifyIcon1.ShowBalloonTip(500);
13088                 }
13089             }
13090
13091             //サウンド再生
13092             string snd = this._cfgCommon.EventSoundFile;
13093             if (!_initial && this._cfgCommon.PlaySound && !string.IsNullOrEmpty(snd))
13094             {
13095                 if ((ev.Eventtype & this._cfgCommon.EventNotifyFlag) != 0 && IsMyEventNotityAsEventType(ev))
13096                 {
13097                     try
13098                     {
13099                         string dir = Application.StartupPath;
13100                         if (Directory.Exists(Path.Combine(dir, "Sounds")))
13101                         {
13102                             dir = Path.Combine(dir, "Sounds");
13103                         }
13104                         using (SoundPlayer player = new SoundPlayer(Path.Combine(dir, snd)))
13105                         {
13106                             player.Play();
13107                         }
13108                     }
13109                     catch (Exception)
13110                     {
13111                     }
13112                 }
13113             }
13114         }
13115
13116         private void StopToolStripMenuItem_Click(object sender, EventArgs e)
13117         {
13118             MenuItemUserStream.Enabled = false;
13119             if (StopRefreshAllMenuItem.Checked)
13120             {
13121                 StopRefreshAllMenuItem.Checked = false;
13122                 return;
13123             }
13124             if (this._isActiveUserstream)
13125             {
13126                 tw.StopUserStream();
13127             }
13128             else
13129             {
13130                 tw.StartUserStream();
13131             }
13132         }
13133
13134         private static string inputTrack = "";
13135
13136         private void TrackToolStripMenuItem_Click(object sender, EventArgs e)
13137         {
13138             if (TrackToolStripMenuItem.Checked)
13139             {
13140                 using (InputTabName inputForm = new InputTabName())
13141                 {
13142                     inputForm.TabName = inputTrack;
13143                     inputForm.FormTitle = "Input track word";
13144                     inputForm.FormDescription = "Track word";
13145                     if (inputForm.ShowDialog() != DialogResult.OK)
13146                     {
13147                         TrackToolStripMenuItem.Checked = false;
13148                         return;
13149                     }
13150                     inputTrack = inputForm.TabName.Trim();
13151                 }
13152                 if (!inputTrack.Equals(tw.TrackWord))
13153                 {
13154                     tw.TrackWord = inputTrack;
13155                     this._modifySettingCommon = true;
13156                     TrackToolStripMenuItem.Checked = !string.IsNullOrEmpty(inputTrack);
13157                     tw.ReconnectUserStream();
13158                 }
13159             }
13160             else
13161             {
13162                 tw.TrackWord = "";
13163                 tw.ReconnectUserStream();
13164             }
13165             this._modifySettingCommon = true;
13166         }
13167
13168         private void AllrepliesToolStripMenuItem_Click(object sender, EventArgs e)
13169         {
13170             tw.AllAtReply = AllrepliesToolStripMenuItem.Checked;
13171             this._modifySettingCommon = true;
13172             tw.ReconnectUserStream();
13173         }
13174
13175         private void EventViewerMenuItem_Click(object sender, EventArgs e)
13176         {
13177             if (evtDialog == null || evtDialog.IsDisposed)
13178             {
13179                 evtDialog = null;
13180                 evtDialog = new EventViewerDialog();
13181                 evtDialog.Owner = this;
13182                 //親の中央に表示
13183                 Point pos = evtDialog.Location;
13184                 pos.X = Convert.ToInt32(this.Location.X + this.Size.Width / 2 - evtDialog.Size.Width / 2);
13185                 pos.Y = Convert.ToInt32(this.Location.Y + this.Size.Height / 2 - evtDialog.Size.Height / 2);
13186                 evtDialog.Location = pos;
13187             }
13188             evtDialog.EventSource = tw.StoredEvent;
13189             if (!evtDialog.Visible)
13190             {
13191                 evtDialog.Show(this);
13192             }
13193             else
13194             {
13195                 evtDialog.Activate();
13196             }
13197             this.TopMost = this._cfgCommon.AlwaysTop;
13198         }
13199 #endregion
13200
13201         private void TweenRestartMenuItem_Click(object sender, EventArgs e)
13202         {
13203             MyCommon._endingFlag = true;
13204             try
13205             {
13206                 this.Close();
13207                 Application.Restart();
13208             }
13209             catch (Exception)
13210             {
13211                 MessageBox.Show("Failed to restart. Please run " + Application.ProductName + " manually.");
13212             }
13213         }
13214
13215         private async void OpenOwnFavedMenuItem_Click(object sender, EventArgs e)
13216         {
13217             if (!string.IsNullOrEmpty(tw.Username))
13218                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + tw.Username + "/recent");
13219         }
13220
13221         private async void OpenOwnHomeMenuItem_Click(object sender, EventArgs e)
13222         {
13223             await this.OpenUriInBrowserAsync(MyCommon.TwitterUrl + tw.Username);
13224         }
13225
13226         private async Task doTranslation(string str)
13227         {
13228             if (string.IsNullOrEmpty(str))
13229                 return;
13230
13231             var bing = new Bing();
13232             try
13233             {
13234                 var translatedText = await bing.TranslateAsync(str,
13235                     langFrom: null,
13236                     langTo: this._cfgCommon.TranslateLanguage);
13237
13238                 this.PostBrowser.DocumentText = this.createDetailHtml(translatedText);
13239             }
13240             catch (HttpRequestException e)
13241             {
13242                 this.StatusLabel.Text = "Err:" + e.Message;
13243             }
13244         }
13245
13246         private async void TranslationToolStripMenuItem_Click(object sender, EventArgs e)
13247         {
13248             if (!this.ExistCurrentPost)
13249                 return;
13250
13251             await this.doTranslation(this._curPost.TextFromApi);
13252         }
13253
13254         private async void SelectionTranslationToolStripMenuItem_Click(object sender, EventArgs e)
13255         {
13256             var text = this.PostBrowser.GetSelectedText();
13257             await this.doTranslation(text);
13258         }
13259
13260         private bool ExistCurrentPost
13261         {
13262             get
13263             {
13264                 if (_curPost == null) return false;
13265                 if (_curPost.IsDeleted) return false;
13266                 return true;
13267             }
13268         }
13269
13270         private void ShowUserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13271         {
13272             ShowUserTimeline();
13273         }
13274
13275         private string GetUserIdFromCurPostOrInput(string caption)
13276         {
13277             var id = _curPost?.ScreenName ?? "";
13278
13279             using (InputTabName inputName = new InputTabName())
13280             {
13281                 inputName.FormTitle = caption;
13282                 inputName.FormDescription = Properties.Resources.FRMessage1;
13283                 inputName.TabName = id;
13284                 if (inputName.ShowDialog() == DialogResult.OK &&
13285                     !string.IsNullOrEmpty(inputName.TabName.Trim()))
13286                 {
13287                     id = inputName.TabName.Trim();
13288                 }
13289                 else
13290                 {
13291                     id = "";
13292                 }
13293             }
13294             return id;
13295         }
13296
13297         private void UserTimelineToolStripMenuItem_Click(object sender, EventArgs e)
13298         {
13299             string id = GetUserIdFromCurPostOrInput("Show UserTimeline");
13300             if (!string.IsNullOrEmpty(id))
13301             {
13302                 AddNewTabForUserTimeline(id);
13303             }
13304         }
13305
13306         private async void UserFavorareToolStripMenuItem_Click(object sender, EventArgs e)
13307         {
13308             string id = GetUserIdFromCurPostOrInput("Show Favstar");
13309             if (!string.IsNullOrEmpty(id))
13310             {
13311                 await this.OpenUriInBrowserAsync(Properties.Resources.FavstarUrl + "users/" + id + "/recent");
13312             }
13313         }
13314
13315         private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
13316         {
13317             if (e.Mode == Microsoft.Win32.PowerModes.Resume) osResumed = true;
13318         }
13319
13320         private void TimelineRefreshEnableChange(bool isEnable)
13321         {
13322             if (isEnable)
13323             {
13324                 tw.StartUserStream();
13325             }
13326             else
13327             {
13328                 tw.StopUserStream();
13329             }
13330             TimerTimeline.Enabled = isEnable;
13331         }
13332
13333         private void StopRefreshAllMenuItem_CheckedChanged(object sender, EventArgs e)
13334         {
13335             TimelineRefreshEnableChange(!StopRefreshAllMenuItem.Checked);
13336         }
13337
13338         private async Task OpenUserAppointUrl()
13339         {
13340             if (this._cfgCommon.UserAppointUrl != null)
13341             {
13342                 if (this._cfgCommon.UserAppointUrl.Contains("{ID}") || this._cfgCommon.UserAppointUrl.Contains("{STATUS}"))
13343                 {
13344                     if (_curPost != null)
13345                     {
13346                         string xUrl = this._cfgCommon.UserAppointUrl;
13347                         xUrl = xUrl.Replace("{ID}", _curPost.ScreenName);
13348
13349                         var statusId = _curPost.RetweetedId ?? _curPost.StatusId;
13350                         xUrl = xUrl.Replace("{STATUS}", statusId.ToString());
13351
13352                         await this.OpenUriInBrowserAsync(xUrl);
13353                     }
13354                 }
13355                 else
13356                 {
13357                     await this.OpenUriInBrowserAsync(this._cfgCommon.UserAppointUrl);
13358                 }
13359             }
13360         }
13361
13362         private async void OpenUserSpecifiedUrlMenuItem_Click(object sender, EventArgs e)
13363         {
13364             await this.OpenUserAppointUrl();
13365         }
13366
13367         private void SourceCopyMenuItem_Click(object sender, EventArgs e)
13368         {
13369             string selText = SourceLinkLabel.Text;
13370             try
13371             {
13372                 Clipboard.SetDataObject(selText, false, 5, 100);
13373             }
13374             catch (Exception ex)
13375             {
13376                 MessageBox.Show(ex.Message);
13377             }
13378         }
13379
13380         private void SourceUrlCopyMenuItem_Click(object sender, EventArgs e)
13381         {
13382             var sourceUri = (Uri)this.SourceLinkLabel.Tag;
13383             try
13384             {
13385                 Clipboard.SetDataObject(sourceUri.AbsoluteUri, false, 5, 100);
13386             }
13387             catch (Exception ex)
13388             {
13389                 MessageBox.Show(ex.Message);
13390             }
13391         }
13392
13393         private void ContextMenuSource_Opening(object sender, CancelEventArgs e)
13394         {
13395             if (_curPost == null || !ExistCurrentPost || _curPost.IsDm)
13396             {
13397                 SourceCopyMenuItem.Enabled = false;
13398                 SourceUrlCopyMenuItem.Enabled = false;
13399             }
13400             else
13401             {
13402                 SourceCopyMenuItem.Enabled = true;
13403                 SourceUrlCopyMenuItem.Enabled = true;
13404             }
13405         }
13406
13407         private void GrowlHelper_Callback(object sender, GrowlHelper.NotifyCallbackEventArgs e)
13408         {
13409             if (Form.ActiveForm == null)
13410             {
13411                 this.BeginInvoke((Action) (() =>
13412                 {
13413                     this.Visible = true;
13414                     if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
13415                     this.Activate();
13416                     this.BringToFront();
13417                     if (e.NotifyType == GrowlHelper.NotifyType.DirectMessage)
13418                     {
13419                         if (!this.GoDirectMessage(e.StatusId)) this.StatusText.Focus();
13420                     }
13421                     else
13422                     {
13423                         if (!this.GoStatus(e.StatusId)) this.StatusText.Focus();
13424                     }
13425                 }));
13426             }
13427         }
13428
13429         private void ReplaceAppName()
13430         {
13431             MatomeMenuItem.Text = MyCommon.ReplaceAppName(MatomeMenuItem.Text);
13432             AboutMenuItem.Text = MyCommon.ReplaceAppName(AboutMenuItem.Text);
13433         }
13434
13435         private void tweetThumbnail1_ThumbnailLoading(object sender, EventArgs e)
13436         {
13437             this.SplitContainer3.Panel2Collapsed = false;
13438         }
13439
13440         private async void tweetThumbnail1_ThumbnailDoubleClick(object sender, ThumbnailDoubleClickEventArgs e)
13441         {
13442             await this.OpenThumbnailPicture(e.Thumbnail);
13443         }
13444
13445         private async void tweetThumbnail1_ThumbnailImageSearchClick(object sender, ThumbnailImageSearchEventArgs e)
13446         {
13447             await this.OpenUriInBrowserAsync(e.ImageUrl);
13448         }
13449
13450         private async Task OpenThumbnailPicture(ThumbnailInfo thumbnail)
13451         {
13452             var url = thumbnail.FullSizeImageUrl ?? thumbnail.ImageUrl;
13453
13454             await this.OpenUriInBrowserAsync(url);
13455         }
13456
13457         private async void TwitterApiStatusToolStripMenuItem_Click(object sender, EventArgs e)
13458         {
13459             await this.OpenUriInBrowserAsync(Twitter.ServiceAvailabilityStatusUrl);
13460         }
13461
13462         private void PostButton_KeyDown(object sender, KeyEventArgs e)
13463         {
13464             if (e.KeyCode == Keys.Space)
13465             {
13466                 this.JumpUnreadMenuItem_Click(null, null);
13467
13468                 e.SuppressKeyPress = true;
13469             }
13470         }
13471
13472         private void ContextMenuColumnHeader_Opening(object sender, CancelEventArgs e)
13473         {
13474             this.IconSizeNoneToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.IconNone;
13475             this.IconSize16ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon16;
13476             this.IconSize24ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon24;
13477             this.IconSize48ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48;
13478             this.IconSize48_2ToolStripMenuItem.Checked = this._cfgCommon.IconSize == MyCommon.IconSizes.Icon48_2;
13479
13480             this.LockListSortOrderToolStripMenuItem.Checked = this._cfgCommon.SortOrderLock;
13481         }
13482
13483         private void IconSizeNoneToolStripMenuItem_Click(object sender, EventArgs e)
13484         {
13485             ChangeListViewIconSize(MyCommon.IconSizes.IconNone);
13486         }
13487
13488         private void IconSize16ToolStripMenuItem_Click(object sender, EventArgs e)
13489         {
13490             ChangeListViewIconSize(MyCommon.IconSizes.Icon16);
13491         }
13492
13493         private void IconSize24ToolStripMenuItem_Click(object sender, EventArgs e)
13494         {
13495             ChangeListViewIconSize(MyCommon.IconSizes.Icon24);
13496         }
13497
13498         private void IconSize48ToolStripMenuItem_Click(object sender, EventArgs e)
13499         {
13500             ChangeListViewIconSize(MyCommon.IconSizes.Icon48);
13501         }
13502
13503         private void IconSize48_2ToolStripMenuItem_Click(object sender, EventArgs e)
13504         {
13505             ChangeListViewIconSize(MyCommon.IconSizes.Icon48_2);
13506         }
13507
13508         private void ChangeListViewIconSize(MyCommon.IconSizes iconSize)
13509         {
13510             if (this._cfgCommon.IconSize == iconSize) return;
13511
13512             var oldIconCol = _iconCol;
13513
13514             this._cfgCommon.IconSize = iconSize;
13515             ApplyListViewIconSize(iconSize);
13516
13517             if (_iconCol != oldIconCol)
13518             {
13519                 foreach (TabPage tp in ListTab.TabPages)
13520                 {
13521                     ResetColumns((DetailsListView)tp.Tag);
13522                 }
13523             }
13524
13525             _curList?.Refresh();
13526
13527             _modifySettingCommon = true;
13528         }
13529
13530         private void LockListSortToolStripMenuItem_Click(object sender, EventArgs e)
13531         {
13532             var state = this.LockListSortOrderToolStripMenuItem.Checked;
13533             if (this._cfgCommon.SortOrderLock == state) return;
13534
13535             this._cfgCommon.SortOrderLock = state;
13536
13537             _modifySettingCommon = true;
13538         }
13539     }
13540 }